text:
Q: RightFax 10.0 Integration With C# If I insert the values into the corresponding tables of RightFax, does it FAX automatically or do i need to write the following code for that?
RFCOMAPILib.FaxServerClass faxserver = new RFCOMAPILib.FaxServerClass();
faxserver.ServerName = "ServerName";
faxserver.Protocol = RFCOMAPILib.CommunicationProtocolType.cpNamedPipes;
faxserver.UseNTAuthentication = RFCOMAPILib.BoolType.True;
faxserver.OpenServer();

RFCOMAPILib.Fax fax = (RFCOMAPILib.Fax) faxserver.get_CreateObject(RFCOMAPILib.CreateObjectType.coFax);

// set up your 'fax' object the way you want it, below is just some sample options
fax.ToName = "John Doe";
fax.ToFaxNumber = "4255551111";
fax.ToVoiceNumber = "4255550000";
fax.ToCompany = "ACME";
fax.FromName = "My Company";
fax.FromVoiceNumber = "4255552222";

fax.Send();

Can you please provide me sample code for attachments? If RightFax sends the FAX automatically then which tables do I need to fill-in in order to do that?
Thanks

A: the below code is vb.net but will show you how to send a fax and add attachment as well, hope this helps. I've written a post about this here  but here's the code below ....
Dim FaxAPI As RFCOMAPILib.FaxServer
Dim fFax As RFCOMAPILib.Fax
FaxAPI = New RFCOMAPILib.FaxServer
FaxAPI.ServerName =something
FaxAPI.Protocol = RFCOMAPILib.CommunicationProtocolType.cpTCPIP
FaxAPI.UseNTAuthentication = RFCOMAPILib.BoolType.False
FaxAPI.AuthorizationUserID = something
FaxAPI.AuthorizationUserPassword = something
FaxAPI.OpenServer()
fFax = FaxAPI.CreateObject(RFCOMAPILib.CreateObjectType.coFax)
fFax.Attachments.Add("D:\FilePickupIn\2222222222-20110322142718-01.tif")
fFax.HasCoversheet = RFCOMAPILib.BoolType.False
fFax.ToFaxNumber = something
fFax.ToName = something
fFax.Send()
FaxAPI.CloseServer()
FaxAPI = Nothing
fFax = Nothing

happy to help if you get stuck with anything...


text:
Q: Hover on mouse over rather than show transition on mouse out I am trying to make the images on my webpage show a different colour when I hover over them. Instead what is happening is that the images have this transparent colour and its showing the original picture when I hover over them.
Please can someone help with this:
.service-style-1 .service-perview figcaption {
  position: absolute;
  width: 100%;
  height: 100%;
  -webkit-border-radius: 50%;
  -moz-border-radius: 50%;
  -o-border-radius: 50%;
  -ms-border-radius: 50%;
  -khtml-border-radius: 50%;
  border-radius: 50%;
  -webkit-transition: all 0.2s linear;
  -moz-transition: all 0.2s linear;
  -o-transition: all 0.2s linear;
  -ms-transition: all 0.2s linear;
  -khtml-transition: all 0.2s linear;
  transition: all 0.2s linear;
  top: 0;
  right: 0;
  z-index: 1;
  border: 104px solid rgba(255, 109, 132, 0.5);
}

.service-style-1:hover .service-perview figcaption {
  border-width: 8px;
}

html:

Product

Product1

A: I've fixed this by making the border to 8px and then on the hover making it 104px

redpajama_set_name: RedPajamaStackExchange


text:
Q: Criterion for continuity at a point. Textbook definition of continuity at a point:
$\forall W\in N(f(x_0)) : f^{-1}[W]\in N(x_0)$
Possibly, a criterion for continuity at a point:
$\forall U\in T_Y : f(x_0)\in U \rightarrow f^{-1}[U] \in T_X$
If criterion holds, then the defintion holds. It is easy to check.
But I don't see how the reverse can be proved.
I proved only that this follows from the definition
$\forall U\in T_Y : f(x_0)\in U \rightarrow f^{-1}[U] \in N(x_0)$

*

*Is there a counterexample when the definition and the criterion are not equivalent?

*What are requiremnts to topology, so they may become equivalent?

A: The criterion is not equivalent to continuity.
For instance, consider on $\Bbb R$ the usual topology and consider the map$$\begin{array}{rccc}f\colon&\Bbb R&\longrightarrow&\Bbb R\\&x&\mapsto&\begin{cases}0&\text{ if }x\in[-1,1]\\1&\text{ otherwise.}\end{cases}\end{array}$$Then $f$ is continuous at $0$, but $(-1,1)$ is an open set to which $f(0)$  and, however, $f^{-1}\bigl((-1,1)\bigr)=[-1,1]$, which is not an open set.


text:
Q: Why do I get InputMismatchException in this code? I'm getting:
'Exception in thread "main" java.util.InputMismatchException' in:
float annualInterest = scanner.nextFloat();
I have tried double and now float, getting same error.
I put in a number with decimal (3.2) and getting this exception.
Someone can tell me whats wrong in this code?
Using JDK 14.
public class Main {

public static void main(String[] args) {
    final byte MONTHS_IN_YEAR = 12;
    final byte PERCENT = 100;

    Scanner scanner = new Scanner(System.in);

    System.out.print("Principal: ");
    int principal = scanner.nextInt();

    System.out.print("Annual Interest Rate: ");
    float annualInterest = scanner.nextFloat();
    float monthlyInterest = annualInterest / PERCENT / MONTHS_IN_YEAR;

    System.out.print("Period (Years): ");
    byte years = scanner.nextByte();
    int numberOfPayments = years * MONTHS_IN_YEAR;

    double mortgage = principal
                * (monthlyInterest * Math.pow(1 + monthlyInterest, numberOfPayments))
                / (Math.pow(1 + monthlyInterest, numberOfPayments) - 1);

    String mortgageFormatted = NumberFormat.getCurrencyInstance().format(mortgage);
    System.out.println("Mortgage: " + mortgageFormatted);
    }
}

A:
On my Mac, when it comes to "Annual Interest Rate: " and I write in 3.2, it crashes, but if i write in 3,2 then it works.

This is due to your system settings that determine the punctuation used for writing decimal numbers. We call this a "locale" in Java. One solution is to change the system settings, but this will change the settings for every program on your computer. For now, I suggest you just enter numbers using the format that your system accepts by default.
If you want to use different settings just in your own Java program, then you need to set the locale that corresponds to the rules you want to use. Don't fight it. In the future when you know more about Java, you can start learning about locale and how to set them in your Java code.

A: As the documentation of the Method says

@throws InputMismatchException if the next token does not match the Float regular expression, or is out of range

I guess your Input (3.2) does not match the format of a float for your current locale. With my default locale (Locale.GERMAN) I would need to type "3,2".
If you want to change the Locale your Scanner uses internally you can do so by using Scanner.useLocale.


text:
Q: Additional solutions to a given solution to a differential equation It's my first week studying differential equations, and I would love some feedback regarding the following question:
A second order homogenous linear differential equation with constant coefficients has solution $cos x$. Which amongst the following functions have to also be solutions to our function?
$f_1(x) = \frac{cos x}{3}$
$f_2(x) = 1$
$f_3(x) = cos x · sin x$
$f_4(x) = 3 sin x - 2 cos x$
$f_5(x) = cos (x + 2)$
$f_6(x) = 0.5x^2 + sin x$
I have written down: 1, 4 and 5, as they are all versions of the same basic homogenous solution $y = e^{ax}(c_1cosbx+c_2sinbx)$. I am just worried I might be missing out on something, as often happens with these kinds of questions.
Many thanks

A: As a solution is $\cos x$, the characteristic polynomial has the roots $\pm i$, and the ODE must be
$$y''+y=0.$$
The general solution is thus
$$C\cos x+S\sin x$$
compatible with $1,4,5$.


text:
Q: Online photo gallery for Ubuntu One? I backup my photos in the cloud using Ubuntu One. I would like to view them in an online gallery in a browser (like Dropbox, which has a "photos" folder). Is this possible?

A: Not yet, but you could request the feature here:
https://bugs.launchpad.net/ubuntuone
Make sure you mention that it's a feature request and that dropbox already provides this functionality.

A: The beauty of the free and open source community is that you can request for a feature and actually expect an intelligent response!
Since I couldn't find any feature requests like this, I created a new bug report and hopefully one of the developers picks it up so we can see this feature in a future Ubuntu One update.
Please subscribe to the bug here:
https://bugs.launchpad.net/ubuntuone-servers/+bug/1036488


text:
Q: How can I load assemblies that are placed in the project (portable class library) folder? I have a .dll file in my project folder and would like to load it via Assembly.Load().
AssemblyName name = new AssemblyName("Portable.Store, Version=0.1.0.0, Culture=neutral, PublicKeyToken=12ay62c33eocf6uf");
Assembly assembly = Assembly.Load(name);

However this would throw a FileNotFoundException due to not specifying a path. And I am unable to use Assembly.LoadFrom() or Assembly.LoadFile() because Portable Class Libraries only support Assembly.Load()
Is there a way to do this inside a pcl? Any help is appreciated, thank you!
Edit #1: Would it matter if the assembly I'm trying to load is a non PCL? I know that this defeats the purpose of the PCL however there are a few libraries that are not included in the PCL. Therefore using conditional compilation, depending on the platform, I will load platform specific assemblies.
Edit #2: Found some more information on where the dll should be placed: https://stackoverflow.com/a/6440406/2464165
As of now I just placed it inside my project folder, with the .sln file and what not Where exactly would be the app probing path?
Edit #3: I was able to get my dll file placed inside the Resources Folder of a .dll file. So I have MyPCL.dll and inside that is where I have the ResourcesFolder/Portable.Store. How could I tell the Assembly.Load to look in specific folders instead of just the main AppX root directory?

A: I'm making the assumption that you are running the portable library in a Windows Store application (based on the assembly name you are trying to load).
There are two places that store apps find their assemblies, either in GAC if it is a framework assembly or the Appx package if it is a user assembly.
As "Portable.Store" (which I assuming is from my PclContrib project) is a user assembly, it must be loaded from the AppX package. To ensure that both assemblies end up in the AppX package, simply make sure that the Windows Store project containing the AppxManifest references both of them. That's it.
If Assembly.Load still cannot find the assembly, check to make sure that the strong name you are passing to Assembly.Load is correct.


text:
Q: View state of a frozen generator while debugging Take e.g. the following sample code:
def gen():
    for i in range(5): yield i

def main():
    for j in gen():
        print j

When the execution point is in main() (e.g. on the print line), can I somehow examine the state of gen() (i.e. the value of i) ? Unlike a regular function, it doesn't appear on the call stack.

A: No, because there's no way to access the generator object, and because pdb doesn't support debugging a suspended stack frame. If you'd saved the generator object, you could inspect its gi_frame manually, though:
>>> def gen():
...     for i in range(5):
...         yield i
...
>>> def main():
...     g = gen()
...     for j in g:
...         import pdb
...         pdb.set_trace()
...         print j
...
>>> main()
> <stdin>(6)main()
(Pdb) p g.gi_frame.f_locals['i']
0

Here, I've accessed the generator's suspended frame through gi_frame, then accessed the frame's locals() through f_locals. (Like with locals(), don't try to modify f_locals manually, though.)


text:
Q: Vue 3 Resolving Image Assets Build So I'm trying to build and deploy a Vue 3 website using Heroku. When I test the website locally using npm run dev it works just fine. However, when building I get the following error
Error:
Could not resolve './assets/Design%20Pics/Drone/7_0030.png' from src/App.vue
error during build:
Error: Could not resolve './assets/Design%20Pics/Drone/7_0030.png' from src/App.vue
    at error (C:\Users\stove\Desktop\Aero Website\AeroWebsite\node_modules\rollup\dist\shared\rollup.js:198:30)
    at ModuleLoader.handleResolveId (C:\Users\stove\Desktop\Aero Website\AeroWebsite\node_modules\rollup\dist\shared\rollup.js:22508:24)
    at C:\Users\stove\Desktop\Aero Website\AeroWebsite\node_modules\rollup\dist\shared\rollup.js:22471:26

code:
Note: it's a fragment of the overall code, this is where the "issue" is. Also, I'm using Bulma to style

delivAERO

Revolutionizing the World's Delivery Infrastructure

Heiarchy:

UPDATE: ANOTHER SOLUTION
After getting a lot of help from Daniel, using the import method mentioned in their answer I was still getting errors. I assume this is more about the way the project is setup, but I found another solution.
The way, this post mentions is, it should be imported is as
import img from '@/assets/path/to/img.png'
Note: I have all my images in the assets folder on the src directory
However, this may give the following error:
error TS1232: An import declaration can only be used at the top level of a namespace or module.

From this post, the reason for this error is because imports should be declared first before any Javascript code.
In other words, it should look like:

I'll still be accepting Daniel's answer as I believe that should be the solution for most.

A: Update
both require and import should work with default setup (used latest ATTOW vue-cli 5.0.6 and vue 3.2.13)
I've setup a new project with vue-cli and updated the helloWorld component with:
<template>

</template>

All three versions work for me. If you are still having issues, I'd recommend the 1st option . The only thing you need to do is to move the image (logo.png) into the public folder (public/images/logo.png)
I've also noticed that with the default settings, the images that are "imported" or "required" get injected into the js as base64, which I'm not a fan of, so unless the configuration is updated to handle those, I'd recommend the first option.
AS an aside, I would also recommend removing spaces from the resource and directory names. You have a space in Design Pics, which servers should all handle properly, but it's not guaranteed .

When you use the image like this in the template, it is handled as a string

In order for Vue to bundle the asset it needs to know about it.
you can do this reference in-template
You can import it and then pass the reference the image as the variable in the template
<template>

</template>

or use require in the template:
<template>

</template>


text:
Q: How to determine currently processed event in ActionScript? When one call Clipboard.generalClipboard.getData() in ActionScript outside of Event.PASTE processing function it fails with following message

The Clipboard.generalClipboard object may only be read while processing a flash.events.Event.PASTE event.

Even if I dispatch Event.PASTE event and call this function within event handler it still fails.
How does it determine which event is currently being processed?

A: you need to lister for the real paste Event from the stage and not simulate it. This is a security issue so flash apps do not read your global clipboard data, only on user paste action.


text:
Q: Conditional data attribute in handlebars template with ember I have this, what should be simple, problem in Ember.js. Based on a boolean property, I want to choose whether or not to set a data attribute. This works perfect for class attributes and I can set the data attribute with a property (so in this example {{bind-attr data-toggle="label"}} works).

    {{label}}
    {{#if hasContent}}{{/if}}

What's the fastest/cleanest solution for this? The object in my template is just a Ember.object.
I'm using Ember 1.5 & Handlebars : 1.2.1

A: Why don't you do it like this
{{#if hasContent}}

        {{label}}

{{else}}
    {{label}}
{{/if}}


text:
Q: Catching temlpateUrl path errors I'm implementing a custom template inside a directive, like this:
  .directive('card', function() {
      return {
          restrict: 'E',
          replace: true,
          templateUrl: function(element, attrs) {
              return '/app/templates/' + attrs.cardtype + '.html';
          }
      };
  });

The main template where the directive is generated looks like this:
<card ng-repeat="card in cards" cardtype="{{card.cardtype}}"></card>

Notice I'm using the "cardtype" attribute to select an appropriate template, and then assuming a template name in the directive.
This works fine as long as the cardtype attribute resolves to an html file in the template. However, if the file doesn't exist I get the error:
Error: [$compile:tpload] Failed to load template: /app/templates/{{card.cardtype}}.html

What's the best way to catch this error in order to render a default template?

A: I would try and ask $templateCache, whether this template exists. If you don't use template cache I highly recommend using it. You can set up a grunt task to scan all your .tpl.html files and set up a template-cache for use. In this way no real HTTP requests are going to get fired in order to fetch the templates.
For a nice example how to use templateCache see ng-boilerplate (ngbp)


text:
Q: How to measure time taken by a method in a Xamarin app using Xamarin UI Test and App Center I have recently added a Xamarin UI Test project for my Xamarin app and configured it with App Center to run the test automation on App center and I need to measure how much time is taken by a method or api call to process and show the result and getting this time in the form of logs for load testing.
For e.g After clicking a search button how much time the api took to display the results? How can I measure this?
I tried using this code
var st = new Stopwatch();
st.Start();
app.Tap("SearchButton");

var element = app.WaitForElement(q => q.Marked("Got Results"), "Time Out occured", new TimeSpan(0,0,50));

st.Stop();
var time = st.ElapsedMilliseconds;

the 'SearchButton' click is actually taking 30secs to process the api call and display results in UI but the 'time' variable is not counting it.
I appreciate any help on this issue.

A: The issue is fixed I am writing logs using DateTime.Now in place of start and stop and then calculating the difference


text:
Q: Why is this not logging to the console when a reaction is added to a message? The current code is not logging to the console when a reaction is added to a message.
I know the messageReactionAdd event is triggered by calling the event separately underneath, however I am not sure why this is not logging.
  // This makes the events used a bit more readable
  const events = {
    ADD: 'messageReactionAdd',
    REMOVE: 'messageReactionRemove',
  };

  // This event handles adding/removing users from the role(s) they chose
  client.on('raw', async event => {

    if (!events.hasOwnProperty(event.t)) return;

    const { d: data } = event;
    const user = client.users.get(data.user_id);
    const channel = client.channels.get(data.channel_id);

    const message = await channel.fetchMessage(data.message_id);
    const member = message.guild.members.get(user.id);

    const emojiKey = (data.emoji.id) ? `${data.emoji.name}:${data.emoji.id}` : data.emoji.name;
    let reaction = message.reactions.get(emojiKey);

    if (!reaction) {
      // Create an object that can be passed through the event like normal
      const emoji = new Emoji(client.guilds.get(data.guild_id), data.emoji);
      reaction = new MessageReaction(message, emoji, 1, data.user_id === client.user.id);
    }

    if(event.t === 'ADD') {
      console.log("Reaction: Added")
    }
  });

There is no errors, console completely blank.

A: For what it seems, you are using if (!events.hasOwnProperty(event.t)) return; to check if event.t is equal to any of them, but when someome react in a message event.t returns MESSAGE_REACTION_ADD. So it's coming back from the beginning.
"Just change the ADD property to fix IT"
But, in if(event.t === 'ADD') you check if event.t is equal to ADD, So this will not execute, since event.p returns MESSAGE_REACTION_ADD
"Just change the if(event.t === 'ADD') to if(event.p === 'MESSAGE_REACTION_ADD) {
Make this to fix your code.


text:
Q: How to update a set of records based on two different field values I am having a really difficult time conceiving how to do the following. Basically I have a table such as the following with a two key fields (an id field and another field with a numerical identifier...
ID      fldNumData   fldData
49562   1            1.145816
49562   2            2.165815
49562   1            5.15165
49562   1            6.156156
32564   2            ...
48151   2            ...
54919   2            ...
54919   3            ...

I need to insert a record into another table for each set of records based on the ID and fldNumData, such as gettings the avg of fldData where the ID = 49562 and the fldNumData = 1, but I need to do this for set of keys and NumData. How can I create a query to do this?

A: If i understand you correctly, what you want is:
Assuming that secondTable has the fields ID, fldNumData and fldDtaAverage you do:
INSERT INTO secondTable
SELECT ID,fldNumData,AVG(fldData)
FROM thisTable
GROUP BY ID,fldNumData

A: try following query. its easy to answer if you mention what are the column names of your 2nd table
INSERT INTO TABLE table_2 VALUES(SELECT AVG(fldData) FROM table_1 WHERE id='49562' AND fldNumData='1');


text:
Q: Docker fails external connectivity for Redis I have tried all the possible solutions available on either StackOverflow or other forums, that I could find. I begin installing redis with docker by actual instructions available on Hub Docker. But I was not able to connect to Redis outside container.
My initial command:
docker run --name c-redis -d redis

After further searching I found that I needed to execute it as:
docker run --name mag-redis -d redis -p 6379:6379

But this failed as well, as I got the following error.
$ docker run --name c-redis -d redis -p 6379:6379
c2dbf68f52b46e90671a7efaafbe46898368bb"
Unable to find image 'redis:latest' locally
latest: Pulling from library/redis
8559a31e96f4: Already exists
85a6a5c53ff0: Already exists
b69876b7abed: Already exists
a72d84b9df6a: Already exists
5ce7b314b19c: Already exists
04c4bfb0b023: Already exists
Digest: sha256:800f2587bf3376cb01e6307afe599ddce9439deafbd4fb8562829da96085c9c5
Status: Downloaded newer image for redis:latest
075d68ec71abf3752050c947e44a4b1c52305fb6153febe815e31659284612cf
docker: Error response from daemon: driver failed programming external connectivity on endpoint c-redis (f251e744aeacbd1a084f11b0e01731b1e1a36454ca8ad634889dd38dae66314d):  (iptables failed: iptables --wait -t nat -A DOCKER -p tcp -d 0/0 --dport 6379 -j DNAT --to-destination 172.17.0.3:6379 ! -i docker0: iptables: No chain/target/match by that name.
 (exit status 1)).

I then restarted iptables as one of the solutions available online was this. But this did not help, and same error again. I then found another query on Stackoverflow i.e.
docker run --name c-redis -p 6379:6379 -d redis --restart unless-stopped -v /etc/redis/:/data --appendonly yes --requirepass "password"

However, same error of iptables... I then removed the image/container, and executed with first command (docker run --name c-redis -d redis), it redis was installed but again I was not able to access to externally (by the same host, outside container).
I again removed the container/image, and tried those other 2 commands, but each time I was having same iptables error, I even tried to reboot the docker. Still no use.
I am using Centos 7. Please let me know if anyone else faced such issue. I am totally stuck here for the past several hour(s).

docker: Error response from daemon: driver failed programming external
connectivity on endpoint c-redis
(f251e744aeacbd1a084f11b0e01731b1e1a36454ca8ad634889dd38dae66314d):
(iptables failed: iptables --wait -t nat -A DOCKER -p tcp -d 0/0
--dport 6379 -j DNAT --to-destination 172.17.0.3:6379 ! -i docker0: iptables: No chain/target/match by that name.  (exit status 1)).

EDIT:
Docker version:
Client: Docker Engine - Community
 Version:           19.03.12
 API version:       1.40
 Go version:        go1.13.10
 Git commit:        48a66213fe
 Built:             Mon Jun 22 15:46:54 2020
 OS/Arch:           linux/amd64
 Experimental:      false

Server: Docker Engine - Community
 Engine:
  Version:          19.03.12
  API version:      1.40 (minimum version 1.12)
  Go version:       go1.13.10
  Git commit:       48a66213fe
  Built:            Mon Jun 22 15:45:28 2020
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.2.13
  GitCommit:        7ad184331fa3e55e52b890ea95e65ba581ae3429
 runc:
  Version:          1.0.0-rc10
  GitCommit:        dc9208a3303feef5b3839f4323d9beb36df0a9dd
 docker-init:
  Version:          0.18.0
  GitCommit:        fec3683

UPDATE: (Iptables -S; iptables -t nat -S)
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-N DOCKER
-N DOCKER-ISOLATION-STAGE-1
-N DOCKER-ISOLATION-STAGE-2
-N DOCKER-USER
-N f2b-postfix
-N f2b-postfix-sasl
-A INPUT -p tcp -m multiport --dports 25,587 -j f2b-postfix
-A INPUT -p tcp -m multiport --dports 25,587,953 -j f2b-postfix-sasl
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 31337 -j ACCEPT
-A INPUT -p tcp -m multiport --dports 80,443,587,25,53 -j ACCEPT
-A INPUT -p udp -m udp --dport 53 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j DOCKER-USER
-A FORWARD -j DOCKER-ISOLATION-STAGE-1
-A FORWARD -o docker0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A FORWARD -o docker0 -j DOCKER
-A FORWARD -i docker0 ! -o docker0 -j ACCEPT
-A FORWARD -i docker0 -o docker0 -j ACCEPT
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
-A DOCKER -d 172.17.0.2/32 ! -i docker0 -o docker0 -p tcp -m tcp --dport 80 -j ACCEPT
-A DOCKER-ISOLATION-STAGE-1 -i docker0 ! -o docker0 -j DOCKER-ISOLATION-STAGE-2
-A DOCKER-ISOLATION-STAGE-1 -j RETURN
-A DOCKER-ISOLATION-STAGE-2 -o docker0 -j DROP
-A DOCKER-ISOLATION-STAGE-2 -j RETURN
-A DOCKER-USER -j RETURN
-A f2b-postfix -s 212.70.149.18/32 -j REJECT --reject-with icmp-port-unreachable
-A f2b-postfix -j RETURN
-A f2b-postfix-sasl -s 212.70.149.18/32 -j REJECT --reject-with icmp-port-unreachable
-A f2b-postfix-sasl -j RETURN
-P PREROUTING ACCEPT
-P INPUT ACCEPT
-P OUTPUT ACCEPT
-P POSTROUTING ACCEPT

Thank you!

A: You probably should just have used firewalld instead of trying to write a manual firewall. It looks like you deleted the DOCKER chain from the nat table, that Docker creates when it starts up. You can re-create this chain and Docker should be able to start writing rules to it again.
iptables -t nat -N DOCKER

But there are probably other rules missing, and so you should just restart Docker and let it fix everything.


text: Q: Add a new NSImageRep to the system-wide Mac OS X save dialog For the Cocoa wizards out there: is it possible to create an NSImageRep "filter service" that registers system-wide and appears as a file type in all "Save" and "Save All" dialogs for images?


text:
Q: How come char[3] can be displayed with more than 3 characters?    char fromBluetooth[] = "zgr\r123\r";
   int name_length = 0;
    int pass_length = 0;

    while (1)
    {
        if (fromBluetooth[name_length] == '\r')
        {
            break;
        }name_length++;
    }

    char ssid_determined[name_length];

    for (int i = 0; i < name_length; i++)
    {
        ssid_determined[i] = fromBluetooth[i];
    }

    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print(ssid_determined);

This code should give a result on LCD as "zgr", but what I am getting on LCD is "zgr!\r\r". Can someone explain me how does this happen?
NOTE: That lcd object is Arduino's LiquidCrystal type.

A: First off, I'm not sure how you're declaring an array with a length specified at run-time. This is standard C, right?
What's probably causing your problem is that ssid_determined is not null-terminated. The size of ssid_determined should be name_length + 1, and the final character should be '\0'.


text:
Q: Возникновение события при изменении checkbox на JavaScript Cкрипт, который делает видимыми или невидимыми контейнеры в зависимости от состояния соответствующего checkbox.
Как сделать чтобы при нажатии на чекбокс показывался только последний контейнер, а предыдущий скрывался. Т.е в не зависимости от кол-ва выбранных чекбоксов, активный контейнер был всегда один последний?

<input type = 'checkbox' id = 'cb1' onchange = 'showOrHide("cb1",
"cat1");'/>Показать содержимое категории 1

Содержимое категории 1

<input type = 'checkbox' id = 'cb2' onchange = 'showOrHide("cb2", "cat2");'
/>Показать содержимое категории 2

Содержимое категории 2

<input type = 'checkbox' id = 'cb3' onchange = 'showOrHide("cb3", "cat3");'
/>Показать содержимое категории 3

Содержимое категории 3

A: Нужно в самом начале функции showOrHide сделать невидимыми все контейнеры:

function showOrHide(cb, cat) {

    document.getElementById('cat1').style.display = "none";
    document.getElementById('cat2').style.display = "none";
    document.getElementById('cat3').style.display = "none";

    cb = document.getElementById(cb);
    cat = document.getElementById(cat);
    if (cb.checked) cat.style.display = "block";
      else cat.style.display = "none";
    }

<input type = 'checkbox' id = 'cb1' onchange = 'showOrHide("cb1",
"cat1");'/>Показать содержимое категории 1

Содержимое категории 1

<input type = 'checkbox' id = 'cb2' onchange = 'showOrHide("cb2", "cat2");'
/>Показать содержимое категории 2

Содержимое категории 2

<input type = 'checkbox' id = 'cb3' onchange = 'showOrHide("cb3", "cat3");'
/>Показать содержимое категории 3

Содержимое категории 3

Если же div-ов будет много, то можно добавить им type, далее с помощью document.querySelectorAll получить массив нужных div-ов, потом, проходя по этому массиву, ставить style.display = "none" (в сниппете type = 'mytype').

function showOrHide(cb, cat) {
  var divs = document.querySelectorAll('div[type=mytype]');
  for(var i=0; i < divs.length; i++)
     divs[i].style.display = "none";

  cb = document.getElementById(cb);
  cat = document.getElementById(cat);
  if (cb.checked) cat.style.display = "block";
     else cat.style.display = "none";
  }

<input type = 'checkbox' id = 'cb1' onchange = 'showOrHide("cb1",
"cat1");'/>Показать содержимое категории 1

Содержимое категории 1

<input type = 'checkbox' id = 'cb2' onchange = 'showOrHide("cb2", "cat2");'
/>Показать содержимое категории 2

Содержимое категории 2

<input type = 'checkbox' id = 'cb3' onchange = 'showOrHide("cb3", "cat3");'
/>Показать содержимое категории 3

Содержимое категории 3


text:
Q: Fatal error: Call to a member function getId() on a non-object in app/design/frontend/ultimo/default/template/page/1column.phtml on line 50 magento When i am doing add to cart its showing this error

Fatal error: Call to a member function getId() on a non-object in /public_html/app/design/frontend/ultimo/default/template/page/1column.phtml on line 50

please help me. here is code:
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE_AFL.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    design
 * @package     base_default
 * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
 * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
?>
<?php
/**
 * Template for Mage_Page_Block_Html
 */
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo $this->getLang() ?>" lang="<?php echo $this->getLang() ?>">

<?php echo $this->getChildHtml('head') ?>

<?php $bodyClasses = $this->getBodyClass() .' '. $this->helper('ultimo')->getThemeBodyClasses(); ?>
<body class="<?php echo $bodyClasses; ?>">
<?php echo $this->getChildHtml('after_body_start') ?>

    <?php echo $this->getChildHtml('global_notices') ?>

        <?php echo $this->getChildHtml('header') ?>

<?php echo $this->getChildHtml('main_before_top') ?>

                <?php //echo $this->getChildHtml('breadcrumbs') ?>
                <?php $_product = Mage::registry('current_product');
                $id = $_product->getId();
                ?>

                        Home /

                    <?php $product = Mage::getModel('catalog/product')->load($id);
                    foreach ($product->getCategoryCollection() as $category) {
                    $parent_category = $category->getParentCategory();
                    $proo =  $parent_category->getId();
                    //echo $proo;
                    } ?>
                   <a href="<?php echo $parent_category->getUrl();?>"><?php echo $parent_category->getName(); ?>
                   <?php if($proo > 3){?>/ <?php }?>

                    <?php $_proId  =  $_product->getId();
                        $product = Mage::getModel('catalog/product')->load($_proId);
                        $cats = $product->getCategoryIds();

                        foreach ($cats as $category_id) {
                            $_cat = Mage::getModel('catalog/category')->load($category_id) ;
                            $currentCategory = $_cat->getName();
                            $currentURL = $_cat->getUrl();
                        }
                    ?>
                        <a href="<?php echo $currentURL; ?>"><?php echo $currentCategory; ?>
                        /

                        <?php echo $_product->getName(); ?>

<?php echo $this->getChildHtml('preface') ?>

                    <?php echo $this->getChildHtml('global_messages') ?>
                    <?php echo $this->getChildHtml('content') ?>

<?php echo $this->getChildHtml('postscript') ?>

        <?php echo $this->getChildHtml('footer') ?>
        <?php echo $this->getChildHtml('global_cookie_notice') ?>
        <?php echo $this->getChildHtml('before_body_end') ?>

<?php echo $this->getAbsoluteFooter() ?>

A: You need to change code like this:
<?php
      if(Mage::registry('current_product'))
      {
           $_product = Mage::registry('current_product');
           $id = $_product->getId();
      }
?>

A: Please update your 1column.phtml
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE_AFL.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    design
 * @package     base_default
 * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
 * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
?>
<?php
/**
 * Template for Mage_Page_Block_Html
 */
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo $this->getLang() ?>" lang="<?php echo $this->getLang() ?>">

<?php echo $this->getChildHtml('head') ?>

<?php $bodyClasses = $this->getBodyClass() .' '. $this->helper('ultimo')->getThemeBodyClasses(); ?>
<body class="<?php echo $bodyClasses; ?>">
<?php echo $this->getChildHtml('after_body_start') ?>

    <?php echo $this->getChildHtml('global_notices') ?>

        <?php echo $this->getChildHtml('header') ?>

<?php echo $this->getChildHtml('main_before_top') ?>

                <?php //echo $this->getChildHtml('breadcrumbs') ?>

                            Home /

                        <?php $controller = Mage::app()->getRequest()->getControllerName(); ?>
                        <?php $action = Mage::app()->getRequest()->getActionName(); ?>
                        <?php if($controller == 'product' && $action == 'view'): ?>
                            <?php $_product = Mage::registry('current_product'); ?>

                            <?php $product = Mage::getModel('catalog/product')->load($_product->getId());
                            foreach ($product->getCategoryCollection() as $category) {
                            $parent_category = $category->getParentCategory();
                            $proo =  $parent_category->getId();
                            //echo $proo;
                            } ?>
                           <a href="<?php echo $parent_category->getUrl();?>"><?php echo $parent_category->getName(); ?>
                           <?php if($proo > 3){?>/ <?php }?>

                            <?php $cats = $product->getCategoryIds();
                                  foreach ($cats as $category_id) {
                                  $_cat = Mage::getModel('catalog/category')->load($category_id) ;
                                  $currentCategory = $_cat->getName();
                                  $currentURL = $_cat->getUrl();
                                }
                            ?>
                                <a href="<?php echo $currentURL; ?>"><?php echo $currentCategory; ?>
                                /

                                <?php echo $_product->getName(); ?>

                        <?php endif; ?>

<?php echo $this->getChildHtml('preface') ?>

                    <?php echo $this->getChildHtml('global_messages') ?>
                    <?php echo $this->getChildHtml('content') ?>

<?php echo $this->getChildHtml('postscript') ?>

        <?php echo $this->getChildHtml('footer') ?>
        <?php echo $this->getChildHtml('global_cookie_notice') ?>
        <?php echo $this->getChildHtml('before_body_end') ?>

<?php echo $this->getAbsoluteFooter() ?>


text:
Q: Making decision based on generic type in java I have a generic class which has a method getOutput. I want to make decision based on the type of T (the class type). I tried the below but it does not work.
class Test<T> implements Interface1<T> {

public T getOutput(String input) {

     if (T instanceof Class1) {
       //do something
     } else {
       //do something else
     }
}

}

A: Java does not provide a run-time mechanism allowing a function to determine the type of the expected return value or how its is going to be immediately used. Type parameters of generic methods are being erased after compilation.
See: https://docs.oracle.com/javase/tutorial/java/generics/genMethods.html
You will have to use a method parameter to pass expected type:
interface Value {
    <T> T get(Class<T> tag);
}

class TheValue implements Value {
    @Override
    public <T> T get(final Class<T> tag) {
        if (tag.isAssignableFrom(String.class)) {
            return (T) "something";
        } else {
            return null;
        }
    }
}

A: I tried the below. What do you guys think? Let me know if you have a better solution. We can also discuss solutions using design pattern like strategy pattern. I need this class to give answers in different formats. say. String or Integer...Or Class1 or Class2 (for example)
class Test<T> implements Interface1<T> {

public T getOutput(String input, Class<T> type) {

     if (type.isAssignableFrom(String.class)) {
       //do something
       String answer = "10"; // example answer
       return type.cast(answer);
     } else {
       //do something else
     }
}

}


text:
Q: Screen Wake Lock ON Interactive Canvas Using the "Screen Wake Lock API", I trying to prevent the screen sleep when i playing a large music on Frontend, but i getting this error

NotAllowedError, Failed to execute 'request' on 'WakeLock': Access to
Screen Wake Lock features is disallowed by feature policy

const requestWakeLock = async () => {
    let wakeLock = null;
    try {
        wakeLock = await navigator.wakeLock.request('screen');
        wakeLock.addEventListener('release', () => {
            console.log('Wake Lock was released');
        });
        console.log('Wake Lock is active');
    } catch (err) {
        console.error(`${err.name}, ${err.message}`);
    }
};

requestWakeLock();


text:
Q: Image display using jsp XHTML template .. JSF i have written a simple code to display an image using Jsp XHTML template but it is not working
but same is working when i am using Jsp HTML template ....
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Car Details</title>
</head>
<body>
<f:view>
<h:graphicImage id="root" value="http://www.allbestwallpapers.com/tagwallpaper/convertible%20car-wallpapers.jpg"></h:graphicImage>
</f:view>
</body>
</html>

please Help....

A: You're mixing JSP (foo.jsp) with Facelets (foo.xhtml).
JSP is the ancient view technology which was the default in JSF 1.x. It is not XML based. Facelets is the successor of JSP and is the default view technology since JSF 2.0 (and JSP became deprecated). Facelets is XML based. Those xmlns XML namespace declarations don't work in JSP, but in Facelets only.
Rename the filename from the .jsp extension to .xhtml extension and get rid of that JSP specific @page declaration and it'll work.


text:
Q: gsutil to copy all files and create a subdirectory I have 4 files xxxxx.xlsx in this directory:
/var/tmp/dagxxxxx/2019-08-10/xxxxx.xlsx

I want to copy them over to:
gs://reports_dev/2019

Using gsutil cp -r the final gcs path should be like(with all 4 files):
gs://reports_dev/2019/2019-08-10/xxxxx.xlsx

I tried different combination of cp and -r like:
gsutil cp -r /var/tmp/dagxxxxx/2019-08-10/** gs://reports_dev/2019

but couldn't get the desired path in gcs.

A: Remove the trailing Asterisks, -r already means recursive, this should work:
gsutil cp -r /var/tmp/dagxxxxx/2019-08-10/ gs://reports_dev/2019

If you append a forward slash / to your source, it will copy the folder to your destination, if you don't, it will copy the Content of your source to your destination.


text:
Q: Webpack shorten property name We have Vue 2.x.x application (typescript) our application should be divided into modules.
Like /users, /articles, /reports and etc. It is micro frontend architecture.
For example this solution:
https://itnext.io/setup-a-micro-frontend-architecture-with-vue-and-single-spa-2c89528bf72f
We want to load these modules dynamically based on user permissions so we decided to choose SystemJS.
export const ApplicationModuleService = {

        createModule(name: string, url: string, activeWhen = "/", props = {}): RegisterApplicationConfig {
            return {
                name,
                app: () => window.System.import(url), //system js is loading from cdn. in global.d has definition
                activeWhen,
                customProps: props
            }
        }
    }

We have import of SystemJS from CDN and when we transpile this with webpack we are not able to use System.import, but we are forced to use window object.
When we try to use System.import webpack transpiles it into shortened property like:
l.import(...)
We have tried to create globally prop with webpack DefinePlugin, ProvidePlugin etc. but it didn't work.
Is there way, how to solve it?
Thank you for your time

A: If you are using webpack already there is no reason to use System.js as module loader.
Webpack has a built-in lazy loading modules capabilities.
All you need to do is use the import('path/to/my/lazy/module'), which returns a Promise which will be resolved when the module is loaded. Webpack will handle the rest of the work.
You code should look like:
export const ApplicationModuleService = {
  createModule(name: string, url: string, activeWhen = '/', props = {}): RegisterApplicationConfig {
    return {
      name,
      app: () => import('path/to/lazy/module')
      activeWhen,
      customProps: props,
    };
  },
};

For a CDN support, you can specify the publicPath option.
For more info read this


text:
Q: TrueCrypt and PCManFM The LXDE FM won't show the volume after mounting it in TrueCrypt. Found this and this. Is there any recommended way?

A: A solution would be to specify the mount point and then navigate to the mount point.
Example:
I have an encrypted file named "enc1" at "/home/desgua/Dropbox", and my mount point is the folder "/mnt/mymountpoint/", so I type this on terminal:
truecrypt --mount /home/desgua/Dropbox/enc1 /mnt/mymountpoint/
And then navigate to "/mnt/mymountpoint/" to see my files.
And to unmount:
truecrypt -d /home/desgua/Dropbox/enc1
or simple:
truecrypt -d  (which should unmount every truecrypted mounted files)
Outside command line
Suggestion One
You can edit the file /etc/fstab (open it with gksu gedit /etc/fstab) and add a line to specify the mount point:
/dev/sda1/home/desgua/Dropbox/enc1 /mnt/mymountpoint  auto   rw,user 0      0
Reboot.
Now you can mount through GUI and navigate to /mnt/mymountpoint
More info here.
Suggestion Two
Also you can create a launcher to mount it:
1) Paste this at terminal: gedit ~/Desktop/unmounttruecrypt.desktop,
2) Then paste this into the file and save:

[Desktop Entry]
Type=Application
Encoding=UTF-8
Name=Unmount Truecrypt
Comment=Unmount all mounted Truecrypt files
Exec=gnome-terminal -e "bash -c \"truecrypt --mount /home/desgua/Dropbox/enc1 /mnt/mymountpoint/ ; exit; exec bash\""
Icon=/usr/share/icons/Humanity/actions/48/go-jump.svg
Categories=Application;Accessories;

3) Now look at your desktop and drag the file to the Launcher.


text:
Q: Get data automaticly when inputs are filled <?php

   if(isset($_POST['submit'])){
      // Here the code captures the inputs that entered.
        Based on the inputs the script shows the associated information.
}

    <form method="POST">
    <input type="text" name="postc">
    <input type="text" name="nr">
    <button name="submit">Send</button>
    </form>

How to check that both of the inputs are filled and if they are filled automaticly load the PHP code to get the data.  (I'm a beginner)
I hope I explained it right!
Example page
http://bit.ly/1hx0EKS

A: I'd suggest something like below:
HTML
<form method="POST" name="myForm" action="page.php">
    <input type="text" name="postc" onchange="submitForm()">
    <input type="text" name="nr" onchange="submitForm()">
</form>

Javascript
this function is called anytime you fill an input of your form. It provides to get your input values and submit dynamically the form ONLY when you filled all your (in this case) inputs.
function submitForm() {
    var postc = document.forms["myForm"]["postc"].value;
    var nr = document.forms["myForm"]["nr"].value;

    if (postc != "" && nr != "")
        document.myForm.submit();
}

EDIT
This is a full working example
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Your title</title>

        <script>
            function submitForm() {
                var postc = document.forms["myForm"]["postc"].value;
                var nr = document.forms["myForm"]["nr"].value;

                if (postc != "" && nr != "") {
                    document.myForm.submit();
                }
            }
        </script>
    </head>
    <body>
        <form method="POST" name="myForm" action="#">
            <input type="text" name="postc" onchange="submitForm()">
            <input type="text" name="nr" onchange="submitForm()">
        </form>

        <?php
            if(isset($_POST['postc'])){
                echo "postc value: " . $_POST['postc'] . '<br />';
                echo "nr value: " . $_POST['nr'];
            }
        ?>
    </body>
</html>

hope this helps :-)


text:
Q: Won't save changes to an EKEvent that has recurrenceRules The following code works for non-recurring events, changes to startDate and endDate are saved just fine.
BOOL success = [theEventStore saveEvent:event
                                   span:EKSpanFutureEvents
                                 commit:YES error:&error];

But whenever I try to edit an event that has recurranceRules, it returns with success == YES, but nothing is saved, and any changes to startDate/endDate or the recurranceRules are reverted back to the original values. (Using span:EKSpanThisEvent works, but this is of course not what I want to do. Also, the code works on iOS, but not on OSX.)

A: eventWithIdentifier returns the first occurrence of a recurring event. When you change something on this event with EKSpanFutureEvents, you will change all occurrences.
eventsMatchingPredicate returns every event occurrence that matches your predicate. EKSpanFutureEvents will change each occurrence from the certain occurrence you used.
If a event is detached it doesn't matter, if you take EKSpanThisEvent or EKSpanFutureEvents.
I don't get what your code is supposed to do.

A: I think I've found a solution, or at least a workaround. It seems that on Mac OS X when you modify recurrent events you should get them with eventWithIdentifier and not use the ones from eventsMatchingPredicate.
NSArray* events = [_eventStore eventsMatchingPredicate:predicate];
EKEvent* event = [events objectAtIndex:index];
EKEvent* original = [_eventStore eventWithIdentifier:event.eventIdentifier];
if (event.isDetached)
{
    … // modify detached event
    success = [_eventStore saveEvent:event
        span:EKSpanThisEvent
        commit:YES
        error:&error];
}
else if (!original.hasRecurrenceRules)
{
    … // modify non-recurrent event
    success = [_eventStore saveEvent:event
        span:EKSpanFutureEvents
        commit:YES
        error:&error];
}
else
{
    … // modify the original in a series of recurring events
    success = [_eventStore saveEvent:original
        span:EKSpanFutureEvents
        commit:YES
        error:&error];
}

I haven't found any good documentation on this, maybe it's a "bug" or just one of those peculiar behaviors of EventKit. In any case it seems that you need to take great care when modifying recurring events.


text:
Q: How to restrict access of a specific country to my website? I have 2 websites with different domain extensions that provide the same services for the visitors, one is .com and the other is .com.au. I want to give access to the Australian people only visit to .com.au website not to .com, so they cannot visit the .com website.
Would you please guide me how to restrict access of those Australian visitors to the .com website? Even if they use the typo in the address bar of the browser's they'll automatically will be redirected to the .com.au website.
As I'm not a techno guy, I need your firm guidance make this happen. Thank you for your assistance.

A: First get a geolocation based on their ip, here
The maxmind service for locating countries is here
There should be some free services just google around and i am sure you will be able to find them
But basically just load the php library of whichever service you find, feed it the ip of the visitor $_SERVER['REMOTE_ADDR']
then do a redirect to the .au address if the geolocation comes up with a Australian result
header('location: http://www.example.com.au');

put the check at the top of your script(s)


text:
Q: Displaying custom cursor in the full screen mode - Flex 3.0 I am having trouble displaying a custom cursor in the full screen mode of my flex application. How can I do this?

A: CursorManager.removeCursor() method removes a cursor from the cursor list.

If the cursor being removed is the currently displayed cursor, the CursorManager displays the next cursor in the list, if one exists. If the list becomes empty, the CursorManager displays the default system cursor.

I can't find a way to add a removed cursor back to the cursor list other than calling the setCursor again. The following code works in normal as well as full screen mode. There's got to be a better way, because the customID is incremented in each call - but at least it works fine.
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"
    xmlns:local="*" >
    <mx:Button label="Custom" click="onCustomClick();"/>
    <mx:Button label="Default" click="onDefaultClick();"/>
    <mx:Button label="Go Fullscreen"
        click="stage.displayState = StageDisplayState.FULL_SCREEN;"/>
    <mx:Script>
        <![CDATA[
            import mx.managers.CursorManager;

            [Embed(source="cursor.png")]
            public var CursorPNG:Class;

            private var customID:int;

            private function onCustomClick():void
            {
                customID = CursorManager.setCursor(CursorPNG);
            }
            private function onDefaultClick():void
            {
                CursorManager.removeCursor(customID);
            }

        ]]>
    </mx:Script>
</mx:Application>

A: I am using the same method you are talking about. I am calling the method which changes the cursor on the RollOver event of mouse on a Canvas. Then I call the restore cursor method on RollOut event which removes the previously assigned cursor and shows the system's default one. It all works fine in normal mode. Custom cursor appears and disappears on roll over and out of the Canvas.
But when I switch the canvas to full screen mode, the custom cursor only appears only for a moment or so. And then it disappears. No cursor on the screen. If you move out of the Canvas, the system's default cursor is only visible then.


text:
Q: Displaying list returned from method on VF page public List<Account> accresults {get;set;}

public List<Account> getAccounts(Integer NumberOfRecords){
    List<Account> accountList = [SELECT Id FROM Account where Status__c = 'Open' Limit 5];
    Map<Id, Account> selectedAccountsMap = new map<Id, Account>();
    Account account;
    List<Account>accResults = new List<Account>();
    Integer rand;
    Integer count = accountList.size();
    //Integer numberOfRecordsToSelect = 25;
    Integer i = 1;

    while (i <= NumberOfRecords){
        rand = randomWithLimit(count);
        System.debug('Random Number: ' + rand);
        account = accountList[rand];

        if(selectedAccountsMap.get(account.Id) == null)
        {
            selectedAccountsMap.put(account.Id, account);

            i++;
        }
    }

   accresults.addAll(selectedAccountsMap.values());
   system.debug(accresults);
   return accresults;
}

public static Integer randomWithLimit(Integer upperLimit){
    Integer rand = Math.round(Math.random()*1000);
    return Math.mod(rand, upperLimit);
}

A: A few starting points:

*

*You can rewrite your method greatly to operate using a dynamic limit

*You can directly call the results of an soql query into a map (Although there seems to be no reason to use a map here, since you later add only the values to a list of accounts)

*If you are calling this method from a visualforce page, you won't be able to pass along the NumberOfRecords parameter from the page, you'll have to use the apex:param tag.

*You likely don't want to return the values themselves, but instead, want to return something to rerender the page, as opposed to the data, if your data is set somewhere in the controller.

Your method can look like this instead of what you have in your post:
public Integer NumberOfRecords { get; set; }
public List<Account> accountResults { get; set; }

public PageReference getAccounts() {

    if (NumberOfRecords > 5) {
        NumberOfRecords = 5;
    }

    accountResults = [SELECT Id FROM Account where Status__c = 'Open' Limit :NumberOfRecords];

    return null;
}

And you can use it in visualforce as such:
<apex:commandButton action="{!getAccounts}" reRender="someBlock">
    <apex:param value="5" assignTo="{!NumberOfRecords}" />
</apex:commandButton>

<!-- .... -->

<apex:outputPanel id="someBlock">
    <apex:repeat value="{!accountResults}" var="a">
        <p>{!a.Name}</p>
    </apex:repeat>
</apex:outputPanel>

As an aside, I'd highly recommend the Visualforce Trailhead to get you accostomed to working with the laungauge.


text:
Q: Cannot reach localhost from angular application configured inside nginx I have an application developed by angular as frontend and spring boot for the backend.
I deployed them in Nginx running in Ubuntu server including let's encrypt ssl certificates
The front end is deployed in the following path /var/www/my-app-domain.local
The backend is a jar which is running on port 8080
The Nginx configuration is in following file located in /etc/nginx/conf.d/my-app-domain.local.conf
server {
        listen 80;
        listen [::]:80;

        server_name my-app-domain;

        location /api/ {
             proxy_pass http://localhost:8080/;
             proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
             proxy_set_header X-Forwarded-Proto $scheme;
             proxy_set_header X-Forwarded-Port $server_port;
        }
}

server {
    server_name my-app-domain www.my-app-domain; # managed by Certbot
    index index.html;
    root /var/www/my-app-domain.local;
    location / {
        #        try_files $uri $uri/ =404;
         try_files $uri $uri/ /index.html;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/my-app-domain/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/my-app-domain/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}server {
    if ($host = my-app-domain) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    if ($host = my-app-domain) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    listen 80 ;
    server_name my-app-domain www.my-app-domain;
    return 404; # managed by Certbot

}

When I call the domain name in the browser, it rejected the call for the API from the webapp
showing this error in the console : Failed to load resource: net::ERR_CONNECTION_REFUSED for calling  http://localhost:8080/api/*****
However, when I call the same API from the browser, it's calling successfully without any issues.
Is my Ngnix configuration incorrect? what should I do with this error and what is the proper way for calling APIs in production environment?


text:
Q: My android app can download but doesnt appear in my downloaded apps My new android app can download from the playstore but doesn't appear in my downloaded apps. When i download it from the play store usually there is an option to 'open' the app aswell as 'uninstall', only the uninstall button is visible. (http://i.imgur.com/jNTvJq2.png notice the missing open button)
here's the my manifest, there were no errors during all the tests i ran.
      <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.jackattackapps.bigl"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/iconimage"
        android:label="@string/app_name"
        android:theme="@style/Theme.Sherlock" >

        <activity
            android:name="com.jackattackapps.bigl.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAINACTIVITY" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

        <activity
            android:name="com.jackattackapps.bigl.Splashscreen"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.SPLASHSCREEN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name="com.google.ads.AdActivity"
                      android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>

    </application>

</manifest>

And this is the activity that is supposed to load on the start of the application.
package com.jackattackapps.bigl;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;

public class Splashscreen extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {

    // TODO Auto-generated method stub

    super.onCreate(savedInstanceState);

    setContentView(R.layout.splashscreen);
    Thread timer = new Thread(){
        public void run(){
            try{

                MediaPlayer ourSong = MediaPlayer.create(Splashscreen.this, R.raw.splashsound);
                ourSong.start();
                sleep(2300);

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

            } finally {

                Intent openMainActivity = new Intent("android.intent.action.MAINACTIVITY");
                startActivity(openMainActivity);

            }
        }
    };
    timer.start();
}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    finish();

}

}
if more information is needed just comment, help would be appreciated greatly.

A: Your Launcher activity should have this Intent Filter
<intent-filter>
    <action android:name="android.intent.action.MAIN"/>
    <category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>


text:
Q: How to send data to other domain I have a store in BigCommerece.
My question is: how to send customers details from one domain A to other domain B and how to retrieve it at domain B. How is it we do in bigcommerce? Please help me.


text:
Q: Let $Z=Z(x,y)$ be a solution of $\frac{\partial z}{\partial x}\frac{\partial z}{\partial y}$ = 1
Let $Z=Z(x,y)$ be a solution of $$\frac{\partial z}{∂x}\frac{\partial z}{\partial y} = 1$$ passing through $(0,0,0)$. Then $Z(0,1)$ is

*

*0

*1

*2

*4

By Charpit Method I get the solution as $Z=ax+by+c$ whare $a, b, c$ are constant and $ab=1$.
since $Z$ passes through the origin then $c=0$.
finally we get the solution  $Z=ax+by$.
then $Z(0,1)= b$. Ather that what will I do?


text:
Q: BMI calculator how to round up to 1 d.c.? I'm creating a BMI calculator project, and I'm almost finished. Just one thing I don't know how to do is how to round the result to 1 d.c.
Also I don't why the calculate button didn't work after I copy and paste to here. The code is below:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>BMI Calculator</title>

<form name="bmiForm">
你的體重(kg): <input type="text" name="weight">

你的身高(cm): <input type="text" name="height">

<input type="button" value="Calculate BMI" onClick="calculateBmi()">
<input type="reset" value="Reset" />

你的BMI: <input type="text" name="bmi">

你的健康狀況: <input type="text" name="meaning">

</form>

 組別
 BMI

 過輕
 <18.5

 體重正常
 18.5 - 22.9

 過重
 23 - 24.9

 肥胖
 25 - 29.9

 太肥胖
 30 & above

A: Assuming you want to round off to one decimal, you can use .toFixed() on a number:
var BMI = 123.5456;
console.log(BMI.toFixed(1));

// output
123.5

The one thing to keep in mind is the this returns a string, to convert back to number wrap the result with parseFloat()


text:
Q: Stopping pushers from breaking my central Mercurial repository I'm running the central mercurial repository, and I understand that the normal "push" command will stop if the remote user is trying to force multiple "head"s to my central repository.  The intention is that the remote user should first pull and merge before trying to push again.
However, using hg push --force will override this.  I would like to block this behavior.
I am currently using the hgwebdir.cgi plus some apache-auth stuff to limit users ability to pull and push.
EDIT: a pretxnchangegroup hook solved the problem.
Hook worked:
#!/bin/bash
# force-one-head
# add the following to <repository>/.hg/hgrc :
# [hooks]
# pretxnchangegroup.forceonehead = /path/to/force-one-head

if [[ `hg heads -q | wc -l` -gt 1 ]]; then
    echo "There are multiple heads."
    echo "Please 'hg pull' and get your repository up to date first."
    echo "Also, don't 'hg push --force' because that won't work either."
    exit 1
fi

A: This is not an Apache change, but you have to set it in the Mercurial repository itself.
You can setup hooks that run a script before accepting a push into your repository. In the scripts triggered by the pretxncommit or pretxnchangegroup hooks you can check if those changes create a new head and refuse them if they do.
See the chapter on hooks in the Hg Book for more details.

A: There is no hook supplied that will create this behavior.  You will need to write it yourself.

A: Consider putting the repository on an access-controlled server, and then implementing mercurial-server (formerly known as hg-admin-tools). Users push through SSH (from Windows or Linux) and are subject to your access controls.
There are two permissions files that will give you fine-grained control over who can read versus push. Multiple repositories can be set up under one management system, so you don't have to install it over and over again.


text:
Q: Why isn't $x-y$ in $\langle x^2+1,y^2+1\rangle$? Why isn't $x-y$ in $\langle x^2+1,y^2+1\rangle$?
It is pretty obvious looking at the degrees, but it is not a very formal reasoning. Could you lend me a hand?

A: In general you can test for ideal membership by computing a Gröbner basis, but in this case the following ad-hoc argument works.
Any polynomial in the ideal $\langle x^2+1, y^2+1\rangle$ vanishes when you plug in $x=i, y=-i$. But the polynomial $x-y$ does not vanish when you plug in $x=i, y=-i$ and hence cannot be in the ideal.

A: We can evaluate at $x = +i, y = -i$.
For $x-y$ we get $2i$.
But for any polynomial in $\langle x^2 + 1, y^2 + 1 \rangle$ we get 0.

A: Since you didn't specify your ground ring $R,$ it may be of characteristic $2,$ in which case the two previous answers don't work.
Instead, let us reason by contradiction: if $x-y\in I:=\langle x^2+1,y^2+1\rangle,$ then $I=\langle x^2+1,x-y\rangle,$ so $R[x,y]/I$ is isomorphic to $R[x]/\langle x^2+1\rangle$ which is a free $R$-module of dimension $2$ (generated by the classes of $1$ and $x$). But this is impossible, since $R[x,y]\langle x^2+1,y^2+1\rangle$ is of dimension $4$ (generated by the classes of $1,x,y,xy$).
Alternatively, apply to the ring $A=R[y]/\langle y^2+1\rangle
$ and the element $\alpha=y$ the fact that for any $A\ni\alpha$, $x-\alpha$ does not belong to the ideal $\langle x^2+1\rangle$ of $A[x].$ May be this a formalization of what you found "pretty obvious looking at the degrees".


text:
Q: Clip path polygon not working in header, but does work in footer On my website I would like to add a clip-path, so one of the sides is in an angle. This does work in my footer, but I can't make it work in my header.
The website is made in wordpress, with my own theme. The code in the header.php file is:
<?php
/**
 * The header for our theme.
 *
 * This is the template that displays all of the  section and
everything up until

 *
 * @link https://developer.wordpress.org/themes/basics/template-
files/#template-partials
 *
 * @package epw_theme
 */

?><!DOCTYPE html>
<html <?php language_attributes(); ?>>

<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="profile" href="http://gmpg.org/xfn/11">
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>">
<link rel="stylesheet" href="<?php bloginfo('style.css'); ?>">

<?php wp_head(); ?>

<body <?php body_class(); ?>>

<a href="<?php echo esc_url( home_url( '/' ) ); ?>"
rel="home"><?php bloginfo( 'name' ); ?>

        <?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_id'
=> 'primary-menu' ) ); ?>

The CSS that goes with this part of the website:
html {
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

body {
  margin: 0;
  padding-bottom: 6rem;
  min-height: 100%;
  font-family: "Helvetica Neue", Arial, sans-serif;
}

.hero {
  margin: 0 auto;
  padding-top: 0px;
  width: 100%;
}

.hero h1  {
  margin-top: 0;
}

// slanted edge here
.hero .hdftbg {
  clip-path: polygon(0 0, 100% 0, 100% 100%, 5% 100%);
}

// demo code below
.hero {
  color: #fff;
  font-family: 'Raleway', sans-serif;
  position: relative;
  text-align: center;
  text-shadow: 0px 0px 1px rgba(0,0,0,0.5);}

  .hdftbg{
    height: 40px;
    width: 50%;
    background-color: #1D1F20;
    float: right;
  }

    .fullwidthbar{
    width: 100%;
    background-color: #1D1F20;
    height: 25px;
    margin-bottom: -1px;
  }

  #headertext {
    font-size: 18px;
    text-transform: uppercase;
        text-align: center;
        text-decoration: none;
        text-transform: uppercase;
        color: white;
  }

  #headerfield {
    font-size: 14px;
    font-weight: 300;
    margin-top: 0.5em;
}


text:
Q: Index will not show up in table of contents I am new to LaTeX and still on the steep learning curve. I am writing some documentation for a school project which has a bibliography and an index, using ShareLaTeX. I am having difficulty getting the index to show in the table of contents. This bare-bones code sample illustrates my problem.
\documentclass[a4paper]{report}

\usepackage{lipsum}
\usepackage{makeidx}

\makeindex
\begin{document}
\tableofcontents
\clearpage{\pagestyle{empty}\cleardoublepage}

\chapter{Introduction}
Some random \index{random} text \index{stuff!text} about fact \cite{fact}.
\clearpage{\pagestyle{empty}\cleardoublepage}

\chapter{Main}
\lipsum[6]
\clearpage{\pagestyle{empty}\cleardoublepage}

\addcontentsline{toc}{chapter}{Bibliography}
\begin{thebibliography}{9}
    \bibitem{fact}
    Factual stuff,
    \emph{The types of Facts}. \\
    XXXX, Publisher
    \end{thebibliography}
\clearpage{\pagestyle{empty}\cleardoublepage} %Line 1

\addcontentsline{toc}{chapter}{Index} %Line 2
\printindex
\clearpage{\pagestyle{empty}\cleardoublepage}

\end{document}

If I change Line 1 to \clearpage{\pagestyle{empty}} then the index shows up in the table of contents, however I want to ensure the index starts on an odd page. I have tried using the hyperref package but doing this with the package:
\phantomsection
\addcontentsline{toc}{chapter}{Index}
\printindex
\clearpage{\pagestyle{empty}\cleardoublepage}

seems to have no effect. I've been looking all over the internet for an answer and I haven't found it. I would appreciate any help and if you need more info please let me know I will do my best :-)

A: To have chapters start on odd pages, you can add twoside,openright to the options of the class. This will change the layout to fit twosided printing, and cause all chapters to start on a right/recto/odd pages.
To add bibliography and index to the ToC, you can add
\usepackage[nottoc]{tocbibind}

to the preamble. nottoc means that the ToC itself does not end up in the ToC.
Also, I just noticed that the index does not seem to start on an odd page even with twoside,openright, add a \cleardoublepage just before \printindex to take care of that. Complete code example:
\documentclass[a4paper,openright,twoside]{report}

\usepackage{lipsum}
\usepackage{makeidx}
\usepackage[nottoc]{tocbibind}

\makeindex
\begin{document}
\tableofcontents

\chapter{Introduction}
Some random \index{random} text \index{stuff!text} about fact \cite{fact}.

\chapter{Main}
\lipsum[6]

\begin{thebibliography}{9}
    \bibitem{fact}
    Factual stuff,
    \emph{The types of Facts}. \\
    XXXX, Publisher
    \end{thebibliography}

\cleardoublepage\printindex

\end{document}

A: Add toc request when you make the index:
\makeindex[columns=3, title=Alphabetical Index, intoc]


text:
Q: Making template html for json data I am using  t.js as a template engine in my project. How to make template for this json:
{
data: [
    {
        FirstName: "Test1",
        LastName: "Test11"

    },
    {
        FirstName: "Test2",
        LastName: "Test22"
    },
    {
        FirstName: "Test3",
        LastName: "Test33"
    }
]

}
I want to render it like

Test1,Test11

Test2,Test22

Test3,Test33

Can you suggest any other template engine along with template html for my above case which is better? I don't want to use any template engine using eval or new Func

A: Markup

    {{@mydata}}
{{=_val.FirstName}},{{=_val.LastName}}
 {{/@mydata}}

Javascript
var source = $("#myList").html();
var template = new t(source);
$("#myList").html(template.render({
    mydata: [
        {
        FirstName: "Test1",
        LastName: "Test11"

        },
        {
            FirstName: "Test2",
            LastName: "Test22"},
        {
            FirstName: "Test3",
            LastName: "Test33"
        }
    ]
}));

demo : http://jsfiddle.net/diode/c2Qhw/


text:
Q: fstab mount, boot stuck on "A start job is running for dev-disk-by\..." I am running debian 8.1 and working on this for hours now! I try to auto mount seagate and medion on boot if they are plugged in, but if the server is booting without one of these LABELs it stucks here for 1:30min and boots into maintainace mode:
Give root password for maintenace
(or type Control-D to continue):

I just want to mount my usb devices if they are present.. : /

/etc/fstab:
# /etc/fstab: static file system information.

#FIXED
#<file system>                             <mount point>   <type>   <options>           <dump>   <pass>
UUID=f243951c-f61c-4af7-88c5-79ba0a33caf8  /               ext4     errors=remount-ro   0        1
UUID=28737539-1569-4db7-9ea3-d74473502f39  none            swap     sw                  0        0

#REMOVABLE
#<file system>   <mount point>   <type>    <options>                    <dump>   <pass>
#LABEL=medion     /mnt/medion     ntfs-3g   rw,noauto,nobootwait,nofail  0        2
LABEL=seagate    /mnt/seagate    ntfs-3g   rw,nobootwait,nofail         0        2

A: Add the (previously documented but unimplemented) option nofail.

$ man fstab
nofail do not report errors for this device if it does not exist.

See also https://askubuntu.com/questions/638985/how-to-configure-systemd-to-ignore-fstab-drive-mount-failures

But also add a low timeout with something like x-systemd.device-timeout=2, because the default timeout seems to be 90 seconds.

A: According to the fstab man-page you can skip the fsck for specific mounts if you put "0" as the last digit, instead of "2" in /etc/fstab.
( For some reason for me the "0" was ignored for my usb-drive I mounted via UUID ... however it may not hurt to take a try. )


text:
Q: How assembly compilators know where to place functions? How do assembly compilators know where to place labels/functions?
I have been thinking about this problem and I couldn't find the answer.
Example code:
Func1:
    mov %ax, 0x100

jmp Func1

How does it know where to place it in good position in .bin/.o file?
Or it just jumps to end of the Function.
I tried to create my own operation code just to make my emulator skip the function. But when it needs to be called it gets jumped to it with offset + 1 to skip the function operation code. \
To be clear, I'm making my own emulator and compilator to understand more how processors work. I can create simple compilators but at some point I must add jumps, conditional jumps and comparisons.
I create my emulator in python.
If anyone knows answer please answer. And I apologise for my bad english.


text:
Q: How to filter ng-repeat values based on another input ng-model value in angularjs? repeat values based on another input ng-model value in angularjs?

*

*I have one input value like Social Psychology for this value ng-model is kpcategory

*I have used ng-repeat like ng-repeat="question in questions to list out the all category and name.

*I tried to filter Social Psychology category in ng-repeat list, so i used like ng-repeat="question in questions | filter:kpcategory".

*what the issue is, it's filtering Social Psychology data's perfectly. but i would like to filter only the category value of Social Psychology not for all data's. the issue is  it's filtered includes of category and category_twodata's.

Expecting result is:-

*

*just want to filter by catgory Social Psychology so result should be Social Psychology , John data.

*My Plunker For Reference

*we don't how to solve this issue please help us thanks.

A: You can try following to filter items by category property only

{{question.category}} , {{question.name}}

Demo

A: Try to do this Demo
 <input type="text" name="kpcategory"
      data-ng-model="kpcategory.category" value="kpcategory">

{{question.category}} , {{question.name}}

Note: I have made data-ng-model="kpcategory.category" in the input field


text:
Q: Code execution time in Linux I was trying to get the execution time of a particular piece of code (may be a loop or a function, etc.). I heard that command time or function clock() do the job. But my requirement was accuracy in milli/micro seconds. So I wrote something like this.
int main()
{
    struct timeval ts1, ts2;
    long long time1, time2, diff;
    int i,var;

    scanf("%d",&var);
    gettimeofday(&ts1, NULL);
    time1 = (ts1.tv_sec * 1000000) + ts1.tv_usec;

    for (i=0; i<var; i++); // <-- Trying to measure execution time for the loop

    gettimeofday(&ts2, NULL);
    time2 = (ts2.tv_sec * 1000000) + ts2.tv_usec;

    printf("-------------------------\n");
    diff = time2 - time1;
    printf("total %ld microseconds\n", diff);
    printf("%ld seconds\n", diff/1000000);
    diff %= 1000000;
    printf("%ld milliseconds\n", diff/1000);
    diff %= 1000;
    printf("%ld microseconds\n", diff);
    printf("-------------------------\n");
    return 0;
}

I have two concerns here

*

*Is the above code reliable and do what my intention is? I'm not quite sure about it ;)

*When I compile the code with optimization level -O2, that's not at all working. I know -O2 will apply some make-up but how I'll see what happened? If I'm good to go with 1, can anyone please suggest how'll recover the O2 issue?

Appreciate the help! Thanks.

A: The above code you show is to get the real time elapsed since gettimeofday() just returns the wall-clock time. As to not working with optimization level -O2, declare i as volatile int i which will prevent the optimization to i.

A: This NanoTimer class (header file) should do the job.
Use startTimer()/stopTimer(). Please note that calculating the elapsed time at this relative resolution takes some time, so you will never have a value of 0 if you execute just startTimer(); stopTimer(); without any code in the middle.
Also there are many other factors that influences the elapsed time, so you should repeat the specific measure several times and take the lowest value.
class NanoTimer
{
    struct timespec ts_;
    u_int64_t startTimer_;
    u_int64_t totalTimer_;
public:
    NanoTimer()
    {
        totalTimer_ = 0;
        startTimer_ = 0;
    }

    u_int64_t getNanoSecTimer(void)
    {
        clock_gettime(CLOCK_REALTIME, &ts_);
        return ts_.tv_sec * 1000000000 +  ts_.tv_nsec;
    }

    void startTimer(void)
    {
        startTimer_ = getNanoSecTimer();
    }
    void stopTimer(void)
    {
        //assert(startTimer_ > 0);
        totalTimer_ += getNanoSecTimer() - startTimer_;
        startTimer_ = 0;
    }
    inline u_int32_t getTotalSeconds()
    {
        return totalTimer_/1000000000;
    }
    inline u_int32_t getTotalMilliseconds()
    {
        return totalTimer_/1000000;
    }
    inline u_int32_t getTotalMicroseconds()
    {
        return totalTimer_/1000;
    }
    inline u_int32_t getTotalNanoseconds()
    {
        return totalTimer_;
    }
    inline u_int32_t getCurrentSeconds()
    {
        return (totalTimer_ + (startTimer_ > 0 ? getNanoSecTimer() - startTimer_ : 0)) / 1000000000;
    }
};

A: You can use the sample code !!. The code results in no-overhead in the computation cost
#include <sys/time.h>
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/resource.h>

void timing(double* wcTime, double* cputime)
{
    struct timeval tp;

    gettimeofday(&tp, NULL);
    *wcTime=(double) (tp.tv_sec + tp.tv_usec/1000000.0);

    struct rusage ruse;
    getrusage(RUSAGE_SELF, &ruse);
    *cpuTime=(double)(ruse.ru_utime.tv_sec+ruse.ru_utime.tv_usec / 1000000.0);
}

TO USE:
double  wcs,    //  Wall Clock Start
        wce,    //  Wall Clock End
        ccs,    //  CPU Clock Start
        cce;    //  CPU Clock End
timing(&wcs, &ccs);

//  COMPUTATION CODE

timing(&wce, &cce);

cout << "CPU RUNTIME:       " << cce - ccs << endl
     << "WALL CLOCK TIME:   " << wce - wcs << endl;

A: Variable rate CPU clocks and exploitation of thermal headroom have left me with an increasing suspicion that wall-clock timing in seconds for functions that don't run for long enough to heat the core up are probably not as useful as cycle counts.
If I'm instrumenting my own code, I tend to prefer something like:
static __inline__ uint64_t rdtsc(void)
{
    uint32_t hi, lo;
    __asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
    return ( (uint64_t)lo)|( ((uint64_t)hi)<<32 );
}

Using this, I can record the TSC value before and after a function call, subtract the two, and get the number of cycles spent.
If you want wallclock time, you can use clock_gettime() from from time.h, which will give you nanosecond resolution if not accuracy, and use the following to subtract the two (before and after) struct timespec objects:
#define NSEC_PER_SEC 1000000000
static int timespec_subtract(result, x, y)
struct timespec *result, *x, *y;
{
    /* Perform the carry for the later subtraction by updating y. */
    if (x->tv_nsec < y->tv_nsec) {
        int nsec = (y->tv_nsec - x->tv_nsec) / NSEC_PER_SEC + 1;
        y->tv_nsec -= NSEC_PER_SEC * nsec;
        y->tv_sec += nsec;
    }
    if (x->tv_nsec - y->tv_nsec > NSEC_PER_SEC) {
        int nsec = (x->tv_nsec - y->tv_nsec) / NSEC_PER_SEC;
        y->tv_nsec += NSEC_PER_SEC * nsec;
        y->tv_sec -= nsec;
    }

    /* Compute the time remaining to wait.
       tv_nsec is certainly positive. */
    result->tv_sec = x->tv_sec - y->tv_sec;
    result->tv_nsec = x->tv_nsec - y->tv_nsec;

    /* Return 1 if result is negative. */
    return x->tv_sec < y->tv_sec;
}

That said, I tend to use perf and avoid instrumentation altogether.


text:
Q: TrackTrace is not logging In to Application Insight I have the below code. It's Not logging to Trace.I am not sure why. If possible can you help me on this?
public static void SAPLogger(string Message)
        {

            TelemetryConfiguration.Active.InstrumentationKey = "XXX-XXX-XXX";
            TelemetryClient TelePositive = new TelemetryClient
            {
                InstrumentationKey = "XXX-XXX" (Optional Value)
            };

            //TelePositive.TrackRequest(Req);
            TelePositive.TrackTrace(Message, SeverityLevel.Verbose, new Dictionary<string, string> { { "Information", "SAP" } });

        }

I am calling this method in the Main() method.
static void Main(string[] args)
        {
            try
            {
                int a = 5;
                int c = a / 2;
                SAPLogger("The value is Success" + c);
            }
}

I am totally not sure why this is not logging. Please help

A: Your example app is probably exiting before your telemetry gets sent.
DeveloperMode should cause it to send immediately, however, if your process exists immediately like your test app appears to, the process might still end before the web request gets created and sent.
For short lived applications like that test app, you'll probably need a flush and a sleep call of some kind at the end to ensure telemetry has a chance to send before the app quits.
For a real application that lives for a long time, telemetry will be batched and sent after an amount of time, or number of events is met, then that batch will be sent.  you app probably still would want to flush/wait at the end just to make sure any batched up telemetry gets sent.
but in either case, the flush/wait should only occur once, at the end.  not with every call to track telemetry.


text:
Q: Why doesn't $\binom{n}{a-b}\binom{n-(a-b)}{b}=\binom{n}{a}$? We know that the multiplication principle states that if there are $a$ ways of doing $A$ and $b$ ways of doing $B$ once $A$ has happened, then there are $ab$ ways of performing both actions.
Keeping this in mind, suppose that I have a group of $n$ distinct objects and I want to choose $a$ of them. This can obviously be done in
$$\binom{n}{a}$$ ways.
However, it would seem that I could also first choose $a-b$ objects followed by another $b$ objects from the group of $n$ objects. Now, the number of ways of choosing the first $a-b$ will clearly be
$$\binom{n}{a-b}$$ and once they've been chosen the number of ways of choosing the remaining $b$ items will be $$\binom{n-(a-b)}{b}.$$

Question According to the multiplication principle, it seems that the number of ways of choosing $a$ objects from $n$ should be equal to the number of ways of choosing $a-b$ objects from $n$ followed by $b$ objects from $n-(a-b)$ objects. If so, why doesn't
$$\binom{n}{a-b}\binom{n-(a-b)}{b}=\binom{n}{a}?$$

A: Consider an arbitrary subset of $a$ of your $n$ objects.
Let's call them $\{x_1, x_2, x_3, \ldots, x_a\}.$
When you count
$$ \binom na $$
ways of drawing a subset of size $a,$ you are counting this subset exactly once.
When you choose $a - b$ elements first and then choose another $b$ elements,
you count this subset once by choosing the first $a - b$ elements,
$\{x_1, x_2, \ldots, x_{a-b}\}.$
But you count it again by choosing the last $a - b$ elements,
and again for every other subset of $a - b$ elements among the $a$ elements
of $\{x_1, x_2, x_3, \ldots, x_a\}.$
Since there are
$$ \binom {a}{a - b} = \binom ab $$
subsets of $a - b$ elements you can choose from among the $a$ elements of
$\{x_1, x_2, x_3, \ldots, x_a\},$ you count this subset exactly $ \binom ab $ times.
The same thing happens for every other subset of $a$ elements from among your original $n$ elements.
This is a very common type of overcounting error: first satisfy the condition partway, and then satisfy it the rest of the way, overlooking the fact that for a single desired outcome there are multiple ways to satisfy it partway.
This case is particularly fortunate, however, in that every single outcome is overcounted the exact same number of times.
So what we have discovered is that choosing $a - b$ items from $n$ items, and then choosing $b$ items from the remaining $n - (a - b)$ items,
can be done in exactly $\binom ab$ times as many ways as choosing
$a$ items from the original $n$ items,
or exactly the same number of ways as choosing $a$ items from $n$ and then choosing
$a - b$ items (or $b$ items) from $a$.
So we have discovered a combinatorial proof of the following identity:
$$ \binom n{a-b} \binom{n-(a-b)}b = \binom na \binom a{a-b} = \binom na \binom ab. $$
If we set $k = a$ and $r = (a - b),$ it should be clear that this is the same identity that is proved in
Proving an identity with a combinatorial proof: $\binom{n}{k}\binom{k}{r}=\binom{n}{r}\binom{n-r}{k-r}$.

A: Perhaps the error in your reasoning becomes clear if you consider the following collections, given some set $X$ containing $n$ objects.
$X_1$ = All possible subsets containing $a$ objects in $X$.
$X_2$ = All possible pairs of sets $(A,B)$ where $A$ is a subset containing $a - b$ objects in $X$ and $B$ is a subset containing $b$ objects, such that $A$ and $B$ are disjoint.
$X_1$ contains $\binom{n}{a}$ elements. and $X_2$ should contain $\binom{n}{a - b} \binom{n - (a - b)}{b}$ elements.
Let's say the set of objects is $\{1, 2, 3, 4, 5, 6\}$, and $a = 3, b = 1$. $X_2$ will contain $(\{1, 4\}, \{2\})$, $(\{1, 2\}, \{4\})$ and $(\{2, 4\}, \{1\})$ as different pairs. However, $X_1$ counts only one choice using the same numbers: $\{1, 2, 4\}$. So you can see that $X_2$ generally contains more elements than $X_1$.
Thought-provoking question btw.

A: Expanding out the two quantities, we obtain
\begin{align*}
&\binom{n}{a} = \frac{n!}{a!(n-a)!} \\
\end{align*}
and
\begin{align*}
&\binom{n}{a-b}\binom{n-(a-b)}{b} \\
&= \frac{n!}{(a-b)!(n-(a-b))!} \frac{(n-(a-b))!}{b! (n-a)!} \\
&= \frac{n!}{(a-b)! b! (n-a)!} \\
&= \binom{n}{a-b,b,n-a}
\end{align*}
Since $a!$ isn't generally the same as $(a-b)!b!$, the two quantities aren't equal


text:
Q: PHP Inventory Management Registration I currently have a system where you can login, and insert values into a database to manage inventory. I'm trying to figure out a way to have users able to register and have it automatically create this table for them according to their session id, and then have them re-directed to a page with options to insert data into this table. The PHP code for inserting an item into the database is:
    <?php
    $con=mysqli_connect("localhost","root","root","inventory");

    // Check connection
    if (mysqli_connect_errno($con))
      {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
     }

    $sql = "INSERT INTO `orders` (ItemNumber, Quantity)
       VALUES
            ('".$_POST['ItemNumber']."', '".$_POST['Quantity']."' )";

     if (!mysqli_query($con,$sql))
     {
    die('Error: ' . mysqli_error($con));
     }
     echo "1 record added";

    mysqli_close($con);
     ?>

Can I change this so instead of inserting into "orders", it inserts into the table matching the users session id? Thanks

A: It is not good practice to create a table for each user.
Have an extra field in the orders table to denote the user who placed the order.
Table definition like this,
UserId,ItemNumber, Quantity
Insert Query
     $sql = "INSERT INTO `orders` (UserId,ItemNumber, Quantity)
   VALUES
        ('<UserId goes here from session data>','".$_POST['ItemNumber']."', '".$_POST['Quantity']."' )";

A: Simply add a field in ur orders table which represents id of the user who inserted the order..
The structure of 'orders' table can be like
id primary key,
item_id int,
ordered_by user_id(foreign key)
..


text:
Q: PHP How to prevent mail from leaking script and IP in header I'm using PHPMailer to send out an email.
In the raw message of the email, the header contains
X-PHP-Script: /path/to/my/script.php myip6address, myip4address
I edited into the php.ini these settings
[mail function]
mail.add_x_header = 0
add_x_header = 0

In my php script, when I use ini_get("mail.add_x_header"), it returns "0".
// to try and erase the info from the global server var
$_SERVER = Array();

$mail = new PHPMailer;
$mail->setFrom("me@mysite.com");
$mail->addAddress("foo@gmail.com");

// to try and override it, instead it just appends and keeps the original header
$mail->addCustomHeader("X-PHP-Script", "No.");
$mail->Subject = "This is a test";
$mail->isHTML(true);
$mail->Body = "hello world";

if($mail->send() == false)
{
    var_dump("failed to send mail", $mail->ErrorInfo);
}

It still sends my scripts location and my IP address with every email I send.
It also sends it if I use mail() instead of PHPMailer, but I assume PHPMailer uses mail() under the hood.
How can I disable that header entirely?

A: Im not sure why your ini settings are not suppressing that. PHPMailer does indeed use mail() by default, but you should try using SMTP to localhost instead as it's both faster and safer than mail(), and will give you control over all the headers. All you have to do is:
$mail->isSMTP();

And the default settings should be fine.


text:
Q: How do I use method in this script? I am using ruby-cucumber for automation. The steps are as follows:
Then    I click on "Add this" link
Then    I click on "Next" link

This is the script:
Then(/^I click on "Add this" link$/) do
  @driver.find_element(:link, "Add this").click
end

How should I modify the code so that I can use it both for "Add this" & "Next" repeatedly? Any help/comments is appreciated.

A: Then(/^I click on "([^"]*)" link$/) do |link|
  @driver.find_element(:link, link).click
end

This will then match anything e.g.
Then    I click on "Add this" link
Then    I click on "Next" link
Then    I click on "Foobar" link


text:
Q: My computer freezes suddenly after 1 hour My laptop is Dell Vostro 5480 and it is running Ubuntu 16.04.
I don't know what is wrong but today after 1 hour running, my laptop freeze. I just listening to music and write some stuff.
I remember I upgrade something like ubuntu-core-launcher before this happen. Could this be the reason?
This is the output of lspci -k | grep -EA2 'VGA|3D|Display' :
00:02.0 VGA compatible controller: Intel Corporation Broadwell-U Integrated Graphics (rev 09)
    DeviceName:  Onboard IGD
    Subsystem: Dell Broadwell-U Integrated Graphics
--
08:00.0 3D controller: NVIDIA Corporation GM108M [GeForce 830M] (rev a2)
    Subsystem: Dell GM108M [GeForce 830M]
    Kernel modules: nvidiafb, nouveau

A: Did you got any error message then share it.
first follow these simple steps:

*

*Remove Battery and all other external devices power cable also.

*press the power button and hold it for 1min.

*then try to start.

A: You need to install Nvidia drivers. Run in terminal
sudo apt install nvidia-361 nvidia-prime

and reboot.
If you have UEFI, you need also to disable Secure Boot.