text:
Q: Getting Exception "Failed to load transport: org/mule/transport D" I am getting below exception in Junit test code in Mule. You can find my mule flow and test code here :Getting "muleContext cannot be resolved" error in mule Junit test code
Can anyone help me to resove this error please.
org.mule.api.registry.ServiceException: Failed to load transport: org/mule/transport D
    at org.mule.registry.MuleRegistryHelper.createServiceDescriptor(MuleRegistryHelper.java:563)
    at org.mule.registry.MuleRegistryHelper.lookupServiceDescriptor(MuleRegistryHelper.java:537)
    at org.mule.endpoint.DefaultEndpointFactory.getEndpointBuilder(DefaultEndpointFactory.java:125)
    at org.mule.endpoint.SimpleEndpointCache.getOutboundEndpoint(SimpleEndpointCache.java:45)
    at org.mule.client.DefaultLocalMuleClient.send(DefaultLocalMuleClient.java:113)
    at org.mule.client.DefaultLocalMuleClient.send(DefaultLocalMuleClient.java:101)
    at fileTestCase.sampleTest.testFile(sampleTest.java:59)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
    at org.junit.internal.runners.statements.FailOnTimeout$StatementThread.run(FailOnTimeout.java:74)

A: You're probably missing the file transport JAR in your build path.


text:
Q: Calling power bi dashboard from c# I have requirement to create a rich ui dashboard dynamically based on user input. Can i call power bi dashboard from my Windows form application ?

A: Here is an example how to do this in WPF application, but the only difference is that InvokeScript method in WPF is in WebBrowser itself, while in WinForms it is in WebBrowser.Document. This example shows how to embed Power BI elements in a native desktop application (WPF, WinForms, etc).
First you need to know that there are two modes for embedding Power BI - user owns data and app owns data. With the first mode, when embedding, the user will authenticate itself using it's own Power BI Pro account, i.e. each of your users needs Power BI Pro license. With the later one, you need only one "master account", which will be used for authentication. The differences in the implementation aren't tremendous, so I will describe app owns data.
You need to do the following:

*

*Register an application - go to dev.powerbi.com/apps and register a native application. Select which permissions to grant it (if you aren't sure, for your first tests simply grant them all). Copy the guid - this is the app ID, a.k.a. client ID.

*Next step is to authenticate from your application and get an access token. Use Azure Active Directory Authentication Library (ADAL) for that - call some of the acquireToken methods of AuthenticationContext class.

*Use this access token to call the Power BI REST API and get the embedUrl of the element you want to embed, e.g. report.

*Use Power BI JavaScript client to actually embed this element. You need to initialize one embed configuration class and pass information about element type (report, dashboard, tile), where to find it (embedUrl), authentication (access token), some other configuration options (show or hide filters pane, navigation, etc.), filters to be applied and so on. In case you will use the access token acquired above, set tokenType to be AAD. This token has many privileges, so for security reasons you may want to use Embed token instead. In this case use the access token to call the REST API again (e.g. Reports GenerateTokenInGroup).

*Call powerbi.embed method of the JavaScript client pass the embedded configuration to visualize this Power BI element in your app.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Launch Dropbox from my app Android I want to call the dropbox app in my app Android using the Intent.
What I have to do???
Thanks!!

A: Try using PackageManager and getLaunchIntentForPackage() with the package name for DropBox, i.e com.dropbox.android. You will get a PackageManager.NameNotFoundException if Dropbox isn't installed.

A: If what you want is to share a file by lauching dropbox , you can use ACTION_SEND  :
Intent intent = new Intent(Intent.ACTION_SEND);
startActivity(Intent.createChooser(intent, "title");

you can also send a specific file :
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType(fileType);
intent.putExtra(Intent.EXTRA_STREAM, Uri.parse(file.getPath()));
startActivity(Intent.createChooser(intent, "title"));

See this article to understand the convention behind ACTION_SEND.


text:
Q: Rounding oddity - what is special about "100"? Does anyone have an explanation for this strange rounding in haskell (GHCi, version 7.2.1). Everything seems fine unless I multiply with 100.
*Main> 1.1
1.1

*Main> 1.1 *10
11.0

*Main> 1.1 *100
110.00000000000001

*Main> 1.1 *1000
1100.0

*Main> 1.1 *10000
11000.0

Edit: what is puzzeling me is that the rounding error only shows when multiplying with 100.
Edit(2): The comments I received made me realize, that this it totally unrelated to haskell, but a general issue with floating point numbers. Numerous questions were already asked (and answered) about floating-point number oddities, where the undelying issue typcally was confusing floats with real numbers.
Perl, python, javascript and C all report 1.1 * 100.0 = 110.00000000000001. Here is what C does
double     10.0 * 1.1 = 11.000000000000000000000000
double    100.0 * 1.1 = 110.000000000000014210854715
double          110.0 = 110.000000000000000000000000
double   1000.0 * 1.1 = 1100.000000000000000000000000

The question "why does this happen only when multiplying with 100" (even though there is a precise representation for 110.0) is still unanswered, but I  suppose there is no simple answer, other than fully stepping through a floating-point multiplication (Thanks to Dax Fohl for stressing that 10 is nothing special in binary)

A: The number 1.1 cannot be represented in finite form in binary. It looks like 1.00011001100110011...
"Rounding errors" are just mathematically inevitable with simple floating-point arithmetic. If you want accuracy, use a Decimal number type.
http://support.microsoft.com/kb/42980

A:
The question "why does this happen only when multiplying with 100" (even though there is a precise representation for 110.0) is still unanswered, but I suppose there is no simple answer, other than fully stepping through a floating-point multiplication

Well, I think there may be things one can say without going to the length of writing the binary multiplication, assuming IEEE 754 arithmetic and the (default) round-to-nearest rounding mode.
The double 1.1d is half a ULP from the real number 1.1. When you multiply it by 10, 100, 1000, and a few more powers of ten, you multiply by a number N that is exactly representable as a double, with the additional property that the result of the real multiplication 1.1 * N is exactly representable as a double, too. That makes 1.1 * N a good candidate for the result of the floating-point multiplication, which we'll write RN(N * 1.1d). But still the multiplication is not automatically rounded to 1.1 * N:
RN(N * 1.1d) = N * 1.1d + E1 with |E1| <= 0.5 * ULP(N*1.1d)

             = N * (1.1 + E2) + E1 with |E2| <= 0.5 * ULP(1.1)

             = N * 1.1 + (N * E2 + E1)

And the question now is how |N * E2 + E1| compares to ULP(N*1.1d), because since we have assumed N * 1.1 is exactly a floating-point number, if the result of the multiplication (which is also a floating-point number) is within 1 ULP of N * 1.1, it has to be N * 1.1.

In short, it is not so much what's special about 100… It is what's special about the real 1.1d * 100, which 1) is close to a power of two while being below it and 2) has an error of the same sign as the error when converting the real 1.1 to double.
Everytime the real N * 1.1d is relatively closer to the nearest inferior power of two than 1.1 is to 1, the result of the floating-point multiplication of 1.1d by N has to be exactly N * 1.1 (I think). An example of this case is N=1000, N*1.1d ~ 1100, just above 1024.
When the real N * 1.1d is relatively closer to the immediately superior power of two than 1.1 is to 2, there may be a floating-point number that represents N * 1.1d better than N * 1.1 does. But if the errors E1 and E2 compensate each other (i.e. have opposite signs), this should not happen.


text:
Q: Who updated the List/Library Columns This is about governance of SharePoint site.. The owners of the SharePoint site are playing with the site and create tickets when they mess it up.. Worst they are playing with the Production sites..
Example:
There was a rule on a number field with Min = 1 and Max = 6, they changed it to Min = 0.3 and Max = 0.6 and created ticket that entering number 1 in the field isn't working..
I don't want to hear about stopping rights or letting them understand the results of their action.. We are working on it..
For now is there a possibility that I can know who updated the List column? or who made the List changes?
Just like this question, but its not an SPFile in this case, does the SPList object has these properties? SharePoint 2010 - last modified by who
If not, what alternatives do I have?
UPDATE
I don't have Central Administration rights on Production server.

A: You can turn on Auditing and look into Audit Log Reports for such events. Following events are available, which can be turned on/off.
•   Opened and downloaded documents, viewed items in lists, or viewed item properties (This event is not available for SharePoint Online sites)
•   Edited items
•   Checked out and checked in items
•   Items that have been moved and copied to other location in the site collection
•   Deleted and restored items
•   Changes to content types and columns
•   Search queries
•   Changes to user accounts and permissions
•   Changed audit settings and deleted audit log events
•   Workflow events
•   Custom events

A: Perhaps someone has a better answer, but get a copy of the log files (pronto, before they're overwritten), and find out who was visiting:
/FldEdit.aspx?List={listguid}&Field=fieldname
or VldSetng.aspx?List={listguid} for validation settings
(Of course, you may need to visit those pages yourself to get the right guids)
The above is the edit page for the field. Of course, they could have visited the page without changing anything...


text:
Q: In Spring, how can I autowire a property of a bean? I'm using Spring 3.2.11.RELEASE.  I have the following bean …
<beans:bean id="customAuthenticationFilter"
    class="org.mainco.subco.core.security.CustomAuthenticationFilter">
    <beans:property name="filterProcessesUrl" value="/j_custom_value" />
    …

From within one of my Spring classes, I'd like to figure out the value of the "filterProcessUrl" property.  I could do something like
@Autowired
private CustomAuthenticationFilter myFilter

…
String value = myFilter.getFilterPRocessesUrl();

but I wanted to see if I could somehow outwore the "filterProcessesUrl" value into a member field (essentially boiling the above two lines of code into one).  How would I go about doing this?


text:
Q: FWER, FDR and multiple comparisons for Beginners Wikipedia:
"In statistics, family-wise error rate (FWER) is the probability of making one or more false discoveries, or type I errors, among all the hypotheses when performing multiple hypotheses tests."
"The false discovery rate (FDR) is one way of conceptualizing the rate of type I errors in null hypothesis testing when conducting multiple comparisons."
I don't understand the difference between these two concepts. How do they not mean the same?
Perhaps you can help me by further elaborating the following example:
Say the probability for an unbiased coin to substantially deviate from a 50/50 head/tail-distribution in a sequence of 1,000 tosses is 0.001.
If I want to find out if one coin is biased I throw it 1,000 times and if it shows heads ~500 times I can be quite sure it is not biased.
However if I throw a million coins 1,000 times and deem those biased who don't show a 50/50-distribution of heads and tails, I will categorize unbiased coins as biased, because the probability of an unbiased coin showing deviating from the 50/50-distribution is multiplied by the number of coins (1 million).
Thus from a set of one million unbiased coins, I have to expect about 1,000,000*0.001=1,000 coins to deviate substantially from the 50% tails, 50% heads-distribution.
As far as I understood this is multiple hypotheses testing (synonymous: multiple comparisons?) as I am testing the hypothesis "coin is unbiased" a million times, and the false discovery rate FDR is 1,000 in this example.
But what, then, is the FWER (family wise error rate)?

A: Part of the reason you're confused may be that you are considering the special case that all null hypotheses are true (i.e. m = m0). When all null hypotheses are true, the FWER and FDR are indeed the same. For m independent tests of true null hypotheses, FDR = FWER = 1-(1-alpha)^m.
The difference comes when some null hypotheses are true and some null hypotheses are false. In that case, the FDR tells you the expected proportion of significant tests (not of all tests) that will be Type I errors. Computing the FDR is then not as simple, because it depends on the proportion of null hypotheses that are false and also on power (the probabilities of significance for the tests of the false null hypotheses).
Neither FWER nor FDR can ever be greater than 1. The value of 1,000 that you computed is a different error rate called the per-family error rate: PFER = alpha*m.


text:
Q: NSURLSessionDownloadTask serial download I am downloading 500 files serially (One by One) Each file is around 4-5 MB size. I have created NSURLSession with backgroundSessionConfigurationWithIdentifier because, my files may download when the app in background mode also.

- (NSURLSession *)backgroundSession
{
    static NSURLSession *session = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:bundleIdentifier];
        configuration.HTTPMaximumConnectionsPerHost = 1;
        configuration.sharedContainerIdentifier = bundleIdentifier;
        session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
    });
    return session;
}

And, i am using NSURLSessionDownloadTask to download the files and once a file downloaded, i am starting a next download on didFinishDownloadingToURL delegate method. And, i have these below lines on my app delegate too.
AppDelegate.h
@property (copy) void(^backgroundSessionCompletionHandler)();
AppDelegate.m
-(void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler{
    self.backgroundSessionCompletionHandler = completionHandler;
}

Here's my question. Once my app goes into background, will my app successfully continue this download process. Have i given all the settings needed for non interrupted download Or i need to enable any other settings more?
Kindly, guide me.


text:
Q: Hierarchy is different in storyboard and when debugged while app is running I have used auto-layout and scrollview. I have created hierarchy in storyboard which looks as shown below :

Basically view has scrollview inside it and scrollview has another subview view1 inside it. Rest of the views are under view1.
While debugging one issue I am facing I show that self.scrollView.subviews prints 3 views. Out of them 2 are ImageViews. And those are not subview of scrollview as per the hierarchy in storyboard.
(lldb) po self.scrollView.subviews
<__NSArrayM 0xb66fe80>(
<UIView: 0xb74b110; frame = (0 0; 320 3240); autoresize = RM+BM; layer = <CALayer: 0xb74b170>>,
<UIImageView: 0xb7e61c0; frame = (313 476; 7 3); alpha = 0; opaque = NO; autoresize = TM; userInteractionEnabled = NO; layer = <CALayer: 0xb7e62a0>>,
<UIImageView: 0xb7e6350; frame = (314.5 3091.5; 3.5 36); alpha = 0; opaque = NO; autoresize = LM; userInteractionEnabled = NO; layer = <CALayer: 0xb7e6430>>
)

What can be wrong here? Ask for any detail you need.

A: The UIView on your console is this view

the 2 UIImageView's are the scroll indicators

And one cool thing to debug view hierarchy is recursiveDescription.
po [self.view recursiveDescription]


text:
Q: How to store range of date? I am developing an analytics tool that track how many time a user spend to do an action.
So I am using this approach:
Database table: id_user ( int ), action ( varchar ), type ( int ), startstop ( datetime )
type can be only 0 or 1 and indicate if the action is started or stopped.

When the user start the action, then a new row is inserted in the database via ajax request ( for example: 1, action_1, 1, 12:22:54 )
When the user stop the action, then a new row is inserted in the database via ajax request ( for example: 1, action_1, 0, 13:31:11 )
Do you think this is a good approach or are there more simple and efficient ways to do this ?

A: Re-write your table fields into id_user ( int ), action ( varchar ), time_start ( datetime ), time_stop ( datetime ) instead.
Update the field time_stop with the current time the action was stopped.


text:
Q: fabric block cloudify bootstrap I am trying to bootstrap an instance of CentOS with cloudify on AWS EC2, but i can't get that happen because i am always interrupted by a fabric error that says: fabric_plugin.tasks.run_module_task' -> Needed to prompt for a connection or sudo password (host: X.X.X.X), but abort-on-prompts was set to True.
I made a simple YAML file to configure the AWS bootstrap, and the .pem public key created after I run the bootstrap command, so basically the fabric should use it with the CentOS EC2 username without prompting for password.
my input.YAML file:
aws_access_key_id: 'XX'
aws_secret_access_key: 'XXXX'

image_id: 'ami-6e37a25e' #ami-e48d6ad7' #ami-45f7ed24'
instance_type: 't2.micro'

ssh_key_filename: '~/.ssh/manager-cle.pem'
agent_private_key_path: ''~/.ssh/client-cle.pem'

manager_security_group_name: 'cloudify-manager-security-group'
agent_security_group_name: 'cloudify-agent-security-group'
manager_server_name: 'cloudify-manager-server'

manager_keypair_name: 'manager-key'
agent_keypair_name: 'agent-key'

A: Usually you are prompted for sudo because one of the following is not valid:

*

*User - make sure that the user you are using exists on the target machine. The user we supply is centos, because that is the default user on the AMI we suggest. I see you've provided your own. I would check what value you are using for "ssh_user" input.

*Key - make sure the path to the key is correct.

*You are using the IP of a different machine.


text:
Q: Unknown GW-BASIC function/syntax: Q(var) = var I'm translating an excessively old GW-BASIC program into JavaScript, and I've come across a piece of syntax that has me stumped.  Note (again): totally not my code, and the variable names are all insane, which is why I'm porting it in the first place.
1380 Z = 1
1390 RATIO = FCO2 /(1-FCO2-10^REFFO2)
1400 AA =(1 - 2*RATIO*(100 / MIXRATIO - 1))/(1 + 2*(100 / MIXRATIO - 1))
1410 PART = LOG(1 - AA)- LOG(100 / MIXRATIO - 1)
1420 FOR I = 1 TO - 1 STEP -2
1430 H = I
1440 W = T + H
1450 GG = 62.110326# - .02144446#*W + 4.720326E-07*(W^ 2)+(- 4.5574288#)*(10^(- 12))*(W^ 3)- 7.343018200000001#*(10^(- 15))*(W^ 4)
1460 KK = EXP(- GG /(R*(W + 273.18)))
1470 Q(Z)= KK
1480 Z = Z + 1
1490 NEXT I
1500 NEWFO21 = LOG(10)*.5*(LOG(Q(1))+ PART):NEWFO22 = LOG(10)*.5*(LOG(Q(2))+ PART)
1510 DELEMFDELT =(FN EMF (TREF + 1,NEWFO21) - FN EMF (TREF - 1, NEWFO22))/2
1520 RETURN

The question mark is line 1470: Q(Z) = KK. Q is defined Q$ earlier in the program as a yes/no input variable, so it makes no sense for me to be putting a float in it.  There's no Q() function defined in the program earlier, and I can't find a reference to a Q() function in GW-BASIC, either.
Any help?

A: As XPDA mentioned, any variable name suffixed with $ is a string.
I wrote some GW-BASIC a few years ago, and thankfully I've still got a lot of the old documentation that was packaged with the compiler.
I've uploaded a copy of the CHM I had archived, you'll probably find some useful information about it in there.
http://www.mediafire.com/?3h9z133ok8wx1l9

A: Q and Q$ are separate variables. Anything with $ is a string variable. Q(Z) is an array of numbers.
The 1 and 2 character names are common because in earlier versions of Basic, variable names were restricted to 2 characters max.


text:
Q: Handling SMILES with metal ions in RDKit I have the following function that takes a dictionary of SMILES strings and converts them to RDKit mol objects.
def smiles_dict_to_mol_list(smiles_dict):
    """smiles dict is a dictionary object containing molecule names
    as keys and smiles strings as values.

    The return value is a list of RDKit mol objects.
    """

    smiles_as_mol = []
    for mol_name, smiles_string in smiles_dict.items():
        try:
            mol = Chem.MolFromSmiles(smiles_string)
            mol.SetProp("_Name", mol_name)
            smiles_as_mol.append(mol)
        except:
            print("Error processing:", mol_name)

    return smiles_as_mol

This function normally works very well and I can convert any SMILES into a mol object, but when I try to convert the below structure I get an exception. I believe that this is because this compound, and others that also give exceptions, have a coordinated metal ion. In this case platinum. It is also possible that the SMILES string I am using is the problem, but I don't know how I would tell the difference.

N2W: COc1cc(cc(c1O)OC)[C@@H]2c3cc4c(cc3[C@H]([C@@H]5[C@H]2C(=O)OC5)NC(=O)CC[C@@H]6C[NH2][Pt]([NH2]6)Cl)OCO4
So my question is: How can I change my RDKit code so I can work with compounds that have metal atoms?

A: The problem is the SMILES not the Pt.
To get a mol from a bad SMILES set the sanitize flag to False.
from rdkit import Chem
from rdkit.Chem.Draw import IPythonConsole
IPythonConsole.molSize = (600,300)
IPythonConsole.drawOptions.addAtomIndices = True

s = 'COc1cc(cc(c1O)OC)[C@@H]2c3cc4c(cc3[C@H]([C@@H]5[C@H]2C(=O)OC5)NC(=O)CC[C@@H]6C[NH2][Pt]([NH2]6)Cl)OCO4'
m = Chem.MolFromSmiles(s, sanitize=False)
m

But now you have a bad molecule.
There a 2 nitrogens with 4 bonds.
problems = Chem.DetectChemistryProblems(m)
for p in problems:
    print(p.Message())

Explicit valence for atom # 32 N, 4, is greater than permitted
Explicit valence for atom # 34 N, 4, is greater than permitted

Addition:
In the RDKit Cookbook there a example how to work with dative bonds.
Tried it with your SMILES and it worked
https://www.rdkit.org/docs/Cookbook.html#organometallics-with-dative-bonds


text:
Q: How does \pgfdecoratedpathlength work? I am trying to understand how it works the decoration pgf module, in order to solve the unanswered question Fiber-Optic-Style decoration.
I am having an hard time with some macros, for example \pgfdecoratedpathlength. Look the following MWE, from what I read on the pgfmanual version 2.10, the options (1), (2) and (3) should be equivalent, but only (2) works, while I get 100 errors for the others.
\documentclass[a4paper]{article}

\usepackage{pgf,pgfsys,pgffor}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\usepackage{tikz}
\usepgfmodule{decorations}
\usetikzlibrary{intersections,arrows,decorations,snakes}

\pgfdeclaredecoration{fiber}{initial}
{
    \state{initial}[
        switch if less than=\pgfdecoratedpathlength/2 to final %% (1)
        %width=\pgfdecoratedpathlength/2 %% (2)
        %width=.5\pgfdecoratedpathlength %% (3)
        ]{
        \pgflineto{\pgfpoint{5pt}{15pt}}
        \pgflineto{\pgfpoint{5pt}{-15pt}}
    }
    \state{final}{
        \pgfpathlineto{\pgfpointdecoratedpathlast}
    }
}

\begin{document}
\begin{tikzpicture}[decoration={fiber, amplitude=1cm}, draw=red]
\draw[->,decorate] (3, 5mm) -- ++(4,0); %% ERROR! Undefined control sequence. <argument> \pgf@decorate@width
\draw[->,decorate] (3,0)    -- ++(3,0);
\draw[->,decorate] (3,-5mm) -- ++(2,0);
\draw[->,decorate] (3,-1cm) -- ++(1,0);
\draw[->,decorate] (3,-1.5cm) -- ++(0.5,0);
\end{tikzpicture}

\end{document}

The first error is Undefined control sequence. <argument> \pgf@decorate@width , in the first draw. Any ideas?

A: You forgot the comma after final. So width=\pgfdecoratedpathlength/2 is dropped and TikZ questioned that how come the width is not defined???
The following code works fine.
\documentclass[border=9,tikz]{standalone}
\usetikzlibrary{decorations}
\pgfdeclaredecoration{fiber}{initial}{
    \state{initial}[
        switch if less than=\pgfdecoratedpathlength/2 to final, %% (1)
        width=\pgfdecoratedpathlength/2 %% (2)
        ]{
        \pgflineto{\pgfpoint{5pt}{15pt}}
        \pgflineto{\pgfpoint{5pt}{-15pt}}
    }
    \state{final}{
        \pgfpathlineto{\pgfpointdecoratedpathlast}
    }
}

\begin{document}
    \begin{tikzpicture}[decoration={fiber, amplitude=1cm}, draw=red]
        \draw[->,decorate] (3, 5mm) -- ++(4,0);
    \end{tikzpicture}
\end{document}


text:
Q: Bridging between mqtt brokers in meteor My question is about mosquitto.conf file while bridging,Well..I am running 2 same meteor apps on different ports on my pc.In which One meteor app contains mosquitto broker running on localhost and the app contains mosquitto broker running on cloud(address:ec2-13-211-229-85.ap-southeast-2.compute.amazonaws.com:1883).Now I have to provide bridge between these mosquitto brokers(between 2 apps) and my topic in this case is 1234567890.I referred so many documents but still I am in confuse.
I have created bridge.conf file in /etc/mosquitto/conf.d directory in ubuntu,bridge.conf file information is as follows:
connection mqtt
address ec2-13-211-229-85.ap-southeast-2.compute.amazonaws.com:1883
topic 1234567890 both
try_private true
clientid test
cleansession true
notification true
bridge_protocol_version mqttv311
bridge_attempt_unsubscribe true
start_type automatic

In the above file if I am not wrong, I gave random name to connection field and clientid field(i.e mqtt and test respectively).
Next,I restarted the mosquitto.Then I checked /var/log/mosquitto/mosquitto.log file which contains below lines:
1527655692: mosquitto version 1.4.8 (build date Thu, 01 Mar 2018 09:34:49 -0500) starting
1527655692: Config loaded from /etc/mosquitto/mosquitto.conf.
1527655692: Opening ipv4 listen socket on port 1883.
1527655692: Opening ipv6 listen socket on port 1883.
1527656884: Error in poll: Interrupted system call.
1527656884: mosquitto version 1.4.8 terminating

Then I used below command in terminal:

mosquitto -c /etc/mosquitto/mosquitto.conf

Again my log output is:
1527655692: mosquitto version 1.4.8 (build date Thu, 01 Mar 2018 09:34:49 -0500) starting
1527655692: Config loaded from /etc/mosquitto/mosquitto.conf.
1527655692: Opening ipv4 listen socket on port 1883.
1527655692: Opening ipv6 listen socket on port 1883.
1527656884: Error in poll: Interrupted system call.
1527656884: mosquitto version 1.4.8 terminating
1527656885: mosquitto version 1.4.8 (build date Thu, 01 Mar 2018 09:34:49 -0500) starting
1527656885: Config loaded from /etc/mosquitto/mosquitto.conf.
1527656885: Opening ipv4 listen socket on port 1883.
1527656885: Opening ipv6 listen socket on port 1883.
1527656885: Connecting bridge mqtt (ec2-13-211-229-85.ap-southeast-2.compute.amazonaws.com:1883)
1527657360: Socket error on client local.test, disconnecting.
1527657391: Connecting bridge mqtt (ec2-13-211-229-85.ap-southeast-2.compute.amazonaws.com:1883)
1527658711: Saving in-memory database to /var/lib/mosquitto/mosquitto.db.
1527658836: New connection from 127.0.0.1 on port 1883.
1527658836: New client connected from 127.0.0.1 as mqttjs_808e4168 (c1, k60).
1527658904: New connection from 127.0.0.1 on port 1883.
1527658904: New client connected from 127.0.0.1 as mqttjs_1ad5b926 (c1, k60).
1527658917: New connection from 127.0.0.1 on port 1883.1527658917: New client connected from 127.0.0.1 as mqttjs_89e1b1cc (c1, k60).
1527658922: New connection from 127.0.0.1 on port 1883.

After this I tried to publish command from one app to other app(both contains different brokers), but other one is not subscribing to
first app. I don't know where I am going wrong or what extra I have to do..


text:
Q: Use a value from SELECT in WHERE So I'm selecting a name and a number of sports that name is related to, and I need to only select them when that number of sports is greater than 1.
SELECT DISTINCT name AS FullName,
      (SELECT COUNT(id) FROM coaches WHERE coaches.name=FullName) AS NrOfSports
FROM coaches WHERE NrOfSports>1

If WHERE is removed the query works just fine and displays all rows of which some have only "1" as NrOfSports. When I add it to the WHERE clause I get an error because it's not recognized. This baffles me since if I were to use it in another SELECT column it would work fine.
Is there a way to do this? It can't be software dependant.

A: Use Group By and Having instead:
SELECT name AS FullName,
   COUNT(id) AS NrOfSports
FROM coaches
GROUP BY name
HAVING COUNT(id) > 1

Your correlated query can work, you just need to move it to a subquery and then you can add the where criteria.  However, I believe the group by would be faster.

A: Error explanation
You're getting an error, because WHERE clause can not access columns by their alias in the very same level. There are two solutions, which I don't recommend, but for the sake of your question I'm attaching:
(1) Move your WHERE NrOfSports > 1 to another level
SELECT *
FROM (
    SELECT DISTINCT
        name AS FullName,
        ( SELECT COUNT(id) FROM coaches c2 WHERE c1.name = c2.name ) AS NrOfSports
    FROM coaches c1
    ) foo
WHERE NrOfSports > 1

(2) Use your condition in the same level.
SELECT DISTINCT
    name AS FullName,
    ( SELECT COUNT(id) FROM coaches c2 WHERE c1.name = c2.name ) AS NrOfSports
FROM
    coaches c1
WHERE
    ( SELECT COUNT(id) FROM coaches c2 WHERE c1.name = c2.name ) > 1

That would fix the error, but it still wouldn't be efficient (!)
Better approach
Instead, you could combine a power of GROUP BY with it's own WHERE clause called HAVING to limit your output only to those names that have more than 1 id.
SELECT DISTINCT
  name AS FullName,
  count(id) AS NrOfSports
FROM
  coaches
GROUP BY
  name
HAVING
  count(id) > 1

A: The answer of sgeddes is better than mine. But you could do also do this query :
    SELECT *
    FROM (
       SELECT DISTINCT name AS FullName,
             (SELECT COUNT(id) FROM coaches WHERE coaches.name=FullName) AS NrOfSports
       FROM coaches
   ) tmp
     WHERE NrOfSports>1


text:
Q: Bash: Difference running a command directly VS from a variable In Bash, when I run echo 'hello', this will output hello, whereas if I put the same command in a variable (i.e., HELLO="echo 'hello'") and run from the variable instead (i.e., $HELLO) the output is 'hello' (note single quotes).
Instead if I run eval $HELLO the output is the same as running echo 'hello' (i.e., the output is hello, without single quotes).
I am trying to understand why running a command from a variable (i.e., $HELLO) behaves differently in Bash.
Thank you.


text:
Q: jquery slider toggles from both direction i have this jquery function what happens is that profilecontain slides from bottom to up then top to bottom . but, when it slides it opens from both direction top and bottom whereas i want it be a smooth slide from bottom to top and top to bottom.
  $(document).ready(function(){
            $("#profilelink").toggle( function(){
                    $("#profilelink").animate({"top": "237px"}, "slow");
                    $("#profilees").animate({"height": "290px", "top": "-165px"}, "slow");
                    //$("#newses").animate({"height": "310px"}, "slow");
                    $("#profilecontain").animate({"height": "270px", 'top': '-154px'}, "slow");
            }, function(){
                    $("#profilelink").animate({"top": "527px"}, 'slow');
                    $("#profilees").animate({"height": "0px", "top": "8px"}, 'slow');
                    $("#profilecontain").animate({"height": "0px", "top": "0px"}, 'slow');
            });
        });


text:
Q: Maintaining git repo containing other cloned git repo I am working on a website using Sharelatex(github) but it contains other repositories that are used to build the main project. I cloned the main repository and did grunt install which is used to download those repositories.
But the problem is that I need to change the code in both main repository and the downloaded ones.
Since these projects can get new updates I want to merge those changes as well. I also need to maintain a repo, but when I push changes to Github it only shows changes in the main repo.
I came across submodules in git but since the main project does not contain any submodule types I am unable to use that.
For example:
There is a repo web used in the main project. I begin with some edits in the files in web. I need these changes to reflect in my remote repository so that others can use them.
Now suppose after some time an important update for web repo is available, how should I use that?
I enter grunt install in the command line to download this repo. It does not create a submodule but clones that repo into my folder, which is subsequently ignored by my main git repo.
The question might seem unclear but I tried my best to explain the problem.
In the nut-shell:

*

*I want not only to perform changes in both main and any other repo that's involved, but pull and merge those other repos, as well, when their updates are available.

*I also need to maintain a remote repo of my project.

A:
I am working on a website using Sharelatex(github) but it contains other repository that are used to build the main project. [...] I came across submodules in git but since the main project does not contain any submodule kind of thing I am unable to use that.

Actually, you do have a submodule.  That's what a nested repository is, and (I'm serious about this) so far as what you need to understand to grok submodules, that's all there is to submodules.  To understand submodules, imagine you have a nested repository (you do) and think about the administrative requirements, what needs to be done to support that setup in a dvcs.
For starters, when people clone a project that uses submodules from some repo you've all decided contains published commits, that clone obviously won't also get the subproject repository (certainly it shouldn't get your private and god-knows-what-you've-done-to-it version).  So they also have to get the subproject repo from some one of its own published repositories.
How do you tell people fetching your commits where to get the necessary subproject commits?  Plainly, you have to drop a note somewhere in a committed file saying "here's a repo that should have any needed $subproject commits".  git submodule has settled on .gitmodules as the conventional place to store notes like this.
Next up: well, what are others to do if the url you handed them goes offline?  They're plainly going to need to use another repo.  Hence, .gitmodules is just suggestions, the git submodule command uses the current values in your .git/config, which git submodule init has populated from the suggested ones in .gitmodules`.
git submodule's operations are all like this.  Forget about it. Don't even bother looking at the command until you need a little assistance doing what you have already found needs doing. Start from the knowledge, the simple fact, that a submodule is nothing more than a nested repo, and the project using it commits nothing more than a commit id that's supposed to be somewhere in that nested repo.  That's it. That's all a submodule is.
As you run across tedious tasks that need doing, look for a git submodule subcommand that does them for you.  You don't have to use the subcommand.  All that subcommand is doing is automating straightforward tasks that would be laborious otherwise.  It's a toolkit for doing whatever it is you need to do, and there's no way on earth it could or should impose some arbitrary and sufficient (<-- that's the hard part) abstraction on everybody in the world. So it's a grab-bag.
That said, there is one important safety play git submodule update and git submodule add perform for you when they do the git clone for you. Repositories conventionally have the actual repo content under the [sub]project toplevel .git, but if you check out a branch that doesn't have that subproject there or otherwise need or want that subproject gone, its  .git will also go away -- not what you want when it holds not just your checked out content but the entire actual repo.  So when git submodule update does its initial clone, it hoists the submodule's .git directory into a handy (and arbitrary) little nook in the containing project's repo, and replaces the .git directory it just moved out of the submodule with a .git file containing the relative path to the moved directory.
To get that initial hoisting done on the repo you currently have, move it out of your current repo, add and update from wherever you put it, and then fix up the upstream urls in .gitmodules for the convenience of others.
There.  Now you know absolutely everything you need to know to understand git submodules and incrementally acquire details only as you find you need them, to understand what the git submodule command is doing for you, and why you don't actually have to care about understanding every little thing on its manpage up front.  At least, I think so.
If I've missed anything important, I'd be very glad of (gentle or blunt, I really don't care) corrections in the comments.


text:
Q: NBConvert PDF/Latex page formatting IPython Got some good advice on suppressing code and other items on NBConvert output,, Here Suppress code in NBConvert? IPython
BUT: now It seems I need to change top and bottom margins And I can see that it seems that it may be set in the sphnix template, (if I even know where it is), which I don't want to mess with but I cannot figure out how to edit the Latex output to get at the margins I attempted to place this in the import headers
\usepackage[margin=0.5in]{geometry}

But nothing happened.. I know squat about latex I am using the TexStudio package to modify the Latex output of NB convert, but at this point I don't see something to modify for margins...
I'm trying to touch up some page flow issues involving placement of output graphs that are just too big so I end up with big ugly blank spots,, pretty sure that if I can get at the margins I can...

A: To change the margins using your proposed code, you have to put this line after the other inputs, e.g. about line 71. If you put it at the top, it will be overridden by another call. With my notebook this works fine.
I'm pretty sure you know you can specify different margins using
\usepackage[left=0.5in, right=0.5in, top=0.5in, bottom=0.5in]{geometry}
see e.g. wikibooks.
Btw. be aware that the sphinx based templates are removed in current master. The new templates are much more customizable and remove some issues due to the mdframed packages (GitHub Issue)


text:
Q: Difference in meaning between converges against and converge to Might be a silly question, but is there any difference between saying that a something (limit, series and so on) converges to a value and converges against a value?

A: From Googling around a bit, it looks like "converges against" is a term which is sometimes (rarely) used by Germans who are translating into English. It seems to be synonymous with "converges to".
It appears to have a alternative but related meaning when considering game theory, but that appears likewise to be very rare.


text:
Q: How to change font of a substring in powerpoint? I want to change every digit in my powerpoint presentation to Times New Roman. I have found the code to change the font of whole textbox but I want to change the font of only the numbers.
I have a PowerPoint Macro VBScript:
Sub use_regex()
    Dim regX As Object
    Dim osld As Slide
    Dim oshp As Shape
    Dim strInput As String
    Dim b_found As Boolean
    Dim iRow As Integer
    Dim iCol As Integer

    Set regX = CreateObject("vbscript.regexp")
    With regX
        .Global = True
        .Pattern = "(\d)"
    End With
    For Each osld In ActivePresentation.Slides
        For Each oshp In osld.Shapes
            If oshp.HasTable Then
                For iRow = 1 To oshp.Table.Rows.Count
                    For iCol = 1 To oshp.Table.Columns.Count
                        strInput = oshp.Table.Cell(iRow, iCol).Shape.TextFrame.TextRange.Text
                        b_found = regX.Test(strInput)
                        If b_found = True Then
                            strInput = regX.Replace(strInput, "$1")
                            oshp.Table.Cell(iRow, iCol).Shape.TextFrame.TextRange = strInput
                        End If
                    Next iCol
                Next iRow
            Else
                If oshp.HasTextFrame Then
                    If oshp.TextFrame.HasText Then
                        strInput = oshp.TextFrame.TextRange.Text
                        b_found = regX.Test(strInput)
                        If b_found = True Then
                            strInput = regX.Replace(strInput, "$1")
                            oshp.TextFrame.TextRange = strInput
                        End If
                    End If
                End If
            End If
        Next oshp
    Next osld
    Set regX = Nothing
End Sub

Source:http://www.pptalchemy.co.uk/PowerPoint_RegEx.html
This is able to identify each digit but how to change its font?

A: I finally did this. Here's the code:
Sub use_regex()
    Dim regX As Object
    Dim osld As Slide
    Dim oshp As Shape
    Dim strInput As String
    Dim b_found As Boolean
    Dim iRow As Integer
    Dim iCol As Integer

    Set regX = CreateObject("vbscript.regexp")
    With regX
        .Global = True
        .Pattern = "(\d)"
    End With
    For Each osld In ActivePresentation.Slides
        For Each oshp In osld.Shapes
            If oshp.HasTable Then
                For iRow = 1 To oshp.Table.Rows.Count
                    For iCol = 1 To oshp.Table.Columns.Count
                        strInput = oshp.Table.Cell(iRow, iCol).Shape.TextFrame.TextRange.Text
                        b_found = regX.Test(strInput)
                        If b_found = True Then

                             Set myMatches = regX.Execute(strInput)
                             For Each myMatch In myMatches
                            oshp.Table.Cell(iRow, iCol).Shape.TextFrame.TextRange.Characters(myMatch.FirstIndex + 1, myMatch.Length).Characters.Font.Name = "Times New Roman"
                            Next
                        End If
                    Next iCol
                Next iRow
            Else
                If oshp.HasTextFrame Then
                    If oshp.TextFrame.HasText Then
                        strInput = oshp.TextFrame.TextRange.Text
                        b_found = regX.Test(strInput)
                        If b_found = True Then

                            Set myMatches = regX.Execute(strInput)
                                For Each myMatch In myMatches
                                    oshp.TextFrame.TextRange.Characters(myMatch.FirstIndex + 1, myMatch.Length).Characters.Font.Name = "Times New Roman"
                                Next

                        End If
                    End If
                End If
            End If
        Next oshp
    Next osld
    Set regX = Nothing
End Sub


text:
Q: Boundary term Ricci tensor Let
$$X = -\frac{1}{2} \nabla^\mu \varphi \nabla_\mu \varphi$$
with $\varphi$ a scalar field. I am trying to show that
$$XR = G_{\mu \nu} \nabla^\mu \varphi \nabla^\nu \varphi$$
up to boundary terms.
My attempt was to write:
\begin{equation}
G_{\mu \nu} \nabla^\mu \varphi \nabla^\nu \varphi = (R_{\mu \nu} - \frac{1}{2}g_{\mu \nu} R)\nabla^\mu \varphi \nabla^\nu \varphi = R_{\mu \nu}\nabla^\mu \varphi \nabla^\nu \varphi - \frac{1}{2}R\nabla^\mu \varphi \nabla_\mu \varphi. \\
\end{equation}
Clearly we need that $R_{\mu \nu}\nabla^\mu \varphi \nabla^\nu \varphi$ is a boundary term. But why is this a boundary term?


text:
Q: Problem with iteration on a string in batchfile FOR Loop I have a batch file that takes some files in different folders.
I want then to analyze the path of those files, and for that I am using an iteration of string.
Here is the problematic part of my code:
REM Put the string of the folder path in "variable_name"
SET variable_name=a
REM Iterate on the string
FOR /F "tokens=* delims=\" %%a IN ("!variable_name!") DO (
     REM I check the result of the iteration
     ECHO %%a
)

For a classic Path folder such as C:\Users\Me\XXX
I would like the return:
C:
Users
Me
XXX

But I got the return:
C:


text:
Q: cakephp auth component, use two models My site has a public section for employees and back end for admin. It uses 2 different models, Employee and Admin.
I want to use Auth component for employee login and admin login. I know how to setup Auth component to use a Model other than default User model. But can i have auth component use 2 models, one for Employee authentication and other for Admin authentication? I am using admin_ prefix routing.
Is this possible? I searched but all i could found was tutorials on howto make Auth component use models other than User model.
Please advise!
EDIT
I use separate login forms for admin login and employee login. Both use the employee controller, but separate actions.

A: http://api.cakephp.org/class/auth-component
check the property authenticate, your answer is there!
and more :
http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html.
Look at authentication handlers!
Here is an example directly from cake page
<?php
// Basic setup
$this->Auth->authenticate = array('Form');

// Pass settings in
$this->Auth->authenticate = array(
'Form' => array('userModel' => 'Member'),
'Basic' => array('userModel' => 'Member')
);

Just put something else instead of Form and Basic and associate the good Model

A: Considering you are using two radio buttons for Employee and Admin. Then you can use the following code into the login method.
 function login()
{
    if ($this->request->is('post'))
    {
        $logged_in = false;
        $login_type = $this->request->data['User']['login_type']
        if ($login_type == 'Admin')
        {
             $this->Auth->authenticate = array('Form' => array('userModel' => 'Admin' ));
        }
        else //if ($login_type == 'Employee')
        {
             $this->Auth->authenticate = array('Form' => array('userModel' => 'Employee' ));
        }
        $this->Auth->constructAuthenticate();
        if ($this->Auth->login())
        {
             $logged_in = true;
                     /*.... Do what you want............*/
        }
    }
}


text:
Q: Php how to get all child nodes under any child node? I have below table with child and parent id's
users
userid   name    parent_user
1        abc      6
2        xyz      1
3        ppp      2
4        mmm      5

I want to get result like below. e.g. i need to show all team member of userid 1, then result should be userid 1,2,3.
userid   name
1        abc
2        xyz
3        ppp

First ,I had tried to get it with below query but it's showing only 1 and 2 userid not 3
SELECT *
FROM users
WHERE userid = 1
UNION
SELECT *
FROM users
WHERE parent_user IN
    (SELECT userid FROM users WHERE userid = 1)

Then i had tried to get it with php, but it's also not working. is there any other way to get it. i had tried many solutions alreday on stack but nothing is working for me.
$sql = $conn->prepare("SELECT * FROM users");
$sql->execute();
$resultDETAILS = $sql->get_result();

while($row = mysqli_fetch_array($resultDETAILS, MYSQLI_ASSOC))
{
    echo $sqlTest = "SELECT * FROM users where parent_user = $row['userid']  or userid = 1";
    $resultATTENDS = $conn->query($sqlTest);
    while($row = mysqli_fetch_array($resultATTENDS, MYSQLI_ASSOC))
    {

        $id[] =  $row['userid'];
    }

}

print_r($id);


text:
Q: Sort for HashMap in Android I have a HashMap and I need sort him by key. What must I do? If you will give me example than I will be glad. Thank you for, anyway.

A: Pick an implementation of SortedMap (for example TreeMap), and :

*

*If your keys implement Comparable use use the copy-constructor (new TreeMap(existingMap)) to put your existing map elements to the sorted map.

*If your keys are not comparable, create the TreeMap with a Comparator and then use treeMap.addAll(existingMap)

A: Use java.lang.TreeMap instead


text:
Q: problem requires condition probability Q. A robot fires 3 shots at a moving target. For the first shot, the probability of hitting the moving target is 1/3. For subsequent shots beyond the first shot, the probability of hitting the moving target is 1/2 if the previous shot is a hit (for example, the probability of hitting the moving target on the 3rd shot is 1/2 if the 2nd shot is a hit) and the probability of hitting the moving target is 1/4 if the previous shot is a miss. What is the mean and variance of the number of hits?
I understand that we can draw a probability tree diagram and find out the possibility of each case, but what i don't understand is how to calculate mean for the number of hits.
some kind of hint would be really helpful

A: Let $X$ be the number of hits. Then $X$ can take on values $0$, $1$, $2$, or $3$.
We want to find the probability of $k$ hits, that is, $\Pr(X=k)$, for $k=0,1,2,3$.
To save space, write for example $hmm$ for hit then miss then miss.
The probability that $X=0$ is the probability of $mmm$. This is $\frac{2}{3}\cdot\frac{3}{4}\cdot\frac{3}{4}$, that is, $\frac{9}{24}$.
There are three ways we can have $1$ hit. They are $hmm$, $mhm$, and $mmh$.
The probabilities are $\frac{1}{3}\cdot\frac{1}{2}\cdot\frac{3}{4}$, $\frac{2}{3}\cdot \frac{1}{4}\cdot\frac{1}{2}$ and $\frac{2}{3}\cdot\frac{3}{4}\cdot\frac{1}{4}$. These add up to $\frac{8}{24}$.
The probability that $X=3$ is $\frac{1}{3}\cdot\frac{1}{2}\cdot\frac{1}{2}$, which is $\frac{2}{24}$.
We skipped $X=2$, because the probabilities must add up to $1$. So the probability that $X=2$ is $\frac{5}{24}$. It might be a good idea to find $\Pr(X=2)$ the long way, by listing cases, as a check.
In summary, $\Pr(X=0)=\frac{9}{24}$ and $\Pr(X=1)=\frac{8}{24}$ and $\Pr(X=2)=\frac{5}{24}$ and $\Pr(X=3)=\frac{2}{24}$.
Now finding the mean is simple:
$$E(X)=\frac{9}{24}\cdot 0+\frac{8}{24}\cdot 1+\frac{5}{24}\cdot 2+\frac{2}{24}\cdot 3.$$
For the variance, if is easiest to use the fact that $\text{Var}(X)=E(X^2)-(E(X))^2$. And we have
$$E(X^2)=\frac{9}{24}\cdot 0^2+\frac{8}{24}\cdot 1^2+\frac{5}{24}\cdot 2^2+\frac{2}{24}\cdot 3^2.$$


text:
Q: Sails.js waterline ORM removing data from multiply models Let's say I have got 2 models.
User and Clubs.
To simplify my problem let's say that User got only Id and Clubs got the ClubId and UserId so one club can have many different users.
Here is my problem :
When I delete for example User with Id 3, I want also to delete all Users from Clubs with this Id 3. How to make it happen?

A: Sails doesn't support cascading deletes yet, but you can handle this yourself:
User.destroy({id:3}).exec(function(err, users) {
   if (err) {return res.serverError();}
   var userIds = users.map(function(user){return user.id;});
   Club.destroy({user_id: userIds}).exec(function(err, clubs) {
      // do something
   });
});

destroy returns an array of all the objects that were destroyed.  In your case, since you're searching by ID, only one would (hopefully) be returned, but if you were using criteria that could destroy several users at once you could still use the above code to wipe out all the related clubs.

A: You can get afterDestroy event after deleting any model. Simple demo as below
In comtroller :
 Company.destroy({id: 12346798})
    .exec(function(e,r){

          return res.json(r);
    });

In Company.js  model :
afterDestroy: function(destroyedCompany, cb) {

    var ids = _.pluck(destroyedCompany, 'id');

    if(ids && ids.length){

         Department.destroy({company_id: ids})
        .exec(function(e,r){
            CompanyArticle.destroy({company_id: ids}).exec(cb);
        });

    }
    else{
        cb();
    }

}


text:
Q: Web application using Razor slow rendering I have a big performance problem in my website when I deploy new code.
I have many views in my website. After deploying new version of code, the first call to my main page take 5 minutes (vs 2 seconds in normal time). When i use a web analyzer like dynatrace i see that i have an application lock. For example : I have this schema :

When i look to the stack details, i saw that i have a lock on these methods :

*

*ViewResultBase.ExecuteResult

*BuildManager.CompileWebFile

*ViewResult.FindView

*RazorView.RenderView
Is that a problem with my views compilation ?
Thank you for your help and your advices.


text:
Q: When configuring CI for a Firebase project, should I use a Firebase token or a GCP service account key? When configuring CI for a Firebase project, I often see references to either a FIREBASE_TOKEN generated with firebase login:ci or a service account key that (I think) is generated by default for each project.
For my particular use case, I want to do the following:

*

*run online tests (with Firestore) against my test project when running npm run test during my CI build

*deploy that code to a different prod project if tests pass

Which one should I use?

A: I would recommend you to use the FIREBASE_TOKEN. As usually, tokens are better to use, as you can quickly cancel or renew in any issue that you might have it, as well it's easier to manage them a service account and to insert them in the code.
Besides that, the official Firebase documentation - Use the CLI with CI systems - indicates and teaches how to use it with the token, so it seems that indeed, using the token is the best and easier option for you to implement.


text:
Q: Codeigniter, Postgresql and keys insensitivity I have one proble. I have my site based on Codeigniter framework, with postgresql database.
If i do this code:
$this->db->select('id');
$this->db->where(array('name' => 'moscow'));
$this->db->get('Cities');

I have empty result.
but in my table i have city with field name = Moscow.
How i can to resolve this problem?
Thanks.

A: Your query is wrong. Remove the from condition. $this->db->get('Cities'); produces:
 SELECT * FROM cities

so no need of an extra from condition. Change your query to :
$this->db->select('id');
$this->db->where(array('name' => 'moscow'));
$this->db->get('Cities');

A: try this code
  $this->db->select('id,name');
  $this->db->from('Cities');
  $this->db->where('name','moscow');

  $sql= $this->db->get();
  if($sql->num_rows()>0)
  {
      return $sql->result();
  }
  else{

      return FALSE;
  }


text:
Q: Erase USB in Disk Utility says "Permission denied" I'm trying to format my USB so I can get all the space back onto it, but every time I try to erase it in Disk Utility, this comes up:

POSIX reports: The operation couldn't be completed. Permission denied

A: Try with diskutil:
diskutil eraseVolume HFS+ "new name" disk1

Replace new name with the name you wish the disk to have, and disk1 with the disk identifier (select disk → Info).

A: Although it may seem unintuitive, try formatting the drive using a Windows computer. Then, take the now (Windows) formatted drive over to the Mac and  format it there - it will work.
It's has happened to me many times too, but the speed of this method has always greatly outweighed any further research time.
I hope that helps you out, however, the question of what causes this error could be one of many... hence, if you need a formatted drive now, this will work.
But do let me know how you get on.


text:
Q: Mock return value of method on mocked ES6 class I'm struggling with mocking a method when mocking an ES6 class, using MockedClass of the jest library.
Example:
export default class CalculatorService {
  constructor() {
    // setup stuff
  }

  public add(num1: number, num2: number): number {
    return num1 + num2;
  }
}

The following works as expected:
import CalculatorService from 'services/calculatorService';
jest.mock('services/calculatorService');
const MockedCalculatorService = CalculatorService as jest.MockedClass<typeof CalculatorService>;

describe('Tests', () => {

    test('Test flow with Calculator service', () => {
        // Arrange

        // Act
        implementation(1,2); // Where CalculatorService is used

        // Assert
        const mockServiceInstance = MockedService.mock.instances[0];
        expect(mockServiceInstance.add).toHaveBeenCalledWith(1,2);
    });
}

But say I wanted to mock add to always return 5, no matter the input.
With jest.Mocked it's done like: MockedService.add.mockReturnValue(5) if I understand it correctly here. But how do I solve it when I've mocked a class?
EDIT: Ismail gave the option to mock the whole implementation in the
jest.mock() invocation. However, in this case, ideally, I'd like to mock the implementation/return value for each test.

A: Here is a rough idea how I have mocked classes
import { mocked } from 'ts-jest/utils';
import { CalculatorService } from 'services/calculatorService';

jest.mock('services/calculatorService', () => {
  return {
    CalculatorService: jest.fn().mockImplementation(() => {
      return {
        add: () => {},
      };
    })
  };
});

describe('Tests', () => {
  const MockedCalculatorService = mocked(CalculatorService, true);

  beforeEach(() => {
   MockedCalculatorService.mockClear();
  });

  it('Test flow with Calculator service', () => {
    const impementingClass = new ImplementingClass();
    expect(MockedCalculatorService).toHaveBeenCalledTimes(1);

    impementingClass.implimentation(1,2);
    expect(MockedCalculatorService.add).toHaveBeenCalledWith(1,2)
  });

}

Note - using npm i ts-jest

A: The following worked, by using jest.spyOn. Not well documented though, so I leave it here for future reference.
describe('Tests', () => {

    test('Test flow with Calculator service', () => {
        // Arrange
        jest.spyOn(MockedCalculatorService.prototype,'add').mockReturnValue(5);

        // Act
        implementation(1,2); // Where CalculatorService is used

        // Assert
        const mockServiceInstance = MockedService.mock.instances[0];
        expect(mockServiceInstance.add).toHaveBeenCalledWith(1,2);
        expect(mockServiceInstance.add).toHaveReturnedWith(5);
}

In my real case, it was an async function that I mocked, and then the following was necessary:
jest.spyOn(MockedCalculatorService.prototype,'add').mockResolvedValue(5);
expect(mockServiceInstance.getRelationsByNobbNrsAsync).toHaveReturnedWith(
    new Promise(() => 5)
);


text:
Q: How do I combine COUNTIF with OR In Google Spreadsheets, I need to use the COUNTIF function on a range with multiple criteria.  So in the table below, I would need to have something like =COUNTIF(B:B,"Mammal"or"Bird") and return a value of 4.
A         |B
-------------------
Animal    | Type
-------------------
Dog       | Mammal
Cat       | Mammal
Lizard    | Reptile
Snake     | Reptile
Alligator | Reptile
Dove      | Bird
Chicken   | Bird

I've tried a lot of different approaches with no luck.

A: One option:
=COUNTIF(B:B; "Mammal") + COUNTIF(B:B; "Bird")

According to the documentation:

Notes
COUNTIF can only perform conditional counts with a single criterion.
  To use multiple criteria, use COUNTIFS or the database functions
  DCOUNT or DCOUNTA.

COUNTIFS: This function is only available in the new Google Sheets.
Example:
=DCOUNTA(B:B; 2; {"Type"; "Mammal"; "Bird"})

A: you can use regex like this:
=ARRAYFORMULA(SUM(N(REGEXMATCH(B:B, "Mammal|Bird"))))

A: You can use QUERY which can be very powerful (and is generally easier to remember, particularly if you came from the DB world) :
QUERY(A:B;"SELECT COUNT(B) WHERE B='Mammal' OR B='Bird'";0)

(0 at the end is used to avoid including header rows if you have such in your range)
Documentation about the QUERY function here : https://support.google.com/docs/answer/3093343?hl=en

A: You can also use ArrayFormula around a SUM(COUNTIFS()) construct:
=ArrayFormula(SUM(COUNTIF(B:B,{"Mammal", "Bird"}))

Source: Google Docs Product Forum


text:
Q: How is it possible to do a live update while a program is running? I wonder how killer applications such as Thunderbird or Firefox can be updated via the system's package manager while they are still running. What happens with the old code while they are being updated? What do I have to do when I want to write a program a.out that updates itself while it is running?

A: The upgrade can be run while the program runs, but the running program you see is actually the old version of it. The old binary remains on the disk until you close the program.
Explanation: on Linux systems, a file is just an inode, which can have several links to it. Eg. the /bin/bash you see is just a link to inode 3932163 on my system. You can find which inode does something link to by issuing ls --inode /path on the link. A file (inode) is only removed if there are zero links pointing to it and is not in use by any program. When the package manager upgrades eg. /usr/bin/firefox, it first unlinks (removes the hard link /usr/bin/firefox), then creates a new file called /usr/bin/firefox that is a hardlink to a different inode (the one which contains the new firefox version). The old inode is now marked as free and can be reused to store new data but remains on the disk (inodes are only created when you build your filesystem and are never deleted). On the next start of firefox, the new one will be used.
If you want to write a program that "upgrades" itself while running, the only possible solution I can think of is to periodically check the timestamp of its own binary file, and if it's newer than the program's start time, then reload itself.

A: Replacing files in general
First, there are several strategies to replace a file:

*

*Open the existing file for writing, truncate it to 0 length, and write the new content. (A less common variant is to open the existing file, overwrite the old content with the new content, truncate the file to the new length if it's shorter.) In shell terms:
echo 'new content' >somefile

*Remove the old file, and create a new file by the same name. In shell terms:
rm somefile
echo 'new content' >somefile

*Write to a new file under a temporary name, then move the new file to the existing name. The move deletes the old file. In shell terms:
echo 'new content' >somefile.new
mv somefile.new somefile

I won't list all the differences between the strategies, I'll just mention some that are important here. With stategy 1, if any process is currently using the file, the process sees the new content as it's being updated. This can cause some confusion if the process expects the file content to remain the same. Note that this is only about processes that have the file open (as visible in lsof or in /proc/PID/fd/; interactive applications that have a document open (e.g. opening a file in an editor) usually do not keep the file open, they load the file content during the "open document" operation and they replace the file (using one of the strategies above) during the "save document" operation.
With strategies 2 and 3, if some process has the file somefile open, the old file remains open during the content upgrade. With strategy 2, the step of removing the file in fact only removes the file's entry in the directory. The file itself is only removed when it has no directory entry leading to it (on typical Unix filesystems, there can be more than one directory entry for the same file) and no process has it open. Here's a way to observe this — the file is only removed when the sleep process is killed (rm only removes its directory entry).
echo 'old content' >somefile
sleep 9999999 <somefile &
df .
rm somefile
df .
cat /proc/$!/fd/0
kill $!
df .

With strategy 3, the step of moving the new file to the existing name removes the directory entry leading to the old content and creates a directory entry leading to the new content. This is done in one atomic operation, so this strategy has a major advantage: if a process opens the file at any time, it will either see the old content or the new content — there's no risk of getting mixed content or of the file not existing.
Replacing executables
If you try strategy 1 with a running executable on Linux, you'll get an error.
cp /bin/sleep .
./sleep 999999 &
echo oops >|sleep
bash: sleep: Text file busy

A "text file" means a file containing executable code for obscure historical reasons. Linux, like many other unix variants, refuses to overwrite the code of a running program; a few unix variants allow this, leading to crashes unless the new code was a very well though-out modification of the old code.
On Linux, you can overwrite the code of a dynamically loaded library. It's likely to lead to a crash of the program that's using it. (You might not be able to observe this with sleep because it loads all the library code it needs when it starts. Try a more complex program that does something useful after sleeping, like perl -e 'sleep 9; print lc $ARGV[0]'.)
If an interpreter is running a script, the script file is opened in an ordinary way by the interpreter, so there is no protection against overwriting the script. Some interpreters read and parse the whole script before they start executing the first line, others read the script as needed. See What happens if you edit a script during execution? and How Does Linux deal with shell scripts? for more details.
Strategies 2 and 3 are safe for executables as well: although running executables (and dynamically loaded libraries) aren't open files in the sense of having a file descriptor, they behave in a very similar way. As long as some program is running the code, the file remains on disk even without a directory entry.
Upgrading an application
Most package managers use strategy 3 to replace files, because of the major advantage mentioned above — at any point in time, opening the file leads to a valid version of it.
Where application upgrades can break is that while upgrading one file is atomic, upgrading the application as a whole isn't if the application consists of multiple files (program, libraries, data, …). Consider the following sequence of events:

*

*An instance of the application is started.

*The application is upgraded.

*The running instance application opens one of its data files.

In step 3, the running instance of the old version of the application is opening a data file from the new version. Whether this works or not depends on the application, of which file it is and how much the file has been modified.
After an upgrade, you'll note that the old program is still running. If you want to run the new version, you'll have to exit the old program and run the new version. Package managers usually kill and restart daemons on an upgrade, but leave end-user applications alone.
A few daemons have special procedures to handle upgrades without having to kill the daemon and wait for the new instance to restart (which causes a service disruption). This is necessary in the case of init, which cannot be killed; init systems provide a way to request that the running instance call execve to replace itself with the new version.

A: I wonder how killer applications such as Thunderbird or Firefox can be updated via the system's package manager while they are still running?
Well, I can tell you that this doesn't really work well... I've had Firefox break on me quite horribly if I left it open while a package update was running. I had to kill it forcefully sometimes and restart it, because it was so broken I couldn't even close it properly.
What happens with the old code while they are being updated?
Normally on Linux a program is loaded into memory, so the executable on disk isn't needed or used while the program is running. In fact you can even delete the executable and the program shouldn't care... However, some programs may need the executable, and certain OSs (like Windows) will lock the executable file, preventing deletion or even renames/moves, while the program is running. Firefox breaks, because its actually quite complex and uses a bunch of data files that tell it how to build its GUI (user interface). During a package update these files get overwritten (updated), so when an older Firefox executable (in memory) tries to use the new GUI files, weird things can happen...
What do I have to do when I want to write a program a.out that updates itself while it is running?
There are lots of answers to your question already. Check this out:
https://stackoverflow.com/questions/232347/how-should-i-implement-an-auto-updater
By the way, questions about programming are better off on StackOverflow.


text:
Q: Why isn't my function returning a value from the innermost then()/catch() promises? The code below adds a document into the current user's friends collection and the target user's friends collection. This part is working fine, but I'm having an issue with returning a value to the client. I've ensured that the client code is working fine, but I don't quite yet understand Typescript well enough to know what I'm doing wrong here.
What the code currently does:
The code returns 69 and the current user's uid.
What the code needs to do:
The code needs to return the appropriate return values based on wherever it ends up. In the Firebase console, I see that the code executes all the way up to the line console.log('_addFriend Finished adding friend.'). The two lines after that assign return values 1 and Friend request sent!, but the client doesn't receive these values. Why isn't the code returning these?
exports.addFriend = functions.https.onCall(async (data, context) => {
  console.log('_addFriend: ');
  const uid1 = context?.auth?.uid as string //current user
  const targetUser = data.targetUser
  var username1: string = ''
  var returnVal: number = 69
  var returnMsg: string = uid1

  if (uid1) {
    var uid2: string;
    const currentUsersFriendsColl = 'friends_' + uid1
    await TS_doesUserExist(targetUser)
    .then(result => {
      if (result[0] == 1) {
        console.log('_addFriend: targetUser ', targetUser, ' exists.')
        uid2 = result[1]
        const targetUsersFriendsColl = 'friends_' + uid2
        TS_getUserInfo('uid', uid1, 'username')
        .then(getUserInfo_result => {
          console.log('_addFriend getUserInfo_result is about to be evaluated')
          console.log('_addFriend getUserInfo_result[0]: ', getUserInfo_result[0])
          if (getUserInfo_result[0] == 1) {
            console.log('_addFriend getUserInfo_result[0]=1')
            username1 = getUserInfo_result[1]
            //Insert into current user's friends list
            const currentUserDoc = admin.firestore().collection(currentUsersFriendsColl).doc();
            currentUserDoc.set({
              createDate: admin.firestore.FieldValue.serverTimestamp(),
              modifiedDate: admin.firestore.FieldValue.serverTimestamp(),
              stat: 2, //pending
              friendUID: uid2,
              friendUsername: targetUser,
            })
            .then(() => {
              console.log('_addFriend: About to insert into target users friends collection')
              //Insert into target user's friends list
              const friendsDoc = admin.firestore().collection(targetUsersFriendsColl).doc();
              friendsDoc.set({
                createDate: admin.firestore.FieldValue.serverTimestamp(),
                modifiedDate: admin.firestore.FieldValue.serverTimestamp(),
                stat: 2, //pending
                friendUID: uid1,
                friendUsername: username1,
              })
              .then(() => {
                console.log('_addFriend Finished adding friend.')
                returnVal = 1
                returnMsg = 'Friend request sent!'

              })
              .catch((error) => {
                console.log('_addFriend error adding to target users friends collec: ', error)
                returnVal = 0
                returnMsg = 'Error all the way inside: ' + error

              })

            })
            .catch(error => {
              console.log('_addFriend error: ', error)
              returnVal = 0
              returnMsg = 'Error1: ' + error

            })

          } else {
            console.log('_addFriend: In else, result was 0.')
            returnVal = 0
            returnMsg = 'Current user does not exist.'

          }

        })
        .catch(error => {
          console.log('_TS_getUserInfo error: ', error)
          returnVal = 0
          returnMsg = 'Could not find current user info.'

        })

      } else {
        console.log('_TS_doesUserExist: targetUser ', targetUser, ' does not exist.')
        returnVal = result[0]
        returnMsg = result[2]

      }

    })
    .catch(error => {
      console.log('_TS_doesUserExist error: ', error)
      returnVal = 0
      returnMsg = 'Error2: ' + error

    });

  }
  else {
    console.log('_addFriend error: User is not authorized');
    returnVal = 0
    returnMsg = 'User is not authorized.'
  }
  return {result: returnVal, message: returnMsg}
});

A: A question I have in regards to what you are seeing on your end, does the console statement happen AFTER the client gets the 69 and other values?
I believe at the location where you are calling TS_getUserInfo inside the TS_doesUserExist then might be where your problem is. You'll need to return that promise chain if you want it to be awaited by the await for TS_doesUserExist.
Then just to explain what I believe I am seeing, if I am reading the nesting right, is that you are:

*

*Calling await on TS_doesUserExist

*The main block stops there. Waits for TS_doesUserExist to process

*It then enters the then block and invokes your TS_getUserInfo function

*After invoking the TS_getUserInfo function the original promise from  TS_doesUserExist resolves

*Main block continues and sends the message to the client

*Main block finishes allows event loop to loop back around to TS_getUserInfo

*TS_getUserInfo resolves, enters then block prints your log and assigns values

So from that, returning TS_getUserInfo should allow it to be awaited your original await as it will then become part of the TS_doesUserExist promise chain and resolve your console and values prior to sending the message to the client.
Abbreviated code example of what I believe needs to happen:
exports.addFriend = functions.https.onCall(async (data, context) => {
  const targetUser = data.targetUser;
  var returnVal: number = 69;
  var returnMsg: string = uid1;

  if (uid1) {
    await TS_doesUserExist(targetUser)
      .then(result => {
        //...other code you want to process before calling TS_getUserInfo...

        // This is where I believe you need your return
        return TS_getUserInfo('uid', uid1, 'username')
          .then(() => {
            console.log('_addFriend Finished adding friend.')
            returnVal = 1
            returnMsg = 'Friend request sent!'
          });
    });
  }

  return {result: returnVal, message: returnMsg}
});

Documentation from MDN on the promise.then function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
The chaining section there should give some more insight into that functionality as well.


text:
Q: How to highlight the selected item with image in DrawerLayout I am working on Xamarin. android where I need to highlight the selected item as in following image.
I can able to highlight the selected item as following.
private async void OnMenuSelection(IMenuItem menuItem)
    {
        menuItem.SetCheckable(true);

    }

By adding menuItem.SetCheckable(true)  can able highlight but I need to add that blue color too at left hand side for selection.
Is there any way to do add such a way?
My layout is:
 <android.support.design.widget.NavigationView
  android:id="@+id/questiontypes_nav_view"
  android:layout_width="220dp"
  android:ellipsize="end"
    android:layout_below="@+id/navigation_drawer_top"
  android:maxLines="1"
    android:scrollbars="none"
      android:layout_above="@+id/navigation_drawer_bottom"
    android:nestedScrollingEnabled="true"
      android:layoutDirection="ltr"
  android:layout_height="match_parent"
    app:theme="@style/NavigationDrawerStyle"
  android:background="#031d2c"
  android:fitsSystemWindows="true"
  app:itemTextAppearance="?android:attr/textAppearanceSmall"
  app:itemTextColor="@android:color/white"
  app:itemBackground="@drawable/nav_item_drawable"
app:itemIconTint="@drawable/nav_item_drawable">


text:
Q: Couldn't installl NtopNG on Ubuntu 18.04 x64 I tried to install NtopNg on Ubuntu 18.04. Got in the below error.
apt-get install pfring-dkms nprobe ntopng n2disk cento -y
    Reading package lists... Done
    Building dependency tree
    Reading state information... Done
    cento is already the newest version (1.11.191119-528).
    n2disk is already the newest version (3.3.191119-5173).
    nprobe is already the newest version (8.7.191119-6669).
    pfring-dkms is already the newest version (7.5.0).
    The following package was automatically installed and is no longer required:
      libndpi5
    Use 'sudo apt autoremove' to remove it.
    The following NEW packages will be installed:
      ntopng
    0 upgraded, 1 newly installed, 0 to remove and 1 not upgraded.
    Need to get 0 B/9,043 kB of archives.
    After this operation, 47.8 MB of additional disk space will be used.
    Preconfiguring packages ...
    (Reading database ... 74204 files and directories currently installed.)
    Preparing to unpack .../ntopng_3.9.191119-8152_amd64.deb ...
    Unpacking ntopng (3.9.191119-8152) ...
    dpkg: error processing archive /var/cache/apt/archives/ntopng_3.9.191119-8152_amd64.deb (--unpack):
     trying to overwrite '/usr/share/ntopng/httpdocs/css/bootstrap-datetimepicker.css', which is also in package ntopng-data 3.2+dfsg1-1
    dpkg-deb: error: paste subprocess was killed by signal (Broken pipe)
    Errors were encountered while processing:
     /var/cache/apt/archives/ntopng_3.9.191119-8152_amd64.deb
    E: Sub-process /usr/bin/dpkg returned an error code (1)

A: Run sudo apt remove ntopng-data then try again.  You've got conflicting packages trying to write to the same file, which is a Bad Thing.


text:
Q: Prove $S$ has a least element. Can anyone help me with my proof, please? I only got half points, but my professor won't tell me what I am doing wrong. My proof is:

Let $z$ $\in \mathbb{Z}$. If $S$ is a nonempty set of integers that are all greater than or equal to $z$, then $S$ has a least element.

And this is what I have:
First note that $S$ is the nonempty set of integers greater than or equal to $z$. We will create and use the alternative set $Q$, where $Q=\{x\in \mathbb{Z}\mid x=g+(-z), g\in S\}$ for some integer $g$. $Q$ is in the set of whole numbers because all elements of $S$ are greater than $z$ and $g$ is in $S$, so our lowest possible result from this is zero, therefore $Q$ is in the set of whole numbers and know it has a least element because of the least ordering principle and the set of whole numbers non-empty and positive. Since we added -$z$ to $S$ to get to the set of whole numbers, we must add $z$ to get back to the set of integers. Since $g+(-z)$ was the least element in the set $Q$ and we added $z$ to get back to the set $S$, we suspect that $k+z$ is the least element in $S$ for some integer $k \in S$. We must now prove $k+z \in S$, and we will do this by using proof by contradiction. That is, we will assume $k+z$ is less than some integer $r$ in $S$ and show that $k+z$ is not less than or equal to $r$. We begin with $r>k+z$. We begin by subtracting $z$ from both sides to get $r-z>k$. Since both $k$ and $r$ are in $S$, they are greater than or equal to $z$, so $r-z$ would be less than $k$ and we have come to a contradiction of our assumption that $k+z$ is less than some integer $r$ in $S$ which proves $k+z$ is the least element in $S$ and completes the proof.

A: You never picked what the least element was. Let's say you meant for $k$ to be the least element. What you then want to prove is not that $k+z\in S$, which is obvious, but rather that $k+z$ is the least element of $S$. You seem to have attempted to do that, but never succeeded.
I'm not sure exactly what you're trying to say with "We will assume $k+z$ is less than some integer $r$ in $S$ and show that $k+z$ is not less than or equal to $r$." But you want $k+z$ to be less than or equal to $r$. Perhaps you meant that $k+z$ is less than $r$, but this need not be true as we could take $r=k+z$. Reading before that, you assume that $k+z$ is less than $r$ from the outset, which is what you actually want to show.
The way to complete it would be to prove that if $r\in S$, then $k+z\leq r$. To do this, we note that $k\leq r-z$ because $r-z\in Q$ and $k$ is the least element of $Q$, hence $k+z\leq r=(r-z)+z$.

A: If z is in S then we are done.
If z is not in S, then see if z+1 is in S. If so then z+1 is the least element. Else see if z+2 is in S. If so then it is the least element. Keep adding 1 until you get an element in S.
If you keep adding 1 and never reach an element in S then S is not a nonempty set of integers all >= k, a contradiction.
Therefore, if you keep adding 1 to k, you will, at some point, get to the lowest integer in S.

A: Let $S=P \cup N$, where $P$ is the set of non-negative elements of $S$ and $N$ is the set of negative elements of $S$.  If $N \neq \emptyset$, then $N$ is finite so it has a least element.  Moreover, every element of $N$ is less than every element of $P$, so the least element of $N$ is necessarily the least element of $S$.
If $N = \emptyset$, then $P \neq \emptyset$.  Since $P$ is a non-empty set of natural numbers, by the well-ordering principle $P$ has a least element, and since $N = \emptyset \Rightarrow P=S$, that means $S$ has a least element.
The problem with your proof is that you have not defined $S$ correctly.  You have defined it as all integers $k \geq z$.  That's not correct.  Although all of the elements of $k \in S$ have the property $k \geq z$, as $S$ is defined in the problem, it's not in general true that $S$ contains all such integers.
For example, it's possible that $z=-5$ and $S=\{3, 8\}$.  You're trying to define it as $T= \{ k \in \Bbb Z \mid k \geq z \} = \{-5, -4, -3, \ldots \}$, and while it's true that $S \subset T$ and you have proved the result for $T$, the inclusion can be proper so you haven't yet proved it for all possible $S$.


text:
Q: Creating a DLL for Windows Store 8.1 Apps I'm attempting to create a DLL written in C# that will utilize Windows 8.1 packages such as Windows.Storage and Windows.Media. The DLL compiles using csc.exe when not including the classes that utilize the Windows packages.
When trying to compile the entire DLL (including the extra classes) I add the /r:"C:\Program Files (x86)\Windows Kits\8.1\References\CommonConfiguration\Neutral\Windows.winmd" compiler option to include the missing Windows packages. The compiler then throws this error:

c:\Program Files (x86)\Windows Kits\8.1\References\CommonConfiguration\Neutral\Windows.winmd: error CS0012: The type 'System.Attribute' is defined in an
          assembly that is not referenced. You must add a reference to assembly
          'System.Runtime, Version=4.0.0.0, Culture=neutral,
          PublicKeyToken=b03f5f7f11d50a3a'.

However when I try to include C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5\System.Runtime.dll the compiler gives error CS0433 for nearly every class that I use stating that The type '...' exists in both '...\mscorlib.dll' and '...\Runtime.dll'.
Is there a way to only include the the necessary packages from the Runtime.dll? Or is there an entirely different way to easily compile this DLL?

A: To fix this, add a reference to the System.Runtime.dll facade. Typically, this facade is at C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.1\Facades\System.Runtime.dll.
The underlying issue here is that different .NET implementations define the System.Attribute type on different assemblies. However, the .NET/Windows type projection layer– the glue that makes Windows Runtime types look like normal .NET types – and the compiler expect System.Attribute to be defined in System.Runtime.dll. This is true for some .NET implementations, but it isn't true for the in-box .NET Framework that comes with Windows.
The facade referenced above provides a pointer to the compiler that the implementation for System.Attribute is really in System.dll for this implementation.


text:
Q: Who hid the collection of ancient Jedi texts in the millenium falcon? Did Yoda know about them when he destroyed the tree? In the film's close moment we can see that Rey possesses the books, as they are stowed away on the Millennium Falcon. But did she put them there?
Did Yoda know something about it? And why didn't anyone tell Luke about them?


text:
Q: (x < 8) returns false when x = -3 (double) Code reads as follows:
if (chan->sampcnt < 8)
{
    *data = 0;
    return;
}

chan contains a pointer to a valid structure.  In the debugger, the value listed for `chan->sampcnt is -3.  Somehow it does not resolve the conditional as false and execute the code in the if statement's scope.  This is only the case very rarely, but it constitutes a major bug.
sampcnt's default value, -3, is run through this conditional many times.  It almost always resolves correctly, but when it does not things get ugly fast.  What the heck is happening?  I am at a loss for words.  I have never encountered anything like this before.  Thanks in advance.
Update (to encourage reopening):
struct channel_struct
{
    channel_struct()
    {}
    u32 num;
   u8 vol;
   u8 datashift;
   u8 hold;
   u8 pan;
   u8 waveduty;
   u8 repeat;
   u8 format;
   u8 keyon;
   u8 status;
   u32 addr;
   u16 timer;
   u16 loopstart;
   u32 length;
   u32 totlength;
   double double_totlength_shifted;
   double sampcnt;
   double sampinc;
   // ADPCM specific
   u32 lastsampcnt;
   s16 pcm16b, pcm16b_last;
   s16 loop_pcm16b;
   int index;
   int loop_index;
   u16 x;
   s16 psgnoise_last;
};

This is a multi-threaded application.  I am not familiar with all the code as it is a large, complex project.  I have suspected sampcnt being changed in another thread, but when the bug occurs it demonstrates a shocking amount of regularity.  This makes me lean away from some sort of atomicity hiccup; however, it is still a consideration.  I have yet to identify code that modifies chan->sampcnt being run in another thread, but it could be out there.
Just to be clear.  sampcnt is of type double and I am sure.  It is declared as double and the debugger lists it as double.  Also, chan is a pointer to type struct channel_struct.

A: It's possible that you are occasionally overwriting chan->sampcnt, so that it isn't really -3 when it fails ... this is a common problem, especially if chan points to malloced memory. You really haven't given nearly enough info, nor done enough debugging. You could, for instance, save the value of chan->sampcnt in a global variable before doing the test, and then when things go bad check that value to see if it's really what you expected it to be. The last thing you should do is assume that there's a bug in compiler or the hardware ... it's almost certainly in your program.

A: Rewriting it to the following form should give the compiler a fighting chance to point out the problem.
double toTest = chan->sampcnt;
if ( toTest < 8)
{
    *data = 0;
    return;
}

A: int test = (int)chan->sampcnt;
if ( test < 8)
{
   *data = 0;
   return;
}

maybe chan->sampcnt is unsigned type


text:
Q: What is the proper formula for calculating the future value of compound interest with end of period deposits I'm trying to recreate this app. However, for cases where the frequency of deposits do not match the compounding periods, my fuction's output doesn't match the linked app's output for the total value of investment.
Here's my function...
def compound_interest(principal, pmt, rate, frequency, period, time):

    contribution_frequencies = {'weekly' : 52, 'biweekly' : 26, 'monthly' : 12, 'quarterly' : 4, 'semiannually' : 2, 'yearly' : 1}
    compounding_periods = {'monthly' : 12, 'quarterly' : 4, 'semiannually' : 2, 'yearly' : 1}

    frequency = contribution_frequencies[frequency]
    period = compounding_periods[period]

    rate = rate / 100

    principal_interest = principal * (1 + (rate / period)) ** (period * time)
    fv =  (pmt * frequency) / period  * ((1 + (rate / period)) ** (period * time) - 1) / (rate / period)

    total = principal_interest + fv

    return round(total, 2)

Here's my tests where the frequency of deposits are the same as the compounding periods...
print(compound_interest(5000, 100, 5, 'monthly', 'monthly', 15))
print(compound_interest(5000, 100, 5, 'yearly', 'yearly', 15))
print(compound_interest(5000, 100, 5, 'quarterly', 'quarterly', 15))
print(compound_interest(5000, 100, 5, 'semiannually', 'semiannually', 15))

The returned actual values below from my function are the same as the actual values i get from the linked app's output...
37297.41
12552.5
19393.36
14878.11

For cases other than the above, the actual values of the tests are not the same as that of the linked app. E.g....
print(compound_interest(5000, 100, 5, 'weekly', 'monthly', 15))

returns...
126393.73

whereas the linked app returns...
126579.19

Keep in mind my equation calculates for additional deposits made at the end of a compounding period (or so it it says) which seems to be the same as that of the linked app.
How would I rewrite my function so that its actual values returned are the same as that of the linked app's actual values for all combinations of frequency of deposits and compounding periods?
Thanks!

A: I think I see the error in the function. Usually (that is, when compounding and additional contributions take place at the same frequency), the compounding period rate is indeed rate/period. So a nominal annual rate of 5%, compounded quarterly, for example, can be divided by 4 for quarterly compounding (i.e., 1.25% per quarter - which is the rate), resulting in an effective annual rate of 5.095%.
However, when the contribution period is changed to monthly, for example, without an equivalent change in the compounding period, the effective annual rate stays the same. So just dividing the the nominal rate by 12 (so that the rate is 0.41667%) overstates the interest you earn.
To get to the actual monthly rate when the compounding is quarterly, you need to calculate the monthly IRR of the same investment (without contributions) resulting in a future value after one year equal to the future value of the same investment (without contributions) using the effective interest rate of quarterly compounding (at least that's the only way I can think of).
So for example, the future value of $1,000, with a nominal annual 5% interest, compounded quarterly (and no contributions) is $1,050.95 (that reflects the effective annual rate mentioned above). To get the same future value with the same interest rate but with monthly compounding, your monthly rate is 0.41494%, which is less than the rate you get by dividing the nominal annual rate by 12. If you check this scenario on the calculator site, this is the result you'll see.
To do it right, you'll have to develop formulas for converting between each pair of compounding/contribution period (semiannual/monthly, semiannual/quarterly, etc.). These may exist out there, but I couldn't find them. Once you have these formulas, you'll have to incorporate them into your function.
Finally, to make things even more complicated, you'll have to deal with the problem of the weekly calculations. While each year is divisible into exactly 4 quarters and 12 months, it's not divisible into exactly  52 weeks. So, for example, 15 years have 782.143 weeks, not 780. That has to be taken into account separately.
Hopefully - if you're still trying to do it - this won't get you to quit. It is an interesting project, after all.