text:
Q: getIdToken from firebase.User in typescript import { AngularFireAuth } from 'angularfire2/auth';

import * as firebase from 'firebase/app';

@Injectable()
export class GetRequestsProvider {

  user: firebase.User;
  userIdToken:string;

  constructor(public http: HttpClient, public afAuth: AngularFireAuth, authservices: AuthService) {
      afAuth.authState.subscribe(user => {
        this.user = user;
      });
  }

  getUserToken(){

      this.afAuth.auth.onAuthStateChanged((user) => {

          user.getIdToken().then((idToken)=>{

            this.userIdToken = idToken;
            console.log("Here I get the user token correctly: ", this.userIdToken);
            console.log(typeof(this.userIdToken)); // 'userIdToken' type is 'string'

          });

          console.log("Here the variable 'userIdToken' is undefined: ", this.userIdToken);
      }
   }
}

I'm trying to use the getIdToken method from Firebase to authenticate users in my app.
The problem I have now, after successfully getting the user's token, I am not able to save it into a variable or to use the token somewhere else.

A: Functions that return promises (such as getIdToken) are asynchronous, and execution of the entire chain happens immediately.  Your console log is always going to happen before the token is available.  Whenever the token is finally availalbe, it will be available in the callback that you pass to then, and no sooner.  You can only use it there, or to some other function that you pass it to.
Do no go down the route of trying to make getIdToken() synchronous or blocking until the token is available - that's not the way it's going to work.  You will need to learn how to work with Firebase APIs asynchronously.


text:
Q: How to display a resource dictionary items in design view? I want to display my resource dictionary items with my custom design view, i want to make a ListView to show the keys with the values. and can edit withing the design view.
-i want to be able to edit my dictionary within visual studio desiner.

A: I think you can use Keys and Values properties of resourceDictionary instance below.
 string exeFilePath = System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase;
 string exeDirPath = System.IO.Path.GetDirectoryName(exeFilePath);
 string targetFile = "subFolder\\ResourceDictionary.xaml";
 string dictionaryPath = new Uri(System.IO.Path.Combine(exeDirPath, targetFile)).LocalPath;
 string xamlString = File.ReadAllText(dictionaryPath);
 ResourceDictionary resourceDictionary = (ResourceDictionary)XamlReader.Parse(xamlString);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Return value type does not match the function type CONST Not sure why error is happening on this function when I made the variable length const on a different function
int list::length() const {
return length;
}

CPP File Above
Header file BELOW
class list {

private:
struct Node
{
int info;
Node *next;

};

int length;
Node *head;

public:

list();
list(const list& otherlist);
~list();

int list::length() const;

};

A: The first issue is that you are qualifying length() inside your class. Remove list::. The second issue is that your member variable length, and your member function length are conflicting, because they have the same name.
I'd rename your members so that they don't clash with the functions. Consider length_ and head_.
Edit: please also post compiler errors in the future, as it makes other readers' jobs a little easier :)


text:
Q: Selenium not working with python 2.7 I am trying to run a basic selenium code with python 2.7. I got the below exception. I have installed the latest selenium.
What should I do to fix it?
C:\Python27\python.exe D:/Python/Selenium/seleniumTest.py
Traceback (most recent call last):
File "D:/Python/Selenium/seleniumTest.py",
    line 4, in <module>     driver = webdriver.Firefox()
File "C:\Python27\lib\site-packages\selenium\webdriver\firefox\webdriver.py",
    line 80, in __init__     self.binary, timeout)
File "C:\Python27\lib\site-packages\selenium\webdriver\firefox\extension_connection.py",
    line 52, in __init__     self.binary.launch_browser(self.profile, timeout=timeout)
File "C:\Python27\lib\site-packages\selenium\webdriver\firefox\firefox_binary.py",
    line 68, in launch_browser     self._wait_until_connectable(timeout=timeout)
File "C:\Python27\lib\site-packages\selenium\webdriver\firefox\firefox_binary.py",
    line 108, in _wait_until_connectable     % (self.profile.path))
selenium.common.exceptions.WebDriverException: Message:
    Can't load the profile. Profile Dir: c:\users\venkat~1.ps\appdata\local\temp\tmpiht1hq
If you specified a log_file in the FirefoxBinary constructor, check it for details.

A: If by latest version you mean the 2.53 you get with pip install selenium, it's a known problem (https://github.com/SeleniumHQ/selenium/issues/2739), this version does not support the last versions of firefox, and it won't be fixed because the dev team focus on the version 3.0 (which works fine).
So you can either :

*

*use another browser

*use an old version of firefox (<=46)

*use the new version of selenium with pip install selenium==3.0.0b3. It should become the default version soon.


text:
Q: Filter and add values using C# using lambda expression New to C# and appreciate any help. The issue is that I need to filter the  results of my api call against an array (using an "allowedA" and "allowedB" array.) I don't know how to edit the lambda expression to check against the loop.
 var activities = await _restClientTaxonomy.GetTaxonomyFullAsync(TAXONOMY_CLASSIFICATIONID_FOR_ACTIVITY);
 var activityTypes = await _restClientTaxonomy.GetTaxonomyFullAsync(TAXONOMY_CLASSIFICATIONID_FOR_ACTIVITY_TYPES);

            var documentEventxx = activities.Select(type => type.Id);

            long [] allowedA = new long []{ 7137, 40385637};
            long [] allowedB = new long []{ 7137, 40385637};

            foreach (long value in documentEventxx)
            {

                foreach (var item in allowed)
                {

                    if (item == value) {
                        //These are the values I am looking for -> values that are part of the documentEventxx and allowedB.
                    }
                }
            }

            var result = activityTypes.Select(type => new CategoryViewModel
            {
                Id = type.Id,//This is where I want to add only items that are in the allowedA array
                Text = type.Name,
                Types = activities.Where(a => a.ParentId == type.Id).Select(t => new TaxonomyMemberTextItem
                {
                    Id = t.Id, //This is where I want to add only items that are in the allowedB array
                    Text = t.Name
                }).ToList()
            }).ToArray();

I have been reading about lambda expressions and foreach loops so please don't just post a random link.
Thanks in advance.

A: Filter the values before Selecting.
            activityTypes.Where(x=>allowedA.Contains(x.Id)).Select(type => new CategoryViewModel
            {
                Id = type.Id,
                Text = type.Name,
                Types = activities.Where(a => a.ParentId == type.Id &&  allowedB.Contains(a.Id)).Select(t => new TaxonomyMemberTextItem
                {
                    Id = t.Id,
                    Text = t.Name
                }).ToList()
            })

A: To filter you use .Where. You .Select to create a list of new types. So in order to filter, then create the lists of objects you want:
var result = activityTypes.Where(type=>isAllowed(type.Id)).Select(type => new CategoryViewModel
{
    Id = type.Id,//This is where I want to add only items that are in the allowedA array
    Text = type.Name,
    Types = activities.Where(a => a.ParentId == type.Id&&isAllowed(a.Id)).Select(t => new TaxonomyMemberTextItem
    {
        Id = t.Id, //This is where I want to add only items that are in the allowedB array
        Text = t.Name
    }).ToList()
}).ToArray();


text:
Q: WebView/AlertView I am using the following code:
- (IBAction)callZH:(id)sender {

UIWebView *callWebview = [[UIWebView alloc] init];
NSURL *telURL = [NSURL URLWithString:@"tel:mynumberhere"];
[callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];

[self.view addSubview:callWebview];
}

The above code works great. However, When user taps button that the above IBAction is connected to, an alert view will automatically pop up showing the Tel# with 2 buttons bellow Tel# cancel or call. How can I set the title above the Tel# in the alert view?

A: Personally, when I want to call, I don't use a webview, but rather I use
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@", phoneNumber]]];

An alert is good practice, so create whatever sort of alert you want with whatever title you want, and if the user chooses to proceed, you can invoke the above code to make the call without any further user-interface interruption.


text:
Q: Can i convert each unique Id of dataframe in list? I have dataframe something like this
| ID   | M001 | M002 | M003 | M004 |
|------|------|------|------|------|
| E001 | 3    | 4    | 3    | 2    |
| E002 | 4    | 5    | 5    | 3    |
| E003 | 4    | 3    | 5    | 4    |

And I want output in list but something like this for each unique ID such E001, E002 i want list of their response in each M001, M002 and so on
My required output is different variable for different id lets say
E001_response = [["M001",3],["M002",4],["M003",3],["M004",2]]

A: Something like that:
new_df = df.apply(lambda x: list(zip(df.columns, x)), axis=1)

Output:
ID
E001    [(M001, 3), (M001, 4), (M001, 3), (M001, 2)]
E002    [(M002, 4), (M002, 5), (M002, 5), (M002, 3)]
E003    [(M003, 4), (M003, 3), (M003, 5), (M003, 4)]
dtype: object

A: You can create Series with lists with custom lambda function:
s = df.set_index('ID').apply(lambda x: list(map(list,zip(df.columns[1:], x))), 1)
print (s)
ID
E001    [[M001, 3], [M002, 4], [M003, 3], [M004, 2]]
E002    [[M001, 4], [M002, 5], [M003, 5], [M004, 3]]
E003    [[M001, 4], [M002, 3], [M003, 5], [M004, 4]]
dtype: object

And then is possible use globals, but better is not create varables by names
for k, v in s.items():
     globals()[f'{k}_response'] = v

print (E001_response)
[['M001', 3], ['M002', 4], ['M003', 3], ['M004', 2]]

Better is create dictionary:
d = s.to_dict()
print (d)
{'E001': [['M001', 3], ['M002', 4], ['M003', 3], ['M004', 2]],
 'E002': [['M001', 4], ['M002', 5], ['M003', 5], ['M004', 3]],
 'E003': [['M001', 4], ['M002', 3], ['M003', 5], ['M004', 4]]}

print (d['E001'])
[['M001', 3], ['M002', 4], ['M003', 3], ['M004', 2]]


text:
Q: Missing header from Qt I'm getting error while compiling qt project which #include's < qvaluelist.h > that this file cannot be find, yet I'm finding on qt website documentation for this header.
How to solve it?

A: This (and its friend QPtrList) are deprecated in Qt 4. You probably have Qt 3 code.
Look here: Porting to Qt 4
You can either link with the QT3 support library in Qt 4 or replace it with QList.


text:
Q: How do I get data items from a complex Nusoap Object coming into php webservice I'm passing a a complex object that is defined on the nusoap server side.
I'm able to declare and access all areas of the objects that are declared over on the nusoap server side after I adding the webservice to my c# client. as seen below.
public void sendArrayOfMHObjects()
    {
        //Steps: Create WS Instance, then create send and recieve objects defined on WS end
        masterH.mhserver mh = new masterH.mhserver();
        masterH.HarvestObject objRequest = new masterH.HarvestObject();
        masterH.ResponseObject objResponse = new masterH.ResponseObject();

        masterH.Stuffs[] stuffsArray = new masterH.Stuffs[2];

     //   stuffsArray[0].id = 4;

        //Populate and request Object
        objRequest.responseCode = 34;
        objRequest.responseMessage = "Whats up docs";

        masterH.Stuffs arrayObject = new masterH.Stuffs();
        arrayObject.id = 6;
         arrayObject.name = "John";

          masterH.Stuffs arrayObject2 = new masterH.Stuffs();
        arrayObject2.id = 7;
         arrayObject2.name = "Johnny boy";

         stuffsArray[0] = arrayObject;
         stuffsArray[1] = arrayObject2;

         objRequest.stuffArray =stuffsArray;

        //Pick up response and display it
        objResponse = mh.sendHarvest(objRequest);

        Console.WriteLine("---------------------------------------------------------------------------");
        Console.WriteLine("Response Code: " + objResponse.responseCode);
        Console.WriteLine("Response Message: " + objResponse.responseMessage);
        Console.WriteLine("---------------------------------------------------------------------------");
        Console.WriteLine("---------------------------------------------------------------------------");

    }

I can verify that the data is getting to the php webservice because I have a response object that is traversed in order to verfiy the data is there on the c# client side.
The problem I have is that I cannot access the array objects on the php side when the object arrives. This is what I have on the php side:
    $server = new soap_server(); $server->configureWSDL("mh-server", "urn:mh-server");
class ResponseObject {
    public $responseCode = -1;
    public $responseMessage = 'Unknown error!';
//    public $stuffArray = NULL;
}

class HarvestObject {
public $responseCode = -1;
public $responseMessage = 'Unknown error!';
public $stuffArray = NULL;
}

class StuffsArray {
public $stuffs = NULL;
}

class Stuffs{
public $id = 23;
public $name = "Larry";
}

$myNamespace = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'];

$server->register("getStuffs", array(),
array('return' => 'tns:ResponseObject'),$myNamespace,  $myNamespace."#getStuffs",
'rpc',  'encoded', 'Fetch array of Stuffs.'
);

$server->register("sendStuffs", array('TheList' => 'tns:ResponseObject'),   array('return' => 'tns:ResponseObject'), $myNamespace,

$myNamespace."#sendStuffs",'rpc', 'encoded',
'Send array of Stuffs.'
);

$server->register("sendHarvest", array('HarvestData' => 'tns:HarvestObject'), array('return' => 'tns:ResponseObject'), $myNamespace,
$myNamespace."#sendHarvest",    'rpc', 'encoded', 'Send Harvest Object.'
);

////////////////////////////////////////////////////WEBSERVICE
STRUCTURES////////////////////////////////////////////////////////////////

////////Response Structure////////////
$server->wsdl->addComplexType('ResponseObject',  'complexType', 'struct', 'all',  '',
array('responseCode' => array('type' => 'xsd:int'),
'responseMessage' => array(     'type' => 'xsd:string')
         )  );

////////Request Structures////////////////////
$server->wsdl->addComplexType('HarvestObject',  'complexType',
'struct', 'all',  '',   array('responseCode' => array('type' => 'xsd:int'),
'responseMessage' => array(   'type' => 'xsd:string'),
'stuffArray'   => array(     'type' => 'tns:StuffsArray' ) )  );

$server->wsdl->addComplexType('StuffsArray', 'complexType', 'array',
'','SOAP-   ENC:Array', array(), array( array('ref' => 'SOAP-ENC:arrayType',
'wsdl:arrayType' => 'tns:Stuffs[]' ) ),'tns:Stuffs'  );

$server->wsdl->addComplexType('Stuffs','complexType','struct','all','',
array( 'id' =>   array('name' => 'id', 'type' => 'xsd:int'),
'name' => array('name' => 'name', 'type' => 'xsd:string') )  );

$server->service(isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '');

/////////////////////////////////////
    ///////////////////////////////////////
    //EXPOSED WEBSERVICE   METHODS//////////////////////////////////
    /////
function sendHarvest($harvestTemp) {

$harvestObject= new HarvestObject();
$harvestObject= $harvestTemp;
$harvestArray = array();
$harvestArray=$harvestObject->stuffArray;

$harvestItems = new Stuffs();

$responseObject = new ResponseObject();
$responseObject->responseCode=0;
$responseObject->responseMessage= $tempID.$tempName;

return $responseObject;
}

At this point I've tried just about everything, and the last response I got was a null value being retured when I try to just build a concatenated string with the elements I want to extract. The items I need from the incoming array of objects are the id and name values.
Please help if you can thanks.


text:
Q: Python class is subscriptable but not iterable I am trying to expose the classes dictionary making it both and subscriptable and be able to iterate through the dict values. Here is the class :
class ExampleClass():
    def __init__(self, *args, **kwargs):
        for key, value in self.kwargs.items():
            setattr(self, key, value)
        for arg in args:
            setattr(self, arg, arg) if isinstance(arg, str) else setattr(self, str(arg), arg)
    def __str__(self):
        return 'This is the example class'
    def __getitem__(self, obj):
        return self.__dict__[obj]
    def __len__(self):
        return len(self.__dict__.items())

If we create an instance and pass in these values :
cls = ExampleClass(123456,'cash', name='newexample', id=1)

This will store all of the args and kwargs as instance attributes, and using the syntax cls['id'] will return 1 as expected. But when I use the syntax for i in cls: print(i) I get a KeyError : KeyError : 0
How can I make this object's dict both subscriptable and iterable ?

A: You need to implement the __iter__ method.
class ExampleClass():
    def __init__(self, *args, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)
        for arg in args:
            setattr(self, arg, arg) if isinstance(arg, str) else setattr(self, str(arg), arg)
    def __str__(self):
        return 'This is the example class'
    def __getitem__(self, obj):
        return self.__dict__[obj]
    def __len__(self):
        return len(self.__dict__.items())
    def __iter__(self):
        return iter(self.__dict__)

cls = ExampleClass(123456,'cash', name='newexample', id=1)
print(cls['cash'])
print(cls['name'])
for i in cls: print(i)

This is the method which is called to create an iterator for your type so that it can be iterated. Your underlying dict already implements it, so you're sort of just proxying it here.

A: To make a class subscriptable, it must contain dunder getitem(), it may or may not contain dunder iter().
At the same time, an iterable must contain iter().
To check if your class has the required method, perform print(dir(your_class)), and look for the respective dunder function.
If you don't have one, create it.


text:
Q: Task stops working on different environment I'm having hard time with this one.
So in my asp.net application there is such a method:
public CopyResponse thirdStage(CopyRequest request)
{
    CopyCCResponse response = new CopyCCResponse();

    Task.Run(() =>
    {
        performCopying(request);
    });

    return response;
}

private void performCopying(CopyCCRequest request)
{
    using (Repository = new myDbContext())
    {
        // do some initial action
        try
        {
        // in general it looks like below
            foreach(var children in father)
            {
                var newChildren = chldren.Copy();
                Repository.Childrens.Add(newChildren);

                foreach (var grandchldren in children.grandchildrens)
                {
                    var newGrandchildren = grandchldren.Copy();
                    newGrandchildren.Parent = newChildren;

                    Repository.Grandchildrens.Add(newGrandchildren);
                }

                Repository.SaveChanges();
            }
        }
        catch (Exception ex)
        {
            // log that action failed

            throw ex;
        }
    }
}

This method and all other (there are some similar) works as designed on my local computer without any problems.
Unfortunately, on another environment those methods fail:

*

*Copying smaller parts of data works fine. But when there is over 3000 objects to operate on, method fails.

*Main application is responding correctly nevertheless.

*Most of the operation is done well (most data is copied and saved in database)

*Application doesn't enter catch block. Instructions for failed copying are not executed. Exception isn't caught by the error handler (BTW, I know by default the app can't catch exceptions from independent task, I wrote my handler so it will manage to do so).

*IIS worker process seems to take over 300MB and 0% of processor power after copying stopped. More than half of RAM on server is still free.

*I looked into windows event log, but haven't found anything.

Do you have any suggestions how I can handle this issue?

A: You can't do reliable "Fire and forget" tasks from inside IIS, if the site is not being served the application pool will get its AppDomain shut down after a while.
Two options to use are:
HostingEnvironment.QueueBackgroundWorkItem to tell IIS you are doing background work. This will let the server know of the work and it will delay the shutdown as long as it can (default up to 90 seconds max) before it kills your process.
public CopyResponse thirdStage(CopyRequest request)
{
    CopyCCResponse response = new CopyCCResponse();

    HostingEnvironment.QueueBackgroundWorkItem(() =>
    {
        performCopying(request);
    });

    return response;
}

Another option is to use a 3rd party library that is designed for doing background work in IIS like Hangfire.io, this will run a service inside of IIS that does the work and attempts to keep the instance alive till the work is done. You can also configure Hangfire to run as a separate process so you don't need to rely on the lifetime of the IIS instance.
public CopyResponse thirdStage(CopyRequest request)
{
    CopyCCResponse response = new CopyCCResponse();

    BackgroundJob.Enqueue(() =>
    {
        performCopying(request);
    });

    return response;
}

Note, using hangfire with a seperate process may require you to do a little redesign of performCopying(CopyCCRequest request) to support being run from a separate process, using it from inside the IIS instance should not require any changes.


text:
Q: How to add and concate two variables in same list array = [[1676, 196, 159, 29, 'invoice'], [1857, 198, 108, 28, 'date:']]

width = 159+108 = 267
height = 29+28 = 57
label = invoice date:

Required solution: [1676, 196, 267, 57, 'invoice date:']

Is there any solution to concatenate string and add numbers in same list

A: Assuming your other lines are for your own notes/testing, and your "required solution" is a typo, you can use zip like so:
array = [[1676, 196, 159, 29, 'invoice'], [1857, 198, 108, 28, 'date:']]

res = []

for x, y in zip(array[0], array[1]):    # compare values at each index
    if isinstance(x, str):              # check to see if x is a string
        res.append(x + ' ' + y)         # add a space if x is a string
    else:
        res.append(x + y)               # add the two integers if x is not a string

print(res)

[3533, 394, 267, 57, 'invoice date:']

Note that the concatenation above will only work if you are sure that the same indices will have strings vs. integers.


text:
Q: income distribution champagne glass in tikz I was trying to draw this or this. However, it is really hard for me to create the concave part of these images and seperate the picture into 5 equal parts.

A: Drawing with Bézier curves can take a bit of getting used to, and may involve some trial and error when trying to code curves in tikz rather than drawing them using a vector graphics program.
The following shows how I got what appears to be the required shape. The show curve controls decoration is only there to illustrate the control points I used.
\documentclass[tikz,border=0.125cm]{standalone}
\usetikzlibrary{decorations.pathreplacing}

\tikzset{
  show curve controls/.style={
    decoration={
      show path construction,
        curveto code={
          \draw [gray, thick]
            (\tikzinputsegmentfirst)
            .. controls (\tikzinputsegmentsupporta) and (\tikzinputsegmentsupportb) .. (\tikzinputsegmentlast);
          \draw [red, thick]
            (\tikzinputsegmentfirst) -- (\tikzinputsegmentsupporta);
          \draw [red, thick]
            (\tikzinputsegmentsupportb) -- (\tikzinputsegmentlast);
          \fill [black]
            (\tikzinputsegmentfirst) circle [radius=2pt]
            (\tikzinputsegmentlast)  circle [radius=2pt];
          \fill [blue]
            (\tikzinputsegmentsupporta) circle [radius=2pt]
            (\tikzinputsegmentsupportb)  circle [radius=2pt];
        }
      },
   decorate}
}

\begin{document}

\begin{tikzpicture}
\draw [help lines] (-5,0) grid (5,10);
\path  [fill=gray!20, fill opacity=0.5, postaction=show curve controls]
    (-5,10)
    .. controls ++(270:2) and ++(100:4) .. (-1/2,6)
    .. controls ++(280:1) and ++(90:2)  .. (-1/4,0)
    -- (1/4,0)
    .. controls ++(90:2) and ++(260:1) .. (1/2, 6)
    .. controls ++(80:4) and ++(270:2) .. (5,10) -- cycle;
\end{tikzpicture}

\end{document}

A: You may use some LaTeX/PSTricks packages for chemists as explained by Denis Girou and retransmitted by
Benjamin Collas. They may be difficult to integrate in tikz. Here is an example from page 50 (25 of PDF):
\usepackage{pst-labo}
\pstChauffageBallon[glassType=flacon,recuperationGaz,
tubeRecourbeCourt,substance={\pstFilaments[10]{gray}}]

You may also use pst-plot, or pst-text, see page 49 of same link.


text:
Q: .mobi is it worth it? Where is .mobi headed? Will the mobile devices use proprietary browsers that simplify a .com site or are they going to use browsers on a .mobi basis? I have a feeling it will be a flop... not sure though.
Thanks

A: My feeling is that smart phone browsers are getting more and more like desktop browsers, so the whole concept of .mobi is flawed from the start.  Plus, a lot of sites can now detect that you're using an inferior browser and redirect you automatically to a less functional version of their web site - no special domains required.
If you're programming a web site, wouldn't it be simpler just to have an internal redirection for mobile phone browsers than to have to maintain a whole different domain?  Especially if you can programattically derive the mobile version from the non-mobile version, either on the fly or whenever you delivery content?

A: .Mobi is worthwhile if you do not own or cannot afford to buy a your ideal .com domain. You can get massively more bang for your buck with a mobi domain. Let's say you need a site to promote your app, you can often just register the exact name as a mobi domain for registration price or a low price if its already taken. Meanwhile typically the .com will almost certainly be taken already and the current owner may think this domain is worth a ridiculous amount of money. Then, if you absolutely want the .com, you end up going for another less optimal .com domain.
My view is, that the exact and memorable, cheap mobi domain, is better, than the expensive or non-exact .com domain.
If you already have your domain, then you don't really need a .mobi.


text:
Q: Microsoft Access database connection using XMLHTTP In
Creating a Microsoft Access database connection to a REST-based API
on this line...
httpReq.Open "GET", "http://whois.arin.net/rest/poc/KOSTE-ARIN", False

I noticed that he points to rest/poc/KOSTE-ARIN.
My question is "Is this a file of sorts? or is it a service?" I am trying to achieve the same thing in my access application.

A:
"Is this a file of sorts? or is it a service?"

It is an endpoint for a web service (in this case, a RESTful web service). It is the web address from which we can retrieve the information for a particular person (whose ID is 'KOSTE-ARIN') in the ARIN database.
Whether you think of it as retrieving a "file" or as retrieving "the result of a database query" the effect is the same: You send the GET request to that particular address (endpoint) and the server returns a big long string containing Mr. Kosters' information.


text:
Q: How to use CNN-LSTMs to classify image sequences for multiple bounding boxes in a video stream? I am working on a pytorch project, where I'm using a webcam video stream. An object detector is used to find objects within the frame and each box is given an id by a tracker. Then, I want to analyse each bounding box with a CNN-LSTM and classify it (binary classification) based on the previous frame sequence of that box (for the last 5 frames). I want the program to run a close to real-time as possible.
Currently I am stuck with the CNN-LSTM part of my problem - the detector and tracker are working quite well already.
I am a little bit clueless on how to approach this task. Here are the questions I have:
1) How does inferencing work in this case? Do I have to save np arrays for each bounding box containing the last 5 frames, then add the current frame and delete the oldest one? Then use the model for each bounding box that is in the current frame. This way sounds very slow and inefficient. Is there a faster or easier way?
2) Do you have any tipps for creating the dataset? I have a couple of videos with bounding boxes and labels. Should I loop through the videos and save save each frame sequence for each bounding box in a new folder, together with a csv that contains the label? I have never worked with an CNN-LSTM, so I don't know how to load the data for training.
3) Would it be possible to use the extracted features of the CNN in parallel? As mentioned above, The extracted features should be used by the LSTM for a binary classification problem. The classification is only needed for the current frame. I would like to use an additional classifier (8 classes) based on the extracted CNN features, also only for the current frame. For this classifier, the LSTM is not needed.
Since my explaining propably is very confusing, the following image hopefully helps with understanding what I want to build:
Architecture
This is the architecture I want to use. Is this possible using Pytorch? So far, I only worked with CNNs and LSTM seperately. Any help is apprechiated :)


text:
Q: script does not stop when arguments are passed I have the following which works perfectly.
#!/bin/bash

killall java
#program USB
make iris install.1 mib510,/dev/ttyUSB0
#listen serial port and write to file
java net.tinyos.tools.PrintfClient -comm serial@/dev/ttyUSB1:iris > foo.txt &
sleep 2
#if "Erase done" is printed to file, stop
if tail -f foo.txt | grep -n "Erase done" -q; then echo "Write ok";fi
killall java

But when I change my script to receive arguments below (sh test.sh USB0 USB1 foo.txt), it does not end. Although it writes the file, the process does not end
#!/bin/bash

killall java
#program USB
make iris install.1 mib510,/dev/tty$1
#listen serial port and write to file
java net.tinyos.tools.PrintfClient -comm serial@/dev/tty$2:iris > $3 &
sleep 2
#if "Erase done" is printed to file, stop
if tail -f $3 | grep -n "Erase done" -q; then echo "Write ok";fi
killall java

Am I doing something wrong?

A: It appears tail -f will quit when grep quits. So the problem might be with:
if tail -f $3 | grep -n "Erase done" -q; then echo "Write ok";fi

You can replace it with the following:
tail -f $3 | while read LOGLINE
do
   [[ "${LOGLINE}" == *"Erase done"* ]] && echo "Write ok" && pkill -P $$ tail
done


text:
Q: jQuery remove elements one by one I try to do upload sistem and use Uploadify. I have onComplete function where apend images and remove buttons. Every image have own remove button, but I can't make it to remove just its image. Please help here is the code what I have. Thanks.
enter code here
'onComplete'  : function(event, ID, fileObj, response, data) {

    $('#inner2').append('
Remove Image
');

    $("#remove-btn").live('click',function() {

        $(this).parent().remove();

    });

}

A: Try selecting the previous image. That is, previous to the clicked div:
$(this).prev("img").andSelf().remove();

A: $(this).parent().find('your image tag here').remove();

A: $(this).prev().remove();
$(this).remove();

As i guess you also want to remove the button as it is for an image that isnt there anymore.
Or you could wrap the image and button in a div then your .parent() is fine.


text:
Q: Insert Image into a Google Sheet with Apps Script using base64 encoded data Given some base64 encoded data for a png file, as in the example below from the image tag.
<img src="data:image/png;base64,R0lGODlhDAAMAKIFAF5LAP/zxAAAANyuAP/gaP///wAAAAAAACH5BAEAAAUALAAAAAAMAAwAAAMlWLPcGjDKFYi9lxKBOaGcF35DhWHamZUW0K4mAbiwWtuf0uxFAgA7">

I need to create an image blob from the base64 encoded data for the insertImage() method.
sheetClass.insertImage(imageBlob, column, row)

Documentation:
Sheets Class - insertImage method
I've tried using the code below, but it throws the error:

Execution failed: Error retrieving image from URL or bad URL

The documentation states that the method needs a blob, not a URL, but it seems like it's expecting a link to an image file.
function insertImageFromBase64Src() {
  var data = 'R0lGODlhDAAMAKIFAF5LAP/zxAAAANyuAP/gaP///wAAAAAAACH5BAEAAAUALAAAAAAMAAwAAAMlWLPcGjDKFYi9lxKBOaGcF35DhWHamZUW0K4mAbiwWtuf0uxFAgA7';

  var imageBlob = Utilities.newBlob(Utilities.base64Decode(data), 'image/png').getBytes();

  var ss = SpreadsheetApp.getActiveSpreadsheet();//This code is bound to a Sheet

  var po = {
    shName:'Update File',
    column:1,
    row:37
  }

  var sh = ss.getSheetByName(po.shName);

  var image = sh.insertImage(imageBlob, po.column, po.row);//Insert an image and return the image
}

A: How about this modification?
Modification points:

*

*insertImage can use the blob and URL which is the direct link of the image file.

*

*In your script, imageBlob is an byte array which is "number[]". By this, I think that an error occurs.

*Please add the name to the blob.

*

*When the name is not given, an error occurs.

Modified script:
When your script is modified, it becomes as follows.
function insertImageFromBase64Src2() {
  var data = 'R0lGODlhDAAMAKIFAF5LAP/zxAAAANyuAP/gaP///wAAAAAAACH5BAEAAAUALAAAAAAMAAwAAAMlWLPcGjDKFYi9lxKBOaGcF35DhWHamZUW0K4mAbiwWtuf0uxFAgA7';

  var imageBlob = Utilities.newBlob(Utilities.base64Decode(data), 'image/png', 'sample');  // Modified

  var ss = SpreadsheetApp.getActiveSpreadsheet();  //This code is bound to a Sheet

  var po = {
    shName:'Update File',
    column:1,
    row:37
  }

  var sh = ss.getSheetByName(po.shName);

  var image = sh.insertImage(imageBlob, po.column, po.row);//Insert an image and return the image
}

*

*In this modification, it supposes that data can be correctly decoded.

References:

*

*insertImage(blobSource, column, row)

*insertImage(url, column, row)
If this was not the direct solution of your issue, I apologize.


text:
Q: Using StackLayout with Grid pushes my button outside the screen I am trying to get my button with the text "I am causing problems" at the bottom right side of my page, but it is being pushed out of the screen on my emulator.
I have read the documentation about StackLayout and looked up alike questions on StackOverflow and this is the closest I have come... Without success unfortunately.
I have not used any CSS and I would prefer to not use it, if not needed.

<ContentPage>//STANDARD CONTENTPAGE STUFF SUCH AS XMLS TAKEN OUT

<ContentPage.ToolbarItems>
    <ToolbarItem Priority="0" Order="Primary" Text="{Binding Inter}" />
</ContentPage.ToolbarItems>

<ContentPage.Content>
    <StackLayout FlexLayout.Grow="1" Margin="10">
        <CollectionView ItemsSource="{Binding Cb}">
            <CollectionView.ItemsLayout>
                <GridItemsLayout
                    Orientation="Vertical"
                    Span="2"
                    VerticalItemSpacing="5"
                    HorizontalItemSpacing="5"/>
            </CollectionView.ItemsLayout>
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Button Text="{Binding Text}" CommandParameter="{Binding CommandParameter}" Command="{Binding Command}" HeightRequest="75" />
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
        <CollectionView ItemsSource="{Binding Msg}">
            <CollectionView.ItemsLayout>
                <GridItemsLayout
                    Orientation="Vertical"
                    Span="2"
                    VerticalItemSpacing="5"
                    HorizontalItemSpacing="5"/>
            </CollectionView.ItemsLayout>
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Label Text="{Binding .}" />
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="80*"></ColumnDefinition>
                <ColumnDefinition Width="20*"></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <StackLayout Grid.Row="0" Grid.Column="1" HorizontalOptions="Center">
                <ButtonText="I am causing problems!"></Button>
            </StackLayout>
        </Grid>
    </StackLayout>
</ContentPage.Content>

A: Welcome Dom. The problem derives from overcomplicating your xaml/ui. If you were to remove your the Grid that contains your button and just replace it with a plain button. You can style that button to fit as needed in your UI.
If you repace the Grid-with-button with just a button then it automatically becomes a direct child of the StackLayout. Now give the Button a Height of 100 and a HorizontalOptions of End and you will probably get what you were looking for with your button.
I've added an image and the code so it's easy for you to replicate. Thanks foryour question and goodluck with your programming endeavors.

And here's your code.
<StackLayout FlexLayout.Grow="1" Margin="10">
        <CollectionView ItemsSource="{Binding Cb}">
            <CollectionView.ItemsLayout>
                <GridItemsLayout
                    Orientation="Vertical"
                    Span="2"
                    VerticalItemSpacing="5"
                    HorizontalItemSpacing="5"/>
            </CollectionView.ItemsLayout>
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Button Text="{Binding Text}"
                            CommandParameter="{Binding CommandParameter}"
                            Command="{Binding Command}"
                            HeightRequest="75" />
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
        <CollectionView ItemsSource="{Binding Msg}">
            <CollectionView.ItemsLayout>
                <GridItemsLayout
                    Orientation="Vertical"
                    Span="2"
                    VerticalItemSpacing="5"
                    HorizontalItemSpacing="5"/>
            </CollectionView.ItemsLayout>
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Label Text="{Binding .}" />
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
        <Button Text="test knop met text" HeightRequest="100"
                HorizontalOptions="End"/>
</StackLayout>


text:
Q: xml to matching rows with xsl I need help with transforming my xml to a html table with two columns with matching rows. My xml-tei file structure for the columns
<?xml version="1.0" encoding="UTF-8"?>
<TEI xmlns="http://www.tei-c.org/ns/1.0">
<teiHeader></teiHeader>
<text>

<hi rend="underline">Sjudubaeots'oh</hi>

<lg>
<l n="1">Jaanguoi<add place="above">goj</add> ninje</l>
<l n="2"><add place="top">Njaar piev<add
place="above">b</add>es</add></l>
<l n="3">Njaar jan|deata</l>
<l n="4">Opoj habidoo</l>
<l n="5">Tab<add place="above">b</add>adooda habih</l>
<l n="6">Njaar jan|deata</l>
</lg>

<lg>
<l n="1" xml:lang="ru">На земили хребты</l>
<l n="2"><add place="top">три братев</add></l>
<l n="3" xml:lang="ru">Три на<note resp="#MAC" place="top" xml:lang="swe">på jorden ej så rika</note> землы оленщик<note resp="#MAC"
place="above">Deatáh, оленщикъ</note> (богатые)</l>
<l n="4" xml:lang="ru">одинъ работник у ихъ</l>
<l n="5" xml:lang="sw">På песачиый<add
place="above">худий</add> слуга <note resp="#MAC">(namn) d.ä hans pimi  äro vardsrlösa, utan band, hänga ned (<hi rend="underline">tabbaltaa</hi>)
</note></l>
<l n="6" xml:lang="sw">Af de tre bröder</l>
</lg>

</text>
</TEI>

I need a table with two columns, which would have lines matching each other. The place of the line inside lg is determining (rather than the n of the line).
This is what I tried, based on the code proposed. It produced only one column with text in column 1 following the text in column 2. I do apologize my previous question, which showed the initial xml too simple, and probably produced the confusion. Obviously, I am quite ignorant in xslt, but all the more hope you could help me.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema" version="3.0">
<xsl:output method="html" html-version="4.0"/>
<xsl:template match="TEI/text/body/div[div[starts-with(@type, 'column')]]">

<xsl:value-of select="head[@n='1']"/>

<xsl:variable name="row-count" select="count(div[1]/lg/l)"/>
<xsl:for-each-group select="div/lg/l" group-by="position() mod $row-count">

<xsl:apply-templates select="current-group()"/>

</xsl:for-each-group>

</xsl:template>
<xsl:template match="l">
{ . }
</xsl:template>
</xsl:stylesheet>

A: It seems you can group the l elements on the n attribute:
  <xsl:template match="*[div[starts-with(@type, 'column')]]">

          <xsl:for-each-group select="div/lg/l" group-by="@n">

                  <xsl:apply-templates select="current-group()"/>

          </xsl:for-each-group>

  </xsl:template>

  <xsl:template match="l">
      { . }
  </xsl:template>

Full XSLT 3 example at https://xsltfiddle.liberty-development.net/3NzcBtN.
As an alternative you can use positional grouping:
  <xsl:template match="*[div[starts-with(@type, 'column')]]">

          <xsl:variable name="row-count" select="count(div[1]/lg/l)"/>
          <xsl:for-each-group select="div/lg/l" group-by="position() mod $row-count">

                  <xsl:apply-templates select="current-group()"/>

          </xsl:for-each-group>

  </xsl:template>

  <xsl:template match="l">
      { . }
  </xsl:template>

XSLT 3 sample at https://xsltfiddle.liberty-development.net/3NzcBtN/2, the HTML table markup produced there is

        abc
        lmn

        efg
        opq

        hij
        rst

        4
        4

which looks like
abc lmn
efg opq
hij rst
4   4


text:
Q: Stress Tensor and the ubiquitous cube: a misrepresentation? So I'm just learning about Stress Tensors and have had an on going confusion and I'm wondering if the cube diagrams may to be blame. Usually when a stress tensor is introduced they show a cube and explain that the corresponding 9 components of the stress tensor represent the the 9 strains on the 3 faces of the cube that one can see.
But if we are considering the possible forces on the faces of a cube, I would want there to be 18 components, that is, 3 components for each of the 6 faces. So I'm wondering if the cube diagram is really just an over simplification to try and give some intuition to students who won't delve into the mathematical details.
I'm wondering this because I finally came across direct reference to Cauchy's stress theorem which explains how the stress across any plane through the point in question can be determined by knowing the stresses on the 3 perpendicular planes. This seems like it would provide the 9 components.
So is my thinking correct? Is the cube not really an accurate portrayal of the underling mathematics?


text:
Q: sha1hash not working, Error in hash. I'm all new to hashes and encryption. What I'm trying to do is to access an API which requires hashing of some variables beforehand, now my hash somehow isn't correctly outputted.
The hash is to be in the following format:

Hash is a sha1hash SHA1 ( CallerID + Time + key + unique) as a 40 -
  char hexadecimal, eg " 6b76a4ede12897d42dabc2a5f9270bbdb76985af "
  where key is the private key you assigned.

I assume the "+" signs in the text assume concatenating. Still, following the instructions and using the digest package something is wrong with my hash, although length of all variables match the instructions. Hash error is verified by using: http://www.hashkiller.co.uk/sha1-decrypter.aspx, which generated an error for my hash, also the HTTP GET query generate 403 error with hash error text.
My Code
library(httr)
library(digest)
library(stringi)

BooliReq  <- function() {

  #ID Info
  key  <- "PRIVATEKEY"
  caller.ID  <- "IDName"
  #//

  unix.timestamp  <- as.integer( as.POSIXct(Sys.time()) )
  random.string  <- stri_rand_strings( n = 1, length = 16)

  #Sha1-Hash: CallerID + time + key + unique, 40-char hexadecimal
  hash.string  <- paste0(caller.ID, unix.timestamp, key, random.string)
    hash.sha1  <- digest(hash.string, "sha1")

  #Create URL
  url.string  <- paste0("https://api.booli.se/listings?q=nacka&limit=3&offset=0&callerId=", caller.ID, "&time=" ,
                        unix.timestamp, "&unique=", random.string, "&hash=", hash.sha1)

  GET(url.string, add_headers( Accept = "json"))

}

Link to API:

https://translate.google.se/translate?sl=sv&tl=en&js=y&prev=_t&hl=sv&ie=UTF-8&u=https%3A%2F%2Fwww.booli.se%2Fapi%2F%23pagination&edit-text=&act=url

A: You need to set serialize=FALSE, otherwise the input string will be first serialized and then the hash computed (so you won't get the hash of the string... check the results for example using this online sha1 generator: link)
digest(hash.string, "sha1", serialize=FALSE)


text:
Q: How to put an image resized with Pillow into GridFS? Scenario
I use a formData form to upload an image via ajax which is then added to a MongoDB GridFS database.
This was working:
my_image = request.files.my_image
raw = my_image.file.read()
fs.put(raw)

Desired Behaviour
I want to resize the image with Pillow before adding to GridFS.
What I Tried
I changed the above to:
my_image = request.files.my_image
raw = Image.open(my_image.file.read())
raw_resized = raw.resize((new_dimensions))
fs.put(raw_resized)

Actual Behaviour
I am now getting 500 errors. Tail shows:
TypeError: file() argument 1 must be encoded string without NULL bytes, not str

Question
How do I properly handle the Pillow image object so that I can add it to GridFS?
Troubelshooting
This is still unresolved, but I'm just adding my attempts to understand what is happening with file types etc at different stages of the process by using the interpretor:
>>> my_image = open("my_great_image.jpg")
>>> my_image
<open file 'my_great_image.jpg', mode 'r' at 0x0259CF40>
>>> type(my_image)
<type 'file'>
>>> my_image_read = my_image.read()
>>> my_image_read
# lots of image data
>>> type(my_image_read)
<type 'str'>
>>> my_pil_image = Image.open("my_great_image.jpg")
>>> my_pil_image
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=400x267 at 0x2760CD8>
>>> type(my_pil_image)
<type 'instance'>

So from this I think I can deduce that, originally, GridFS was accepting of the string version of the image generated from the read() method.
So I think I need to somehow make the Pillow image object a string in order to get it into GridFS.

A: Solution
Wo, check this out, it works, the logic is:

*

*Form uploads image,

*Pillow does three different resizes,

*Use StringIO to convert Pillow objects to strings

*Put resized images, as strings, in GridFS.

Python
from PIL import Image
import StringIO

# define three new image sizes
card_dimensions = (108,108)
main_dimensions = (42,38)
thumb_dimensions = (18,14)
# covert uploaded image to Pillow object
raw_pil = Image.open(my_image.file)
# conversion to card size
raw_card_output = StringIO.StringIO()
raw_card = raw_pil.resize((card_dimensions))
raw_card.save(raw_card_output,format=raw_pil.format)
raw_card_output_contents = raw_card_output.getvalue()
# conversion to main size
raw_main_output = StringIO.StringIO()
raw_main = raw_pil.resize((main_dimensions))
raw_main.save(raw_main_output,format=raw_pil.format)
raw_main_output_contents = raw_main_output.getvalue()
#conversion to thumb size
raw_thumb_output = StringIO.StringIO()
raw_thumb = raw_pil.resize((thumb_dimensions))
raw_thumb.save(raw_thumb_output,format=raw_pil.format)
raw_thumb_output_contents = raw_thumb_output.getvalue()
# put card image into GridFS
fs.put(raw_card_output_contents)
# put main image into GridFS
fs.put(raw_main_output_contents)
# put thumb image into GridFS
fs.put(raw_thumb_output_contents)

Further Explanation
Basically I deduced that GridFS was accepting a string, so therefore I needed to transform the Pillow object into a string.
The interpreter troubleshooting below should make some of the dynamics clearer and carries on from the troubleshooting in the original post:
>>> my_pil_image
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=400x267 at 0x2760CD8>
>>> my_pil_image_resized = my_pil_image.resize((50,50))
>>> my_pil_image_resized
<PIL.Image.Image image mode=RGB size=50x50 at 0x2898710>
>>> output = StringIO.StringIO()
>>> my_pil_image_resized.save(output,format="JPEG")
>>> contents = output.getvalue()
>>> type(contents)
<type 'str'>
>>> contents
# lots of image data

So basically the above process show the mechanics of how to convert the Pillow object into a string which can then be added to GridFS.

A: I just got a simple way to do this with flask.
I am using FileStorage for file holder before uploading to gridFS.
It also help me to wrap image from pillow after resize.
Document looks like this.
from mongoengine import Document ImageField

class SomeDocument(Document):
    icon = ImageField(required=False, collection_name="collection_name")

And the controller is
from io import BytesIO
from werkzeug.datastructures import FileStorage
from PIL import Image

im = Image.open(request.files.get('icon'))
im.thumbnail((400, 400))

output = BytesIO()

im.save(output, format=im.format, quality=90)

original_extension = request.files.get('icon').filename.rsplit('.', 1)[1].lower()

SomeDocument.icon.put(FileStorage(output, content_type=f"image/{original_extension"))
SomeDocument.save()
im.close()


text:
Q: cannot compare arraylist values in android i am creating an android application in which i want to access database from mysql for user name, phone no and email address. and i want to compare phone no from android phone contact list and the phone no getting from mysql database. for that purpose i use 2 arraylist 1st for phone contact and 2nd for mysql phone no.
my main problem is when i compare both the arraylist then i shows no result.
i attach here the code please someone help me to solve this problem.
public class PhoneNoActivity extends Activity{
    JSONArray jArray,jArray1;
    JSONObject jobj;
    String result = null,phone=null;
    InputStream is = null;
    StringBuilder sb=null;
    double lat=0;
    double lon=0;
    String user=null;
    ArrayList<NameValuePair> nameValuePairs;

    ListView lv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        String phno=null;
        ArrayList<String> cntPhone=new ArrayList<String>();
        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        if (cur.getCount() > 0) {
            while (cur.moveToNext()) {
                String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                    Cursor pCur = cr.query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", new String[]{id}, null);
                    while (pCur.moveToNext()) {
                        String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        if(phoneNo.length()>10) {
                            phno=phoneNo.subSequence(phoneNo.length()-10, phoneNo.length()).toString();
                            // Log.e(name, phno);
                        }
                        cntPhone.add(phoneNo);
                    }
                    pCur.close();
                }
            }
        }

        ArrayList<String> cntOnline=new ArrayList<String>();
        try {
            nameValuePairs = new ArrayList<NameValuePair>();

            /*String phone=null;
            for(int k=0;k<=cntPhone.size();k++) {
                Log.e("k",k+"");
                phone=cntPhone.get(k);
                nameValuePairs.add(new BasicNameValuePair("phone", phone));
            */
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://10.0.2.2/ah_login_api/select.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            sb = new StringBuilder();
            sb.append(reader.readLine() + "\n");

            String line="0";
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result=sb.toString();

            Log.e("result=", result);
            jArray = new JSONArray(result);
            JSONObject json_data=null;
            for(int i=0;i<jArray.length();i++){
                json_data = jArray.getJSONObject(i);
                user=json_data.getString("user");
                phone=json_data.getString("phone");
                lat=json_data.getDouble("email");

                cntOnline.add(phone);
            }
            for(String s:cntOnline) {
                for(String s1:cntPhone ) {
                    if(s.equals(s1)) {
                        Log.e("match found", phone);
                    }
                }
            }
            /*
                for(int l=0;l<cntOnline.size();l++) {
                    Log.e("loop start", ""+l);
                    for(int k=0;k<cntPhone.size();k++) {
                        if(cntPhone.get(k).trim().equals(cntOnline.get(l).trim())) {
                            Log.e("match found", phone);
                        }
                    }
                }*/
        //}
        } catch(Exception ex) {
            Log.e("Exception  in ",ex.toString());
        }
    }
}

and this is my php code from which i access details
<?php
    mysql_connect("localhost","root","");
    mysql_select_db("MyContact");
    $sql=mysql_query("select * from newuser");
    while($row=mysql_fetch_assoc($sql))
        $output[]=$row;
    print(json_encode($output));
    mysql_close();
?>

A: /* Retrieves phone numbers from Phone Contact List */
public ArrayList<String> getNumber() {
    String phoneNumber;
    ArrayList<String> contact_number = new ArrayList<String>();
    ContentResolver cr = getApplicationContext().getContentResolver();
    Cursor phones = cr.query(
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
            null, null);
    while (phones.moveToNext()) {
        phoneNumber = phones
                .getString(phones
                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

        System.out.println(".................." + phoneNumber);
        contact_number.add(phoneNumber);
    }
    phones.close();
    return contact_number;
}

/* Gets the Numbers from MySQL database using object "Contact" and Compares it with the method "getNumber()" which retrieves phone numbers from Phone Contact List */
@SuppressWarnings("unused")
private Contact convertContact(JSONObject obj) throws JSONException {
    Contact contact = new Contact();
    String name = obj.getString("user_name");
    String mobile_no = obj.getString("mobile_no");

    boolean isMatched = false;
    contact_number = getNumber();
    for (int i = 0; i < contact_number.size(); i++) {
        if (mobile_no.equals(contact_number.get(i))) {
            isMatched = true;
            contact.setName(name);
            contact.setMobileNo(mobile_no);

        }
    }
    return isMatched ? contact : null;

}

/* If the number from database matches with the phone contact list add and generate in listview */
private class AsyncTasak extends
        AsyncTask<String, Void, ArrayList<Contact>> {

    @Override
    protected void onPostExecute(ArrayList<Contact> result) {
        super.onPostExecute(result);
        arrayadapter.setItemList(result);
        arrayadapter.notifyDataSetChanged();

    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected ArrayList<Contact> doInBackground(String... params) {
        ArrayList<Contact> result = new ArrayList<Contact>();

        try {
            URL u = new URL(params[0]);

            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
            conn.setRequestMethod("GET");

            conn.connect();
            InputStream is = conn.getInputStream();

            byte[] b = new byte[1024];
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            while (is.read(b) != -1)
                baos.write(b);

            String JSONResp = new String(baos.toByteArray());

            JSONArray arr = new JSONArray(JSONResp);
            for (int i = 0; i < arr.length(); i++) {
                Contact temp = convertContact(arr.getJSONObject(i));
                if (temp != null) {
                    result.add(temp);
                }
            }

            return result;
        } catch (Throwable t) {
            t.printStackTrace();
        }
        return null;
    }


text:
Q: Custom Campaigns with Google Tag Manager I used to work with Google Analytics and build Custom Campaigns with the Campaign URL Builder.
Once I've moved to Google Tag Manager, I've stopped seeing any new campaigns in my Google Analytics page.
some facts:

*

*No I'm not an idiot, and I've triple checked that I'm building the URL right in the Campaign Builder. (https://ga-dev-tools.appspot.com/campaign-url-builder/)

*Again, I'm not an idiot, there are no Filters In my GA which hides all the new Campaigns.

*I'm getting this error in my GA page:
"Property betzavta.me is not receiving hits. Either your site is not receiving any sessions or it is not tagged correctly."
=> though all the other GA functionalities are working currectly (Events, logged users, Real Time data and so on...)

*I did install the Tag assistant chrome extension, and it only gave me warnings which say that I should ignore those warnings :-) :-)

Is there anything specific (Trigger, Tag, Variable) that I should define in GTM so the campaign URL will be sent to GA, because so far I didn't see anything about that.
Again, all the other GA things have migrated successfuly to the GMT ( the GMT sends them correctly to the GA).
All my Tags
Thanks

A: GTM is nothing more than an additional layer between site and GA. GTM doesn't do anything by itself, so utm parameters don't reach GA (and we presume they are correct), then you did something wrong setting up GA through GTM. What exactly you did wrong - it is pure guesswork, unless you provide more details. At least, example of a utm-tagged link and screenshot of the settings of you main GA tag in GTM.


text:
Q: Define operator for List in C# I would like to define some operations for List in C#.
For example, addition (+) and transpose(').
However, errors appeared when I compiled the code.
I defined a matrix class which is inherited from List>.
Moreover, I implemented the + and ' operator.
The first one is good but when I called it in the main, errors appear.
The second method cannot be even compiled.
Can anyone please help?
Thanks a lot.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace test
{
    class Matrix : List<List<double>>
    {
        public static Matrix operator +(Matrix a, Matrix b)
        {
            Matrix c = new Matrix();
            int i, j;

            for (i = 0; i < a.Count; i++)
            {
                for (j = 0; j < a[1].Count; j++)
                {
                    c[i][j] = a[i][j] + b[i][j];
                }

            }

            return c;

        }

        public static Matrix operator ' (Matrix a)
        {
            Matrix b = new Matrix();
            int i, j;

            for (i = 0; i<a.Count; i++)
            {
                for (j = 0; j < a[1].Count; j++)
                {
                 b[j][i] = a[j][i];
                }

            }

            return b;

        }

        public static int Main(string[] args)
        {

            Matrix x = new Matrix { new List<double> { 1, 2, 5, 2 }, new List<double> { 3, 4, 0, 7 } };
            Matrix y = new Matrix { new List<double> { 1, 2, 5, 2 }, new List<double> { 3, 4, 0, 7 } };
            Matrix z = new Matrix();

            z = x + y;

            Console.WriteLine(z);

            return 0;
        }
    }
}

A: ' is not a valid operator. The overloadable operators are:
Unary: + - ! ~ ++ -- true false
Binary: + - * / % & | ^ << >> == != < > <= >=
Some of these also have restrictions. For instance, the comparison operators must be overloaded in pairs and the second parameter of the shift operators (<< and >>) must be an int.
Take a look at: C# overloadable operators


text:
Q: I can't seem to model my data to a cubic function I've recently been trying to model my data according to separate equations. This function should take some data (xdata and ydata) and fit it as best it can to a cubic equation, but it seems to be giving the wrong answers, and I'm not sure where I've gone wrong. For example when given xdata from 1 to 4 and the ydata of the first 5
4 cubes, it returns:
(array([[ 1.00000000e+00, -2.17381668e-12, -2.20122021e-12, -2.16174470e-12]]))
Here's my code:
import numpy as np
import scipy as sp

from scipy import optimize

xdata_string = input("Enter your values for the xdata")
ydata_string = input("Enter your values for the ydata")

xdata = xdata_string.split()
ydata = ydata_string.split()

#convert input to numbers
    for i in range(len(xdata)):
          xdata[i] = float(xdata[i])

    for i in range(len(ydata)):
          ydata[i] = float(ydata[i])

def curve_fn(x,a,b,c,d):
    return (a*(x**3))+(b*(x**2))+(c*x)+d

def cubefit(xdata,ydata):

    answer_string = sp.optimize.curve_fit(curve_fn,xdata,ydata)

    #debug
    answer_string = answer_string[:1]
    print(answer_string)

    return np.array(answer_string, dtype=float)

cubefit(xdata,ydata)


text:
Q: php foreach inside for statement problems Sorry if this has been asked before however I am having trouble finding the answer to my problem.
I am trying to build a calendar system and schedule system for my web application in PHP and having difficulty with one particular area.
I have a "for" statement where it will draw up the times of the day starting at 12:00AM and finishing at 11:30PM
Inside this for loop, I have a foreach which i want to echo out the objects in an array that match a particular time.
Everything I have tried which includes using for,while and foreach statements don't show what I am after which is the events lining up next to the time.
here is my code
<?php
$tStart = strtotime($start_time);
$tEnd = strtotime($end_time);
$tNow = $tStart;

while($items = mysql_fetch_object($result)){
    $events[] = $items;
}

for($tNow=$tStart; $tNow<$tEnd; $tNow=strtotime('+30 minutes',$tNow)){
    // Time to color the rows to make it easier to read
    if(!isset($day_row)){
        $day_row = "0";
    }
    if(isset($day_row) && $day_row >= "2"){
        $day_row--;
    }
    else{ $day_row++;
    }

    //This bit draws the first column.
    echo "
".date("h:i A",$tNow)."	";

    // MySQL stuff is now here
    foreach($events as $e => $item){
        if($item->apnt_start == $tnow){
            $rowspan = ((strtotime($item->apnt_finish)-strtotime($item->apnt_start))/"1800");
            echo "".$item->apnt_start."-".$item->apnt_finish." ".$item->apnt_brief."
";
        }
    }
}
?>

at present i am given a page with
12:00 AM
12:30 AM
01:00 AM
01:30 AM
02:00 AM
02:30 AM
03:00 AM
03:30 AM
04:00 AM
04:30 AM
05:00 AM
05:30 AM
Next to the time I want the appointment with matching time.
I am trying to achieve something similar to http://mrbs.sourceforge.net/
I can't use their system however as I can't integrate it properly and I have tried looking at their code and it seems to be pointing at many files and i am having trouble trying to understand the function i am after.
Please let me know if this is not clear enough and will try to explain further.

A: You need to define and set value for variables below:
$start_time = "09:00 AM";
$end_time = "11:30 PM";

Also you need to add query and database connection (above while($items = mysql_fetch_object($result)){ statement):
mysql_connect("hostname", "user", "password");
mysql_select_db("mydb");
$result = mysql_query("select * from mytable");

EDIT:
You should use while mysql_fetch_assoc instead of mysql_fetch_object.
Replace
while($items = mysql_fetch_object($result)){

with
while($items = mysql_fetch_assoc($result)){

Delete: $events[] = $items;
Ensure your while statement above ends after all code is executed (code you listed in your question) - closing bracket }.

A: Okay, this should work for you.
<?php
    $tStart = strtotime($start_time);
    $tEnd = strtotime($end_time);
    $tNow = $tStart;

    echo '
';

    while($events = mysql_fetch_assoc($result)){
        for($tNow=$tStart; $tNow<$tEnd; $tNow=strtotime('+30 minutes',$tNow)){
        // Time to color the rows to make it easier to read
            if(!isset($day_row)){
                $day_row = "0";
            }
            if(isset($day_row) && $day_row >= "2"){
                $day_row--;
            }
            else{ $day_row++;
            }

            //This bit draws the first column.
            echo "
".date("h:i A",$tNow)."	";
            if(strtotime($events['apnt_start']) == $tNow) {
                $rowspan = ((strtotime($events->apnt_finish)-strtotime($events->apnt_start))/"1800");
                echo "".$events->apnt_start."-".$events->apnt_finish." ".$events->apnt_brief."
";
            }
        } //end for
    } //end while
    echo '
';
?>

A: I would like to thank everyone that provided advice on this issue, I have finally got it working with added another variable and using a method of storing an array in an array.
The final code looks like
<?php
    $tStart = strtotime($start_time);
    $tEnd = strtotime($end_time);
    $tNow = $tStart;
    $events = array();
    $eas = "0"; // eas stands for Event Array Start. this will be used to cycle through the events in the array.
    while($items = mysql_fetch_assoc($result)){
        $events[] = $items;
    }

    for($tNow=$tStart; $tNow<$tEnd; $tNow=strtotime('+30 minutes',$tNow)){
        // Time to color the rows to make it easier to read
            if(!isset($day_row)){
                $day_row = "0";
            }
            if(isset($day_row) && $day_row >= "2"){
                $day_row--;
            }
            else{ $day_row++;
            }

            //This bit draws the first column.
            echo "
".date("h:i A",$tNow)."	";
        if(strtotime($events[$eas]['apnt_start']) == $tNow) {
                $rowspan = ((strtotime($events[$eas]['apnt_finish'])-strtotime($events[$eas]['apnt_start']))/"1800");
                echo "".$events[$eas]['apnt_start']."-".$events[$eas]['apnt_finish']." ".$events[$eas]['apnt_brief']."
";
                $eas++;
           }
            else{
                echo "	";
            }
        } //end for
?>

By using the variable $eas I was able to then control which number it would start at by setting it to 0 initially and then when it found an entry with a matching time it went through the if statement where at the end of the if statement it was given $eas++ to increment.
This then proved that if there was no appointment the $eas would not run and it would not increment thus remaining on the last incremented $eas.
Thanks again for everyone's help.


text:
Q: Why does tkinter mix bindings of different widgets when creating the widgets in a loop but not when creating them separately? Tkinter mixes bindings of different widgets when the widgets are created in a loop, but when the widgets are created separately, the bindings are correct. I cannot figure out why this is the case.
Wrong bindings
Here's a working example to reproduce the problem. Two widgets (images that should work as buttons that are highlighted when hovering over) are created in a loop and packed in a second loop.
import tkinter as tk
import tkinter.ttk as ttk

IMG_DEFAULT = 'add_default.png'
IMG_HOVER = 'add_hover.png'

class Application(tk.Tk):
    def __init__(self, master=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.title('WRONG!')
        self.img_default = tk.PhotoImage(file=IMG_DEFAULT)
        self.img_hover = tk.PhotoImage(file=IMG_HOVER)
        self.create_widgets()
        self.pack_widgets()

    def create_widgets(self):
        self.buttons = []
        for i in range(2):
            button = ttk.Label(image=self.img_default)
            button.bind('<Button-1>', ...)  # Do something
            button.bind('<Enter>', lambda e: button.config(image=self.img_hover))
            button.bind('<Leave>', lambda e: button.config(image=self.img_default))
            self.buttons.append(button)

    def pack_widgets(self):
        for button in self.buttons:
            button.pack(padx=100, pady=10)

app = Application()
app.mainloop()

As can be seen from the image below, the bindings are wrong: when I hover over the upper button, the lower button is highlighted.

Correct binding
When the widgets are created outside a loop, the key bindings are correct.
import tkinter as tk
import tkinter.ttk as ttk

IMG_DEFAULT = 'add_default.png'
IMG_HOVER = 'add_hover.png'

class Application(tk.Tk):
    def __init__(self, master=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.title('RIGHT!')
        self.img_default = tk.PhotoImage(file=IMG_DEFAULT)
        self.img_hover = tk.PhotoImage(file=IMG_HOVER)
        self.create_widgets()
        self.pack_widgets()

    def create_widgets(self):
        button1 = ttk.Label(image=self.img_default)
        button1.bind('<Button-1>', ...)   # Do something
        button1.bind('<Enter>', lambda e: button1.config(image=self.img_hover))
        button1.bind('<Leave>', lambda e: button1.config(image=self.img_default))

        button2 = ttk.Label(image=self.img_default)
        button2.bind('<Button-1>', ...)   # Do something
        button2.bind('<Enter>', lambda e: button2.config(image=self.img_hover))
        button2.bind('<Leave>', lambda e: button2.config(image=self.img_default))

        self.buttons = [button1, button2]

    def pack_widgets(self):
        for button in self.buttons:
            button.pack(padx=100, pady=10)

app = Application()
app.mainloop()

As can be seen from the image, now the bindings are correct: when I hover over the upper button, the upper button is highlighted and when I hover over the lower, it is highlighted.

Can anyone explain why the second case works as intended but the first does not? In my application, I have a more general use case with an unknown number of buttons. How can I get the correct bindings in place?
EDIT
As pointed out by Bryan Oakley in his comment, my question is a duplicate of Tkinter assign button command in loop with lambda. Both the solutions of Henry (https://stackoverflow.com/a/66663554/12646289) and acw1668 provide the solution.
Thanks a lot for your help! I have upvoted the comments and accepted Henry's answer.

A: This problem is caused by your lambdas. When the binding is called, it uses the current value of button for config. If you made 4 buttons they'd all change the image on the last one because it is the last value of button. (I'm not sure if I've explained it very well, please look at this answer for more detail). You need to change the lambda to
lambda e, b = button: b.config(...)

This creates a reference to the particular button so when the binding is called, the image for that button changes.


text:
Q: How To Create A Fixed Width Element I have a full width page template in wordpress and have created a box inside this through a plugin. However, I need the box to have the text wrapping around this. The plugin developer has said to wrap the text inside a fixed width element. For this I am a little confused and any help would be greatly appreciated. The page in question is http://www.haylockpittman.co.uk/refurbishment-and-renovation-of-kitchens/
Thanks in advance.

A: You are applying a width to the child DIV when you should be applying to the parent.
Your CSS selector currently reads
.grid3 .content_block

If you changed this to .content_block_wrapper.grid-3 and added a float:left; it will work. You will also need to remove the

 you have below your container.

A: try this if you don't knew it already :

    this is a fixed area

A: I think the simplest way is to change this html:

to this:

And then remove the

 the lives just after the
 above closes.
You'll probably want a margin to the right of that box, so add that to CSS for the .content_block general-2


text:
Q: overflow-y Scroll Visible on Custom Modal but is Not Functioning I have a custom modal in my angular app. In the body I want to layout the terms and conditions (it will be lengthy) so I need the body portion of the modal to be able to scroll. The problem is currently the scroll bar is visible but its acting as if its disabled -- it wont move even though content is definitely overflowing.
Here's how it looks:
https://i.stack.imgur.com/Lgl9p.png
And here's my code:
HTML:

        <cel-dialog [backdrop-dismiss]="true" class="modal-dialog">

Conditions of Demo Account Access

X

Boedy

Boedy

Boedy

Boedy

Boedy

Boedy

Boedy

Boedy

Boedy

Boedy

Boedy

Boedy

Boedy

Boedy

Boedy

Boedyzzzz

Boedy

Boedy

Boedy

Boedy

Boedy

Boedy

Footer

        </cel-dialog>

CSS:
.backdrop {
    width: 100vw;
    height: 100vh;
    position: fixed;
    top: 0px;
    left: 0px;
    background: rgba(0, 0, 0, 0.75);
}
.modal-dialog {
    width: 600px;
    height: 250px;
    position: fixed;
    margin: 10% auto;
    left: 0;
    right: 0;
    box-shadow: 0px 3px 8px rgba(0, 0, 0, 0.5);
    border-radius: 3px;
    background: var(--white);
}

.modal-container {
    min-height: 0;
    height: 250px;
    width: 100%;
}

.modal-header {
    height: 20%;
    background-color: var(--blueDark);
    color: white;
}

.modal-body {
    height: 70%;
    overflow-y: auto;
}

.modal-footer {
    height: 10%;
    background-color: black;
}

.modal-header .title {
    margin-left: 10px;
}
.modal-header .close-modal-button {
    margin-right: 10px;
}

A: pointer-event in class .modal-dialog of _modal.scss is set to "none"
you can change this in this way:
.modal-dialog {
   .
   .
   .
   /* Add Line Below */
   pointer-events:unset !important;
}


text:
Q: OpenMP - Running parallel code inside parallel code I have a function compute() that has parallelized matrix multiplication inside of it using OpenMP
#pragma omp parallel for

This function is called many times in a loop - which I would like to run in parallel.
Will there be any issues in running parallel code inside other parallel code?
This is c++ compiled on Ubuntu.

A: It will work fine, but you'll need to enable OpenMP nesting for it to work.
Call
omp_set_nested(1);

at the start of the program and it will allow you to have nested parallel regions.
However: Be aware, that you could end up running many more threads than what you want. So you will want to limit the # of threads of both the top and inner parallel regions.


text:
Q: Call dll with C++ header from C# I'm trying to call a method in a dll which I have the C++ header for. I'm calling the dll from C#. The input is a string and the output is binary data. Any of the following 3 methods would probably work, I just don't know how to make any of them work all the way.
The C# declaration is made by me, so they might not be correct
1: I'm able to get the hGlobal, but I don't know how to get data from the handle.
//CMBT_LL_WINAPI INT DLLPROC  LlConvertStringToHGLOBALW(LPCWSTR pszText, _PHGLOBAL phMemory);
 [DllImport("cmll15.dll", EntryPoint = "LlConvertStringToHGLOBALW", CharSet =   CharSet.Unicode, ExactSpelling = true)]
 private static extern int _LlConvertStringToHGlobal32(string text, ref IntPtr handle);

2:
[DllImport("cmll15.dll", EntryPoint = "LlConvertStringToBLOBW", CharSet = CharSet.Unicode, ExactSpelling = true)]
//CMBT_LL_WINAPI INT      DLLPROC  LlConvertStringToBLOBW(LPCWSTR pszText, _PUINT8 pBytes, UINT nBytes);
private static extern int _LlConvertStringToBLOBW(string text, ref IntPtr pBytes, UInt32 nBytes);

3:
[DllImport("cmll15.dll", EntryPoint = "LlConvertStringToStreamW", CharSet = CharSet.Unicode, ExactSpelling = true)]
//CMBT_LL_WINAPI INT      DLLPROC  LlConvertStringToStreamW(LPCWSTR pszText, _PISTREAM pStream);
private static extern int _LlConvertStringToStreamW(string text, ref IntPtr pStream);

Updated, here is the code I think I will end up with.
    [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
    private static extern UIntPtr GlobalSize(IntPtr hMem);

    [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
    public static extern IntPtr GlobalLock(IntPtr handle);

    [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
    public static extern IntPtr GlobalUnlock(IntPtr handle);

    [DllImport("cmll15.dll", EntryPoint = "LlConvertStringToHGLOBALW", CharSet = CharSet.Unicode, ExactSpelling = true)]
    private static extern int _LlConvertStringToHGlobal32(string text, ref IntPtr handle);

    private static void Main(string[] args)
    {
        IntPtr dataHandle = IntPtr.Zero;
        _LlConvertStringToHGlobal32(Contents, ref dataHandle);
        try
        {
            var size = (uint) GlobalSize(dataHandle);
            var array = new byte[size];
            IntPtr dataPtr = GlobalLock(dataHandle);
            try
            {
                Marshal.Copy(dataPtr, array, 0, array.Length);
            }
            finally
            {
                GlobalUnlock(dataPtr);
            }

            using (var fs = new FileStream("c:\\file.dat", FileMode.Create))
            {
                fs.Write(array, 0, array.Length);
            }
        }
        finally
        {
            Marshal.FreeHGlobal(dataHandle);
        }
    }

A: The first one ought to be easiest to get going because that leaves it up to the callee to figure out the required size.  It is however not obvious how you are supposed to know the size of the allocation.  Maybe the return value.  You can always pinvoke GlobalSize() to get the size from the HGLOBAL handle.  You should pinvoke GlobalLock() to convert the handle to a pointer, then Marshal.CopyMemory() to copy it into a byte[].  Cleanup by calling GlobalUnlock() and  Marshal.FreeHGlobal() to release the memory, put it inside a finally block so you cannot leak.
For the second one, you should declare the 2nd argument as byte[] (not ref).  Trouble is that you'll have to guess the size of the array up front.  A failure mode would be guessing the size too small.
The third one requires a COM IStream.  Declare it as out System.Runtime.InteropServices.ComTypes.IStream.  It behaves a lot like a .NET Stream, you'd call Seek to seek to the beginning and Read to read the data.
I'd go for the first one, least likely to blow up in your face.

A: For 1:
You should have the length of binary data output and then using Marshal.Copy method as following:
byte[] data = new byte[length];
Marshal.Copy(handle, data, 0, length);
For 2 & 3: what's your problem?


text:
Q: nirq: Flags mismatch irq 80. 00002083 (ledtrig-gpio) vs. 00000083 (USER) I am doing some experiments on SAMA5D27-SOM1-EK1 board. I am using Linux operating system. I am exploiting GPIOS of my board. There is RED LED defined at GPIO 10 and USER button defined at GPIO 29. I wrote C++ program to control LED of the board and here is the code :
#include<iostream>
#include<fstream>
#include<string>
using namespace std;

#define LED0_PATH "/sys/class/leds/red"

void removeTrigger(){
   // remove the trigger from the LED
   std::fstream fs;
   fs.open( LED0_PATH "/trigger", std::fstream::out);
   fs << "none";
   fs.close();
}

int main(int argc, char* argv[]){
   if(argc!=2){
 cout << "Usage is makeLED and one of: on, off, flash or status"
<< endl;
 cout << "e.g. makeLED flash" << endl;
   }

   string cmd(argv[1]);
   std::fstream fs;
   cout << "Starting the LED flash program" << endl;
   cout << "The LED Path is: " << LED0_PATH << endl;

 // select whether it is on, off or flash
   if(cmd=="on"){
 removeTrigger();
 fs.open (LED0_PATH "/brightness", std::fstream::out);
 fs << "1";
 fs.close();
   }

   else if (cmd=="off"){
 removeTrigger();
 fs.open (LED0_PATH "/brightness", std::fstream::out);
 fs << "0";
 fs.close();
   }

   else if (cmd=="flash"){
 fs.open (LED0_PATH "/trigger", std::fstream::out);
 fs << "timer";
 fs.close();
 fs.open (LED0_PATH "/delay_on", std::fstream::out);
 fs << "50";
 fs.close();
 fs.open (LED0_PATH "/delay_off", std::fstream::out);
 fs << "50";
 fs.close();
   }

   else if (cmd=="status"){
 // display the current trigger details
 fs.open( LED0_PATH "/trigger", std::fstream::in);
 string line;
 while(getline(fs,line)) cout << line;
 fs.close();
 }

   else{
 cout << "Invalid command" << endl;
 }

cout << "Finished the LED flash program" << endl;
       return 0;

This seems to work fine : When I tape ./target_bin off the Red Led turn off and the same for on and flash commands.
But when I tried to control LED ( RED / GPIO 10 ) with BUTTON ( USER / GPIO 29 ) I added this part of code :
else if (cmd=="button"){
        removeTrigger();
        fs.open (LED0_PATH "/trigger", std::fstream::out);
        fs << "gpio";
        fs.close();
        fs.open (LED0_PATH "/gpio", std::fstream::out);
        fs << "29";
        fs.close();
   }

And now when I tape ./target_bin button It shows me an error :

nirq: Flags mismatch irq 80. 00002083 (ledtrig-gpio) vs. 00000083
  (USER) leds red: request_irq failed with error -16

Can Anyone help me out please ?

A:
And now when I tape [sic] ./target_bin button It shows me an error :

nirq: Flags mismatch irq 80. 00002083 (ledtrig-gpio) vs. 00000083 (USER) leds red: request_irq failed with error -16

Error 16 is "Device or resource busy".
The device or resource in question is the gpio_key for the push button.
Note that the error message mentions "USER", which happens to be the label assigned to the gpio_key for the push button in the Device Tree file at91-sama5d27_som1_ek.dts.
gpio_keys {
    ...
    pb4 {
        label = "USER";
        gpios = <&pioA PIN_PA29 GPIO_ACTIVE_LOW>;
        ...
    };
};

In order for GPIO 29 to be used as a LED trigger, it must be an available, i.e. unused, GPIO.
However the default dts file configures that GPIO 29 to be a gpio_key, and therefore that GPIO is owned by the gpio_key driver.
GPIO 29 is not an unused pin, and is not available for use as a LED trigger (i.e. ownership cannot be transferred to the ledtrig-gpio driver).
You can either use the push-button gpio_key as an input-event device as currently configured, or reconfigure the GPIO 29 so that it is not a gpio_key and available for use as a LED trigger.

ADDENDUM
[responses to comments]

But when i search for the devices which are " USED " on my board with gpioinfo | grep "[used]" command I find that RED led is used before I run my program : line 10: "PA10" "red" output active-high [used] but my code does not show an error for it.

Are you complaining that you did not get a LED error?
I fail to understand what point you are trying to make.

Why would it show an error for BUTTON ...

As I already explained the dts file configures GPIO 29 (i.e. the push button) to be a gpio_key, and assigning GPIO 29 to be a LED trigger causes a conflict.
To be more specific, the LED trigger driver (ledtrig-gpio) requires that the interrupt be configured for "one-shot" mode.
 * IRQF_ONESHOT - Interrupt is not reenabled after the hardirq handler finished.
 *                Used by threaded interrupts which need to keep the
 *                irq line disabled until the threaded handler has been run.
 ...
#define IRQF_ONESHOT        0x00002000

This (new) interrupt mode (i.e. 0x00002083) conflicts with the existing mode/flags (i.e. 0x00000083) established by the gpio_keys driver.
This conflict means that this GPIO cannot be used simultaneously for both a gpio_key (input event) and a LED trigger.
Therefore you have to choose in which mode this GPIO will operate.

... and not for LED ?

You mean you want the error to occur on the LED?
You don't get to choose which device causes an error when you perform a specific operation.
The operation you requested, i.e. assign a specific GPIO (which is already installed as a gpio_key) to be the LED trigger, failed during the assignment of the (new) interrupt handler for the gpio_key.
So the error is reported for the gpio_key, and not the LED.

For further confirmation to quell your doubts:
Since the error message mentions "irq 80", you should look up this "irq 80" in the /proc/interrupts file on your board.
That file should indicate that "irq 80" is associated with "GPIO 29" (which per the DT is a gpio_key).
For yet another procedure to quell your doubts:
Locate an unused PIO pin that is accessible and unused (by any peripheral or any driver/process as a gpio).
Assign that pin as the LED trigger.
No error should occur (assuming you selected an unused pin).
Short the pin to ground or VDD_3V3 to change the (default) state of the LED.

How can I reconfigure the button USER so that it is not a gpio_key and be available for use as a LED trigger ?

As I already wrote, the Device Tree file at91-sama5d27_som1_ek.dts is where the GPIO with the push button is declared to be a gpio_key, and I also posted a snippet of the salient lines of that node.
If you do not want that GPIO to be configured as a gpio_key, then the Device Tree file needs to be modified by removing that node (and of course recompiled into a dtb).


text:
Q: Marshal error when RegisterStreamReadCallback I'm using C# to call methods from an dll file to record video.
This is the Marshal methods file
    http://pastebin.com/YrVvBfZ9
This is my CameraUtilities file
    http://pastebin.com/0AZNtnhk
This is my camera file
   http://pastebin.com/ZE3HD1zq
When I call StartRecord method (in camera file) to start Record video.
 public void StartRecord()
    {
        if (this.ListCameras != null)
        {
            bool bRes = true;
            try
            {
                int tmpError = -1;
                m_tmpContext = new IntPtr();
                m_handle = new GCHandle();
                m_callBackChannels = new ulong[m_ListCameras.Length];

                for (int i = 0; i < m_ListCameras.Length; i++)
                {
                    m_callBackChannels[i] = 10;
                    cameraCurrentIndex = 0;
                    IntPtr channelHandle = T1800.T18_ChannelOpen(cameraCurrentIndex);
                    m_ListCameras[cameraCurrentIndex].ChannelHandle = channelHandle;
                    T1800.T18_CaptureIFrame(m_ListCameras[i].ChannelHandle);

                    m_ListCameras[i].BeginRecord();
                    if (AllowRecordVideo)
                    {
                        m_del = new T1800.STREAM_READ_CALLBACK(StreamReadCallBack);
                        m_tmpContext = m_ListCameras[i].ChannelHandle;
                        tmpError = T1800.T18_RegisterStreamReadCallback(m_del, ref m_tmpContext);
                    }
                }

                if (tmpError == -1) bRes = false;
            }
            catch (Exception ex)
            {
                Log.Logger.Error(ex);
                bRes = false;
            }
        }
    }

It throw an exception
- System.Runtime.InteropServices.MarshalDirectiveException: Invalid PInvoke calling convention.
 Thiscall requires that the first parameter is present and can be enregistered.
   at System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegateInternal(Delegate d)
   at System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(Delegate d)
   at TH.Parking.Wrapper.HBCamera.T1800.dll_T18_RegisterStreamReadCallback(STREAM_READ_CALLBACK STREAM_READ_CALLBACK, IntPtr& context)
   at TH.Parking.Wrapper.HBCamera.CameraUtilities.StartRecord() in d:\TH.Parking\TH.Parking\Wrapper\HBCamera\CameraUtilities.cs:line 93

I can't find any reason for this error. Can somebody help me to fix this.

A: I think the callback you pass to create the STREAM_READ_CALLBACK object should be static. Otherwise, the thispointer is lost during the marshalling.
Instead of:
private int StreamReadCallBack(ulong channelHandle, IntPtr context)
{
   ...
}

try:
private static int StreamReadCallBack(ulong channelHandle, IntPtr context)
{
   ...
}

And you'll need to somehow put your instance of CameraUtility into the context parameter.


text:
Q: Autohotkey restart script when time is up I have an infinite loop script running. I want to run it during night without monitoring it (it gets stuck once in a while at something unavoidable).
So I need code to restart the script if 4 minutes are done. ( Script will finish within 3 minutes 100% ). Also, it should not restart before 3 minutes..
Thank you :)

A: Try the SetTimer command.
SetTimer, restartScript, -240000  ;run the timer just once after 240000 milliseconds

;main script here
;....
;return

restartScript:
Reload
return


text:
Q: Finding directory in another directory I need to find specific directory in a different directory, but for some reason my code finds directory in current directory but when I start to search for a specific named directory in parent directory, it can not find it there
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
void print_dir(char *dir_n, char *file)
{
DIR *dir = opendir(dir_n);

struct dirent *Dirent;
struct stat stats;

while(1)
{
    Dirent = readdir( dir );
    if (Dirent == NULL)
    {
        break;
    }

        stat( Dirent->d_name, &stats );
        if ( S_ISDIR( stats.st_mode ))
        {
            if(strcmp(file ,Dirent->d_name) == 0  &&  S_ISDIR( stats.st_mode ) )
            {
                printf("found\n");
                break;

            }
        }
}
closedir(dir);
}
int main(int argc, const char * argv[])
{
  print_dir("..", "dirtest");
  return 0;
}

A: You need to check the return status of your system calls, and specifically stat().
What's happening is that you read a name found in the .. directory, but when you invoke stat(), you are doing so on ./name and not ../name.
This code should demonstrate the point:
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>

void print_dir(char *dir_n, char *file)
{
    DIR *dir = opendir(dir_n);

    if (dir == 0)
    {
        int errnum = errno;
        fprintf(stderr, "error: opendir(\"%s\") failed (%d: %s)\n", dir_n, errnum, strerror(errnum));
        exit(1);
    }

    struct dirent *Dirent;

    while ((Dirent = readdir(dir)) != 0)
    {
        struct stat stats;
        if (stat(Dirent->d_name, &stats) < 0)
        {
            int errnum = errno;
            fprintf(stderr, "error: failed to stat(\"%s\") (%d: %s)\n", Dirent->d_name, errnum, strerror(errnum));
        }
        else if (S_ISDIR(stats.st_mode))
        {
            if (strcmp(file, Dirent->d_name) == 0)
            {
                printf("found directory %s (inode = %ld)\n", Dirent->d_name, (long)stats.st_ino);
                break;
            }
            else
                printf("found directory %s - not a match for %s\n", Dirent->d_name, file);
        }
        else
        {
            printf("%s is not a directory\n", Dirent->d_name);
        }
    }
    closedir(dir);
}

int main(void)
{
    print_dir("..", "dirtest");
    return 0;
}

And this trivial variant should find the directory ../dirtest if it exists:
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>

void print_dir(char *dir_n, char *file)
{
    DIR *dir = opendir(dir_n);

    if (dir == 0)
    {
        int errnum = errno;
        fprintf(stderr, "error: opendir(\"%s\") failed (%d: %s)\n", dir_n, errnum, strerror(errnum));
        exit(1);
    }

    struct dirent *Dirent;

    while ((Dirent = readdir(dir)) != 0)
    {
        char fullname[1024];
        snprintf(fullname, sizeof(fullname), "%s/%s", dir_n, Dirent->d_name);
        struct stat stats;
        if (stat(fullname, &stats) < 0)
        {
            int errnum = errno;
            fprintf(stderr, "error: failed to stat(\"%s\") (%d: %s)\n", fullname, errnum, strerror(errnum));
        }
        else if (S_ISDIR(stats.st_mode))
        {
            if (strcmp(file, Dirent->d_name) == 0)
            {
                printf("found directory %s (%s) (inode = %ld)\n", Dirent->d_name, fullname, (long)stats.st_ino);
                break;
            }
            else
                printf("found directory %s - not a match for %s\n", fullname, file);
        }
        else
        {
            printf("%s is not a directory\n", fullname);
        }
    }
    closedir(dir);
}

int main(void)
{
    print_dir("..", "dirtest");
    return 0;
}

A: I tested it on my computer (and created directory ../dirtest for that), and it seems to work fine. Are you sure your directory is created and that you are searching at the right place?


text:
Q: How to convert "weekday month day time" to datetime (YYYY-MM-DD)? I have a column fecha formatted as a string in the form of
Mon Feb 22 07:55:55 CET 2021

How do I convert it to a date format like YYYY-MM-DD? I have tried CAST, CONVERT ...
And I always get the following error message:

Msg 241, Level 16, State 1, Line 4
Conversion failed when converting date and/or time from character string

A: Assuming, as I comment, the value is always ddd MMM dd hh:mm:ss tz yyyy you could do some messy string manipulation to convert the value to a valid date and time data type. Then you can format the date however you want in your presentation layer, as it's strongly typed:
SELECT V.DateString,
       TRY_CONVERT(datetime2(0),STUFF(STUFF(LEFT(STUFF(V.DateString,1,8,''),12),3,0,RIGHT(V.DateString,5)),3,0,SUBSTRING(V.DateString,4,4)),113) AS ConvertedDate
FROM (VALUES('Mon Feb 22 07:55:55 CET 2021'))V(DateString);

Of course, the real lesson here is don't store date and time values as a varchar in your database. Date and Time data types exist for a reason; use them.

A: I don't think there are standard functions to deal with your source strings, so I would combine simpler standard transformations to get that result :
declare @Cadena varchar(50) = 'Mon Feb 22 07:55:55 CET 2021'

select substring(@Cadena, 25, 4)  + '-' +
       replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(substring(@Cadena, 5, 3), 'Jan', '01'), 'Feb', '02'), 'Mar', '03'), 'Apr', '04'), 'May', '05'), 'Jun', '06'), 'Jul', '07'), 'Aug', '08'), 'Sep', '09'), 'Oct', '10'), 'Nov', '11'), 'Dec', '12') + '-' +
       substring(@Cadena, 9, 2)

This will fail if your string are not always in the exact same format, in that case more code would be needed.


text:
Q: NestJS pipe stream to response I'm learning about streams and trying a simple experiment. I want to pipe a readable stream into the HTTP response, but I get an error saying "Cannot set headers after they are sent to the client".
What is the cause of this and how should I proceed ?
@Post('/pipe-into-response')
pipeIntoResponse(@Body() payload, @Res() response: Response) {
    const stream = new Readable();
    stream.on('end', () => response.end());
    stream.push('Hello World');
    stream.pipe(response);
}

A: As you already stream.pipe(response) you don't need to tell the response to response.end(). That should betaken care of by the pipe operation.