text:
Q: Finishing Activity from another activity Say I have 3 activities A, B and C. A leads to B which leads to C. I would like to be able to move back and forth between A and B but I want to finish both A and B once C gets started. I understand how to close B when starting C via the intent but how do I also close A when C gets started?

A: Use this flag when you are opening the C acitivity.
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

This will clear all the activities on top of C.

A: Since A is your root (starting) activity, consider using A as a dispatcher. When you want to launch C and finish all other activities before (under) it, do this:
// Launch ActivityA (our dispatcher)
Intent intent = new Intent(this, ActivityA.class);
// Setting CLEAR_TOP ensures that all other activities on top of ActivityA will be finished
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add an extra telling ActivityA that it should launch ActivityC
intent.putExtra("startActivityC", true);
startActivity(intent);

in ActivityA.onCreate() do this:
super.onCreate();
Intent intent = getIntent();
if (intent.hasExtra("startActivityC")) {
    // Need to start ActivityC from here
    startActivity(new Intent(this, ActivityC.class));
    // Finish this activity so C is the only one in the task
    finish();
    // Return so no further code gets executed in onCreate()
    return;
}

The idea here is that you launch ActivityA (your dispatcher) using FLAG_ACTIVITY_CLEAR_TOP so that it is the only activity in the task and you tell it what activity you want it to launch. It will then launch that activity and finish itself. This will leave you with only ActivityC in the stack.


text:
Q: Json to XML with namespaces and prefix I have a json and I want to create specific XML format for electronic invoices.
{
   "invoice": {
      "issuer": {
         "vatNumber": "888888888",
         "country": "GR",
         "branch": "1"
      },
      "counterpart": {
         "vatNumber": "999999999",
         "country": "GR",
         "branch": "0",
         "address": {
            "postalCode": "12345",
            "city": "TEST"
         }
      },
      "invoiceHeader": {
         "series": "A",
         "aa": "101",
         "issueDate": "2021-04-27",
         "invoiceType": "1.1",
         "currency": "EUR"
      },
      "paymentMethods": {
         "paymentMethodDetails": {
            "type": "3",
            "amount": "1760.00",
            "paymentMethodInfo": "Payment Method Info..."
         }
      },
      "invoiceDetails": [
         {
            "lineNumber": "1",
            "netValue": "1000.00",
            "vatCategory": "1",
            "vatAmount": "240.00",
            "discountOption": "true",
            "incomeClassification": {
               "classificationType": "E3_561_001",
               "classificationCategory": "category1_2",
               "amount": "1000.00"
            }
         },
         {
            "lineNumber": "2",
            "netValue": "500.00",
            "vatCategory": "1",
            "vatAmount": "120.00",
            "discountOption": "true",
            "incomeClassification": {
               "classificationType": "E3_561_001",
               "classificationCategory": "category1_3",
               "amount": "500.00"
            }
         }
      ],
      "taxesTotals": {
         "taxes": {
            "taxType": "1",
            "taxCategory": "2",
            "underlyingValue": "500.00",
            "taxAmount": "100.00"
         }
      },
      "invoiceSummary": {
         "totalNetValue": "1500.00",
         "totalVatAmount": "360.00",
         "totalWithheldAmount": "100.00",
         "totalFeesAmount": "0.00",
         "totalStampDutyAmount": "0.00",
         "totalOtherTaxesAmount": "0.00",
         "totalDeductionsAmount": "0.00",
         "totalGrossValue": "1760.00",
         "incomeClassification": [
            {
               "classificationType": "E3_561_001",
               "classificationCategory": "category1_2",
               "amount": "1000.00"
            },
            {
               "classificationType": "E3_561_001",
               "classificationCategory": "category1_3",
               "amount": "500.00"
            }
         ]
      }
   }
}

https://www.aade.gr/sites/default/files/2020-09/SampleXML_1.1_taxes_per_invoice%20%28%CE%A4%CE%99%CE%9C-%CE%A0%CE%A9%CE%9B%CE%97%CE%A3%CE%97%CE%A3%29.xml
Can you help me with the best solution to achieve this ? I am working with .net core 3.1
My problem for now is the namespaces and the prefixes
<InvoicesDoc xmlns="http://www.aade.gr/myDATA/invoice/v1.0"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.aade.gr/myDATA/invoice/v1.0/InvoicesDoc-v0.6.xsd"
        xmlns:icls="https://www.aade.gr/myDATA/incomeClassificaton/v1.0"
        xmlns:ecls="https://www.aade.gr/myDATA/expensesClassificaton/v1.0">

...
<incomeClassification>
                <icls:classificationType>E3_561_001</icls:classificationType>
                <icls:classificationCategory>category1_2</icls:classificationCategory>
                <icls:amount>1000.00</icls:amount>
</incomeClassification>

A: Namespaces are tricky.  So I like to parse strings which is easier than trying to do in code.  Here is an example using xml linq :
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
         static void Main(string[] args)
        {
             string ident =
                 "<InvoicesDoc xmlns=\"http://www.aade.gr/myDATA/invoice/v1.0\"" +
                 " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" +
                 " xmlns:icls=\"https://www.aade.gr/myDATA/incomeClassificaton/v1.0\"" +
                 " xmlns:ecls=\"https://www.aade.gr/myDATA/expensesClassificaton/v1.0\"" +
                 " xsi:schemaLocation=\"http://www.aade.gr/myDATA/invoice/v1.0/InvoicesDoc-v0.6.xsd\">" +
                 "</InvoicesDoc>";

             XDocument doc = XDocument.Parse(ident);
             XElement invoicesDoc = doc.Root;
             XNamespace ns = invoicesDoc.GetDefaultNamespace();
             XNamespace nsIcls = invoicesDoc.GetNamespaceOfPrefix("icls");
             XNamespace nsEcls = invoicesDoc.GetNamespaceOfPrefix("ecls");
             XElement invoice = new XElement(ns + "invoice");
             invoicesDoc.Add(invoice);

             XElement incomeClassification = new XElement(ns + "incomeClassification", new object[] {
                 new XElement(nsIcls + "classificationType", "E3_561_001"),
                 new XElement(nsIcls + "classificationCategory", "category1_2"),
                 new XElement(nsIcls + "amount", 1000.00),
             });
             invoice.Add(incomeClassification);

        }
    }

}

A: You could use XSLT 3.0, along the lines:
    <xsl:template name="xsl:initial-template">
      <xsl:variable name="in" select="json-doc('input-json.json')"/>
      <InvoicesDoc xmlns="http://www.aade.gr/myDATA/invoice/v1.0"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://www.aade.gr/myDATA/invoice/v1.0/InvoicesDoc-v0.6.xsd"
            xmlns:icls="https://www.aade.gr/myDATA/incomeClassificaton/v1.0"
            xmlns:ecls="https://www.aade.gr/myDATA/expensesClassificaton/v1.0">
         <xsl:for-each select="$in?invoices?invoiceDetails?*">
           <incomeClassification>
             <icls:classificationType>{?incomeClassification?classificationType}</icls:classificationType>
             <icls:classificationCategory>{?incomeClassification?classificationCategory}</icls:classificationCategory>
             <icls:amount>{?incomeClassification?amount}</icls:amount>
           </incomeClassification>
         </xsl:for-each>
      </InvoicesDoc>
    </xsl:template>

redpajama_set_name: RedPajamaStackExchange


text:
Q: how can i make my installer to check for invalid folder installation? .Actually i have installed  different version of the software in the same computer so want to check  the folder for  both the version when user proceed for third version of installation. i am trying to use loop but the the installer is not working.Thanks in advance.
I have already 2 versions of same software installed in the same computer .I want when i will install the third version the script should check the path and it should not allow user to  install in the same path in which previous two versions are already installed
Function .onVerifyInstDir

  nsArray::Set array 1.6
  nsArray::Set array 1.7
  nsArray::Set array 1.8

  nsArray::Length array
  Pop $R0
  ;DetailPrint `array length: $R0`

  StrCpy $R1 0
  ${DoWhile} $R1 < $R0
    nsArray::Get array $R1
    Pop $R2
    StrCpy $tempregistry "$(^Name)_$R2"

    ;DetailPrint `MyArray2[$R1] is $R2`

 ReadRegStr $path  HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstal\$tempregistry""InstallLocation"  ;fetching installed location

   ${If} $path == ""

   ${Else}
   strCmp $path $INSTDIR 0 pathGood
   ;Abort
    IntOp $R1 $R1 + 1
   ${EndIf}
  ${Loop}

    PathGood:
  FunctionEnd

A: Here are the steps

*

*Store ur product name or ur registry entry in a variable.

*Store the path to be installed in a variable eg $path

*Inside a loop check for the registry entry.
ReadRegStr $pdt  HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\productname

*If found,retrieve the value of the installed location and store it in a variable;
eg $path1
ReadRegStr $path1 $pdt "installed location"
else proceed

*${if} $path == $path1
messagebox mb_ok "Another version already installed in the path"

*${else}
proceed

*${endif}


text:
Q: Non-static method execute() cannot be referenced from a static context I don't understand why I'm receiving this compile error; none of my classes or methods involved here are static. Maybe someone can shed some light here.
In my MainActivity class I have declared a public class that extends AsyncTask:
public class AsyncStuff extends AsyncTask<String, Void, String> {
    ...
}

In my non-activity class I have a public function that should fire the async task:
public class Util {
    public void ExecuteAsyncMethod(){
        MainActivity.AsyncStuff.execute(new String[]{"test" }); // error here
    }
}

I have also tried to instantiate an object of the MainActivity.AsyncStuff class and execute its execute() method, but this doesn't work either since it's not in an enclosing class. I can't move it somewhere else because I need to update the UI so it needs to stay in the MainActivity class.
Anyhow, I need help to figure out why my ExecuteAsyncMethod() method doesn't compile.
Thank you!!

A: Define like this:
public static class AsyncStuff extends AsyncTask<String, Void, String> {
    ...
}

and run like this:
public class Util {
    public void ExecuteAsyncMethod(){
        new AsyncStuff().execute(new String[]{"test" });
    }
}

A: The reason you're getting that error is that you have to instantiate your AsyncTask, you're trying to call execute() as if it was a static method.
As for if you can move your AsyncTask, yes you can, just make the class static (or make it its own class entirely) and have a weak reference to the activity, so you don't hold it in ram should it finish prior to your AsyncTask. This is something you want to do regardless of if you keep it inside your MainActivity or not.


text:
Q: Images with opacity "jumping" on hover in Firefox I have an image which I've faded out using opacity css. The opacity of the image returns to 1 when hovered.
However, in Firefox, it appears to "jump" a little when hovered over. It seems to be something to do with the way Firefox smooths the image while faded - is there a way around this?
Here's a fiddle:
http://jsfiddle.net/jngS8/5/

CSS:
img {
    height: auto;
    max-width: 100%;
}
.container{
    width:200px;
}

.opacity {
    opacity: 0.6;
}
.opacity:hover {
    opacity:1;
}

A: Set
-moz-backface-visibility: hidden;

on the image.
Source: http://nickpye.com/2013/04/03/css3-opacity-transition-image-wiggle-bug-in-mozilla-firefox/.
That article is talking about CSS transitions, but looks like it works without transitons, too.
http://jsfiddle.net/jngS8/6/


text:
Q: Unity lots of similar prefabs vs. editing a master prefab in my projects I often have multiple things I want to instantiate while playing, which are very similar and just differ in e.g. the sprite of the image-component.
My question is, whether it is better to
a) create many prefabs which are mostly the same and just differ in the image component vs.
b) create one prefab and Resources.Load() the needed sprite and set it to the image component of the instance of the prefab, or maybe even
c) create public references for the needed sprites and combine the "one prefab" approach but don't do Resources.Load().
For me, this is mostly interesting concerning image-components, but it would also be nice to know for other cases. Is there a clear answer to which option is better, or does it depend on the component and has maybe the one option better performance, while the other one saves more space?
Cheers.

A: Typically I think the best way to do this is to create a single prefab and then give it a public component or a script that can receive messages and change a private component to control the aspect you want to change.  In the instance you describe, where you just want to change the image component, you can change that component when you instantiate the prefab.
The question becomes a design problem: would you rather change the property (in this case the image components) from the script that instantiated the game object from the prefab after you've instantiated it?  Or send a message to a script on the prefab, which would then, reacting to that message, set its properties accordingly?
You can see a fairly thorough and diverse discussion of instantiation here.
I think the consensus is generally that you do not want to addComponent on tons of prefabs to "specialize" them and you do not want to instantiate tons of prefabs all at once (in one frame) unless it's in start().  Other than that, my suggestion would be to have a single prefab, give it a script that lets you set the proprties you want to set, and proceed accordingly.


text:
Q: How to create a batch file from .exe file? I want to know simply how to create a batch file from .exe file?

A: If you mean you want to create a new batch file from an unrelated existing executable file (in other words, the batch file does something different), you do it the way you create any file. In C, you'd use fopen, fwrite and fclose to create your new file and write whatever batch file commands you want to it.
If you mean you want to create a batch file that "intercepts" your exe file, you can do that too. If your executable file is pax.exe, you can simply rename it to pax2.exe and create a batch file called pax.cmd thus:
@echo off
pax2.exe

This will allow you to do arbitrary actions before and after your executable runs but there are things to watch out for such as executables that return control before they're actually finsihed.
If, however, you're talking about converting an arbitrary executable into a batch file that performs the same task, that's much more difficult. Unless you have the source code or a very good specification on how the executable works, you're going to have a lot of trouble.
Automating the conversion for anything but the simplest executable will be insanely difficult.

And, if you want a link to a batch file that runs your executable, just create the batch file (say in c:\bin\pax.cmd) containing:
@echo off
c:\bin\pax.exe

and then create a shortcut to it from wherever you want (such as the desktop). You could even put the batch file itself in your desktop directory but I'm not a big fan of that. However, to each their own.


text:
Q: Why am I getting just one item (instead of multiple items) in a pandas column? Here is my code:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
import pandas as pd

driver = webdriver.Chrome(service=Service(executable_path=ChromeDriverManager().install()))
driver.maximize_window()
driver.get('https://quotes.toscrape.com/')

df = pd.DataFrame(
    {
        'Quote': [''],
        'Author': [''],
        'Tags': [''],
    }
)

quotes = driver.find_elements(By.CSS_SELECTOR, '.quote')
for quote in quotes:
    text = quote.find_element(By.CSS_SELECTOR, '.text')
    author = quote.find_element(By.CSS_SELECTOR, '.author')

    tags = quote.find_elements(By.CSS_SELECTOR, '.tag')
    for tag in tags:
        quote_tag = tag

    df = df.append(
        {
            'Quote': text.text,
            'Author': author.text,
            'Tags': quote_tag.text,
        },
        ignore_index = True
    )

df.to_csv('C:/Users/Jay/Downloads/Python/!Learn/practice/scraping/selenium/quotes.csv', index=False)

I should be getting this result:

Quote
Author
Tags

"The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking."
Albert Einstein
change deep-thoughts thinking world

Instead I'm getting this:

Quote
Author
Tags

"The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking."
Albert Einstein
world

I'm getting just the last item in the Tags column instead of all four items.
If I run:
quotes = driver.find_elements(By.CSS_SELECTOR, '.quote')
for quote in quotes:
    tags = quote.find_elements(By.CSS_SELECTOR, '.tag')
    for tag in tags:
        quote_tag = tag
        print(quote_tag.text)

I get:
change
deep-thoughts
thinking
world
etc

So that piece of code works.
Why isn't the Tags column being populated appropriately?

A: For your loop, use this code:
quote_tags = []
for tag in tags:
    quote_tags.append(tag.text)

df = df.append(
    {
        'Quote': text.text,
        'Author': author.text,
        'Tags': ' '.join(quote_tags),
    },
    ignore_index = True
)

If you notice, the only tag that's being added (world) happens to be the very last tag...and that's not a coincidence. It's because you loop over the tags, and for each tag, you assign that tag to the quote_tag variable, but you don't do anything with it, so the next loop iteration just overwrites the value set by the previous iteration. Finally, when the loop is over, quote_tag has the value of the last tag.

A: With your code
for tag in tags:
    quote_tag = tag

you replace quote_tag with tag on each run of the for loop and thus override the previous value stored in quote_tag. Thus, after the last run, quote_tag only contains the last tag.
You need to do something like
quote_tag = ''
for tag in tags:
    quote_tag += ' ' + tag

if you want to concatenate all tags together.


text:
Q: AutoComplete with render item to dynamic textbox in razor view? I have few textbox in razor partial view which will be available based on condition. Out of that 1 is attached to autocomplete with below code but when the partial view is loaded then i get error (if textbox is not available)

0x800a138f - JavaScript runtime error: Unable to set property
  '_renderItem' of undefined or null reference

if the textbox is available in Razor view then error doesn't appear.
My code for Jquery is


text:
Q: 2D Collision & Stop in Unity 3D I have a simple scene in 2D. The right yellow box is the "Player", while the green & brown thing is the "Obstacle".
Player has a BoxCollider2D, RigidBody2D and a C# script named Hero.cs attached to it. BoxCollider2D enabled Is Trigger; RigidBody2D enabled Is Kinematics; other settings are left in default values.
Obstacle has only a BoxCollider2D with Is Trigger enabled.
and here is the Hero.cs:
using UnityEngine;
using System.Collections;

public class Hero : MonoBehaviour {
    public float moveSpeed = 0.1f;
    private Vector3 moveDirection;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        Vector3 currentPos = transform.position;
        if(Input.GetKey("left")) {
            transform.Translate(new Vector3(-1, 0, 0));
        } else if(Input.GetKey("right")) {
            transform.Translate(new Vector3(1, 0, 0));
        }
    }

    void OnCollisionEnter2D(Collision2D collision) {
        Debug.Log("Colliding");
    }

    void OnTriggerEnter2D(Collider2D other) {
        Debug.Log("Triggering");

    }
}

Only "Triggering" appears in Console Log.
My question is: What should I add to make the "Player" inaccessible to the "Obstacle" (no need to bounce away)?
Note: Using Unity 4.5

Update: After I set Gravity Scale to 0, collision detection works, but in a strange way. The "Player" go sideway during collision. Watch this YouTube video for action.
I expect the Player only go along X or Y axis. What did I miss ?

A: IsTrigger
Triggers let other colliders pass through without any collision happening. They are only triggering an event, hence the name.
If you disable IsTrigger for both objects, you will get collisions and the corresponding events are fired.
More infos here: http://docs.unity3d.com/Manual/CollidersOverview.html
IsKinematic
Kinematic rigidbody colliders will only collide with other non-kinematic rigidbody colliders.
Have a look at this matrix http://docs.unity3d.com/Manual/CollisionsOverview.html
Disable IsKinematic and move the player with MovePosition if you don't want to use force values to move the player.


text:
Q: C# string case insensitive class for file paths The scenario:
We have on our .Net Core 3.1 application many file paths (of windows OS) that we need to compare and store in Hashsets and Dictionaries that use string comparison (case insensitive).
I tried to find an easy way to handle all these file paths strings and I found 3 options:
Option 1:
Use StringComparison.OrdinalIgnoreCase and use StringComparer.OrdinalIgnoreCase.

*

*Advantage: No need to implement a new class, just use the existing framework.

*Big Disadvantage: Very easy to forget these while developing new code. (We have many strings in the application that are not case insensitive)

Option 2:
Create a IgnoreCaseString class that wraps the string class and overrides Equals, GetHashCode and operator == with StringComparison.OrdinalIgnoreCase.
public sealed class IgnoreCaseString
{
    public IgnoreCaseString(string originalString)
    {
        this.OriginalString = originalString;
    }

    public string OriginalString { get; }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(this, obj))
            return true;

        if (!(obj is IgnoreCaseString filePathString))
            return false;

        return OriginalString.Equals(filePathString.OriginalString, StringComparison.OrdinalIgnoreCase);
    }

    public static bool operator ==(IgnoreCaseString a, IgnoreCaseString b)
    {
        return Equals(a, b);
    }

    public static bool operator !=(IgnoreCaseString a, IgnoreCaseString b)
    {
        return !Equals(a, b);
    }

    public override int GetHashCode()
    {
        return OriginalString.GetHashCode(StringComparison.OrdinalIgnoreCase);
    }
}

*

*Advantage: Very optimize, use the existing string methods, and easy to use.

*Disadvantage: Need to maintain the IgnoreCaseString class.

Option 3:
Use Uri class which is designated for it.

*

*Advantage: Existing class, easy to use.

*Disadvantage: Memory and performance overhead.

The question:

*

*Is there any built-in or easy way to do it?

*Is there another option that I miss?

A:
file paths that we need to compare and store

That already screams case sensitivity. Only Windows has case insensitive paths, all other modern operating systems (for the better or worse) are case sensitive. You should play it safe and stick to case sensitivity.
In fact I'd challenge you to think of how you would get a path of the wrong casing on any OS -- manual entry from a spreadsheet or something? In that case I'd add a "Browse" button that opens a standard open file dialog and gives you the correct string.

#1, Use StringComparison.OrdinalIgnoreCase and use StringComparer.OrdinalIgnoreCase.

It's an okay solution if you ignore the first part. Anything about "forgetting" things can usually be done with custom code analysis modules, and it's fast and memory efficient by itself.

#2, Create a IgnoreCaseString class that wraps the string class and overrides Equals, GetHashCode and operator == with StringComparison.OrdinalIgnoreCase.

Perhaps a better name would be CaseInsensitiveString, as Ignore implies an active action being performed, while your string doesn't perform any actions, it just passively behaves differently.
This solution uses more memory than the previous one, and it doesn't let you use modern constructs like Span for less memory overhead in tight string processing scenarios.
Your implementation is also broken, re-read your operators:
public static bool operator ==(IgnoreCaseString a, IgnoreCaseString b)
{
    return string.Equals(a, b);
}

#3, Use Uri class which is designated for it.

It's meant for URI protocol paths, of which file:// is one of. It's not meant for local disk paths, though of course it can encode them with the file:// handler. I agree with you, seems overkill.


text:
Q: Decode unknown encoding for numpy array Can anybody help me decode this?
{'py/object': 'numpy.ndarray',
'values': 'eJxjYGBgkGnVczQGAl07DcezZ86cmeCo7Dhr5syZJ6fLgelSHwnHNCBY5isMlpdYxQdWfz2aA6I+mhmsTvDAPwcQ/TDvh4PHwyqRS6mfHQptua5PvvIOTCc3vwDTwVWPHeRbXwdqPLsHpn9MueEAVL7uefdlh8NfNWL8Oc87AJUt3rDgBJgWWH/YAehMhgX++8G0wo4dEP70zWD6gMJ6hy9/r1S8PLrCwbzTMUF1/2IwP/PBPIesPSWTJZbNAKtrODbZQd2QY42MUT+Yz/C8wyF1VUJI0LxmB1YTQTObGfUO4dEb97+5X+EQaqC1UnhHscM/519vX/fkO2wV/X363eUMB8UNRRkTTyc7HDy10HVbcrzDWWu/ixNlIh2a2/5x6h0IdjgnGXhLeo2/g07ti6Zf7zwcfqyayrn/jjNU3B4qbgEVN4aK6ztsUDgbYXJWw2HDv/OJ++4oO1z7b3lm+nF5h33fzkxicJV0qDoa3G/CIeLgfPLJlXMT+B0cr764yuDK6fD9mbmPCQeLw/l5p6+o/Phvn3WXbev9qJ/2bmw7uw1cv9hDxN/bAwBaO9+O',
'shape': [61],
'dtype': 'float64',
'byteorder': '<'}
Many thanks - looked through several encode/decode functions and haven't had any luck yet.


text:
Q: Simulating user input in bash script while executing bin file I'd like to ask what is the most common way to parse user input to the executable program, in particular on Linux.
I tried to invoke bash script that contains the following lines:
BIN_FILE=<filepath>
FLAG=<flag>\n

${BIN_FILE}
echo -ne ${FLAG}
[...]

but since the executed program is a separate thread the echo line of my script is not processed until the program terminates.
In adnvace thank you for your answers! BR -M


text:
Q: changing page content dynamically based on the url Is it possible to change the content on a webpage based on the URL ?
For example, when someone visits:
example.com/dyanmictextpage.html/?utm_source=google&utm_campaign=dynamictext&utm_term=hello-world
I'd like to update a specific piece of text on the page to then say "Hello World" that's based on the last part of the URL under "utm_term=hello-world"
The code would need to auto insert whatever is after "utm_term=" and remove the hyphen and capitalise the first letters of each word.....
Do you know how??

A: var message = '';

var query = document.location.search.substring(1); // Remove leading '?'
var params = query.split('&');

// Get 'utm_term' from the request parameters
for (var i = 0; i < params.length; i++) {
   var key = params[i].split('=')[0];
   if (key === 'utm_term') {
      message = params[i].split('=')[1];
      break;
   }
}

if (message.length > 0) {
   // Split the message by words and capitalize the first letter of each word
   var words = message.split('-');
   for (var i = 0; i < words.length; i++) {
      words[i] = words[i].charAt(0).toUpperCase() + words[i].substring(1);
   }

   // Finally, put the message to HTML (say, to element with id="message")
   document.getElementById('message').innerHTML = words.join(' ');
}

A: You can - a good place to start is to break down your problem into smaller problems, and solve it piece by piece.
The first thing you need to do is get the query string values from the URL (i.e. utm_term=hello-world):
How can I get query string values in JavaScript?
Once you've got those, you'll need to dynamically replace things like hyphens so you can work the data into the format you want:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FString%2Freplace
Once you've done that, you can inject content into the page. I'll leave that bit for you to look up.


text:
Q: image map circle will only allow clicking on top line and bottom line of image my image map wont allow clicking on the circle only the top and bottom line of the image
i tried resizing and i have checked many places and i cant see my error
<img src="../images/pumpkin.gif" alt="pumpkin" height="75"
usemap="#pumpkin">
<map name="pumpkin">
    <area target="_self" alt="pumpkin" title="home" href="../index.html"
coords="40,40,40" shape="circle">
</map>

i expect the image to be clickable anywhere in the 40 radius


text:
Q: logics for particular dates for overtime sheets in excel I am working on overtime sheet for a institution. I made a sheet where I used date from 1 to 31 of days. However, over time is appearing in random days. Therefore, I need to write this days manually. Thus, I want to apply logics if input OT into the overtime date (OT = overtime) then that particular date will be shown in the other rows. Is there any formula available?

A: I think I understand what you're trying to achieve:
Assuming you have row of dates in cells B9:AF9

*

*In cells  B10:AF10 input "OT" where needed

Or, if you enter "OT" according to people's names, add a formula there to find out if you anyone had OT on this date
=IF(COUNTIF(B11:B24,"OT")>0,"OT","")

or if your Excel uses semicolon ";" not comma "," :
=IF(COUNTIF(B11:B24;"OT")>0;"OT";"")

it will indicate if we had OT on this day.

*In cell D30 paste a formula

=IFERROR(INDEX($B$9:$AF$9,1,SMALL(IF(($B$10:$AF$10="ot")*($B$9:$AF$9>0)>0,MATCH(COLUMN($A$9:$AE$9),COLUMN($A$9:$AE$9),0),""),COLUMN(A1))),"")

but insert it as an array formula, pressing Ctrl+Shift+Enter simultaniously.
If your Excel uses semicolon as parameter separator use this one:
=IFERROR(INDEX($B$9:$AF$9;1;SMALL(IF(($B$10:$AF$10="ot")*($B$9:$AF$9>0)>0;MATCH(COLUMN($A$9:$AE$9);COLUMN($A$9:$AE$9);0);"");COLUMN(A1)));"")

insert it as an array formula, pressing Ctrl+Shift+Enter simultaniously.

*Copy and paste it to cells E30 - AH30.

It will give us an array of dates where you put 'OT' in the upper table.


text:
Q: Why is willUnloadSearchResultsTableView not getting called in iOS7? For some reason the UISearchDisplayController delegate method, willUnloadSearchResultsTableView, stopped working in iOS7.
It works correctly on my 4s device running iOS 6.1.3, but not in the iOS7 simulator. I've tried both 7.0.3 with Xcode 5.0 and 7.1 with Xcode 5.1 Beta 5 (5B103i).
To test this open the sample project in Xcode 5, Simple UISearchBar with State Restoration, xcdoc://ios/samplecode/TableSearch/Introduction/Intro.html
1) Locate the search delegate methods in APLViewController.m and add below them:
- (void)searchDisplayController:(UISearchDisplayController *)controller willUnloadSearchResultsTableView:(UITableView *)tableView {

    NSLog(@"willUnloadSearchResultsTableView");
}

2) Run the app on an iOS6 device and punch some text into the search view and then tap the Cancel button. You should see the text "willUnloadSearchResultsTableView" in the console log.
3) Now try running the same code on an iOS7 device/simulator. This time, when you tap the cancel button, you won't see anything written to the console log.
Can anyone shed light on this?
It's a real problem for me, because I've added a custom search item to the Tab navigator and update the item-label with the number of search results. I restore the original tab item-label when the user unloads the search view, but it doesn't get restored in iOS7.

A: It could be that Apple changed the table view caching mechanism and doesn't unload the table in the same pattern as before.
If you believe that this is a bug on Apple's side, make sure to open a bug report at https://bugreport.apple.com.
In the meantime, try moving your code to the following delegate methods:
– searchDisplayController:willShowSearchResultsTableView:
– searchDisplayController:didShowSearchResultsTableView:
– searchDisplayController:willHideSearchResultsTableView:
– searchDisplayController:didHideSearchResultsTableView:


text:
Q: How to get extra claims from OpenIDConnect client login in OpenLiberty I'm trying to get a specific claim from an token using OpenIDConnectClient feature in open liberty.
The user is mapped correctly, as is the roles (groups claim), but I can't get the specific claim.
The OpenIDConnectClient is connecting to a KeyCloak realm.
My server.xml:
<?xml version="1.0" encoding="UTF-8"?>
<server description="${project.name}">

    <featureManager>
<!--         <feature>microProfile-3.2</feature> -->
        <feature>appSecurity-3.0</feature>
        <feature>transportSecurity-1.0</feature>
        <feature>openIDConnectClient-1.0</feature>
        <feature>jaxrs-2.1</feature>
        <feature>mpJwt-1.1</feature>
        <feature>cdi-2.0</feature>
        <feature>jwtSso-1.0</feature>
    </featureManager>

    <httpEndpoint id="defaultHttpEndpoint"
                  httpPort="9080"
                  httpsPort="9443"/>

    <webApplication location="${project.name}.war" contextRoot="/">
        <classloader apiTypeVisibility="+third-party" />
    </webApplication>

    <openidConnectClient id="cdoMondaine"
        clientId="cdo-mondaine"
        clientSecret="****"
        discoveryEndpointUrl="https://example.server.com/auth/realms/esdl-mapeditor/.well-known/openid-configuration"
        signatureAlgorithm="RS256"
        scope="openid profile email groups user_group microprofile-jwt"
        userNameAttribute="email"
        userIdentifier="email"
        userIdentityToCreateSubject="email"
        groupNameAttribute="groups"
        groupIdentifier="groups"
        userInfoEndpointEnabled="true"
        authFilterRef="dataUrl">
    </openidConnectClient>

    <jwtSso includeLtpaCookie="true" jwtBuilderRef="myBuilder" setCookieSecureFlag="false"></jwtSso>
    <jwtBuilder id="myBuilder"
        issuer="https://example.server.com/auth/realms/esdl-mapeditor"
        scope="openid profile email groups user_group microprofile-jwt">
        <claims>name,aud,user_group,groups,upn</claims>
        <audiences>cdo-mapeditor</audiences>
    </jwtBuilder>
    <mpJwt id="myMpJwt"
        issuer="https://example.server.com/auth/realms/esdl-mapeditor"
        jwksUri="https://example.server.com/auth/realms/esdl-mapeditor/protocol/openid-connect/certs"
        audiences="cdo-mapeditor"
        />

    <authFilter id="dataUrl">
         <requestUrl id="requestUrl" urlPattern="/data" matchType="contains"/>
    </authFilter>

    <!-- This is the keystore that will be used by SSL and by JWT. -->
    <keyStore id="defaultKeyStore" location="public.p12" type="PKCS12" password="*****" />

    <!-- com.ibm.ws.webcontainer*=all:HTTPChannel=all:GenericBNF=all -->
    <logging traceSpecification="com.ibm.ws.webcontainer*=all:com.ibm.ws.security.*=all=enabled:nl.tno.*=all" /> <!-- maxFiles="8" maxFileSize="200"  -->

</server>

In the trace logs I see the token is correctly received (after Keycloak's login page).
As you can see I mapped the token using a jwtBuilder to a mpJWT token, but the claims are not copied.
How can I access the user_group claim in code? The user_group is a JSON array in the token.

A: You may need adjust the following configuration if group claim name in id_token is "user_group". You always set groupIdentifier to the claim name.
Remove following two attributes from server.xml
        groupNameAttribute="groups"
groupIdentifier="groups"
and replace them with
groupIdentifier="user_group".
Option 1:
`Suject sujb = com.ibm.websphere.security.auth.WSSubject.getRunAsSubject();`
`Iterate through subject, until find  com.ibm.websphere.security.cred.WSCredential`
`use method getGroupIds() to find all groups.`

Option 2:
    com.ibm.websphere.security.openidconnect.token.IdToken idToken
com.ibm.websphere.security.openidconnect.PropagationHelper.getIdToken();
idToken.getClaim("claim_name");


text:
Q: std::vector and Constructors Which constructor does std::vector call when it is making a new instance of the object it's containing? I am under the impression it calls a default constructor but what if one is not defined or is the compiler doing that for me?
Particularly in a case as such:
class Foo
{
    public:
        Foo(int size)
        {
            data = new double[size];
        }

        ~Foo()
        {
            delete[] data;
        }

    private:
        double* data;
};

std::vector<Foo> myVector;
Foo bar(5);
myVector.push_back(bar);
//stuff

How does it know how much memory to allocate when the object has an unknown size until after construction?

A: At a minimum, for std::vector<T> to compile, T must be copy-constructible, and copy-assignable.  If you want to use std::vector<T>::vector(int) (or std::vector<T>::resize()), then T must have be default-constructible.  If any of these requirements are not fulfilled, the code will not compile.
...
C++03 standard, section 23.1 (discussing containers in general):

The type of objects stored in these components must meet the requirements of CopyConstructible types (20.1.3), and the additional requirements of Assignable types.

Section 20.1.4:

20.1.4 Default construction
The default constructor is not required.  Certain container class member function signatures specify the default constructor as a default argument. T() shall be a well-defined expression (8.5) if one of those signatures is called using the default argument (8.3.6).

A: What happens, after you fix the error:
std::vector<Foo> myVector;
myVector.reserve(10);
myVector.push_back(bar);

is that you have two Foo instances pointing to the same data buffer.  It will probably appear to work for a while, but eventually both objects get destroyed, the destructor is called twice (or more, depending on whether the vector needs to move its content around) and the buffer is double-freed, resulting in undefined behavior (which usually means crash).

To address the initial content of the vector, it copy-constructs the pattern you pass in as a parameter (this parameter defaults to a default-constructed object, but doesn't have to be):
std::vector<Foo> myVector(10, bar); // 10 copies of bar


text:
Q: Adding two tuples in F# Trying to understand tuples in F#..
Current thought process
let add tuples a b =
let a = (_,_)
let b= (_,_)
(a+b)

this won't work due to "_" being invalid for this case so then I thought to try
let add tuples a b =
let a = (c,d)
let b = (e,f)
fst a + fst b, snd a + snd b;;

this won't work because c,d,e,&f are not known variables. In java I would traditionally just initialize that variable so it can be used but in F# that seems a bit funky let a= int not even sure if that would work anyways
any help on trying to fix my thought process would be appreciated. Thanks
edit:
expected result
a (1,3)
b (2,4)
return (3,7)

A: There are two ways of accessing elements from a tuple and your code seems to be confusing them. First, you can use fst and snd on two-element tuples. You actually have this right, but you need to remove other unnecessary lines - a and b are tuples, so you can write just:
let add a b =
  fst a + fst b, snd a + snd b

The other option is to use pattern matching. To do this, you need to assing a tuple value, i.e. a or b to a pattern that defines new variables like (c, d). Doing the above using pattern matching looks like this:
let add a b =
  let (a1, a2) = a
  let (b1, b2) = b
  a1 + b1, a2 + b2

Patterns can appear in stand-alone let bindings like above, but you can also use them directly in the arguments of a function - so you can shorted this to:
let add (a1, a2) (b1, b2) =
  a1 + b1, a2 + b2


text:
Q: Total energy of a causal impulse response (tricky integral) The total energy of a causal impulse response is given by:
$$
\begin{align}
E
&= {1 \over 2 \pi} \int_{-\pi}^{\pi} \left|{H(e^{i\omega})}\right|^2d\omega
\\
&= {1 \over 2 \pi i} \oint H(z)H(z^{-1})z^{-1}dz
\end{align}
$$
Where $z = e^{-i\omega}$ and $H(z)$ is given by:
$$
H(z) = {b_0 + b_1 z^{-1} + b_2 z^{-2} \over 1 + a_1 z^{-1} + a_2 z^{-2}}
$$
Apparently the determination of this integral in the z-domain is known, does anyone know what it is?

A: Use the residue theorem. Note that the poles of $H(z)$ and of $H(z^{−1})$ are reciprocals of each other, so unless they're on the unit circle (in which case the integral would be undefined), two are inside and two are outside (and $z^{−1}$ contributes a third pole at $z=0$, with residue $b_0b_2/a_2$). I don't see any way to make use of the special structure of the problem beyond that.


text:
Q: Needed: A simple way to remotely monitor a process on my server I have a cloud-based server running a Java process (a POP/SMTP server called davmail, details don't really matter).
What is the simplest way to monitor the status of that Java process remotely? I need to know if and when it goes down. I could just leave an ssh session open and tail the log, but is there something more elegant?
Maybe I need to install a webserver and run  some monitoring software on the same server. Or maybe there is a client program I can run on my local machine (a Mac) that can be alerted by some cron job on the server whenever the Java process stops?

A: Well you can always have a cronjob doing
echo "100 logout" | nc yourserver.fqdn 143 || \
   {
      echo "The server is down" |\
      mailx -s "Red alert! Red alert! This is not a drill!" user@domain.com;
   }

Depends on what you call simple and what other functionality you may want.

*

*100 logout is nothing but a very trivial IMAP command that, if you haven't logged in before, will make the server terminate the connection.

*nc is a tool that opens TCP connections and attaches STDIN and STDOUT to the socket.

The combination results in establishing a connection to your IMAP server, and telling it "we're done". If your IMAP server is up and running, it recongnises the command and close the TCP connection, making nc exit normally.
If something goes wrong, for instance the TCP connection is never established, or times out because the server doesn't handle the IMAP command, your IMAP server obvously is not available. In that case you want a notification and in that case nc will always terminate abnormaly.
|| means that if nc terminates abnormaly, everyting in the { ... } is executed. The example command i provided here sends an email using mailx to user@domain.com with the subject "Red alert! Red alert! This is not a drill" and the content "The server is down".
Note however, that mailx is not part of every Linux's installation and that there are different versions of it, behaving differently.
You can, of course, deploy some monitoring software, for instance Shinken, which have a fancy web frontend, keep track of what they monitored and can send emails.

A: That all depends on what you mean by "goes down", the details of what you are running and doing do tend to matter when monitoring as well....
The most thorough form of monitoring for your "service" is to have an external automated system do what your clients do and report to you when anything unexpected occurs.
From the brief description of your email service, my first end to end test would be:

*

*Send an email #id via SMTP to a local monitor account

*Wait the maximum amount of seconds you want that to take.

*Check for email #id @ monitor on the POP server.

That one check from an external monitoring host is going to pick up about 99% of the problems that could occur in a simple email system.
These service or transaction monitors tend be custom scripts written in something like Ruby, Python or Perl which have modules to easily implement things like SMTP or POP programatically.  The scripts then generally plug into a monitoring solution but even triggering a simple email or SMS via a gateway from a cron job would suffice if you want something simple. If you pay for a monitoring solution you will generally get their attempt at a GUI designer for the same type of monitor.
Of course in the real world this quickly becomes more complicated. You might offer secure ports for both POP and SMTP requiring another check. Maybe IMAP is added in with a bit of Carddav and Caldav, you might have services on multiple hosts.
What an overall service check like the above won't readily tell you, is where the problem lies, just that there is a problem somewhere.
Lower level monitoring
By monitoring individual components of the you service you basically make it easier to identify (or predict) where an issue lies from monitoring before doing any leg work. This type of component monitoring is what systems like Nagios, Zabbix or big ones like Tivoli Monitoring are good at.
This can be an ever expanding tree of things, depending on how detailed you make it and again, how complex the system is that supports your "service"
"Your mail Service" depends on
Services:     POP:110 SMTP:25
Application:  devmail
OS:           linux Z
Host:         server Y
  Components:   diskA diskB cpu1 cpu2  memory
Ntwork:      ethernetA, Switch B, Router C, Firewall X

Each component has metrics or a state you can report on.
Externally
Service:
  POP service   - Are we accepting connections on 110,995
  SMTP service  - Are we accepting connections on 25,587

Locally
Application:
  devmail process(es) (is it running, memory, cpu, handles, io)
  JMX parameters of the java process (memory, threads, performance, garbage collection)
OS:
  Disk, Memory, Cpu, IO

etc...

What if the monitoring host goes down? Or it's just the network between the service and monitor.
It's generally good to run the service checks from two (or more) external hosts which are as close to where the clients are coming from (without impacting your monitoring). Then also run the checks locally on the host or at least from local network. This way you get a better idea of most network based problems.

*

*If one external client fails, probably an external network.

*If local client is working, but all external clients are failing, probably local network.

*If all clients are failing, probably local issue.

I see a lot of people tend to build their monitoring solutions the wrong way around. They come up with a lot of the lower level system metrics and 1000's of monitors and level's they think are appropriate to alarm at, when none if that really matters. I mean they're nice for analysis and capacity management, you can make some swanky graphs out of all those values and they can be extremely useful but don't really mean much when you missed metric x at level y that means no one can receive emails.

A: There are any number of monitoring applications that can be configured to send an alarm in various manner - by SNMP traps, by email, by SMS if you've got the hardware or software/subscription. Many of them can also restart the process on itself as necessary.
Google for monit, nagios, or just "monitoring software". Also https://softwarerecs.stackexchange.com/ may be a good place to ask for recommendations.

A: I'd suggest trying out SeaLion. It is a cloud based Linux server monitoring tool.  Installation takes just seconds and UI is clean and simple. Plus the alerting feature is great. There is a 'daily digest' feature which sends you a timed email everyday with the summary of the servers' performance.

A: Using nagios or monit locally is hard to avoid but you can get a great second line of defense by using something like https://cronitor.io to monitor the nagios process itself. Setup nagios or monit to do a health check against a Cronitor address and you'll be alerted if the health check doesn't run.


text:
Q: how to prevent ir receiver from waking computer I have an HP dv4 notebook, which has an ir receiver on the front.  I want to configure it so that no matter what, IR signals will not trigger vista media center to start.  It currently starts whether the computer is on or in sleep mode in response to MCE remote commands being directed at another computer in the room.  how do I make the notebook ignore the ir commands?
Ive tried uninstalling the IR tranceiver device, whenever I reboot windows reinstalls the drivers for it and im back where i started.

A: no option in the BIOS to disable the IR receiver?

A: In Device Manager, highlight the IR device and right click. Select properties. Navigate to the Power Management tab (might be labeled differently in XP) and uncheck the box that says "Allow this device to wake the computer" and click apply.

A: Low-tech solutions for high-tech problems. Don't laugh. Cut a strip of duct tape and paste it over the IR window. I had to resort to this on an old Compaq notebook that kept trying to transfer files whenever my Treo came near.

A: Have you tried steps like these (from a message board post):
1) Disable automatic driver downloads:
- Start menu -> Right click Computer -> Properties -> Advanced System Settings (top left) -> Hardware -> Windows Update Drivers Settings -> Select "Never check for drivers when I connect a device." -> OK -> Apply -> OK
2) Turn off SSDP Discovery:
- Start menu -> Type in "services.msc" without quotes and press Enter -> Scroll to "SSDP Discovery" -> Right click and select Properties -> Change Startup Type to "Disabled" -> Apply -> OK
3) Uninstall ENE CIR Receiver:
- Start menu -> Right click Computer -> Manage -> Device Manager -> Click the + beside Human Interface Devices -> Right click "ENE CIR Receiver" and select Uninstall -> MAKE SURE TO CHECK THE UNINSTALL SOFTWARE BOX ON THE PROMPT (this will take the Microsoft eHome Infrared Trasceiver with it) -> OK -> Let the uninstall take place -> Reboot the computer
4) Preventing installation of IR device drivers:
- Upon reboot you will receive a prompt asking you if you want to install the device drivers -> SELECT "NEVER FOR THIS DEVICE"
5) Turn ON SSDP Discovery:
- Follow directions from earlier and select "Manual" from the drop down menu (Startup Type) -> Apply -> OK

Have you tried just disabling the IR transceiver?


text:
Q: "Error Cannot find module '/var/task/index" AWS Lambda I'm currently coding a Node.js Alexa skill via Powershell, and I have been trying to code a function that you can use the echo dot as nightlight. I cloned the skill via github.
The code is:
import { SkillBuilders } from "ask-sdk-core";
import { AmazonCancelAndStopIntentHandler } from "./handlers/AMAZON_CancelAndStopIntentHandler";
import { AmazonHelpIntentHandler } from "./handlers/AMAZON_HelpIntentHandler";
import { CustomErrorHandler } from "./handlers/CustomErrorHandler";
import { GameEngineInputHandler } from "./handlers/GameEngine_InputHandler";
import { LaunchRequestHandler } from "./handlers/LaunchRequestHandler";
import { SessionEndedHandler } from "./handlers/SessionEndedHandler";
import { TimeIntentHandler } from "./handlers/TimeIntentHandler";
import { LogInterceptor } from "./interceptors/LogInterceptor";

export const handler = SkillBuilders.custom()
    .addRequestHandlers(
        new AmazonCancelAndStopIntentHandler(),
        new AmazonHelpIntentHandler(),
        new LaunchRequestHandler(),
        new SessionEndedHandler(),
        new TimeIntentHandler(),
        new GameEngineInputHandler(),
    )
    .addErrorHandlers(
        new CustomErrorHandler(),
    )
    .addRequestInterceptors(
        new LogInterceptor(),
    )
    .addResponseInterceptors(
        new LogInterceptor(),
    )
    .lambda();`

When I upload it via ask deploy or zip it and upload it via aws lambda, I get this error
{
  "errorMessage": "Cannot find module '/var/task/index'",
  "errorType": "Error",
  "stackTrace": [
    "Function.Module._load (module.js:474:25)",

    "Module.require (module.js:596:17)",
    "require (internal/module.js:11:18)"
  ]
}

This is the Outpot log
START RequestId: 68837f04-333e-453f-b643-1818f2a33807 Version: $LATEST
Unable to import module 'index': Error
    at Function.Module._resolveFilename (module.js:547:15)
    at Function.Module._load (module.js:474:25)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
END RequestId: 68837f04-333e-453f-b643-1818f2a33807
REPORT RequestId: 68837f04-333e-453f-b643-1818f2a33807  Duration: 53.20 ms  Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 58 MB  Init Duration: 0.98 ms

I tried to zip only the files, give the permission to node_modules folder, I checked the index.hadler and I installed module-js, request modules, and many other Node modules.
This is my directory
│   index.ts
│   package-lock.json
│   package.json
│
├───handlers
│       AMAZON_CancelAndStopIntentHandler.ts
│       AMAZON_HelpIntentHandler.ts
│       CustomErrorHandler.ts
│       GameEngine_InputHandler.ts
│       LaunchRequestHandler.ts
│       SessionEndedHandler.ts
│       TimeIntentHandler.ts
│
├───interceptors
│       LogInterceptor.ts
│
├───node_modules
│
└───utils
        ColorCycle.ts
        Constants.ts
        Directives.ts
        SilenceGenerator.ts


text:
Q: Load and then append on AJAX Success I'm using AJAX to send inputted data to the database which I've managed to achieve. Where I'm struggling is on the success parameter. I'm trying to load and then append a PHP file once the initial AJAX call is successfully completed.
var data = $("#form_write_post").serializeArray()

$.ajax({
    type: "POST",
    url: $("#form_write_post").attr("action"),
    data: data,
    async: false,
    success: $.get("test.php", function(data) {
        $('ul.timeline').append(data);
    });
});

I managed to append JavaScript data but I need to be able to get other data from the database.
Thanks

A: remove $.get(){} in success
$.ajax({
    type: "POST",
    url: 'test.php', //if ur action is test.php
    data: data,
    async: false,
    success: function(data) {
        $('ul.timeline').append(data);
    });
});


text:
Q: Objective-C Static Library I currently sell a static library and one of my clients is asking for "Generate Debug Symbols" to be turned on to help them debug any issues.  My concern is they'll be able to use this to see my source code or any information I may not want them to see.
Do debug symbols allow my library to be reverse engineered or does it allow them to view source?
Thanks.

A: It allows them to see the variable names and routine names in the debugger.  It does not expose the source code.  It might make it slightly easier to reverse engineer, but not a whole lot.

A: Yes, it does make it easier for them to reverse engineer your code. But you should also see this as something positive! If you include debug symbols it will be easier for them to debug any errors, and they may help you fix them.


text:
Q: How to save in values server in JSON android http://www.slicapp.com/slic/edit_profile.php?message=[{&email1=arun&email2=gggg&email3=gg&facebook=ffg&twitter=ddgg&gplus=ffdd&youtube=fdd&linkedin=gff&instagram=gfg&tumblr=aa}]

i have to upload data on server by click on save buttton ho to do this in android
i am new and need urgent

A: In your android application, you need to do the following:

*

*Build a JSONObject with values

*Send this to your server through HttpPost

And on your server, you need a php file which will receive this object, parse it and insert the values into an sql database. It is as important to have the php code right as much as the android code.
You will get a lot of tutorials if you google this. Some of the first few results when I googled this now are:
http://androidforums.com/application-development/297822-sending-json-server.html
http://www.codeproject.com/Articles/267023/Send-and-receive-json-between-android-and-php
A similar question has been asked multiple times. Have a look at this: Send data from android to server via JSON


text:
Q: KDP 'changeMedia' not working after 2 count I am using Kaltura HTML5 Video Player in my web page. On end of the video playing next endryId using changeMedia event.
Code is:
function playerPlayEndHandler(){
   eIdCount++;
   kdp.sendNotification("changeMedia", {'entryId': entryIdArray[eIdCount]});
}

Array variable entryIdArray has 4 endry id's. First 2 endry id's only playing. After end of the 2nd media 3rd media is not changed.
Any one suggest for this?

A: That issue occure in Kaltura Player.
Now its solved by Kaltura team. So, now it is working fine.


text:
Q: How to reset the 'jupyter notebook password' to default set token again? I mistakenly typed 'jupyter notebook password' command in my virtual enviromint that I created to run anaconda (linux). This prompted me to set a password. I just gave 'a blank' password to the following:
Enter password:  *
Verify password: *
The problem is when I call 'jupyter notebook', it does not provide me with the full address with its token anymore. I only get  http://localhost:8888/ instead without the token and I cannot open Jupiter notebook from my virtual env).
My question is, how I can reset it back to the default where it used to give me the full address with the token?
another words, how do I make it like the way it was or how do I get the token back?
Below is link for the reference document, look at the 'Automatic Password setup' section with command I used --> $ jupyter notebook password
https://jupyter-notebook.readthedocs.io/en/latest/public_server.html


text:
Q: Rails active record query: rendering only the most recent child object (ordered by child created_at date) in has_many relationship A Parent has_many :children. I want to render each Parent's last child, ordered by the child's created_at date. I'm having trouble figuring out how to do this with active record & rails.

A: Try:
youngest_kids = Parent.includes( :children ).map { |parent| parent.children.last }.compact

compact removes the nils returned for parents without children

A: try
Parents.all.each do |parent|
  parent.children.order(:created_at).last
end


text:
Q: .NET 6 App Registration authorization validates token but returns 401-Unauthorized error I am trying to do an app registration authorization for an ASP.NET Core 6 Web API. I get a token using the app registration credentials and authenticated to the API. The token validation seems to be working but I get a 401-Unauthorized error with no information. In Postman is shows up as an invalid token.
Here is my client setup to get the token
var keyValues = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("tenant_id", tenant_id),
                    new KeyValuePair<string, string>("client_id", client_id),
                    new KeyValuePair<string, string>("client_secret", client_secret),
                    new KeyValuePair<string, string>("scope", scope),
                    new KeyValuePair<string, string>("grant_type", "client_credentials")
                };

var c = new FormUrlEncodedContent(keyValues);
tokenUrl = "https://login.microsoftonline.com/"+tenant_id+"/oauth2/v2.0";

var call = await client.PostAsync(tokenUrl + "/token", c);}

The Web API appsettings.json setup matches the token parameters
{
    "AzureAd": {
        "Instance": "https://login.microsoftonline.com",
        "Domain": "<domain>",
        "TenantId": "<tenant>",
        "ClientId": "<clientId>",
        "ClientSecret": "<clientSecret>",
        "Roles": "api://<role>"
      },
}

The API is using the new call to get the parameters from the appsettings.json.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMicrosoftIdentityWebApiAuthentication(configuration);

The API is getting hit and validating the token:
Microsoft.IdentityModel.LoggingExtensions.IdentityLoggerAdapter: Information: IDX10239: Lifetime of the token is valid.
Microsoft.IdentityModel.LoggingExtensions.IdentityLoggerAdapter: Information: IDX10234: Audience Validated.Audience: '<audience>'
Microsoft.IdentityModel.LoggingExtensions.IdentityLoggerAdapter: Information: IDX10245: Creating claims identity from the validated token: '<claims>'.
Microsoft.IdentityModel.LoggingExtensions.IdentityLoggerAdapter: Information: IDX10241: Security token validated. token: <'token>' `

My client is getting back a 401 - Unauthorized with no other information.
Endpoints are getting hit with no authorization.
The controller never hits the Get in the route with authorization on.
The app registration has the API Permission set and has the admin consent.
I have been working with Microsoft on this and what seems like a straight forward authentication has us both stumped.

A: Turns out that the solution was the order in which the authorize and authenticate were in the startup. I had to change the order of these 2 lines in the startup and things started working. The following is the correct order.
app.UseAuthentication();
app.UseAuthorization();


text:
Q: How to return the derived type from the base type I have a base class, Sport, that has a property will return the proper type of object it should be for a given derived type (for example, Billiards extends Sport, and the property would return the BilliardBall type).
Is there a better way to do this  than having a large if statement in the Sport class (if this object is a Billiards instance then return BilliardBall, else if...)?

A: Why are you talking generics here? And why is Sport knowing about all the sports there are?
You can do something like below, for starters:
public interface IBall
{
}
public class BilliardBall : IBall
{
}
public abstract class Sport
{
    protected abstract IBall Ball { get; }

}
public class Billiards : Sport
{
    protected override IBall Ball
    {
        get { return new BilliardBall(); }
    }
}


text:
Q: EC2 instance connection refused: unprotected private key file I accidentally set 0775 permission for "/" while trying to fix permission problem for HADOOP and when I restarted my instance it says connection refused.
When I check system log (from instance settings) this message are among the last messages in the log.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0775 for '/etc/ssh/ssh_host_rsa_key' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
bad permissions: ignore key: /etc/ssh/ssh_host_rsa_key
Could not load host key: /etc/ssh/ssh_host_rsa_key

According to this http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesConnecting.html#d0e105559 and many other solution on the internet, I should run some command like
chmod 0400 .ssh/my_private_key.pem

but the problem is I can't access the instance, so I can't run that command from that instance.
Anyone has any idea about this problem?
Thank you!

A: There is only one way to do this.

*

*Stop the instance having bad permission.

*Detach the Root Volume (check the volume id).

*Launch a new Instance and attach the volume that you took out in Step 2.

*Mount the volume on the new Instance at any mount point /temp-perm.

*Save the changes and again detach the volume that you attach in Step 4.

*Re-attach the volume to your old Instance that you stopped in Step 1.


text:
Q: The performance of retrieve all columns and multiple columns I am learning SQL following "SQL in 10 minutes",
Reference to use wildcards to retrieve all the records, it states that:

As a rule, you are better off not using the * wildcard unless you really do need every column in the table. Even though use of wildcards may save you the time and effort needed to list the desired columns explicitly, retrieving unnecessary columns usually slows down the performance of your retrieval and your application.

However, It consume less time to retrieve all the records than to retrieve multiple fields:

As the result indicate, wildcards for 0.02 seconds V.S. 0.1 seconds
I tested several times, wildcards faster than multiple specified columns constantly, even though time consumed varied every times.

A: Kudos to you for attempting to validate advice you get in a book!  A single test neither invalidates the advice nor invalidates the test.  It is worthwhile to dive further.
The advice provided in SQL In 10 Minutes is sound advice -- and it explicitly states that the purpose related to performance.  (Another consideration is that that it makes the code unstable when the database changes.)  As a note:  I regularly use select t.* for ad-hoc queries.
Why are the results different?  There can be multiple reasons for this:

*

*Databases do not have deterministic performance, so other considerations -- such as other processes running on the machine or resource contention -- can affect the performance.

*As mentioned in a comment, caching can be the reason.  Specifically, running the first query may require loading the data from disk, and it is already in memory for the first.

*Another form of caching is for the execution plan, so perhaps the first execution plan is cached but not the second.

*You don't mention the database, but perhaps your database has a really, really slow compiler and compiling the first takes longer than the second.

Fundamentally, the advice is sound from a common-sense perspective.  Moving less data around should be more efficient.  That is really what the advice is saying.
In any case, the difference between 10 milliseconds and 2 milliseconds is very short.  I would not generalize this performance to larger data and say that the second is 5 times faster than the first in general.  For whatever reason, it is 8 milliseconds shorter on a very small data set, one so small that performance would not be a consideration anyway.

A: For manual testing the data that's in a table or tables?
Then it doesn't matter much whether you used a * or the column names.
Sure, if the table has like 100 columns and you only are interested in a few?   Then explicitly adding the columnnames will give you a less convulted result.
Plus, you can choose the order they appear in the result.
And using a * in a sub-query would drag all the fields into the resultset.
While if you only selected the columns you need could improve performance.
For manual testing, that normally doesn't matter much.
Whether a test SQL runs 1 seconds or 2 seconds, if it's a test or an ad-hoc query then it wouldn't bother you.
What the suggestion is more intended for, is about coding SQL's that are to be used in a production environment.
When using * in a SQL, that means that when something changes in the tables that are used in the query, that it can affect the output of that query.
Possibly leading to errors.  Your boss would frown upon that!
For example, a SQL with a select * from tableA union select * from tableB that you coded a year ago suddenly starts crashing because a column was added to tableB.  Ouch.
But by explicitly putting the column names, adding a column to 1 of the tables wouldn't make any difference to that SQL.
In other words.
In production, stability and performance matter much more than golf-coding.
Another thing to keep in mind is the effect of caching.
Some databases can temporarly store metadata or even data in memory.
Which can speed up the retrieval of a query that gets the same results of a query that just run before it.
So try running the following SQL's.
Which are in a different order than in the question.
And check if there's still a speed difference.
select * from products;
select prod_id, prod_name, prod_price from products;


text:
Q: Is there such a version as JPA 3? AFAIK, the latest and greatest that I have been using is JPA 2.0.
I am befuddled that GAE has a jar somewhat called appengine-java-sdk-1.6.5/lib/user/orm/geronimo-jpa_3.0_spec-1.1.1.jar. I have been having the impression that GAE always has a latency in adopting compatibility with latest, greatest bleeding edge protocols. It took them some time to adopt JPA 2.0.
What is that JPA 3.0 jar doing inside GAE SDK libs? Is there such a version as JPA 3.0? Is Google one-upping us this time by implementing a new version protocol ahead of everyone else? Is there a JPA 3.0 spec or reference impl somewhere I could refer to?
I am not (currently) an EJB person (sorry ... had decided to avoid EJB ever since I had bad experience with EJB 1.0 10 years ago).

*

*Is EJB 3.0 synonymous with JPA 2.0,

*or is JPA 2.0 adopted as a subset of EJB 3.0

*or is JPA 3.0 = EJB 3.0?

WRT this question I asked: moving from Hibernate entitymanager 3.6.9 to 4.1.2 crashed mysql connection,
Is Hibernate entity-manager 4.x somehow related to JPA 3.0 or at least a JPA version later than 2.0? I am experiencing significant differences between Hibernate entity-manager 3.x and 4.x (and have so far avoided deploying 4.x).
I realise this question is rather self-confusing and may be I should have asked each of the items as individual question, but I am hoping some one could tie all these together in a single thesis: ejb 3, JPA 2/3, geronimo, hibernate ent-mgr 3/4. Thanks.

A: No there is not such a thing (in June 2012) as JPA3. There is JPA1, JPA2, and (in planning) JPA2.1. That geronimo-specs jar is actually for JPA1 but some very shortsighted person/group decided to name it like that, and are now seeing the consequences of it.
As you say GAE already does support JPA2, using v2.x of their JPA plugin as available from Maven repositories or here http://code.google.com/p/datanucleus-appengine/  and that works with a compatible jpa-api v2 jar (such as geronimo-jpa_2.0_spec).

A: As others have said, JPA 2.0 is the current version (part of Java EE 6) and the next version is going to be JPA 2.1 which is currently in specification (JSR 338) and going to be included in Java EE 7. There is no JPA 3 as of yet, so that JAR is just badly named.
JPA 1.0 was introduced as part of Java EE 5, splitting the persistence part from the EJB specification (so Java EE 5 introduced EJB 3.0 and JPA 1.0, no more Entity Beans, yeah!). Java EE 6 then included EJB 3.1 and JPA 2.0.
Java EE 7 will include EJB 3.2 and JPA 2.1.

A: I am speaking under correction here as things might have changed since I last seriously worked with JPA. However JPA 2 from my understanding is the current specification. I doubt the jar you mentioned is a JPA 2 specification. In 2011 Geronimo did not support JPA 2 out of the box at that point.
As far as EJB's and JPA is concerned:

*

*Both EJB and JPA are based on POJO's (Plain Old Java Objects).

*JPA classes is essentially a data access layer technology i.e. used to interact with your data layer.

*EJB is essentially used for a business layer. It would contain business logic and orchestrate interaction between different JPA classes. For example in JPA you might have a Customer Class (which interacts with the Customer Table) and a Orders Class (which interacts with the Orders table). In your EJB you will use both these classes to create a new order for a particular customer.

When using JPA as a technology it allows you to keep your database access funtionallity in one layer. This layer could be used by EJB's, a web application(Servlets,JSP,JSF), web services and even a swing application. This will keep the database access logic consistent across all these applications. Changes to the database will then require a change to the JPA.
This is a very simplified explanation of the differences and this subject matter is really deep but these points should help you differentiate between the two.
By the way the new EJB specification really makes beans very easy to use, develop and deploy. I am lucky I missed the original specification all those years ago. Currently they are very easy to use.
Hope this helps clear up the mist a bit.


text:
Q: cannot resolve symbols in androidmanifest.xml while developing flutter application I am developing a flutter application, it is working fine. In order to publish the app to the play store, I have to make some changes in the manifest.xml file.
I want to change the icon and the label of the application. I changed the android:label to my label but it is not reflecting when I run the application.
I have specified the icon:  android:icon="@drawable/app_logo.png", but it says "Cannot resolve symbol 'drawable' "
Even the GradleException is working the same as drawable.
I tried answer like setting the SDK path in the project structure but it did not work.
Can someone help me with this please?

A: delete the ".png"
you should use
android:icon="@drawable/app_logo"
instead of
android:icon="@drawable/app_logo.png"


text:
Q: Retrieving values from ajax post object I have 6 JS objects that each contain three values.
question1 = {testNumber : 51, Answer : 2 , timeComplete : 05:00:00)
question2 = etc etc etc.
then I have one object to hold them all:
var allQuestions = {q1:question1, q2:question2, q3:question3, q4:question4, q5:question5, q6:question6};
I used ajax to send this object to my php page:
$.ajax({
 type: 'POST',

 url: allURL,

 data: {"questions" : JSON.stringify(allQuestions)},

 success: function( resp ){

    $('#allanswers').append( resp );

 },
 error: function( xhr, status, errorThrown ) {
    alert( "Sorry, there was a problem!" );
    console.log( "Error: " + errorThrown );
    console.log( "Status: " + status );
    console.dir( xhr );
},

});
now im trying to access these variables server-side:
What am I doing wrong? I realize it may be a nesting issue, but im confused on how to reference these objects/arrays now.

A: When you send a request to the server in php, you access that information through the $_REQUEST variable (http://php.net/manual/en/reserved.variables.request.php)
Try including this in your php code to see exactly what is getting sent to the server:
<?php print_r($_REQUEST); ?>

A: I wasnt able to use this answer. For some reason the array was not accessible. I ended up using regular form to form links. I have to read more on ajax/jquery/php.
Thank you Casey for your attempt.


text:
Q: How to change the columns of a datatable according to select menu? I am using JSF 2 and PrimeFaces 5 I have a data table whose cell need to be updated according to the selection from drop down menu.To be specific  I want to change the list(dataTable value) based on my selection(basically this means for every option dataTable will show different records)?
Is it possible to do so?

A: Yes, it's possible by just changing the model accordingly.
E.g. this:
<p:selectOneMenu value="#{bean.selectedItem}">
    <f:selectItems value="#{bean.availableItems}" />
    <p:ajax listener="#{bean.changeDataModel}" update="table" />
</p:selectOneMenu>

<p:dataTable id="table" value="#{bean.dataModel}">
    ...
</p:dataTable>

And in a @ViewScoped bean:
public void changeDataModel() {
    dataModel = someService.load(selectedItem);
}


text:
Q: Best way of setting a state with Redux and React Hooks Currently i implemented React Hooks with Redux. Now the only issue is that when changing the Redux state the performance is going down in my app e.g:
import { cardItemIsDragging, storeWidgetDrag } from '../../redux/actions';

then:
/** pass currentUser and currentChannel from redux to global props */
const mapStateToProps = state => ({
  storeWidget: state.storewidgetinfo.storeWidgetInfo,
  storeDrag: state.storewidgetdrag.storeWidgetDrag,
  storeDelete: state.storewidgetdelete.storeWidgetDelete,
});

and also having:
/** @component */
export default connect(mapStateToProps, {
  cardItemIsDragging,
  storeWidgetDrag,
})(Layout);

Now inside of this component there is a function that will update the Redux state:
  /** Calls when drag starts. */
  const onDragStart = () => {
    const { cardItemIsDragging } = props;
    cardItemIsDragging(true);
  };

Im updating this state because im also using it in another component.
The code above is resulting in a performance drop of the component/app, so my question is what is the best practice to setup Redux without losing performance / unnecessary re-rendering of the component, but keep changing state while it is needed in another component.


text:
Q: Render/ submit jsf form with conditionally chosen different input component types but submitting to same bean field Is it ok, in JSF, to render & submit a form with conditionally chosen different input components but all submitting to the same bean field like as shown below:
 (At any given time, only 1 type of input component is chosen)
            <h:form>
                <h:panelGroup rendered="..cond1..">
                    <p:inputText value="#{lobCr.text}"/>
                </h:panelGroup>
                <h:panelGroup rendered="..cond2..">
                    <p:inputTextarea value="#{lobCr.text}"/>
                </h:panelGroup>
                <h:panelGroup rendered="..cond3..">
                    <h:inputHidden value="#{lobCr.text}"/>
                </h:panelGroup>

                <p:commandButton value="Submit" actionListener="..." />
            </h:form>

I've tested this out & although this works fine as expected, I just fear of any unknown issues with this.

A: It is perfectly fine , your form will only submit the values for rendered component


text:
Q: change current TextArea value without assign a new one? When I press "A" to add a character to a value of the TextArea, how does the value change?
does the browser do something like this:
texarea.value+="A";
//same as:
texarea.value=texarea.value+"A";

?
I would like to change that value dynamicaly and notify the textarea about the change without assign a new one, because I think that assingment is not very perfomant if the value takes a lot of memory.
Is there a way to do this?

A: Ok, I solved it:
at first sight this solution seems also not very performant, but it has some big advatages:
for example you could load only a specific part of a very big file from server and dynamically load it if the user scroll through the page.
you can also update the client version of the file representation (synchronized editing)

document.registerElement('text-area', class NicePanel extends HTMLElement {
  createdCallback() {
    //this.root = this.createShadowRoot();
    this.tabIndex = 1;
    this.onkeydown = function(e) {
      this.monkeydown(e);
    }
    this.onkeypress = function(e) {
      this.monkeypress(e);
    }

    this.setValue(this.innerHTML);
  }
  setValue(value) {
    var mutablestring = Array.from(value);
    this.innerHTML = "";
    var l = mutablestring.length;
    for (var i = 0; i < l; i++) {
      if (mutablestring[i] == '\n') {
        var br = document.createElement('br');
        br.onclick = this.characterClick;
        this.appendChild(br);
      } else {
        var span = document.createElement('span');
        span.onclick = this.characterClick;
        span.innerHTML = mutablestring[i];
        this.appendChild(span);
      }
    }
    this.cursor = document.createElement('span');
    this.cursor.innerHTML = "|";
    this.appendChild(this.cursor);
  }
  getValue() {
    var value = "";
    var children = this.childNodes;
    var that = this;
    children.forEach(function(child) {
      if (child.nodeName == "BR") {
        value += "\n";
        return;
      }
      if (child === that.cursor) return;
      value += child.innerHTML;
    });

    return value;
  }

  attachedCallback() {}
  monkeydown(e) {
    var KeyID = event.keyCode;
    switch (KeyID) {
      case 8:
        this.cursor.parentNode.removeChild(this.cursor.previousSibling);

        e.preventDefault();
        break;
      case 46:
        this.cursor.parentNode.removeChild(this.cursor.nextSibling);
        e.preventDefault();
        break;

      case 13:
        var br = document.createElement('br');
        br.onclick = this.characterClick;
        this.cursor.before(br);
        e.preventDefault();
        break;
      case 37: //left
        this.cursor.parentNode.insertBefore(this.cursor, this.cursor.previousSibling);
        break;
      case 38: //up
        break;
      case 39: //right
        this.cursor.parentNode.insertBefore(this.cursor, this.cursor.nextSibling.nextSibling);
        break;
      case 40: //down
        break;
      default:
        break;
    }
  }
  characterClick(e) {
    this.parentNode.cursor.parentNode.insertBefore(this.parentNode.cursor, e.target);
  }
  monkeypress(e) {
    var span = document.createElement('span');
    span.onclick = this.characterClick;

    span.innerHTML = String.fromCharCode(e.which);
    this.cursor.parentNode.insertBefore(span, this.cursor);
  }
  monclick(e) {
    var target = e.target; // Clicked element
    while (target && target.parentNode !== this) {
      target = target.parentNode; // If the clicked element isn't a direct child
      if (!target) {
        return;
      } // If element doesn't exist
    }
    if (target.tagName === 'SPAN') {
      alert(target.id); // Check if the element is a LI
    }
  }
})
var myta = document.getElementById('myta');
myta.setValue("huhu\nlala");
console.log(myta.getValue());
text-area {
  width: 100%;
  background: #fff;
  display: block;
}
<text-area id="myta" class="text">Hello World

</text-area>


text:
Q: Reload all page when changing jQuery UI tab I'd like refresh all tab content when I change tab. Example, I have 3 tabs, when selected the second, I refresh the first and the third. Other solution reload the tab content when I just click on the tab.
Any idea ?
Thanks,
I catch the changing tab event, like this :
$("#tabs").bind('tabsselect', function (event, ui) {
   //ui.index is tab selected
});

HTML

Choice1

Choice2

Choice3

@Html.Partial("Choice1", Model)

@Html.Partial("Choice2", Model)

@Html.Partial("Choice3", Model)

A: Why should you use that?
Just use the load through ajax option located here: Load tab data through ajax
So you won't need to refresh tab 1 & 3, because they arent visible :). Just reload the data you want to see, it saves load on you page!
Btw I'm relating to this function in the UI Tabs Demo:
$(function() {
    $( "#tabs" ).tabs({
        ajaxOptions: {
            error: function( xhr, status, index, anchor ) {
                $( anchor.hash ).html(
                    "Couldn't load this tab. We'll try to fix this as soon as possible. " +
                    "If this wouldn't be a demo." );
            }
        }
    });
});

A: Your tabs will be having
 containing the name of the tabs displayed.

Tab1

Tab2

Also you will be having list of divs for the tabs

           Loading....

           Loading....

On Click of tab-1 if you want to reload the tab2,just load the tabs-2 div
$("#tab-1").livequery('click',function(event) {
              $("#tabs-2").load('url');
              });


text:
Q: transform oracle query to postgresql I am trying to pass a query from oracle to POSTGRESQL and it has not worked for me, how can I do it? the code is the following:
Oracle:
create function updateinsert
create cursor xx
select id
  from "CCRs"
  where status = 'POR REGULARIZAR'
    and id in (221424,188790);
begin
open cursor xx
loop

update ccrs
set status  ='ANULADO',
    isActive = false,
    cancelationDate = now(),
    updatedAt= now()
where id = xx.id;

INSERT INTO public.CCRHistories
(status, createdAt, updatedAt, ccrId, userId)
VALUES('ANULADO', now(), now(),xx.id , 2438);

end loop;
end;

A: No need for a LOOP or PL/pgSQL. This can be done with a single statement that uses a data modifying common table expression to copy the updated rows into the history table:
with updated as (
  update "CCRs"
  set status = 'ANULADO',
      isActive = false,
      cancelationDate = now(),
      updatedAt= now()
  where id = in (select id
                 from "CCRs"
                 where status = 'POR REGULARIZAR'
                 and id in (221424,188790))
  returning id, status
)
INSERT INTO public.CCRHistories (status, createdAt, updatedAt, ccrId, userId)
select status, now(), now(), upd.id, 2438
from updated upd;

If "CCRs".id is unique, you can get rid of the subquery
with updated as (
  update "CCRs"
  set status = 'ANULADO',
      isActive = false,
      cancelationDate = now(),
      updatedAt= now()
  where id in (221424,188790)
    and status = 'POR REGULARIZAR'
  returning id, status
)
INSERT INTO public.CCRHistories (status, createdAt, updatedAt, ccrId, userId)
select status, now(), now(), upd.id, 2438
from updated upd;

A: I think that would be everything:
DO $$
declare
        registro record;

cur_id cursor for select id
from
    "CCRs"
where
    status = 'POR REGULARIZAR' and id in (204);
 begin
    open cur_id;

fetch cur_id
into
    registro;

while (found) loop

    update
    "CCRs"
set
    status = 'ANULADO',
    isActive = false,
    cancelationDate = now(),
    updatedAt = now()
where
    id = registro.id;

insert
    into
    CCRHistories
(status,
    createdAt,
    updatedAt,
    ccrId,
    userId)
values('ANULADO',
now(),
now(),
registro.id,
2438);

fetch cur_id
into
    registro;
end loop;
end $$ LANGUAGE 'plpgsql';


text:
Q: Where to get name of signature algorithm from SSLSocket? I could not find a suitable way to get the name of the signature algorithm used for a certificate that is received by an SSLSocket. I'm aware you can pull the bytes of the peer's cert with SSLSocket.getpeercert(True) but I don't know what to do with it past that. PyOpenSSL doesn't seem to have an easy interface to load an X509 from it's byte content.
I would like to know this information as certificates with SHA1 are not allowed to have expiration times after January 1st, 2017 and this is not checked by Python's SSLSocket.do_handshake() implementation.

A: After the very helpful comment pointing me in the right direction, you can use the cryptography module to load the DER X509 format that the SSLSocket.getpeercert() function outputs.  From this Certificate instance you can also access many other fields about the certificate such as expiration time. Here is the way that I am doing it right now:
import cryptography.x509
import cryptography.hazmat.backends.openssl
import ssl
sock = ssl.SSLSocket()

# Wrap a socket, connect, handshake, etc etc...

cert = cryptography.x509.load_der_x509_certificate(
    sock.getpeercert(True),
    cryptography.hazmat.backends.openssl.backend
)
print(cert.signature_hash_algorithm.name) # This prints "sha1".


text:
Q: How to create separate columns for values in Database I have an SQL query that displays information from different tables in a database. One of the fields is called PieceType and this contains values like PLT, CASE, CTN etc. Each company could have a different number of PieceTypes e.g. company 4 could have just PLT, but company 5 could have 10 different types. I want to display these types in separate columns like:
Plt | CASE | CTN

My SQL query:
SELECT  c.Name,
        jp.PieceType
FROM customer c
LEFT JOIN job_new jn ON ja.JobID = jn.ID
LEFT JOIN job_pieces jp ON ja.JobID = jp.ID
WHERE c.Company_ID = compid
GROUP BY c.ID

Right now the query just displays one value from PieceTypes even though the company might have multiple piece types. I tried  GROUP_CONCAT(DISTINCT jp.PieceType) but that displays all the values in the same column. I need each piece to be in a separate column.
Sample Database can be found on sqlfiddle: http://www.sqlfiddle.com/#!9/c34306/3

A: What you could do is a select where you do a lookup of the property you want.
ie:
Select
name,
(select property from job_pieces where companyid = id and property = 'A') as A,
(select property from job_pieces where companyid = id and property = 'B') as B,
(select property from job_pieces where companyid = id and property = 'C') as C
 from company

A: I think you are looking for PIVOT TABLE. Hope this works :
SET group_concat_max_len=4294967294;
SET @COLUMNS = NULL;

/* Build columns to pivot */

SELECT GROUP_CONCAT(
        DISTINCT CONCAT(
            'CASE WHEN jp.PieceType = "',
            jp.PieceType ,
            '" THEN 1 ELSE NULL END AS ',
            jp.PieceType
        )
) INTO @COLUMNS
FROM job_pieces jp;

/* Build full query */
SET @SQL = CONCAT(
        'SELECT
                c.Name,
                ',@COLUMNS,'
        FROM customer c
        LEFT JOIN job_new jn ON ja.JobID = jn.ID
        LEFT JOIN job_pieces jp ON ja.JobID = jp.ID
        WHERE c.Company_ID = compid
        GROUP BY c.ID'
);

/* Prepare and execute the query*/
PREPARE stmt FROM @SQL;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;


text:
Q: Finding the limit of a trigonometric function I got it interms of e but couldn't find the limit of the power
$$\displaystyle \lim_{x \to \frac{\pi}{4}} {\sin 2x}^{\tan^2 2x}$$

A: As $x \to \pi/4$, the exponent goes to $+\infty$. So because $\pi/4<1$, you can do this problem without any sophisticated tricks: $x^{\tan^2(2x)} \to 0$ so the limit is $\sin(0)=0$.

A: Hint:
$$\exp(\log((\sin 2x)^{\tan^2 2x})=\exp(\tan^2 2x\log \sin 2x).$$
As $x\to \pi/4$, $\tan 2x =\sin 2x/\cos 2x\sim 1/\cos 2x$.
$$\lim_{x\to \pi/4} \cos2x = \lim_{y\to 0} \cos(\pi/2+2y)
= \lim_{y\to 0} -\sin^22y .$$
$$\lim_{x\to \pi/4} \sin2x -1 = \lim_{y\to 0} \sin(\pi/2+2y) -1
= \lim_{y\to 0} \cos 2y-1 =\lim_{y\to 0} -\sin^2y.$$
Since $\log (1+y)\sim y$ for $y\to 1$,
Then plug these approximations in the original expression inside $\exp$ to get
$$\lim_{x\to \pi/2}\tan^2 2x\log \sin 2x= \lim_{y\to 0} \frac1{\sin^4 2y}(-\sin^2y)=-\infty,$$
hence your original limit is $0$.

A: I do not know if you are allowed to use Taylor series; so forgive me if I am off-topic.
If I correctly read the problem, you are concerned by the behavior of $$A={\sin (2x)}^{\tan^2 (2x)}$$ So,$$\log(A)=\tan^2 (2x) \log\Big(\sin(2x)\Big)$$ Around $x=\frac{\pi}{4}$ we have $$\sin(2x)=1-2 \left(x-\frac{\pi }{4}\right)^2+\frac{2}{3} \left(x-\frac{\pi
   }{4}\right)^4+O\left(\left(x-\frac{\pi }{4}\right)^6\right)$$ Now, use the fact that, for small values of $y$, $$\log(1+y)=y-\frac{y^2}{2}+\frac{y^3}{3}+O\left(y^4\right)$$ and so $$\log\Big(1+\sin(2x)\Big)=-2 \left(x-\frac{\pi }{4}\right)^2-\frac{4}{3} \left(x-\frac{\pi
   }{4}\right)^4+O\left(\left(x-\frac{\pi }{4}\right)^6\right)$$ Now, and this is slightly more difficult, around $x=\frac{\pi}{4}$, an expansion of $\tan(2x)$ is given by $$\tan(2x)=-\frac{1}{2 \left(x-\frac{\pi }{4}\right)}+\frac{2}{3} \left(x-\frac{\pi
   }{4}\right)+O\left(\left(x-\frac{\pi }{4}\right)^3\right)$$ which then implies $$\tan^2(2x)=\frac{1}{4 \left(x-\frac{\pi }{4}\right)^2}-\frac{2}{3}+\frac{4}{15}
   \left(x-\frac{\pi }{4}\right)^2+O\left(\left(x-\frac{\pi }{4}\right)^3\right)$$ So, replacing and expanding leads to $$\log(A)=-\frac{1}{2}+\left(x-\frac{\pi }{4}\right)^2+O\left(\left(x-\frac{\pi
   }{4}\right)^3\right)$$ $$A=\frac{1}{\sqrt{e}}+\frac{\left(x-\frac{\pi
   }{4}\right)^2}{\sqrt{e}}+O\left(\left(x-\frac{\pi }{4}\right)^4\right)$$ If you plot the original function and this approximation on the same graph, you should be amazed to notice how close they are in the range $0 \leq x \leq \frac{\pi}{2}$.
Interesting or not, if you consider the function $$f(x)={\sin (2x)}^{\tan^2 (2x)}$$ after simplifications and factoring the first derivative write $$f'(x)=\tan (x) \sec ^2(x) {\sin (2x)}^{\tan^2 (2x)}\Big(\cos (2 x)+2 \log \big(\sin (2 x)\big)\Big)$$ and this cancels for $2x=\frac{\pi}{2}$; then the limit is finite.


text:
Q: Is there a way to determine the exact value of static friction in this situation?
Consider the following situation. Two blocks A and B connected by an inextensible string rest on a rough horizontal surface. The mass of A is 2kg and that of B is 3kg. The coefficient of static friction between block A and the surface is 0.1 and the coefficient of static friction between block B and the surface is 0.2
Two external forces of magnitudes 1N and 8N are now applied on A and B. The situation is shown in the figure below:

My goal is to find the tension in the string connecting the blocks and the friction acting on each block after the forces are applied.

First, I calculated the values of limiting friction corresponding to A and B, using (friction coefficient)*(normal contact force). For A it turns out to be 2N and for B 6N.
Now, considering the two blocks plus the string as a single system, the total external force is 8-1=7N rightwards and the maximum possible static friction is 6+2=8N leftwards. From this I concluded that the system cannot accelerate under the application of the given forces. Moreover, the sum of the static friction forces acting on A and B must be exactly 7N in order to balance out the external force.
To find the tension in the string, we need to find the individual magnitudes of the two friction forces. But I can't think of any reasonable way to obtain this using Newton's laws. I would like to know the right way to approach this problem.
The correct answer:

*

*Friction on block B is 6N leftwards.

*Friction on block A is 1N leftwards.

*Tension in the string is 2N, the system is in equilibrium.

From the solution, it seems that the friction on block B has been taken as the limiting(or maximum) value, 6N.
How did they arrive at this conclusion? Is there a way to explain this just using Newton's laws and motion constraints, or is some additional reasoning and extra conceptual insight required? Are these the ONLY possible values of friction forces? It seems like the forces could be anything as long as they add up to 7N and do not exceed their respective limiting values(although my gut feeling tells me that only one solution is possible for a practical situation such as this). The tension would then be decided accordingly, depending on the values of the friction forces (assuming that the breaking stress of the string is large enough, of course). In other words, Newton's laws predict an INFINITE number of solutions. What would be the most accurate and way of arriving at the answer to the question?
Final question: Is my way of concluding that the system does not accelerate correct? Or is there a more solid argument?

A: Such problems of indeterminate forces (eg Block on a block problem, with friction and Paradox in the two block problem) can be dealt with in 2 stages :
stage 1 : look at the system as a whole to determine whether it accelerates, and if so by how much
stage 2 : apply $F=ma$ to each part of the system individually.
Regarding the 2 blocks and string together as the system, the net applied force on it is 7N to the right. The maximum friction force is 8N (left or right). So the system does not accelerate. The net force on each block must be zero.
Applying the equilibrium conditions for each block we have
block A : $T-1 \le 2$ and $1-T \le 2$ giving $-1 \le T \le 3$
block B : $8-T \le 6$ and $T-8 \le 6$ giving $2 \le T \le 14$.
There is also a constraint for the string : $T \ge 0$.
Combining the inequalities, the only feasible solutions are in the interval
$2 \le T \le 3$.
I agree with Pirx : a unique solution does not exist. The answer given is not the only solution. If you think the IITJEE exam question proves otherwise, please upload the question and official solution.

A: The answer will indeed depend on the initial conditions. Here is how I think about this problem to arrive at the solution suggested to you: Very roughly, if you consider a situation with the rope slack at the beginning, then block B will start moving until the rope is tight. While the block is moving, the friction force on it will be equal to its weight times the kinetic friction coefficient for the moving surface (which in general will be lower than the limiting value for static friction). At some point the rope will tighten, and exert a force on Block B, retarding its motion and ultimately stopping it. The assumption seems to be that, at the point when block B stops, the friction force returns to the limiting value of static friction. Sounds reasonable to me, but reality might be more complex than this.


text:
Q: HTML5 Video bounce when scrolling I've noticed that when I embed a video into a webpage with the <video> tag, upon scrolling up and down, the video bounces vertically up and down in the browser.  Is there a way to disable this behavior?

A: With a few list of options on the page, try removing the background-position: fixed for the container div and to ancestors.

A: I'm not sure if this works, but try putting a CSS property of position: absolute; to it. I am pretty sure it is something to do with the browser not any of your coding.

A: I had this problem with an embedded webkit browser, I solved it using position: absolute; for the video tag, and by placing the data that needed to scroll, inside a scrollable div.

A: I have noticed this with certain videos and have solved it with:
video { vertical-align: baseline }