text:
Q: How to increase load performance of referenced dll's on startup? I have an windows forms application on .NET 4 framework and using Devexpress components. In first run of my application it wait 20 or 30 seconds for loading assemblies. After that it runs like a rocket :) How can I solve this? I googled some and found NGEN.exe. I don't have any idea NGEN is usable or not. Is there any another simple way for increase load assembly speed? What do you prefer?

A: You have a cold start problem.  Cold start times are dominated by the disk drive, locating the assemblies on disk.  A warm start is fast, the assemblies are present in the file system cache so don't have to be located on the slow disk.
Using ngen.exe makes cold starts worse, it requires another file to be found.  The reason that Microsoft recommends that you only ever use ngen.exe on large assemblies.  Jitting can actually be faster than finding the ngen image file.
There's not that much you can do about slow cold starts, it is a pure hardware problem and you need a faster disk to truly get ahead.  Making sure it is defragged well certainly helps.  An SSD is very nice.  You could use ILMerge.exe to reduce the number of DLLs that need to be found.  It is a problem that tends to solve itself over time if the user starts the program often enough after machine startup.  Windows learns the usage pattern and prefetches executables so they'll be in the file system cache when needed.  A feature called SuperFetch.
Fwiw, slow cold starts are not exclusive to .NET programs, unmanaged programs that use lots of DLLs have this problem too.  Office and Adobe Reader are common examples.  They cheat, they install an "optimizer" that runs at login.  All it does is get those DLLs into the file system cache.  Very annoying.  You could do this too, of course I can't recommend that.

A: If you are running your WinForms project set to "Any CPU", try building it as x86 (or prefer 32-bit) instead and see if that makes a difference.
I specifically had an issue with the .NET 4.5.1 JIT compiler taking way too long to compile a couple of DevExpress WinForms dlls as 64-bit. Switching to 32-bit allowed our heaviest form to cold-start load in 3 seconds, whereas before it was taking 35 seconds.
Interestingly enough turning off the JIT optimization also helped, as apparently the 64-bit optimization was very slow. I noticed that our Release mode builds were running far slower than our Debug builds. As an easy test you can put a simple <App Executable Name>.ini in your application folder to turn off JIT optimization and see if makes a difference:
[.NET Framework Debugging Control]
GenerateTrackingInfo=1
AllowOptimize=0

If any DevExpress support staff are reading this post and for posterity sake, here was my NGen output when pre-compiling with some DevExpress 14.1.3.0 dlls as 64-bit. I ended up not using NGen, but it threw some strange errors which you may find useful.
E:\Applications\Pryme>C:\Windows\Microsoft.NET\Framework\v4.0.30319\ngen.exe install Pryme.exe
Microsoft (R) CLR Native Image Generator - Version 4.0.30319.18408
Copyright (c) Microsoft Corporation.  All rights reserved.
Failed to load dependency DevExpress.XtraMap.v14.1 of assembly DevExpress.Dashboard.v14.1.Win, Version=14.1.3.0, Culture
=neutral, PublicKeyToken=b88d1754d700e49a because of the following error : The system cannot find the file specified. (E
xception from HRESULT: 0x80070002)
Failed to load dependency DevExpress.Map.v14.1.Core of assembly DevExpress.Dashboard.v14.1.Core, Version=14.1.3.0, Cultu
re=neutral, PublicKeyToken=b88d1754d700e49a because of the following error : The system cannot find the file specified.
(Exception from HRESULT: 0x80070002)
Failed to load dependency DevExpress.XtraMap.v14.1 of assembly DevExpress.Dashboard.v14.1.Core, Version=14.1.3.0, Cultur
e=neutral, PublicKeyToken=b88d1754d700e49a because of the following error : The system cannot find the file specified. (
Exception from HRESULT: 0x80070002)
Failed to load dependency DevExpress.XtraCharts.v14.1.Extensions of assembly DevExpress.XtraReports.v14.1.Extensions, Ve
rsion=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a because of the following error : The system cannot find
 the file specified. (Exception from HRESULT: 0x80070002)
3>    Compiling assembly DevExpress.SpellChecker.v14.1.Core, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d
700e49a (CLR v4.0.30319) ...
2>    Compiling assembly DevExpress.XtraSpellChecker.v14.1, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d7
00e49a (CLR v4.0.30319) ...
4>    Compiling assembly DevExpress.Data.v14.1, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a (CLR
v4.0.30319) ...
1>    Compiling assembly E:\Applications\Pryme\Pryme.exe (CLR v4.0.30319) ...
2>    Compiling assembly DevExpress.Utils.v14.1, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a (CLR
 v4.0.30319) ...
3>    Compiling assembly DevExpress.Printing.v14.1.Core, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e
49a (CLR v4.0.30319) ...
4>Cannot embed generic MethodDesc while compiling method PropVariant.GetVector
2>    Compiling assembly DevExpress.XtraEditors.v14.1, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49
a (CLR v4.0.30319) ...
4>Cannot embed generic MethodDesc while compiling method PropVariant.GetVector
4>Cannot embed generic MethodDesc while compiling method PropVariant.GetVector
4>Cannot embed generic MethodDesc while compiling method PropVariant.GetVector
4>Cannot embed generic MethodDesc while compiling method PropVariant.GetVector
4>Cannot embed generic MethodDesc while compiling method PropVariant.GetVector
4>Cannot embed generic MethodDesc while compiling method PropVariant.GetVector
4>Cannot embed generic MethodDesc while compiling method PropVariant.GetVector
4>Cannot embed generic MethodDesc while compiling method PropVariant.GetVector
4>Cannot embed generic MethodDesc while compiling method PropVariant.GetVector
4>Cannot embed generic MethodDesc while compiling method PropVariant.GetVector
4>Cannot embed generic MethodDesc while compiling method PropVariant.GetVector
4>Cannot embed generic MethodDesc while compiling method PropVariant.GetVector
3>    Compiling assembly DevExpress.Sparkline.v14.1.Core, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700
e49a (CLR v4.0.30319) ...
3>    Compiling assembly Merydyan.Pryme.SI, Version=3.0.18.34925, Culture=neutral, PublicKeyToken=null (CLR v4.0.30319)
...
4>    Compiling assembly Merydyan.Pryme.Core, Version=3.0.18.34915, Culture=neutral, PublicKeyToken=null (CLR v4.0.30319
) ...
3>    Compiling assembly NodaTime, Version=1.2.0.0, Culture=neutral, PublicKeyToken=4226afe0d9b296d1 (CLR v4.0.30319) ..
.
4>    Compiling assembly AutoMapper, Version=3.2.1.0, Culture=neutral, PublicKeyToken=be96cd2c38ef1005 (CLR v4.0.30319)
...
3>    Compiling assembly Autofac, Version=3.5.0.0, Culture=neutral, PublicKeyToken=17863af14b0044da (CLR v4.0.30319) ...

4>    Compiling assembly EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 (CLR v4.0.30
319) ...
3>    Compiling assembly Merydyan.Pryme.Data, Version=3.0.18.34919, Culture=neutral, PublicKeyToken=null (CLR v4.0.30319
) ...
2>    Compiling assembly EntityFramework.Extended, Version=6.0.0.0, Culture=neutral, PublicKeyToken=05b7e29bdd433584 (CL
R v4.0.30319) ...
1>    Compiling assembly Merydyan.Pryme.Services, Version=3.0.18.34923, Culture=neutral, PublicKeyToken=null (CLR v4.0.3
0319) ...
2>    Compiling assembly Humanizer, Version=1.28.0.0, Culture=neutral, PublicKeyToken=979442b78dfc278e (CLR v4.0.30319)
...
3>    Compiling assembly DevExpress.XtraReports.v14.1, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49
a (CLR v4.0.30319) ...
2>    Compiling assembly DevExpress.Office.v14.1.Core, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49
a (CLR v4.0.30319) ...
1>    Compiling assembly DevExpress.XtraCharts.v14.1, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a
 (CLR v4.0.30319) ...
2>    Compiling assembly DevExpress.Charts.v14.1.Core, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49
a (CLR v4.0.30319) ...
3>    Compiling assembly DevExpress.PivotGrid.v14.1.Core, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700
e49a (CLR v4.0.30319) ...
2>    Compiling assembly DevExpress.RichEdit.v14.1.Core, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e
49a (CLR v4.0.30319) ...
1>    Compiling assembly DevExpress.XtraGauges.v14.1.Core, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d70
0e49a (CLR v4.0.30319) ...
3>    Compiling assembly DevExpress.XtraGrid.v14.1, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a (
CLR v4.0.30319) ...
1>    Compiling assembly DevExpress.XtraLayout.v14.1, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a
 (CLR v4.0.30319) ...
1>    Compiling assembly DevExpress.XtraPrinting.v14.1, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e4
9a (CLR v4.0.30319) ...
4>    Compiling assembly DevExpress.XtraBars.v14.1, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a (
CLR v4.0.30319) ...
1>    Compiling assembly DevExpress.XtraTreeList.v14.1, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e4
9a (CLR v4.0.30319) ...
3>    Compiling assembly DevExpress.XtraScheduler.v14.1, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e
49a (CLR v4.0.30319) ...
4>Cannot embed generic MethodDesc while compiling method MouseEventSubscriber`1.PreFilterMessage
1>    Compiling assembly DevExpress.XtraScheduler.v14.1.Core, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754
d700e49a (CLR v4.0.30319) ...
3>    Compiling assembly DevExpress.XtraScheduler.v14.1.Extensions, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b8
8d1754d700e49a (CLR v4.0.30319) ...
3>    Compiling assembly DevExpress.XtraWizard.v14.1, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a
 (CLR v4.0.30319) ...
1>    Compiling assembly DevExpress.Dashboard.v14.1.Win, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e
49a (CLR v4.0.30319) ...
3>    Compiling assembly DevExpress.Dashboard.v14.1.Core, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700
e49a (CLR v4.0.30319) ...
3>Warning: System.IO.FileNotFoundException: Could not load file or assembly 'DevExpress.XtraMap.v14.1, Version=14.1.3.0,
 Culture=neutral, PublicKeyToken=b88d1754d700e49a' or one of its dependencies. The system cannot find the file specified
.. If this assembly is found during runtime of an application, then the native image currently being generated will not
be used.
3>Warning: System.IO.FileNotFoundException: Could not load file or assembly 'DevExpress.Map.v14.1.Core, Version=14.1.3.0
, Culture=neutral, PublicKeyToken=b88d1754d700e49a' or one of its dependencies. The system cannot find the file specifie
d.. If this assembly is found during runtime of an application, then the native image currently being generated will not
 be used.
1>Warning: System.IO.FileNotFoundException: Could not load file or assembly 'DevExpress.XtraMap.v14.1, Version=14.1.3.0,
 Culture=neutral, PublicKeyToken=b88d1754d700e49a' or one of its dependencies. The system cannot find the file specified
.. If this assembly is found during runtime of an application, then the native image currently being generated will not
be used.
1>Warning: System.IO.FileNotFoundException: Could not load file or assembly 'DevExpress.Map.v14.1.Core, Version=14.1.3.0
, Culture=neutral, PublicKeyToken=b88d1754d700e49a' or one of its dependencies. The system cannot find the file specifie
d.. If this assembly is found during runtime of an application, then the native image currently being generated will not
 be used.
3>Warning: System.IO.FileNotFoundException: Could not load file or assembly 'DevExpress.XtraMap.v14.1, Version=14.1.3.0,
 Culture=neutral, PublicKeyToken=b88d1754d700e49a' or one of its dependencies. The system cannot find the file specified
. (Exception from HRESULT: 0x80070002). If this assembly is found during runtime of an application, then the native imag
e currently being generated will not be used.
3>Warning: System.IO.FileNotFoundException: Could not load file or assembly 'DevExpress.Map.v14.1.Core, Version=14.1.3.0
, Culture=neutral, PublicKeyToken=b88d1754d700e49a' or one of its dependencies. The system cannot find the file specifie
d. (Exception from HRESULT: 0x80070002). If this assembly is found during runtime of an application, then the native ima
ge currently being generated will not be used.
1>Warning: System.IO.FileNotFoundException: Could not load file or assembly 'DevExpress.XtraMap.v14.1, Version=14.1.3.0,
 Culture=neutral, PublicKeyToken=b88d1754d700e49a' or one of its dependencies. The system cannot find the file specified
. (Exception from HRESULT: 0x80070002). If this assembly is found during runtime of an application, then the native imag
e currently being generated will not be used.
4>Cannot embed generic MethodDesc while compiling method MouseEventSubscriber`1.PreFilterMessage
4>    Compiling assembly DevExpress.DataAccess.v14.1, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a
 (CLR v4.0.30319) ...
1>    Compiling assembly DevExpress.Xpo.v14.1, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a (CLR v
4.0.30319) ...
3>    Compiling assembly DevExpress.XtraGauges.v14.1.Win, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700
e49a (CLR v4.0.30319) ...
4>    Compiling assembly DevExpress.XtraGauges.v14.1.Presets, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754
d700e49a (CLR v4.0.30319) ...
2>    Compiling assembly DevExpress.XtraCharts.v14.1.Wizard, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d
700e49a (CLR v4.0.30319) ...
3>Cannot embed generic MethodDesc while compiling method GaugeDataBindingPage`1.OnSelectedItemChanged
3>Cannot embed generic MethodDesc while compiling method GaugeDataBindingPage`1.OnSelectedItemChanged
3>    Compiling assembly DevExpress.Utils.v14.1.UI, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a (
CLR v4.0.30319) ...
4>    Compiling assembly DevExpress.XtraRichEdit.v14.1, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e4
9a (CLR v4.0.30319) ...
3>    Compiling assembly DevExpress.XtraVerticalGrid.v14.1, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d7
00e49a (CLR v4.0.30319) ...
2>    Compiling assembly DevExpress.XtraNavBar.v14.1, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a
 (CLR v4.0.30319) ...
3>    Compiling assembly DevExpress.XtraCharts.v14.1.UI, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e
49a (CLR v4.0.30319) ...
1>    Compiling assembly DevExpress.DataAccess.v14.1.UI, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e
49a (CLR v4.0.30319) ...
3>    Compiling assembly DevExpress.CodeParser.v14.1, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a
 (CLR v4.0.30319) ...
2>    Compiling assembly DevExpress.XtraPivotGrid.v14.1, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e
49a (CLR v4.0.30319) ...
4>    Compiling assembly DevExpress.XtraRichEdit.v14.1.Extensions, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88
d1754d700e49a (CLR v4.0.30319) ...
1>    Compiling assembly DevExpress.XtraPdfViewer.v14.1, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e
49a (CLR v4.0.30319) ...
1>    Compiling assembly DevExpress.Pdf.v14.1.Core, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a (
CLR v4.0.30319) ...
4>    Compiling assembly DevExpress.Pdf.v14.1.Drawing, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49
a (CLR v4.0.30319) ...
2>    Compiling assembly DevExpress.XtraReports.v14.1.Extensions, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d
1754d700e49a (CLR v4.0.30319) ...
4>    Compiling assembly WebCam_Capture, Version=1.0.2395.24959, Culture=neutral, PublicKeyToken=null (CLR v4.0.30319) .
..
2>Warning: System.IO.FileNotFoundException: Could not load file or assembly 'DevExpress.XtraCharts.v14.1.Extensions, Ver
sion=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a' or one of its dependencies. The system cannot find the
file specified.. If this assembly is found during runtime of an application, then the native image currently being gener
ated will not be used.
4>    Compiling assembly DevExpress.XtraScheduler.v14.1.Reporting, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88
d1754d700e49a (CLR v4.0.30319) ...
4>    Compiling assembly DevExpress.Xpf.Core.v14.1, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a (
CLR v4.0.30319) ...
2>Warning: System.IO.FileNotFoundException: Could not load file or assembly 'DevExpress.XtraCharts.v14.1.Extensions, Ver
sion=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a' or one of its dependencies. The system cannot find the
file specified. (Exception from HRESULT: 0x80070002). If this assembly is found during runtime of an application, then t
he native image currently being generated will not be used.
3>    Compiling assembly DevExpress.Mvvm.v14.1, Version=14.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a (CLR
v4.0.30319) ...
1>    Compiling assembly Merydyan.Pryme.UI.Windows, Version=3.0.18.34928, Culture=neutral, PublicKeyToken=null (CLR v4.0
.30319) ...

E:\Applications\Pryme>C:\Windows\Microsoft.NET\Framework\v4.0.30319\ngen.exe install Pryme.exe

A: Maybe automatically run a stub of the program after install? That is, automatically load the program with a switch that exits silently as the last step in your install. Most people expect installs to take a few seconds/minutes so most people wont even notice.
UPDATE:
I checked the MSDN C# documentation and it says assemblies are loaded on demand (as needed) but you can force them to load explicitly using the Assembly.ReflectionOnlyLoadFrom method. If you preload your assemblies (and optionally the dependencies) while the user is entering login info then you'll effectively hide the loading delay.


text:
Q: Dissolve features according to an order set by a field I want to dissolve overlapping feature according to a specified order using an attribute field. For instance if I have three overlapping features, like the image below, I'd want to keep the purple feature, then the red one and then what's left the remaining feature

Dissolving would look like this.

I would need to do this with thousands of features so editing manually is not an option.

A: You can use "Control feature rendering order" option under "Layer Rendering" in "Layer Style" panel.

Open Define Order window by clicking AZ button. Add field name (Type here) and values (1: purple, 2: red, 3: green).

Before:

After:

A: There is actually a solution to this problem that does not require a script. It requires multiple processing steps, but you could chain these tools together in a graphical model.
I'm using QGIS, but I believe this could be done in ArcMap in a similar fashion (though perhaps using different tools).
Say you have three features in a single layer that overlap like so:

Step 1: Reassign the primary key column (in my case ID) for the layer so it reflects the order in which you'd like the overlaps retained. So the feature with ID = 1 will be left completely intact, feature 2 will be prioritized over feature 3, feature 3 over feature 4, and so on.
Step 2: Run Union, setting the layer as the only input (leaving the Overlay layer empty). This will perform a Union between the layer and itself, resulting in (in my case) 12 features.

Result:

Step 3: Run Delete Duplicate Geometries on the output from Step 2. This reduced the number of features to 7.

Step 4: Run Join Attributes by Location, setting the Base Layer to the output from Step 3, the Join Layer to the original layer from Step 1, the Geometric predicate to "within", and the Join type to "Take attributes from the first matching feature only (one-to-one)". This is where the magic happens, since the first matching feature in each case is determined from the order of the primary key.

Step 5: Finally, run Dissolve, setting the Dissolve field to "ID_2", which is the ID of the original features that were joined in Step 4.
Final result:

redpajama_set_name: RedPajamaStackExchange


text:
Q: GNU Make - terminal rules and keyword "null" BACKGROUND
This is related to my question GNU make - transform every prerequisite into target (implicitly)
I've posted this question because it's interesting and may be useful by itself - to understand make - and I don't want it to get lost in the "original" question.
INFO
I have a file Dummy.mk:
%:: null
    @:

null:
    @:

which I pass to my make as make all MAKEFILES=Dummy.mk.
When I replace null with saflkjsaflkjdsa,
%:: saflkjsaflkjdsa
    @:

saflkjsaflkjdsa:
    @:

the behavior of the build was different: the rule was never executed.
The reason is because this is a "terminal rule":

One choice is to mark the match-anything rule as terminal by defining
  it with a double colon. When a rule is terminal, it does not apply
  unless its prerequisites actually exist. Prerequisites that could be
  made with other implicit rules are not good enough. In other words, no
  further chaining is allowed beyond a terminal rule.

Since saflkjsaflkjdsa did not exist, the rule was not executed. Ok fine I understand that.
But when I set Dummy.mk using the keyword null
%:: null
    @:

null:
    @:

the %:: rule does execute i.e. it captures ALL targets, filenames, etc giving me outputs of the form :2: update target <item> due to: null where <item> is any filename or target that make reads in.
Since the rule is executing using null but not with using saflkjsaflkjdsa, make is definitely detecting null as "existing".
QUESTION
But then why do I still get the output :5: target 'null' does not exist?
Is that because of the OS- or shell-level peculiarities of null existing but not existing at the same time?
Environment
* Windows 8, 64-bit
* Make 4.2.1 (here's output of make
# GNU Make 4.2.1
# Built for Windows32
# Copyright (C) 1988-2016 Free Software Foundation, Inc.
# License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
# This is free software: you are free to change and redistribute it.
# There is NO WARRANTY, to the extent permitted by law.
find_and_set_shell() path search set default_shell = C:/Users/User1/Desktop/A/QNX_SDK/host/win32/x86/usr/bin/sh.exe
...

* Shell that make is using internally is:
C:\Users\User1\Desktop\A\Project\bld\armle-v7\release\subProj>where sh
C:/Users/User1/Desktop/A/QNX_SDK/host/win32/x86/usr/bin/sh.exe

C:\Users\User1\Desktop\A\Project\bld\armle-v7\release\subProj>sh --help
GNU bash, version 3.1.17(1)-release-(i686-pc-msys)
Usage:  sh [GNU long option] [option] ...
        sh [GNU long option] [option] script-file ...
GNU long options:
        --debug
        --debugger
        --dump-po-strings
        --dump-strings
        --help
        --init-file
        --login
        --noediting
        --noprofile
        --norc
        --posix
        --protected
        --rcfile
        --restricted
        --verbose
        --version
        --wordexp
Shell options:
        -irsD or -c command or -O shopt_option          (invocation only)
        -abefhkmnptuvxBCHP or -o option
Type `sh -c "help set"' for more information about shell options.
Type `sh -c help' for more information about shell builtin commands.
Use the `bashbug' command to report bugs.

A:
Is that because of the OS- or shell-level peculiarities of null existing but not existing at the same time?

Since you didn't specify which OS or shell you're using, it's impossible for us to say.  All I can say is that I tried to replicate your problem on my GNU/Linux system and couldn't: on my system no targets were built in either case (using null or saflkjsaflkjdsa made no difference)
My suspicion is you're using Windows; I have a vague recollection that null is special somehow on Windows.  But, I don't do Windows so I can't say for sure.


text:
Q: Wordpress - Display Limited Post From A Specific Category In wordpress i need to display post on home page from a specific category.

*

*Need Five Post With Title

*Category Is News

*Display On Main home page

i use plugin business news but when i activate this plugin nex gen gallery plugin will be conflict now i dont know how to resolve this please suggest.

A: Following is the code to display post of a specific category. To display on home page, you will have to make following changes in your index.php file.
$query = new WP_Query( array('category_name'=>'news', 'posts_per_page'=> '5') );
  if ( $query->have_posts() ) :
       while ( $query->have_posts() ) : $query->the_post();
             get_template_part( 'content', get_post_format() );
       endwhile;
  endif;


text:
Q: How to link JRE.framework in swift framework I create a swift framework with objectiveC code which are translated by j2objc.
I have add java files to compile source, and use the following setting:
GENERATED_FILES_DIR = "${SRCROOT}/Generated";
HEADER_SEARCH_PATHS = "${J2OBJC_HOME}/frameworks/JRE.framework/Headers" "${GENERATED_FILES_DIR}" "${J2OBJC_HOME}/include" $(inherited);
LIBRARY_SEARCH_PATHS = ${J2OBJC_HOME}/lib;
OTHER_LDFLAGS = -ljre_emul
CLANG_ENABLE_OBJC_ARC = NO
and I got error:
include "J2ObjC_header.h"  >> Include of non-modular header inside framework module 'XXXXX'
Then  i do the following:
CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES = YES
The error still exist.
I link 'JRE.framework' and  set the   HEADER_SEARCH_PATHS
The error still exist.
How to fix it?

A: You also want to set DEFINES_MODULE = NO;
Besides that, you don't need the "${J2OBJC_HOME}/include" in HEADER_SEARCH_PATHS and you can also remove LIBRARY_SEARCH_PATHS = ${J2OBJC_HOME}/lib; OTHER_LDFLAGS = -ljre_emul; since you are using the JRE framework now.
If you are translating the .java sources without the --no-package-directories flag and you want to preserve the directory structure, then you also want to do following:

*

*Add the generated files as a folder references in Xcode

*Remove them from Copy Bundle Resources phase

*Drop the folders in Public section of the Headers phase

*Add new Run Scrip phase to remove the .m files from Headers directory:
find "$TARGET_BUILD_DIR/$PUBLIC_HEADERS_FOLDER_PATH" -name "*.m" -exec rm -f {} \;

*Now you can reference them in your umbrella header using #include <your-framework-name/path/to/header/Header.h>


text:
Q: Execute externall compiled program in Python I would like to execute an external compiled program in Python. In shell,
./bin/myProgram ./dir1/arg1 ./dir/arg2 arg3 arg3 arg4

And my Python script looks like:
import subprocess
subprocess.call(["./Users/Solar/Desktop/parent/child1/child2/bin/myProgram",
                 "/Users/Solar/Desktop/parent/child1/child2/dir1/arg1",
                 "/Users/Solar/Desktop/parent/child1/child2/dir1/arg2",
                 "arg3", "arg4", "arg5"])

But I get this error:
Traceback (most recent call last):
  File "/Users/Solar/Desktop/test.py", line 5, in <module>
    "32", "0.06", "15"])
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 522, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

Process finished with exit code 1

Could you help me? Thank you in advance!!

A: when subprocess.Popen issues
OSError: [Errno 2] No such file or directory

that's only because the executable cannot be found (if one of the file-arguments was not found it's the sub-process which reports the error, and no exception is thrown)
In your case ./Users/... is not likely to be valid considering that /Users/ is valid (root against current dir) so that's your problem.
"./Users/Solar/Desktop/parent/child1/child2/bin/myProgram" should be "/Users/Solar/Desktop/parent/child1/child2/bin/myProgram"
Note: better coding could have avoided the error:
import subprocess
root = "/Users/Solar/Desktop/parent/child1/child2"
subprocess.call([os.path.join(root,"bin/myProgram"),
                 os.path.join(root,"dir1/arg1"),
                 os.path.join(root,"dir1/arg2"),
                 "arg3", "arg4", "arg5"])

A: It's solved, I just had to execute
subprocess.call(["/Users/Solar/Desktop/parent/child1/child2/bin/myProgram",
                 "/Users/Solar/Desktop/parent/child1/child2/dir1/arg1",

...

Instead of
subprocess.call(["./Users/Solar/Desktop/parent/child1/child2/bin/myProgram",
                 "/Users/Solar/Desktop/parent/child1/child2/dir1/arg1",
...

Thank you people!!


text:
Q: Folding a rectangular paper such that one corner moves along an opposite side
A rectangular paper is folded such that one corner moves along the opposite side. Prove that all the creases formed are tangent to a parabola.

Attempt:
Let the paper be oriented such that its in the first quadrant and has one corner as the origin and sides along the axis.
After folding like so:

Let one side of the paper be $a$.
The equation of the crease is $$y=(x-h)\tan\theta$$
Also, in $\Delta LOH$,
$$\cos(\pi-2\theta)=-\cos(2\theta)=\frac{h}{a-h}$$
$$-\frac{1-\tan^2\theta}{1+\tan^2\theta}=\frac{h}{a-h}$$
Substituting the value of $\tan\theta$ from equation of crease,
$$ah^2+2(y^2-ax)h+a(x^2-y^2)=0$$
I am not getting anywhere close to proving the statement given.

A:
This is a basic question to be solved using Mathematical Origami,
  which was initially developed to serve as a tangible key to
  mathematical comprehension of geometry shapes.

Let $L_1$ be the line forming the bottom edge of our paper. Let $P_1$ be a point towards the middle, fairly close to $L_1$, and $P_2$ be a point on the left or right edge of our paper. Fold the paper and call the creased line $L_2$.

From the point $P_1$ construct a line which is $\perp$ to the folded portion of $L_1$. Let $X$ be the point where this line intersects $L_2$.

By opening our paper, we observe that the line segment $XP_1$ and the line segment from $X$ to $L_1$, call it $\overline{XA}$, are equal.

Therefore, $X$ is the point on $L_2$ which is equidistant to both $P_1$ and $L_1$. By definition, this point is on the parabola with focus $P_1$ and directrix $L_1$. $L_2$ is also the $\perp$ bisector of $\angle AXP_1$. Therefore, any point on $L_2$ is equidistant to $A$ and $P_1$.
Choose a point $Y$, on $L_2$ between $P_2$ and $X$. Construct the $\perp$ line to $L_1$ passing through $Y$, call it $\overline{YB}$. Note, that $\triangle YBA$ is right, thus $\overline{YB}<\overline{YA} = \overline{YP_1}$. Since all points of the parabola must be equidistant to both the directrix, $L1$, and the focus, $P1$, we know the parabola lies above $L_2$ at this point.

Similarly, we can show this is true for any point on $L_2$ from $X$ to $L_1$. Thus, $L_2$ is the tangent line to the parabola.[Source]


text:
Q: Eulerian paths visiting at most 2 vertices and odd degree edges
Hello,I am trying to understand Euler circle or not. If a graph has an euler path ,then it has at most 2  vertices with odd degree. (If I understand it right.)
I find some graphs I try solve them and ask you if my answers are right.
On graph 1.  it is Eulerian. We have u0,u1,u2,u3. We have 4 vertices. Each vertice has 2 edges max so it is Euler.
On graph 2.  u0,u1,u2,u3,u4. I have 5  vertices with 6 edges.
I have circle the u2 ,u1 on the image  (I have circle and u4 but wrong circle ,only u2 and u3 I wanted) .So, u2,u3 are vertices that have 3 edges. I wasn't sure if it is Euler or not.
Cause the most 2 vertiies with odd edges. Maybe it is Euler?
On graph 3. I have 20 vertices (If we count u0 until u19 is 20 vertices).Its not Euler cause
it has  all those  u1,u2,u3,u9,u14,u16,u17,u18  all those vertices have 3 edges each one that makes not Euler. u6 or u7 for example has 4 edges.Not Euler
**On graph 4.**It is u0 until u7 so it is 8 vertices.
u0,u1,u6,u7 are have odd degree (3 edges) so it is not euler .
On graph 5. the same it is not Euler example u0,u1,u2 are 3 vertices and have 3 edges each one .
Not euler

A: As you say, the first graph has an Euler circuit, and the third, fourth, and fifth all have more than two vertices of odd degree, so they have neither an Euler circuit nor an Euler path. The second graph is the interesting one. It has some vertices of odd degree, so it does not have an Euler circuit, but it has only two of them, so it does have an Euler path with those vertices as endpoints, for instance $u_2u_3u_0u_1u_4u_2u_1$. However, in order to be Eulerian, a graph must have an Euler circuit; an Euler path is not enough. Thus, only the first graph is Eulerian.


text:
Q: My code is not working properly The code is set to on the start slide forward and after 500 its suppose slide back. Well the code does slide forward but the code does not slide back after the 500. The code is not written properly as it should slide back. Here is the code JSFiddle:
$("#slideout").animate({right:'0px'}, {queue: false, duration: "slow"}, function () {
    timer = setTimeout(function () {
        $("#slideout").animate({right:'-280px'}, {queue: false, duration: 500})
    }, 500);
});

http://jsfiddle.net/wdvUQ/2/
If anybody can fix it up so that the code can slide back would be awesome.

A: Your issue is with the animate arguments
$("#slideout").animate({right:'0px'}, {queue: false, duration: "slow"}, function ()...

should be
$("#slideout").animate({right:'0px' , queue: false, duration: "slow"}, function ()...

You'll need to remove the closing/opening curly braces.


text:
Q: MongoDB Unwind In Parallel Stages or Combine Given the following data:
let tasks = [
  {
    _id: 1,
    task_number: 1,
    description: 'Clean Bathroom',
    customer: 'Walmart',
    users_worked: [
      {user: 'Jonny', hours: 1},
      {user: 'Cindy', hours: 1}
    ],
    supplies_used: [
      {item_code: 'LD4949', description: 'Liquid Detergent', quantity: 1}
    ]
  },
  {
    _id: 2,
    task_number: 2,
    description: 'Stock Cheeses',
    customer: 'Walmart',
    users_worked: [
      {user: 'Mark', hours: 3.0},
      {user: 'Shelby', hours: 2.0}
    ],
    supplies_used: []
  }
];

Suppose I want to show a table with each one of these in a list format:
task_number | description | customer | users | users_worked.hours (sum) | supplies_used.quantity (sum)
----------------------------------------------------------------------------------------------
      1 | 'Clean Bathroom' | 'Walmart' | 'Jonny, Cindy' |        2                |           1
      2 | 'Stock Cheeses'  | 'Walmart' | 'Mark, Shelby' |        5                |           0

The aggregate:
[
  {
    "unwind: {
      "path": "$users_worked",
      "preserveNullAndEmptyArrays": true
    }
  },
  {
    "unwind: {
      "path": "$supplies_used",
      "preserveNullAndEmptyArrays": true
    }
  },
  {
    $group: {
      _id: "$_id",
      task_number: {
        $first: "$task_number"
      },
      description: {
        $first: "$description"
      },
      customer: {
        $first: "$customer"
      },
      users: {
        $push: "$users_worked.user"
      },
      users_worked: {
        $sum: "$users_worked.hours"
      },
      supplies_used: {
        $sum: "$supplies_used.quantity"
      }
  }
]

The problem is that I need to $unwind both arrays (users_worked and supplies_used), which ends up skewing my results (cartesian product).  Since task #1 has 2 elements in users_worked array, it will make my supplies_used count go to 2.
This is a simple example, there could be many arrays and the more elements each have the more it skews the data.
Is there a way with aggregates to unwind multiple arrays separately so they don't skew each other?  I have seen an example of creating 1 combined object, where then theres only 1 source of unwinding.  Don't seem to understand how to do what I want though.
* EDIT *
I see that you can use the $zip mongo aggregate command to combine multiple arrays into 1 array.  This is a good start:
arrays: {
  $map: {
    input: {
      $zip: {
        inputs: [
          '$users_worked',
          '$supplies_used'
        ],
      }
    },
    as: 'zipped',
    in: {
      users_worked: {
        $arrayElemAt: [
          '$$zipped',
          0
        ]
      },
      supplies_used: {
        $arrayElemAt: [
          '$$zipped',
          1
        ]
      }

How can I use this $zip command if I were to have an array of array.  For example:
let tasks = [
  {
    _id: 1,
    task_number: 1,
    description: 'Clean Bathroom',
    customer: 'Walmart',
    users_worked: [
      {user: 'Jonny', hours: 1},
      {user: 'Cindy', hours: 1}
    ],
    supplies_used: [
      {item_code: 'LD4949', description: 'Liquid Detergent', quantity: 1}
    ],
    invoices: [
      {
        invoicable: true,
        items: [
           {item_code: 'LD4949', price: 39.99, quantity: 1, total: 39.99},
           {item_code: 'Hours', price: 50.00, quantity: 2, total: 100.00}
        ]
      }
    ]
  },
  {
    _id: 2,
    task_number: 2,
    description: 'Stock Cheeses',
    customer: 'Walmart',
    users_worked: [
      {user: 'Mark', hours: 3.0},
      {user: 'Shelby', hours: 2.0}
    ],
    supplies_used: [],
    invoices: []
  }
];

And I want to include the sum of invoices.items.total in my list.

A: Instead of using $unwind and $group you can use $reduce to aggregate names and $sum to sum up the numbers:
db.collection.aggregate([
    {
        $project: {
            task_number: 1,
            description: 1,
            customer: 1,
            users: {
                $reduce: {
                    input: "$users_worked",
                    initialValue: "",
                    in: {
                        $concat: [ "$$value", ", ", "$$this.user" ]
                    }
                }
            },
            users_worked: { $sum: "$users_worked.hours" },
            quantity: { $sum: "$supplies_used.quantity" }
        }
    }
])

Mongo Playground

A: I was able to solve this using multiple layers of $zip.  Starts on root layer, all arrays on root need to be zipped and then unwound.  Then you find the $sum of any fields on that layer, then you find next layer, $zip new arrays, then unwind, then sum that layer, etc.
The issue is you don't want to unwind multiple arrays or you get the cartesian product.  Need to combine into 1 array then unwind then everything is correct!


text:
Q: Spring Cloud Config Client multiple property files retrieve from same repo I have a requirement to retrieve the property files with environment name distinguishing those.
Config server is listening to this repo (https://github.com/tpande1/spring-cloud-config-repo/tree/master) which has : config-client-dev.properties, config-client-sbx.properties, config-client-test.properties and config-client-prod.properties
In Client Server i have the below config to read from the above github repo. How can i read these different properties with the environment specified in my Client Application?
Sample Rest Code:
@GetMapping("/message") //Pick message(SBX, DEV, Test, PROD) from the propertyfile from github
public String getMessage() {

    return message;

}

bootstrap.yml:
spring:
  profiles: dev
  application:
    name: config-client
  cloud:
    config:
      uri:  http://localhost:1000 //Config server port
      profile: sbx, dev, test, prod
management.endpoints.web.exposure.include: "*"

A: You can add multiple active profiles in your bootstrap yaml file. In the option where you have spring.profiles.active and in your config server, you can add search patterns for each profile.
As mentioned in the below link in Pattern matching section.
https://cloud.spring.io/spring-cloud-config/multi/multi__spring_cloud_config_server.html


text:
Q: Questions on simple threading jargon
When a manual-reset event is signaled,
  all threads waiting on the event
  become schedulable. When an auto-reset
  event is signaled, only one of the
  threads waiting on the event becomes
  schedulable.

I have some really noob questions here to ask, as I'm new to threading.

*

*What does it mean to "set" and "reset" an event?

*What is the difference between a manual-reset and auto-reset event?

*What does it mean when an event is "signaled"? Does it mean it is activated?

*What does it mean when a thread becomes  "schedulable" ?

*What is "waiting on the event" ?

A: *

*Think about a light switch.  When an event is "signaled," the light switch is turned ON.  When the event is "reset," the light switch is turned OFF.

*An auto-reset event means that after the event is signaled (turned ON) and a thread is released, the event is automatically reset (turned OFF).  A manual reset event remains signaled (turned ON) until it is manually reset (turned OFF).

*See #1 above.

*When a thread is waiting on an event, the thread is blocked, meaning that it cannot be scheduled for work by the operating system.  When the event the thread is waiting on is set (signaled, turned ON), the thread is released, i.e., becomes schedulable.  This simply means that the operating system can now schedule the thread for work.

*Waiting on an event simply means to call one of the Wait() functions on an event.  The thread will "wait" until the event is set/signaled/turned ON before continuing any work it has.

A: Basically, a "WaitHandle" (which includes both Manual Reset Events and Auto Reset Events) are types that allow a thread to wait until something happens - in this case, until the WaitHandle is "Set".
A thread (Thread A) can "wait" on a WaitHandle, blocking until a separate thread (Thread B) "sets" (=="signals") the WaitHandle.  This will allow thread A to continue on at that point.
The main difference occurs if you have multiple threads waiting on the WaitHandle.  In this case, with a Manual reset event, all of the threads will be allowed to continue on (ie: they're now schedulable, which means the OS will set them up and run them again at some point, usually fairly quickly).  With an auto reset event, one thread is allowed to continue, and the WaitHandle is "reset", which prevents the other threads from continuing (until the WaitHandle is signaled again, when the next thread is "released").

A: To address each of your questions:
1) When an event is reset, it means that another thread waiting on the event can now be signaled. In other words, a thread that is now sleeping (blocking) can be woken up to do work.
2) According to Event Objects (MSDN),

*

*Manual-reset event: An event object whose state remains signaled until it is explicitly reset to nonsignaled by the ResetEvent function. While it is signaled, any number of waiting threads, or threads that subsequently specify the same event object in one of the wait functions, can be released.

*Auto-reset event: An event object whose state remains signaled until a single waiting thread is released, at which time the system automatically sets the state to nonsignaled.
If no threads are waiting, the event object's state remains signaled. If more than one thread is waiting, a waiting thread is selected. Do not assume a first-in, first-out (FIFO) order. External events such as kernel-mode APCs can change the wait order.
So basically with a manual reset event you can explicitly reset the event, triggering any number of threads to execute. With an auto reset event, the OS guarantees that only a single thread will ever execute when the event is signaled.
3) Right, when an event is signaled, a thread is using the event to perform work. Any other threads attempting to access (signal) the event will be blocked.
4) In this context, schedulable means that a thread can be executed. Depending upon the event settings, the OS will pick one or more threads waiting on the event, and will execute them.
5) Waiting on the event means that a thread is blocking on the event object. While blocked, a thread is not executing any CPU cycles and is basically "put to sleep" by the OS.


text:
Q: WSO2 EI (ESB) - CSV File Data Validation I am able to read the csv file using WSO2 EI and insert the csv data into MySQL DB as well. Picked the csv fle from sftp as also and inserted the csv file data into MySQL DB. I have followed the WSO2 doc from official web site.
But I am not able to validate the data. Please suggest how to write a Java class to put validation on CSV File data while reading it.


text:
Q: F# Circular Type Definition Loop I want to have a type A which has a property which is an instance of type B. And type B has a property of an instance of type A. The problem is, F# reads the source files in order. So if I define type A first, then it won't recognize type B. And if I define type B first, I can't make it have an instance of A. Is there a way around this, or is this just bad design on my part?

A: You can a define mutually recursive type if they are in the same file like this
type Chicken =
   | Eggs of Egg list
and Egg =
   | Chickens of Chicken list


text:
Q: Angular - unit testing a controller that consumes a promise on initialization. ( Jasmine ) You have a controller ExampleController which consumes a method on a service RequestService.data during it's initialization, and you just want to test that the  controllers (scope).property is set to a value in the response:
ExampleController:
app.controller('ExampleController'
            , ['$scope','RequestService', function($scope, RequestService){
  var ex = this;
  (function initialize(){
    RequestService.
      data().
      then(function RSresp(info){
       ex.property = info.data.property;
      }
  })();
}]

RequestService:
app.service('RequestService', ['$http', function($http){
   this.data = function RSdata(){
     var closure = {prop: 'val', derp: 'aderp'};
     var url = 'http://aWebsite.' + closure.prop + '.com/' + closure.derp;
     return $http.get(url);
   }
}]);

Unit test:
describe('on initialization, ExampleController',function(){
 var controller, injector, $httpBackend, $scope, RequestService;

  beforeEach(function(){
   inject(function(_$injector_, _$controller_, _$rootScope_){
     injector = _$injector_;
     $scope = _$rootScope_.new();
     $httpBackend = injector.get('$httpBackend');
     controller = _$controller_('ExampleController', {$scope : $scope});
     RequestService = injector.get('RequestService');
   })
  })

  beforeEach(function(){
    $httpBackend.
       when('GET', 'http://aWebsite.val.com/aderp').
       respond({property: 'value'});
  });

  afterEach(function(){
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
  });

  it('has a property "property" with a value "value" ', function(){
    expect(controller.property).toBeDefined();
    expect(controller.property).toBe('value');
  });
});

I've tried a bunch of different things like:
expect($scope.property).toBeDefined();

or
spyOn(RequestService, 'data');
// or spyOn(RequestService, 'data').andCallThrough();
expect(controller.property).toBeDefined();
expect(RequestService.data).toHaveBeenCalled;

Karma's saying:
"Error: Unflushed requests"
or
on initialization, ExampleController has a property "property" with a value "value"
Fail: undefined is not defined.
console.log(controller) doesn't show that the property is set, and it doesn't seem like RequestService is ever called...
I don't know.
All of my tests for RequestService are passing, and the application itself works... but I can't figure out how to write the spec to reflect that.
I've looked at:
Unit testing promises in controllers in AngularJS
and some others that haven't turned out to be irrelevant... but no luck

A: Your tests currently try to do far too much.
The responsibility for testing your $http requests should be the tests for your RequestService. When testing anything that calls RequestService, you mock the RequestService.
In general, do not go any further than 1 dependency in unit tests (so, ExampleController -> RequestService would be your limit). Your integration tests will be responsible for testing the full sequence.
So your unit tests should look something like this:
describe('on initialization, ExampleController',function(){
 var $q, $controller, injector, $scope, RequestService;

  beforeEach(function(){
    inject(function(_$q_, _$injector_, _$controller_, _$rootScope_){
      $q = _$q_;
      injector = _$injector_;
      $controller = _$controller_;
      $scope = _$rootScope_.$new();
      RequestService = injector.get('RequestService');
    });
  });

  beforeEach(function(){
    spyOn(RequestService, 'data');
  });

  describe('with successful data retrieval', function () {
    beforeEach(function () {
      // mock a success
      RequestService.data.andReturn($q.when({property: 'value'}));
      controller = $controller('ExampleController', {$scope : $scope});

      $scope.$digest(); // fulfil the promises
    });

    it('has a property "property" with a value "value" ', function(){
      expect(controller.property).toBeDefined();
      expect(controller.property).toBe('value');
    });
  });

  describe('with failed data retrieval', function () {
    beforeEach(function () {
      // mock a fail
      RequestService.data.andReturn($q.reject(null));
      controller = $controller('ExampleController', {$scope : $scope});

      $scope.$digest(); // fulfill the promises
    });

    it('should do something', function(){
      expect('this').toBe('that');
    });
  });
});

A: The solution to that problem was to call $digest.


text:
Q: Reset function is not working for JavaScript game I am new to programming, and I am creating a psychic game where you guess the letter the computer created.
For some reason, when you select the letter the computer chose, the reset(); function is not causing the guesses to reset, and still uses the previous computer guess as the letter, even though the reset(); function creates a new computer guess. I've Googled this and haven't been able to find anything to answer my question. I'm not sure what I'm doing wrong.
        <!DOCTYPE html>

            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Psychic Game</title>

The Psychic Game

Guess what letter I'm thinking of?

Wins: 0

Losses: 0

Guesses left: 10

Your guesses so far:

JavScript:
    var alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i",
    "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];

    var wins = 0;
    var losses = 0;
    var guessesLeft = 10;
    var guessedLetters = [];

    //generate random letter

    var randomLetter = Math.floor(Math.random() * alphabet.length);
    var computerChoice = alphabet[randomLetter];
    console.log("The computer choose " + computerChoice);

    //reset function
    function reset(){
        guessesLeft = 10;
        guessedLetters = [];
        var randomLetter = Math.floor(Math.random() * alphabet.length);
        var computerChoice = alphabet[randomLetter];
        console.log("The computer choose " + computerChoice);
    }

    //event listener for keyup event
    document.onkeyup = function(event){
        //user makes choice
        var userChoice = event.key;
        //double check userChoice is viable
        var viableChoice = /[a-z]/gi;
        if (!viableChoice.test(userChoice)) {
        alert("please enter a letter");
        }
        else {
        console.log(userChoice);
        }
        //if user guesses the right letter
        if(userChoice !== computerChoice){
            guessesLeft--;
            document.getElementById("guessesLeft").innerText = guessesLeft;
            document.getElementById("main-text").innerText = "Try again!";
            guessedLetters.push(userChoice);
            document.getElementById("guessedLetters").innerText = guessedLetters;
        } else if(userChoice === computerChoice){
            wins++;
            alert("You won!");
            document.getElementById("wins").innerText = wins;
            reset();
        }
        if(guessesLeft === 0){
            losses++;
            document.getElementById("main-text").innerText = "You lose! Try again";
          reset();
        }
    }

A: In your reset() function,
var randomLetter = Math.floor(Math.random() * alphabet.length);
        var computerChoice = alphabet[randomLetter];

should be
randomLetter = Math.floor(Math.random() * alphabet.length);
        computerChoice = alphabet[randomLetter];

You are defining new local vars when you just want to update the old ones.


text:
Q: After upgrade app to 64-bit Apk anaylzer only hows 32-bit in lib I am struggeling to upgrade my app to support 64 bit.
I have added
ndk.abiFilters 'armeabi-v7a','arm64-v8a','x86','x86_64'
in build.gradle, but when I analyze the apk I only see 32 bit in lib

I have quite a lot of external stuff imported in dependencies, so I guess at last one of them is not 64-bit compliant.
The developer guide doesn't mention anything about how to find out which one is causing problems. Help is greatly appreciated.


text:
Q: Unable to Upgrade GuzzleHttp with PHP8.1 version Previously we are using GuzzleHttp 6.0 and PHP 7.0, Now we have updated our PHP version to 8.1 and also trying to update GuzzleHttp to latest 7.0 version. I am following its document to update GuzzleHttp. But I am getting errors shown in the image.
My composer code is below. Can anyone please help me regarding this
"require-dev": {
"phpunit/phpunit": "9.5.0",
"phpunit/dbunit": "4.0.0"
},
"require": {
    "jwmickey/php-jwt": "dev-master",
    "aws/aws-sdk-php": "3.19.30",
    "pear/versioncontrol_git": "0.5.0",
    "aws/aws-php-sns-message-validator": "1.1.0",
    "endroid/qr-code": "^3.0",
    "guzzlehttp/guzzle": "^7.0"

},


text:
Q: f.readlines(): how to print without extra figures I am trying to print from f.readlines. As seen in the code, when I print a, it prints each element in a new line without any extra additions (\,n,"). However when I try to split the string and call only a specific element, it adds the extra symbols. How do I fix this?
cargo.txt
wardrobe 550.30
mattress 300.10
fauteuil 600.00
drawer 1230.55
hammock 75.00

code:

import sys
fn = sys.argv [1]
wl= sys.argv [2]
with open ("cargo.txt","r") as f:
    a = (f.readlines())
    print(*a)
    b = a.split()
    print(b[1])

A: Here is how you can extract all the floats:
with open ("cargo.txt","r") as f:
    a = [l.split()[1] for l in f.readlines()]
    print(a)

Output:
['550.30', '300.10', '600.00', '1230.55', '75.00']


text:
Q: Custom PAM modules and security considerations I am writing my own PAM module that will be part of an application that I am developing, but I'm not sure exactly where to put it. My module basically does network-level authentication (with other mojo of course) similar to LDAP.
There are a lot of config files in my /etc/pam.d/ directory, and I know what most of the services do (except a couple, like atd, polkit, ppp). I assume that authentication with PAM stack goes something like this:

*

*Runs stack based on service name (if a config file exists)

*If not authenticated, fall back on common-*, where * is the module-type (auth, account, etc)

*Return success or fail to calling application (and any other data of course)

Am I correct in this assumption? Do all platforms have common-auth, common-account, common-password, and common-session?
If so, I was thinking about just putting it at the top of common-* as a sufficient module so that on failure the regular PAM stack would be left unaffected. This is particularly advantageous because I can programmatically do this on software install.
Am I missing any potential security vulnerabilities?
I couldn't find very good documentation on where to integrate custom PAM modules or security issues surrounding where to put modules.

A: When you call into Linux-PAM for some authentication procedure, there
is always one and only one stack that is run.
The stack definition is looked up in these places; the first
successful attempt determines which file is read:

*

*the file in /etc/pam.d named after the application "service name" (e.g., sshd or gdm), or

*the file /etc/pam.d/other if no service-specific file exists, or

*the file /etc/pam.conf if directory /etc/pam.d does not exist.
See the documentation for function pam_start for details.
The common-* files are a convention followed by many Linux
distributions but are not mandated by the PAM software itself.
They are usually included by other PAM files by means of @include
statements; for instance the /etc/pam.d/other file on Debian has the
following content:
# We fall back to the system default in /etc/pam.d/common-*
@include common-auth
@include common-account
@include common-password
@include common-session

The same @include statements may be used by service-specific file as
well, and -indeed- they are in the default configuration on Debian.
Note that this is a matter of configuration: a sysadmin is free to
change the file in /etc/pam.d not to include any common-* files at
all!
Therefore: if your PAM module is specific to your application, create
an application-specific service file and call the module from there.
Do not automatically add a module to other services' PAM file nor to
the fall-back others file, as this may break other applications
installed on the system.  Management of the PAM software stack is a
task for the system administrator, not for the application
developers.


text:
Q: How to add custom attributes (on-chain) in ERC721 token? i'm learning solidity using Openzeppelin Framework.
Currently i'm using the ERC721 Preset Contract (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/presets/ERC721PresetMinterPauserAutoId.sol)
I would like to add custom attributes for each token minted in order to store some important data on the blockchain (i would not use for certain attributes the REST API, but i prefer to write them on the chain).
Each token will have different data.
string: Name
string: Surname
bytes32: 0x63383a61613a62323a30373a63383a323020

Is it possible to do it creating some new functions (without editing the mint function), allowing only the addresses that have the minter role?

A: Yes.
You can create a mapping between the tokenId and whatever you want it to have. Let's call it name.
mapping(uint256 => string) name;
If you have a lot of attributes, you can do a mapping of a struct.
    struct Character {
        uint256 strength;
        uint256 dexterity;
        uint256 constitution;
        uint256 intelligence;
        uint256 wisdom;
        uint256 charisma;
        uint256 experience;
        string name;
    }

    Character[] public characters;

    mapping(uint256 => uint256) tokenIdToCharacterIndex;

Then, just make sure to update your tokenURI to include the on-chain attributes so that they show up in NFT marketplaces.


text:
Q: How to setup mass dynamic virtual hosts in nginx on docker? How can I setup mass dynamic virtual hosts in nginx As seen here
except using docker as the host machine?
I currently have it setup like this:
# default.conf
server {
   root /var/www/html/$http_host;
   server_name $http_host;
 }

And in my Dockerfile
COPY default.conf /etc/nginx/sites-enabled/default.conf

And after I build the image and run it:
docker run -d 80:80 -v www/:/var/www/html

But when I point a new domain (example.dev) in my hosts file and make a www/example.dev/index.html. It doesn't work at all.

A: The setup is correct and it works as i tested on my system. The only issue is that you are copying the file on a wrong path. The docker image doesn't use the sites-enabled path by default. The default config loads everything present in /etc/nginx/conf.d. So you need to copy to that path and rest all works great
COPY default.conf /etc/nginx/conf.d/default.conf

Make sure to map you volumes correctly. While testing I tested it using below docker command
docker run -p 80:80 -v $PWD/www/:/var/www/html -v $PWD/default.conf:/etc/nginx/conf.d/default.conf nginx

Below is the output on command line
vagrant@vagrant:~/test/www$ mkdir dev.tarunlalwani.com
vagrant@vagrant:~/test/www$ cd dev.tarunlalwani.com/
vagrant@vagrant:~/test/www/dev.tarunlalwani.com$ vim index.html
vagrant@vagrant:~/test/www/dev.tarunlalwani.com$ cat index.html

This is a test

Output on browser


text:
Q: Deploy VUE project on Nginx, static file like css, js can not be found My OS is window, and deploy VUE project on Nginx server.

*

*Build VUE project
cd E:\test\test-project-frontend-demo
npm install && npm run build

*config nginx:

nginx.conf
worker_processes  1024;

pid                     logs/nginx.pid;

events {
    multi_accept        on;
    worker_connections  65535;
}

http {
    #MIME
    include             mime.types;
    default_type        application/octet-stream;

    #LOGGING
    log_format          main  '$remote_addr - $remote_user [$time_local] "$request" '
                            '$status $body_bytes_sent "$http_referer" '
                            '"$http_user_agent" "$http_x_forwarded_for"';

    access_log          logs/access.log     main;
    error_log           logs/error.log      warn;

    charset             utf-8;
    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    server_tokens       off;
    log_not_found       off;
    types_hash_max_size 2048;
    client_max_body_size 16M;
    #keepalive_timeout  0;
    keepalive_timeout   65;
    gzip  on;

    #SITES
    include sites-available/project.conf;
}

project.conf
server {
    listen          80;
    listen          443 ssl;

    server_name project.testltd.com;

    # security
    include nginxconfig.io/security.conf;

    # logging
    access_log logs/project.access.log;
    error_log logs/project.error.log warn;

    # site project
    location / {
        alias E:/test/test-project-frontend-demo/dist;
        index index.html;
        try_files $uri $uri/ /index.html;
    }

    # additional config
    include nginxconfig.io/general.conf;

    # ssl config
    include nginxconfig.io/self-signed.conf;
    include nginxconfig.io/ssl-params.conf;
}

start nginx:
    nginx.exe -c conf/nginx.conf

index.html can be access , and response is 200, but static file like css and js can not be accessed, Why?


text:
Q: Como pasar datos de props a un state en React Hooks El dato es enviando desde un componente hijo a un componente padre utilizando React Hooks y Redux, el dato llega correctamente al componente padre y lo puedo visualizar inicialmente con un console.log pero necesito pasar ese dato a un estado ya iniciado, ya que ese estado se pasa a un input en el cual me muestra los datos y lo puedo editar.
El problema esta que no puedo pasar el dato del props directamente al estado ya que me genera un renderizado infinito, y cuando intento pasar el dato directamente al input, no lo toma como un cambio y no lo deja editar ya que el dato no es el estado inicial.
Lo ideal seria pasar el dato al estado y el automáticamente lo tomaría como un cambio pero si alguien tiene alguna idea de como resolver este problema seria de mucha ayuda.
Componente hijo
import React,{ useState } from 'react';
import { Container,Row,Col,Button,Form } from 'react-bootstrap'
import {color} from './propStatus'
import findHistory from '../../redux/actions/findHistory'
import { connect } from 'react-redux';
const moment = require('moment');

const History = (props) => {
    const tableData = props.tableData
    const dataHistory= (e,data) => {
        e.preventDefault();
        props.addHistory({jsonHistory:data.jsonHistory,statusHistory:data.statusHistory,responseHistory:data.responseHistory})
    }

    return(
        tableData.sort((a, b) => moment(a.date).format('LLL') < moment(b.date).format('LLL') ? 1:-1).map((val,index) =>
            <Container key={index}>
                <Form onSubmit={(e,dataSubmit) => dataHistory(e,dataSubmit={jsonHistory: val.json,statusHistory: val.state,responseHistory: val.response})}>

{ moment(val.date).format('LLL') }

                    <Row>
                        <Col md={8}>

{ val.response === '""' ? 'No hay informacion' : val.response }

{ val.json }

                        </Col>
                        <Col md={4}>
                            <Button
                                variant={color(val.state)}
                                type="submit">
                                { val.state }
                            </Button>
                        </Col>
                    </Row>

                </Form>
            </Container>
        )
    )
}

const mapDispatchToProps=dispatch=>({
    addHistory:data=>dispatch(findHistory(data))
})

export default connect(null,mapDispatchToProps)(History);

Componente padre
import React, { useState,useEffect, useRef, useCallback } from 'react';
import { Container,Row,Col,Button } from 'react-bootstrap'
import Axios from 'axios';
import { connect } from 'react-redux'
import ContentHistoryState from '../components/ThirdParty/ContentHistoryState'
import EmptyHistoryState from '../components/ThirdParty/EmptyHistoryState'
import '../components/css/blog.css'
import Paginate from '../components/Paginate'
const moment = require('moment');
let day = moment();

function Home(props) {
    const code = props.sendCode
    const title = props.sendTitle
    const history = props.history
    const [resp, setRespList] = useState([])
    const [historyList, setHistoryList] = useState([])

    const [json, setJson] = useState('')
    const [state, setState] = useState('')
    const [response] = useState('')
    let hJson = 0
    try{
        if(history[0].history){
            hJson = history[0].history.jsonHistory
            console.log(history[0].history.statusHistory)
        }
    }catch(e){
    }

    const handleCount = useCallback(() => {
        console.log(state)
        setState(history[0].history.statusHistory)
        console.log(state)
    },[]);

    useEffect(() => {
        Axios.post('http://localhost:3000/get/history',{
            code: code,
            client:1
        })
        .then(response => response)
        .then((data) => {
            const countKey = Object.keys(data.data).length;
            let info= []
            for(let i=0;i< countKey; i++){
                info.push(data.data[i])
            }
            setHistoryList(info)
        })
    },[])

    const submit = (data) => {
        const jsonSend = data.json
        setState('')
        if(resp.length !== 0 )
            resp.shift()

        Axios.post("http://localhost:3000/set/thirdParty",{
            json: jsonSend,
            code: code,
        })
        .then(response =>response)
        .then(data =>{
            setRespList([
                ...resp,
                {
                    status: data.status,
                    statusText: data.statusText,
                    info: data.data,
                }
            ])
            day = moment().format();
            const j=({'date':day,'json':jsonSend,'response':JSON.stringify(data.data),'state':data.status })
            setHistoryList(j)
        })
        .catch(error => {
            setRespList([
                ...resp,
                {
                    status: error.response.status,
                    statusText: error.response.statusText,
                    info: error.toString(),
                }
            ])
        })
    }
    const handleChange= (data) => {
        console.log(data)
        setJson(data)
        //hJson = data
    }

    const memoizedCallback = useCallback(
    () => {
        setJson(hJson)
    },
    [hJson],
    );

    return(

            <Container fluid>

{ title }

                <Row>
                    <Col md={5}>
                        { historyList.length !== 0
                            ? <Paginate historyList={ historyList }/>
                            :
Load...

                        }
                    </Col>
                    <Col md={7}>
                        Ingresa la información
                        <textarea
                            rows="8"
                            type="text"
                            name="json"
                            className="form-control mb-3"
                            value={ hJson !== 0 ? memoizedCallback : json }
                            onChange={(e)=> {
                                handleChange(e.target.value)
                        }}>
                        </textarea>
                        <Button
                            variant="dark"
                            onClick={(dataClick) =>
                            submit(dataClick={json: json})}>
                            Send Data
                        </Button>
                        {   state
                            ?   <ContentHistoryState
                                state={ state }
                                response={ response }/>
                            :   <EmptyHistoryState
                                resp={ resp }/>
                        }
                    </Col>
                </Row>
            </Container>

    )
}

const mapStateToProps = (state) => {
    if(state.history.length > 1)
        state.history.shift();

    return {
        history: state.history
    }
};

export default connect(mapStateToProps,null)(Home);


text:
Q: Using MSBuild for Build solution include InstallShield ProjecT I'm doing a project in C #. In my solution I have an installsheld project that works very well when I compile directly from visual studio, I have a setup that is generated and is ready to be installed.
I would like for various reasons to be able to compile with command-line solution using MSBuild. Everything works but my setup does not generate correctly despite any errors.
Below, the log when I compile the installshield project from visual studio:
Log InstallShield compile from visual studio
With MSBuild :
Log InstallShield compile from command line using MSBuild
We notice that during the step Building File table, from visual studio we have the dependency of component 'RegieCiel.Primary_output', so we are good. Since MSbuild, nothing is added ....
So what happens is that during the installation of the Setup, it lacks the dependencies.
I first thought of a build order but it would work in both cases?
What do you think ?

A: I avoid project output references like the plague. I suggest having an Application.sln and an Installer.sln.  Have your final projects in application.sln ( EXE, Web Projects )  do a postbuild xcopy or MSBuild publish profile and create a directory that models your deployed application.  From there use one Path Variable in InstallShield  to point to all those files as static links.  Also make sure you turn off all  dependency scanning.  You want to be 100% in control of what does and doesn't go into your project.

A: I thank you for your answer and actually I think putting up does not place a solution "static" would solve the problem.
However after a long search I finally found!
In my solution I had a package named "SlowCheetah" to manage several configuration files. By uninstalling it, restart MSbuild, my Setup works perfectly!
Thank you for your help !


text:
Q: iframe not working in AngularJS 1.3.0 I'm new to web dev. I'm using AngularJS 1.3.0. When I try using {{ things[0].embed }} to insert the embedded source video link from my database, nothing is displayed, but hardcoding the link, for example "//www.youtube.com/embed/wZZ7oFKsKzY", works. Is there something that I'm missing? Am I misusing the scope somehow?
Here's another example of what I'm trying to do. If you replace the {{thing[0].embed}} with the youtube link, it works. Why doesn't it replace the {{thing[0].embed}} with the link?
http://plnkr.co/edit/Udml7NIyWcUuMtYGDXNc?p=preview
//myCore.js

var coreControl = angular.module('myCore', []);

function mainController($scope, $http) {
    $scope.formData = {};

    $http.get('*')
        .success(function(data) {
            $scope.things = data;
            console.log(data);
        })
        .error(function(data) {
            console.log('Error: ' + data);
        });

    $scope.doThings = function() {
        $http.post('*', $scope.formData)
            .success(function(data) {
                $scope.formData = {};
                $scope.things   = data;
                console.log(data);
            })
            .error(function(data) {
                console.log('Error: ' + data);
            });
    };
}

//index.html

 {{ things[0].name }}

        {{ things[0].embed }}

A: I know I joined the party late (again), but there you go:
Strict Conceptual Escaping (SCE) is an important concept in Angular should not be taken light-heartedly (if you care about the security of your app).
It is important to understand wht it means and what are the implications and dangers in calling $sce.trustAs...().
This answer gives a little insight on what is SCE and why does Angular treat resources (such as URLs) the way it does.
That answer explains the importance of client-side sanitization (this is what you by-pass by calling $sce.trustAs...() unless you are 100% sure that you can trust it).

That said, there might be better (read "safer and more maintainable") ways to achieve the same result.
E.g. $sceDelegateProvider (which is used by the $sce service to decide what is secure and what isn't) provides methods to white-list/black-list resources using string-matching (with optional wildcards) or regular expressions (not recommended).
For more info on how to populate your white-/black-list take a look here.

E.g. if you want your application to allow links from www.youtube.com, you can define your white-list like this:
.config(function ($sceDelegateProvider) {
    $sceDelegateProvider.resourceUrlWhitelist([
        'self',   // trust all resources from the same origin
        '*://www.youtube.com/**'   // trust all resources from `www.youtube.com`
    ]);
});

See, also, this updated demo.

A: Your updated plunker
You must explicitly direct angular to trust content that could otherwise provide security holes for xss attacks. That is what the
$sce.trustResourceAsUrl()
function call is for.


text:
Q: Access RichTextContentControl Text from an AddIn in MS Word using C# I've created an AddIn for MS Word. There's a new tab and a button. I've added a new template document that has a RichTextContentControl in it.
 WORD_APP = Globals.ThisAddIn.Application;
            object oMissing = System.Reflection.Missing.Value;
            object oTemplate = "E:\\Sandbox\\TemplateWithFields\\TemplateWithFields\\TemplateWithFields.dotx";
            oDoc = WORD_APP.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref oMissing);

I want to get the text inside the RichTextContentControl. How can I access the text or content of a RichTextContentControl in my AddIn project?

A: The text of the content control can be accessed as follows:
string text = contentControl1.Range.Text;

Additionally, there are a number of ways you can iterate through content controls and only select content controls of specific type or content controls which match a certain tag or title.
This is quite important as you may want to process only content controls which match a specific type or naming convention, please see an example below:
        WORD_APP = Globals.ThisAddIn.Application;
        object oMissing = System.Reflection.Missing.Value;
        object oTemplate = "E:\\Sandbox\\TemplateWithFields\\TemplateWithFields\\TemplateWithFields.dotx";
        Word.Document document = WORD_APP.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref oMissing);

        //Iterate through ALL content controls
        //Display text only if the content control is of type rich text
        foreach (Word.ContentControl contentControl in document.ContentControls)
        {
            if (contentControl.Type == Word.WdContentControlType.wdContentControlRichText)
            {
                System.Windows.Forms.MessageBox.Show(contentControl.Range.Text);
            }
        }

        //Only iterate through content controls where the tag is equal to "RT_Controls"
        foreach (Word.ContentControl contentControl in document.SelectContentControlsByTag("RT_Controls"))
        {
            if (contentControl.Type == Word.WdContentControlType.wdContentControlRichText)
            {
                System.Windows.Forms.MessageBox.Show("Selected by tag - " + contentControl.Range.Text);
            }
        }

        //Only iterate through content controls where the title is equal to "Title1"
        foreach (Word.ContentControl contentControl in document.SelectContentControlsByTitle("Title1"))
        {
            if (contentControl.Type == Word.WdContentControlType.wdContentControlRichText)
            {
                System.Windows.Forms.MessageBox.Show("Selected by title - " + contentControl.Range.Text);
            }
        }


text:
Q: Как сменить язык пользователю на сайте Django? Делаю возможность на сайте переключаться между русской, английской и украинской версией. Обернул строки в шаблонах, которые надо перевести, в тег {% trans %}, строки в коде, всё перевёл и скомпилировал перевод. Также установил locale_url.
В settings.py прописал:
LANGUAGE_CODE = 'Ru-ru'
LANGUAGES = (
    ('en', 'English'),
    ('ru', 'Russian'),
    ('uk', 'Ukrainian'),
)

TIME_ZONE = 'Europe/Kiev'
USE_I18N = True
USE_L10N = True
USE_TZ = True

LOCALE_PATHS = (
    'locale',
     # os.path.join(BASE_DIR, 'locale'),
)

Переключать язык через POST, так как это делается в django.conf.urls.i18n мне не захотелось, поэтому создал такое представление:
def select_lang(request, code):
    go_next = request.META.get('HTTP_REFERER', '/')
    response = HttpResponseRedirect(go_next)
    if code and translation.check_for_language(code):
        if hasattr(request, 'session'):
            request.session['django_language'] = code
        else:
            response.set_cookie(settings.LANGUAGE_COOKIE_NAME, code)
        translation.activate(code)
    return response

Перехожу в браузере на /lang/uk, страница перезагружается, а язык остаётся прежний. Если вводить адрес /uk/about - страница переводится, но при переходе на другую язык опять возвращается.
В чем проблема, подскажите, пожалуйста!
Вот мои middleware, может в них дело:
MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.locale.LocaleMiddleware',
]

P.S. язык сайта по дефолту русский, как и весь текст в коде и в шаблонах. Но у меня по умолчанию отображается английский. Через заголовки запроса
"Accept-Language en-US,en;q=0.5"
P.S.S. функцию вьюхи проверял, на выходе у request.session['django_language'] стоит код языка, который мне надо.

A: Нужно в метод добавить еще:
request.session['_language'] = code

В сессии django хранит 2 параметра:
django_language и _language


text:
Q: Split lists in batches This may sound simple but sometimes its the simple things that are quite harder to achieve. At least I can't find a proper way to do this clean with PHP and I searched different functions.
I have a lists of items I read from a file. For example:
foreach(file('items.txt') as $line) {
// Do something here with $line;
}

Assuming this text list (which is read line by line) has a specific number of items, 50, or 10,000 or 9,444, how can I split them into smaller batches?
For example split them into batches of 100 each. I basically want to read items.txt and write the items into smaller files, for example items1.txt, items2.txt, items3.txt, and so on. Each containing the same number of items, except the last file that contain less as we don't know the total numbers of items to split.

A: You can use array_chunk() to automatically split your array of lines into sub-arrays of a specific size.
Examples
$chunks = array_chunk(file('items.txt'), 100);
foreach ($chunks as $chunk) {
   foreach($chunk as $line) {
   // Do something here with $line;
   }
}

A: I would suggest you have a counter variable which counts how many lines you've added. Whenever it reaches your threshold you should do something with that data and afterwards clean the array and reset the counter to zero.
This also depends on what you're trying to achieve. If your're getting an out of memory error half way through, due to something like sending an email every iteration. You might solve it by adding a delay (sleep) after every action.
Hope this helps you.


text:
Q: Stormcrawler not fetching/indexing pages for elasticsearch I am using the Stormcrawler with the Elasticsearch example  and no pages are shown with the FETCHED status in Kibana while crawling the webpage http://books.toscrape.com/
Still on the console the webpages appear to be fetched and parsed
48239 [Thread-26-fetcher-executor[3 3]] INFO  c.d.s.b.FetcherBolt - [Fetcher #3] Threads : 0    queues : 1      in_queues : 1
48341 [FetcherThread #7] INFO  c.d.s.b.FetcherBolt - [Fetcher #3] Fetched http://books.toscrape.com/catalogue/category/books_1/index.html with status 200 in msec 86
48346 [Thread-46-parse-executor[5 5]] INFO  c.d.s.b.JSoupParserBolt - Parsing : starting http://books.toscrape.com/catalogue/category/books_1/index.html
48362 [Thread-46-parse-executor[5 5]] INFO  c.d.s.b.JSoupParserBolt - Parsed http://books.toscrape.com/catalogue/category/books_1/index.html in 13 msec

Also it seems that the index of Elasticsearch gets some items even though these have no title
Screenshot of Kibana
I expanded the com.digitalpebble.stormcrawler.elasticsearch.bolt.IndexerBolt to also store the metadata of a web page in a local file and it seems like it does not get any tuples at all. Since the IndexerBolt also marks the status of a url as FETCHED that would explain the mentioned observation in Kibana.
Is there any explanation for this behaviour? I already reverted the crawler configuration to the standard, except the index bolt in crawler.flux to run my class.
The Topology Configuration:
name: "crawler"

includes:
    - resource: true
      file: "/crawler-default.yaml"
      override: false

    - resource: false
      file: "es-conf.yaml"
      override: true

spouts:
  - id: "spout"
    className: "com.digitalpebble.stormcrawler.elasticsearch.persistence.AggregationSpout"
    parallelism: 10

bolts:
  - id: "partitioner"
    className: "com.digitalpebble.stormcrawler.bolt.URLPartitionerBolt"
    parallelism: 1
  - id: "fetcher"
    className: "com.digitalpebble.stormcrawler.bolt.FetcherBolt"
    parallelism: 1
  - id: "sitemap"
    className: "com.digitalpebble.stormcrawler.bolt.SiteMapParserBolt"
    parallelism: 1
  - id: "parse"
    className: "com.digitalpebble.stormcrawler.bolt.JSoupParserBolt"
    parallelism: 1
  - id: "index"
    className: "de.hpi.bpStormcrawler.IndexerBolt"
    parallelism: 1
  - id: "status"
    className: "com.digitalpebble.stormcrawler.elasticsearch.persistence.StatusUpdaterBolt"
    parallelism: 1
  - id: "status_metrics"
    className: "com.digitalpebble.stormcrawler.elasticsearch.metrics.StatusMetricsBolt"
    parallelism: 1

streams:
  - from: "spout"
    to: "partitioner"
    grouping:
      type: SHUFFLE

  - from: "spout"
    to: "status_metrics"
    grouping:
      type: SHUFFLE

  - from: "partitioner"
    to: "fetcher"
    grouping:
      type: FIELDS
      args: ["url"]

  - from: "fetcher"
    to: "sitemap"
    grouping:
      type: LOCAL_OR_SHUFFLE

  - from: "sitemap"
    to: "parse"
    grouping:
      type: LOCAL_OR_SHUFFLE

  - from: "parse"
    to: "index"
    grouping:
      type: LOCAL_OR_SHUFFLE

  - from: "fetcher"
    to: "status"
    grouping:
      type: FIELDS
      args: ["url"]
      streamId: "status"

  - from: "sitemap"
    to: "status"
    grouping:
      type: FIELDS
      args: ["url"]
      streamId: "status"

  - from: "parse"
    to: "status"
    grouping:
      type: FIELDS
      args: ["url"]
      streamId: "status"

  - from: "index"
    to: "status"
    grouping:
      type: FIELDS
      args: ["url"]
      streamId: "status"

The reconfigured IndexerBolt
package de.hpi.bpStormcrawler;

/**
 * Licensed to DigitalPebble Ltd under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * DigitalPebble licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import static com.digitalpebble.stormcrawler.Constants.StatusStreamName;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

import java.io.*;
import java.util.Iterator;
import java.util.Map;

import org.apache.storm.metric.api.MultiCountMetric;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.digitalpebble.stormcrawler.Metadata;
import com.digitalpebble.stormcrawler.elasticsearch.ElasticSearchConnection;
import com.digitalpebble.stormcrawler.indexing.AbstractIndexerBolt;
import com.digitalpebble.stormcrawler.persistence.Status;
import com.digitalpebble.stormcrawler.util.ConfUtils;

/**
 * Sends documents to ElasticSearch. Indexes all the fields from the tuples or a
 * Map <String,Object> from a named field.
 */
@SuppressWarnings("serial")
public class IndexerBolt extends AbstractIndexerBolt {

    private static final Logger LOG = LoggerFactory
            .getLogger(IndexerBolt.class);

    private static final String ESBoltType = "indexer";

    static final String ESIndexNameParamName = "es.indexer.index.name";
    static final String ESDocTypeParamName = "es.indexer.doc.type";
    private static final String ESCreateParamName = "es.indexer.create";

    private OutputCollector _collector;

    private String indexName;
    private String docType;

    // whether the document will be created only if it does not exist or
    // overwritten
    private boolean create = false;
    File indexFile;

    private MultiCountMetric eventCounter;

    private ElasticSearchConnection connection;

    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    public void prepare(Map conf, TopologyContext context,
                        OutputCollector collector) {
        super.prepare(conf, context, collector);
        _collector = collector;

        indexName = ConfUtils.getString(conf, IndexerBolt.ESIndexNameParamName,
                "fetcher");
        docType = ConfUtils.getString(conf, IndexerBolt.ESDocTypeParamName,
                "doc");
        create = ConfUtils.getBoolean(conf, IndexerBolt.ESCreateParamName,
                false);

        try {
            connection = ElasticSearchConnection
                    .getConnection(conf, ESBoltType);
        } catch (Exception e1) {
            LOG.error("Can't connect to ElasticSearch", e1);
            throw new RuntimeException(e1);
        }

        this.eventCounter = context.registerMetric("ElasticSearchIndexer",
                new MultiCountMetric(), 10);

        indexFile = new File("/Users/jonaspohlmann/code/HPI/BP/stormCrawlerSpike/spikeStormCrawler2/index.log");
    }

    @Override
    public void cleanup() {
        if (connection != null)
            connection.close();
    }

    @Override
    public void execute(Tuple tuple) {

        String url = tuple.getStringByField("url");

        // Distinguish the value used for indexing
        // from the one used for the status
        String normalisedurl = valueForURL(tuple);

        Metadata metadata = (Metadata) tuple.getValueByField("metadata");
        String text = tuple.getStringByField("text");

        //BP: added Content Field
        String content = new String(tuple.getBinaryByField("content"));

        boolean keep = filterDocument(metadata);
        if (!keep) {
            eventCounter.scope("Filtered").incrBy(1);
            // treat it as successfully processed even if
            // we do not index it
            _collector.emit(StatusStreamName, tuple, new Values(url, metadata,
                    Status.FETCHED));
            _collector.ack(tuple);
            return;
        }

        try {
            XContentBuilder builder = jsonBuilder().startObject();

            // display text of the document?
            if (fieldNameForText() != null) {
                builder.field(fieldNameForText(), trimText(text));
            }

            // send URL as field?
            if (fieldNameForURL() != null) {
                builder.field(fieldNameForURL(), normalisedurl);
            }

            // which metadata to display?
            Map<String, String[]> keyVals = filterMetadata(metadata);

            Iterator<String> iterator = keyVals.keySet().iterator();
            while (iterator.hasNext()) {
                String fieldName = iterator.next();
                String[] values = keyVals.get(fieldName);
                if (values.length == 1) {
                    builder.field(fieldName, values[0]);
                    try {
                        saveStringToFile(indexFile, fieldName + "\t" + values[0]);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else if (values.length > 1) {
                    builder.array(fieldName, values);
                }
            }

            builder.endObject();

            String sha256hex = org.apache.commons.codec.digest.DigestUtils
                    .sha256Hex(normalisedurl);

            IndexRequest indexRequest = new IndexRequest(indexName, docType,
                    sha256hex).source(builder);

            DocWriteRequest.OpType optype = DocWriteRequest.OpType.INDEX;

            if (create) {
                optype = DocWriteRequest.OpType.CREATE;
            }

            indexRequest.opType(optype);

            connection.getProcessor().add(indexRequest);

            eventCounter.scope("Indexed").incrBy(1);

            _collector.emit(StatusStreamName, tuple, new Values(url, metadata,
                    Status.FETCHED));
            _collector.ack(tuple);

        } catch (IOException e) {
            LOG.error("Error sending log tuple to ES", e);
            // do not send to status stream so that it gets replayed
            _collector.fail(tuple);
        }
    }
    private void saveStringToFile(File file, String stringToWrite) throws IOException {
        String pathName = file.getPath();
        File folder = file.getParentFile();

        if (!folder.exists() && !folder.mkdirs()) {
            throw new IOException("Couldn't create the storage folder: " + folder.getAbsolutePath() + " does it already exist ?");
        }

        try (PrintWriter out = new PrintWriter(new FileOutputStream(file, true))) {
            out.append(stringToWrite + '\n');

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

}

A: Have you merged all your configs i.e generic SC + specific ES one into a single es-conf.yaml? If not then your Flux file is probably missing
   - resource: false
     file: "crawler-conf.yaml"
     override: true

where the indexer config typically looks like:
  indexer.url.fieldname: "url"
  indexer.text.fieldname: "content"
  indexer.canonical.name: "canonical"
  indexer.md.mapping:
  - parse.title=title
  - parse.keywords=keywords
  - parse.description=description
  - domain=domain

Not having any md mappings defined would explain why your modified indexer does not write to the files and why the index contains urls but no additional fields.
Please note that the 'index' index (excuse the terminology) does not contain the status of the URL. See https://stackoverflow.com/a/49316316/432844 for an explanation of status vs index.


text:
Q: Is it possible to create .OVR (like by gdaladdo) as smooth as QGIS oversampling feature of raster layer? I found Hugolpz's tutorial for creating a GeoTIFF that contains grayscale with an alpha band.
Creating transparent hillshade?
# filter the color band, keep greyness of relevant shadows below limit
gdal_calc.py -A ./hillshade.tmp.tif  --outfile=./color_crop.tmp.tif \
    --calc="255*(A>220) +      A*(A<=220)"
# filter the opacity band, keep opacity of relevant shadows below limit
gdal_calc.py -A ./hillshade.tmp.tif  --outfile=./opacity_crop.tmp.tif \
    --calc="  1*(A>220) +(256-A)*(A<=220)"
# gdalbuildvrt -separate ./final.vrt ./color_crop.tmp.tif ./opacity_crop.tmp.tif
# gdal_translate -co COMPRESS=LZW -co ALPHA=YES ./final.vrt ./final_crop.tif

I wonder if it's posible to have also the .OVR that contains each zoom level's alpha band? I have tried this
gdaladdo -r bilinear -ro -b 1,2 --config COMPRESS_OVERVIEW DEFLATE --config PREDICTOR_OVERVIEW 2 --config ZLEVEL 9 GrayWithAlpha.tif 2 4 8 16 32 64

I found out that if the command lacks of -b 1,2, it doesn't work at all. Then the result still doesn't match the smoothness of QGIS raster layer oversampling feature. Despite beauty of oversampling, it's very very slow.
So I wonder if I can create .OVR that is as smooth as what presented by QGIS oversampling feature?


text:
Q: ActiveRecord Recover associated records I have an app which models companies that have users who can even have meals.
So I have a Company table, a User table and a Lunch table.
The lunch contains the id of the user, and the user contains the id of the company. I'd like to get all the lunches available for the current_user.company
I'd like to have something like Lunch.all.where(user.company == current_user.company). I know this won't work, but I've just started out and I'm having a little trouble with sql.

A: Try this one
Lunch.joins(user: :company).where(users: {company: current_user.company})

A: You can do this using #joins, or there's an easier way. Set this up in your Company model
class Company
  has_many :users,
  has_many :lunches, through: :users
end

And you get all the lunches:
current_user.company.lunches


text:
Q: vim-snippet: after pressing first tab my snippet does not go to next position in snippet It is a while I am using snippet plugin in vim along with snipMate. I am totally happy with it.
My problem is after pressing the first tab (and autocompletion) I can not jump to next position in a snippet.
I guess maybe some setting in vimrc impede snippet from working.
for example, I want this custom snippet to work properly. It is located in my ./vim/bundle/vim-snippets/snippet/c.snippet
# for (custom)
snippet forr
    for (int ${1:i} = ${2:0}; ${3:$1 < 10}; $1${4:++}){
        ${5}
    }

my .vimrc is here:
 https://github.com/Aznaveh/defaultSetting/blob/master/.vimrc
my .bashrc is also there if any alias caused the problem.

A: The problem is YouCompleteMe addon. Here is a line of my .vimrc
" Trigger configuration. Do not use <tab> if you use https://github.com/Valloric/YouCompleteMe.
let g:UltiSnipsExpandTrigger="<TAB>"

I use Vundle and I had to use :PluginClean to clean that addon


text:
Q: Footer налезает на блок с контентом Здравствуйте, такая проблема: почему-то у меня img как-будто не имеет веса.

.conteiner {
  padding: 0px;
  margin: 25 auto;
  max-width: 900px;
  text-align: center;
  background: #fdfcfc;
  min-height: 100px;
  border-top: 1px solid #000;
  border-bottom: 1px solid #000;
}

.title {
  margin: 25px;
}

h1 {
  margin-bottom: 5px;
  font-size: 30px;
  text-transform: uppercase;
}

.text {
  margin: 10px;
  color: #666;
}

.icons {
  display: block;
  padding-top: 20px;
  padding-bottom: 20px;
}

.icon1 {
  float: left;
  height: 290;
  width: 320;
}

.footer {
  margin: 12 auto;
  width: 150px;
  min-width: 300px;
  text-align: center;
}

Proin iaculis purus consequat sem cure.

Proin iaculis purus consequat sem cure digni ssim. Donec porttitora entum suscipit aenean rhoncus posuere odio in tincidunt.Proin iaculis purus consequat sem cure digni ssim. Donec porttitora entum suscipit aenean rhoncus posuere odio in tincidunt.Proin iaculis purus consequat sem cure digni ssim. Donec porttitora entum suscipit aenean rhoncus posuere odio in tincidunt.

  Copyright 2017

A: Необходимо очистить поток от float: left;
.title:after {
    content: "";
    display: table;
    clear: both;
}

Пример

.conteiner {
  padding: 0px;
  margin: 25px auto;
  max-width: 900px;
  text-align: center;
  background: #fdfcfc;
  min-height: 100px;
  border-top: 1px solid #000;
  border-bottom: 1px solid #000;
}

.title {
  margin: 25px;
}

h1 {
  margin-bottom: 5px;
  font-size: 30px;
  text-transform: uppercase;
}

.title:after {
  content: "";
  display: table;
  clear: both;
}

.text {
  margin: 10px;
  color: #666;
}

.icons {
  display: block;
  padding-top: 20px;
  padding-bottom: 20px;
}

.icon1 {
  float: left;
  height: 290;
  width: 320;
}

.footer {
  margin: 12px auto;
  width: 150px;
  min-width: 300px;
  text-align: center;
}

Proin iaculis purus consequat sem cure.

Proin iaculis purus consequat sem cure digni ssim. Donec porttitora entum suscipit aenean rhoncus posuere odio in tincidunt.Proin iaculis purus consequat sem cure digni ssim. Donec porttitora entum suscipit aenean rhoncus posuere odio in tincidunt.Proin
        iaculis purus consequat sem cure digni ssim. Donec porttitora entum suscipit aenean rhoncus posuere odio in tincidunt.

  Copyright 2017