text:
Q: Ribbon Command to read values My javascript is not the best and was wondering if someone could help me out with this. Essentially I have a library with an integer column called PGCount, I want to be able to click this button and it adds to the value of the defined variable pgcount, it is currently alert but I have greater plans for it, if only to get the desired results.
Sadly it is counting the first item twice.
Here is the whole module
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction
  Id="Ribbon.Library.Actions.AddAButton"
  Location="CommandUI.Ribbon"
  RegistrationId="101"
  RegistrationType="List"
  Title="PGCount">
    <CommandUIExtension>
      <CommandUIDefinitions>
        <CommandUIDefinition
           Location="Ribbon.Library.Share.Controls._children">
          <Button Id="Ribbon.Library.Share.NewRibbonButton"
            Command="CountPGCount"
            LabelText="Page Count"
            TemplateAlias="o2" />
        </CommandUIDefinition>
      </CommandUIDefinitions>
      <CommandUIHandlers>
        <CommandUIHandler Command="CountPGCount"
                          CommandAction="javascript:
                            var listitem;
                            var pgcounts = 0;
                            getWebProperties();
                            function getWebProperties() {
                                var ctx = new SP.ClientContext.get_current();
                                var currentWeb = ctx.get_web();
                                var currentListGuid = SP.ListOperation.Selection.getSelectedList();
                                var currentList = currentWeb.get_lists().getById(currentListGuid);
                                var selectedItems = SP.ListOperation.Selection.getSelectedItems();
                                for (i in selectedItems) {
                                    listitem = currentList.getItemById(selectedItems[i].id);
                                    ctx.load(listitem);
                                    ctx.executeQueryAsync(Function.createDelegate(listitem, function () {
                                        var c = listitem.get_fieldValues().PGCount;
                                        pgcounts+=c;
                                    }), null);
                                };}
                                 setTimeout(function () {
                                  alert(pgcounts);
                                }, 3000);"
        EnabledScript="javascript:SP.ListOperation.Selection.getSelectedItems().length >= 1;" />
      </CommandUIHandlers>
    </CommandUIExtension>
  </CustomAction>

  <Module Name="Module1">
  </Module>
</Elements>

Any help would be appreciated!

A: Well I must say I am trilled to bits after working with this all day!
That is not counting the same issue experienced with similar projects as this load multiple items. A conflict always occurs.
Now I know a lot of you cool java heads are gonna say that's wrong here and there and I know that, especially checking the item counts and so on, but I don't think it is too shabby and it will I know help someone. Do feel free to tidy up the code if willing :)
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction
  Id="Ribbon.Library.Actions.AddAButton"
  Location="CommandUI.Ribbon"
  RegistrationId="101"
  RegistrationType="List"
  Title="PGCount">
    <CommandUIExtension>
      <CommandUIDefinitions>
        <CommandUIDefinition
           Location="Ribbon.Library.Share.Controls._children">
          <Button Id="Ribbon.Library.Share.NewRibbonButton"
            Command="CountPGCount"
            LabelText="Page Count"
            TemplateAlias="o2" />
        </CommandUIDefinition>
      </CommandUIDefinitions>
      <CommandUIHandlers>
        <CommandUIHandler Command="CountPGCount" CommandAction="javascript:

                                var rows = new Array();
                                var countofitems = -1;
                                var countogpgcounts = 0;

                                getpgcounts();

                                function getpgcounts() {
                                    var context = new SP.ClientContext.get_current();
                                    var web = context.get_web();
                                    var lists = web.get_lists();
                                    var listId = SP.ListOperation.Selection.getSelectedList();
                                    var list = lists.getById(listId);
                                    var selectedItems = SP.ListOperation.Selection.getSelectedItems();

                                    rows = [];

                                    for (var i in selectedItems) {
                                        var id = selectedItems[i].id;
                                        rows[i] = list.getItemById(id);
                                        context.load(rows[i]);
                                        countofitems++;
                                    }

                                    context.executeQueryAsync(Function.createDelegate(this, show),Function.createDelegate(this, showError));
                                }

                                function show() {

                                    for (i in rows) {
                                        var thiscount = rows[i].get_item('PGCount');
                                        countogpgcounts += thiscount;
                                        if (i == countofitems) {
                                            alert(countogpgcounts);
                                        }
                                    }
                                }

                                function showError(sender, args) {
                                    throw new Error('request failed: ' + args.get_message() + '\n' + args.get_stackTrace());
                                }
"

        EnabledScript="javascript:SP.ListOperation.Selection.getSelectedItems().length >= 1;" />
      </CommandUIHandlers>
    </CommandUIExtension>
  </CustomAction>

  <Module Name="Module1">
  </Module>
</Elements>


text:
Q: Menu click opens a small box? again im having a issues, I'm trying to get when a menu item is clicked then it'll open up a box that has a title and maybe a text box/ btn in it how could I do this?
This is what menu code im using
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.icon:     Toast.makeText(this, "You pressed the icon!", Toast.LENGTH_LONG).show();
                            break;
        case R.id.text:     Toast.makeText(this, "You pressed the text!", Toast.LENGTH_LONG).show();
                            break;
        case R.id.icontext: Toast.makeText(this, "You pressed the icon and text!", Toast.LENGTH_LONG).show();
                            break;
    }
    return true;
}

}

A: Finally figure this out with the help of Egor this is how you have it so when you click a menu item a custom dialog box appears
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.savefile:
            showDialog(SAVE_DIALOG);
    }
    return true;
}
protected Dialog onCreateDialog(int id) {
    Dialog dialog = new Dialog(this);

    switch(id) {
    case SAVE_DIALOG:
        dialog.setContentView(R.layout.savedialog);
        dialog.setTitle("Custom Dialog");
        TextView text = (TextView) dialog.findViewById(R.id.text);
        text.setText("Hello, this is a custom dialog!");
        ImageView image = (ImageView) dialog.findViewById(R.id.image);
        image.setImageResource(R.drawable.icon);
        break;
    default:
        dialog = null;
    }
    return dialog;
}

A: Take a look at AlertDialog. This post has some good examples of creating dialogs. Hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Minor versions for SharePoint custom list I've developed a SharePoint 2007 custom list with a single custom content type derived from Item. The problem is that I only get major versions when enabling versioning on the list. Is it possible to get minor version on a custom list? If not, does anyone know of a post explaining a good approach around how this might be accomplished for a custom list.

A: Minor versions are only available for lists based on SPDocumentLibrary - that is to say, the SPListItems must have an associated SPFile. I think you're out of luck on this unless you decide to implement the minor version as a custom column and maintain it using a custom ItemEventReceiver. Yuck.


text:
Q: Should I test if equal to 1 or not equal to 0? I was coding here the other day, writing a couple of if statements with integers that are always either 0 or 1 (practically acting as bools). I asked myself:
When testing for positive result, which is better; testing for int == 1 or int != 0?
For example, given an int n, if I want to test if it's true, should I use n == 1 or n != 0?
Is there any difference at all in regards to speed, processing power, etc?
Please ignore the fact that the int may being more/less than 1/0, it is irrelevant and does not occur.

A: In language where int that are not 0 represents the boolean value 'true', and 0 'false', like C, I will tend to use if (int != 0) because it represents the same meaning as if (int) whereas int == 1 represents more the integer value being equal to 1 rather than the boolean true. It may be just me though. In languages that support the boolean type, always use it rather than ints.

A: A Daft question really. If you're testing for 1, test for 1, if you're testing for zero, test for zero.
The addition of an else statement can make the choice can seem arbitrary. I'd choose which makes the most sense, or has more contextual significance, default or 'natural' behaviour suggested by expected frequency of occurrence for example.
This choice between int == 0 and int != 1 may very well boil down to subjective evaluations which probably aren't worth worrying about.

A: Two points:
1) As noted above, being more explicit is a win. If you add something to an empty list you not only want its size to be not zero, but you also want it to be explicitly 1.
2) You may want to do
    (1 == int)
That way if you forget an = you'll end up with a compile error rather than a debugging session.

A: Human's brain better process statements that don't contain negations, which makes "int == 1" better way.

A: It really depends.  If you're using a language that supports booleans, you should use the boolean, not an integer, ie:
if (value == false)

or
if (value == true)

That being said, with real boolean types, it's perfectly valid (and typically nicer) to just write:
if (!value)

or
if (value)

There is really very little reason in most modern languages to ever use an integer for a boolean operation.
That being said, if you're using a language which does not support booleans directly, the best option here really depends on how you're defining true and false.  Often, false is 0, and true is anything other than 0.  In that situation, using if (i == 0) (for false check) and if (i != 0) for true checking.
If you're guaranteed that 0 and 1 are the only two values, I'd probably use if (i == 1) since a negation is more complex, and more likely to lead to maintenance bugs.

A: To be honest if the value of int is just 1 or 0 you could even say:
if (int)

and that would be the same as saying
if (int != 0)

but you probably would want to use
if (int == 1)

because not zero would potentially let the answer be something other than 1 even though you said not to worry about it.

A: If only two values are possible, then I would use the first:
if(int == 1)

because it is more explicit. If there were no constraint on the values, I would think otherwise.

A: IF INT IS 1
NEXT SENTENCE
ELSE MOVE "INT IS NOT ONE" TO MESSAGE.

A: As others have said, using == is frequently easier to read than using !=.
That said, most processors have a specific compare-to-zero operation. It depends on the specific compiler, processor, et cetera, but there may be an almost immeasurably small speed benefit to using != 0 over == 1 as a result.
Most languages will let you use if (int) and if (!int), though, which is both more readable and get you that minuscule speed bonus.

A: I'm paranoid. If a value is either 0 or 1 then it might be 2. May be not today, may be not tomorrow, but some maintenance programmer is going to do something weird in a subclass. Sometimes I make mistakes myself [shh, don't tell my employer]. So, make the code say tell me that the value is either 0 or 1, otherwise it cries to mummy.
if (i == 0) {
    ... 0 stuff ...
} else if (i == 1) {
    ... 1 stuff ...
} else {
    throw new Error();
}

(You might prefer switch - I find its syntax in curly brace language too heavy.)

A: If you're working with values that can only be 1 or 0, then I suggest you use boolean values to begin with and then just do if (bool) or if (!bool).

A: When using integers as booleans, I prefer to interpret them as follows: false = 0, true = non-zero.
I would write the condition statements as int == 0 and int != 0.

A: I would say it depends on the semantics, if you condition means
while ( ! abort ) negation is ok.
if ( quit ) break; would be also ok.

A: if( is_numeric( $int ) ) { its a number }
elseif( !$int ) { $int is not set or false }
else { its set but its not a number }

end of discussion :P

A: I agree with what most people have said in this post. It's much more efficient to use boolean values if you have one of two distinct possibilities. It also makes the code a lot easier to read and interpret.
if(bool) { ... }

A: I was from the c world. At first I don't understand much about objective-c. After some while, I prefer something like:
if (int == YES)

or
if (int == NO)

in c, i.e.:
if (int == true)
if (int == false)

these days, I use varchar instead of integer as table keys too, e.g.
 name   marital_status
------  --------------
 john      single
 joe       married

is a lot better than:
 name   marital_status
------  --------------
 john         S
 joe          M

or
 name   marital_status
------  --------------
 john         1
 joe          2

A: (Assuming your ints can only be 1 or 0) The two statements are logically equivalent.  I'd recommend using the == syntax though because I think it's clearer to most people when you don't introduce unnecessary negations.


text:
Q: How to assign and change the value of a QString? I would like to know how to assign and change the value of a QString variable. If I wanted to assign the QString value as 0, how would I do it?

A: It is important to note that 0 is an integer and QString is a...well QString.  I'm assuming you'd like to convert the 0 to a string first then assign that to the QString.   There a couple of ways to do this, the easiest is to just do:
QString s = "0";

If you are trying to assign an int variable to a string you can do:
int i = 0;
QString s("%1").arg(i);

The parameter in the first arg call will fill the places of %1, the second arg call fills the value of %2, etc.  arg will convert the int to a string.
To later change the value you can do:
QString s = "0";
s = "This value has changed to something else";

A: You can assign any string to a QString as follows.
QString a="this is a string";
QString b="250"; //though this is a number it is in a string format now in the variable b

If you want to take it for calculations then a conversion is needed. Simply convert it to an int:
int i;
i=b.toInt(); // i holds the integer 250 now.

Do calculations and convert it back to a string before displaying it in a label or something:
i=(i*5)+650; //just a calculation.
a=QString::Number(i); // now i is converted to a string and assigned to a

Simply display it in a QLabel as follows:
ui->label->setText(a);


text:
Q: Python convert docx to html using mammoth: html, head and body tag missing I am trying to convert a simple docx file into HTML file using mammoth package. But it seems that the generated html contains only part of a full HTML file: the HTML, head, and body tags are all missing in the generated html string.
I wonder if there are parameters to make the HTML become valid HTML code.

A: I read the doc and haven't found an option to generate the full HTML. Since the generated HTML is just a string, it is easy to make it a full HTML-compliant:
import mammoth

with open("test.docx", "rb") as docx_file:
    result = mammoth.convert_to_html(docx_file)
    html = result.value  # The generated HTML
    messages = result.messages  # Any messages,

    full_html = (
        '<!DOCTYPE html><meta charset="utf-8"/>'
        + html
        + ""
    )

    with open("test.html", "w", encoding="utf-8") as f:
        f.write(full_html)

In the above code, we just prepend and append the necessary opening and closing tags to make the html string a valid HTML source code.


text:
Q: Magento on LocalHost - Links Not Working? Eugh, i'm honestly banging my ahead against the brick wall with this.
I have my Magento site hosted on the localhost so that I can make changes without affecting the live site. Everything works perfectly EXCEPT none of the links seem to be working. If I click anything on the site, nothing even attempts to load.
Backend loads fine, but the frontend links won't work at all.
Any ideas? Pleaaaaase.
UPDATE: My unsecure site Base URL shows: http://127.0.0.1:8888/magento/
My secure site Base URL shows the same: http://127.0.0.1:8888/magento/
I access the frontend of my store by visiting: http://127.0.0.1:8888/magento/  or  http://127.0.0.1:8888/magento/index.php/
And I access the bankend of my store by visitng:http://127.0.0.1:8888/magento/index.php/admin

A: Alan Kent posted a great article recently on Magento 2 behavior similar to what you describe that linked to this Stack Overflow discussion, but the key concepts are relevant to 1.X as well since it's more generally about cookie implementation logic not specific to Magento's codebase.
In short, the fundamental implementation of cookie handling logic has some requirements included within it to check for the presence of certain attributes of a domain name:

I broadly agree with @Ralph Buchfelder, but here's some amplification
  of this, by experiment when trying to replicate a system with several
  subdomains (such as example.com, fr.example.com, de.example.com) on my
  local machine (OS X / Apache / Chrome|Firefox).
I've edited /etc/hosts to point some imaginary subdomains at
  127.0.0.1:
127.0.0.1 localexample.com
  127.0.0.1 fr.localexample.com
  127.0.0.1 de.localexample.com If I am working on fr.localexample.com and I leave the domain parameter out, the cookie is stored correctly
  for fr.localexample.com, but is not visible in the other subdomains.
If I use a domain of ".localexample.com", the cookie is stored
  correctly for fr.localexample.com, and is visible in other subdomains.
If I use a domain of "localexample.com", or when I was trying a domain
  of just "localexample" or "localhost", the cookie was not getting
  stored.
If I use a domain of "fr.localexample.com" or ".fr.localexample.com",
  the cookie is stored correctly for fr.localexample.com and is
  (correctly) invisible in other subdomains.
So the requirement that you need at least two dots in the domain
  appears to be correct, even though I can't see why it should be.

Thus, the best way to configure your local development environment to make sure you see behavior similar to your live environments is to update your hosts file to map a domain, any domain, to your local system, as long as it has a format of
xxx.yyy.zzz <- includes two 'dots' in the domain name
We've adopted a process of adding something like the following for sites we develop to our hosts file to make sure we don't have to fight with this kind of problem:
127.0.0.1 dev.somesite.com
127.0.0.1 dev.someothersite.com
After doing this, the odd behavior you describe no longer happens in our dev environments and we can get back to coding :)
You may still need to perform one of these  two approaches to troubleshoot this kind of issue to make sure you create the correct local host entry in your hosts file:

*

*If you have a (your_database_system) client that can connect to the database you're using, open it and run the following query:
select * from core_config_data where path like '%base%url%';
On my mySQL system I can open up MySQL Workbench and see something like the following:

*Since you can also login to your Magento Admin back-end, you can also try browsing to the following menu option:
System -> Configuration -> Web which should display the following page.
Expand the Unsecure and Secure accordions and you should look for the fields marked Unsecure : Base URL and Secure : Base URL :

Add what you see in the Unsecure : Base URL and Secure : Base URL fields along with the URL your browser is displaying when you access the back-end and front end  in the comments and we can figure out what's happening and a way to restore your functionality:


text:
Q: How to get count of multiple column using sql    My table like
   ---------------
      trtm       t_date          id_no  certno1   certno2  certno3  certno4  certno5  certno6 certno7 certno8 certno9  certno10
       TM       15/02/2002       A12      2158
       TM       15/02/2010       A13      8181     8182     8183     8184     8185     8186     8187     8188      8189     8190
       TM       15/02/2010       A14      19138
      -------------------

I need to take count of id_no and certno from 1 to 10
   my query is
   ----------
  select count(id_no) as total_id,count(CONCAT(certno1, certno2, certno3,certno4,certno5,certno6,certno7,certno8,certno9,certno10)) as certificate from table where trtm='TM'
  ----------
  my output is:
   ---------
   total_id      certificate
       3             3
  -------------------------

but i need the count of certificate where the values are there is 3 but i need is 12
  ------------
  output needs:
  -----------
  total_id      certificate
       3             12
  -------------

i am getting only the count in both total_id and certificate.so, please help me if anybody knows.

A: Assuming the "empty" certX fields are nulls, you'd need something like this:
SELECT (cert1 is not null) + (cert2 is not null) + ... (cert10 is not null)

Each is not null test will return a boolean true/false, which will be typecast to integers by mysql, and converted into a basic 1+1+0+1+....-type addition operation.

A: Count separately and then SUM it:
SELECT
    count(id_no) as total_id,
    (count(certno1) +
        count(certno2) +
        count(certno3) +
        count(certno4) +
        count(certno5) +
        count(certno6) +
        count(certno7) +
        count(certno8) +
        count(certno9) +
        count(certno10)) as certificate
FROM table
WHERE trtm='TM';


text:
Q: Best Way To Store Multiple Arrays Associated Together - Objective C Throughout my iOS program. I create multiple arrays that all work together to make the program work. Now I need a method to store the arrays even when the iPhone is turned off. So I need these arrays to be stored like files that only I can touch.
I really would like to use User Defaults, but I just don't know if that is what I need. I have questions like:

*

*How long will my data last in User Defaults?

*When could you possibly lose the data?

If I was able to store arrays in User Defaults, how might I go about storing arrays in NSDictionaries? That way I could keep of my associated arrays together and give each array a specific key.

A: store array as NSData as in NSDefaults
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:urArray1] forKey:@"Array1"];

[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:urArray2] forKey:@"Array2"];

and read it as
 NSData *dataRepresentingSavedArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"Array1"];
 if (dataRepresentingSavedArray != nil)
      NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray];

A: I think that what you want is to store the arrays on the disk and then (when you actually need them) get them back. You can start by seeing if the objects inside your NSMutableArrays conform with the NSCoding protocol. You can then simply write them to disk and load them when you need. For that you can use NSKeyedArchiver class.

As @The Saad pointed, and well, you can store the arrays using that piece of code. Although I wouldn't recommend it. You can check @roronoa zorro answer, as well.

A: Well NSuSerDefaults is a way of storing persistent data in iPhone and you don't have to worry about losing of data or about it's persisitency as long as the application remains on the iPhone.
    Yes, you can store the NSDictionary object in NSUserDefaults but it is advisable to use it for small Data.For bigger data you can use sqlite or any other DB.
Here's the Tutorial For NSUserDefault

A: NSUserDefaults basically just a wrapper around property list serialization.

NSUserDefaults provides a programmatic interface to Mac OS X's
  preferences system. preferences are actually stored to the disk, they
  are written to the user's Library/Preferences/ directory with the file
  name equal to the bundle identifier with a plist extension.

Take a look at MikeBeam's article here


text:
Q: Can't copy or delete certain files and explorer.exe uses over 50% CPU Not sure what to do. I can't copy, overwrite or delete certain files in certain locations, like the desktop. They look like they are copying or deleting but the get stuck at 0%. Also, explorer.exe sometimes uses upwards of 50% to 90% CPU. This makes the system pretty unusable.
I ran SFC and it says "Windows Resource Protection did not find any integrity violations."
I'm not sure how to proceed.


text:
Q: Forwarding journald to Cloudwatch Logs I'm a newbie to CentOS and wanted to know the best way to parse journal logs to CloudWatch Logs.
My thought processes so far are:

*

*Use FIFO to parse the journal logs and ingest this to Cloudwatch Logs,  - It looks like this could come with draw backs where logs could be dropped if we hit buffering limits.

*Forward journal logs to syslog and send syslogs to Cloudwatch Logs --
The idea is essentially to have everything logging to journald as JSON and then forward this across to CloudWatch Logs.
What is the best way to do this? How have others solved this problem?

A: Take a look at https://github.com/advantageous/systemd-cloud-watch
We had problems with journald-cloudwatch-logs. It just did not work for us at all.
It does not limit the size of the message or commandLine that it sends to CloudWatch and the CloudWatch sends back an error that journald-cloudwatch-logs cannot handle which makes it out of sync.
systemd-cloud-watch is stateless and it asks CloudWatch where it left off.
systemd-cloud-watch also creates the log-group if missing.
systemd-cloud-watch also uses the name tag and the private ip address so that you can easily find the log you are looking for.
We also include a packer file to show you how to build and configure a systemd-cloud-watch image with EC2/Centos/Systemd. There is no question about how to configure systemd because we have a working example.

A: Take a look at https://github.com/saymedia/journald-cloudwatch-logs by Matin Atkins.
This open source project creates a binary that does exactly what you want - ship your (systemd) journald logs to AWS CloudWatch Logs.
The project depends on libsystemd to forward directly to CloudWatch.  It does not rely on forwarding to syslog.  This is a good thing.
The project appears to use golang's concurrent channels to read the logs and batches writes.

A: Vector can be used to ship logs from journald to AWS CloudWatch Logs.
journald can be used as a source and AWS Cloudwatch Logs as a sink.
I'm working on integrating this with an existing deployment of about 6 EC2 instances that generate about 30 GB of logs daily.  I'll update this answer with any caveats or gotchas after we've used Vector in production for a few weeks.
EDIT 8/17/2020
A few things to be aware of.  The match batch size for the PutLogEvents is 1MB and there is a max of 5 requests per second per stream.  See the limits here..
To help with that, in my set up each journald unit has it's own log stream.   Also, there are a lot of fields that the Vector journald sink includes, I used a vector transform to remove all the ones I didn't need.  However, I'm still running into rate limits.
EDIT 10/6/2020
I have this running in production now.  I had to update the version of vector I was using from 0.8.1 to 0.10.0 to take care an issue with vector not respecting the max bytes per batch requirement for AWS CloudWatch logs.  As far as the rate limit issues I was experiencing, it turns out I wasn't having any issues.  I was getting this message in the vector logs tower_limit::rate::service: rate limit exceeded, disabling service.  What that actually means is that vector is pausing send logs temporarily to respect the rate limit of the sink. Also, each Cloudwatch Log Stream can consume up to 18 GB per hour which is fine for my 30 GB per day requirement for over 30 different services on 6 VMs.
One issue I did run into was causing the CPU to spike on our main API service.  I had a source for each service unit to tail the journald logs.  I believe this somehow blocked our API from not being able to write to journald (not 100% though).  What I did was have one source and specified multiple units to follow so there was only one command tailing the logs and I increased the batch size since each service generates a lot of logs.  I then used vector's template syntax to split the Log Group and Log Stream based on the service name.  Below is an example configuration:
[sources.journald_logs]
  type = "journald"
  units = ["api", "sshd", "vector", "review", "other-service"]
  batch_size = 100

[sinks.cloud_watch_logs]
  type = "aws_cloudwatch_logs"
  inputs = ["journald_logs"]
  group_name = "/production/{{host}}/{{_SYSTEMD_UNIT}}"
  healthcheck = true
  region = "${region}"
  stream_name = "{{_SYSTEMD_UNIT}}"
  encoding = "json"

I have one final issue I need to iron out, but it's not related to this question.  I'm using a file source for nginx since it writes to an access log file.  Vector is consuming 80% of the CPU on that machine getting the logs and sending them to AWS CloudWatch.  Filebeat also runs on the same box sending the logs to Logstash, but it's never caused any issues.  Once we get vector working reliably we'll retire the Elastic Stack, but for now we have them running side by side.


text:
Q: How to create a javascript functions that accept parameters or type and methods I am a novice in javascript programming and just want to learn more about functions and fascinated with javascript libraries like jquery and I am intrigued by how was it made and I also noticed that all pre-functions like ajax accept parameters,type or methods like below.
$.ajax({
    type: 'POST',
    url : 'test.php',
    data : XXX
})

My question is how does it process this parameter? or how to construct a similar function like above.

A: It's just an object stored in the variable $ with the property ajax, which is a function, which takes an object as a parameter:

    var $ = {
        ajax: function(params) {
            console.log(params.type, params.url, params.data);
        }
    }

    $.ajax({
        type: 'POST',
        url : 'test.php',
        data : { test: 'data' }
    })

A: It's a "normal" function where the parameter you pass is a object. So you can build a function like so:

var myFunction = function(options) {
    console.log(options.one);
    console.log(options.two);
};

var someObject = {
    one: 'one',
    two: 'two'
};

myFunction(someObject);

// which is the same as

myFunction({one: 'blubb', two: 'blubb two'});

So now the problem might be that someone uses the function without setting the options so you can set default if no options are set like so

var myFunction = function(options) {
    var options = options || {};
        options.one = options.one || 'hello';
        options.two = options.two || 'world';
    console.log(options.one);
    console.log(options.two);
};

myFunction();


text:
Q: belongs_to id not being set activeadmin I have two models: Asssessment and Question which are organized like this:
class Question < ActiveRecord::Base
    belongs_to :assessment

class Assessment < ActiveRecord::Base
    has_many :questions

I'm trying to create an activeadmin (ver 1.0.0) interface to create assessments and add questions to them.
So far I've tried making a questions tab:
ActiveAdmin.register Question do
  permit_params :question_text, :question_type, :scale_min, :scale_max

  form do |f|
    f.inputs "Question Information" do
      f.input :assessment, :as => :select, :collection => Assessment.non_daily_assessments
      f.input :question_type, :as => :select, :collection => Question.human_readable_question_types.keys
      f.input :question_text, :input_html => {:rows => 2, :cols => 10}
      f.input :scale_min
      f.input :scale_max
    end
    f.actions
  end

non_daily_assessments simply returns a subset of all assessments
I am able to select from a list of assessments, but when I save the question and am taken to the "view question" page the question's assessment_id is empty.
Similarly, if I create an assessments tab:
ActiveAdmin.register Assessment do
  permit_params :name, :questions

  form do |f|
    f.inputs "Assessment Information" do
      f.input :name, :input_html => {:rows => 1, :cols => 10}
      f.has_many :questions, :allow_destroy => true, :heading => 'Questions' do |qf|
        qf.input :question_type, :as => :select, :collection => Question.human_readable_question_types.keys
        qf.input :question_text, :input_html => {:rows => 2, :cols => 10}
        qf.input :scale_min
        qf.input :scale_max
      end
    end
    f.actions
  end

I am able to go to a particular assessment and start adding questions, but when I reload the page they're gone. Going into the console I see that the questions were created, but their assessment_id's are nil just like through the question tab.
What is a correct way to create an activeadmin interface for a belongs_to has_many relationship?
Let me know if you need more information.

A: Your permit_params are incomplete. Have a look at this answer: Nested form in activeadmin not saving updates
You need to add :assessment_id to the permit_params in the Question section, and if you want to be able to edit questions with the assessments, you're probably missing the accepts_nested_attributes_for :questions in the Assessment model, and you'll also need to change the permit_params in the Assessment section to something like
permit_params :name, questions_attributes: [:id, :question_type, :question_text, :scale_min, :scale_max]


text:
Q: dynamically configuring .NET client via socket Anyone have a pointer to a C# configuration class that a .NET service can use to do configurations via an admin socket or other control port? I'd rather do this than a filewatcher on the app.config file.
We have some long running C#/.NET services (24h X 6.5 days/week) that may need to be re-configured on the fly. I'm looking for a good way to push out config changes to a .NET service
Any pointers appreciated.
Craig

A: How about exposing a WCF service for configuration purposes? That way you can get a nicely typed API for configuration of the service.

A: To expand on Manga's answer;
I'd recommend hosting a WCF endpoint on the same IIS box hosting your long running C#/.NET services.  This endpoint run on an arbitrary port.
Its responsiblity would simply be to change the appconfig(s) of your running service(s).  You could specify a config type decorated with DataContract to allow for a nice configuration API exposed to the client responsible for pushing the config changes.

A: I'm not experienced with WCF, but I've typically solved this problem by rolling my own API via RPC. Expose some methods to add/remove/update certain configuration items, throw some sort of UI on top of it, and you can update your service on the fly.


text:
Q: How can I fix this issue with flutter unity widget? LOGS:
e: C:\src\flutter\.pub-cache\hosted\pub.dartlang.org\flutter_unity_widget-4.2.5\android\src\main\kotlin\com\xraph\plugin\flutter_unity_widget\FlutterUnityWidgetController.kt: (14, 27): Unresolved reference: MultiWindowSupport
e: C:\src\flutter\.pub-cache\hosted\pub.dartlang.org\flutter_unity_widget-4.2.5\android\src\main\kotlin\com\xraph\plugin\flutter_unity_widget\FlutterUnityWidgetController.kt: (232, 17): Unresolved reference: MultiWindowSupport
e: C:\src\flutter\.pub-cache\hosted\pub.dartlang.org\flutter_unity_widget-4.2.5\android\src\main\kotlin\com\xraph\plugin\flutter_unity_widget\FlutterUnityWidgetController.kt: (239, 17): Unresolved reference: MultiWindowSupport
e: C:\src\flutter\.pub-cache\hosted\pub.dartlang.org\flutter_unity_widget-4.2.5\android\src\main\kotlin\com\xraph\plugin\flutter_unity_widget\FlutterUnityWidgetController.kt: (245, 13): Unresolved reference: MultiWindowSupport
e: C:\src\flutter\.pub-cache\hosted\pub.dartlang.org\flutter_unity_widget-4.2.5\android\src\main\kotlin\com\xraph\plugin\flutter_unity_widget\FlutterUnityWidgetController.kt: (250, 13): Unresolved reference: MultiWindowSupport

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':flutter_unity_widget:compileDebugKotlin'.
> Compilation error. See log for more details

I've added this :
buildscript {
    ext.kotlin_version = '1.5.10'
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:4.1.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

Did : -flutter upgrade
-flutter clean
-flutter pub get
-flutter pub upgrade
-deleted android/.gradle

A: This problem is from .pub-cache so just flutter clean, if the error still persist delete all the .pub-cache then
you can also check the link to related link
flutter clean
and pub get


text:
Q: Не могу создать массив в js с выходными данными Задача: Функція getOutdated приймає масив роботів robots і повертає масив індексів для роботів, у яких core_version менший за нову версію newVersion ПЗ.
Приклад:
const robots = [{core_version: 9}, {core_version: 13}, {core_version: 16}, {core_version: 9}, {core_version: 14}];

getOutdated(robots, 10) === [0, 3]
getOutdated(robots, 14) === [0, 1, 3]
getOutdated(robots, 8) === []
getOutdated(robots, 18) === [0, 1, 2, 3, 4]

Вопрос: в консоль мне сбоку (на фото) выводит правильные индексы, но я никак не могу собрать их в один массив, чтобы вывести, что я делаю неправильно и как доделать?
Мое решение сейчас :
function getOutdated(robots, newVersion) {
  //let number = [];

  for (let i = 0; i < robots.length; i++) {
    //console.log(robots[i]);

    if(robots[i].core_version < newVersion) {
      console.log(robots.indexOf(robots[i]));
    }
  }
}

A:

function getOutdated(robots, newVersion) {
  let results = [];
  for (let i = 0; i < robots.length; i++) {
    if(robots[i].core_version < newVersion) {
      results.push(i);
    }
  }
  return results;
}

const robots = [{core_version: 9}, {core_version: 13}, {core_version: 16}, {core_version: 9}, {core_version: 14}];

console.log(JSON.stringify(getOutdated(robots, 10))); // === [0, 3]
console.log(JSON.stringify(getOutdated(robots, 14))); // === [0, 1, 3]
console.log(JSON.stringify(getOutdated(robots, 8))); // === []
console.log(JSON.stringify(getOutdated(robots, 18))); // === [0, 1, 2, 3, 4]


text:
Q: Huffman code - Probability of finding a specific bit in the code Let $X$ be a random variable in $A = \{1,2,3,4\}$ with pmf $p(1) = \frac{1}{8}$, $p(2) = \frac{1}{8}$, $p(3) = \frac{1}{4}$ and $p(4) = \frac{1}{2}$. Let $c$ be the binary Huffman code $c(1) = 110$, $c(2) = 111$, $c(3) = 10$ and $c(4) = 0$. Generate a sequence in $A^n$ iid based on pmf p, then encode the sequence using $c$. Pick a bit uniformly at random from this encoded sequence. What is the probability that this bit is $1$?

A: This is a very special case of Huffman coding that every symbol has a power of $2^{-k}$ for the length of k. This is the case that the expected length of Huffman is equal to the entropy of the source.
It also results in the sequence generated from i.i.d. source to have random i.i.d. bitstream. So independent of the position, all bits have an equal probability of $1/2$.
For your case, I will explain case by case. Assume that the bit we pick is the 3rd bit of a Huffman codeword then the probability of getting 0 of the codeword 110 is equal to getting 1 of 111 both equal to 1/8.
Now assume that we pick the 2nd bit, the probability of getting 1 is (1/8+1/8=1/4) for the codewords of 110 and 111 and the probability of getting 0 is 1/4 for codeword 10. And if you picked the 1st bit, you have a probability of 1/2 of getting 0 of the codeword 0, and a probability of getting 1 is (1/8+1/8+1/4=1/2) for the codewords 110, 111, and 10. So independent of where your bit is the probability of 0 and 1 are equal.


text:
Q: Como utilizar o PIVOT no select Olá, eu queria separa uma informação que esta em linha transformando em coluna, é uma tabela de preço nela contém 5 linhas e uma delas é o custo queria transforma essa linha em coluna no select dos produtos que fiz segue o select que to usando
use S9_Real
go
select p.Codigo, p.Nome, p.Codigo_Barras, pp.Preco, u.Descricao, n.Codigo, c.Codigo, t.Nome,
[1] as [Custo],
[2] as [Custo medio]
from Prod_Serv p
left join Prod_Serv_Precos pp on pp.Ordem_Prod_Serv=p.Ordem
left join Unidades_Venda u on u.Ordem=p.Ordem_Unidade_Venda
left join NCM n on n.Ordem=p.Ordem_NCM
left join CEST c on c.Ordem=p.Ordem_CEST
left join Tabelas_Preco t on pp.Ordem_Tabela_Preco=t.Ordem
PIVOT (MAX(t.nome) for t.Ordem  in ([1],[2])) p order by 1

porém não deu resultado esse select, retirando os dados do PIVOT ele funciona me traz as informação dessa forma
Resultado do Select
o que eu quero fazer é pegar a linha Custo e o preço e criar uma coluna
estou fazendo pelo management studio


text:
Q: Upload data from a webpage to an IPFS How can we upload data from a webpage to an IPFS server? In IPFS, I have already uploaded a .txt/JSON empty file.
The file can either be a .txt or a JSON  file.

A: If i understand your question correctly,you are trying to upload something from your webpage to IPFS cluster(at least this is the basic context i understand).
So with this intent i would say this is possible.
What you need to do is
a. Upload the file in a local IPFS node using the IPFS api(Read the official documentation) and getting the content identifier(cid) from your webpage.
Problem:

*

*What happens when the local node is not available?(You shutdown your computer simply!!)

*The file yo upload will be garbage collected after it is not used for some time as a result you lose the data completely.

Solution:
Use a Pinning service.Pinning is the mechanism that allows you to tell IPFS to always keep a given object somewhere where it is always accessible and save it from the internal Garbage collection that the system performs.
The default pinning location is your local computer node and you can do that using the IPFS specified API.
You can also use other pinning service available like Pinnata where you can host the content in their node itself(You scale the number of nodes and you pay!)
In this way you can guarantee that the content is always served and online.
Hope this helps you to get started with.


text:
Q: Signal Sigabrat when pushing button in storyboard Hi I have an error when I press my button in one page to connect to another view
would you please help me
Thanks in advance!
Here is my code
-(void)buttonPressed:(UIButton *)button
{
NSLog(@"button %u -- frame: %@", button.tag, NSStringFromCGRect(button.frame));
[self performSegueWithIdentifier:@"WeekView" sender:self];

}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString: @"WeekView"]){

    [segue.destinationViewController setTitle:@"WeekView"];
    }}

this error in this line
with debugging = Signal Sigabrat start from here

 [self performSegueWithIdentifier:@"WeekView" sender:self];

I also identify WeekView in Segue and also use shipt+command+K to clean but still error

A: You have to initialize your destinationviewcontroller before you can change properties:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString: @"WeekView"]){

SecondViewController*second=segue.destinationViewController;   //You´re missing this line.

second.title=@"WeekView";    // now you can do stuff on your destinationViewController

    }}

I hope it fixes it.


text:
Q: How to update Gtk::TreeModel::Row from external function Currently I'm developing a multi-thread application. I use a TreeView to display the states of each thread, one row per thread.
There are mainly two classes:

*

*Main GUI class containing TreeView

*class for thread handling

Passing Gtk::TreeModel::iterator as an argument to the second class is not viable since we cannot access the elements in row in formats like row[m_Columns.m_id].
Using Glib::Dispatcher is also unavailable since the elements we change in the external function is thread-specific.
So, is there any practical method to update GUI from external functions?

A: It's available to declare a class for Columns in an external file and include the file in both GUI class file and thread class file.
Like
class Columns : public Gtk::TreeModel::ColumnRecord
{
public:
    Gtk::TreeModelColumn<unsigned int> m_id;
    Gtk::TreeModelColumn<Glib::ustring> m_pin;
    Gtk::TreeModelColumn<Glib::ustring> m_name;
    Gtk::TreeModelColumn<unsigned int> m_percentage;
    Gtk::TreeModelColumn<Glib::ustring> m_status;

    Columns()
    {
        add(m_id);
        add(m_pin);
        add(m_name);
        add(m_percentage);
        add(m_status);
    }
};

So that if you created a Columns instance m_columns in GUI class, and passed it as a parameter to thread class, you can use
(*row)[m_columns.m_id]

to access the elements in TreeModel.

A: I think you should rethink your architecture. The simpliest and safest way is for your thread to send information in a thread safe way to a class that will gather them. Then make your GUI thread read those informations, change your treevien and then refresh.
I use this paradigm in a big gtkmm/multithreaded application. Remember that it is always better to centralize your synchronization code.
I hope it helps.


text:
Q: Bootstrap Glyphicons not showing in Cakephp I am using CakePhp 3.4.7 and Bootstrap 3.3.7 and Bootstrap is working fine except that Glyphicons are not showing. Here's what my Login page looks like and you can see the icons are missing: http://i.imgur.com/wTAZEyO.jpg
I placed all the glyphicons-halflings-regular.* fonts in the App/webroot/font directory and the bootsrap.min.css in App/webroot/css and bootsrap.min.js/jquery-3.2.1.min.js in App/webroot/js
And inspecting my website I can see both css and js files are being pulled correctly and in fact the code is working: http://i.imgur.com/mFO3HWhh.jpg
Here is my code
DEFAULT CTP HEAD
<!DOCTYPE html>

<?= $this->Html->charset() ?>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>
    <?= $cakeDescription ?>:
    <?= $this->fetch('title') ?>
</title>
<?= $this->Html->meta('icon') ?>

<?= $this->Html->css('bootstrap.min.css') ?>
<?= $this->Html->script('jquery-3.2.1.min.js') ?>
<?= $this->Html->script('bootstrap.min.js') ?>

<?= $this->fetch('meta') ?>
<?= $this->fetch('css') ?>
<?= $this->fetch('script') ?>

LOGINT CTP
<?
// Path File: \App\src\Templates\Usuarios\login.ctp
/** @var $this \Cake\View\View */
?>

  Formulario de ingreso al sistema

                <?= $this->Flash->render('auth') ?>
                <form id="loginform" class="form-horizontal" role="form" method="post" action="<?php echo $this->Url->build(["controller" => "Usuarios", "action" => "login"]) ?>">
                    E-Mail

                        @
                        <input id="login-username" type="text" class="form-control" name="email" value="" placeholder="E-Mail">

                    Clave

                        <input id="login-password" type="password" class="form-control" name="password" placeholder="Clave">

                            <button type="submit" id="btn-login" class="btn btn-primary btn-block"> ENTRAR</button>

                </form>

I can see that in my bootstrap.min.css files the path is correct. Any idea why Cake is not pulling the icons even though they exist?

A: *

*Go to your CSS folder.

*Open the bootstrap.min.css file.

*Search for glyphicon text in that.

*You can find out its url address.

*You should change the font folder name to fonts.

*Go and enjoy your life. :)


text:
Q: Bootstrap 4 center align full height no scrolling I would like to clarify that this is a basic page and there will be no scrolling whatsoever and minimal text.
I have been trying to use Bootstrap 4 to align text to the direct middle of the page, then also having a footer at the bottom of the page, also centered.
I currently have the following

        Test

    Anything here adds a scrollbar

I have tried to change the h-100 and split the classes up into different divs to see if that would make a difference, but it does not.
I have also tried things like (with this, it works, besides a scrollbar being added to the page and to see the footer I need to scroll down):

Hi!

        Footer

A: The vertical center aspect of this question is duplicate: Vertical Align Center in Bootstrap 4
The page height and no scrolling aspect of the question, "no scrolling whatsoever... direct middle of the page, then also having a footer at the bottom of the page" requires flexbox to fill the height. h-100 won't work since it pushes the footer over height:100% and thus requires scrolling to see the footer (or hides the footer).
.cover-container {
    height: 100vh;
}

.flex-fill {
    flex: 1 1 auto;
}

HTML

Hi!

        Footer

https://www.codeply.com/go/CIMvZxkT4O
Note: The flex-fill class will be included in Bootstrap 4.1 so the extra flex-fill CSS will no longer be needed when 4.1 is released.

Related question:
Bootstrap 4 expanded navbar and content fill height flexbox

A: Try this:
Change<div class="cover-container text-center" to
 and add justify-content-center class to

Hi!

    Footer


text:
Q: unable to adjust elements according to screen in swiftui I'm trying to adjust elements based on screen sizes. .for example for the car I used a frame for image and set its width and height
.frame(width: geometry.size.width * 0.6, height:geometry.size.width * 0.6*2.094)

0.6 because I want its width to be 0.6 times that of the screen width. and multiplied 2.094 to height because original image height is 2.094 times that of width. and I also set the image position as
.position(x: geometry.size.width - geometry.size.width * 0.68, y: geometry.size.height - geometry.size.height*0.38 )

But as you can see that the spacing from the bottom is less on small screen than a large screen. Geometry reader has width and height same as that of the screen.
My questions are:

*

*Shouldn't the spacing from the bottom be concurrent in all screens as I'm setting the image width, height as well as position w.r.t. the screen dimensions?

*I used width: geometry.size.width * 0.6 because I wanted image width to be 60% of screen width. Is there any better approach to solve this problem?
The code:
GeometryReader { geometry in
            ZStack{

                Image("TeslaCar")
                    .resizable()
                    .aspectRatio(contentMode: .fit)

                    .frame(width: geometry.size.width * 0.6, height:geometry.size.width * 0.6*2.094)
                    .background(Color.yellow)
                    .position(x: geometry.size.width - geometry.size.width * 0.68, y: geometry.size.height - geometry.size.height*0.38 )
            }
        .frame(width: screen.width, height: screen.height)
        .edgesIgnoringSafeArea(.all)


text:
Q: List all surveys programmatically in SharePoint 2010? I need to change some permissions for all surveys in a SharePoint 2010 site collection, how can I list them?
For example to list document libraries  I can do
            SPSite oSiteCollection = SPContext.Current.Site;
            SPWebCollection collWebsite = oSiteCollection.AllWebs;
            foreach (SPWeb web in collWebsite)
            {
        SPListCollection collList = web.Lists;

                foreach (SPList oList in collList)
        {
                if (oList is SPDocumentLibrary)
                {
                   // Do something
                }
        }
            }

Thanks in advance.

A: As your if statement use
if (oList.BaseType == SPBaseType.Survey)


text:
Q: iptables fails to load nf_conntrack_ftp I have recently had to rebuild my iptables configuration and when I run
service iptables restart

I now receive the following error line:
iptables: Loading additional modules: nf_conntrack_ftp   [FAILED]

My iptables-config file includes the following line:
IPTABLES_MODULES="nf_conntrack_ftp"

When I run modprobe nf_conntrack_ftp the response is:
FATAL: Module nf_conntrack_ftp not found.

Here's my iptables file:

Table: mangle Chain PREROUTING (policy ACCEPT) num  target     prot
opt source               destination
Chain INPUT (policy ACCEPT) num  target     prot opt source
destination 1    ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0
state NEW tcp dpt:8447 2    ACCEPT     tcp  --  0.0.0.0/0
0.0.0.0/0           state NEW tcp dpt:8443
Chain FORWARD (policy ACCEPT) num  target     prot opt source
destination
Chain OUTPUT (policy ACCEPT) num  target     prot opt source
destination
Chain POSTROUTING (policy ACCEPT) num  target     prot opt source
destination
Table: filter Chain INPUT (policy DROP) num  target     prot opt
source               destination 1    ACCEPT     all  --  0.0.0.0/0
0.0.0.0/0           state RELATED,ESTABLISHED 2    DROP       tcp  --  0.0.0.0/0            0.0.0.0/0           tcp flags:0x3F/0x00 3    DROP       tcp  --  0.0.0.0/0            0.0.0.0/0           tcp flags:!0x17/0x02
state NEW 4    DROP       tcp  --  0.0.0.0/0            0.0.0.0/0
tcp flags:0x3F/0x3F 5    ACCEPT     all  --  0.0.0.0/0
0.0.0.0/0 6    ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:80 7    ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0
tcp dpt:443 8    ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0
tcp dpt:25 9    ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0
tcp dpt:995 10   ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0
tcp dpt:143 11   ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0
tcp dpt:993 12   ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0
tcp dpt:22 13   ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0
tcp dpt:110 14   ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0
tcp dpt:465 15   ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0
tcp dpt:8181 16   ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0
tcp dpt:8443 17   ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0
Chain FORWARD (policy ACCEPT) num  target     prot opt source
destination
Chain OUTPUT (policy ACCEPT) num  target     prot opt source
destination

It seems nf_conntrack_ftp isn't loading -- how do I load this?

A: Try issuing the following:

modprobe ip_conntrack & modprobe ip_conntrack_ftp

Then substitute nf_conntrack_ftp with ip_conntrack_ftp in your iptables configuration.


text:
Q: ¿Se puede mostrar un resultado generado en PHP en un HTML? Estoy haciendo un programa que hace varios cálculos y al final genera el resultado en un $resultado, los datos se ingresan desde el HTML en <form method="POST" action="archivo.php" >
Por ejemplo en el <form>, el usuario ingresa:
Valor 1 + Valor 2
Se envían a archivo.php por medio de un Botón para sumarse y el resultado sale en $resultado
Y lo que quiero es que en la pagina en HTML (aunque se tenga que recargar la pagina) muestre Algo como:
"Tu valor es igual a 5"
Donde 5 es lo que quedo en $resultado.
Lo que quería saber es si se puede y de ser así como mostrar el resultado en el HTML o si es mas conveniente hacerlo todo en un PHP.

A: archivo.html:
<form method="post" action="archivo.php">
    <input name="valor1">
    <input name="valor2">
</form>

archivo.php:
Si solo quieres imprimirle:
<?php
    $valor1 = filter_input(INPUT_POST, 'valor1');
    $valor2 = filter_input(INPUT_POST, 'valor2');
    $resultado = $valor1 + $valor2;
    echo "Tu valor es igual a $resultado";

Si quieres replicar el formulario inicial, para hacer un nuevo calculo quizás:
<?php
    $valor1 = filter_input(INPUT_POST, 'valor1');
    $valor2 = filter_input(INPUT_POST, 'valor2');
    $resultado = $valor1 + $valor2;
?>

<form method="post" action="archivo.php">
    <input name="<?php echo $valor1 ?>">
    <input name="<?php echo $valor2 ?>">
    <?php echo "Tu valor es igual a $resultado"; ?>
</form>

Recuerda que puedes mezclar código PHP en contenido HTML, como lo expresa  php.net:

las páginas de PHP contienen HTML con código incrustado que hace "algo"

Te dejo el enlace para que leas el contenido completo: http://php.net/manual/es/intro-whatis.php

A: Si se puede lo que comentas lo que tienes que hacer es que tu archivo en lugar de guardarlo como .hmtl lo guardes como .php.
Luego en archivo.php poner algo como lo que sigue:
<?php
    $valor1 = $_POST["valor1"];
    $valor2 = $_POST["valor2"];
    $resultado = $valor1 + $valor2;
?>

El resultado es <?php echo $resultado ?>.


text:
Q: How to mute/unmute default sound output What's the generic way to mute/unmute my system's default sound output?
$ amixer set Master mute
amixer: Unable to find simple control 'Master',0

$ amixer scontrols
Simple mixer control 'IEC958',0
Simple mixer control 'IEC958',1
Simple mixer control 'IEC958',2
Simple mixer control 'IEC958',3
Simple mixer control 'IEC958',4
Simple mixer control 'IEC958',5

I know the sound control had been moving away from amixer to Pulseaudio, however, I'm still able to use the ALSA "Master" control in my Debian 10, but not my Ubuntu 21.10, see above.
There is pactl set-sink-mute 0 1 from https://superuser.com/questions/805525/, but I tried it but that doesn't work for my Ubuntu 21.10 above.
All in all, I just need a generic way to mute/unmute my system's default sound output that is good across all my machines and all my Linuxes, just like the ALSA "Master" control.

A: I've been using this command for ages now:
pactl set-sink-mute @DEFAULT_SINK@ toggle

This mutes/unmutes depending on the current state.

Also to increase volume: pactl set-sink-volume @DEFAULT_SINK@ +3%
or decrease volume: pactl set-sink-volume @DEFAULT_SINK@ -3%

A: to mute:
pactl set-sink-mute `pactl get-default-sink` 1

to unmute :
pactl set-sink-mute `pactl get-default-sink` 0

A: With the toggle option, it mutes everything.  However, toggle Master does not unmute everything.
So, if we toggle Master, and always unmute the sub-channels, then Master will toggle, and the (sub-) channels will always unmute.
So I made a 3 line script ::
will@will:~$ cat toggle
amixer -c 1 set Master toggle
amixer -c 1 set Headphone unmute
amixer -c 1 set Speaker unmute

Then bind the script to the key ... because I'm to lazy to press the Fn - mute / vol+ / vol- combination for my keyboard.


text:
Q: Check if two strings are permutations in C Im actually trying to make some program who can check if two strings are permutation from each other. I explain :
If I consider :
Eagle

and
Hdjoh

(I used these two examples in a previous question).
I get a permutation, and the permutation parameter is 3. Why ? Because in the alphabet : E + 3 = H, a + 3  = d etc..
I used unsigned char because if I get a z in one of my strings, I want that (for example) z + 3 = c.

What I started to do :
#include <stdio.h>
#define N 20

int my_strlen(unsigned char *string){
    int length;
    for (length = 0; *string != '\0'; string++){
        length++;
    }
    return(length);
}

int main()
{
    unsigned char string1[N], string2[N];
    int test=0, i=0, length1, length2;
    scanf("%s", string1);
    scanf("%s", string2);

    length1=my_strlen(string1);
    length2=my_strlen(string2);

    if(length1==length2){
        for(i=0; i<length1; i++){
            if(string1[i]==string2[i]){
                test=1;
                }
                else{
                    test=0;
                }
        }
        printf("Test = %d", test);
    }
    else{
        printf("Error");
    }

    return 0;
}

I just started to think about it.. So for the moment I just try to compare the two strings letter by letter.
The problem here : If i try to compare Hello and hello, or Hello and Helqo I get Test = 1.
So someone can tell me whats wrong here ?
Thanks a lot.

EDIT 1 :
#include <stdio.h>
#define N 20

int my_strlen(unsigned char *string){
    int length;
    for (length = 0; *string != '\0'; string++){
        length++;
    }
    return(length);
}

int main()
{
    unsigned char string1[N], string2[N];
    int test=0, i=0, length1, length2;
    scanf("%s", string1);
    scanf("%s", string2);

    length1=my_strlen(string1);
    length2=my_strlen(string2);

    if(length1==length2){
        for(i=0; i<length1; i++){
            if(string1[i]==string2[i]){
                test=1;
                }
                else{
                    test=0;
                    break;
                }
        }
        printf("Test = %d", test);
    }
    else{
        printf("Error");
    }

    return 0;
}

Now it's correct. I will continue.

EDIT 2 - 6.7.14 :
I am actually working and the "second part" of the program. I am looking for the d and I verify if its a permutation or not. No so easy so I need some advices, do I have to write an other function to do this ? Or just working on this part of my code :
if(length1==length2){
            for(i=0; i<length1; i++){
                if(string1[i]==string2[i]){
                    test=1;
                    }
                    else{
                        test=0;
                        break;
                    }
            }
            printf("Test = %d", test);
        }
        else{
            printf("Error");
        }

        return 0;
    }

I wrote it like this for the moment :
if(length1==length2){
        for(i=0; i<length1; i++){
                for(d=0; d<255; d++){
                    if(string1[i]==string2[i] + d){
                        permutation=1;
                }
                else{
                    permutation=0;
                    break;
                }
                }
        }
        printf("\nPermutation = %d \nd = %d", permutation, d);
    }
    else{
        printf("Not a permutation");
    }

    return 0;
}

(I know that it doesn't  work but I just tried..).
Thanks by advance for the help.

A: You are only printing out the results of the last character comparison.
for(i=0; i<length1; i++){
            if(string1[i]==string2[i]){
                test=1;
                }
                else{
                    test=0;
                }
}

This goes through and compares each character and changes test each time. At the end of the loop, only the last character comparison is output.

A: This is because your test variable gets updated for each character in the string.
For the strings Hello and hello, or Hello and Helqo, last character is same ('o'), hence at the end of loop, test is updated to 1.
Try with Hello and Hellm, you will get test = 0.

A: You can think about the problem like this. For two strings to be a valid permutation, the
character distances have to be equal for each character in the strings.
So you can check the first character distance and then loop over the other characters
and verify that the distance is the same. As soon as it is not equal to first character distance, you can safely conclude that it is not a permutation.
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int i;
    unsigned char string1[] = "test";
    unsigned char string2[] = "vguv";

    int slength1 = 4;
    int slength2 = 4;

    int distance;
    int is_permutation = 1;

    if (slength1 != slength2) {
        is_permutation = 0;
    }

    distance = (int)string2[0] - (int)string1[0];

    for (i=1; i<slength1; ++i) {
        if ( ((int)string2[i] - (int)string1[i]) != distance ) {
            is_permutation = 0;
            break;
        }
    }

    if (is_permutation) {
        printf("%s is a permutation of %s with distance %d\n", string1, string2, distance);
    } else {
        printf("%s is not a permutation of %s\n", string1, string2);
    }

    return EXIT_SUCCESS;
}

Please note that I have used statically defined strings and stringlengths. Your original way of reading in user input is prone to undefined behaviour. You declare a string of fixed length (20 in the OP) so if a user enters a string longer than 19 the scanf will run out of bounds and invoke undefined behaviour. This is very bad and you should read up on it.

A: #include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
    char a[100], b[100];
    int size_a, size_b, i, j, flag;
    scanf("%s", &a);
    scanf("%s", &b);
    size_a = strlen(a);
    size_b = strlen(b);
    if(size_a!=size_b)                   //if size of both strings are      unequal then print and exit
    {
        printf("no");
        exit(0);
    }
    for(i=0;i<size_a;i++)               //compare every element of a with every element of b
    {
        for(j=0; j<size_b;j++)
    {
        if(a[i]==b[j])
        {
            b[j]=32;                //when elements matches add character 'space' there, of ASCII value 32
            flag++;                 //flag guards of every successful match
        }
    }
}
if(flag==size_a&&flag==size_b)
    printf("yes");
else
    printf("no");
return 0;

}
i wrote this code and works fine for me

A: bool IsPremutation(char* s1, char* s2, int sl1, int sl2)

{
if (sl1 != sl2)
{
    return false;
}

std::set<char> charset;

for (int index = 0;  index < (sl1 + sl2); index++)
{
    int source = (index) / sl1;

    if (source == 0)
{
    charset.insert(s1[index]);
    }
    else
    {
    charset.insert(s2[source - 1]);
    }
}

return charset.size() == sl2;

}

A: I know this is old, but the quality of answers is disturbing. First, you aren't really looking for a permutation; you are checking to see if two strings are different by a shift cipher.
A cleaner version of the accepted answer that handles case conversions like you mentioned:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <ctype.h>

int shifted(const char* a, const char* b, int* amount) {
    size_t len_a = strlen(a);
    size_t len_b = strlen(b);
    if (len_a != len_b) return 0;

    int shift_amount = *b - *a;
    for (; *a; a++, b++)
        if (tolower(*b) - tolower(*a) != shift_amount) return 0;

    *amount = shift_amount;
    return 1;
}

int main(void) {
    const char *a = "shift";
    const char *b = "tigU";

    int shift_amount = 0;
    if (shifted(a, b, &shift_amount))
        printf("Shifted by amount: %d\n", shift_amount);
    else
        printf("Not shifted\n");

    a = "shift";
    b = "shifT";
    if (shifted(a, b, &shift_amount))
        printf("Shifted by amount: %d\n", shift_amount);
    else
        printf("Not shifted\n");

    a = "shift";
    b = "shifv";
    if (shifted(a, b, &shift_amount))
        printf("Shifted by amount: %d\n", shift_amount);
    else
        printf("Not shifted\n");

    return EXIT_SUCCESS;
}

Output:
Shifted by amount: 1
Shifted by amount: 0
Not shifted

A: #include <stdio.h>
#define possiblechars 256

int is_permutation(char *str1, char *str2)
{
    int count1[possiblechars] = {0};
    int count2[possiblechars] = {0};
    int i;

    //sets count arrays '0' for 256 times
    for (i = 0; str1[i] && str2[i]; i++)
    {
        count1[str1[i]]++;
        count2[str2[i]]++;
    }

    //interates until either string 1 or 2 hits null
    //increments individual indexes of the count arrays
    if (str1[i] || str2[i]){
        return 0;
    }

    //if different lengths, then return false
    for (i = 0; i < possiblechars; i++){
        if (count1[i] != count2[i]){
            return 0;
        }
    }
    return 1;
}

int main(int argc, char *argv[])
{
    char str1[] = "Eagle";
    char str2[] = "Hdjoh";
    if (is_permutation(str1, str2)){
      printf("Permutation\n");
    }
    else {
      printf("Not a permutation\n");
    }
    return 0;
}

A: #include <stdio.h>
#include <conio.h>
#include <string.h>
#define N 20

int my_strlen(unsigned char *string)
{
    int length;

    for (length = 0; *string != '\0'; string++)
    {
        length++;
    }
    return (length);
}

int main()
{
    unsigned char string1[N], string2[N];
    int permutations = 0, i = 0, d = 0, length1, length2;
    scanf("%s", string1);
    scanf("%s", string2);
    length1 = my_strlen(string1);
    length2 = my_strlen(string2);
    d = string1[0] - string2[0];   //finding out the distance
    if (length1 == length2)
    {
        for (i = 0; i < length1; i++)
        {
            if (d < 0)           //if less then 0 then String2 >String1
            {
                if (string2[i] == string1[i] + d * (-1)) //when d enters here d will be always negative
                {
                    permutations=1;
                }
                else
                {
                    permutations = 0;
                    break;
                }
            }
            else           //else String1 >String2
            {
                if (string1[i] == string2[i] + d)
                {
                    permutations = 1;
                }
                else
                {
                    permutations = 0;
                    break;
                }
            }
        }
        printf("Permutations=%d\n and distamce=%d", permutations, d);
    }
    else
    {
        printf("Error");
    }
    return 0;
}


text:
Q: Uploading file(s) to webserver in silverlight (C#) Alright, so i have a silverlight application,
it opens a filedialog, gets the selected file, transfers it to asp.net which saves it to the server, but i want to know how to implement a progress bar for it. for big files, and multiple file uploads, i will need to know the progress of the file upload to the server, is this possible?

A: You will probably save yourself a lot of time and heartache by just integrating this Silverlight File Upload codeplex project into your app.
You can't actual get good progress information from the standard WebRequest or WebClient components.  Not only do they not send any of the Request stream until your code has finished writing to it (a decision I can't begin to understand), it doesn't provide any progress events once it starts sending it.  For reasons I can't begin to fathom you can get progress events when sending a string, go figure.
I can only guess that these limitations arise from Silverlight needing to operate in multiple browsers and therefore the interface to the Browser HTTP transport is kept as basic as possible.


text:
Q: Haskell function returns prefix I am trying to create a function in haskell that takes a predicate and a list as arguments and returns the prefix of the list satisfying the predicate.
the test being:
p1tests = [myTakeWhile (/= ' ') "This is practice." == "This"]

I have this so far..
myTakeWhile :: (a-> Bool ) -> [a] -> [a]
myTakeWhile []    =[]
myTakeWhile (x:xs)=[] : map (x:) (myTakeWhile xs)

I receive errors saying except type

A: You need to work with both the predicate and the elements in the list. The function thus should look like:
myTakeWhile :: (a -> Bool) -> [a] -> [a]
myTakeWhile _ [] = []
myTakeWhile p (x:xs)
    | p x = …
    | otherwise = …
where the p x guard thus covers the case where the predicate is satisfied for the first item of the list, and the otherwise is not.
In case the predicate is satisfied, we have to yield x and recurse on the tail of the list. I keep filling in … as an exercise.


text:
Q: how to get values in an array in jQuery I'm having a following set of html codes:

'Himu' Onepage HTML Template

Fully Professional one page template

                    Get Started

Get All in Onepage

Everything is outstanding
 Get Started

Fully Responsive Template

100% Responsive HTML template

                    Get Started

I want the text values of h2 tags, p tags and a tag into an array, like I've the background image illustrated below:
$('#nitsslider > .item').each(function (i) {
    var sliderimage = [];
    var sliderheading = [];
    var sliderpara = [];
    var sliderbutton = [];
    sliderimage[i] = $(this).css('background-image').replace(/^url\(['"](.+)['"]\)/, '$1');
    sliderheading[i] = $('.item > h2').text();
    console.log(sliderimage[i]);
    console.log(sliderheading[i]);
});

I want to use these values to appending into the code.
Please help me out guys. Thanks

A: Use iteration context this along with find selector to find child element in it:
sliderheading[i] = $(this).find('h2').text();

A: var p=[],h2=[],a=[];
$('p').each(function(){
p.push($(this).text());
});

$('h2').each(function(){
h2.push($(this).text());
});

$('a').each(function(){
a.push($(this).text());
});

//Merge all 3 of them if you want it in single array


text:
Q: Почему SUM не суммирует значения? Здравствуйте.
Почему SUM не суммирует результат UNION?:
Мой запрос выдает:
При том, что SUM(count) запроса UNION без группировки выдает правильное кол-во:
Сам SQL-запрос:
SELECT
    a.code_spec_product,
    a.code_spec_detail,
    a.id_subdivision,
    SUM(
        CAST('SUM(count)' AS SIGNED)
    )
FROM
    (
        SELECT
            code_spec_product,
            acc.id_subdivision,
            code_spec_detail,
            SUM(count)
        FROM
            conn_accep_detail
            INNER JOIN acceptance acc ON acc.number = num_acc
        WHERE
            acc.id_subdivision != 9
        GROUP BY
            code_spec_product,
            code_spec_detail,
            acc.id_subdivision
        UNION ALL
        SELECT
            code_spec_product,
            acc.id_subdivision,
            code_spec_detail,
            SUM(count)
        FROM
            connacc_detail
            INNER JOIN acceptance acc ON acc.number = num_acc
        WHERE
            acc.id_subdivision != 9
        GROUP BY
            code_spec_product,
            code_spec_detail,
            acc.id_subdivision
    ) a
GROUP BY
    a.code_spec_product,
    a.id_subdivision,
    a.code_spec_detail

UPDATE
Запрос для нужного мне результата:

SELECT
    a.code_spec_product,
    a.code_spec_detail,
    a.id_subdivision,
    SUM(total)
FROM
    (
        SELECT
            code_spec_product,
            acc.id_subdivision,
            code_spec_detail,
            SUM(count) AS total
        FROM
            conn_accep_detail
            INNER JOIN acceptance acc ON acc.number = num_acc
        WHERE
            acc.id_subdivision != 9
        GROUP BY
            code_spec_product,
            code_spec_detail,
            acc.id_subdivision
        UNION ALL
        SELECT
            code_spec_product,
            acc.id_subdivision,
            code_spec_detail,
            SUM(count) AS total
        FROM
            connacc_detail
            INNER JOIN acceptance acc ON acc.number = num_acc
        WHERE
            acc.id_subdivision != 9
        GROUP BY
            code_spec_product,
            code_spec_detail,
            acc.id_subdivision
    ) a
GROUP BY
    a.code_spec_product,
    a.id_subdivision,
    a.code_spec_detail

A: Все верно, это из-за того, что вы используете конструкцию
GROUP BY
    a.code_spec_product,
    a.id_subdivision,
    a.code_spec_detail

Так как у вас сумма одинаковая, у вас две из трех записей получаются одинаковые и они группируются. Из трех записей получается 2. Уберете GROUP BY получите одну запись.
Назначьте конструкции SUM(count) псевдоним при помощи AS, например,
SUM(count) AS total

и добавьте группировку этот столбец
GROUP BY
    a.code_spec_product,
    a.id_subdivision,
    a.code_spec_detail
    total

Если же вам нужна сумма всех столбцов, убирайте группировку вообще.


text:
Q: WPF DropShadowEffect appears on preview but not at runtime So I implemented the following code within my grid:
        <Grid.Effect>
        <DropShadowEffect ShadowDepth="0"
                      Color="Black"
                      Opacity="1"
                      BlurRadius="30" RenderingBias="Quality"/>
       </Grid.Effect>

I can see the shadow appear in the preview; however, when I run it, there is no shadow. So I was wondering if I missed something.
xaml:
<Window x:Class="test.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525" Background="Transparent" WindowStyle="None" AllowsTransparency="True">
<Grid>
    <Grid.Effect>
        <DropShadowEffect ShadowDepth="0"
                  Color="Black"
                  Opacity="1"
                  BlurRadius="30" RenderingBias="Quality"/>
    </Grid.Effect>

    <Rectangle Height="350" Width="525" Fill="White" Grid.ColumnSpan="2">
    </Rectangle>
</Grid>

You should see a window with a shadow around the border. Then run it and its gone.
EDIT: So all I did was add a margin to the rectangle and the drop shadow appears. I'm assuming the window blocks the drop shadow.

A: Add a margin to your rectangle like this
<Rectangle Margin="10"  Height="350" Width="525" Fill="White" Grid.ColumnSpan="2">

The reason it needs the margin is because the drop shadow effect draws a larger outline than what is in the bounds of the rectangle. If you don't want to use the rectangle and just apply to it your grid then add the margin to your grid instead. Hope this helps.


text:
Q: How to update block in magento using ajax i want to update sidebar block in magento 1.9 when add to cart action fire
my controller is
public function sidebarAction()
{
    $this->getLayout()->createBlock('checkout/cart_sidebar')->setTemplate('checkout/cart/sidebar.phtml')->toHtml();
}

But this code cant update block

A: your ajax action tag in config.xml should content like below
 <block type="checkout/cart_sidebar" name="cart_sidebar_ajax" as="cart_sidebar_ajax" template="checkout/cart/ajaxsidebar.phtml">
                    <action method="addItemRender">
                        <type>simple</type>
                        <block>checkout/cart_item_renderer</block>
                        <template>checkout/cart/sidebar/default.phtml</template>
                    </action>
                    <action method="addItemRender">
                        <type>grouped</type>
                        <block>checkout/cart_item_renderer_grouped</block>
                        <template>checkout/cart/sidebar/default.phtml</template>
                    </action>
                    <action method="addItemRender">
                        <type>configurable</type>
                        <block>checkout/cart_item_renderer_configurable</block>
                        <template>checkout/cart/sidebar/default.phtml</template>
                    </action>
                </block>

hope this will work for you.

A: Step1:Create new event handler for this action
so, create local.xml in (app/design/frontend/yourpackage/yourtemplate/layout) and put this code:
<?xml version="1.0"?>
<layout version="0.1.0">
    <yourRouter_controller_sidebar>
    </yourRouter_controller_sidebar>
</layout>

and in sidebarAction add below code:
 $layout = Mage::getSingleton('core/layout');
$layout->removeOutputBlock('root');
Mage::app()->getFrontController()->getResponse()->setHeader('content-type', 'application/json');
$page = $layout->getBlock('cart_sidebar');
$container = $layout->createBlock('core/template', 'amit');
$container->setData('page',$page->toHtml());
$layout->addOutputBlock('amit_json', 'toJson');

Note:  cart_sidebar is your cart siderbar block name which is defined at checkout.xml in default theme.
For Rwd theme call cart sidebar from head using below code
<block type="checkout/cart_minicart" name="minicart_head" template="checkout/cart/minicart.phtml" before="-">.....

and here block name is minicart_head. So you should make required change.
$layout->getBlock('cart_sidebar');

to
$layout->getBlock('minicart_head');


text:
Q: Find a Taylor polynomial approximation of Find a Taylor polynomial approximation of
$ \ f(x)=\large \frac{1}{x} \int_0^x \frac{dt}{1+t^3} \ $ of degree $ \ 3 \ $ or larger , centered at $ \ a=0 \ $
Estimate $ \ f(0.1) \ $ and find the upper bound of error.
Answer:
$ \ f(x)=\large \frac{1}{x} \int_0^x \frac{dt}{1+t^3}  $
The anti-derivative of $ \ f(x) \ $ is involving again an integral sign as follows
$ \frac{d}{dx} f(x)=-\frac{1}{x^2}\int_{0}^{x} \frac{dt}{1+t^3} +\frac{1}{x(1+x^3)}-\frac{1}{x} $
This becomes critical to expand as series.
I need help doing this.

A: First multiply $x$ on both sides.
$x$ $f(x)=\int_{0}^{x}\frac{dt}{1+t^3}$
$f(x)+x$ $f'(x)=\frac{1}{1+x^3}$ $ $ $ $ $f(0)= 1$
$2f'(x)+xf''(x)=-3x^2(1+x^3)^{-2}$ $ $ $f'(0)=0$
$f''(0)=0$
$f'''(0)=-\frac{3}{2}$
$f(x)=1-\frac{1}{4}x^3$
$f(0.1)=0.99975$


text:
Q: Paste text stored on Clipboard to a variable using pbpaste I have some text stored on my clipboard. I want to store this text onto a shell script "variable".
So something like:
ls -altr > pbcopy
tmp="something"
pbpaste > $tmp    # this doesn't get the ls command output :(
echo $tmp         # should not print something

A: This works for me...
#!/bin/bash

ls -altr | pbcopy
tmp=`pbpaste`
echo $tmp

You needed a pipe rather than redirect on the pbcopy line and you can use = to assign tmp to the result of pbpaste - remembering the backticks around pbpaste, of course, otherwise it will just echo the word "pbpaste"!

A: Try
ls | pbcopy
tmp=$(pbpaste)

And don't forget to remove the files called pbcopy and something you created with your first and second line.


text:
Q: Does C# code contained in Javascript still need to be compiled? We have a web application built with C# and ASP.NET.  I have to reference a few .NET session variables in my JavaScript code, so I use the following line to do so:
var layoutID = '<%=Server.UrlEncode(string.Format("{0}", Session["layout_id"]))%>';

This works just fine.  The web application is built and published to our web server.  If I want to make a change, a .NET change would require me to compile the changes and publish it to the web server again.  If it's a JavaScript change, I can simply edit the js in the .ASPX page and the fix is immediately picked up...no compiling needed.
My question - what if I make a change to this inline C# code contained in JavaScript?  Say, for example, I meant to access Session["layoutid"] without the underscore.  Could I just edit the .ASPX page on the web server, or will this require compiling just as if it were in a .CS file?  I'm guessing since it's C#, I will still need to compile for the change to be picked up.  And yes I could just try it and see for myself, but I was hoping someone could give a little insight into what goes on behind the scenes with this inline c# code.  And while we're on the topic, is the technique I'm using to access .NET sessions variables in JavaScript the most efficient way to do it?
Bonus question - what is this technique called?  I tried searching for an answer but I wasn't sure what to search for other than "in-line c# code JavaScript".
Thanks!

A: No, changes to ASPX/CSHTML files don't require re-compilation.
Note: whether it is good idea to jump on production server and change random code bypassing source control/testing is question to discuss and answer by your team.


text:
Q: Extracting extra parameters from HTTP request Let's say I send to a Node Server a request to get a JS file:
<script src="/blabla.js" id="545234677">

and on my Node side:
app.get('/blabla.js', function(req, res, next) {
console.log(req.params.id); //undefined
res.setHeader('content-type', 'text/javascript');
res.render('blabla'); //default

});

and finally I have this template file blabla.ejs:
var id = <%= id %>

Now, I am trying to get that id para but it's showing undefined. I am using Express and EJS, and once I get that ID I want to manipulate an EJS file and send back a JS file which adapts itself according to the ID my node app received.
Thank you.

A: The way to do this would probably be like this - In your HTML you would request the JS file like so:
<script src="/blabla.js?id=545234677">

And then for express you would do the following:
app.get('/blabla.js', function(req, res, next) {
  console.log(req.query.id);
  res.setHeader('content-type', 'text/javascript');
  // Pass id into the renderer
  res.render('blabla', {id: req.query.id}); //default
});

Although rendering is normally used to render HTML. There is probably a better way to do what you want in a more elegant way.
Note: req.params would work, but would make the url look like /blabla.js/545234677. See the documentation on req.params.

A: How about changing your script to
<script src="[filename][id].js"></script>

EG:<script src="blabla123.js"></script>
then you can do something using regular expressions like
app.get(/^\/([a-zA-z]*)([0-9]*).js/,function(req,res,next){
  var fileName = req.params['0'],
      id = req.params['1'];
  console.log(fileName);
  console.log(id);
  // Now since you have both fileName and id as you required, you can
  // use it to dynamically serve the content
  // if(file=='' && id==''){//logic}
  // If you want static file Name, modify the regular expression accordingly
})

Just modify the regular expression in above example as per your need and its done. Currently the above regex matches for any of
/.js
/[numeric].js
/[alphabet].js
/[alphabet][numerals].js

I hope this helps.


text:
Q: What is the use of the Rofe-Beketov formula? Let $y_1(x)$ be an elementary solution of the Sturm-Liouville equation,
$$ \frac{d}{dx}\left( p(x)\frac{dy}{dx} \right) + q(x)y = 0 $$
It is well known that a second linearly independent solution may be computed from the reduction of order formula, provided that $y_1(x)$ is nonvanishing.  I came upon a formula attributed to Fedor Rofe-Beketov which relaxes this constraint and claims to give a second linearly independent solution without any requirements as to the oscillation of $y_1(x)$:
$$ y_2(x) = y_1(x)\int \frac{(p(t)^{-1} - q(t))[(y_1(t)^2 - (p(t)y_1(t)')^2]}{[y_1(t)^2 + (p(t)y_1(t)')^2]^2} dt - \frac{p(x)y_1(x)}{y_1(x)^2 + (p(x)y_1(x)')^2} $$
which can be established by a somewhat lengthy but relatively straightforward computation.  But in every example I can think of where a second solution must be determined when only one is known, it can be obtained by the ordinary reduction of order formula.  For other problems, any algorithmic solution procedure should automatically gives both fundamental solutions and so neither formula is necessary.  Perhaps this merely signifies a lack of imagination on my part, but are there any examples of applications of the Rofe-Beketov formula actually being required to complete the solution of an ODE?

A: The formula has the advantage over d'Alembert's more well-known formula that it gives an expression for the second solution that is unencumbered with the problems d'Alembert's formula has at zeros of the first solution. In my paper "Critical Coupling Constants and Eigenvalue Asymptotics of Perturbed Periodic Sturm-Liouville Operators", Commun. Math. Phys. 211 (2000) 465-485, Rofe-Beketov's formula is used in a situation where the first solution has infinitely many zeros, and then motivates a transformation that leads to the desired result; d'Alembert's formula will not get you anywhere in this problem. This paper also provides a reference to Rofe-Beketov's paper (who only considers the case p = 1).
K. M. Schmidt


text:
Q: What is a good way to handle command read from user and server's response in a remote command-line interpreter? I'm implementing a client side software that lets user input commands, sends them to a server, the server interprets them and sends the result to the client. Here's where I'm stuck, I have a while loop that gets responses from server until the connection ends.
try(Socket socket = new Socket(hostname, port);
    PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))){

    System.out.println("Connected to " + hostname + ":" + port + " !");

    Scanner scanner = new Scanner(System.in);
    String command = scanner.nextLine();
    String fromServer = null;
    int status;
    HashMap<String, String> response;
    long start = 0;

    System.out.println("C:" + command);

    if (command.toLowerCase().equals("exit")) return;

    out.println(command);

    if (command.toLowerCase().equals("shutdown")) return;

    out.println();

    while ((fromServer = in.readLine()) != null) {

        // Here's my problem
        response = parseResponse(fromServer);

        if (response.containsKey("response")) response.put("response", response.get("response").replaceAll("\\\\n", "\n"));

        try {

            status = Integer.parseInt(response.get("status"));

        } catch (NumberFormatException e){

            status = Status.RESPONSE_CORRUPTED;

        }

        System.out.println("S:" + status + (response.get("response") != null ? "\n" + response.get("response") : ""));
        command = scanner.nextLine();
        System.out.println("C:" + command);
        out.println(command);

    }

} catch (IOException e){

    System.out.println("Server isn't connected, try again later.");

}

The real problem is that I need to put
if (command.toLowerCase().equals("exit")) return;

out.println(command);

if (command.toLowerCase().equals("shutdown")) return;

out.println();

before the while, so there's three out.println() in the code while one would be more "logic" and I need to put
if (command.toLowerCase().startsWith("shutdown") && fromServer.equalsIgnoreCase("0") || status == Status.RESPONSE_CORRUPTED) break;

in that while so the client stops directly when the command shutdown is sent (to shutdown the server) to prevent the user from entering another command.
I'm searching for a more efficient way to manage commands and to add a ping command (but I need to add an if before the one to shutdown), maybe using more OOP but I don't see how to do it.

A: I think you should give a try to Spring Shell first before attempting to make your own from scratch. It is quite modular and you can create the backend handlers that send the commands to the remote server.

A: Use an infinite loop and break it based on the user input or on the server response
Here is an example which does not send the exit/shutdown commands to the server, but rather they only stop the client. If you need to send all the commands to the server and stop only based on the server response then just delete the if statement from the while loop
    Scanner scanner = new Scanner(System.in);
    String command = null;
    while (true) {

        command = scanner.nextLine();

        if (command.toLowerCase().equals("exit") || command.toLowerCase().equals("shutdown")) {
            break;
        }

        out.print(command);
        out.flush();

        String response = in.readLine();

        // do something with the response (ex. stop the client by calling break or just print the response

    }


text:
Q: mark a slave permanently offline in jenkins using an API I am looking for a way to mark a slave permanently offline in jenkins through an API and i got this
http://[jenkins_url]:8080/computer/[slave_name]/doDisconnect?offlineMessage=bye

But the slave connects again when the next time a job runs on this.
Is there a way to permanently disconnect a slave so that it does not connect automatically again unless started manually?
Thanks in advance.

A: That seems similar to JENKINS issue 13140

To prevent reconnect after manual disconnect, don't configure Jenkins to Keep this slave online as much as possible.

Try also the Jenkins plugin "jenkins-keep-slave-disconnected-plugin".
Changing my slaves to "take this slave on-line when in demand and off-line when idle", and as suggested set
in demand delay = 0
idle delay = 1000000

That does not prevents that, when a slave is required by a job, the slave process is started.


text:
Q: "something which" or "something that" According to Korean English grammar books, nouns that ends with "thing", such as something, anything, generally take "that" as a relative pronoun.
But does that mean that "something which" is not preferred? If so, are there any rules?

It is not just the newness of contemporary literature that makes it different, but also the context in which it is written and received, something which gives it a very interesting edge over the literature of the past. (excerpt)

In the sentence, "something which" is used because "which" can be used as non-restrictive, but "that" cannot be used so?

A: It is traditionally accepted to use that for a restrictive clause and which for a non-restrictive clause.

In modern English usage, "that" always introduces a restrictive clause
  (due to which it is almost never set off by commas).

*

*The box that lies on the table is empty. (correct)

In British English, it is absolutely fine to use "which" in
  restrictive as well as non-restrictive clauses.

*

*The box which lies on the table is empty. (correct in British English)
This sentence above is usually perceived as incorrect in formal American English.
Extra information:

There are several issues with this rule. First of all, it is a
  prescriptive rule, and most Americans don't strictly follow it in
  speech (many being unaware of its existence altogether). Secondly,
  when "which" is combined with a preposition, noun, or a pronoun, it
  cannot be replaced by "that", even when it introduces a restrictive
  clause (this is considered to be an exception to the rule), as in:

*

*The principle in which he believes has been proved wrong. (correct)

*The principle in that he believes has been proved wrong. (incorrect)

A: "which" refers to the state of being (e.g. characteristics, specifications) of an indicated noun, almost as if one would afterwards want to add some comments (e.g. adjectives) to the noun for a broader view or perspective.
If this is not the intention and the context needs no further explanation, then the use of "that" is common rule.
Remark: when a preposition needs to be used to refer to the noun, always combine with "which".


text:
Q: applicationWillEnterForeground gets found nil for textLabel I'm trying to change text on label when app will enter foreground but I always get
fatal error: unexpectedly found nil while unwrapping an Optional value
ViewController.swift

  @IBOutlet var textLabel: UILabel!

    func showLabel() {
        textLabel.text = "Welcome back"
    }

and
AppDelegate.swift

func applicationWillEnterForeground(application: UIApplication) {
       ViewController().showLabel()
    }

Any Idea how to fix it?

A: thanks for answers! I managed it with
NSNotificationCenter.defaultCenter().addObserver(self, selector: "showLabel", name: UIApplicationDidBecomeActiveNotification, object: nil)

in viewDidLoad
and then in AppDelegate
func showLabel() {}

based on :
Nil when unwrapping an Optional Value in didBecomeActive()

A: As I explained in a previous post, you should initialize your label in the viewDidLoad function of your view controller.
In fact, at the time you are in applicationWillEnterForeground, your view controller has not been yet initialized, so the label textLabel is null (nil) and you are trying to access a property of a null object (reason of your error).
ViewController.swift:
@IBOutlet var textLabel: UILabel!

func viewDidLoad() {
    textLabel.text = "Welcome back"
}

A: The issue is, you are creating a new instance of your ViewController and trying to set the data to it.
Instead of that use the existing one ( You created on didFinishLaunchingWithOptions: )


text:
Q: Search for specific directory names within subdirectories and copy files (Windows batch) need some help with this one
I have a directory that contains subdirectories from various applications so let's say directory is c:\home and each application has a subdirectory called the application name so we will have
    c:\home\app1
    c:\home\app2

etc.
These applications write large log files and they then get recreated every hour but into a different directory, called according t date and time like dd/mm/yyyy/hr and this is created within the actual subdirectory and a log file with the exact same name will be within each directory for each app. so we will end up with this
    c:\home\app1\1015201410\app1.log
    c:\home\app1\1015201411\app1.log
    c:\home\app1\1015201412\app1.log
    c:\home\app2\1015201410\app2.log
    c:\home\app2\1015201411\app2.log
    c:\home\app2\1015201412\app2.log

I want to list through the directories every hour and collect the latest log from each application, in other words in this instance I want to collect the following 2 only as they are the latest (end time 12 shows it is the 12th hour)
    c:\home\app1\1015201412\app1.log
    c:\home\app4\1015201412\app2.log

Now getting the file one by one is easy enough but the script is going to become too long and needs to be edited on a regular base to allow for new applications added to the directories.
I am able to do the copying, formatting the time/date section etc. I just need to find a way to search through the home directories for all subdirectories containing the latest timedate and then copy a file from it elsewhere.
So I tried this. Note timedateformat has been predefined:
    for /D %%d in (c:\home\*\%timedateformat%\*) do (
    for %%f in (%%d\.log) do (
    xcopy %%f C:\destination\
    )
    )

but this obviously does not like the * part and therefore I will get no result.
Please if anyone is able to assist, I would greatly appreciate.

A: for /d %%F in ("c:\home\*") do xcopy "%%F\%timedateformat%\*.log" "c:\destination\"