text:
Q: Почему ExcelWriter не записывает данные в одну и туже страницу? Моя программа считывает данные с .xlsx файла, обрабатывает его, далее я записываю данные в дата фреймы. Через ExcelWriter создаю страницы в .xlsx и записываю туда данные из дата фреймов.
Я писал этот код на ПК в офисе и код работал как нужно, но когда я запускаю этот же код с домашнего ПК, мне выдает ошибку:

Sheet already exists and if_sheet_exists is set to 'error'.

Не понимаю как так, один и тот же код. Использую оболочку PyCharm. Ниже прилагаю отрезок кода. Кто понимает в чём тут дело, подскажите пожалуйста.
Самый главный парадокс проблемы в том, что на другом ПК этот же код работает отлично, возможно проблема в самом PyCharm.
with pd.ExcelWriter('C:\Myronchuk\Pyton\File for open\HO.xlsx', engine='openpyxl', mode='a') as writer:
    data1.to_excel(writer, sheet_name='2G>LTE', index=False)
    data2.to_excel(writer, sheet_name='2G>LTE', startcol=3, startrow=0, index=False)
    data3.to_excel(writer, sheet_name='LTE>2G', index=0)
    data4.to_excel(writer, sheet_name='LTE>2G', startcol=3, startrow=0, index=False)
    data5.to_excel(writer, sheet_name='LTE>2G', startcol=6, startrow=0, index=False)
    data6.to_excel(writer, sheet_name='LTE>LTE', index=False)
    data7.to_excel(writer, sheet_name='LTE>LTE', startcol=3, startrow=0, index=False)
    data8.to_excel(writer, sheet_name='LTE>LTE', startcol=6, startrow=0, index=False)
    data9.to_excel(writer, sheet_name='LTE>3G', index=False)
    data10.to_excel(writer, sheet_name='LTE>3G', startcol=3, startrow=0, index=False)

Пишу этот вопрос второй раз, в первый мою тему скрестили с похожей темой. Там предложили другой вариант записи данных в .xlsx, я попробовал воспользоваться и им, результат такой же.

Error: Sheet '2G>LTE' already exists and if_sheet_exists is set to 'error'.

Код второго варианта кода прилагаю:
import os
from openpyxl import load_workbook

def append_df_to_excel(filename, df, sheet_name='Sheet1', startrow=None,
                       truncate_sheet=False,
                       **to_excel_kwargs):
    """
    Append a DataFrame [df] to existing Excel file [filename]
    into [sheet_name] Sheet.
    If [filename] doesn't exist, then this function will create it.

    @param filename: File path or existing ExcelWriter
                     (Example: '/path/to/file.xlsx')
    @param df: DataFrame to save to workbook
    @param sheet_name: Name of sheet which will contain DataFrame.
                       (default: 'Sheet1')
    @param startrow: upper left cell row to dump data frame.
                     Per default (startrow=None) calculate the last row
                     in the existing DF and write to the next row...
    @param truncate_sheet: truncate (remove and recreate) [sheet_name]
                           before writing DataFrame to Excel file
    @param to_excel_kwargs: arguments which will be passed to `DataFrame.to_excel()`
                            [can be a dictionary]
    @return: None

    Usage examples:

    >>> append_df_to_excel('d:/temp/test.xlsx', df)

    >>> append_df_to_excel('d:/temp/test.xlsx', df, header=None, index=False)

    >>> append_df_to_excel('d:/temp/test.xlsx', df, sheet_name='Sheet2',
                           index=False)

    >>> append_df_to_excel('d:/temp/test.xlsx', df, sheet_name='Sheet2',
                           index=False, startrow=25)

    (c) [MaxU](https://stackoverflow.com/users/5741205/maxu?tab=profile)
    """
    # Excel file doesn't exist - saving and exiting
    if not os.path.isfile(filename):
        df.to_excel(
            filename,
            sheet_name=sheet_name,
            startrow=startrow if startrow is not None else 0,
            **to_excel_kwargs)
        return

    # ignore [engine] parameter if it was passed
    if 'engine' in to_excel_kwargs:
        to_excel_kwargs.pop('engine')

    writer = pd.ExcelWriter(filename, engine='openpyxl', mode='a')

    # try to open an existing workbook
    writer.book = load_workbook(filename)

    # get the last row in the existing Excel sheet
    # if it was not specified explicitly
    if startrow is None and sheet_name in writer.book.sheetnames:
        startrow = writer.book[sheet_name].max_row

    # truncate sheet
    if truncate_sheet and sheet_name in writer.book.sheetnames:
        # index of [sheet_name] sheet
        idx = writer.book.sheetnames.index(sheet_name)
        # remove [sheet_name]
        writer.book.remove(writer.book.worksheets[idx])
        # create an empty sheet [sheet_name] using old index
        writer.book.create_sheet(sheet_name, idx)

    # copy existing sheets
    writer.sheets = {ws.title: ws for ws in writer.book.worksheets}

    if startrow is None:
        startrow = 0

    # write out the new sheet
    df.to_excel(writer, sheet_name, startrow=startrow, **to_excel_kwargs)

    # save the workbook
    writer.save()

append_df_to_excel('C:\Myronchuk\Pyton\File for open\HO.xlsx', data1, sheet_name='2G>LTE', index=False)
append_df_to_excel('C:\Myronchuk\Pyton\File for open\HO.xlsx', data2, sheet_name='2G>LTE', index=False, startcol=3, startrow=0)
append_df_to_excel('C:\Myronchuk\Pyton\File for open\HO.xlsx', data3, sheet_name='LTE>2G', index=False)
append_df_to_excel('C:\Myronchuk\Pyton\File for open\HO.xlsx', data4, sheet_name='LTE>2G', index=False, startcol=3, startrow=0)
append_df_to_excel('C:\Myronchuk\Pyton\File for open\HO.xlsx', data5, sheet_name='LTE>2G', index=False, startcol=6, startrow=0)
append_df_to_excel('C:\Myronchuk\Pyton\File for open\HO.xlsx', data6, sheet_name='LTE>LTE', index=False)
append_df_to_excel('C:\Myronchuk\Pyton\File for open\HO.xlsx', data7, sheet_name='LTE>LTE', index=False, startcol=3, startrow=0)
append_df_to_excel('C:\Myronchuk\Pyton\File for open\HO.xlsx', data8, sheet_name='LTE>LTE', index=False, startcol=6, startrow=0)
append_df_to_excel('C:\Myronchuk\Pyton\File for open\HO.xlsx', data9, sheet_name='LTE>3G', index=False)
append_df_to_excel('C:\Myronchuk\Pyton\File for open\HO.xlsx', data10, sheet_name='LTE>3G', index=False, startcol=3, startrow=0)

K сожалению, версию модулей openpyxl и pandas на рабочем ПК сейчас указать не могу, но версии на домашнем пк приложу ниже на скринах:

A: Судя по вашему коду:
    ...
    data3.to_excel(writer, sheet_name='LTE>2G', index=0)
    data4.to_excel(writer, sheet_name='LTE>2G', startcol=3, startrow=0, index=False)
    data5.to_excel(writer, sheet_name='LTE>2G', startcol=6, startrow=0, index=False)
    ...

основная проблема в том, что вы дописываете столбцы по частям хотя можно было бы сначала объединить все, что нужно писать в один фрейм и уже его записывать в Excel:
lte_2g = pd.concat([d.reset_index(drop=True) for d in [data3, data4, data5]], axis=1)
lte_2g.to_excel(writer, sheet_name='LTE>2G', index=0)


text:
Q: Room DB, pass ASC or DESC as param I have a room database set up. And have the following query (which works fine as is):
@Query("SELECT * FROM " + TABLE_REPORT
        + " WHERE " + COLUMN_CLASS_ID + " =:classID"
        + " ORDER BY CASE :orderByColumnName"
        + " WHEN 'maths' THEN maths"
        + " WHEN 'physics' THEN physics"
        + " WHEN 'history' THEN history"
        + " END"
        + " DESC")
List<ResultEntity> getClassResult(long classID, String orderByColumnName); // , String orderBy);

I want to uncomment the last line and include the orderBy parameter in the function and replace " DESC" by " :orderBy" so I can have the list sorted by orderBy which would be ASC or DESC.
I tried doing what I explained above. But it doesn't seem to work.
Error shown is: "ASC, BETWEEN, COLLATE, DESC, IN, LIMIT, comma or semicolon expected, found :orderBy"
How can I get this working? Thanks in advance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why use exec in Makefile? Is the exec keyword required in a Makefile?
build-cache: clean-cache
    @exec ./scripts/copy_packages.sh
    ./scripts/build_makefile.sh
    docker build -t common/cache ./cache

I just noticed that some lines use exec and others do not.

A: No (exec is not a keyword in make); you're misparsing the line:
@exec ./scripts/copy_packages.sh

The @ means "do not echo this line" when executing the commands in this 'recipe'.  The exec means that the shell that make starts to run the line replaces itself with the script ./scripts/copy_packages.sh.
See also What do @, - and + do as prefixes to recipe lines in make?


text:
Q: MongoDB Service not started with WAMP I am a newbie to MongoDB and followed this for installation purpose. In my phpinfo, I can see mongodb under Apache Environment, Environment and PHP Variables. When I try starting MongoDB service it shows the error as in screensshot

Also I can not see it installed like below

My DLL file is php_mongo-1.5.5-5.4-vc9-x86_64 and MongoDB is installed from here
PHP Version    5.4.3
Compiler       MSVC9 (Visual C++ 2008)
Architecture   x86
System Type    64 bit

Could someone please guide me on how to install MongoDB with PHP
Thanks.

A: Thanks for responding. I resolved it my uninstalling the MongoDB services and then again installing a relevant version.
The source code issue was of previous MongoDB version and not the latest one, and the folder containing the old version was deleted somehow, thus throwing an exception for source path not found.
Also, the DLL file that worked was php_mongo-1.5.5-5.4-vc9.dll downloaded from here for below configuration
PHP Version    5.4.3
Compiler       MSVC9 (Visual C++ 2008)
Architecture   x86
System Type    64 bit

Hope it helps someone.


text:
Q: addRole to a mentioned user isn't working I'm trying to make a discord bot, which can add a specific role to an user.
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

client.on('message', (message) => {
    let allowedRole = message.guild.channels.find(channel => channel.name === "Streamer");
    let gRole = message.guild.channels.find(channel => channel.name === "Stream 1");
    mention = message.mentions.users.first();
    let member = message.mentions.users.first();
  if (message.content === "addRole") {
      members.get(message.mentions.user.id).addRole(gRole);
  }
});

client.login('mytoken');

I expect that the bot can add role to a specific person

A: First of all, your first mistake was, that you searched for channel names and not role names in your variable gRole and allowedRole. I changed this 2 variables, so they search for roles instead of channels.
You defined twice the same, once as mention and once as member = message.mentions.users.first(). Because of this, I removed your variable named mention and used the variable member. I found that the code for this variable didn't match the name of the variable because your code returned the user Object and I changed it to the member Object (because your variable is named member).
Lastly, I used your predefined variable member and assigned the role gRole to it, so you don't have to get the member another time.

Try to use the following code:

const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`);
});

client.on('message', message => {
    const allowedRole = message.guild.roles.find(role => role.name === 'Streamer'); // isn't used
    const gRole = message.guild.roles.find(role => role.name === 'Stream 1');
    const member = message.mentions.members.first();
    if (message.content === 'addRole') {
        member.addRole(gRole);
    }
});

client.login('mytoken');


text:
Q: R error when trying to cluster data using pam (package cluster) I am trying to run k-means clustering on a data set which was preprocessed (categorical to dummy, na cleaning etc.).
here is an extract (head) of the data:
dput(head(clustering.set.in))
structure(list(activity_type = c(1, 1, 1, 1, 1, 1), app_id.PXkw7OJ1se = c(0,
1, 1, 1, 1, 0), app_id.PXszbKVa5M = c(0, 0, 0, 0, 0, 0), app_id.PXw3GFQKBm = c(1,
0, 0, 0, 0, 0), browser_version = c(48, 42, 9, 9, 48, 44), continent.AS = c(0,
1, 1, 0, 0, 0), continent.EU = c(0, 0, 0, 0, 1, 0), continent.SA = c(0,
0, 0, 0, 0, 0), f_activex = c(1, 1, 1, 1, 1, 1), f_atob = c(2,
2, 2, 2, 2, 2), f_audio = c(2, 2, 2, 2, 2, 2), f_battery = c(2,
2, 1, 1, 2, 2), f_bind = c(2, 2, 2, 2, 2, 2), f_flash = c(1,
2, 2, 2, 2, 2), f_getComputedStyle = c(2, 2, 2, 2, 2, 2), f_matchSelector = c(2,
2, 2, 2, 2, 2), f_mimeTypes = c(2, 2, 2, 2, 2, 2), f_mimeTypesLength = c(0,
8, 11, 55, 7, 8), f_navigationTiming = c(2, 2, 1, 2, 2, 2), f_orientationEvents = c(2,
1, 1, 1, 1, 1), f_plugins = c(2, 2, 2, 2, 2, 2), f_pluginsLength = c(0,
6, 6, 15, 5, 6), f_raf = c(2, 2, 2, 2, 2, 2), f_resourceTiming = c(2,
2, 1, 1, 2, 2), f_sse = c(2, 2, 2, 2, 2, 2), f_webgl = c(1, 2,
2, 2, 2, 1), f_websql = c(1, 2, 2, 2, 2, 2), f_xdr = c(1, 1,
1, 1, 1, 1), n_appCodeName = c(2, 2, 2, 2, 2, 2), n_doNotTrack = c(2,
2, 1, 2, 2, 2), n_geolocation = c(2, 2, 2, 2, 2, 2), n_mimeTypes = c(2,
2, 2, 2, 2, 2), n_platform.iPhone = c(0, 0, 0, 0, 0, 0), n_platform.Linux.armv7l = c(1,
0, 0, 0, 0, 0), n_platform.MacIntel = c(0, 0, 1, 1, 0, 0), n_platform.Win32 = c(0,
1, 0, 0, 1, 0), n_plugins = c(2, 2, 2, 2, 2, 2), n_product.Sub20030107 = c(1,
1, 1, 1, 1, 1), n_product.Sub20100101 = c(0, 0, 0, 0, 0, 0),
    n_product.Submissing = c(0, 0, 0, 0, 0, 0), os_family.Android = c(1,
    0, 0, 0, 0, 0), os_family.iOS = c(0, 0, 0, 0, 0, 0), os_family.Mac.OS.X = c(0,
    0, 1, 1, 0, 0), os_family.Windows = c(0, 1, 0, 0, 1, 0),
    os_version = c(6, 8.1, 10, 10, 7, 0), site_history_length = c(31,
    1, 1, 1, 1, 1), w_chrome...loadTimes....csi....app....webstore....runtime.. = c(0,
    1, 0, 0, 1, 0), w_chrome...loadTimes....csi.. = c(0, 0, 0,
    0, 0, 0), w_chrome... = c(1, 0, 1, 1, 0, 0), window_dimensions = c(2,
    1, 2, 2, 2, 2), window_history = c(50, 1, 1, 1, 1, 3)), .Names = c("activity_type",
"app_id.PXkw7OJ1se", "app_id.PXszbKVa5M", "app_id.PXw3GFQKBm",
"browser_version", "continent.AS", "continent.EU", "continent.SA",
"f_activex", "f_atob", "f_audio", "f_battery", "f_bind", "f_flash",
"f_getComputedStyle", "f_matchSelector", "f_mimeTypes", "f_mimeTypesLength",
"f_navigationTiming", "f_orientationEvents", "f_plugins", "f_pluginsLength",
"f_raf", "f_resourceTiming", "f_sse", "f_webgl", "f_websql",
"f_xdr", "n_appCodeName", "n_doNotTrack", "n_geolocation", "n_mimeTypes",
"n_platform.iPhone", "n_platform.Linux.armv7l", "n_platform.MacIntel",
"n_platform.Win32", "n_plugins", "n_product.Sub20030107", "n_product.Sub20100101",
"n_product.Submissing", "os_family.Android", "os_family.iOS",
"os_family.Mac.OS.X", "os_family.Windows", "os_version", "site_history_length",
"w_chrome...loadTimes....csi....app....webstore....runtime..",
"w_chrome...loadTimes....csi..", "w_chrome...", "window_dimensions",
"window_history"), row.names = c(NA, 6L), class = "data.frame")

I am trying to cluster kmeans this data sets (k=2)
and getting error message:
Error in pam(clustering.set.in, k) :
  negative length vectors are not allowed

my line of code:
pam(clustering.set.in, 2)

Any suggestions ?

A: it turns out that one column has na values in it.
Removed it with
new.data[is.na(new.data)] <- 1

and it seems to work fine now


text:
Q: Who can explain how this code is not an error? I was making some exercise to train myself and the exercise asked me to do a program that calculates fractals, very simple, i've done in about 1-2 minutes and it work, but looking at his solution it return x multiplicated by the function itself? how does this run? I know maybe it's a stupid question but i think it might be useful.
def fract(x):
    if x == 0:
        return 1
    return x * fract(x - 1)

print(fract(int(input())))

A: Here's a walk through of whats going on.
First, you call fract(int(input())). The input method gets a response from the user and parses that to an int. and then calls fract on that int.
Say we enter 3. So our print statement evaluates to fract(3).
fract(3) returns 3 * fract(2)
fract(2) is called and that returns 2 * fract(1)
fract(1) is called and that returns 1
So putting it altogether and substituting function calls for what they return we get fract(3) returns 3 * (2 * (1)).


text:
Q: Spring JPA: How can I see the commits being issued in the logs? I have a Spring Batch app that processes 1000s of rows of data in batches of 20 (the throttle-limit per thread). The commit-interval in the batch configuration is also 20. Data that has been processed is kept in a detail table reflecting its status (in a Postgresql database).
I'm finding that the more data I throw at the app, the last few batches don't get committed to the detail table, although the processes in the batch were executed successfully. So right now I'm combing through logs to see where the commits are occurring, but can't seem to come up with the right logger. In my properties file I have spring.jpa.properties.hibernate.type=trace, and here are my loggers:
  <logger name="org.springframework.orm.jpa" level="DEBUG">
    <appender-ref ref="STDOUT" />
  </logger>

  <logger name="org.springframework.transaction" level="TRACE">
    <appender-ref ref="STDOUT" />
  </logger>

  <logger name="org.springframework.jdbc" level="TRACE">
    <appender-ref ref="STDOUT" />
  </logger>

  <logger name="org.hibernatec" level="TRACE">
    <appender-ref ref="STDOUT" />
  </logger>

And here's the method that issues the statements that aren't always being committed:
@Transactional(propagation = Propagation.REQUIRES_NEW)
@Override
public void updateJobDetail(String jobId, String domainCode, String codesDelimited, Date effectiveDate,
                                   StatusEnum status, String userId) {

        [business logic]

        detailRepository.save(entities);
        detailRepository.flush();
        entityManager.clear();
}

I guess my question is two-fold: Why might the database not reflect the last few batches, and how do I see in the logs if commits are being issued?
Update: Here is what the logs do show. Why are the statements being logged twice, I wonder?
15:35:02.288 [ThreadPoolExecutor-26] INFO  c.e.s.i.DetailServiceImpl - updateDetail - exit in 101 ms
15:35:02.288 [ThreadPoolExecutor-26] TRACE o.s.t.i.TransactionInterceptor - Completing transaction for [com.erd.service.impl.DetailServiceImpl.updateDetail]
15:35:02.288 [ThreadPoolExecutor-26] TRACE o.s.t.i.TransactionInterceptor - Completing transaction for [com.erd.service.impl.DetailServiceImpl.updateDetail]

A:
I use REQUIRES_NEW because I need to see the results immediately in the db, otherwise we can't see the detail result until the entire batch is finished.

I see no valid reason for that. Why use a chunk oriented step in the first place then? A chunk oriented step is used when a chunk of records is meant to be processed and written as a unit (at the chunk' transaction boundaries), aka all or nothing semantics.
So trying to work around that with nested smaller transactions inside the one driven by Spring Batch is working against the goal of chunk-oriented processing in the first place.
I recommend changing your approach by removing @Transactional(propagation = Propagation.REQUIRES_NEW) and choosing a smaller chunk size if you want to see more records committed more frequently to the database.

How can I see the commits being issued in the logs?

In addition to setting the log level to debug for Spring Batch and Spring JDBC, I use p6spy to see all statements sent to the database. It will give you something like:
1543399291411|0|statement|connection0|select BATCH_STEP_EXECUTION_SEQ.nextval from dual
1543399291412|0|statement|connection0|INSERT into BATCH_STEP_EXECUTION(STEP_EXECUTION_ID, VERSION, STEP_NAME, JOB_EXECUTION_ID, START_TIME, END_TIME, STATUS, COMMIT_COUNT, READ_COUNT, FILTER_COUNT, WRITE_COUNT, EXIT_CODE, EXIT_MESSAGE, READ_SKIP_COUNT, WRITE_SKIP_COUNT, PROCESS_SKIP_COUNT, ROLLBACK_COUNT, LAST_UPDATED) values(1, 0, 'step', 1, '28-Nov-18', NULL, 'STARTING', 0, 0, 0, 0, 'EXECUTING', '', 0, 0, 0, 0, '28-Nov-18')
1543399291413|0|statement|connection0|INSERT INTO BATCH_STEP_EXECUTION_CONTEXT (SHORT_CONTEXT, SERIALIZED_CONTEXT, STEP_EXECUTION_ID) VALUES('{}', NULL, 1)
1543399291413|0|commit|connection0|


text:
Q: SSDT project builds much slower with MSBuild than in VS 2013 I noticed that our SSDT projects were building much slower via TFS build definitions than via VS 2013 on my local dev box.
On the build server itself, I can build our largest SSDT project via VS 2013 in about 2 minutes. The exact same project builds from the command line on the same server using MSBuild in about 16 minutes (i.e. building in the same way TFS build definitions build SSDT projects)
I've gathered /verbosity:diagnostic output from both methods, but cannot for the life of me see any material difference in the parameters being supplied to MSBuild.
In VS 2013, the configuration was Debug:AnyCPU.
The MSBuild command I used was:
msbuild /t:rebuild /p:Configuration=Debug /p:Platform=AnyCPU .sqlproj
I've tried the same process on much smaller SSDT projects, and I get similar relative discrepancies in build times (e.g. another project I have takes 10 seconds in VS 2013, and 70-80 seconds via MSBuild)
I have the very latest versions of VS 2013 (12.0.40629.00 Update 5) and SSDT (12.0.60629.0)
Has anyone else seen this issue, or even has a solution to this problem?
Would a move to VS 2015 solve the problem?

Edited to respond to comments and to include diagnostic information - 15-08-2016
Thank you guys for getting back to me with your suggestions.
Ed, When testing VS against MSBuild I've used build target Rebuild, which I believe is a combination of Clean and Build.  In the TFS build definition I have the "Clean Workspace" and "Clean build" set to true, however the time for the "Get sources" step is only 9 seconds.
Steven, the dbmdl factor sounded really promising.  However, I tried the tests again after deleting all dbmdl files from the solution, and I'm still getting the same times (I verified the dbmdl files hadn't been regenerated between test builds).  Also, I've deleted all the bin and obj folders before the tests, just to eliminate any possibility of cached data for VS builds.
Cece, I've effectively removed TFS from this problem, because I get build time discrepancies when testing VS and MSBuild.  I think if I can crack that, TFS build times will be cracked too.  You had a good point about which build step the time is been taken in.  I didn't want to flood the initial post with too much info, but now's the time :-).  I used the /clp:PerformanceSummary option to get a breakdown of where the time's being spent.
Below in section 1 you can see the time is almost all spent in the "SqlBuildTask".  Nice to know, but not very helpful in pinpointing the issue.
In sections 2 and 3 is information I got from both build methods using the /verbosity:diagnostic output
I cannot see any material difference between the two builds.  Both must be using this DLL to perform that actual build (MSBuild explicitly declares a reference to this DLL):
 C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\\Extensions\Microsoft\SQLDB\Dac\130\Microsoft.Data.Tools.Schema.Tasks.Sql.dll"

------------- section 1 -------------
(Output from MSBuild with /clp:PerformanceSummary)
Project Performance Summary:
        82518 ms  P:\<snip>.sqlproj   1 calls
                  82518 ms  rebuild                                    1 calls

Target Performance Summary:
        0 ms  BuildOnlySettings                          2 calls
        0 ms  GetReferenceAssemblyPaths                  2 calls
        0 ms  GetSqlSymbolsPath                          1 calls
        0 ms  BeforeBuild                                2 calls
        0 ms  ResolveReferences                          2 calls
        0 ms  GetCopyToOutputDirectoryXamlAppDefs        2 calls
        0 ms  SqlStudioSourceFilesToCopy                 2 calls
        0 ms  AssignProjectConfiguration                 1 calls
        0 ms  BeforeClean                                2 calls
        0 ms  _CopySourceItemsToOutputDirectory          2 calls
        0 ms  Build                                      2 calls
        0 ms  GetCopyToOutputDirectoryItems              2 calls
        0 ms  Clean                                      2 calls
        0 ms  CleanPublishFolder                         2 calls
        0 ms  GetFrameworkPaths                          2 calls
        0 ms  GetTargetPath                              2 calls
        0 ms  _CleanGetCurrentAndPriorFileWrites         2 calls
        0 ms  _CopyFilesMarkedCopyLocal                  1 calls
        0 ms  AfterResolveReferences                     2 calls
        0 ms  PreXsdCodeGen                              2 calls
        0 ms  CopyFilesToOutputDirectory                 2 calls
        0 ms  GetNativeManifest                          1 calls
        0 ms  GetInstalledSDKLocations                   2 calls
        0 ms  IncrementalClean                           2 calls
        0 ms  PrepareForRun                              2 calls
        0 ms  _SplitProjectReferencesByFileExistence     2 calls
        0 ms  _SetupSqlBuildOutputs                      2 calls
        0 ms  BeforeResolveReferences                    2 calls
        0 ms  GetSqlTargetPath                           1 calls
        0 ms  Rebuild                                    1 calls
        0 ms  AfterClean                                 2 calls
        0 ms  AfterBuild                                 2 calls
        0 ms  ExpandSDKReferences                        2 calls
        0 ms  CleanStaticCodeAnalysis                    2 calls
        0 ms  BeforeRebuild                              1 calls
        0 ms  CheckRequiredProperties                    2 calls
        0 ms  GenerateSqlTargetFrameworkMoniker          2 calls
        0 ms  ResolveSDKReferences                       2 calls
        0 ms  AfterRebuild                               1 calls
        0 ms  ResolveArtifactReferences                  2 calls
        0 ms  _CopyOutOfDateSourceItemsToOutputDirectoryAlways   1 calls
        0 ms  _CheckForCompileOutputs                    2 calls
        0 ms  PrepareForBuild                            2 calls
        0 ms  CleanXsdCodeGen                            2 calls
       16 ms  _CheckForInvalidConfigurationAndPlatform   2 calls
       16 ms  AssignTargetPaths                          2 calls
       16 ms  CoreClean                                  2 calls
       31 ms  ResolveAssemblyReferences                  2 calls
       31 ms  SqlPrepareForRun                           2 calls
       31 ms  CleanReferencedProjects                    2 calls
       63 ms  PostBuildEvent                             2 calls
       63 ms  PreBuildEvent                              2 calls
       94 ms  CoreCompile                                2 calls
      625 ms  _SetupSqlBuildInputs                       2 calls
     6452 ms  ResolveProjectReferences                   2 calls
    81502 ms  SqlBuild                                   2 calls

Task Performance Summary:
        0 ms  AssignTargetPath                          26 calls
        0 ms  CallTarget                                 2 calls
        0 ms  FindAppConfigFile                          2 calls
        0 ms  ConvertToAbsolutePath                      2 calls
        0 ms  AssignProjectConfiguration                 1 calls
        0 ms  ReadLinesFromFile                          4 calls
        0 ms  WriteLinesToFile                           4 calls
        0 ms  Copy                                       6 calls
        0 ms  FindUnderPath                             14 calls
        0 ms  RemoveDuplicates                           6 calls
        0 ms  MakeDir                                    4 calls
       16 ms  SqlScriptDependenciesTask                  2 calls
       16 ms  Delete                                    12 calls
       31 ms  ResolveAssemblyReference                   2 calls
       31 ms  Message                                    8 calls
       94 ms  Csc                                        1 calls
      126 ms  Exec                                       4 calls
      516 ms  SqlModelResolutionTask                     2 calls
     6468 ms  MSBuild                                    7 calls
    81424 ms  SqlBuildTask                               2 calls

------------- section 2 -------------
(The diagnostic output given during the SqlBuildTask phase of the build for VS)
Target "SqlBuild" in file "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v12.0\SSDT\Microsoft.Data.Tools.Schema.SqlTasks.targets" from project "P:<snip>.sqlproj" (target "Build" depends on it):
    Building target "SqlBuild" completely.
    Output file "P:<snip>.dacpac" does not exist.
    Task "SqlBuildTask"
        Task Parameter:SqlTarget=P:<snip>.dacpac
        Task Parameter:ContributorArguments=ConfigurationName=Debug;
        Task Parameter:BuildContributors=;
        Task Parameter:DeploymentContributors=;
        Task Parameter:CreateScriptFileName=<snip>.sql
        Task Parameter:DacApplicationName=<snip>
        Task Parameter:DacDescription=<snip>
        Task Parameter:DacFile=P:<snip>\bin\Debug\
        Task Parameter:DacVersion=3.27.0.0
        Task Parameter:DatabaseName=<snip>
        Task Parameter:DatabaseSchemaProviderName=Microsoft.Data.Tools.Schema.Sql.Sql100DatabaseSchemaProvider
        Task Parameter:DefaultSchema=dbo
        Task Parameter:DeploymentScriptName=<snip>.sql
        Task Parameter:DeployToDatabase=True
        Task Parameter:ImplicitDllAssemblyName=<snip>
        Task Parameter:ImplicitDllFileName=P:<snip>.dll
        Task Parameter:ImplicitDllSymbolsFileName=P:<snip>.pdb
        Task Parameter:ImplicitDllGenerateSqlClrDdl=true
        Task Parameter:IntermediateDirectory=P:<snip>\obj\Debug\
        Task Parameter:ModelCollation=1033,CI
        Task Parameter:OutputDirectory=P:<snip>\bin\Debug\
        Task Parameter:
    Source= <snip - list of all the source files in the SSDT project - matches list for MSBuild builds>

        Task Parameter:
    SqlCmdVariables= <snip - same for both builds>
        Task Parameter:
    SqlReferencePath=
        C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\mscorlib.dll
                CopyLocal=false
                FrameworkFile=true
                FusionName=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
                ImageRuntime=v4.0.30319
                OriginalItemSpec=C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\mscorlib.dll
                ReferenceSourceTarget=ResolveAssemblyReference
                ResolvedFrom=C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\mscorlib.dll
                Version=4.0.0.0
        Task Parameter:SuppressTSqlWarnings=71562,71502,71558
        Task Parameter:ValidateCasingOnIdentifiers=true
        Task Parameter:CmdLineInMemoryStorage=false
        Task Parameter:DefaultCollation=SQL_Latin1_General_CP1_CI_AS
        Task Parameter:AnsiNullDefault=False
        Task Parameter:AnsiNulls=False
        Task Parameter:AnsiPadding=False
        Task Parameter:AnsiWarnings=False
        Task Parameter:ArithAbort=False
        Task Parameter:ConcatNullYieldsNull=False
        Task Parameter:QuotedIdentifier=False
        Task Parameter:NumericRoundAbort=False
        Task Parameter:RecursiveTriggersEnabled=False
        Task Parameter:DatabaseChaining=False
        Task Parameter:DatabaseState=ONLINE
        Task Parameter:CloseCursorOnCommitEnabled=False
        Task Parameter:DefaultCursor=GLOBAL
        Task Parameter:AutoClose=False
        Task Parameter:AutoCreateStatistics=True
        Task Parameter:AutoShrink=False
        Task Parameter:AutoUpdateStatistics=True
        Task Parameter:TornPageDetection=False
        Task Parameter:DatabaseAccess=MULTI_USER
        Task Parameter:Recovery=FULL
        Task Parameter:EnableFullTextSearch=False
        Task Parameter:DefaultFilegroup=PRIMARY
        Task Parameter:Trustworthy=True
        Task Parameter:AutoUpdateStatisticsAsynchronously=False
        Task Parameter:PageVerify=CHECKSUM
        Task Parameter:ServiceBrokerOption=DisableBroker
        Task Parameter:DateCorrelationOptimizationOn=False
        Task Parameter:Parameterization=SIMPLE
        Task Parameter:AllowSnapshotIsolation=False
        Task Parameter:ReadCommittedSnapshot=True
        Task Parameter:VardecimalStorageFormatOn=True
        Task Parameter:SupplementalLoggingOn=False
        Task Parameter:CompatibilityMode=100
        Task Parameter:IsChangeTrackingOn=False
        Task Parameter:IsChangeTrackingAutoCleanupOn=True
        Task Parameter:ChangeTrackingRetentionPeriod=2
        Task Parameter:ChangeTrackingRetentionUnit=Days
        Task Parameter:IsEncryptionOn=False
        Task Parameter:IsBrokerPriorityHonored=False
        Task Parameter:IncludeCompositeObjects=True
        Loading project references...
        Loading project files...
        Building the project model and resolving object interdependencies...
        Validating the project model...
        Writing model to P:<snip>\obj\Debug\Model.xml...

------------- section 3 -------------
(The diagnostic output given during the SqlBuildTask phase of the build for MSBuild)
Target "SqlBuild: (TargetId:68)" in file "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v12.0\SSDT\Microsoft.Data.Tools.Schema.SqlTasks.targets" from project "P:<snip>.sqlproj" (target "Build" depends on it):
Building target "SqlBuild" completely.
Output file "P:<snip>.dacpac" does not exist.
Using "SqlBuildTask" task from assembly "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\\Extensions\Microsoft\SQLDB\Dac\130\Microsoft.Data.Tools.Schema.Tasks.Sql.dll".
Task "SqlBuildTask" (TaskId:56)
  Task Parameter:SqlTarget=P:<snip>.dacpac (TaskId:56)
  Task Parameter:ContributorArguments=ConfigurationName=Debug; (TaskId:56)
  Task Parameter:BuildContributors=; (TaskId:56)
  Task Parameter:DeploymentContributors=; (TaskId:56)
  Task Parameter:CreateScriptFileName=<snip>.sql (TaskId:56)
  Task Parameter:DacApplicationName=<snip> (TaskId:56)
  Task Parameter:DacDescription=<snip> (TaskId:56)
  Task Parameter:DacFile=P:<snip>\bin\Debug\ (TaskId:56)
  Task Parameter:DacVersion=3.27.0.0 (TaskId:56)
  Task Parameter:DatabaseName=<snip> (TaskId:56)
  Task Parameter:DatabaseSchemaProviderName=Microsoft.Data.Tools.Schema.Sql.Sql100DatabaseSchemaProvider (TaskId:56)
  Task Parameter:DefaultSchema=dbo (TaskId:56)
  Task Parameter:DeploymentScriptName=<snip>.sql (TaskId:56)
  Task Parameter:DeployToDatabase=True (TaskId:56)
  Task Parameter:ImplicitDllAssemblyName=<snip> (TaskId:56)
  Task Parameter:ImplicitDllFileName=P:<snip>.dll (TaskId:56)
  Task Parameter:ImplicitDllSymbolsFileName=P:<snip>.pdb (TaskId:56)
  Task Parameter:ImplicitDllGenerateSqlClrDdl=true (TaskId:56)
  Task Parameter:IntermediateDirectory=P:<snip>\obj\Debug\ (TaskId:56)
  Task Parameter:ModelCollation=1033,CI (TaskId:56)
  Task Parameter:OutputDirectory=P:<snip>\bin\Debug\ (TaskId:56)
  Task Parameter:
      Source= <snip - list of all the source files in the SSDT project - matches list for VS builds>
  Task Parameter:
      SqlCmdVariables= <snip - same for both builds>
  Task Parameter:
      SqlReferencePath=
          C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\mscorlib.dll
                  CopyLocal=false
                  FrameworkFile=true
                  FusionName=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
                  ImageRuntime=v4.0.30319
                  OriginalItemSpec=C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\mscorlib.dll
                  ReferenceSourceTarget=ResolveAssemblyReference
                  ResolvedFrom=C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\mscorlib.dll
                  Version=4.0.0.0 (TaskId:56)
  Task Parameter:SuppressTSqlWarnings=71562,71502,71558 (TaskId:56)
  Task Parameter:ValidateCasingOnIdentifiers=true (TaskId:56)
  Task Parameter:CmdLineInMemoryStorage=false (TaskId:56)
  Task Parameter:DefaultCollation=SQL_Latin1_General_CP1_CI_AS (TaskId:56)
  Task Parameter:AnsiNullDefault=False (TaskId:56)
  Task Parameter:AnsiNulls=False (TaskId:56)
  Task Parameter:AnsiPadding=False (TaskId:56)
  Task Parameter:AnsiWarnings=False (TaskId:56)
  Task Parameter:ArithAbort=False (TaskId:56)
  Task Parameter:ConcatNullYieldsNull=False (TaskId:56)
  Task Parameter:QuotedIdentifier=False (TaskId:56)
  Task Parameter:NumericRoundAbort=False (TaskId:56)
  Task Parameter:RecursiveTriggersEnabled=False (TaskId:56)
  Task Parameter:DatabaseChaining=False (TaskId:56)
  Task Parameter:DatabaseState=ONLINE (TaskId:56)
  Task Parameter:CloseCursorOnCommitEnabled=False (TaskId:56)
  Task Parameter:DefaultCursor=GLOBAL (TaskId:56)
  Task Parameter:AutoClose=False (TaskId:56)
  Task Parameter:AutoCreateStatistics=True (TaskId:56)
  Task Parameter:AutoShrink=False (TaskId:56)
  Task Parameter:AutoUpdateStatistics=True (TaskId:56)
  Task Parameter:TornPageDetection=False (TaskId:56)
  Task Parameter:DatabaseAccess=MULTI_USER (TaskId:56)
  Task Parameter:Recovery=FULL (TaskId:56)
  Task Parameter:EnableFullTextSearch=False (TaskId:56)
  Task Parameter:DefaultFilegroup=PRIMARY (TaskId:56)
  Task Parameter:Trustworthy=True (TaskId:56)
  Task Parameter:AutoUpdateStatisticsAsynchronously=False (TaskId:56)
  Task Parameter:PageVerify=CHECKSUM (TaskId:56)
  Task Parameter:ServiceBrokerOption=DisableBroker (TaskId:56)
  Task Parameter:DateCorrelationOptimizationOn=False (TaskId:56)
  Task Parameter:Parameterization=SIMPLE (TaskId:56)
  Task Parameter:AllowSnapshotIsolation=False (TaskId:56)
  Task Parameter:ReadCommittedSnapshot=True (TaskId:56)
  Task Parameter:VardecimalStorageFormatOn=True (TaskId:56)
  Task Parameter:SupplementalLoggingOn=False (TaskId:56)
  Task Parameter:CompatibilityMode=100 (TaskId:56)
  Task Parameter:IsChangeTrackingOn=False (TaskId:56)
  Task Parameter:IsChangeTrackingAutoCleanupOn=True (TaskId:56)
  Task Parameter:ChangeTrackingRetentionPeriod=2 (TaskId:56)
  Task Parameter:ChangeTrackingRetentionUnit=Days (TaskId:56)
  Task Parameter:IsEncryptionOn=False (TaskId:56)
  Task Parameter:IsBrokerPriorityHonored=False (TaskId:56)
  Task Parameter:IncludeCompositeObjects=True (TaskId:56)
  Creating a model to represent the project... (TaskId:56)
  Loading project references... (TaskId:56)
  Loading project files... (TaskId:56)
  Building the project model and resolving object interdependencies... (TaskId:56)
  Validating the project model... (TaskId:56)
  Writing model to P:<snip>\obj\Debug\Model.xml... (TaskId:56)
Done executing task "SqlBuildTask". (TaskId:56)

A: For those who experiences slow SSDT builds of projects with many dacpac dependencies there is one more option: simplify those dacpacs and make them smaller.
The key assumption was made with realizing that referencing a dacpac is not the same as deploying it: it is not supposed to require as much meta data as the "normal" sqlproj.
Here are possible steps that can be done with dacpac-references to reduce their sizes and build time drastically (in addition to options mentioned by Mark and others).
Shown code tips are in Powershell.
Inside DACPAC
DACPAC is a ZIP archive containing XML files. So you can open it and review model.xml which is the project itself expressed as a single file of metadata and sources. This file can be very big (100MB+) and as you know size of XML file influences processing performance of it. SSDT generates very verbose description of different sql elements.
To start processing it unpack and load source XML:
Expand-Archive -Path $dacpac -DestinationPath $expandedFolder | Out-Null;
[xml] $dacpacXml = Get-Content "$expandedFolder/model.xml";

$ns = New-Object System.Xml.XmlNamespaceManager($dacpacXml.value.NameTable);
$ns.AddNamespace("dac", $dacpacXml.value.DocumentElement.NamespaceURI);

Metadata not used for referencing
authorization
I believe your TSQL code is not supposed to need hard references to such objects in a different database as:

*

*user, login, role

*permissions, rolemembership, authorization and execution context (user/login) info

so removing them
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlRoleMembership']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlPermissionStatement']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlLogin']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlUser']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlRole']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Relationship[@Name = 'Login']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Relationship[@Name = 'User']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Relationship[@Name = 'Authorizer']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Relationship[@Name = 'Schema']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;

and if you keep all of it in your sqlproj (users, logins), I'd suggest to review this approach and remove exploitation level data from source code.
plus sensitive data and signatures
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Property[@Name = 'EncryptionPassword' or @Name = 'Password']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlCertificate' or @Type = 'SqlSymmetricKey']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlSignature']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;

file storage and partitions info
If you have partitioned tables with many partitions then your dacpacs contain hundreds or thousands of elements for each partition.

$dacpacXml.value.DocumentElement.SelectNodes("//dac:Relationship[@Name = 'DataCompressionOptions' or @Name = 'BoundaryValues']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Relationship[@Name = 'Filegroups']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Relationship[@Name = 'Filegroup']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Relationship[@Name = 'FilegroupForTextImage']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Relationship[@Name = 'PartitionScheme' or @Name = 'PartitionColumn']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;

DML and DDL objects
Objects not supposed to be referenced from outside a database as well

*

*triggers

*indicies

*default constraints

so removing them
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlIndex']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlDmlTrigger']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlIndexedColumnSpecification']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlDatabaseDdlTrigger']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlDefaultConstraint']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;

sources
Whilst a SP can be referenced, it's sources are not required for this - we already have all the metadata for it: params are described verbosely as separate Elements with type info and so on. So removing all the sources
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlView']/dac:Property[@Name = 'QueryScript']", $ns) | % { write-verbose $_.ParentNode.Name; $_.ParentNode.removechild($_); } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlProcedure']/dac:Property[@Name = 'BodyScript']", $ns) | % { write-verbose $_.ParentNode.Name; $_.ParentNode.removechild($_); } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlScriptFunctionImplementation']/dac:Property[@Name = 'BodyScript']", $ns) | % { write-verbose $_.ParentNode.Name; $_.ParentNode.removechild($_); } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlAssemblyFile']/dac:Property[@Name = 'Source']", $ns) | % { write-verbose $_.ParentNode.Name; $_.ParentNode.removechild($_); } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlComputedColumn']/dac:Property[@Name = 'ExpressionScript']", $ns) | % { write-verbose $_.ParentNode.Name; $_.ParentNode.removechild($_); } | Out-Null;

and dependencies produced by build from these sources
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Relationship[@Name = 'BodyDependencies']", $ns) | % { write-verbose $_.ParentNode.Name; $_.ParentNode.removechild($_); } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Relationship[@Name = 'QueryDependencies' or @Name = 'ExpressionDependencies']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Relationship[@Name = 'DynamicObjects']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Relationship[@Name = 'AssemblySources']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlQueue']/dac:Relationship", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlContract']/dac:Relationship[@Name = 'Messages']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;

annotations
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Annotation[@Type = 'SysCommentsObjectAnnotation']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Relationship[@Name = 'BoundTargets']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Annotation[@Type = 'PersistedResolvableAnnotation']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlExtendedProperty']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlSimpleColumn']/dac:AttachedAnnotation", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;

update of november 2022
Some time later I decided to go deeper, reviewed our cleaned dacpacs and found some more options for cleanup.
A little more sources/expressions
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Property[@Name = 'CheckExpressionScript']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Relationship[@Name = 'FunctionBody']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlSubroutineParameter']/dac:Property[@Name = 'DefaultExpressionScript']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;

"private" relations
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlContract']/dac:Relationship[@Name = 'Messages']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlService']/dac:Relationship[@Name = 'Contracts' or @Name = 'Queue']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlSynonym']/dac:Property[@Name = 'ForObjectScript']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlSynonym']/dac:Relationship[@Name = 'ForObject']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;

properties which have no effect on build or reference resolution
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Property[@Name = 'IsActivationOn' or @Name = 'MaxQueueReaders']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Property[@Name = 'IsMemoryOptimized' or @Name = 'IsNativelyCompiled' or @Name = 'IsSchemaBound']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Property[@Name = 'FillFactor' or @Name = 'IsPadded' or @Name = 'IsClustered']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Property[@Name = 'LockEscalation' or @Name = 'RetentionUnit' or @Name = 'Collation']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Property[@Name = 'IsAnsiNullsOn' or @Name = 'IsQuotedIdentifierOn']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Property[@Name = 'IsNullable' or @Name = 'IsReadOnly' or @Name = 'IsHidden']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Property[@Name = 'IsIdentity' or @Name = 'IdentitySeed' or @Name = 'IsRowGuidColumn']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Property[@Name = 'IsCaller' or @Name = 'IsOwner']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;

Proc/func param and column type definitions are terribly verbose and somehow it comes SSDT never uses any of it. Which looks strange to me. It felt dangerous and a bit unreal when removing this metadata but after removing it from 70+ dacpacs SSDT haven't said anything about it. Builds are the same (just faster).
Here is an example of saying "this column is of type DECIMAL(18,8)":
<Relationship Name="TypeSpecifier">
    <Entry>
        <Element Type="SqlTypeSpecifier">
            <Property Name="Scale" Value="8"/>
            <Property Name="Precision" Value="18"/>
            <Relationship Name="Type">
                <Entry>
                    <References ExternalSource="BuiltIns" Name="[decimal]"/>
                </Entry>
            </Relationship>
        </Element>
    </Entry>
</Relationship>

making our ref-dacpac structure much more flat
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlScalarFunction']/dac:Relationship[@Name = 'Type']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlPartitionFunction']/dac:Relationship[@Name = 'ParameterType']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlSubroutineParameter']/dac:Relationship[@Name = 'Type']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlSimpleColumn' or @Type = 'SqlTableTypeSimpleColumn']/dac:Relationship[@Name = 'TypeSpecifier']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Relationship[@Name = 'ColumnSpecifications']/dac:Entry", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;

Removing constraints and links to them. Note, these must be removed all at once! or none. Earlier I tried to remove some of constraints, some of annotations but internal cross-references from metadata became broken and such dacpacs did not work. Finally found out how to remove it "consistently":
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlDefaultConstraint' or @Type = 'SqlTableTypeDefaultConstraint' or @Type = 'SqlTableTypePrimaryKeyConstraint' or @Type = 'SqlPrimaryKeyConstraint']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlForeignKeyConstraint' or @Type = 'SqlCheckConstraint' or @Type = 'SqlUniqueConstraint']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Annotation[@Type = 'SqlInlineConstraintAnnotation' or @Type = 'SqlInlineIndexAnnotation']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Relationship[@Name = 'Constraints']", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlTable' or @Type = 'SqlTableType']/dac:AttachedAnnotation", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;
# here only Disambiguator attr getting removed, not the whole element
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Element[@Type = 'SqlTableType' or @Type = 'SqlSubroutineParameter']", $ns) | % { $_.RemoveAttribute("Disambiguator") } | Out-Null;

Changes from this update reduced dacpacs more by 1.5 times. Build gained boost by ~20%
// end of update
cleanup
Deletions have produced number of empty elements with no children. Removing them
$dacpacXml.value.DocumentElement.SelectNodes("//dac:Entry[not(child::*)]", $ns) | % { $_.ParentNode.RemoveChild($_) } | Out-Null;

save changes
$dacpacXML.Save("$expandedFolder/model.xml");

Recompress DACPAC
After editing we need to turn our xml files back into dacpac. Before that it's required to recompute and update checksum in Origin.xml which is a part of dacpac archive as well. DACPACs with mismatching checksum won't work.
$newModelHash = (Get-FileHash -Path "$expandedFolder/model.xml").Hash;

[xml] $originXML = Get-Content "$expandedFolder/Origin.xml";
$originXML.DacOrigin.Checksums.Checksum.InnerText = $newModelHash;
$originXML.Save("$expandedFolder/Origin.xml");

Now we are ready, so compressing it back (note /* in the end of path to compress all the files but not the containing folder). Copy, rename afterwards.
Compress-Archive -Path "$expandedFolder/*" -DestinationPath "$dacpac.zip" -CompressionLevel Optimal -Force;

Build
Now put your recompressed references (dacpacs) into appropriate folder and rerun build process. As tested, edited dacpacs can become smaller 10-50 times and are fine for references resolution in VS or MSBuild. Build time can be halfed by this dirty trick.
Example SQLPROJ build (cli msbuild) statistics with ~3K procs, hundreds of tables and ~20 dacpac dependencies:

*

*naive: ~15min

*p:CmdLineInMemoryStorage: 5-6min

*hacked dacpacs: 2min
Note! Obtained reduced dacpac is fine for referencing but not for deploy!

A: I made the following changes to our large SSDT project and TFS MSBUILD arguments that have brought the build times via TFS build definitions to an explainable level:
1) Add /p:CmdLineInMemoryStorage=TRUE to MSBUILD arguments

This reduced our build times massively.  We had a build definition that went from 40 mins to 16 mins by adding this option. (Times are pre-removal of duplicate references)
2) Removed all duplicate references in the .sqlproj file
Over time the .sqlproj file managed to reference some files 2 or 3 times.  We had about 40 duplicate references.  This was almost certainly due to merge issues between our many branches.  Visual Studio does not complain about this, and builds perfectly happily, but the dups made a significant difference to our build times in TFS, which of course uses MSBUILD.
Finding Duplicate References in sqlproj files
Here's a powershell script I used to find duplicates in our sqlproj files (change $root to point to the folder containing your .sqlproj files):
[Reflection.Assembly]::LoadWithPartialName("System.Xml.Linq") | Out-Null

$root = "C:\TFS"

$sqlprojFiles = Get-ChildItem -Path $root -Filter "*.sqlproj" -Recurse
$numFilesChecked=0

foreach ($f in $sqlprojFiles)
{
    $numFilesChecked++
    $fullName = $f.FullName

    $xml = [System.Xml.Linq.XDocument]::Load($fullName)
    $ns = $xml.Root.Name.Namespace;

    $itemGroups = $xml.Descendants() | Where-Object { $_.Parent.Name -eq $ns + "ItemGroup" };

    $dict = @{}
    $itemGroups.Attributes() | Where-Object { $_.Name -eq "Include"} `
        | % { if ($dict.ContainsKey($_.Value)) {$dict[$_.Value]++} else {$dict.Add($_.Value,1)} }

    $duplicates = $dict.Keys | Where-Object { $dict[$_] -gt 1}

    $fullName

    if ($duplicates.Count -gt 0)
    {
        Write-Output "--------------------------------------------------------"
        $duplicates | % {$_+", "+$dict[$_]}
    }
    else
    {
        Write-Output "No duplicates found"
    }
}

"Files checked: $numFilesChecked"

I used the output of this to manually edit the .sqlproj files textually (i.e. "Unload Project", then "Edit .sqlproj" in VS)
Build Time Differences Explained
Now that our large sqlproj builds in 9 minutes on our build server, I think the build time differences between VS and MSBuild can be explained.
I've been told VS takes advantage of precompiled information about the SSDT project that's not used by MSBuild from the command line.  I can't confirm this, and I certainly didn't see any evidence of this in the "/verbosity:diagnostic"   output from VS (I may have missed it).  However it takes 2 mins to build the large project in VS after VS has finished analysing the project, which suggests it is using cached information in the build process.  It takes several minutes for VS to finish analysing the large project.
MSBuild build times (either from the command line or TFS build definition) takes a consistent 9 mins now.  The extra 7 mins is almost certainly taken up by the MSBuild process analysing the project on every build - something the VS seems to do once (or at least periodically), then takes advantage of the cached information at build time.

A: Thanks to all the other posters here for some great ideas on how to improve our database build times
I significantly modified the PS script to automatically cleanup the sqlproj file of duplicate include entries. We just run it automatically before we run msbuild to set and forget.
In case it can help anyone else:
-- Remove-DbprojDuplicateIncludeNode.ps1
<#
.SYNOPSIS
    Will remove any duplicate references from all sqlproj files
#>
[CmdletBinding(PositionalBinding = $true, SupportsShouldProcess)]
Param(
    $Root = "$PSScriptRoot\..\..\src\"
)

$sqlprojFiles = Get-ChildItem -Path $Root -Filter "*.sqlproj" -Recurse
$numFilesChecked = 0

foreach ($f in $sqlprojFiles) {
    Write-Host "Checking file $($f.FullName)"
    $dbProjPath = $f
    $projXml = [xml](Get-Content $dbProjPath -raw)
    $nsm = [Xml.XmlNamespaceManager]($projXml.NameTable)
    $nsm.AddNamespace('ns', $projXml.Project.xmlns)

    $sqlProjNodes = $projXml.SelectNodes('//ns:*[@Include]', $nsm)

    $numFilesChecked++

    $includedFileSet = [System.Collections.Generic.HashSet[string]]::new()
    $changed = $false

    foreach ($includeNode in $sqlProjNodes) {
        if (-not $includedFileSet.Add($includeNode.Include)) {
            Write-Host "Removing duplicate include node '$($includeNode.Include)'"
            $includeNode.ParentNode.RemoveChild($includeNode)
            $changed = $true
        }
    }

    if ($changed) {
        if ($PSCmdlet.ShouldProcess($dbProjPath)) {
            $projXml.Save($dbProjPath)
        }
    }
}

"Files checked: $numFilesChecked"


text:
Q: Command 'ng serve --host 0.0.0.0' working fine for localhost but APIs not working on different machines, is there any solution for this? The thing is when I run the command ng serve --host 0.0.0.0 it's working fine for both the localhost as well as on the different machines within same network. But, on adding token to the APIs, APIs are not being hit on different machines. It just showing the HTML with CSS without data. It would be great if any solution to this is provided.
I tried with disableHostCheck or with port commands but nothing worked as:
ng serve --host 0.0.0.0 --disableHostCheck true,
ng serve --host 0.0.0.0 --port 4200
I expect the API response to all the devices within same network but there is no response to other devices except mine which is localhost.

A: It will be good if you add a proxy to you server.
In package.json file add below code.
  "scripts": {
    "start": "ng serve --proxy-config proxy.config.json",
}

then create a proxy.config.json file where your package.json file is located.
add below json to proxy.config.json file
{
  "/container1/*": {
    "target": "http://10.101.10.11:8080",
    "secure": false,
    "logLevel": "debug"
  },
"/container2/*": {
    "target": "http://10.101.10.12:8080",
    "secure": false,
    "logLevel": "debug"
  },
"/container3/*": {
    "target": "http://10.101.10.12:8080",
    "secure": false,
    "logLevel": "debug"
  },
}

start your local server using the command npm start
we can give following options to proxy,
{
  "/container": {
     "target":  {
       "host": "stackoverflow.com",
       "protocol": "https:",
       "port": 7001
     },
     "secure": false,
     "changeOrigin": true,
     "logLevel": "info"
  }
}


text:
Q: How to plot integral of a gradient function For $f : \mathbb{R} \longrightarrow \mathbb{R}$ continously differentiable and $\phi \in [0,\pi/2]$ let
$$F(x) = \int \frac{f'(x)-\cot \phi}{1+ f'(x) \cot \phi} d x$$
be a clockwise 'rotation' of $f$.
For given $f$ it is not hard to plot $\tilde f$ in mathematica.
For $f : \mathbb{R}^2 \longrightarrow \mathbb{R}$ a two-dimensional generalization (in my opinion) of this mapping (in direction $\vec{1}$) is given by
$$F(x) = \int \frac{\nabla f(x)-\frac{\cot \phi}{\sqrt{2}}\vec{1}}{1+ \frac{\cot \phi}{\sqrt{2}}\nabla f(x) \vec{1}^\top} \cdot d x.$$
Using for instance f[x_,y_]:=Exp[-x^2-y^2], how can we plot $F$?
Note: For instance $\int \nabla f(x) \cdot d x$ should look like $f$ (up to a constant) since it does not matter over which path we integrate.
Edit: Using a trivial path it is
$$\int_{\vec{0}}^{(u,v)} \nabla f(x) \cdot d x = \int_0^1 \nabla f(u t,v t)\cdot (u,v)  d t$$
and we can write
f[x_,y_]:=Exp[-x^2-y^2];
nabla[x_,y_]=D[f[x,y],{{x,y}}];
F[u_,v_]:=Integrate[nabla[u t,v t].{u,v},{t,0,1}];
Plot3D[F[u,v],{u,-1,1},{v,-1,1}]

But is this the best path, the best method to do it? At least it seems to work if we apply this for $F$:


text:
Q: jQuery и переключение без перезагрузки Приветствую! У меня такая проблема: пытаюсь реализовать переключение по ссылкам без перезагрузки страницы, а именно отправляя $.post и меняя содержимое #content-блока. При клике на ссылку вне блока #content все работает, но когда нажимаешь ссылку внутри этого блока - страница открывается с перезагрузкой.
Вот сам скрипт, в php просто отправляется скрипт с подменой блока, а в js:
$('a').click(function(){
var href = $(this).attr('href');
cl(href);
return false;
});
function cl(href) {
$.post(href,{act: 'load'},function (result) {eval(result);});
return false;
}

A: Просто вы обновляете DOM и новые ссылки не знают, что не нужно перегружать страницу.
Попробуйте вместо
$('a').click(function(){...})

использовать
$('a').live('click', function(){...})

live привязывает событие не только ко всем текущим элементам DOM, но и к новым, динамически созданным


text:
Q: React. How to collect and transfer the collection of nodes as props to children So, I try to collect the nodes after that the page are builded in the module iteamsHolder. It works for main App component and it see all collected iteams when I invoke the module iteamsHolder inside it.
But when I try to transfer the iteamsHolder module with iteams to children componennts of App, I have an error or undefined for this module iteams. So, I understand that the problem is in the component queue render. But how we can solve that error?
/* MAIN APP COMPONENT */
import iteamsHolder from '../view/iteamsHolder'
import sidebarWidgetHide from '../view/sidebarWidgetHide'

class App extends React.Component {
  constructor(props) {
    super(props);

    this.handleKeyCode = this.handleKeyCode.bind(this);
    this.handleClick = this.handleClick.bind(this);
 }

  render() {
    return (
      <Fragment>
        <Preloader/>
        <LeftSideInfo state={this.state.toggle} updateState={this.updateState}
             coordY={this.state.coordY}/>
        <MenuButtonOpen state={this.state.toggle} updateState={this.updateState}
             iteamsHolder={iteamsHolder().iteamsMain}/> // this is where I'm
                                    // trying to transfer the iteams module.
      </Fragment>
    )
  }

/* ITEAM HOLDER MODULE */
const iteamsHolder = () => {
    if (document.readyState === "complete") {
        let iteamsMain = {
            sidebar: document.querySelector('.left-side__column'),
            rightColumn: document.querySelector('.right-side__column')
        };

        let iteamsSupport = {
            header: document.querySelectorAll('.menu-button__container'),
            menuButton: document.querySelectorAll('.menu-button'),
            menuName: document.querySelector('.personal-name'),
            experienceblock: document.querySelector('.block-headline.block-headline__experience')
        };

        return { iteamsMain, iteamsSupport };
    } else {
        return 'Sorry';
    }

};

export default iteamsHolder;

/CHILD COMPONENT WITH NESTED ITEAMS MODULE/
class MenuButtonOpen extends React.Component {
constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
    this.handleScroll = this.handleScroll.bind(this);
}

render() {
    return (
    {console.log(this.props.iteamsHolder)} // undefined of error
    )
}

A: You're getting undefined because iteamsHolder is returning the default value 'Sorry', not the object { iteamsMain, iteamsSupport }. If you change is to:
<MenuButtonOpen
  state={this.state.toggle}
  updateState={this.updateState}
  iteamsHolder={iteamsHolder()}
/>

you'll see that 'Sorry' is being passed to the component. This is because when iteamsHolder is being evaluated, the webpage is not yet fully loaded. Without knowing why you've structured your code the way you did, I can't make a good suggestion on how to "fix" it. What may help is looking at how document.readyState works and reading through suggestions like what's listed here.


text:
Q: Download and installation of d3web I am new to d3web. However, after I downloaded the latest software from your website and unzip it:
~/study/d3web$ ls
d3web Quickstart.pdf  doc.zip  lib.zip  sources.zip

It contains 3 zip files. There is no bin/ directory as described here.
I want to quickly get it started and test the Printer demo.

A: You are right, and I am sorry for the confusion. With the last release of d3web-KnowWE we changed the distribution script but haven't yet updated the documentation on the linked page to reflect that. The distribution zip now contains 3 folders, d3web, KnowWE and Licenses.
The folder d3web contains just the core libraries to be embedded in other software, you probably won't use them at the beginning. After creating knowledge bases in KnowWE you could use these libraries to run that knowledge base without KnowWE in your own software/app.
The folder KnowWE contains the actual wiki that you probably expect. Besides the zips for documentation and sources, it also contains the KnowWE-Tomcat.zip. Extract this and you get the bin folder and all the rest that is described in the Quickstart.


text:
Q: Is there a callback I can use after a form has been validated? I have to reflow the Foundation equalizer on a page that contains a form [contact page] - if validation failsthe form will overlap the footer with the added validation error elements.
<script type="text/javascript">
//<![CDATA[

    var contactForm = new VarienForm('contactForm', true);

    jQuery('#contact-submit').click(function(){
        console.log('submitted');
        jQuery(document).foundation('equalizer', 'reflow');
    });

//]]>
</script>

Obviously this only works after the submit button is clicked a second time.
Is there a callback function [or something] I can use after Magento have validated the form to call the Foundation reflow?
UPDATE
According to some different docs here and there, I'm supposed to be able to do something like this:
<script type="text/javascript">
//<![CDATA[
    var contactForm = new VarienForm('contactForm', {onFormValidate: myCallback, immediate : true});

    function myCallback(result, form) {
        console.log('callback = ' + result);
    }
//]]>
</script>

It will validate the form, but does not fire the callback OR validate immediately....

A: Yes you can validate your form explicitly and based on the status of the validation (success/failed) you can roll out your own callback actions. Hope am understanding you correctly and pointing you to the right direction.
<script type="text/javascript">
//<![CDATA[

    var contactForm = new VarienForm('contactForm', true);
    if (contactForm .validator.validate()){
        alert("Contact form is submitted and Validation Passed !"); //i love alerts more than console.log() as it works on all the browsers and versions
    }else{
        alert("Contact form is submitted and Validation Failed !");
        jQuery(document).foundation('equalizer', 'reflow'); // assumed you have jQuery.noConflict(); before you call jQuery
    }

//]]>
</script>

A: Solution
<script type="text/javascript">
//<![CDATA[

    var contactForm = new VarienForm('contactForm', true);

    jQuery('#contactForm').submit(function(){
        console.log('submitted');
        jQuery(document).foundation('equalizer', 'reflow');
    });

//]]>
</script>

Difference here is, you are now listening to the event submit() instead of click(). Due to this your jquery function will be triggered after validations are carried out by VarienForm.
Why does it so ?
See VarienForm declaration in js/varien/form.js.
VarienForm = Class.create();
VarienForm.prototype = {
    initialize: function(formId, firstFieldFocus){
        this.form       = $(formId);
        if (!this.form) {
            return;
        }
        this.cache      = $A();
        this.currLoader = false;
        this.currDataIndex = false;
        this.validator  = new Validation(this.form);
        this.elementFocus   = this.elementOnFocus.bindAsEventListener(this);
        this.elementBlur    = this.elementOnBlur.bindAsEventListener(this);
        this.childLoader    = this.onChangeChildLoad.bindAsEventListener(this);
        this.highlightClass = 'highlight';
        this.extraChildParams = '';
        this.firstFieldFocus= firstFieldFocus || false;
        this.bindElements();
        if(this.firstFieldFocus){
            try{
                Form.Element.focus(Form.findFirstElement(this.form))
            }
            catch(e){}
        }
    },

    submit : function(url){
        if(this.validator && this.validator.validate()){
             this.form.submit();
        }
        return false;
    },
    ...
}

You can see above that Validator is called inside the function submit. This means VarienForm validation is bind to the event submit.
In your case, you are using click() event on button, which will be fired before submit() event on form. This is why it is not working in your scenario.
In my solution, we are using form submit event and which is loaded after varien form call. Due to this, jquery submit call will be fired only after VarienFrom has done.

A: var contactForm = new VarienForm('contactForm', true);
$('contactForm').onsubmit = function () {
      if (contactForm.validator.validate()) {
          alert('submited');
          return false;
      }
 };

A: Take a look at the product detail page
    var productAddToCartForm = new VarienForm('product_addtocart_form');
    productAddToCartForm.submit = function(button, url) {
        if (this.validator.validate()) {

            var form = this.form;

            var e = null;
            try {
                this.form.submit();
            } catch (e) {
            }

            if (e) {
                throw e;
            }
        }

        else{
            productOptionError();
        }
    }.bind(productAddToCartForm);

A: I just got success with this method in the newsletter subscription form. But this will work with other forms as well.
 var newsletterSubscriberFormDetail = new VarienForm('newsletter-validate-detail'); // to validate

 function processForm(e) {
    if (e.preventDefault) e.preventDefault();

      if (newsletterSubscriberFormDetail.validator.validate()) {
         // Here comes my ajax fucntion to subscribe
      }

     // You must return false to prevent the default form behavior
     return false;
 }

 var form = document.getElementById('newsletter-validate-detail');
 if (form.attachEvent) {
    form.attachEvent("submit", processForm);
 } else {
    form.addEventListener("submit", processForm);
 }


text:
Q: Excel Sum another sheet with Indirect To sum data from another sheet, I use:
=SUM('SHEETNAME'!A1:A2)
However, I can't figure out how to sum data from another sheet if I use INDIRECT function with it.
I tried:
=SUM('SHEETNAME'!INDIRECT(CONCATENATE("E",C11)):INDIRECT(CONCATENATE("D",C11)))
The CONCATENATE data is on active sheet.  I just need the SUM data from another sheet.

A: Please try:
=SUM(INDIRECT("SHEETNAME!E"&C11&":D"&C11))


text:
Q: Gradle Multiproject I am trying to configure gradle for a multiproject environment.
My project structure is as follows:
MainProject
--external
  --A
  --B
  --C

I have been able to configure the build.gradle and the settings.gradle file for the MainProject.
The problem that I have is that both subprojects A & B depend on C
In project A 's build.gradle
apply plugin: 'android-library'

dependencies {
    compile fileTree(dir: 'libs', include: '*.jar')
    compile project('../C')
}

Gradle says unable to find project with path ../C. What path should I put in there?

A: Try with:
compile project(':external:C')

For more details about project paths see section 56.5 in the Gradle user guide.


text:
Q: Change the color of the "candle" in QCandlestickSet when clicked I am trying to change the color of a QCandlestickSet object but it does not display any color. I have sucessfully changed the color and the width of the "wick" in a QCandlestickSet object however the "candle body" part does not have any color after I have clicked the candlestick in the chart.
Below is a reference of the python program.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets, QtChart
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtChart import *

class Window(QMainWindow):

    def __init__(self):
        super().__init__()

        self.data = ((20190111,15.28,15.54,15.22,15.26),(20190114,15.3,15.56,15.3,15.42),(20190115,15.7,15.98,15.4,15.4),(20190116,15.58,15.6,15.24,15.34))
        self.chart = QChart()
        self.series = QCandlestickSeries(clicked=self.onCandleClicked)

        color = QColor()
        color.setRgb(229,57, 53)
        self.series.setDecreasingColor(color)

        color.setRgb(76,175, 80)
        self.series.setIncreasingColor(color)

        self.series.setBodyOutlineVisible(False)

        self.date_labels = []
        self.resize(640, 480)

        for num, o, h, l, c in self.data:
            self.series.append(QCandlestickSet(o, h, l, c))
            self.date_labels.append(str(num))

        self.chart.addSeries(self.series)

        self.chart.createDefaultAxes()
        self.chart.legend().hide()
        self.chart.axisX(self.series).setCategories(self.date_labels)

        self.chartview = QChartView(self.chart)
        self.chartview.setChart(self.chart)

        central_widget = QtWidgets.QWidget()
        lay = QtWidgets.QVBoxLayout(central_widget)
        lay.addWidget(self.chartview)
        self.setCentralWidget(central_widget)

        self.show()

    def onCandleClicked(self, value):
        candleSet = value
        color = QColor()
        pen = QPen()
        brush = QBrush()

        color.setRgb(0,140,140)
        pen.setColor(color)
        pen.setWidth(3)
        candleSet.setPen(pen)

        brush.setColor(color) #I want to change the color of candle
        candleSet.setBrush(brush)

app = QApplication(sys.argv)
window = Window()
sys.exit(app.exec_())

Output of the program

Output of the program after clicking some candlesticks


text:
Q: Linking Excel tables with multiple similar fields Is there a way to link (or vlookup) two Excel data sheets having mutliple duplicate fields? For example, I want to join session and person data as described below (sample with dummy data):

Both sheets have thousands of rows.
The output should be somthing like that, e.g. for person 00001:

A: Excel PowerQuery did the trick.


text:
Q: How to compute land cover area in R Basically, I computed a global distribution probability model in the form of ASCII, say:
gdpm. gdpm's values are all between 0 and 1.
Then I imported a local map from shape file:
shape <- file.choose()
map <- readOGR(shape, basename(file_path_sans_ext(shape)))

The next step, I rasterized gdpm, and cropped using the local map:
ldpm <- mask(gdpm, map)

Then, I reclassified this continuous model into a discrete model (I divided the model into 6 levels):
recalc <- matrix(c(0, 0.05, 0, 0.05, 0.2, 1, 0.2, 0.4, 2, 0.4, 0.6, 3, 0.6, 0.8, 4, 0.8, 1, 5), ncol = 3, byrow = TRUE)

ldpmR <- reclassify(ldpm, recalc)

I've got a cropped and reclassified raster, now I need to summarize land cover, that is, to each level, I want to calculate its proportion of area in each region of the local map. (I don't know how to describe it in terminology). I found and followed an example (RobertH):
ext <- raster::extract(ldpmR, map)

tab <- sapply(ext, function(x) tabulate(x, 10))
tab <- tab / colSums(tab)

But I'm not sure if it works, since the output of tab is confusing.
So how to compute land cover area correctly? How can I apply the correct method within each polygon?
My original data is too large, I can only provide an alternative raster (I think this example should apply a different reclassify matrix):
Example raster
Or you can generate a test raster (RobertH):
library(raster)
s <- stack(system.file("external/rlogo.grd", package="raster"))
writeRaster(s, file='testtif', format='GTiff', bylayer=T, overwrite=T)
f <- list.files(pattern="testtif_..tif")

I also have a question about plotting a raster:
r <- as(r, "SpatialPixelsDataFrame")
r <- as.data.frame(r)
colnames(r) <- c("value", "x", "y")

I do this conversion to make a raster plot-able with ggplot2, is there a more concise method?

A: loki's answer is OK, but this can be done the raster way, which is safer. And it is important to consider whether the coordinates are angular (longitude/latitude) or planar (projected)
Example data
library(raster)
r <- raster(system.file("external/test.grd", package="raster"))
r <- r / 1000
recalc <- matrix(c(0, 0.05, 0, 0.05, 0.2, 1, 0.2, 0.4, 2, 0.4, 0.6, 3, 0.6, 0.8, 4, 0.8, 2, 5), ncol = 3, byrow = TRUE)
r2 <- reclassify(r, recalc)

Approach 1. Only for planar data
f <- freq(r2, useNA='no')
apc <- prod(res(r))
f <- cbind(f, area=f[,2] * apc)
f

#     value count    area
#[1,]     1    78  124800
#[2,]     2  1750 2800000
#[3,]     3   819 1310400
#[4,]     4   304  486400
#[5,]     5   152  243200

Approach 2. For angular data (but also works for planar data)
a <- area(r2)
z <- zonal(a, r2, 'sum')
z
#     zone     sum
#[1,]    1  124800
#[2,]    2 2800000
#[3,]    3 1310400
#[4,]    4  486400
#[5,]    5  243200

If you want to summarize by polygons, you can do something like this:
# example polygons
a <- rasterToPolygons(aggregate(r, 25))

Approach 1
# extract values (slow)
ext <- extract(r2, a)

# tabulate values for each polygon
tab <- sapply(ext, function(x) tabulate(x, 5))
# adjust for area (planar data only)
tab <- tab * prod(res(r2))

# check the results, by summing over the regions
rowSums(tab)
#[1]  124800 2800000 1310400  486400  243200

Approach 2
x <- rasterize(a, r2)
z <- crosstab(x, r2)
z <- cbind(z, area = z[,3] * prod(res(r2)))

Check results:
aggregate(z[, 'area', drop=F], z[,'Var2', drop=F], sum)
  Var2    area
#1    1  124800
#2    2 2800000
#3    3 1310400
#4    4  486400
#5    5  243200

Note that if you are dealing with lon/lat data you cannot use prod(res(r)) to get the cell size. In that case you will need to use the area function and loop over classes, I think.
You also asked about plotting. There are many ways to plot a Raster* object. The basic ones are:
 image(r2)
 plot(r2)
 spplot(r2)

 library(rasterVis);
 levelplot(r2)

More tricky approaches:
 library(ggplot2) # using a rasterVis method
 theme_set(theme_bw())
 gplot(r2) + geom_tile(aes(fill = value)) +
      facet_wrap(~ variable) +
      scale_fill_gradient(low = 'white', high = 'blue') +
      coord_equal()

 library(leaflet)
 leaflet() %>% addTiles() %>%
 addRasterImage(r2, colors = "Spectral", opacity = 0.8)

A: Seems like you can get the area by the number of pixels.
Let's start with a reproducible example:
r <- raster(system.file("external/test.grd", package="raster"))
plot(r)

Since, the values in this raster are in another range than your data, let's adapt them to your values:
r <- r / 1000
r[r>1,] <- 1

Afterwards, we apply your reclassification:
recalc <- matrix(c(0, 0.05, 0, 0.05, 0.2, 1, 0.2, 0.4, 2, 0.4, 0.6, 3, 0.6, 0.8, 4, 0.8, 1, 5), ncol = 3, byrow = TRUE)
r2 <- reclassify(r, recalc)
plot(r2)

Now, how do we get the area?
Since you are working with a projected raster, you can simply use the number of pixels and the raster resolution. Therefore, we first need to check the resolution and the map units of the projection:
res(r)
# [1] 40 40
crs(r)
# CRS arguments:
#   +init=epsg:28992
# +towgs84=565.237,50.0087,465.658,-0.406857,0.350733,-1.87035,4.0812 +proj=sterea
# +lat_0=52.15616055555555 +lon_0=5.38763888888889 +k=0.9999079 +x_0=155000
# +y_0=463000 +ellps=bessel +units=m +no_defs

Now, we know that we are dealing with pixels of 40 x40 meters, since we have a metric CRS.
Let's use this information to calculate the area of each class.
app <- res(r)[1] * res(r)[2] # area per pixel

table(r2[]) * app
#      1       2       3       4       5
# 124800 2800000 1310400  486400  243200

For the plotting of georeferenced rasters, I would like to refer you to an older question here on SO


text:
Q: hibernate recursive Json response I'm mapping two database tables in two java objects using hibernate. Instead of representing the foreign keys of the tables with an attribute in Java I use @OneToMany and @ManyToMany hibernate annotations.
The problem is that when I want to get the Json list of the objects I get the recursive relationship.
Here is the "parent" object Cliente.java
@Entity @Table(name="clienti")
@AllArgsConstructor @NoArgsConstructor @Data
public class Cliente {

  @Id @Column(name="idcliente") @NotBlank
  private String idCliente;

  @Column(name="ragionesociale")
  private String ragioneSociale;

  @Column(name="nominativo") @NotBlank
  private String nominativo;

  @Column(name="indirizzo")
  private String indirizzo;

  @Column(name="telefono")
  private String telefono;

  @Column(name="email")
  private String email;

  @Column(name="sito")
  private String sito;

  @Column(name="segnalatore")
  private String segnalatore;

  @Column(name="attivita")
  private String attivita;

  @Column(name="interessatoa")
  private String interessatoA;

  @OneToMany(mappedBy="cliente")
  private List<Pratica> pratiche;

  @Column(name="registratoda")
  private String registratoDa;

  @Column(name="data")
  private Date data;

  @Column(name="note")
  private String note;

  @PrePersist
  private void salvaData(){
    data = new Date();
  }
}

This object has a List which is a list of child objects.
Now The Pratica.java class:
@Entity @Table(name="pratiche")
@AllArgsConstructor@NoArgsConstructor @lombok.Data
public class Pratica {

  @Id @Column(name="idpratica")
  private String idPratica;

  @Column(name="descrizione")
  private String descrizione;

  @Column(name="note")
  private String note;

  @Column(name="data")
  private Date data;

  @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name="idcliente", nullable=false)
  private Cliente cliente;

  @Column(name="registratoDa")
  private String registratoDa;

  @PrePersist
  private void setCampi(){
    data = new Date();
    idPratica = data.toInstant().toString() + cliente.getIdCliente();
  }
}

I've saved some Cliente and Pratica objects using my Daos:
//******
    clienteDao.save(new Cliente("IDCLIENTE_1", "RAGIONESOCIALE_1", "NOMINATIVO_1", "INDIRIZZO_1", "TELEFONO_1", "EMAIL_1", "SITO_1", "SEGNALATORE_1", "ATTIVITA_1", "INTERESSATOA_1", null, "RGNLSN87H13D761R", null, "NOTE_1"));
    clienteDao.save(new Cliente("IDCLIENTE_2", "RAGIONESOCIALE_2", "NOMINATIVO_2", "INDIRIZZO_2", "TELEFONO_2", "EMAIL_2", "SITO_2", "SEGNALATORE_2", "ATTIVITA_2", "INTERESSATOA_2", null, "RGNLSN87H13D761R", null, "NOTE_2"));
    clienteDao.save(new Cliente("IDCLIENTE_3", "RAGIONESOCIALE_3", "NOMINATIVO_3", "INDIRIZZO_3", "TELEFONO_3", "EMAIL_3", "SITO_3", "SEGNALATORE_3", "ATTIVITA_3", "INTERESSATOA_3", null, "RGNLSN8UTED761R", null, "NOTE_3"));
//******
    praticaDao.save(new Pratica("IDPRATICA_1", "DESCRIZIONE_1", null, "NOTE_1", null, clienteDao.getOne("IDCLIENTE_1"), "RGNDCN8DUYD761R"));
    praticaDao.save(new Pratica("IDPRATICA_2", "DESCRIZIONE_2", null, "NOTE_2", null, clienteDao.getOne("IDCLIENTE_1"), "RGNLS32H13D761R"));

    praticaDao.save(new Pratica("IDPRATICA_3", "DESCRIZIONE_3", null, "NOTE_3", null, clienteDao.getOne("IDCLIENTE_2"), "RGNLKIU87H13D761R"));
    praticaDao.save(new Pratica("IDPRATICA_4", "DESCRIZIONE_4", null, "NOTE_4", null, clienteDao.getOne("IDCLIENTE_2"), "RGNTGH7H13D761R"));

    praticaDao.save(new Pratica("IDPRATICA_5", "DESCRIZIONE_5", null, "NOTE_5", null, clienteDao.getOne("IDCLIENTE_3"), "RGNLGTR13D761R"));
    praticaDao.save(new Pratica("IDPRATICA_6", "DESCRIZIONE_6", null, "NOTE_6", null, clienteDao.getOne("IDCLIENTE_3"), "RGNLSNHYDFR3D761R"));

But when I want to get the List or the List in JSON format I get the recursive relationship.
[{"idCliente":"IDCLIENTE_1","ragioneSociale":"RAGIONESOCIALE_1","nominativo":"NOMINATIVO_1","indirizzo":"INDIRIZZO_1","telefono":"TELEFONO_1","email":"EMAIL_1","sito":"SITO_1","segnalatore":"SEGNALATORE_1","attivita":"ATTIVITA_1","interessatoA":"INTERESSATOA_1","pratiche":[{"idPratica":"2018-03-21T21:27:05.582ZIDCLIENTE_1","descrizione":"DESCRIZIONE_1","documenti":[],"note":"NOTE_1","data":"2018-03-21T21:27:05.582+0000","cliente":{"idCliente":"IDCLIENTE_1","ragioneSociale":"RAGIONESOCIALE_1","nominativo":"NOMINATIVO_1","indirizzo":"INDIRIZZO_1","telefono":"TELEFONO_1","email":"EMAIL_1","sito":"SITO_1","segnalatore":"SEGNALATORE_1","attivita":"ATTIVITA_1","interessatoA":"INTERESSATOA_1","pratiche":[{"idPratica":"2018-03-21T21:27:05.582ZIDCLIENTE_1","descrizione":"DESCRIZIONE_1","documenti":[],"note":"NOTE_1","data":"2018-03-21T21:27:05.582+0000","cliente":{"idCliente":"IDCLIENTE_1","ragioneSociale":"RAGIONESOCIALE_1","nominativo":"NOMINATIVO_1","indirizzo":"INDIRIZZO_1","telefono":"TELEFONO_1","email":"EMAIL_1","sito":"SITO_1","segnalatore":"SEGNALATORE_1","attivita":"ATTIVITA_1","interessatoA":"INTERESSATOA_1","pratiche":[{"idPratica":"2018-03-21T21:27:05.582ZIDCLIENTE_1","descrizione":"DESCRIZIONE_1","documenti":[],"note":"NOTE_1","data":"2018-03-21T21:27:05.582+0000","cliente":{"idCliente":"IDCLIENTE_1","ragioneSociale":"RAGIONESOCIALE_1","nominativo":"NOMINATIVO_1","indirizzo":"INDIRIZZO_1","telefono":"TELEFONO_1","email":"EMAIL_1","sito":"SITO_1","segnalatore":"SEGNALATORE_1","attivita":"ATTIVITA_1","interessatoA":"INTERESSATOA_1","pratiche":[{"idPratica":"2018-03-21T21:27:05.582ZIDCLIENTE_1","descrizione":"DESCRIZIONE_1","documenti":[],"note":"NOTE_1","data":"2018-03-21T21:27:05.582+0000","cliente":{"idCliente":"IDCLIENTE_1","ragioneSociale":"RAGIONESOCIALE_1","nominativo":"NOMINATIVO_1","indirizzo":"INDIRIZZO_1","telefono":"TELEFONO_1","email":"EMAIL_1","sito":"SITO_1","segnalatore":"SEGNALATORE_1","attivita":"ATTIVITA_1","interessatoA":"INTERESSATOA_1","pratiche":[{"idPratica":"2018-03-21T21:27:05.582ZIDCLIENTE_1","descrizione":"DESCRIZIONE_1","documenti":[],"note":"NOTE_1","data":"2018-03-21T21:27:05.582+0000","cliente":{"idCliente":"IDCLIENTE_1","ragioneSociale":"RAGIONESOCIALE_1","nominativo":"NOMINATIVO_1","indirizzo":"INDIRIZZO_1","telefono":"TELEFONO_1","email":"EMAIL_1","sito":"SITO_1","segnalatore":"SEGNALATORE_1","attivita":"ATTIVITA_1","interessatoA":"INTERESSATOA_1","pratiche":[{"idPratica":"2018-03-...

Is there an error in the annotations or is it something normal using @OneToMany and @ManyToOne and there is a way to get a best JSON which represents better the table?

A: Thanks to S.Y. Wang it is a duplicate of Infinite Recursion with Jackson JSON and Hibernate JPA issue

So the way to solve this recursion is to use the two annotations:
@JsonManagedReference

close to @OneToMany annotation in the parent object and
@JsonBackReference

close to @ManyToOne annotation in the child object to block recursion while using JacksonLibrary.


text:
Q: FFmpeg get duration of video file without meta data I got a video file which has no meta data.
If I do this for example:
ffmpeg -i test.m2v

I get these values:
Duration: N/A, bitrate: N/A

Is there still a way to get the duration of the video / .m2v file ?
Edit:
The full console output:
ffmpeg version 2.8.4 Copyright (c) 2000-2015 the FFmpeg developers
  built with gcc 5.2.0 (GCC)
  configuration: --enable-gpl --enable-version3 --disable-w32threads --enable-avisynth --enable-bzlib --enable-fontconfig --enable-frei0r --enable-gnutls --enable-iconv --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libdcadec --enable-libfr
eetype --enable-libgme --enable-libgsm --enable-libilbc --enable-libmodplug --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-librtmp --enable-libschroedinger --enable-libsoxr --enable-libspeex --enab
le-libtheora --enable-libtwolame --enable-libvidstab --enable-libvo-aacenc --enable-libvo-amrwbenc --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxavs --enable-libxvid --enable-lzma --enable-decklink
--enable-zlib
  libavutil      54. 31.100 / 54. 31.100
  libavcodec     56. 60.100 / 56. 60.100
  libavformat    56. 40.101 / 56. 40.101
  libavdevice    56.  4.100 / 56.  4.100
  libavfilter     5. 40.101 /  5. 40.101
  libswscale      3.  1.101 /  3.  1.101
  libswresample   1.  2.101 /  1.  2.101
  libpostproc    53.  3.100 / 53.  3.100
Input #0, mpegvideo, from '.\Test.m2v':
  Duration: N/A, bitrate: N/A
    Stream #0:0: Video: mpeg2video (Main), yuv420p(tv), 720x576 [SAR 64:45 DAR 16:9], max. 7000 kb/s, 25 fps, 25 tbr, 1200k tbn, 50 tbc

A: For a raw bitstream, ffprobe can be used.
ffprobe -show_entries stream=r_frame_rate,nb_read_frames -select_streams v -count_frames -of compact=p=0:nk=1 -v 0 in.m2v

This produces
30/1|120

where first entry is the frame rate as a rational number, and second is the number of frames counted. Duration is 120 / (30/1) = 4.00s

A: If you don't have metadata, then you need to build those metadata by reading and parsing the whole file (this is what ffprobe does), and get a correct answer based on the file's actual content.
There is no more accurate answer. There is, however, a faster answer. As noticed, "if you open such videos in VLC, it shows you the duration of the video immediately". In several places, VLC (and other tools too) appear to make an estimate, instead of reading in and parsing the whole file (which you might be unable or unwilling to do):
/* try to calculate movie time */
if( p_sys->p_fp->i_data_packets_count > 0 )
{
    uint64_t i_count;
    uint64_t i_size = stream_Size( p_demux->s );

    if( p_sys->i_data_end > 0 && i_size > p_sys->i_data_end )
    {
        i_size = p_sys->i_data_end;
    }

    /* real number of packets */
    i_count = ( i_size - p_sys->i_data_begin ) /
              p_sys->p_fp->i_min_data_packet_size;

    /* calculate the time duration in micro-s */
    p_sys->i_length = VLC_TICK_FROM_MSFTIME(p_sys->p_fp->i_play_duration) *
               (vlc_tick_t)i_count /
               (vlc_tick_t)p_sys->p_fp->i_data_packets_count;
    if( p_sys->i_length <= p_sys->p_fp->i_preroll )
        p_sys->i_length = 0;
    else
    {
        p_sys->i_length  -= p_sys->p_fp->i_preroll;
        p_sys->i_bitrate = 8 * i_size * CLOCK_FREQ / p_sys->i_length;
    }
}

In this case,
Stream #0:0: Video: mpeg2video (Main), yuv420p(tv), 720x576 [SAR 64:45 DAR 16:9], max. 7000 kb/s, 25 fps, 25 tbr, 1200k tbn, 50 tbc
knowing that the stream speed is 7000 kb/s and the file size, dividing the file size by 7000 kbit and multiplying by 8 immediately gives the likely duration in seconds.
For example with a file I have here (actual file duration 02:32:19, file size 733,802,496)
Stream #0:0: Video: ... 562 kb/s, 25 fps ...
Stream #0:1: Audio: ... 54 kb/s

562+54 is 616 kbits, which is 77 kbytes. 733,802,496 divided by (77*1024) is 9306, and 9306 seconds are 2 hours, 35 minutes, 6 seconds, which is not exactly correct, but pretty close.
Depending on the actual codec used, the audio/video interleaving method, any padding for the same, and whether it's CBR or VBR, the actual accuracy might vary.
Lacking reliable metadata, if you value speed over accuracy, then I fear that estimate is the way to go.
In some scenarios you might be able to do both (provide an immediate estimate based on file header and size, then start reading whenever the UI/program has nothing better to do and refine the answer. You might then even save the newly calculated metadata somewhere, to retrieve them if needed later on - in a database, a thumbnail file, an alternate data stream, or even offer to update/"repair" the video file if feasible).
Command-line
From the command line, using ffmpeg:
 #!/bin/bash

 if [ ! -r "$1" ]; then
     echo "File '$1' not found"
     exit 1
 fi
 FILESIZE=$( stat -c "%s" "$1" )
 STREAMS=$(
      ffmpeg -i "$1" 2>&1 \
      | grep 'Stream #' \
      | tr "," "\n" \
      | grep "kb/s" \
      | tr " " "\n" \
      | grep "^[1-9][0-9]*$" )
 RATE=0
 for r in $STREAMS; do
     RATE=$[ $RATE + $r ]
 done
 # I don't think that bash has decimal support, so we use bc
 SECONDS=$( echo "$FILESIZE / $RATE" | bc )
 # To get seconds in HH:MM:SS format we use 'date'
 DURATION=$( TZ=UTC date +"%H:%M:%S" -d @$SECONDS )

This should be accurate even if you have multiple audio streams in  a video file. I am not sure what happens if there is some data stream such as subtitles. The size of such a stream shouldn't be much, so it shouldn't interfere, but then again, it might.


text:
Q: Table cannot be created I have written this code, but still table can not be created in database. And just output is:

"database created.... Sorry Table Not Created".

<?php
    include 'connection.php';
    //Creating database
    $creatingdatabase = "CREATE DATABASE IF NOT EXISTS quest";
    $query1 = mysqli_query($con, $creatingdatabase);
    if($query1){

        echo "database created....";
        //creating tables
        $creatingtable = "CREATE TABLE quiz (
                        id INT(6) AUTO_INCREMENT PRIMARY KEY,
                        questions VARCHAR(255) NOT NULL,
                        optiona VARCHAR(255) NOT NULL,
                        optionb VARCHAR(255) NOT NULL,
                        optionc VARCHAR(255) NOT NULL,
                        optiond VARCHAR(255) NOT NULL,
                        answer VARCHAR(50) NOT NULL
                                                )";
        $query2 = mysqli_query($con, $creatingtable);
        if($query2){echo "table created...";}
        else { echo "sorry... table not created"; }

    }
    else { echo "database can not be created"; }
?>

A: <?php
$servername = 'localhost';
$username = 'root';
$password = 'xxxxx';

$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE guest"; //Set name database here
if ($conn->query($sql) === TRUE) {
    $conn =  mysqli_connect($servername, $username, $password,'guest');//Set name database here
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    $query = "CREATE TABLE quiz (
        id INT(6) AUTO_INCREMENT PRIMARY KEY,
        questions VARCHAR(255) NOT NULL,
        optiona VARCHAR(255) NOT NULL,
        optionb VARCHAR(255) NOT NULL,
        optionc VARCHAR(255) NOT NULL,
        optiond VARCHAR(255) NOT NULL,
        answer VARCHAR(50) NOT NULL
    )";
    if ($conn->query($query) === TRUE) {
        echo "Table users created successfully";
    } else {
        echo "Error creating table: " . $conn->error;
    }
} else {
    echo "Error creating database: " . $conn->error;
}

$conn->close();
?>

But I'm not recommend user can create new database in your sql server.

In terms of security, it's probably best to have a database already created and then simply add in the user data, even if it's the first record. Nothing is gained from a user being able to enter data into a web form and then indirectly running SQL code.

A: The CREATE TABLE statement needs to specify the database to use, or you need to set the default database with mysqli_select_db().
$creatingdatabase = "CREATE DATABASE IF NOT EXISTS quest";
$query1 = mysqli_query($con, $creatingdatabase);
mysqli_select_db($con, "quest");


text:
Q: Where to find MSOffice 2013 installer? Wine 2.0 After viewing this how to install office 2013 question I am lost on where to find the Office2013Setup.x86.exe file, to install office 2013, (last step). I've dug around microsoft's download pages to no avail.
Looking for a source to dl this .exe or for someone to tell me what I'm not understanding.


text:
Q: linking font files in the css does not work in firefox (but works in every other browser) I have the following code:
#entrance {
    margin: 20% auto auto auto;
    text-align: center;
    font-family: 'Baron Neue';
    src: url('fonts/baron.otf');
}

This allows the text to be rendered in the desired font in chrome, ie, safari, and opera, but not firefox.  All I get is times new roman.

A: Use the @font-face property.
@font-face {
   font-family: Baron Neue;
   src: local('Baron Neue'),
   url('fonts/baron.otf');
   font-weight: 400;
}

see http://sixrevisions.com/css/font-face-guide/