text:
Q: How to fetch api via looped callbacks with React functional components So I have a 40+ loop that's calling another component to display images. Each image has an ID and with that ID I can get more information about the image like Name and description via another API call.
When DisplayImage gets called I want it to call another callback function that will send out API calls for that image's metadata, store it in a variable and display it as an H1 tag.
return (

  {array.map(index) => {

   // Some Other Code That return a TokenID //

   <>
    {displayImage(tokenId)}
   </>

})

 const displayImage = (tokenId) => {

  const imageName = GetURI(tokenId)

  return (

{imageName}

        <img className="artwork" width="250px" src={`https://ipfs-asdf/${tokenId}`} />

  )

 }

const GetURI = async (tokenId) => {

    const res = await fetch("https://api"+tokenId , {
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
    }).then(data => {
      console.log(data)
      return data.json();
    })
    .then(data => {
      return (data.name || [])
    })
    .catch(err => {
      console.log(err);
    });
}

The data is being displayed on the console but now I'm running into an infinite loop issue that I know UseEffect can solve but I can't quite figure it out. I managed to display the data on the console with UseEffect using the [] attribute but don't know how to display the data. Any help would be amazing. Thank you!

A: Two things useful to your situation

*

*functions declared outside the component aren't recreated each render

*useState and useEffect pairing limits calls to API to only when tokenId changes
// Put this function outside the component
// so it does not need a useCallback
// i.e not reconstructed each render of DisplayImage

const GetURI = async (tokenId) => {
  ...
});

const DisplayImage = (tokenId) => {

  const [imageName, setImageName] = useState()

  // limit calls to API to when tokenId changes
  // and if eslint complains add GetURI to dependency list
  // - but GetURI never changes, so no un-needed calls from it
  useEffect(() => {
    setImageName(GetURI(tokenId))
  }, [tokenId, GetURI])

  return (

{imageName}

      <img className="artwork" width="250px" src={`https://ipfs-asdf/${tokenId}`} />

  )
};

You can also abstract to custom hook useImageName()
const GetURI = async (tokenId) => {
  ...
});

const useImageName = (tokenId) => {

  const [imageName, setImageName] = useState()

  useEffect(() => {
    setImageName(GetURI(tokenId))
  }, [tokenId, GetURI])

  return imageName
})

const DisplayImage = (tokenId) => {

  const imageName = useImageName(tokenId)

  return (

{imageName}

      <img className="artwork" width="250px" src={`https://ipfs-asdf/${tokenId}`} />

  )
};

BTW in GetURI this
return (data.name || [])

looks like should be
return data.name || ''

A: Is a different approach ok? I'd put display image into its own component.
const DisplayImage = ({tokenId: {_tokenId}}) => {

  const imageName = GetURI(_tokenId)

  const GetURI = useCallback(async () => {
      await fetch("https://api"+tokenId , {
            headers: {
              'Content-Type': 'application/json',
              'Accept': 'application/json'
            },
        }).then(data => {
          console.log(data)
          return data.json();
        })
        .then(data => {
          return (data.name || [])
        })
        .catch(err => {
          console.log(err);
        });
      })
    });

    useEffect(() => {
      if (_tokenId) GetURI();
    }, [GetURI]);

  return (

{imageName}

        <img className="artwork" width="250px" src={`https://ipfs-asdf/${_tokenId}`} />

  )
};

and then
return (

  {array.map(index) => {

   //Some Other Code//

   <DisplayImage tokenId={tokenId} />

})

A: You should probably cache the response from GetURI(tokenId). No need to ask twice for the same URI when using the same tokenId.
An easy way is using react-query:
Setup in App.js:
 // App.js
 import { QueryClient, QueryClientProvider } from 'react-query'

 const queryClient = new QueryClient()

 export default function App() {
   return (
     <QueryClientProvider client={queryClient}>
       <Example />
     </QueryClientProvider>
   )
 }

Then use in a DisplayImage component (instead of inline function):
// DisplayImage.js
import { useQuery } from 'react-query'

export function DisplayImage(tokenId) {
  const { isLoading, error, data: imageName } = useQuery(['images', tokenId], GetURI(tokenId))
  return (

{isLoading ? 'loading...' : imageName}

      <img className="artwork" width="250px" src={`https://ipfs-asdf/${tokenId}`} />

  )
}

A: I found the best way to go about it with everyones help on here so thanks!
I put the GetURI function inside the show image component, and had a useEffect method call GetURI every time there was a new token ID, then I set a state variable to whatever was returned.
No loops, no errors

const DisplayImage = (data) => {

  const [nftMetadata, setNftMetadata] = useState();

  const GetURI = async (data) => {
     const nftURI = await data.drizzle.contracts.Contract.methods.tokenURI(data.tokenId).call()

      await fetch(nftURI , {
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          "Access-Control-Allow-Origin": "*"
        },
        })
        .then(data => {
          return data.json();
        })
        .then(data => {
          return setNftMetadata(data || []);
        })
        .catch(err => {
          return console.log(err);
      });
  });

  useEffect(() => {
    GetURI(data);
  }, [data.tokenId])

  return (

{nftMetadata.name}

     <img className="artwork" width="450px" src={`https://ipfs:/whatever/${nftMetadata.image}`} />

  );

};

return (

  {array.map(index) => {

   // Some Other Code That returns a TokenID //

   <>
    <DisplayImage address={drizzle.contractList[0].address} tokenId={tokenId} drizzle={drizzle} drizzleState={drizzleState}/>
   </>

})


text:
Q: Matching data in two columns I have an excel sheet with a series of last and first names in columns B and C.  I'm trying to match names to those in a second sheet in columns A and B.  Not every name will match and first or last names might be duplicate but assume never both.  I've tried this
=IF((MATCH(B3,Sheet1!$A$1:$A$150,0)*MATCH(C3,Sheet1!B1,0))>1,1,0)
It kind of work but there is nothing stopping excel from matching the last name and then going to a separate line entry to find the first name.
Can somebody please show me how to make excel only search the same row for the last name as it found the first?

A: I'm not sure if I'm clear about the thing you try to do, but I've two suggestions:

*

*Is this the way you want it to work?
=IF((MATCH(B3,Sheet1!A:A,0))*AND(MATCH(C3,Sheet1!B:B,0))>1,1,0)

*What if you make third column in each sheet, using:
=CONCATENATE("CELL WITH A FIRST NAME", " ", "CELL WITH A LAST NAME")
stretched down to the whole data. Then you can do your match between this 2 columns.

A: With first names in column A, last names in column B on sheet 1, and first name in B3, last name in C3 on current sheet:
=match(B3&C3,index(Sheet1!$A$1:$A$150&Sheet1!$B$1:$B$150,0),0)

Formula in D3 returns the position of the found match:

Don't use with whole column references. It will be slow to recalculate.

redpajama_set_name: RedPajamaStackExchange


text:
Q: getting a list of kernel objects windows
*

*HI!

I bet more than a week and I can not form a complete picture of how you can get a list of kernel objects .My algorithm is as follows :

*

*1) Connecting NTDLL.dll (LoadLibrary)

*2) GetProcAddress (variable_Library_name, "NtQueryDirectoryObject")
and the pre-announcement structures : _OBJDIR_INFORMATION,
_OBJECT_ATTRIBUTES

*3) Trying to apply a function NtOpenDirectoryObject for a list of
objects

Here is a piece of code that is responsible for the use of the function NtOpenDirectoryObject:
 OBJDIR_INFORMATION *ssinfo  =(OBJDIR_INFORMATION* ) HeapAlloc(GetProcessHeap(), 0, 0x800);
           ///////////////////////
                    HANDLE hFile,hThread,hMapFile;
  HMODULE hNtdll ,hKernel;
  DWORD dwThreadId;
  OBJECT_ATTRIBUTES obj;
  WCHAR  * uString=L"\\BaseNamedObjects";
  UNICODE_STRING str;
  DWORD i,a,iStrLen,b=0;
  char sObjName[30],sTmp[50];
  LPVOID lpMapAddress;
  FARPROC pWinExec,pExitThread;
  bool bFound;
  char* sCommand;
            /////////////////////////////////////////////////////////////////
            NtQueryDirectoryObject = (NTQUERYDIRECTORYOBJECT )GetProcAddress(hinstLib,"NtQueryDirectoryObject");
            InitializeObjectAttributes (&obj, &str, 0, 0, 00);
            NtOpenDirectoryObject(&hFile,0x20001,&obj);

The full code (including struct definitions) is at: http://pastebin.com/pDNb3GTn
When calling a function with parameters NtOpenDirectoryObject get an exception c0000005, which means that access is blocked .
tell me please, am I doing smth wrong, and where is my mistake. Is it possible to not to use the native api? Thank you for your help

A: Exception c0000005 is an Access Violation.   That does not mean that access was blocked. It means invalid memory was accessed, such as if a NULL/uninitialized pointer were accessed, or if you are not aligning data correctly and accessing something out of bounds of what you have allocated.
As Andrew mentioned, you are not initializing the UNICODE_STRING at all.  Try this instead:
hNtdll = LoadLibrary("ntdll.dll");
NtOpenDirectoryObject = (NTOPENDIRECTORYOBJECT) GetProcAddress(hNtdll, "NtOpenDirectoryObject");
...
if (NtOpenDirectoryObject)
{
    // add these three lines
    str.Length = lstrlenW(uString) * sizeof(WCHAR);
    str.MaximumLength = str.Length;
    str.Buffer = uString;

    InitializeObjectAttributes (&obj, &str, 0, NULL, NULL);
    NtOpenDirectoryObject(&hFile, 0x20001, &obj);
}


text:
Q: Regex to get value within tag I have a sample set of XML returned back:
<rsp stat="ok">
  <site>
    <id>1234</id>
    <name>testAddress</name>
    <hostname>anotherName</hostname>
    ...

  </site>
  <site>
    <id>56789</id>
    <name>ba</name>
    <hostname>alphatest</hostname>
    ...
  </site>
</rsp>

I want to extract everything within <name></name> but not the tags themselves, and to have that only for the first instance (or based on some other test select which item).
Is this possible with regex?

A: <disclaimer>I don't use Objective-C</disclaimer>
You should be using an XML parser, not regexes. XML is not a regular language, hence not easely parseable by a regular expression. Don't do it.

Never use regular expressions or basic string parsing to process XML. Every language in common usage right now has perfectly good XML support. XML is a deceptively complex standard and it's unlikely your code will be correct in the sense that it will properly parse all well-formed XML input, and even it if does, you're wasting your time because (as just mentioned) every language in common usage has XML support. It is unprofessional to use regular expressions to parse XML.

You could use Expat, with has Objective C bindings.

Apple's options are:

*

*The CF xml parser

*The tree based Cocoa parser (10.4 only)

A: Without knowing your language or environment, here are some perl expressions.  Hopefully it will give you the right idea for your application.
Your regular expression to capture the text content of a tag would look something like this:
m/>([^<]*)</

This will capture the content in each tag.  You will have to loop on the match to extract all content.  Note that this does not account for self-terminated tags.  You would need a regex engine with negative lookbehinds to accomplish that.  Without knowing your environment, it's hard to say if it would be supported.
You could also just strip all tags from your source using something like:
s/<[^>]*>//g

Also depending on your environment, if you can use an XML-parsing library, it will make your life much easier.  After all, by taking the regex approach, you lose everything that XML really offers you (structured data, context awareness, etc).

A: As others say, you should really be using NSXMLParser for this sort of thing.
HOWEVER, if you only need to extract the stuff in the name tags, then RegexKitLite can do it quite easily:
NSString * xmlString = ...;
NSArray * captures = [xmlString arrayOfCaptureComponentsMatchedByRegex:@"<name>(.*?)</name>"];
for (NSArray * captureGroup in captures) {
  NSLog(@"Name: %@", [captureGroup objectAtIndex:1];
}

A: The best tool for this kind of task is XPath.
NSURL *rspURL = [NSURL fileURLWithPath:[@"~/rsp.xml" stringByExpandingTildeInPath]];
NSXMLDocument *document = [[[NSXMLDocument alloc] initWithContentsOfURL:rspURL options:NSXMLNodeOptionsNone error:NULL] autorelease];

NSArray *nodes = [document nodesForXPath:@"/rsp/site[1]/name" error:NULL];
NSString *name = [nodes count] > 0 ? [[nodes objectAtIndex:0] stringValue] : nil;

If you want the name of the site which has id 56789, use this XPath: /rsp/site[id='56789']/name instead. I suggest you read W3Schools XPath tutorial for a quick overview of the XPath syntax.

A: Careful about namespaces:
<prefix:name xmlns:prefix="">testAddress</prefix:name>

is equivalent XML that will break regexp based code. For XML, use an XML parser. XPath is your friend for things like this. The XPath code below will return a sequence of strings with the info you want:
./rsp/site/name/text()

Cocoa has NSXML support for XPath.


text:
Q: Cannot run paramiko-expect on windows I get following error when ran on windows -
Traceback (most recent call last):
  File "demo2.py", line 5, in <module>
    from paramikoe import SSHClientInteraction
  File "C:\Python27\lib\site-packages\paramikoe.py", line 17, in <module>
    import termios
ImportError: No module named termios

When I searched about it, some articles said it required UNIX like environment, and workaround can be to run using Cygwin.
I installed Cygwin, but still can't run the script.
I'm new to python, can anybody help me with this? How can I make paramiko-expect work on windows?


text:
Q: Dict Index's in BeautifulSoup and "if x in Dict" I don't think I understand how to check if an array index exists...
for tag in soup.findAll("input"):
            print tag['type']
            if 'type' in tag:
                print "b"

Outputs:
2255
text
hidden
text
text
text
Traceback (most recent call last):
  File "/home//workspace//src/x.py", line 268, in <module>
    print tag['type']
  File "/home//workspace//src/BeautifulSoup.py", line 601, in __getitem__
    return self._getAttrMap()[key]
KeyError: 'type'

Why is it not outputting 'b' ever?

A: A BeautifulSoup Tag is not a dict. Sometimes it acts like one in certain ways ([] notation as you discovered gets the value of an attribute), but in other ways it doesn't. in on a Tag will check if a tag is a direct child of that tag; it does not check attributes.
Instead, you could do something like this:
if not tag.get('type', None):
    pass # type is empty or nonexistent

A:
Why is it not outputting 'b' ever?

You're assuming that the tags returned from findAll are dicts, when in fact they're not. The BeautifulSoup library that you're using has its own custom classes, in this case BeautifulSoup.Tag, which may work a lot like a dict, but isn't.
Here, check this out:

    >>> doc = ['<title>Page title</title>',
    ...        '
This is paragraph one.',
    ...        '
This is paragraph two.',
    ...        '']
    >>> soup = BeautifulSoup(''.join(doc))
    >>> tag = soup.findAll("p")[0]
    >>> type(tag)
    class 'BeautifulSoup.Tag'>
    >>> isinstance(tag, dict)
    False

Since it's not actually a dict, you're getting some different (domain-specific) behavior, in this case a list of immediate children (tags immediately contained within the tag you're "indexing").
It looks like you want to know if the input tag has an attribute type, so according to the BeautifulSoup documentation you can list the attributes of a tag using tag.attrs and attrMap.

    >>> tag.attrs
    [(u'id', u'firstpara'), (u'align', u'center')]
    >>> tag.attrMap
    {u'align': u'center', u'id': u'firstpara'}
    >>> 'id' in tag.attrMap
    True

BeautifulSoup is a really helpful library, but it's one that you have to play with a bit to get the results you want. Make sure to spend time in the interactive console playing with the classes, and remember to use the help(someobject) syntax to see what you're playing with and what methods it has.


text:
Q: In Apple OS X's Calendar app, how to trigger an alert at the end of the event? If the event is one hour long, you can have the alert start one hour after the event. However, if you then change the event to be two hours long, the alert will then occur in the middle of the event unless you also edit the timing of the alert.
Another way to accomplish this is to have another event right after the first event, and have the alert go off at the start of the second event. However, each time you change the time of the first event, you'll also need to change the time of the second.
What I am looking for is a way to have the trigger time be the end of the event, even if you subsequently change the duration of the event, without any additional steps. Does anyone know of a way to accomplish this?


text:
Q: Updating internal fieldname not getting reflected Here's my scenario : Created a content type hub and programmatically created a custom content type and added a custom field in it. Solution got deployed successfully.
<Elements xmlns="http://schemas.microsoft.com/sharepoint">
<ContentType ID="0x010008F15D6B2D0A454BA95AA5D91E21416E"
             Name="MyCustomContentType"
             Group="JL"
             Description="This is my custom content type">
<FieldRefs>
     <FieldRef ID="{4e6a1cad-d0e4-4ce2-9086-8664cbb6ef73}" Name="CustomChoice" />
</FieldRefs>
</ContentType>
<Field ID="{4e6a1cad-d0e4-4ce2-9086-8664cbb6ef73}"
       Name="CustomChoice"
       DisplayName="Custom Choice Column"
       Type="Choice"
       StaticName="CustomChoice"
       DisplaceOnUpgrade="TRUE"
       Group="JL">
<CHOICES>
        <CHOICE>Choice 1</CHOICE>
        <CHOICE>Choice 2</CHOICE>
</CHOICES>
</Field>
</Elements>

However, i had to change the internal name of the field. So when i modified the internal name of the field in the schema and deployed the solution, the column in content type hub modified. But if i create a new site collection subscribing the content type hub it still refers the old internal value.
Here's my modification
<Field ID="{4e6a1cad-d0e4-4ce2-9086-8664cbb6ef73}"
       Name="CustomChoice_01"
       DisplayName="Custom Choice Column"
       Type="Choice"


text:
Q: Magento Product Image Moved to the righte Can someone help me in figuring out why all of the sudden the image file for my product moved to the right and disrupted the layout.  I have been through many of the files and i cannot figure out what happened.  Very confused
http://www.shadecontrol.com/index.php/view-by-shape/quick-order-classic/jmc0908as48.html

A: Your current html/css is

...

...

 .col1-layout .product-view .product-shop {
    float: left;
    width: 360px;
 }

 .product-view .product-img-box {
    float: left;
    width: 256px;
 }

Because both div are floating left you will have the product detail before the product image.
You could either change the css to
 .col1-layout .product-view .product-shop {
    float: right;
    width: 360px;
 }

or change the order of the divs within  /app/design/frontend/default/[theme]/template/catalog/product/view.phtml

...

...


text:
Q: I've just started python and I'm trying to make a Rock ,Paper ,Scissors game and I can't work out how to change the font and its size Here is my code if anyone can help then that would be greatly apricated.
import random

a = ["rock", "paper", "scissors"]

def game():
    while True:
        try:
            word = input('Enter rock, paper, or scissors: ')
            if word not in a:
                raise ValueError # this will send it to the print message and back to the input option
            break

        except ValueError:
            print(" You must enter rock, paper, or scissors.")

    comp_draw = random.choice(a)
    print('The computer drew ' + comp_draw)

    if comp_draw == 'rock' and word =='rock':
        print('It was a tie')
    elif comp_draw == 'paper' and word =='paper':
        print('It was a tie')
    elif comp_draw == 'scissors' and word =='scissors':
        print('It was a tie')
    elif comp_draw == 'paper' and word =='rock':
        print('GAME OVER')
    elif comp_draw == 'rock' and word =='paper':
        print('you won!')
    elif comp_draw == 'rock' and word =='scissors':
        print('GAME OVER')
    elif comp_draw == 'scissors' and word =='rock':
        print('you won!')
    elif comp_draw == 'scissors' and word =='paper':
        print('GAME OVER')
    elif comp_draw == 'scissors' and word =='rock':
        print('you won!')

if __name__ == "__main__":
    game()
    while True:
        if input('Would you like to play_again? ') == 'yes':
            game()
        else:
          break

      font = 'Arial (sans-serif)' : 'normal'
        'weight' : 'bold',
        'size'   : 99}

This is how I've tried to change the font
font = 'Arial (sans-serif)' : 'normal'
        'weight' : 'bold',
        'size'   : 99}

This is the error message I've received
IndentationError: unindent does not match any outer indentation level on line 48 font = 'Arial (sans-serif)' : 'normal' ^ in main.py

A: For the code to work, you need to unindent font, add a comma after 'normal' and add an opening brace:
if __name__ == "__main__":
    game()
    while True:
        if input('Would you like to play_again? ') == 'yes':
            game()
        else:
          break

font = {'Arial (sans-serif)' : 'normal' ,
       'weight' : 'bold',
       'size'   : 99}

However, you are not using the font variable so it won't change anything. As has been mentioned, if you are printing to the terminal you can't change the font in python.

A: Unfortunately, there isn't an easy way for changing the printed font and it's size through Python.
You can try changing the console font and size using the shell's api, but this is very platform specific and isn't easy to set up.
What you can do, is use a simple graphics library like pygame, where you can output graphics from your python application. You can check out this docs to learn how to use fonts in pygame.


text:
Q: JAXB won't unmarshal my previously marshalled interface impls Here is my working marshalling code:
For starters I have an Entity class with something like the following:
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public final class Entity implements {
    private Map<String, Component> components = new HashMap<String, Component>();

    @XmlElementWrapper(name="components")
    @XmlAnyElement
    public List<Component> getComponentList() {
        return new ArrayList<Component>(components.values());
    }

    public void setComponentList(List<Component> comps) {
        for(Component c : comps) {
            components.put(c.getComponentType(), c);
        }
    }

    ...
}

Component is a very varied interface but all implementations are nice and round beans carefully annotated.
Now, marshalling produces some good looking XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<entity>
    <components>
       <containerComponent>
           <children>
               <entity>
                   <components>
                       <containerComponent>
                           <children>
                        <entity>
                            <components>
                               <directionComponent>
                                  <direction x="0.0" y="1.0"/>
                               </directionComponent>
                               <sizeComponent>
                                  <size x="52.0" y="12.0"/>
                               </sizeComponent>
                               ...

As you can see, each component type has its very own tag name but that doesn't seem to be enough for JAXB because
Exception in thread "main" java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.ElementNSImpl cannot be cast to tobacco.core.components.Component
    at tobacco.core.components.Entity.setComponentList(Entity.java:121)
    at tobacco.core.components.Entity$JaxbAccessorM_getComponentList_setComponentList_java_util_List.set(Unknown Source)
    at com.sun.xml.internal.bind.v2.runtime.reflect.Lister$CollectionLister.endPacking(Unknown Source)
    at com.sun.xml.internal.bind.v2.runtime.reflect.Lister$CollectionLister.endPacking(Unknown Source)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Scope.finish(Unknown Source)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.endScope(Unknown Source)
    at com.sun.xml.internal.bind.v2.runtime.property.ArrayERProperty$ItemsLoader.leaveElement(Unknown Source)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.endElement(Unknown Source)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.SAXConnector.endElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.endElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanEndElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(Unknown Source)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(Unknown Source)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(Unknown Source)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(Unknown Source)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(Unknown Source)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(Unknown Source)
    at tobacco.core.serialization.XmlEntityConverter.toEntity(XmlEntityConverter.java:32)
    at tobacco.core.loader.XmlLoader.loadEntityTree(XmlLoader.java:43)
    at tobacco.game.test.main.Main.main(Main.java:75)

At the other end of the process I receive ElementNSImpl objects.
I though about using an ObjectFactory but after reading and testing I'm almost convinced it's no use: I couldn't find a way to access tag name on the creator method, and even if I could I'm not so sure JAXB would just accept my object and fill its properties happily or if I would have to fill them myself, which absolutely impractical.
I think this guy had the same problem. Does it work out of the box with MOXy? Is there a way to do this without switching implementations?

A: You can use @XmlElements annotation instead of @XmlAnyElement and list all possible subclasses like in example:
@XmlElementWrapper(name = "components")
@XmlElements(
   {
      @XmlElement(name = "directionComponent", type = DirectionComponent.class),
      @XmlElement(name = "sizeComponent", type = SizeComponent.class),
   })
public List<Component> getComponentList()
{
    return new ArrayList<Component>(components.values());
}

Also, in this case you don't need to use @XmlRootElement annotation on DirectionComponent and  SizeComponent classes.
PS. Also, now you can use List of components instead of Map
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public final class Entity
{
    private List<Component> components = new ArrayList<Component>();

    @XmlElementWrapper(name = "components")
    @XmlElements(
       {
          @XmlElement(name = "directionComponent", type = DirectionComponent.class),
          @XmlElement(name = "sizeComponent", type = SizeComponent.class),
       })
    public List<Component> getComponentList()
    {
        return components;
    }

    public void setComponentList(List<Component> comps)
    {
         this.components = comps;
    }
    //...
}


text:
Q: Disable jQuery UI Tooltips except for certain elements I'm looking for the inverse of what's being done here. I would like to disable the tooltips except in certain situations.
Here's the code I'm using now, just not sure what/where to add a disable:
$(function() {
$( document ).tooltip({
  position: {
    my: "center bottom-20",
    at: "center top",
    using: function( position, feedback ) {
      $( this ).css( position );
      $( "<div>" )
        .addClass( "arrow" )
        .addClass( feedback.vertical )
        .addClass( feedback.horizontal )
        .appendTo( this );
    }
  }
});

});

A: Just use a specific selector instead of document
$(function () {
    $("a.has-tooltip, p").tooltip({
        position: {
            my: "center bottom-20",
            at: "center top",
            using: function (position, feedback) {
                $(this).css(position);
                $("<div>")
                    .addClass("arrow")
                    .addClass(feedback.vertical)
                    .addClass(feedback.horizontal)
                    .appendTo(this);
            }
        }
    });
});

Demo: JSFiddle


text:
Q: Parse XML to JSON or JavaScript object I am receiving xml data from an api, check this link https://developers.cj.com/docs/rest-apis/advertiser-lookup
I need to parse xml to json or js object in order to use it properly.
I've tried xml2js, it converts stuff in the following way.
<?xml version="1.0" encoding="UTF-8"?>
<cj-api><error-message>  You must provide an Authorization header.</error-message></cj-api>

{
  'cj-api': { 'error-message': [ 'You must provide an Authorization header.' ] }
}

In this case I dont need the array, just the simple value.
Is there a working parser that I can use?

A: you can use camaro like this
const { transform } = require('camaro')

async function main() {
    const xml = `
<?xml version="1.0" encoding="UTF-8"?>
<cj-api><error-message>  You must provide an Authorization header.</error-message></cj-api>

`

    const template = {
        errorMessage: '/cj-api/error-message'
    }
    const output = await transform(xml, template)
    console.log(output.message);
}

main()

output
  You must provide an Authorization header.


text:
Q: Assigning a class in a .erb clause, "syntax error, unexpected tASSOC, expecting tCOLON2" All, I'm getting the following syntax error when trying to assign a class in an erb file:
SyntaxError in Posts#index

Showing [..]/app/views/posts/_post.html.erb where line #5 raised:

[..]/app/views/posts/_post.html.erb:5: syntax error, unexpected tASSOC, expecting tCOLON2 or '[' or '.'
...append= ( post.title, :class => 'my-custom-class' );@output_...
...

                      ^
3:
4:

5:       <%= post.title, :class => 'my-custom-class' %>
6:

7:

I could add the class into the
 - namely
 ..
, but is there not a more elegant way, without the div, embedding the class assignment in the erb clause?
Ideas here?

A: <%= content_tag, :div, post.title, :class => 'my-custom-class' %>

http://api.rubyonrails.org/classes/ActionView/Helpers/TagHelper.html#method-i-content_tag


text:
Q: How to convert html page to pdf and breaking the content with header in each pdf page? I am using css to break the content as required to be printed in fresh pdf page, I want to include the header/footer on each pdf page, I tried with fixed css/ along with margin but that works for first page not the successive page.  The footer is getting overlapped with page content..
mypage.php
<?php //call_db
//call_func
 ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>My Print Page</title>

//call sql query for content // A collection of 200 lists

 THE GAME OF THORNES

Sean's CSS Print vs. Screen Example

Lesson 1

This is my first Page in the document.

Lesson 2

Examples and theory of lesson2

Lesson 3

Examples and theory of lesson2

UNCLASSIFIED

** I am adding PHP tag as if you have any other better way to print the content from db, please suggest.

A: I think this is duplicate of this Convert HTML + CSS to PDF with PHP? ,
you must use your pdf convertor library to add header and footer to pdf.
I'm used http://www.tcpdf.org/ in my project. you can use it too.


text:
Q: Facebook sharer not working correctly I'm trying to set up facebook sharing.  But i'm having problem getting any information to show other than the link.
This is the rendered head:

    <meta charset='utf-8'>
    <meta content='prettySocial - custom social share buttons.' property='og:title'>
    <meta content='http://sonnyt.com/prettySocial/' property='og:url'>
    <meta content='http://sonnyt.com/assets/imgs/prettySocial.png' property='og:image'>
    <meta content='Custom share buttons for Pinterest, Twitter, Facebook and Google Plus.' property='og:description'>

This is where the button is clicked

and an image of what I see

But the link is set to the correct path. "http://mysite-staging.dev/orders/1"


text:
Q: Access list box items added on client side
*

*I have a listbox with runat=server

*Items are added to this listbox on the client side, using javascript

*I would want to retrieve the items on the server side on the click of a button

The problem is in the Buttons's server side click handler, I cannot see the new items added to the listbox. Only the items that were there on page_load are displayed. How do i accomplish what i want to do
Edit 1
My Code Is like this
 protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            if (ViewState["gameID"] == null)
            {
                //Populate Listbox
                //Set gameid in viewstate
            }

            //Add javascript handlers to buttons
            btnSomeButton.Attributes.Add("onclick", "aJavaScriptFunction");

        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        ListItemCollection x = ListBoxRanks.Items;
        //Here items is has just those items that are added to the listbox on page load

    }

A: Ah when abstractions leek :)
Web server controls are serialised to view state before the response is sent, the control is recreated on postback and the options all put back from view state.
When you add option items client side they are not added to viewstate. The only way is to use your own hidden field to serialise client side additions and read them on postback or ajax the additions serverside.

A: Only bind to the ListBox if Page.IsPostBack is false.  This will allow you to see any items added on the client side.
If you are binding to the control on each load you are wiping out any existing items that were loaded by ASP.NET from the request.  By only binding if the current page load was not triggered by a postback you are allowing all the items from the request to load, including any items added client-side.

A: You should use ajax to add items to the dropdown list. It will ensure your viewstate is in sync with the serverside dropdown control.


text:
Q: is there a way to make the GUI stay ontop of fullscreen games? The title question, simple, is there a way to keep my GUI on top of full screen games?
I managed to do it while the games are borderless but I feel that could be done more.

A: You can use option keep_on_top=True in sg.Window, and method window.maximize() to maixmize window.
import PySimpleGUI as sg

sg.theme('DarkBlue')
sg.set_options(font=('Courier New', 32))
layout = [
    [sg.Text('Bordless, maxmize and keep-on-top window')]
]
window = sg.Window("Title", layout, keep_on_top=True,finalize=True)
window.maximize()

while True:
    event, values = window.read()
    if event == sg.WINDOW_CLOSED:
        break
    print(event, values)

window.close()


text:
Q: How to consume spring cloud config server Jdbc backend configs from Spring cloud Client server? I went through lots of tutorials regarding this but could not get this done.
Here is my table structure for this.
Application Profile Label  prop_key       value
masking     dev     latest test-property  message

I have a cloud config server which should integrate with JDBC backend. Here is my application.properties in config server
server.port=8082
spring.application.name=masking
management.endpoints.web.exposure.include=*
spring.datasource.url=jdbc:postgresql://localhost:8000/finos?currentSchema=xlabs
spring.datasource.username=mufgdev
spring.datasource.password=XXX
spring.profiles.active=XXX
spring.cloud.config.server.jdbc.sql=SELECT prop_key,value from xlabs.properties where application=? and profile=? and label=?
spring.cloud.config.server.jdbc.order=1

With this configs if I enter http://localhost:8082/masking/dev/latest response will show the results as I want.
I want to consume properties in client side with the following configs in bootstrap.properties
spring.application.name=masking
spring.cloud.config.uri=http://localhost:8082
spring.cloud.config.label=latest
spring.cloud.config.profile=dev

And in my client side
@RestController
@RefreshScope
public class TestController {

    @Value("${test-property}")
    private String aConf;

    @GetMapping("/message")
    String message() {
        String name =aConf ;
        return name;
    }
}

This gives java.lang.IllegalArgumentException: Could not resolve placeholder 'test-property' in value "${test-property}"
Can anyone comment on this?
Thanks.

A: This issue comes with the latest Spring boot release, All the above code segments steps all okay, But by default Spring has disabled bootstrap. So you have to enable them by adding
<dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>

No need add for older versions of the Spring boot projects.


text:
Q: How do I compare the current datetime to another datetime in javascript I am looking for some help, trying to compare 2 dates in JavaScript, but haven't managed to find the exact answer on this site yet.
I am only just starting out with JavaScript and I get the impression that getting the current date\time is not a simple 1 line of code which I thought it would be. I thought I could use a ternary operator but maybe not. I hope I'm wrong but here is my dilemma.
I want to compare 2 dates. If date1 is before date2 then do something. If not then do something else.

*

*date1: is the current date time. i.e. my system clock

*date2: is a predefined value. I already have this value in the web page: ${expiredDateTime.format("ddMyyyyhm") I believe date 2 is a string but I'm no expert on jquery.

Any help with this would be great.

A: Please try the below code:
var user="12/11/2012/5/30";
var arrdt= user.split("/");
var userdt = new Date(arrdt[2], arrdt[1] - 1, arrdt[0],arrdt[3],arrdt[4]);
var currdt = new Date();
if (userdt < currdt) {
alert("userdate is before current date");
}else{
alert("userdate is after current date");
}

A: The easiest way to compare dates in javascript is to first convert it to a Date object and then compare these date-objects.
Below you find an object with three functions:
dates.compare(a,b)
Returns a number:
-1 if a < b
0 if a = b
1 if a > b
NaN if a or b is an illegal date
dates.inRange (d,start,end)
Returns a boolean or NaN:
true if d is between the start and end (inclusive)
false if d is before start or after end.
NaN if one or more of the dates are illegal.
dates.convert
Used by the other functions to convert their input to a date object. The input can be
a date-object : The input is returned as is.
an array: Interpreted as [year,month,day]. NOTE month is 0-11.
a number : Interpreted as number of milliseconds since 1 Jan 1970 (a timestamp)
a string : Several different formats is supported, like "YYYY/MM/DD", "MM/DD/YYYY", "Jan 31 2009" etc.
an object: Interpreted as an object with year, month and date attributes. NOTE month is 0-11.
 // Source: http://stackoverflow.com/questions/497790
    var dates = {
        convert:function(d) {
            // Converts the date in d to a date-object. The input can be:
            //   a date object: returned without modification
            //  an array      : Interpreted as [year,month,day]. NOTE: month is 0-11.
            //   a number     : Interpreted as number of milliseconds
            //                  since 1 Jan 1970 (a timestamp)
            //   a string     : Any format supported by the javascript engine, like
            //                  "YYYY/MM/DD", "MM/DD/YYYY", "Jan 31 2009" etc.
            //  an object     : Interpreted as an object with year, month and date
            //                  attributes.  **NOTE** month is 0-11.
            return (
                d.constructor === Date ? d :
                d.constructor === Array ? new Date(d[0],d[1],d[2]) :
                d.constructor === Number ? new Date(d) :
                d.constructor === String ? new Date(d) :
                typeof d === "object" ? new Date(d.year,d.month,d.date) :
                NaN
            );
        },
        compare:function(a,b) {
            // Compare two dates (could be of any type supported by the convert
            // function above) and returns:
            //  -1 : if a < b
            //   0 : if a = b
            //   1 : if a > b
            // NaN : if a or b is an illegal date
            // NOTE: The code inside isFinite does an assignment (=).
            return (
                isFinite(a=this.convert(a).valueOf()) &&
                isFinite(b=this.convert(b).valueOf()) ?
                (a>b)-(a<b) :
                NaN
            );
        },
        inRange:function(d,start,end) {
            // Checks if date in d is between dates in start and end.
            // Returns a boolean or NaN:
            //    true  : if d is between start and end (inclusive)
            //    false : if d is before start or after end
            //    NaN   : if one or more of the dates is illegal.
            // NOTE: The code inside isFinite does an assignment (=).
           return (
                isFinite(d=this.convert(d).valueOf()) &&
                isFinite(start=this.convert(start).valueOf()) &&
                isFinite(end=this.convert(end).valueOf()) ?
                start <= d && d <= end :
                NaN
            );
        }
    }

A: Possible douplicate for link
if (date1.getTime() > date2.getTime()) {
    alert("The first date is after the second date!");
}

Reference to Date object

A: try below code for getting current month, year , date
var date = new Date();
var currentMonth = date.getMonth();
var currentDate = date.getDate();
var currentYear = date.getFullYear();


text:
Q: .htaccess Subdirectory Rewrite Exception I'm currently consolidating posts on a site we recently acquired that had multiple WordPress installs to manage content, one in the public_html folder and another in a subdirectory, like so:
1. http://domain.com/
2. http://domain.com/another-install/

We're moving all of the content from /another-install/ into the main setup, and using a 301 redirect to remove /another-install/ from all old links like so:
RedirectMatch 301 ^/another-install/(.*) http://domain.com/$1

Resulting in all articles redirecting like so:
http://domain.com/another-install/article-name/
TO
http://domain.com/article-name/

The problem is, we want to keep /another-install/ viewable as a page. With the current redirect, http://domain.com/another-install/ goes to http://domain.com/. Is there any way to add an exception, or rewrite the current rule so that it keeps /another-install/ viewable?

A: Change your regex from (.*) (which matches 0 or more of any character) to (.+) (which matches 1 or more of any character). That means there would have to be something following /another-install/ in order for there to be a redirect.

A: You need a RewriteRule to specify exclusions. Add this to your .htaccess file
RewriteCond %{REQUEST_URI} !^/old-install/(index\.wml)?$ [NC]
RewriteRule ^old-install/(.+)$ http://domain.com/$1 [R=301,NC,L]


text:
Q: Regular expression to replace line feeds with a space only if the break is not in the contents of an HTML attribute I'm trying to write a regular expression that replaces line feeds between certain areas of a text file, but only on plain text content (i.e. excludes text inside HTML attribute contents, like href) but not having much luck past the first part.
Example input:
AUTHOR: Me
DATE: Now
CONTENT:
This is an example. This is another example. This is an example. This is an example. This is yet another
example.
END CONTENT
COMMENTS: 0

Example output:
AUTHOR: Me
DATE: Now
CONTENT:
This is an example. This is another example. This is an example. This is an example. This is yet another example.
END CONTENT
COMMENTS: 0

So ideally, a space replaces line breaks if they occur in plain text, but removes them without adding a space if they are inside HTML parameters (mostly href, and I'm fine if I have to limit it to that).

A: Ideally you would use a real HTML parser (or XML it it was XHTML) and replace the attribute contents with that.
However, the following may do the trick if the engine supports positive lookbehind of arbitrary length:
(?<=\<[^<>]+=\s*("[^"]*|'[^']*))[\r\n]+

Usage: Replace all occurences of this regex with an empty string.

A: This will remove newlines in attribute values, assuming the values are enclosed in double-quotes:
$s = preg_replace(
       '/[\r\n]+(?=[^<>"]*+"(?:[^<>"]*+"[^"<>]*+")*+[^<>"]*+>)/',
       '', $s);

The lookahead asserts that, between the current position (where the newline was found) and the next >, there's an odd number of double-quotes.  This doesn't allow for single-quoted values, or for angle brackets inside the values; both can be accommodated if need be, but this is ugly enough already. ;)
After that, you can replace any remaining newlines with spaces:
$s = preg_replace('/[\r\n]+/', ' ', $s);

See it in action on ideone.com.


text:
Q: How to connect to USB TTY from BeagleBone Black? I would like to establish serial communication from a Windows PC to the BeagleBone Black. The purpose is to have a Python application on the BeagleBone interact with a terminal running on the PC. I would like to use the same USB cable I use for the SSH connection (from PC to micro-usb on the BB), but instead of SSH, I want to open a serial connection via something like TeraTerm, and have a running python application connect to the TTY, something like /dev/ttyUSB. However, this TTY does not exist.
Note that I'm not trying to do serial debugging, as this article suggests. I'm also not trying to do this connection over UART. I specifically want to communicate with a python application via a terminal running on the PC. The Python application would use a library like pyserial.
Since the TTY is not showing on the BeagleBone, how can I proceed?

A: A TTL to USB converter will work. I got an older model that is still produced from some company. Here is one I found easily online at Adafruit: https://www.adafruit.com/product/954.
That will give you TX, RX, GND, and PWR. Please make sure to get a 3.3v type if you are using it for the BBB.
Here is some write up w/ questions/answers: https://askubuntu.com/questions/40959/how-do-i-connect-to-tty-com-dev-ttyusb0
Sometimes when you use PuTTY w/ Win 10 COM ports, it is necessary to make sure you get the COM port correct. Actually, every time! Click on the connection ICON on the bottom, right of the screen under the "^", click on the Open Devices and Printers, and then go to the BBB on the photo screen. Once you right click and go to Properties, finally click on the Hardware tab to find your COM Port. Then, one can use a COM Port on Win 10 w/ the BBB along w/ PuTTY.
So, w/ PuTTY, you can click the serial connection, type your COM Port (COM6 or whatever), and finally click Open.
...


text:
Q: Case statement in oracle Here's my queries, they don't work but I want to do something like this in sql (oracle)
$P{parametre} is a parameter used in jasper;
select val1, val2 from table where
table.column1  =(case when  $P{parametre} is not null   then  $P{parametre}    end  )
and
table.column1 is not null (case when  $P{parametre} is null     end  )

but table.column1 is not null (case when  $P{parametre} is null     end  )  don't work
do you have  idea please??

A: I think you want this:
...
where (column1 is null and $P{parametre} is null)
or column1 = $P{parametre}

Which matches column1 to the parameter, but treats both being null as a match.


text:
Q: Change parent frame url if iframe url changes I have iframed a page:

And I want to change the parent url to http://mywebsite.com/succes.html if the iframe url changes to http://externalwebsite.com/succes.html
I was trying to figure it out with JavaScript but I didn't manage to do it. Can someone help me?

A:
Bind to the frame.onload event in the parent window.
var frame = document.getElementById('frameId');
frame.onload = function(e){
   if(frame.src === 'http://externalwebsite.com/succes.html' ){
      window.location.href = 'http://externalwebsite.com/succes.html';
   }
};

Try frame.src='someUrl'; for test.


text:
Q: Passing Main class as this to another class - gives inaccessible reference I have 2 classes in my ActionScript project; Main and ContentManager. I wish to pass Main to ContentManager because I want to first instantiate Main, pass control to a method in ContentManager after which control should return to Main.
I do this within Main's constructor by instantiating
contentManager = new ContentManager(this);

Inside Content Manager's constructor
public class ContentManager(_main:Main) {
    this.main = _main;
}

And later
this.main.setData(data);

In Main, setData is
public function setData(data:Object):void
{
    versionData = data;
}

I am getting a compiler warning that I find strange. Flash Builder auto-completes setData for me inside ContentManager suggesting it is able to see it via this.main. And I am also able to access vars in main during run, e.g.
main.somePublicVar = "foo";

But calling setData as a method gives:
Attempted access of inaccessible method setData through a reference with static type Main.

I've since tried a couple of other calls:
main.toString();
main.addChild(null);
main.setData(null);

The first 2 work fine, the 3rd, my one, fails with the error. Utterly lost.
Cheers

A: As per net.uk.sweet, a custom event + dispatch/listen worked. Listening had to be done ON the contentManager instance which is where I had gone wrong with the approach before, so that it is added to the display list. I added my data into my custom event class so I could access it by the listen callback function. Thanks everyone.

A: I am thinking you have probably declared the function as a setter:
public function set setData(data:Object):void
{
    versionData = data;
}

And since you are calling it like main.setData(data) instead of main.setData = data you are getting that error.
Could this be the case?!


text:
Q: Use Oracle client tracing and tkprof to review submitted SQL queries I would like to learn how to trace an Oracle client and view the SQL queries submitted.
I started by adding these lines to my client's sqlnet.ora file:
TRACE_LEVEL_CLIENT=16
TRACE_FILE_CLIENT=sqlnet.trc
TRACE_DIRECTORY_CLIENT=c:\temp
LOG_DIRECTORY_CLIENT=c:\temp
TRACE_UNIQUE_CLIENT=TRUE
TRACE_TIMESTAMP_CLIENT=TRUE
DIAG_ADR_ENABLED=OFF

Then I logged into the database on that same client using SQL*Plus. I submitted two queries:
select * from all_tables where table_name = 'ADDRESS';
select * from all_users where username like 'AB%';

Then I exited SQL*Plus.  The trace file was created in c:\temp.  The file is about 4000 lines long.  I can definitely see my two SQL statements in there.  The format is a pain to read though, as they are just hex dumps:
(10632) [29-AUG-2016 17:08:40:240] nsbasic_bsd: 00 00 31 73 65 6C 65 63  |..1selec|
(10632) [29-AUG-2016 17:08:40:240] nsbasic_bsd: 74 20 2A 20 66 72 6F 6D  |t.*.from|
(10632) [29-AUG-2016 17:08:40:240] nsbasic_bsd: 20 61 6C 6C 5F 75 73 65  |.all_use|
(10632) [29-AUG-2016 17:08:40:240] nsbasic_bsd: 72 73 20 77 68 65 72 65  |rs.where|
(10632) [29-AUG-2016 17:08:40:240] nsbasic_bsd: 20 75 73 65 72 6E 61 6D  |.usernam|
(10632) [29-AUG-2016 17:08:40:240] nsbasic_bsd: 65 20 6C 69 6B 65 20 27  |e.like.'|
(10632) [29-AUG-2016 17:08:40:240] nsbasic_bsd: 41 42 25 27 01 00 00 00  |AB%'....|

My research leads me to believe that tkprof is the way to get a readable report of my trace file.  I tried the following:
tkprof c:\temp\sqlnet_10632.trc report.txt

But that gives me a pretty pointless file:
   0  session in tracefile
   0  user  SQL statements in trace file.
   0  internal SQL statements in trace file.
   0  SQL statements in trace file.
   0  unique SQL statements in trace file.
4361  lines in trace file.
   0  elapsed seconds in trace file.

Ideally, I'd like to see a report that for this situation shows me easy-to-read SQL text submitted by the client (including the two I manually typed in), in the order they were submitted.  Am I on the right track?  What am I missing?  If I'm not on the right track, what should I do instead to trace the SQL submitted by the client?
Note:  I am using a 12c client.  I do not have access to the database server.

A: Just for reference, Oracle provides the trcasst utility to perform this action:
$ORACLE_HOME/bin/trcasst client_Tract_file.trc > client_Tract_file.txt

A: The tkprof utility is used to generate reports from 10046 trace files.
These trace files show database operations.
Here is a good article to get you started with those:
sql trace 10046
tkprof would not be at all useful for sqlnet trace files.
For sqlnet trace files, you would want to use the trcasst utility.
While trcasst is useful, if you really want to find out what is going on, you will need to develop some understanding of the files themselves.
Here are some good references to get started with understanding sqlnet trace files:
Tracing Error Information for Oracle Net Services
If you have access to My Oracle Support, the following notes will be invaluable:

SQLNET PACKET STRUCTURE: NS PACKET HEADER (Doc ID 1007807.6)
  Examining Oracle Net, Net8, SQLNet Trace Files (Doc ID 156485.1)

That second article has a PDF attached that explains quite a bit.
Documentation from 11g - 19c will all state that you should set the following in sqlnet.ora:
diag_adr_enabled=off

If you want accurate timestamps, then do this instead:
diag_adr_enabled=on

That is a bug that I hope to see fixed by the time Oracle 20c is released.

A: This isn't the answer I was hoping for, but I needed to get-r-done and move on, so I wrote a quick and dirty Windows console application (C#):
    static void Main(string[] args)
    {
        using (var sr = new StreamReader(args[0]))
        {
            var line = string.Empty;
            var parsingSqlHex = false;
            var timestamp = string.Empty;
            var parsedSql = string.Empty;
            var patternStart = @"nsbasic_bsd\: packet dump";
            var patternTimeStamp = @"\[\d{2}-[A-Z]{3}-\d{4} (\d\d\:){3}\d{3}\]";
            var patternHex = @"nsbasic_bsd\: ([0-9A-F][0-9A-F] ){8}";
            var patternEnd = @"nsbasic_bsd\: exit \(0\)$";

            while (line != null)
            {
                if (Regex.IsMatch(line, patternStart))
                {
                    timestamp = Regex.Match(line, patternTimeStamp).Value;
                    parsingSqlHex = true;
                }
                else if (parsingSqlHex)
                {
                    if (Regex.IsMatch(line, patternEnd))
                    {
                        if (!string.IsNullOrEmpty(parsedSql))
                        {
                            Console.WriteLine(timestamp);
                            Console.WriteLine(parsedSql + "\r\n");
                        }
                        parsedSql = string.Empty;
                        parsingSqlHex = false;
                    }
                    else if (Regex.IsMatch(line, patternHex))
                    {
                        parsedSql += HexToString(line.Substring(line.Length - 35, 23));
                    }
                }

                line = sr.ReadLine();
            }
        }
    }

    static string HexToString(string hexValues)
    {
        var hexCodeArray = hexValues.Split(" ".ToCharArray());
        var n = 0;
        var s = string.Empty;

        for (var i = 0; i < hexCodeArray.Length; i++)
        {
            n = Convert.ToInt32(hexCodeArray[i], 16);
            if (n > 31 && n < 127) s += Convert.ToChar(Convert.ToUInt32(hexCodeArray[i], 16));
        }

        return s;
    }

I'm using it to parse my trace files like so:
OracleTraceParser.exe c:\temp\trace.txt > report.txt

Then my report.txt file has some odd characters here and there, but nonetheless gives me what I'm after:
[30-AUG-2016 13:50:51:534]
i^qx(SELECT DECODE('A','A','1','2') FROM DUAL

[30-AUG-2016 13:50:51:534]
i

[30-AUG-2016 13:51:05:003]
^a5select * from all_tables where table_name = 'ADDRESS'

[30-AUG-2016 13:51:21:081]
i^a1select * from all_users where username like 'AB%'


text:
Q: How to Save Current Drivers before Updating? I'm been losing my internet connection about once a day and one suggestion was to delete the driver and reinstall the new driver from Intel. Okay I can do that, but what happens if the new driver is worse than the old one? Where would I find the original driver for my system to reinstall it?
Just clarify, I'm looking for a way to save copies of a driver on my system (not just the Network Adapters) before I update a driver. I just gave the system to myself for a Christmas present and I don't want to screw it up!
It's a ASUS Z170-A motherboard with an i7 6700k 4.GHz/4.2GHz running Windows 10 64bit.
Ran the Intel Driver Update Utility and got NO DRIVERS DETECTED!
This 2009 thread suggested something called Double Drivers, from a Google Search it looks it hasn't been updated since 2014.  The second program Driver Genius, is supposed to support Windows 10.  Unfortunately, it has such horrible reviews I am not about to load on my machine.
Edit:  Double Drivers worked!  Here are a couple screen shots:
Backup program results screen shot:

Download of the program results screen shot, I used DD.exe:

A: Double Driver is exactly what you are looking for.
However, the download link on the authors webpage does not seem to work.   I found this version over at Major Geeks
http://www.majorgeeks.com/files/details/double_driver.html
Download and run the application.   By default, the program will auto select all of the drivers you need to have your computer function properly.
When the application opens, click Backup > Scan Current System to scan your system for drivers.    After Double Drivers scans your system, click Backup Now and select a location to save your drivers to.   I would recommend putting them on a thumb drive or something if you are planning on reinstalling your operating system, otherwise you will end up erasing them when you go to format your hard drive (if you plan on doing a full reinstall of windows).


text:
Q: How to output multiple graphs using sns.distplot() I have 3 lists of data.
If I do:
sns.distplot(data1)
sns.distplot(data2)
sns.distplot(data3)

I'm going to get a single graph with 3 different distributions on the same graph.
I'd like to output 3 individual distributions. How do I do this without using subplots? I find that subplots are too cramped and small.
Thanks

A: You just need to set the figsize accordingly when creating subplots:
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
data1, data2, data3 = [np.random.normal(size=[100]) for _ in range(3)]

fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15, 4))
sns.distplot(data1, ax=ax1)
sns.distplot(data2, ax=ax2)
sns.distplot(data3, ax=ax3)

Here's what I got


text:
Q: Can We Pass Multiple Parameters to RestCypherQueryEngine.query? I want to implement a log in portal using java, neo4j REST API and Spring Framework. I am using the RestCypherQueryEngine class to send a cypher query to the server.
The query looks like -->
String query = "MATCH n WHERE n.Email = {email} AND n.Password = {pass} RETURN n;"
final QueryResult<Map<String,Object>> result = engine.query(query, Map.Util("Email", email), Map.Util("Password", pass);
.
"email" and "pass" are both Strings with the respective values.
I wanted to know if this is a valid query and can two parameters be passed like this ?
and how to know if a node has been returned or not or if the the login is authenticated. ?
Thank you.

A: You need to put all parameters into one map:
Map<String,Object> params = new HashMap<>();
params.put("email", email");
params.put("password", pass);
QueryResult<Map<String,Object>> result = engine.query(query,params);

NB: Query parameters are case sensitive.


text:
Q: How to make a Polymer CRUD app? Does anyone know any example/tutorial of Polymer using core-ajax and ajax-form to build a CRUD application?
My main question is how to structure the app (best practices) to focus data access in "modules" (custom elements) like in Angular services.
Should I use a unique core-ajax by "module" for example and change this attributes (like url and method) in javascript or put multiple core-ajax in template? I know this is maybe a personal choice, but if an idea for this already exists I would follow it.
Thanks

A: The best choice is use Firebase!
http://polymer.github.io/firebase-element
Also there is the AngularJS binding for Firebase
https://www.firebase.com/docs/web/libraries/angular/quickstart.html


text:
Q: R - NAs turn columns into character class (should be integer/ numeric) I imported a huge dataset with a lot of missing values or N/As, NAs.
This is how i import the Data:
Databsp<-read.csv("C:/Users/adminfor/Desktop/Neuer Ordner/Pseudonymized-Genet-Treatment-Summary-20220201120538.csv", na.strings=TRUE)

Next, I converedt all the NAs or N/As to using the following code:
a <- Databsp %>% replace_with_na_all(condition = ~.x %in% common_na_strings)

Now my question: Why are columns that only include numbers and NAs from the class "character" and not "integer/numeric". I tried several codes, but nothing seems to help...

A: You don't change your column classes. When you import your data, the column classes are first set, and you do nothing to change them. If a column in your CSV file has only numeric and NA values when you import it, it will be numeric. But if it has strings (including strings that you haven't yet told R are NA-equivalent, like "N/A") then read.csv must read them as character class because they are not numeric. Later, you replace those NA-equivalent values with actual NAs, but that replaces values only, it does not change the class of the columns.
The bad solution would be to patch this. Add an extra step after you replace the NA values, you could use the type.convert() function to re-assess the columns and convert them as necessary, a <- type.convert(a).
The better solution is to give read.csv your list of NA-equivalent strings when you read in the data. This is what the na.strings argument is supposed to be. From ?read.csv

na.strings
a character vector of strings which are to be interpreted as NA values.

So change your import line to
Databsp <- read.csv(
  "C:/Users/adminfor/Desktop/Neuer Ordner/Pseudonymized-Genet-Treatment-Summary-20220201120538.csv",
   na.strings = common_na_strings
)

And then the columns should be classed appropriately when you read them in, and you can skip the replace_with_na_all step as it is already taken care of. Relatedly, your current na.strings = TRUE does nothing because TRUE is not a character vector.


text:
Q: How to stop git hanging on commit in cygwin bash Whenever I type
git commit

My cygwin bash terminal looks up as if it was waiting for me to finish editing the message in another process but no editor starts.
I get an error
"C:/Program (x86)/Git/bin/sh.exe": line 0: igncr: invalid option name

Which I assume is todo with one of the environment variables I have to try and make cygwin usable.
If I use
git commit -m "Some Message Here"

Then everything works fine

A: The hanging was caused by git being unable to find my editor when I set the global editor to notepad
git config --global core.editor "notepad"

Then everything works fine.
By setting the global editor to the windows location of vim
git config --global core.editor "c:/APPS/CYGWIN/bin/vim.exe"

I was able to run vim and then I could see that there was a lock file as well.


text:
Q: How do I organize a list into a specifically formatted column in bash? I'm working on a script where I need to organize some output into columns by line number. So Line number 5 needs to go to line number 1, line number 6 needs to go to line number 2 etc.
There is not really a pattern between the output to tell which one should be moved. The output is always the same, but just puts line breaks after every word, and lists the category names first, then the data after. Below I have some example code, along with what the output looks like. Thank you for your help!
while :
do
    read -r -p ""${LINK}" ---> " LOOP
    case "${LOOP}" in

      1) command | tr ',' '\n' | tr -d '"' | printf '1m11\n,p\n'
      2) another command
      3) blah blah
    esac
done

When running command 1, it outputs something like so (0 spaces in between)
CategoryA
CategoryB\
CategoryC\
CategoryD\
Answer1\
Answer2\
Answer3\
Answer4

I'm trying to format the output for 1 to look like this
CategoryA - Answer1\
CategoryB - Answer2\
CategoryC - Answer3\
CategoryD - Answer4

However I am having trouble, I have also tried the following
sed -e '1~11{h;d};G'
column -t
awk '{ print $2 " " $1}'

I am not the best at formatting, as I'm newer to coding. I can pull data from querys, databases etc. Just gotta get better at formatting the output. I appreciate yall taking time out of your day to help with this!

A: EDIT: Since OP changed the samples completely so adding solution as per new samples now.
awk '
BEGIN{ OFS=" - " }
match($0,/Category[^\\]*/){
  val=substr($0,RSTART,RLENGTH)
}
!/Category/{
  found=1
}
found && !/Category/{
  print arr[++count],$0
  next
}
{
  arr[FNR]=val
}
'  Input_file

Considering your Input_file looks same as shown samples strictly here, written and tested it in following link https://ideone.com/8XEVBW
awk '
BEGIN{ OFS=" - " }
match($0,/[^0-9]+/){
  val=substr($0,RSTART,RLENGTH)
}
prev!=val && prev{
  found=1
}
found{
  print arr[++count],$0
  next
}
{
  arr[FNR]=$0
  prev=val
}
'  Input_file

Output will be as follows with shown samples.
Example1 - Answer1
Example2 - Answer2
Example3 - Answer3
Example4 - Answer4


text:
Q: 'The network path was not found' every first attempt to Azure SQL Server I am developing a web application, using Visual Studio 2013 and a SQL SERVER database created on Azure.
Almost every time that I took more than 30 seconds to build and re-run the application (F5) I get this error below. The connection sql connection to SQL Timed-out and this is the error raised.

[Win32Exception (0x80004005): The network path was not found]

I retry the connection and the problem goes away.
The point is that I am loosing so much time on this issue.
INFO ADDED:

*

*I have the SAME issue on SQL Management, first attempt network not found, second attempt it works.

*I have seen other computers, running other apps (.net based) on the company with the same behavior on a different SQL Azure server, so, in my mind is something related to azure dns.

*I have two SQL connections, to the same server, one for OWIN context, and another used by Entity Framework 6. Both MARS enable.

*I don't feel to having the same issue browsing any other website.

*My computer is part of an enterprise domain (that I had myself setup, and I am not an expert on Windows Server)

*I am using a Macbook with ThunderBolt dongle for ethernet.

My connection strings
<connectionStrings>
    <add name="Container" connectionString="metadata=res://*/Models.MakeItMine.csdl|res://*/Models.**********.ssdl|res://*/Models.**********.msl;provider=System.Data.SqlClient;provider connection string="data source=**********.database.windows.net;initial catalog=db**********;persist security info=True;user id=**********;password=**********;MultipleActiveResultSets=True;App=EntityFramework;Connection Timeout=3;ConnectRetryCount=3;ConnectRetryInterval=1"" providerName="System.Data.EntityClient" />
    <add name="OWINConnection" connectionString="data source=**********.database.windows.net;initial catalog=db**********;persist security info=True;user id=**********;password=**********;MultipleActiveResultSets=True;App=MakeItMine;Connection Timeout=3;ConnectRetryCount=3;ConnectRetryInterval=1" providerName="System.Data.SqlClient" />
</connectionStrings>

My IP settings

What I tried

*

*Disabled AVG Components

*Disabled Windows Firewall for Home/Enterprise
networks

*Changed my dns to Google's dns (8.8.8.8/8.8.4.4), if I open
nslookup and try to resolve my database path, it works every time.

*Changed my sql connection parameters: "Connection Timeout=3;ConnectRetryCount=3;ConnectRetryInterval=1", so it takes less time to raise the error, and I can retry faster and not loose so much time.

Azure doesn't permit me "pinging" the server, since never returns. So, I am really in trouble on how to troubleshoot/monitor this issue.
Any suggestions on how to troubleshoot this are appreciated.

A: I did not found the exact problem neither the perfect solution yet, but I do know its a DNS related problem.
So, my fix by now is changing my windows HOSTS file and fixing my database dns to its ip. It's working for now and saving me a lot of debugging time.


text:
Q: У кого есть материал как работать с FaceDetection Camera2API? На официальных источниках я вообще не нашел информации... Как работать с Camera API есть много примеров, но насчет Camera2API вообще ничего..., пара обсуждений на стаке и все... есть один похожий вопрос на мой, но у меня проблема не решилась...
Вот ссылка на такой же вопрос...
Я взял пример гугла по Camera2API
Google: https://github.com/googlesamples/android-Camera2Basic.
Вот что я сделал, но у меня не определяет лица...
Я добавил мод
private void createCameraPreviewSession() {
    try {
        SurfaceTexture texture = mTextureView.getSurfaceTexture();
        assert texture != null;

        // We configure the size of default buffer to be the size of camera preview we want.
        texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());

        // This is the output Surface we need to start preview.
        Surface surface = new Surface(texture);

        // We set up a CaptureRequest.Builder with the output Surface.
        mPreviewRequestBuilder
                = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
        mPreviewRequestBuilder.addTarget(surface);

        // Here, we create a CameraCaptureSession for camera preview.
        mCameraDevice.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()),
                new CameraCaptureSession.StateCallback() {

                    @Override
                    public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                        // The camera is already closed
                        if (null == mCameraDevice) {
                            return;
                        }

                        // When the session is ready, we start displaying the preview.
                        mCaptureSession = cameraCaptureSession;
                        try {

//           ---->>         Установка модуля распознания лица
                            mPreviewRequestBuilder.set(CaptureRequest.STATISTICS_FACE_DETECT_MODE,
                                    CameraMetadata.STATISTICS_FACE_DETECT_MODE_FULL);

                            // Auto focus should be continuous for camera preview.
                            mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,
                                    CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);

                            // Flash is automatically enabled when necessary.
                            setAutoFlash(mPreviewRequestBuilder);

                            // Finally, we start displaying the camera preview.
                            mPreviewRequest = mPreviewRequestBuilder.build();

                            mCaptureSession.setRepeatingRequest(mPreviewRequest,
                                    mCaptureCallback, mBackgroundHandler);
                        } catch (CameraAccessException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onConfigureFailed(
                            @NonNull CameraCaptureSession cameraCaptureSession) {
                        System.out.println("Failed строка 757");
                    }
                }, null
        );
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

private CameraCaptureSession.CaptureCallback mCaptureCallback
        = new CameraCaptureSession.CaptureCallback() {

    @Override
    public void onCaptureProgressed(@NonNull CameraCaptureSession session,
                                    @NonNull CaptureRequest request,
                                    @NonNull CaptureResult partialResult) {
        process(partialResult);
    }

    @Override
    public void onCaptureCompleted(@NonNull CameraCaptureSession session,
                                   @NonNull CaptureRequest request,
                                   @NonNull TotalCaptureResult result) {
        process(result);
    }

    private void process(CaptureResult result) {

--->   //здесь проверяю получает ли он массив лиц или нет + непонятный мод
        Integer mode = result.get(CaptureResult.STATISTICS_FACE_DETECT_MODE);
        Face[] faces = result.get(CaptureResult.STATISTICS_FACES);
        if(faces != null && mode != null)
            System.out.println("tagDDDDDDDDDDDDDDDDDDDDDDDD" + "faces : " +
                    faces.length + " , mode : " + mode);

        switch (mState) {
            case STATE_PREVIEW: {
                // We have nothing to do when the camera preview is working normally.

//                  Установка модуля распознания лица
                mPreviewRequestBuilder.set(CaptureRequest.STATISTICS_FACE_DETECT_MODE,
                        CameraMetadata.STATISTICS_FACE_DETECT_MODE_FULL);
                break;
            }

потом проверил максимальное кол-во лиц которое может принимать камера и какой то мод(до сих пор не пойму что он означает)
private void setUpCameraOutputs(int width, int height) {

    CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    try {
        for (String cameraId : manager.getCameraIdList()) {
            CameraCharacteristics characteristics
                    = manager.getCameraCharacteristics(cameraId);

            // We don't use a front facing camera in this sample.
            //проверяет какая камера активна сейчас, если внутренняя то цикл запускается заново
            Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
            if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
                continue;
            }

            max_count = characteristics.get(
                    CameraCharacteristics.STATISTICS_INFO_MAX_FACE_COUNT);
            modes = characteristics.get(
                    CameraCharacteristics.STATISTICS_INFO_AVAILABLE_FACE_DETECT_MODES);

            System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! max_count " + max_count + " modes " + modes);

Выводит такое :
I/System.out: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! max_count 16 modes [I@3e2907e8

и вот что в лог печатает
03-08 18:34:07.018 7405-7438/com.example.android.camera2basic I/System.out: tagDDDDDDDDDDDDDDDDDDDDDDDDfaces : 0 , mode : 1
03-08 18:34:07.048 7405-7438/com.example.android.camera2basic I/System.out: tagDDDDDDDDDDDDDDDDDDDDDDDDfaces : 0 , mode : 1
03-08 18:34:07.078 7405-7438/com.example.android.camera2basic I/System.out: tagDDDDDDDDDDDDDDDDDDDDDDDDfaces : 0 , mode : 1
03-08 18:34:07.118 7405-7438/com.example.android.camera2basic I/System.out: tagDDDDDDDDDDDDDDDDDDDDDDDDfaces : 0 , mode : 1
03-08 18:34:07.148 7405-7438/com.example.android.camera2basic I/System.out: tagDDDDDDDDDDDDDDDDDDDDDDDDfaces : 0 , mode : 1
03-08 18:34:07.178 7405-7438/com.example.android.camera2basic I/System.out: tagDDDDDDDDDDDDDDDDDDDDDDDDfaces : 0 , mode : 1
03-08 18:34:07.218 7405-7438/com.example.android.camera2basic I/System.out: tagDDDDDDDDDDDDDDDDDDDDDDDDfaces : 0 , mode : 1
03-08 18:34:07.258 7405-7438/com.example.android.camera2basic I/System.out: tagDDDDDDDDDDDDDDDDDDDDDDDDfaces : 0 , mode : 1
03-08 18:34:07.288 7405-7438/com.example.android.camera2basic I/System.out: tagDDDDDDDDDDDDDDDDDDDDDDDDfaces : 0 , mode : 1
03-08 18:34:07.308 7405-7438/com.example.android.camera2basic I/System.out: tagDDDDDDDDDDDDDDDDDDDDDDDDfaces : 0 , mode : 1
03-08 18:34:07.348 7405-7438/com.example.android.camera2basic I/System.out: tagDDDDDDDDDDDDDDDDDDDDDDDDfaces : 0 , mode : 1

Как сделать так чтоб все работало правильно? Даже не знаю где почитать...
Буду рад любому совету)) а еще лучше если дадите ссылку на рабочий пример для наглядности... чтоб посмотреть как это работает на практике... А то неделю уже не могу разобраться((


text:
Q: Intersection not narrowing union properly I have the following use case: I have a union of Foo and Bar. Both Foo and Bar have a type property, each with their own enum values "foo" and "bar". In addition, they each have a payload property, with Foo's being a string and Bar's being a number.
enum Types {
    FOO = "foo",
    BAR = "bar"
}

interface Foo {
    type: Types.FOO;
    payload: string;
}

interface Bar {
    type: Types.BAR;
    payload: number;
}

type Union = Foo | Bar;

Now, I tried to narrow the union using an intersection where I define the type like this:
// Does not pass type check because payload must be a string
const baz: Union & { type: Types.FOO } = {
  type: Types.FOO,
  payload: 42
}

This does not pass the type check (as I did expect), since payload is a number, but should be a string when the type is FOO.
On the other hand, this compiles (As I did expect):
// Passes type check
const baz: Union & {type: Types.FOO} = {
    type: Types.FOO,
    payload: "foobar"
}

Now I have a function handleFoo which I type like this:
function handleFoo(foo: Union & {type: Types.FOO}) {
    // payload is string | number
    console.log(foo.payload)
    if (foo.type === Types.FOO) {
        // payload is still string | number??
        console.log(foo.payload)
    }
}

TS tells me that payload is a string | number union. But at the same time, the type is impossible to construct with payload being a number. In addition, even if I check that the type is FOO, it still does not narrow the type of foo down.
On the other hand, if I do it like this, I get the expected narrowing after the FOO check.
function handleFoo2(foo: Union) {
    console.log(foo.payload) // payload is string | number
    if (foo.type === Types.FOO) {
        // payload is string
        console.log(foo.payload)
    }
}

The second approach (and the general type check in handleFoo) is impractical for me, because that check is already performed in the caller of handleFoo.
Is this a bug, or simply some kind of misunderstanding of type narrowing?
Is there any way to solve this, or should I file a bug with the TypeScript team?

A: Where do you get this (I have not been able to figure it out)?

TS tells me that payload is a string | number union. But at the same time, the type is impossible to construct with payload being a number.

I put together bits of your code, when I check the types of the payloads that can be assigned to the respective functions filtered by type, the end result is that I have a discreet "string" or "number" type, I have not been able to get "string | number".
So, if what you want is a generic handler for "Union" types, as long as they are agnostic to the type of payload Typescript will warn you if on your code you have incompatible types. Do note I added a function that has no checks (kind of like your handleFoo2 without the if check), and it does not have any issues dealing with both types as long as they are declared consistently (i.e. you don not pass an object Foo with a numeric payload or a Bar Object with a string payload).
I put together an example that can be run on Typescript Playground where all functions do work. For convenience I also copied the source below. Typescript Playground Example
enum Types {
    FOO = "foo",
    BAR = "bar"
}

interface Foo {
    type: Types.FOO;
    payload: string;
}

interface Bar {
    type: Types.BAR;
    payload: number;
}

type Union = Foo | Bar;

const bar: Union & { type: Types.BAR } = {
    type: Types.BAR,
    payload: 5
};

const foo: Union & { type: Types.FOO } = {
    type: Types.FOO,
    payload: "foobar"
};

const fooUnion: Union = {
    type: Types.FOO,
    payload: "foobar"
}

const barUnion: Union = {
    type: Types.BAR,
    payload: 5
}

function handleFoo(foo: Union & {type: Types.FOO}) {
    alert(typeof foo.payload);
    // alert displays "string"
    if (foo.type === Types.FOO) {
        alert(foo.payload);
    }
}

function handleFoo2(foo: Union) {
    alert(typeof foo.payload);
    // alert displays "string"
    if (foo.type === Types.FOO) {
        alert(foo.payload)
    }
}

function handleUnion(union: Union) {
    alert(typeof union.payload);
    alert(union.payload);
}

function handleBar(foo: Union & {type: Types.BAR}) {
    alert(typeof foo.payload);
    // alert displays "number"
    if (foo.type === Types.BAR) {
        alert(foo.payload);
    }
}

function handleBar2(foo: Union) {
    alert(typeof foo.payload);
    // alert displays "number"
    if (foo.type === Types.FOO) {
        alert(foo.payload)
    }
}

handleFoo(foo);
handleFoo2(foo);
handleBar(bar);
handleBar2(bar);

handleFoo(fooUnion);
handleFoo2(fooUnion);
handleBar(barUnion);
handleBar2(barUnion);

handleUnion(fooUnion);
handleUnion(barUnion);

A: try Extract<Union, {type: Types.FOO}> instead of Union & { type: Types.FOO }


text:
Q: How best to store an array in Oracle? I plan to create an Oracle database that will contain arrays of numeric data.  Each array has from 2 to 4 dimensions, and on the order of 1000 data points.  I will want to use the arrays in WHERE clauses, e.g. .
Oracle's array support (VARRAYS, Nested Tables) seems disappointing; it's awfully hard for client software to retrieve the data in a useful way.  Possible, but hard.
Any advice is appreciated.

A: Simple example of varray
declare
   type array_example is varray(5) of varchar2(1);
   array array_example := array_example('A', 'B', 'C' , 'D', 'E');
begin
   for i in 1..array.count loop
       dbms_output.put_line(array(i));
   end loop;
end;


text:
Q: Chrome persistently redirecting to HTTPS for HTTP site I'm building a site to replace an older site. The newer site currently is NOT HTTPS. However, the old site is HTTPS. I'm switching between the two sites by toggling an entry in my 'hosts' file.
I occasionally need to access the old site. When I do, it forcibly redirects to https://, but when I switch back to the new site, Chrome is then broken and will not let me get to http:// to the site but forcibly redirects to https:// which gives me the obvious "Privacy Error" warning and screws up a number of other things (it's WordPress, so it asks me to re-login, but I can't).
How the heck can I force Chrome to stop redirecting to https://? I tried chrome://net-internals/#hsts and I deleted the domain security policies for the site, but it seems to do absolutely nothing. Chrome still redirects. I also tried refreshing clearing cache - this doesn't work either.

A: I have been able to get around this by deleting the domain security policy for the domain:
Go to chrome://net-internals/#hsts
Go towards the end and enter your domain in this textbox and hit delete.

Delete domain security policies
  Input a domain name to delete its dynamic domain security policies (HSTS and Expect-CT). (You cannot delete preloaded entries.):

Domain:
example.com

A: I found it !! I found it !!
For me, I had to perform this extra step :

*

*Click on the icon of HTTPS on the left of the URL bar, and choose "Settings for this site".

*Scroll and find "Secured content" (with the /!\ icon), and choose "Allow".

Thats all !
All the steps combined, give this :

*

*In chrome://net-internals/#hsts, in the "Delete domain security policies", enter the domain of the page, and click "Delete".

*Push CTRL+H, and delete all history/cache/cookies.

*On the page causing problem, click on the HTTPS icon on the top left of the URL bar, and choose "Settings for this website" (I'm French, I don't know the exact label in english versions).

*Scroll and find "Secured content", and choose "Allow".

*Go back to your page, remove the "s" of the https:// in the URL (it has been added again automatically since the last time it failed).

*Press enter to apply the URL. It should work :)

*If not, relaunch the browser.

A: Just deleting the domain security policies using chrome://net-internals/#hsts will not make this work. You have to delete your browsing history and make sure the cache is cleared. Should work after that.

A: In my case, this was because a superdomain of my domain had HSTS enabled. You can check this by going to chrome://net-internals/#hsts and entering your domain under "Query HSTS/PKP domain". If this is the case, you'll see something like
dynamic_sts_domain: example.com
dynamic_upgrade_mode: FORCE_HTTPS
dynamic_sts_include_subdomains: true

A: Starting a new incognito window will give an immediate workaround of the problem. Also handy if You do not want to clear Your history.

A: If you're a developer, go to chrome://net-internals/#hsts
Then, at the bottom of the page "Delete domain security policies", simply type in "localhost" into the box and click [Delete]


text:
Q: Adobe AIR Equivalent in Silverlight? Is it possible to create standalone, desktop Silverlight 4 apps similar to what you can do in Adobe AIR?

A: You can use the Out of Browser mode, which is pretty close AFAIK.  Basically, it allows users to install your Silverlight application to their Desktop or start menu, and they can launch it from the installation point thereafter.  With Silverlight 4, you get additional features like HTML hosting, COM interop, and a little bit more filesystem access.

A: Silverlight has an Out of Browser feature, where the user can right-click an app and choose to install it on their desktop. Other than that You can use WPF for desktop apps, which is pretty similar to Silverlight (or should I sat Silverlight is similar to WPF). Theres a few differences but most of the skills are transferrable.
At my work we are making 2 versions of our app, Silverlight 4 and WPF and I find the biggest differences are in theming but Blend makes it easy to cope with. Most of the code is shared through linking.

A: Yes, Windows Forms (or WPF if you want).  Unless I'm missing something, the .NET framework, and one of those GUI libraries, is the most common fit for your requirements.  Silverlight itself is primarily intended for web applications, not complete, stand-alone desktop apps.