Q: Create lists of nodes from rows of matching pairs Not sure if this can be done with pandas or if I need to write a loop with some logic.
I have some data representing chains of pairs of nodes:
pairs = [
    # A1 -> B1 -> C1
    {'source': 'A1', 'target': 'B1'},
    {'source': 'B1', 'target': 'C1'},
    # A1 -> D1
    {'source': 'A1', 'target': 'D1'},
    # C2 -> A2 -> B2
    {'source': 'C2', 'target': 'A2'},
    {'source': 'A2', 'target': 'B2'},
]

And I want to resolve those chains to create the list of nodes they contain:
results = [
    ['A1', 'B1', 'C1', 'D1'],
    ['C2', 'A2', 'B2'],
]

So far I have this code which does allow me to match some of those nodes together:
def pair_nodes(df, src, tgt):
    df = df.groupby([src]).agg({tgt: 'unique'}).reset_index()
    df['nodes'] = df.apply(lambda r: np.append(r[src], r[tgt]), axis=1)
    return df

df1 = pair_nodes(df, 'source', 'target')
df2 = pair_nodes(df, 'target', 'source')
print(df1)
print(df2)

Which gives me:
  source    target         nodes
0     A1  [B1, D1]  [A1, B1, D1]
1     A2      [B2]      [A2, B2]
2     B1      [C1]      [B1, C1]
3     C2      [A2]      [C2, A2]
  target source     nodes
0     A2   [C2]  [A2, C2]
1     B1   [A1]  [B1, A1]
2     B2   [A2]  [B2, A2]
3     C1   [B1]  [C1, B1]
4     D1   [A1]  [D1, A1]

And I'm a stuck there. What I guess I'm missing is to merge rows from df1 and df2 whenever source or target is found in nodes
I had a look at df.merge but it only seems to work for exact key match.
Can this be achieved with pandas or do I need to write a custom loop/logic to do this?

A: Creating the desired result with merging dataframes can be a complicated process.
The above used login of merging will not be able to satisfy all types of graphs. Have a look at the below method.
# Create graph
graph = {}
for pair in pairs:
    if pair['source'] in graph.keys():
        graph[pair['source']].append(pair['target'])
    else:
        graph[pair['source']] = [pair['target']]

# Graph
print(graph)
{
    'A1': ['B1', 'D1'],
    'B1': ['C1'],
    'C2': ['A2'],
    'A2': ['B2']
}

# Generating list of nodes
start = 'A1' # Starting node parameter
result = [start]
for each in result:
    if each in graph.keys():
        result.extend(graph[each])
    result = list(set(result))

# Output
print(result)
['A1', 'B1', 'C1', 'D1']


Q: iTunes connect update limited to some countries? I have an app available for multiple countries; and now I need to release an update only to some of this countries.
Example
An app available for the whole world, is going to get an update, but it should only be available for USA users for instance.
Is it possible to release this update only to the USA store, or somehow limit it?
Thanks in advance.

A: If you limit the app to any geographical extent, then current users will be able to use it, but it won't appear to anyone on iTunes.
So, if you wanted an update for some region while having the previous version available, the answer is no, there's no way to do that.
@skorulis I find many reasons why you could want to do so, e.g. incremental release of the app update amongst many others.


Q: UIImageView.image not loading I have a strange issue with loading an imageview into a UITableViewCell during:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

here is my code:
    UIImageView *title = [[[UIImageView alloc] initWithFrame:CGRectMake(0,10,300,150)] autorelease];

    title.image = [UIImage imageNamed:@"featured_graphic.png" ];
    title.contentMode = UIViewContentModeScaleAspectFill;
    title.alpha = 1.0;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

its inside this:
 if( [indexPath isEqual:[NSIndexPath indexPathForRow:0 inSection:0]] )
 {
 }

I verified that featured_graphic.png is in my application.

A: You make the title but you don't actually add it to the view.
[cell.contentView addSubview:title];


Q: How to update column name after finding the table names from information schema I have run a script to find the table names with a specific column name from a database using the information schema
here is the query
  use IMS_SCMS_DIGITAL_POWER
  select * from information_schema.columns
  where column_name like 'COMPANY_ID%'

after finding the table names now i would like to update the specific column values of all the database. Need solutions.

A: Run following query to get all tablenames with specific column name
SELECT t.name AS TableName
FROM sys.columns c
    JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE '%COMPANY_ID%'

just use in forward only cursor with tablenames to update the specific table.


Q: Angular PWA implementation on a specific component of angular Successfully converted my app into PWA but what I wanted to achieve is, I wanted that install option start visible from localhost/employee/dashboard not from localhost/.
What I tried so far is:
I put the URL (employee/dashboard/) in the starting URL of menifest.json, but what I achieve by this is it still showing the install option from the localhost/ but on installing it start PWA screen from localhost/employee/dashboard which is not what I wanted.
What I wanted:
I know to achieve this what I have to do is to put  in the index.html of that component, but my project is not in simple html,css,js where every component have a  tag where I put  and it starts giving install option from there. It is angular, can I somehow achieve this.


Q: np.transpose behavior different for different array constructions I came across this weird behavior with np.transpose wherein it works differently when used on an numpy array and array constructed from a list. As an MWE following code is presented.
import numpy as np

a = np.random.randint(0, 5, (1, 2, 3))
print(a.shape)
# prints (1, 2, 3)
b = np.transpose(a, (0, 2, 1))
print(b.shape)
# prints (1, 3, 2), which is expected

# Constructing array from list of arrays
c = np.array([np.random.randint(0, 5, (2, 3)), np.random.randint(0, 5, (2, 3)), np.random.randint(0, 5, (2, 3)), np.random.randint(0, 5, (2, 3))])
print(c.shape)
# prints (4, 2, 3)
d = np.transpose(c, (2, 0, 1))
print(d.shape)
# prints (3, 4, 2), whereas I expect it to be (2, 3, 4)

I do not understand this behavior. Why is it that the array constructed from the list has the dimensions mixed up? Any help is appreciated.

A: np.transpose() picks the dimensions you specify in the order you specify.
In your first case, your array shape is (1,2,3) i.e. in dimension->value format, it is 0 -> 1, 1 -> 2 and 2 -> 3. In np.transpose(), you're requesting for the order 0,2,1 which is 1,3,2.
In the second case, your array shape is (4,2,3) i.e. in dimension->value format, it is 0 -> 4, 1 -> 2 and 2 -> 3. In np.transpose(), you're requesting for the order 2,0,1 which is 3,4,2.


Q: How can Apache Camel be used to monitor file changes? I would like to monitor all of the files in a given directory for changes, ie an updated timestamp. This use case seems natural for Camel using the file component, but I can't seem to find a way to configure this behavior.
A uri like:
file:/some/directory

will consume the files in the provided directory but will delete them.
A uri like:
file:/some/directory?noop=true

consumes each file once when it is added or when the route is started.
It's surprising that there isn't an option along the lines of
consumeOnChange=true

Is there a straightforward way to monitor file changes and not delete the file after consuming?

A: You can do this by setting up the idempotentKey to tell Camel how a file is considered changed. For example if the file size changes, or its timestamp changes etc.
See more details at the Camel file documentation at: https://camel.apache.org/components/latest/file-component.html
See the section Avoiding reading the same file more than once (idempotent consumer). And read about idempotent and idempotentKey.
So something alike
from("file:/somedir?noop=true&idempotentKey=${file:name}-${file:size}")

Or
from("file:/somedir?noop=true&idempotentKey=${file:name}-${file:modified}")

You can read here about the various ${file:xxx} tokens you can use: http://camel.apache.org/file-language.html

A: Setting noop to true will result in Camel setting idempotent=true as well, despite the fact that idempotent is false by default.
Simplest solution to monitor files would be:
.from("file:path?noop=true&idempotent=false&delay=60s")

This will monitor changes to all files in the given directory every one minute.
This can be found in the Camel documentation at: http://camel.apache.org/file2.html.

A: I don't think Camel supports that specific feature but with the existent options you can come up with a similar solution of monitoring a directory.
What you need to do is set a small delay value to check the directory and maintain a repository of the already read files. Depending on how you configure the repository (by size, by filename, by a mix of them...) this solution would be able to provide you information about news files and modified files. As a caveat it would be consuming the files in the directory very often.
Maybe you could use other solutions different from Camel like Apache Commons VFS2 (I wrote a explanation about how to use it for this scenario: WatchService locks some files?

A: I faced the same problem i.e. wanted to copy updated files also (along with new files). Below is my configuration,
public static void main(String[] a) throws Exception {

    CamelContext cc = new DefaultCamelContext();

    cc.addRoutes(createRouteBuilder());

    cc.start();

    Thread.sleep(10 * 60 * 1000);

    cc.stop();
}

protected static RouteBuilder createRouteBuilder() {
    return new RouteBuilder() {
        public void configure() {
            from("file://D:/Production"
                    + "?idempotent=true"
                    + "&idempotentKey=${file:name}-${file:size}"
                    + "&include=.*.log"
                    + "&noop=true"
                    + "&readLock=changed")

            .to("file://D:/LogRepository");
        }
    };
}

My testing steps:

*

*Run the program and it copies few .log files from D:/Production to D:/LogRepository and then continues to poll D:/Production directory

*I opened a already copied log say A.log from D:/Production (since noop=true nothing is moved) and edited it with some editor tool. This doubled the file size and save it.

At this point I think Camel is supposed to copy that particular file again since its size is modified and in my route definition I used "idempotent=true&idempotentKey=${file:name}-${file:size}&readLock=changed". But camel ignores the file.
When I use TRACE for logging it says "Skipping as file is already in progress...", but I did not find any lock file in D:/Production directory when I editted and saved the file.
I also checked that camel still ignores the file if I replace A.log (with same name but bigger size) in D:/Production directory from outside.
But I found, everything is working as expected if I remove noop=true option.
Am I missing something?

A: If you want monitor file changes in camel, use file-watch component.
Example -> RECURSIVE WATCH ALL EVENTS (FILE CREATION, FILE DELETION, FILE MODIFICATION):
from("file-watch://some-directory")
.log("File event: ${header.CamelFileEventType} occurred on file ${header.CamelFileName} at ${header.CamelFileLastModified}");

You can see the complete documentation here:
Camel file-watch component


Q: What is helperGrowEdges function in MATLAB I was following a tutorial in matlab documentation at  http://www.mathworks.com/help/vision/examples/automatically-detect-and-recognize-text-in-natural-images.html
There they use a function helperGrowEdges but I it is not being recognized right now. I verified that I have Computer Vision System Toolbox. I am unable to figure how to implement it. It says it 'Grow the edges outward by using image gradients around edge locations', but I am unable to figure out how to implement is well.

A: As hinted out by Naveh, It works those functions are present only in MATLAB 2014 version and not in older versions.
Older versions do not have that example as well when I try to open edit TextDetectionExample

A: This example first appears in release R2014a.  helperGrowEdges is a helper function, which goes with the example.  Unfortunately it does not get published in the documentation.  The only way for you  to see it is to get access to an installation of MATLAB R2014a with the Computer Vision System Toolbox, and do edit helperGrowEdges.


Q: Lightweight pickle for basic types in python? All I want to do is serialize and unserialize tuples of strings or ints.
I looked at pickle.dumps() but the byte overhead is significant. Basically it looks like it takes up about 4x as much space as it needs to. Besides, all I need is basic types and have no need to serialize objects.
marshal is a little better in terms of space but the result is full of nasty \x00 bytes. Ideally I would like the result to be human readable.
I thought of just using repr() and eval(), but is there a simple way I could accomplish this without using eval()?
This is getting stored in a db, not a file. Byte overhead matters because it could make the difference between requiring a TEXT column versus a varchar, and generally data compactness affects all areas of db performance.

A: personally i would use yaml.  it's on par with json for encoding size, but it can represent some more complex things (e.g. classes, recursive structures) when necessary.
In [1]: import yaml
In [2]: x = [1, 2, 3, 'pants']
In [3]: print(yaml.dump(x))
[1, 2, 3, pants]

In [4]: y = yaml.load('[1, 2, 3, pants]')
In [5]: y
Out[5]: [1, 2, 3, 'pants']

A: Maybe you're not using the right protocol:
>>> import pickle
>>> a = range(1, 100)
>>> len(pickle.dumps(a))
492
>>> len(pickle.dumps(a, pickle.HIGHEST_PROTOCOL))
206

See the documentation for pickle data formats.

A: If you need a space efficient solution you can use Google Protocol buffers.
Protocol buffers - Encoding
Protocol buffers - Python Tutorial

A: Take a look at json, at least the generated dumps are readable with many other languages.

JSON (JavaScript Object Notation) http://json.org is a subset of JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data interchange format.

A: There are some persistence builtins mentioned in the python documentation but I don't think any of these is remarkable smaller in the produced filesize.
You could alway use the configparser but there you only get string, int, float, bool.

A: "the byte overhead is significant"
Why does this matter?  It does the job.  If you're running low on disk space, I'd be glad to sell you a 1Tb for $500.
Have you run it?  Is performance a problem?  Can you demonstrate that the performance of serialization is the problem?
"I thought of just using repr() and eval(), but is there a simple way I could accomplish this without using eval()?"
Nothing simpler than repr and eval.
What's wrong with eval?
Is is the "someone could insert malicious code into the file where I serialized my lists" issue?
Who -- specifically -- is going to find and edit this file to put in malicious code?  Anything you do to secure this (i.e., encryption) removes "simple" from it.

A: Luckily there is solution which uses COMPRESSION, and solves
the general problem involving any arbitrary Python object
including new classes. Rather than micro-manage mere
tuples sometimes it's better to use a DRY tool.
Your code will be more crisp and readily refactored
in similar future situations.
y_serial.py module :: warehouse Python objects with SQLite
"Serialization + persistance :: in a few lines of code, compress and annotate Python objects into SQLite; then later retrieve them chronologically by keywords without any SQL. Most useful "standard" module for a database to store schema-less data."
http://yserial.sourceforge.net
[If you are still concerned, why not stick those tuples in
a dictionary, then apply y_serial to the dictionary.
Probably any overhead will vanish due to the transparent
compression in the background by zlib.]
As to readability, the documentation also gives details on
why cPickle was selected over json.


Q: React get metamask latest transaction status I am using this, to make a function call in smart contract via metamask in react:
export default class EthereumForm1 extends Component {
  constructor (props) {
    super (props);
    const MyContract = window.web3.eth.contract(ContractABI);

    this.state = {
      ContractInstance: MyContract.at('ContractAddress')
    }
    this.doPause = this.doPause.bind (this);
}
  doPause() {
    const { pause } = this.state.ContractInstance;

    pause (
      {
        gas: 30000,
        gasPrice: 32000000000,
        value: window.web3.toWei (0, 'ether')
      },
      (err) => {
      if (err) console.error ('Error1::::', err);
      console.log ('Contract should be paused');
    })
  }

What I want is to run jQuery code with loading gif: $(".Loading").show();
while transaction is being processed and remove it after. Also, it would be good to add transaction status in div after, like in metamask(either passed or rejected).

A: What helped me was checking every few seconds if my transactiopn finished, and if yes hiding the loader.
if (latestTx != null) {
  window.web3.eth.getTransactionReceipt(latestTx, function (error, result) {
    if (error) {
      $(".Loading").hide();
      console.error ('Error1::::', error);
    }
    console.log(result);
    if(result != null){
      latestTx = null;
      $(".Loading").hide();
    }
  });
}

A: You don't need jquery to do this. React state can manage the status of the progress automatically. All you have to do is to call setState function.
class EthereumFrom1 extends React.Component {

    state = {
        loading: false
    };

    constructor(props) {
        super(props);

        this.doPause = this.doPause.bind(this);

    }

    doPause() {
        const {pause} = this.state.ContractInstance;

        pause(
            {
                gas: 30000,
                gasPrice: 32000000000,
                value: window.web3.toWei(0, 'ether')
            },
            (err) => {
                if (err) console.error('Error1::::', err);
                this.setState({loading: true});
            })
    }

    render() {
        return (

                {this.state.loading ?

                        Loading...

 :
done

                }

        )
    }
}


Q: my server it looking for a file, but i have a string, How would i simulate a fileupload via jquery i was curious if there was a way for me to set up an ajax call such that a string would be recognized as a file.
i essentially created a XML via javascript that is in string format, and want to upload it, but the server looks for a file.
I was thinking that i would have to post it to a webservice such that it would post to a iframe as file contents or something and then upload it that way or some other hack around it.
EDIT:  I was thinking this might be a solution?  Creating a fake file?  How to upload string as file with jQuery or other js framework

A: After looking at the same for how to upload a string as a file with Jquery and then looking at how the server processed the information.  I determined that the data saved doesnt nessicarily have to be that of a file.  When looking at responsees, all that information was in the string the next time it was pulled.  I actually just removed the data and pushed it up and it returned what i wanted.
var myData = {
   user: top.USERNAME,
   pass: top.PW_HASH,
   secure: true,
   url: top.BASE_URL,
   ext: "foo",
   data:saveXML
 };

which as you can see, the data being passed in the object to my $.ajax wrapper was just the saveXML.


Q: X Axis on graph in Power BI does not display full date range I am new at Power BI and created a column chart to display events for every month in a 13 month period. The X axis is displaying all the data, but the naming of the months is not correct as it skips every second month. Does anyone know where I can change this as I suspect it might only be a format change.
I have attached a screenshot to show the x axis.
Thank you!
enter image description here

A: Please go to X-axis in format tab in Visualizations and change type from Continuous to Categorical.
Type as Categorical
Create a calculated column as follows and sort it using Date field
MonthLabel = CONCATENATE(CONCATENATE(LEFT([Date].[Month],3)," "),Right([Date],4))
Hope this helps!
Best Regards,
Shani Noorudeen


Q: Here the class Main is throwing DERIVED without declaring Main as THROWS but it works, can anyone explain this Here the class Main is throwing DERIVED without declaring Main as THROWS but it works, can anyone explain this.
class Base extends Exception {}
    class Derived extends Base  {}
     public class Main {//main class throwing DERIVED
     public static void main(String args[]) {
       // some other stuff
       try {
           // Some monitored code
           throw new Derived();
        }
        catch(Base b)     {
           System.out.println("Caught base class exception");
        }
        catch(Derived d)  {
           System.out.println("Caught derived class exception");
        }
      }
    }


Q: How to find a substring in a cell array I am trying to use regexp in MATLAB to search for two words in strings in cell arrays. My cell array contains
strings={'1abc_2def_ghi_AB_12A','1abc_2def_ghi_BD_19A','1abc_2def_ghi_CD_16A',}

How would I go about constructing the expression to search the cell array for the string that contains both 'ghi' and '12'?
Thanks in advance for any assistance.

A: How about this?
result = find(~cellfun(@isempty, regexp(strings, 'ghi')) & ...
    ~cellfun(@isempty, regexp(strings, 'AB')));

Or, using a single regular expression,
result = find(~cellfun(@isempty, regexp(strings, '(ghi.*AB|ghi.*AB)')));


Q: addHTMLImage not working I am working on a project that sends out HTML emails to people after a forum is filled out, I have gotten the HTML portion of the code to work but for some reason cannot get the banner image to appear at the top when embedding the image into my code. I had it work before when I was working on the latest version of PHP but had to downgrade to PHP 5.3 in order for my scripts to run on our server. Since then I used the same code and it resulted in failure. I have tried many different methods and none have proven effective. Here is my code
    require_once('Mail.php');
    require_once('Mail/mime.php');

    $smtp_credentials = array('host' => 'smtp.postmarkapp.com', 'port' => 25, 'auth' =>          TRUE, 'username' => '*', 'password' => '*');

    $headers = array('From' => '*', 'To' => $email, 'Subject' => $subject);

    $mime = new Mail_mime(array('eol' => PHP_EOL));

    $file = '/*/*/*/dls.jpg';
    $mime->addHTMLImage(file_get_contents($file),'image/jpeg',basename($file),false, "blackstone");

    #I used this code to fish out the cid out of mime I tried echoing this out and
    # it returned blackstone which I defined as the 5th parameter of addHTMLImage which
    # sets the cid.
    $cid=$mime->_html_images[count($mime->_html_images)-1]['cid'];

    $banner = '

    ';

    $message_text = $banner;

    $mime->setHTMLBody($message_text);

    $mime->setTXTBody($body_text);

    $mail = Mail::factory('smtp', $smtp_credentials);

    try {
    $send = $mail->send($email, $mime->headers($headers), $mime->get());

    } catch (Exception $e) {

    echo $e->getMessage(); die;
    }

    echo 'mail sent!';

I have tried many different things, like not using cids at all which I would prefer since a lot of mail clients do not work well with cids, but on the PEAR manual it is suggested to use cid in the src attribute. I am using gmail, but I do not think this is the problem since it worked when I was running the newer version of php. whenever I open the email, the html portion of it works. Where the image should be there is a little image icon but no image is displayed.

A: The image url is supposed to be an absolute url.. not a path (relative or absolute).. it can't be a path, it must be a complete url to the image.
So you need to use a valid url such as the one below.
http://www.example.com/images/image-name.jpg
Something like the below would not work.
../path/to/images/image-name.jpg
and the same goes for below (it won't work):
/root/public/path/to/images/image-name.jpg
so make sure you are specifying a valid url to your image.


Q: How to set element invisible with animation? I have this toggle button that when it is on, calls an animation method that sets several elements visible. But when I turn it off, the elements remain visible, although the opposite instruction. How can I make them disapear with the same logic? Do I have to create another method? Thanks, here's the code:
 drum.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                key1.setVisibility(View.VISIBLE);
                key1.startAnimation(fadeInAnimation());

                key2.setVisibility(View.VISIBLE);
                key2.startAnimation(fadeInAnimation());

                key3.setVisibility(View.VISIBLE);
                key3.startAnimation(fadeInAnimation());

                rocking.setLooping(true);
                rocking.start();

                Toast.makeText(getApplicationContext(), "Rock and Rolling!", Toast.LENGTH_SHORT).show();
            } else {
                rocking.setLooping(false);
                key1.setVisibility(View.INVISIBLE);// These instrucions are ignored...
                key2.setVisibility(View.INVISIBLE);
                key3.setVisibility(View.INVISIBLE);

                Toast.makeText(getApplicationContext(), "Can't keep up? Try the tamborine!", Toast.LENGTH_SHORT).show();

            }
        }
    });

And the animation method:
private Animation fadeInAnimation() {
Animation animation = new AlphaAnimation(0f, 1.0f);
animation.setDuration(1000);
animation.setFillEnabled(true);
animation.setFillAfter(true);
return animation;
}

A: Change the fadeInAnimation and pass a boolean argument, if true do fade-In animation else fade-out animation. Code sample is given below. Usage fadeAnimation(true) for fadeIn animation and fadeAnimation(false) for fadeOut animation. Hope this helps.
private Animation fadeAnimation(boolean fadeIn) {

 Animation animation = null;
 if(fadeIn)
    animation = new AlphaAnimation(0f, 1.0f);
 else
    animation = new AlphaAnimation(1.0f, 0f);
 animation.setDuration(1000);
 animation.setFillEnabled(true);
 animation.setFillAfter(true);
 return animation;

}

A: Checkout below code
viewObject.animate()
            .alpha(0.0f)
            .setStartDelay(10000)
            .setDuration(2000)
            .setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    // do your stuff if any, after animation ends
                }
            }).start();

A: possible duplicate of View.setVisibility(View.INVISIBLE) does not work for animated view. visibility are not honoured as long as an animation is  performed even though  animation is cancelled


Q: what does allowLossyConversion mean in ios I am using the dataUsingEncoding(encoding: NSStringEncoding, allowLossyConversion: Bool = default) -> NSData? function to convert String to NSData, but I don't get what allowLossyConversion actually means.
Is it similar to Lossy compression? Can anybody help me understand this?

A: If flag is YES and the receiver can’t be converted without losing some information, some characters may be removed or altered in conversion. For example, in converting a character from NSUnicodeStringEncoding to NSASCIIStringEncoding, the character ‘Á’ becomes ‘A’, losing the accent.


Q: How can I set different session lifetime for each role? How can I set different session lifetime for each symfony role? Is there a built-in option for doing this?
We're using different roles, one for our clients and one for each department within our company. We'd like to increase session lifetime for company roles without increasing it for the clients role.

A: You would have to set the session lifetime for the role that has the highest, and then, saving dates on your database, log users out after the amount of time that you want.


Q: Angular component has click listener attribute How can I know within my-component, if the parent listens to the click event (A) or not (B).
Case A:
<my-component (click)="onClick()"></my-component>

Case B:
<my-component></my-component>

Definition:
@Component({
  selector: 'my-component',
  templateUrl: './my-component.component.html',
})
export class MyComponent {
  @???()
  hostHasClickListener: boolean;   // I want to know this within my component
}

Thank you!

A: You can achieve this by using an @Output with click as the name. This forces the consumers to bind their function to this click when they use (click)="Blah()" in the HTML.
this.click.observed return true when click is used in the HTML.
mycomponent.component.ts
@Component({
  ...
})
export MyComponent implements OnInit {

  @Output()
  public click = new EventEmitter();

  private _hasClick = false;

  public ngOnInit() {

     this._hasClick = this.click.observed;

     if(this._hasClick) {
       // do something here.
     }

  }
}


Q: replace columns in hive I have created a table in hive, now I am trying to replace the columns name using REPLACE COLUMNS.
Alter query is:
**ALTER TABLE emp1 REPLACE COLUMNS (
id INT eid int,
name STRING ename string,
sal INT esal int,
city string ecity string,
country string ecountry string);**

MismatchedTokenException(26!=301)
    at org.antlr.runtime.BaseRecognizer.recoverFromMismatchedToken(BaseRecognizer.java:617)
    at org.antlr.runtime.BaseRecognizer.match(BaseRecognizer.java:115)
    at org.apache.hadoop.hive.ql.parse.HiveParser.alterStatementSuffixAddCol(HiveParser.java:9898)
    at org.apache.hadoop.hive.ql.parse.HiveParser.alterTblPartitionStatementSuffix(HiveParser.java:8524)
    at org.apache.hadoop.hive.ql.parse.HiveParser.alterTableStatementSuffix(HiveParser.java:8139)
    at org.apache.hadoop.hive.ql.parse.HiveParser.alterStatement(HiveParser.java:7190)
    at org.apache.hadoop.hive.ql.parse.HiveParser.ddlStatement(HiveParser.java:2602)
    at org.apache.hadoop.hive.ql.parse.HiveParser.execStatement(HiveParser.java:1589)
    at org.apache.hadoop.hive.ql.parse.HiveParser.statement(HiveParser.java:1065)
    at org.apache.hadoop.hive.ql.parse.ParseDriver.parse(ParseDriver.java:201)
    at org.apache.hadoop.hive.ql.parse.ParseDriver.parse(ParseDriver.java:166)
    at org.apache.hadoop.hive.ql.Driver.compile(Driver.java:462)
    at org.apache.hadoop.hive.ql.Driver.compileInternal(Driver.java:1276)
    at org.apache.hadoop.hive.ql.Driver.runInternal(Driver.java:1393)
    at org.apache.hadoop.hive.ql.Driver.run(Driver.java:1205)
    at org.apache.hadoop.hive.ql.Driver.run(Driver.java:1195)
    at org.apache.hadoop.hive.cli.CliDriver.processLocalCmd(CliDriver.java:220)
    at org.apache.hadoop.hive.cli.CliDriver.processCmd(CliDriver.java:172)
    at org.apache.hadoop.hive.cli.CliDriver.processLine(CliDriver.java:383)
    at org.apache.hadoop.hive.cli.CliDriver.executeDriver(CliDriver.java:775)
    at org.apache.hadoop.hive.cli.CliDriver.run(CliDriver.java:693)
    at org.apache.hadoop.hive.cli.CliDriver.main(CliDriver.java:628)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:136)
FAILED: ParseException line 2:7 mismatched input 'eid' expecting ) near 'INT' in add column statement
Please help me. I am learning hive

A: REPLACE is used when you want to have an altogether different columns to your table.If not it is better to rename the column_name with the CHANGE option in the alter statement.

A: The ALTER TABLE <TableName> REPLACE COLUMNS removes all existing columns and adds the new set of columns.
ALTER TABLE <TableName> REPLACE COLUMNS
(EID INT,
EName STRING);
REPLACE COLUMNS
For your scenario you can make use of ALTER TABLE <TableName> CHANGE <ColumnName>
ALTER TABLE <TableName> CHANGE ID EID INT;
This page will give you a lots of information ALTER COLUMNS


Q: Why, in Python, a dictionary does not need to be nonlocal to be seen in an inner function I am learning Python and while I was doing exercises with decorators, I found a case that I don't understand. The code bellow, inspired by the tutorial I use, is working:
>>> def maxExeTime(absMax,printMax=False):
...     def decorFun(toDo):
...         storeInfo = {"exeMax":0}
...         def modified(*p,**pp):
...             startTime = time.time()
...             returnValue = toDo(*p,**pp)
...             exeTime = time.time() - startTime
...             if exeTime > storeInfo["exeMax"]:
...                 storeInfo["exeMax"] = exeTime
...             if printMax:
...                 print("max execution time = {}".format(storeInfo["exeMax"]))
...             if exeTime > absMax:
...                 raise Exception("Max exe time reached: {}".format(exeTime))
...             return returnValue
...         return modified
...     return decorFun
...
>>> @maxExeTime(15,printMax=True)
... def mul(x,y):
...     input("Press Enter...")
...     return x*y
...
>>>
>>> mul(3,4)
Press Enter...
max execution time = 1.1439800262451172
12
>>> mul(3,5)
Press Enter...
max execution time = 2.1652064323425293
15
>>> mul(3,7)
Press Enter...
max execution time = 2.1652064323425293
21
>>> mul(3,10)
Press Enter...
max execution time = 21.074586629867554
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 13, in modified
Exception: Max exe time reached: 21.074586629867554
>>>

But I don't understand why the dictionary storeInfo is persistent and can be re-used from one call to the other. If I try to store the information directly in a variable (ie exeMax=0) and adapt the code accordingly, I get the behavior that I was expecting with an exception at run time: UnboundLocalError: local variable 'exeMax' referenced before assignment when I try to compare the current execution time with the actual max value (if exeTime > exeMax:)
Why does the dictionary persists out of the scope of the maxExeTime function execution?
Thanks to the links an the redirection to duplicate questions, I discovered closure which was a concept I never see before. Good. And I understand why it does not work in my test with the local variable exeMax since I didn't declare it as nonlocal. But I didn't do it either for the dictionary storeInfo, and it is working. Why does this type of object have a different behavior?
Edit
@kindall what you say explains why it is necessary to use nonlocal when I use and integer directly since it seems that integers have a different behavior/rules than other objects, and I want to modify the value in the inner function.
But I still don't understand why if exeTime < exeMax: fails when exeTime < storeInfo["exeMax"] does not, and then why the next code is valid.
>>> a = 12
>>> def m(x):
...     return a*x
...
>>> m(3)
36
>>> a = 15
>>> m(3)
45

For the moment, all these differences in behavior make the variable scope definition looking fuzzy for me. I need to find a clear definition of it, with, I hope, a small set of rules and no exception.


Q: TypeGuards for optional property while filtering array of objects I've got the following interfaces in typescript:
interface ComplexRating {
  ratingAttribute1?: number;
  ratingAttribute2?: number;
  ratingAttribute3?: number;
  ratingAttribute4?: number;
}

export interface Review {
  rating: ComplexRating | number;
}

I'd love to calculate an average rating for say ratingAttribute1 for sake of simplicity.
So given these reviews:
const reviews: Review[] = [
  { rating: { ratingAttribute1: 5 } },
  { rating: { ratingAttribute1: 10 } },
  { rating: { ratingAttribute2: 15 } },
  { rating: 5 }
]

I can filter down the reviews to the ones I'm interested in i.e.:
const calculateAverageRating = (reviews: Review[]): number => {
  const reviewsWithRating = reviews.filter(
    (review) =>
      typeof review.rating === 'object' &&
      typeof review.rating['ratingAttribute1'] === 'number'
  );
  return (
    reviewsWithRating.reduce((acc, review) => {
      let newValue = acc;
      if (typeof review.rating === 'object') {
        const rating = review.rating['ratingAttribute1'];
        if (rating) {
          newValue += rating;
        }
      }
      return newValue;
    }, 0.0) / reviewsWithRating.length
  );
};

Now, what's annoying is that Typescript does not know that by running the reviews.filter function I type guarded the Reviews only to a subset of the Reviews that have rating of type ComplexType and also the ones that have ratingAttribute1: number;  rather than ratingAttribute?: number.
What I'd love to end up with is not having to repeat the type checks in the calculation effectively ending up with:
const calculateAverageRating = (reviews: Review[]): number => {
  const reviewsWithRating = reviews.filter(
    (review) =>
      typeof review.rating === 'object' &&
      typeof review.rating['ratingAttribute1'] === 'number'
  );
  return (
    reviewsWithRating.reduce(
      (acc, review) => acc + review.rating['ratingAttribute1'],
      0.0
    ) / reviewsWithRating.length
  );
};

but that does not work out of the box:

Is there any way of achieving this level of type guarding? Or is there a neater of way doing this type of stuff?

A: The .filter() function will always return an array of the same type that was given as the argument. That is why reviewsWithRating is still a Review[], even after you filter it.
To change this, you can add a type guard to the callback:
const reviewsWithRating = reviews.filter(
  (review): review is { rating: Required<ComplexRating> } =>
    typeof review.rating === 'object' &&
    typeof review.rating['ratingAttribute1'] === 'number'
);

Now TypeScript will know that reviewsWithRating is of type { rating: Required<ComplexRating> }[].


Q: Connection Error in SQL Server Compact with ASP.Net I am trying to access a database, using a DataSet. I am using Visual Studio for Web Express 2013, ASP Web Forms project with SQL Server Compact 4.0. I created the database from Database Explorer, added 3 tables, now my code has getData, setData methods which will use Dataset to get data.
But the SqlConnection object is throwing exception at runtime.

[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error:
   26 - Error Locating Server/Instance Specified)]

I guess this is due to connection string since error is at line:
SLQCon.Open();

I have tried more than one method but none of them has worked yet. These are few of them,
msdn link
Connection Strings
The other things work fine (web form controls), only problem is when I do something related to database, any fixes?
My code is as follows:
void setData(string tableName) {
    string ConString = @"Data Source=" + "F:\\Github\\JournalClassifier\\WebApplication1\\WebApplication1\\App_Data\\KeywordsDB.sdf" + ";Connect Timeout=30";

    SQLCon.ConnectionString = ConString;

    SQLCon.Open();      // Exception here

    // insertion code
}

A: Make sure your database inside App_Data folder on your root application. and change the connection string to this one
<add name="ConnectionStringName"
    providerName="System.Data.SqlServerCe.4.0"
    connectionString="Data Source=\KeywordsDB.sdf;Connection Timeout=30" />

things you need to concern is you are using SQL Server Compact, so the provider name need use System.Data.SqlServerCe.4.0 otherwise it will confused with SQL Server Client


Q: How to detect corner "joints" that connect elements on images? I'm using OpenCV via Python 3.7. I have a set of monochrome images that look like this:

I'd like to find all "joint points" on these images, where a "joint point" - is a center (1 pixel) of every intersection of two planks. These "joints" are roughly represented by red cicrles on the image below:

The first idea was to skeletonize the image and then find all connected edges algorythmically, but all skeletonizations technques gave me wiggly or round corners and extra "sprouts".
import cv2
import numpy as np
from skimage.morphology import skeletonize

image = cv2.imread("SOURCE_IMAGE.jpg", cv2.IMREAD_GRAYSCALE)
binary_image = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 91, 12)
skeleton = (skeletonize(binary_image//255) * 255).astype(np.uint8)

Result:

The second idea was to find inner contours, approximate them to bounding points, find closest neighbours and then somehow calculate centers, but, again, Canny edge detection method gave me wiggly corners and extra points.
import cv2

image = cv2.imread("SOURCE_IMAGE.jpg", cv2.IMREAD_GRAYSCALE)
edged = cv2.Canny(image, 100, 200)

Result:

Are there any reliable approcahes to this problem?

A: This is my approach to solve this issue:

*

*Determine vertical lines

*Determine horizontal lines

*Find their intersections which are joints

For first step check each column and determine thin lines and make them black(0). The result will be only vertical lines. For the second step do reverse.
At the end compare vertical line image with the horizontal line image. The pixels which are white(255) in both are the intersection points.
Note: Please do not blame me because of coding in C++. I am not familiar with python I just wanted to show my approach and results.
Here is the code and results:
Source:

Vertical Lines:

Horizontal Lines:

Result:

The code:
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
using namespace std;
using namespace cv;

int main()
{
    Mat img = imread("/ur/image/directory/joints.jpg",1);

    imshow("Source",img);

    int checker = 1,checker2 = 1;
    int begin_y,finish_y2,finish_y,begin_y2;
    Mat vertical_img = img.clone();
    Mat horizontal_img = img.clone();

    cvtColor(vertical_img,vertical_img,CV_BGR2GRAY);
    cvtColor(horizontal_img,horizontal_img,CV_BGR2GRAY);

    int finish_checker = 0,finish_checker2=0;
    for(int i=0;i<horizontal_img.rows;i++)
    {
        for(int j=0;j<horizontal_img.cols;j++)
        {
            if(horizontal_img.at<uchar>(Point(j,i))>100 && checker)
            {
                begin_y = j;
                checker = 0;
            }

            if(horizontal_img.at<uchar>(Point(j,i))<20 && checker==0)
            {
                finish_y = j;
                checker = 1;
                finish_checker = 1;

            }

            if(finish_checker)
            {
                if((finish_y-begin_y)<30)
                {
                    for(int h=begin_y-2;h<=finish_y;h++)
                    {
                        horizontal_img.at<uchar>(Point(h,i)) = 0;
                    }
                }

                finish_checker = 0;
            }
        }
    }

    imshow("Horizontal",horizontal_img);

    for(int i=0;i<vertical_img.cols;i++)
    {
        for(int j=0;j<vertical_img.rows;j++)
        {
            if(vertical_img.at<uchar>(Point(i,j))>100 && checker2)
            {
                begin_y2 = j;
                checker2 = 0;
            }
            if(vertical_img.at<uchar>(Point(i,j))<50 && checker2==0)
            {
                finish_y2 = j;
                checker2 = 1;
                finish_checker2 = 1;
            }
            if(finish_checker2)
            {
                if((finish_y2-begin_y2)<30)
                {
                    for(int h=begin_y2-2;h<=finish_y2;h++)
                    {
                        vertical_img.at<uchar>(Point(i,h)) = 0;
                    }
                }
                finish_checker2 = 0;
            }
        }
    }
    imshow("Vertical",vertical_img);

    for(int y=0;y<img.cols;y++)
    {
        for(int z=0;z<img.rows;z++)
        {
            if(vertical_img.at<uchar>(Point(y,z))>200 && horizontal_img.at<uchar>(Point(y,z))>200)
            {
                img.at<cv::Vec3b>(z,y)[0]=0;
                img.at<cv::Vec3b>(z,y)[1]=0;
                img.at<cv::Vec3b>(z,y)[2]=255;
            }
        }
    }

    imshow("Result",img);
    waitKey(0);
    return 0;
}

A: Here's a slight modified version of @YunusTemurlenk's approach using Python instead of C++. The idea is:

*

*Obtain binary image. Load image, convert to grayscale, Gaussian blur, then Otsu's threshold.

*Obtain horizontal and vertical line masks. Create horizontal and vertical structuring elements with cv2.getStructuringElement then perform cv2.morphologyEx to isolate the lines.

*Find joints. We cv2.bitwise_and the two masks together to get the joints.

*Find centroid on joint mask. We find contours then calculate the centroid.

Horizontal/vertical line masks

Detected joints in green

Results

import cv2
import numpy as np

# Load image, grayscale, Gaussian blur, Otsus threshold
image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

# Find horizonal lines
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (10,1))
horizontal = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, horizontal_kernel, iterations=2)

# Find vertical lines
vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1,10))
vertical = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, vertical_kernel, iterations=2)

# Find joints
joints = cv2.bitwise_and(horizontal, vertical)

# Find centroid of the joints
cnts = cv2.findContours(joints, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    # Find centroid and draw center point
    M = cv2.moments(c)
    cx = int(M['m10']/M['m00'])
    cy = int(M['m01']/M['m00'])
    cv2.circle(image, (cx, cy), 3, (36,255,12), -1)

cv2.imshow('thresh', thresh)
cv2.imshow('horizontal', horizontal)
cv2.imshow('vertical', vertical)
cv2.imshow('joints', joints)
cv2.imshow('image', image)
cv2.waitKey()


Q: Convert POJO into JSON I have a POJO.
@Data
@AllArgsConstructor
@Builder
public class Emp {
    private String position;
    private String name;
}

Suppose, we have created an object
Emp emp = new Emp("Manager", "Bob");

How can I convert it to a list and save it in a database in JSON format?
The data should be stored in the database in the format below:
{
  list:[
    {
       position: Manager
       name: Bob
    }
  ]
}

Are there any ready solutions for that?
I  converted an object into a list and then I called the .toString() method on it:
Collections.singletonList(emp);

But when I store it in the database, the next save goes to the database:
[Emp(position=Manager, name=Bob)]

But I need to store the record in a different way

A:
How can I convert it to a list and save it in a database in JSON
format?
The data should be stored in the database in the format below:
{
  "list": [
    {
       "position": "Manager"
       "name": "Bob"
    }
  ]
}

Since the serialized JSON is required to have a property "list" you can't simply serialize the List as is.
Instead, you can define a POJO wrapping this list.
That's how it might look like (I've made it generic in order to make it suitable for serializing any type of list):
@Data
@AllArgsConstructor
public static class ListWrapper<T> {
    private List<T> list;
}

And that's how it can be serialized using Jackson's ObjectMapper and ObjectWriter:
List<Emp> emps = List.of(new Emp("Manager", "Bob"));
ListWrapper<Emp> listWrapper = new ListWrapper<>(emps);

ObjectMapper mapper = new ObjectMapper();
ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();

String json = writer.writeValueAsString(listWrapper);
System.out.println(json);

Output:
{
  "list" : [ {
    "name" : "Manager",
    "position" : "Bob"
  } ]
}

A: If you need to store the object list as JSON in DB then you need Convert the list of object to JSON string using Jackson ObjectMapper. Store the converted string to DB.


Q: testing sails.js with mocha: can't find /api/services/myService consider this mocha test:
var Sails = require('sails');

describe("Foo Model creation:", function() {
  // create a variable to hold the instantiated sails server
  var app;

  // Global before hook
  before(function(done) {
    // Lift Sails and start the server
    Sails.lift({
      log: {
        level: 'error'
      }
    }, function(err, sails) {
      app = sails;
      done(err, sails);
    });
  });

  // Global after hook
  after(function(done) {
    app.lower(done);
  });

  describe("new foo", function() {
    var foo;
    before(function (cb) {
      var fooData = {
        name: "test foo to be removed after test"
      };

      Foo.create(fooData, function (err, newFoo)
        if (err) return cb(err);
        foo = newFoo;
        cb();
      });
    });
    it("must show the name", function() {
      foo.must.have.property('name');
    });

    after(function (cb){
      foo.destroy(function (err) {
        cb(err);
      });
    });
  });
})

This would work except that the Foo model depends on a sails service i.e. library code defined in /api/services.  Sails, when lifted here, can't find those services.
Is there a way to instruct Sails during a mocha test to also load the services?

A: I had a similar issue, and indeed, Sails should be loading services, controllers, etc.
There were some debug tools that helped when lifting Sails:
Sails.lift({
  log: {
    level: 'verbose'
  },
  appPath: '../',
  // explicitly load almost everything but policies
  //loadHooks: ['moduleloader', 'userconfig', 'orm', 'http', 'controllers', 'services', 'request', 'responses', 'blueprints']
}

I also did a live debug of Mocha (though I won't go into steps on that here).
What I found out through debugging and a log level of verbose (you could also try silly if verbose doesn't answer a question) is that I was loading Sails from the wrong directory - the test directory.  Once I changed appPath to '../', I could tell from the log messages that it was loading the proper content, and voila, my sails.services.myService object was now there!
Hope that helps!


Q: How to capture file save as cancel respond I followed this post http://www.the-art-of-web.com/php/dataexport/ and successfully create an export to csv file from DB, base on user current search view. But to prevent hit to db while export is happening so I disable the export unless there is change within the view or user query.  The issue I face with is when user hit on export a file save as confirm dialog pop up and if user changed her mind click on cancel.  The export button remain disable.  The only way for user to get back is to change query and come back again.
My question is there anyway I could capture the cancel click respond on file save as confirm dialog.
Thanks
The code is very similar to http://www.the-art-of-web.com/php/dataexport/  Where as the view would be a grid with bunch of customer information from given date range.  If user like the view they choose.  They would click on export button.
sample code
export.php
function exportCSV(){
  document.getElementById("exportCSV").src = "test1.php";
  document.getElementById("exportBtn").disabled = true;
}

function performSearch(){
  //perform search get result and display
  //if resultset length > 0
  document.getElementById("exportBtn").disabled = false;
}

Grid display right here
 <button id="search" onclick="performSearch()">Search
 <button id="exportBtn" onclick="exportCSV()"> Export
 <iframe id="exportCSV" style="display:none"/>
test1.php
$data = array(
       array("firstname" => "Mary", "lastname" => "Johnson", "age" => 25),
       array("firstname" => "Amanda", "lastname" => "Miller", "age" => 18),
       array("firstname" => "James", "lastname" => "Brown", "age" => 31),
       array("firstname" => "Patricia", "lastname" => "Williams", "age" => 7),
       array("firstname" => "Michael", "lastname" => "Davis", "age" => 43),
       array("firstname" => "Sarah", "lastname" => "Miller", "age" => 24),
       array("firstname" => "Patrick", "lastname" => "Miller", "age" => 27)
     );
# filename for download
 $filename = "website_data.xls";
header("Content-Disposition: application/octet-stream; filename=\"$filename\"");
 header("Content-Type: application/vnd.ms-excel");
$flag = false;
 foreach($data as $row) {
   if(!$flag) {
     # display field/column names as first row
     echo implode("\t", array_keys($row)) . "\n";
     $flag = true;
   }
   array_walk($row, 'cleanData');
   echo implode("\t", array_values($row)) . "\n";
 }
 exit;
 function cleanData(&$str)
 {
   $str = preg_replace("/\t/", "\\t", $str);
   $str = preg_replace("/\r?\n/", "\\n", $str);
   if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
 }

A: There's no way to capture the browser event for canceling a save file.  Using a confirm in an if statement(or something similar) is probably the best ux for that situation:
if(confirm('are you sure you want to export?'))
{
//export code
}
else
{
//cancel code
}

If you want your export button to become re-enabled I would call a re-enable function whenever your user's search(or whatever action they make to change data) is called. Or you can also use setTimeout() after the export button is hit and re-enable it after a certain time period.

A: Maybe you can send the dump file through a php script. There you (again: maybe, I dont know, if it really works) can test the connection status with connection_status(). But if you send the file through a php-script, you dont need to know the status, because if the script shutdown properly, it doenst matter, if the transmission were completed, if you just want to unlock the database.
Usually a normal database dump is safe anyway. So if you let the database dump the data it contains and save it to a file, there is no reason to lock the database while someone downloads a file.


Q: Better solution to data storage and passing I'm trying to find a more elegant solution for some code I'm working on at the moment. I have data that needs to be stored then moved around, but I don't really want to take up any more space than I need to for the data that is stored.
I have 2 solutions, but neither seem very nice.

Using inheritance and a tag
enum class data_type{
    first, second, third
};

class data_base{
    public:
        virtual data_type type() const noexcept = 0;
};

using data_ptr = data_base*;

class first_data: public data_base{
    public:
        data_type type() const noexcept{return data_type::first;}

        // hold the first data type
};

// ...

Then you pass around a data_ptr and cast it to the appropriate type.
I really don't like this approach because it requires upwards casting and using bare pointers.

Using a union and storing all data types
enum class data_type{
    first, second, third
};

class data{
    public:
        data(data_type type_): type(type_){}
        data_type type;
        union{
            // first, second and third data types stored
        };
};

But I don't like this approach because then you start wasting a lot of memory when you have a large data type that may get passed around.

This data will then be passed onto a function that will parse it into a greater expression. Something like this:
class expression{/* ... */};
class expr_type0: public expression{/* ... */};
// every expression type

using expr_ptr = expression*;

// remember to 'delete'
expr_ptr get_expression(){
    data_ptr dat = get_data();

    // interpret data
    // may call 'get_data()' many times
    expr_ptr expr = new /* expr_type[0-n] */

    delete dat;
    return expr;
}

and the problem arrises again, but it doesn't matter in this case because the expr_ptr doesn't need to be reinterpreted and will have a simple virtual function call.

What is a more elegant method of tagging and passing around the data to another function?

A: It's difficult to envisage exactly what you're looking for without more information. But if I wanted some framework that allowed me to store and retrieve data in some structured way, in as-yet-unknown storage devices this is the kind of way I'd be thinking.
This may not be the answer you're looking for, but I think there'll be concepts here that will inspire you in the right direction.
#include <iostream>
#include <tuple>
#include <boost/variant.hpp>
#include <map>

// define some concepts

// bigfoo is a class that's expensive to copy - so lets give it a shared-handle idiom
struct bigfoo {

    struct impl {
        impl(std::string data) : _data(std::move(data)) {}
        void write(std::ostream& os) const {
            os << "I am a big object. Don't copy me: " << _data;
        }
    private:
        std::string _data;
    };

    bigfoo(std::string data) : _impl { std::make_shared<impl>(std::move(data)) } {};

    friend std::ostream& operator<<(std::ostream&os, const bigfoo& bf) {
        bf._impl->write(os);
        return os;
    }

private:
    std::shared_ptr<impl> _impl;
};

// all the data types our framework handles
using abstract_data_type = boost::variant<int, std::string, double, bigfoo>;

// defines the general properties of a data table store concept
template<class...Columns>
struct table_definition
{
    using row_type = std::tuple<Columns...>;
};

// the concept of being able to store some type of table data on some kind of storage medium
template<class IoDevice, class TableDefinition>
struct table_implementation
{
    using io_device_type = IoDevice;
    using row_writer_type = typename io_device_type::row_writer_type;

    template<class...Args> table_implementation(Args&...args)
    : _io_device(std::forward<Args>(args)...)
    {}

    template<class...Args>
    void add_row(Args&&...args) {
        auto row_instance = _io_device.open_row();
        set_row_args(row_instance,
                     std::make_tuple(std::forward<Args>(args)...),
                     std::index_sequence_for<Args...>());
        row_instance.commit();
    }

private:
    template<class Tuple, size_t...Is>
    void set_row_args(row_writer_type& row_writer, const Tuple& args, std::index_sequence<Is...>)
    {
        using expand = int[];
        expand x { 0, (row_writer.set_value(Is, std::get<Is>(args)), 0)... };
        (void)x; // mark expand as unused;
    }

private:
    io_device_type _io_device;
};

// model the concepts into a concrete specialisation

// this is a 'data store' implementation which simply stores data to stdout in a structured way
struct std_out_io
{
    struct row_writer_type
    {
        void set_value(size_t column, abstract_data_type value) {
            // roll on c++17 with it's much-anticipated try_emplace...
            auto ifind = _values.find(column);
            if (ifind == end(_values)) {
                ifind = _values.emplace(column, std::move(value)).first;
            }
            else {
                ifind->second = std::move(value);
            }
        }

        void commit()
        {
            std::cout << "{" << std::endl;
            auto sep = "\t";
            for (auto& item : _values) {
                std::cout << sep << item.first << "=" << item.second;
                sep = ",\n\t";
            }
            std::cout << "\n}";
        }

    private:
        std::map<size_t, abstract_data_type> _values;  // some value mapped by ascending column number
    };

    row_writer_type open_row() {
        return row_writer_type();
    }
};

// this is a model of a 'data table' concept
using my_table = table_definition<int, std::string, double, bigfoo>;

// here is a test
auto main() -> int
{
    auto data_store = table_implementation<std_out_io, my_table>( /* std_out_io has default constructor */);
    data_store.add_row(1, "hello", 6.6, bigfoo("lots and lots of data"));

    return 0;
}

expected output:
{
        0=1,
        1=hello,
        2=6.6,
        3=I am a big object. Don't copy me: lots and lots of data
}


Q: Application is getting crash while using gridview in Android In my app i want to use a gridView in fragment of navigation drawer but my application is getting crash.
this is my code:
public class HomeFragment extends Fragment {

    GridView gridView;
    private String[] categoryHomeGridView;
    private Integer[] icon={R.drawable.cat_offer_women,R.drawable.cat_offer_men,
            R.drawable.cat_offer_food_and_drink,R.drawable.cat_offer_electronics};
    private ArrayList homeGridViewItems;
    private HomeGridViewListAdapter adapter;
    public HomeFragment(){}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        init();
        return view;
    }

    private void init() {
        // TODO Auto-generated method stub
        gridView=(GridView) getActivity().findViewById(R.id.homeGridView);
        categoryHomeGridView=getActivity().getResources().getStringArray(R.array.category_array);

        homeGridViewItems=new ArrayList();
        homeGridViewItems.add(new HomeGridViewItem(categoryHomeGridView[0],
                icon[0]));
        homeGridViewItems.add(new HomeGridViewItem(categoryHomeGridView[1],
                icon[1]));
        homeGridViewItems.add(new HomeGridViewItem(categoryHomeGridView[2],
                icon[2]));
        homeGridViewItems.add(new HomeGridViewItem(categoryHomeGridView[3],
                icon[3]));
    //  iconHomeGridView.recycle();

        adapter=new HomeGridViewListAdapter(getActivity().getApplicationContext()
                ,homeGridViewItems);
        gridView.setAdapter(adapter);

    }
}

and this is crash log

03-26 14:50:56.524: E/AndroidRuntime(2355): FATAL EXCEPTION: main
03-26 14:50:56.524: E/AndroidRuntime(2355): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.couponoffer/com.example.couponoffer.MainActivity}: java.lang.NullPointerException
03-26 14:50:56.524: E/AndroidRuntime(2355):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at android.app.ActivityThread.access$600(ActivityThread.java:130)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at android.os.Looper.loop(Looper.java:137)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at android.app.ActivityThread.main(ActivityThread.java:4745)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at java.lang.reflect.Method.invokeNative(Native Method)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at java.lang.reflect.Method.invoke(Method.java:511)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at dalvik.system.NativeStart.main(Native Method)
03-26 14:50:56.524: E/AndroidRuntime(2355): Caused by: java.lang.NullPointerException
03-26 14:50:56.524: E/AndroidRuntime(2355):     at fragments.HomeFragment.init(HomeFragment.java:57)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at fragments.HomeFragment.onCreateView(HomeFragment.java:34)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:829)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1035)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at android.app.BackStackRecord.run(BackStackRecord.java:635)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1397)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at android.app.Activity.performStart(Activity.java:5017)
03-26 14:50:56.524: E/AndroidRuntime(2355):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2032)
03-26 14:50:56.524: E/AndroidRuntime(2355):     ... 11 more

A: Place this line gridView=(GridView) getActivity().findViewById(R.id.homeGridView); in onCreate and do it like this gridView=(GridView) view.findViewById(R.id.homeGridView); because your gridview is part of your View. Or pass the View view to init();
like this:
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        init(view);
        return view;
    }

private void init(View rootView) {
        // TODO Auto-generated method stub
        gridView=(GridView) rootView.findViewById(R.id.homeGridView);
        categoryHomeGridView=getActivity().getResources().getStringArray(R.array.category_array);

        homeGridViewItems=new ArrayList();
        homeGridViewItems.add(new HomeGridViewItem(categoryHomeGridView[0],
                icon[0]));
        homeGridViewItems.add(new HomeGridViewItem(categoryHomeGridView[1],
                icon[1]));
        homeGridViewItems.add(new HomeGridViewItem(categoryHomeGridView[2],
                icon[2]));
        homeGridViewItems.add(new HomeGridViewItem(categoryHomeGridView[3],
                icon[3]));
    //  iconHomeGridView.recycle();

        adapter=new HomeGridViewListAdapter(getActivity().getApplicationContext()
                ,homeGridViewItems);
        gridView.setAdapter(adapter);

    }

A: The gridView probably belongs to the fragment layout
So you need to change this
 gridView=(GridView) getActivity().findViewById(R.id.homeGridView);

to
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
 View view = inflater.inflate(R.layout.fragment_home, container, false)
 gridView=(GridView) view.findViewById(R.id.homeGridView);

A: Change this:
gridView=(GridView) getActivity().findViewById(R.id.homeGridView);

to this:
View view = inflater.inflate(R.layout.fragment_home, container, false);
gridView=(GridView) view .findViewById(R.id.homeGridView);


Q: Viewing outstanding requests Is there any way to view what requests Protractor are waiting on? I'm trying to debug flaky state testing, but it is hard to tell whether a button didn't trigger a response or if Protractor didn't bother to wait.
TL;DR: How can I view the remaining promises on the Protractor control flow?

A: The usual approach is to start protractor in a debug mode and put browser.debugger() breakpoint before the problem block of code.
See more information at Debugging Protractor Tests.

On the other hand, you can catch the chromedriver service logs that look like:
[2.389][INFO]: COMMAND FindElement {
   "sessionId": "b6707ee92a3261e1dc33a53514490663",
   "using": "css selector",
   "value": "input"
}
[2.389][INFO]: Waiting for pending navigations...
[2.389][INFO]: Done waiting for pending navigations
[2.398][INFO]: Waiting for pending navigations...
[2.398][INFO]: Done waiting for pending navigations
[2.398][INFO]: RESPONSE FindElement {
   "ELEMENT": "0.3367185448296368-1"
}

Might also give you a clue of what is happening.
For this, you need to start chrome with --verbose and --log-path arguments:
{
     browserName: "chrome",
     specs: [
         "*.spec.js"
     ],
     chromeOptions: {
         args: [
             "--verbose",
             "--log-path=/path/to/the/log/file"
         ]
     }
 }

(not tested)
For firefox, you can turn on and view logs by setting webdriver.log.driver and webdriver.log.file firefox profile settings.
See also:

*

*Monitoring JSON wire protocol logs

*How to change firefox profile


Q: Trying to create composite unique index with partialFilterExpression I'm trying to create an unique index for my collection with composite keys, but some documents might have null on the fields of the index. Going by the documentation it seems I should be able to do it with partialFilterExpression.
I tried it as following:
db.collection.createIndex(
 { a: 1, b: 1, c: 1 },
 {
   "background":true,
   "unique": true,
   "partialFilterExpression": {
     "a": { "$exists": true },
     "b": { "$exists": true },
     "c": { "$exists": true }
   }
 })

but that gave me the following error:

exception: E11000 duplicate key error collection: schema.collection index: a_1_b_1_c_1 dup key: { : null, : null, : null }

I even tried changing the partial filter criteria to this:
db.collection.createIndex(
  { a: 1, b: 1, c: 1 },
  {
    "background":true,
    "unique": true,
    "partialFilterExpression": {
      "a": { "$exists": true, "$ne": null  },
      "b": { "$exists": true, "$ne": null  },
      "c": { "$exists": true, "$ne": null  }
    }
  }
)

But still returned the same error.
Did I misunderstand the use or am using it wrongly?

A: Just figured out what was my issue. The version of my monogo is 3.0.12 and partialFilterExpression was introduced in version 3.2


Q: Why does Crashlytics go into an infinite loop for an unhandled exception? I have just updated to the latest Crashlytics. I tried testing it by throwing an unhandled exception.
It did not send a bug report.
The app simply froze.
Checking the debugger, it appears to be in an infinite loop.
If I pause threads in the debugger, it looks like the picture.
enter image description here
That is absolutely unacceptable. I can't ship an app like this.
This is in build.gradle at the app level.
 // Recommended: Add the Firebase SDK for Google Analytics.
    implementation 'com.google.firebase:firebase-analytics:17.1.1'

    // Add the Firebase Crashlytics SDK.
    implementation 'com.google.firebase:firebase-crashlytics:17.1.1'

This in build.gradle at the project level:
    // Add the Crashlytics Gradle plugin.
    classpath 'com.google.firebase:firebase-crashlytics-gradle:2.2.0'


Q: Checkbox with PHP and MYSQL I have two checkboxes
<form action="" method="post" enctype="multipart/form-data">
<input type="checkbox" name="file_type" value="1"> Filer

<input type="checkbox" name="file_type" value="1"> Statistik
</form>

and i have two rows on my database table das_custermer_files.
row 1 = files
row 2 = statistic
how can i check one of them an put the value into my rows.
i have try with this code
if($_POST['file_type'] == 1){
            mysql_query("INSERT INTO das_custermer_files (url, das_file_categories_id, das_custermers_id, name)
                         VALUE('$fileurl', 1, $user_custermers_id, '$name')"
                    ) or die(mysql_error());
            }

            elseif($_POST['statistik_type'] == 1){
                mysql_query("INSERT INTO das_custermer_files (url, das_custermer_upload_id, das_custermers_id, name)
                         VALUE('$fileurl', 1, $user_custermers_id, '$name')"
                    ) or die(mysql_error());
            }
            else{
                echo "no choices";
            }

But if i only check one of them it stil put value 1 in both of my rows.
Hope people understand. If not. ask

i have done it.
the finel code:
html
<form action="" method="post" enctype="multipart/form-data">
    <input type="radio" name="file_type" value="1"> Filer

    <input type="radio" name="file_type" value="2"> Statistik
</form>

PHP
$field = false;

            switch($_POST['file_type'])
            {
                case 1:
                    $field = 'das_file_categories_id';
                break;
                case 2:
                    $field = 'das_custermer_upload_id';
                break;
                default:
                $field = false;
            }
            if($field)
            {
               mysql_query("INSERT INTO das_custermer_files (url, $field, das_custermers_id, name)
                         VALUE('$fileurl', 1, $user_custermers_id, '$name')"
                    ) or die(mysql_error());
            }

A: My approach would be like this:
I would use radio buttons instead, to ensure a type is selected.
Form Bits:
    <input type="radio" name="file_type" value="0" checked="checked"> None

    <input type="radio" name="file_type" value="1"> Filer

    <input type="radio" name="file_type" value="2"> Statistik

PHP Bits:
$field = false;

 // set the field name based on the file type selected in the form
switch($_POST['file_type'])
{
    case 1:
        $field = '`das_file_categories_id`';
    break;
    case 2:
        $field = '`das_custermer_upload_id`';
    break;
    default:
    $field = false;
}

// if a field has been set ( i.e file_type != 0 ) then build and run the query
if($field)
{

    $query  =   "INSERT INTO `das_custermer_files` (`url`, " . $field . ", `das_custermers_id`, `name`) ";
    $query .=   "VALUES ('" . $fileurl . "', 1, " . $user_custermers_id . ", '" . $name . "')";
    mysql_query($query);
    echo "Inserting to db: " . $query;
} else {
    echo "No field set: ";
    print_r($_POST);
}

Things worth noting

*

*You're using mysql_query which is outdated, see here: http://php.net/manual/en/function.mysql-query.php

*Even though you are using $fileurl, $user_custermers_id,$name i cannot see these being set, so i am assuming they are set somewhere higher in the file

A: your check_box names should be different. yours the same.
<input type="checkbox" name="file_type" value="1"> Filer

<input type="checkbox" name="file_type" value="1"> Statistik

A: Html code :
<form action="test.php" method = 'post'>
<input type="checkbox" name="file_type[]" value="1"> Filer

<input type="checkbox" name="file_type[]" value="2"> Statistik
<input type="submit" value="submit" />

checkbox will contain its value in array $_POST['file_type']
and you may inter its value to db as follows :-
if(isset($_POST['file_type'])){
 foreach($_POST['file_type'] as $keys)
   {
     mysql_query("INSERT INTO das_custermer_files (url, das_file_categories_id,     das_custermers_id, name)
                 VALUE('$fileurl', $keys, $user_custermers_id, '$name')"
            ) or die(mysql_error());
    }
 }
    else if(isset($_POST['statistik_type'])){
        mysql_query("INSERT INTO das_custermer_files (url, das_custermer_upload_id, das_custermers_id, name)
                 VALUE('$fileurl', 1, $user_custermers_id, '$name')"
            ) or die(mysql_error());
    }
    else{
        echo "no choices";
    }

this maybe your requirement...

A: Try this .Should work.
 if(isset($_POST['file_type'])){
        mysql_query("INSERT INTO das_custermer_files (url, das_file_categories_id, das_custermers_id, name)
                     VALUE('$fileurl', 1, $user_custermers_id, '$name')"
                ) or die(mysql_error());
        }

        else if(isset($_POST['statistik_type'])){
            mysql_query("INSERT INTO das_custermer_files (url, das_custermer_upload_id, das_custermers_id, name)
                     VALUE('$fileurl', 1, $user_custermers_id, '$name')"
                ) or die(mysql_error());
        }
        else{
            echo "no choices";
        }

A: You approach is totally wrong. You should follow this structure
<form action="test.php" method = 'post'>
    <input type="checkbox" name="file_type" value="1"> Filer

    <input type="checkbox" name="file_type" value="2"> Statistik
    <input type="submit" value="submit" />
</form>

Now with php
$query  =   '';
if($_POST['file_type'] == 1){
    $query  =   "INSERT INTO das_custermer_files
                (url, das_file_categories_id, das_custermers_id, name)
                VALUE
                ('$fileurl', 1, $user_custermers_id, '$name')";
}else if($_POST['file_type'] == 2){
    $query  =   "INSERT INTO das_custermer_files
                (url, das_custermer_upload_id, das_custermers_id, name)
                VALUE
                ('$fileurl', 1, $user_custermers_id, '$name')";
}

mysqli_query($query);

A: You probably forgot to <form action = "..." method = "POST"> </form>.
First step, you should do the test:
print_r($_POST);

What you get by this test?
If the first step is correct (not empty array), we can finish:
if (isset($_POST['file_type'])) {
   ...
};

// OR use alternative
if ($_POST['file_type'] == 1) {
   ...
};

A: Clicking on a checkbox doesen't change the value attribute but adds "checked" in the dome like this:
<input type="checkbox" name="file_type" value="1" checked> Filer

So the submitted value of the checked box will stay forever at "1"
EDIT
When you replace the values with strings you can check against it in php.
HTML
<form action="" method="post" enctype="multipart/form-data">
<input type="checkbox" name="file_type" value="Filer"> Filer

<input type="checkbox" name="file_type" value="Statistik"> Statistik
</form>

PHP
if($_POST['file_type'] == "Filer"){
            mysql_query("INSERT INTO das_custermer_files (url, das_file_categories_id, das_custermers_id, name)
                         VALUE('$fileurl', 1, $user_custermers_id, '$name')"
                    ) or die(mysql_error());
            }

            elseif($_POST['file_type'] == "Statistik"){
                mysql_query("INSERT INTO das_custermer_files (url, das_custermer_upload_id, das_custermers_id, name)
                         VALUE('$fileurl', 1, $user_custermers_id, '$name')"
                    ) or die(mysql_error());
            }
            else{
                echo "no choices";
            }


Q: File upload validation - to unlink from tmp or not Just a quick question on best practice.
If my website visitors are uploading files that fail file validation (too large, wrong filetype etc.) is it safer/ more efficient to programatically delete the file from the servers tmp directory? Or do I just let the purge cycle performed by the server take care of it?
Many thanks
Phill

A: From the manual:

The file will be deleted from the temporary directory at the end of the request if it has not been moved away or renamed.

So, you could omit it, however:

Whatever the logic, you should either delete the file from the temporary directory or move it elsewhere.

... it's always nice to be explicit in your script. In short: you don't have to, but I would.


Q: Scrapping memory issue (Out Of Memory) Good day,
I have cameras that are saving videos by clips on a cloud service, with a limit on N clips. In order to save more clips, I made a scrapping script that gets all my video links from the website where I can preview them. (to be executed on page load with a JS extension)
Note that these are M3U8 files.
Here is my script:
var cameraScrapper = {
    playerReady: false,
    videos: {},

    cameraCurrent: 0,
    cameras: [
        'cid1', // #1
        'cid2', // #3
        'cid3', // #2
    ],

    gui: function()  {
        return {
            calendarPreviousMonth: document.getElementById( 'event_calendar_section' ).getElementsByClassName( 'navigation' )[0].getElementsByClassName( 'prev' )[0],
            calendarNextMonth: document.getElementById( 'event_calendar_section' ).getElementsByClassName( 'navigation' )[0].getElementsByClassName( 'next' )[0],
            calendarSelectedDate: document.getElementById( 'event_selected_date' ),
            calendarMonthDays: document.getElementById( 'event_calendar_section' ).getElementsByClassName( 'month' )[0].children,
            cameras: document.getElementById( 'camera_list_dropdown' ).children,
            dayClips: document.getElementById( 'event_clips_wrap' ).children,
            noRecords: document.getElementsByClassName( 'no_recording' )[0]
        };
    },

    init: function() {
        document.getElementById( 'hls_player' ).addEventListener( 'canplay', function() { this.playerReady = true; }.bind( this ) );

        for( let i = 0; i < this.cameras.length; i++ ) {
            if( window.location.href.includes( '=' + this.cameras[i] + '&' ) ) {
                this.cameraCurrent = i;
                break;
            }
        }

        while( !this.gui().calendarPreviousMonth.children[0].classList.contains( 'disabled' ) ) {
            this.gui().calendarPreviousMonth.click();
        }

        this.scrap();
    },

    getVideo: function( pCamera, pTimeStamp ) {
        let performance = window.performance || window.mozPerformance || window.msPerformance || window.webkitPerformance || {};
        let requests = ( performance.getEntries() || {} );

        for( let i = 0; i < requests.length; i++ ) {
            if( requests[i].name.includes( '.ts?' ) ) {
                if( this.videos[encodeURIComponent( requests[i].name )] === undefined ) {
                    this.videos[encodeURIComponent( requests[i].name )] = { 'camera': pCamera, 'timestamp': this.formatDate( pTimeStamp ) };
                }
            }
        }

        if( Object.entries( this.videos ).length > 25 ) {
            this.save();

            this.videos = {};
            performance.clearMarks();
            performance.clearMeasures()
            performance.clearResourceTimings();
        }
    },

    formatDate( pTimestamp ) {
        let date = pTimestamp.split( ' ' )[0];
        let time = pTimestamp.split( ' ' )[1];

        let month = {
            JAN: '01',
            FEB: '02',
            MAR: '03',
            APR: '04',
            MAY: '05',
            JUN: '06',
            JUL: '07',
            AUG: '08',
            SEP: '09',
            OCT: '10',
            NOV: '11',
            DEC: '12'
        }

        return date.split( '.' )[2] + '-' + month[date.split( '.' )[1]] + '-' + date.split( '.' )[0] + ' ' + time;
    },

    sleep: function( pMs ) {
        return new Promise( resolve => setTimeout( resolve, pMs ) );
    },

    scrap: async function() {
        let scrapDays = true;

        while( scrapDays ) {
            for( let i = 0; i < this.gui().calendarMonthDays.length; i++ ) {
                if( !this.gui().calendarMonthDays[i].classList.contains( 'is-disabled' ) && !this.gui().calendarMonthDays[i].classList.contains( 'is-expired' ) && !this.gui().calendarMonthDays[i].classList.contains( 'is-future' ) ) {
                    // console.log( 'day ' + this.gui().calendarMonthDays[i].innerText );

                    this.gui().calendarMonthDays[i].click();

                    let clipsLoaded = false;

                    if( this.gui().noRecords !== undefined ) {
                        clipsLoaded = !this.gui().noRecords.classList.contains( 'displayOff' )
                    }

                    while( !clipsLoaded && ( this.gui().dayClips.length == 0 ) ) {
                        await this.sleep( 99 );

                        if( this.gui().noRecords !== undefined ) {
                            clipsLoaded = !this.gui().noRecords.classList.contains( 'displayOff' )
                        }
                    }

                    // console.log( 'clips ' + this.gui().dayClips.length );

                    for( let j = 0; j < this.gui().dayClips.length; j++ ) {
                        this.playerReady = false;
                        this.gui().dayClips[j].children[0].click();

                        while( !this.playerReady ) {
                            await this.sleep( 99 );
                        }

                        this.getVideo( ( '' + this.cameraCurrent ), this.gui().calendarSelectedDate.innerText + ' ' + this.gui().dayClips[j].children[0].children[1].children[1].innerText );
                    }
                }
            }

            if( !this.gui().calendarNextMonth.children[0].classList.contains( 'disabled' ) ) {
                this.gui().calendarNextMonth.click();
            } else {
                scrapDays = false;
            }
        }

        this.save();

        this.sleep( 4999 );

        let cameraNext = this.cameraCurrent + 1;
        if( this.cameras.length >= cameraNext ) {
            cameraNext = 0;
        }

        window.location.href = 'https://cloudcamerasservice.com/camera?no=' + this.cameras[cameraNext] + '&model=CAM';
    },

    save() {
        let xhr = new XMLHttpRequest();
        xhr.open( 'POST', 'http://localhost/videomonitoring/stack.php', true );
        xhr.setRequestHeader( 'Content-type', 'application/x-www-form-urlencoded' );

        xhr.onload = ( e ) => { /* console.log( 'saved' ); */ };
        xhr.onerror = ( e ) => {};
        xhr.send( 'stack=' + encodeURIComponent( JSON.stringify( this.videos ) ) );
    }
};

setTimeout( function() { cameraScrapper.init() }.bind( this ), 4999 );

stack.php will handle file download from provided list, my script is mainly about getting the video links and date of recording.
But when launching my script, my browser run out of memory after 75-100 clips saved. Can you help me with this?
Not sure if it's comming from my script, indeed, I have the feeling this is due to preloading many videos on the same page.


Q: Scrollbar in textarea Css is like:
::-webkit-scrollbar,::-moz-scrollbar {
    -webkit-appearance: none;
    width: 6px;    /* for vertical scrollbars */
    height: 8px;    /* for horizontal scrollbars */
}
::-webkit-scrollbar-track,::-moz-scrollbar-track {
    background: rgba(0, 0, 0, 0.1);
    border-radius:4px;
}
::-webkit-scrollbar-thumb,::-moz-scrollbar-thumb {
    background: rgba(0, 0, 0, 0.5);
    border-radius:4px;
}

but it works only in chrome ..in other browser it display default scrollbar and second doubt is it start appears in ipad after I scrolldown..how to display vertical scroll if it has max text on hover of the textarea?
jsfiddle

A: You can use mouseout and mouseover events to hide or show the scroll bar using css.

A: For a cross browser solution you should use javascript/jquery. There are many successful scrollbar plugins that you can use


Q: Button isn't displayed in RelativeLayout below GridView I have the next problem: when a gridview content doesn't fit into device display and scrolling begins then a button below the gridview is not shown.
Here is my code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingLeft="16dp"
 android:paddingRight="16dp">

  <GridView
    android:id="@+id/generated_number_gridview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:columnWidth="90sp"
    android:horizontalSpacing="10sp"
    android:stretchMode="columnWidth"
    android:verticalSpacing="10sp" />

  <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/generated_number_gridview"
    android:layout_centerHorizontal="true"
    android:onClick="proceed"
    android:text="@string/proceed"
    android:textSize="25sp" />
</RelativeLayout>

Would be very thankful for your help !

A: Remove this line from Button Layout properties.
        android:layout_below="@id/generated_number_gridview"

This means that It should be below the GridView. And your GridView size is not fixed. Since the renderer shows the GridView with multiple elements it fills the screen and your Button goes below that. That's why it's not visible.
I hope this is the UI that you are looking for.
 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp">

    <GridView
        android:id="@+id/generated_number_gridview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:columnWidth="90sp"
        android:horizontalSpacing="10sp"
        android:stretchMode="columnWidth"
        android:verticalSpacing="10sp"
        android:layout_above="@+id/proceedButton"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:id="@+id/proceedButton"
        android:onClick="proceed"
        android:text="proceed"
        android:textSize="25sp" />
</RelativeLayout>

Hope it helps.

A: Try this.
Just replace this with your XML code.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp">

    <GridView
        android:id="@+id/generated_number_gridview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btnProceed"
        android:layout_centerHorizontal="true"
        android:columnWidth="90sp"
        android:horizontalSpacing="10sp"
        android:stretchMode="columnWidth"
        android:verticalSpacing="10sp" />

    <Button
        android:id="@+id/btnProceed"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:onClick="proceed"
        android:text="Proceed"
        android:textSize="25sp" />
</RelativeLayout>

Here is the Screen shot.

A: You can use this layout..
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:paddingLeft="16dp"
     android:paddingRight="16dp">

  <GridView
        android:id="@+id/generated_number_gridview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        **android:layout_above="@+id/btn_proceed"**
        android:layout_centerHorizontal="true"
        android:columnWidth="90sp"
        **android:horizontalSpacing="10dp**"
        android:stretchMode="columnWidth"
        **android:verticalSpacing="10dp"** />

 <Button
        android:id="@+id/btn_proceed"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:onClick="proceed"
        android:text="@string/proceed"
        android:textSize="25sp" />
    </RelativeLayout>


Q: How to ignore code when data does not contain necessary values? I'm very new to R and here as well and need some help fixing my code because sometimes my data gets weird
So I have data similar to this
Random  Price
11.23   0.68
66.77   0.51
68  0.46
78  0.51
88  0.32
89  0.51
90  0.27
91  0.65

This is my code so far:
newdata <- data[ which(data$Random>=30
& data$Random < 50), ]
Pvalue<- lapply(1:length(dat), function(i){
if(length(dat[[i]][[4]])>1){
t.test(newdata$Price,dat[[i]][[4]])$p.value
}else 'not enough observation'
})

My code basically does a t.test between the data from 'newdata' and another set of data called 'dat'
But there are times when I don't have data from 30 to 50 similar to my example data above.
So instead of my code returning an error, how could I change it so that it just returns NA .

A: You already know how to use the if/else construct. All you have to do is add one testing nrow(newdata), or maybe combine both as follows:
newdata <- subset(data, Random >= 30 &
                        Random < 50)
Pvalue <- lapply(dat, function(x){
  if (length(x[[4]]) > 1 & nrow(newdata) > 1) {
    t.test(newdata$Price, x[[4]])$p.value
  } else NA
})

You could also replace lapply(...) with sapply(...) or vapply(..., numeric(1)) to get a numeric vector instead of a list. For that, it is recommended to replace 'not enough observation' with NA like I did, or you could end up with a character vector.


Q: SQLITE: SELECT between timestamps doesnt work my goal is it to search between two time stamps of a certain time span  all of this is stored in an array of an dynamic amount of time stamps depending on how much days i want to search in the past. Originally they looked like that 2020-07-30T08:41:22.164Z but i removed the unimportant parts of it and now it looks like that 07-30. So i just filtered the time stamp to its month and day. Now to my problem: I am trying to bring that command to work: "SELECT status FROM database WHERE timeStamp BETWEEN '%datesStored[datesStored.length -1]%' AND '%datesStored[0]%'".
Ignore the fact that i used JS where the time stamps should be. The whole SQLite statement is in fact a String I've built that i am trying to send to SQLite node in nore-red. But that is not important. They only thing i need is the certain command that would work.
Thank you for any responses.

var datesSaved = msg.payload;
var daysBack = global.get("maxDaysBack");
var min = datesSaved[0];
var max = datesSaved[datesSaved.length-1];

msg.topic = "SELECT status, dateTime FROM database WHERE dateTime BETWEEN '%07-28%' AND '%07-29%';";

msg.labels = msg.payload;
msg.payload = [];
return msg;

A: I don't know exactly what your search strategy is here, but if you want to see all records going back 7 days to the past, you may use:
SELECT status, dateTime
FROM database
WHERE dateTime >= date('now', '-7 day');


Q: How do I safely lock an ASP.NET MVC3 Session? I want to modify the Session variable in an ASP.NET MVC3 Controller (that has SessionState required) in a thread-safe manner. What object should I lock on?


Q: Where do I start with developing a Silverlight app using Windows Workflow Foundation? We are starting out with the development of a Silverlight app that will make use of Windows Workflow Foundation (WF4). Our workflows are long-running. We plan to use the tracking and persistence functionality of WF. We will probably need to also store data related to each workflow instance in another DB (I suspect running reporting against the workflow persistence store would be tricky). Our workflows may change with time so we would probably also need some strategy to implement versioning on them.
So specifically, are there any resources you can point me to or direction you can give me on where to start, taking into account that we need to implement tracking, persistence and versioning of workflows?

A: Based on your question, I'm assuming that you already have experience with WWF and are really just asking about how it interacts with Silverlight.  The short answer is that it would not be noticeably different from how you would implement a WWF-enabled application in traditional ASP.NET.  Remember that Silverlight is only a UI client that usually lives on top of a traditional ASP.NET web application.  Your WWF-related logic and code would live in the ASP.NET layer -- not in Silverlight at all.
So if you already know how to make a WWF-enabled application in ASP.NET, all you really need to learn is how to wire up a shiny Silverlight interface to an ASP.NET web app.  For that, you of course only need to hit up http://silverlight.net/, which you're probably already doing.
Good luck!


Q: Why is Serilog(.Extras.)Web's ApplicationLifecycleModule.Init() called twice? I'm hosting a Web API in IIS (7.5) as an Application under "Default Web Site", and am using several of the Enrichers from Serilog.Extras.Web (I'll be upgrading soon to the SerilogWeb.Classic package). I noticed in my logs that ApplicationLifecycleModule.LogRequest() was being called twice for each request, and I'm trying to understand why.
What I noticed is that ApplicationLifecycleModule.Init() is being called twice, thus registering two event handlers.
The first callstack:
Serilog.Extras.Web.dll!Serilog.Extras.Web.ApplicationLifecycleModule.Init(System.Web.HttpApplication context)
System.Web.dll!System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(System.IntPtr appContext, System.Web.HttpContext context, System.Reflection.MethodInfo[] handlers)
System.Web.dll!System.Web.HttpApplication.InitSpecial(System.Web.HttpApplicationState state, System.Reflection.MethodInfo[] handlers, System.IntPtr appContext, System.Web.HttpContext context)
System.Web.dll!System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(System.IntPtr appContext, System.Web.HttpContext context)
System.Web.dll!System.Web.Hosting.PipelineRuntime.InitializeApplication(System.IntPtr appContext)
[AppDomain Transition]

And the second:
Serilog.Extras.Web.dll!Serilog.Extras.Web.ApplicationLifecycleModule.Init(System.Web.HttpApplication context)
System.Web.dll!System.Web.HttpApplication.InitModulesCommon()
System.Web.dll!System.Web.HttpApplication.InitInternal(System.Web.HttpContext context, System.Web.HttpApplicationState state, System.Reflection.MethodInfo[] handlers)
System.Web.dll!System.Web.HttpApplicationFactory.GetNormalApplicationInstance(System.Web.HttpContext context)
System.Web.dll!System.Web.HttpApplicationFactory.GetApplicationInstance(System.Web.HttpContext context)
System.Web.dll!System.Web.HttpRuntime.ProcessRequestNotificationPrivate(System.Web.Hosting.IIS7WorkerRequest wr, System.Web.HttpContext context)
System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags)
System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags)

Am I doing something wrong? Or is this a bug in the ApplicationLifecycleModule?