text:
Q: Youtube-dl error Tried using youtube-dl with many different types of youtube videos and I keep getting an "unable to download video info webpage: HTTP Error 500: Internal Server Error" message:
>youtube-dl 'http://www.youtube.com/watch?v=t-eWAc1Knlw' -v

 [debug] youtube-dl version 2013.02.02
 [debug] Python version 2.7.3
 [debug] Proxy map: {}
 [youtube] Setting language
 [youtube] t-eWAc1Knlw: Downloading video webpage
 [youtube] t-eWAc1Knlw: Downloading video info webpage

ERROR: unable to download video info webpage: HTTP Error 500: Internal Server Error

File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "/usr/bin/youtube-dl/__main__.py", line 17, in <module>
youtube_dl.main()
File "/usr/bin/youtube-dl/youtube_dl/__init__.py", line 512, in main
_real_main()
File "/usr/bin/youtube-dl/youtube_dl/__init__.py", line 496, in _real_main
retcode = fd.download(all_urls)
File "/usr/bin/youtube-dl/youtube_dl/FileDownloader.py", line 505, in download
videos = ie.extract(url)
File "/usr/bin/youtube-dl/youtube_dl/InfoExtractors.py", line 93, in extract
return self._real_extract(url)
File "/usr/bin/youtube-dl/youtube_dl/InfoExtractors.py", line 397, in _real_extract
self._downloader.trouble(u'ERROR: unable to download video info webpage: %s' % compat_str(err))
File "/usr/bin/youtube-dl/youtube_dl/FileDownloader.py", line 230, in trouble
tb_data = traceback.format_list(traceback.extract_stack())

I've updated youtube-dl to version 2013.02.02 (latest one), by running it with the --update option, but it still produces the same error.

A: Please reinstall youtube-dl
sudo curl https://yt-dl.org/downloads/2014.03.03/youtube-dl -o /usr/local/bin/youtube-dl

sudo chmod a+x /usr/local/bin/youtube-dl

More info: http://rg3.github.io/youtube-dl/download.html

A: try to reinstall your youtube-dl
1.update first
sudo apt-get update

2.then remove existing youtube-dl
sudo apt-get remove youtube-dl

3.then re-install it
sudo apt-get install youtube-dl

you should now able to download youtube video via youtube-dl again

A: I tried your answer
sudo curl https://yt-dl.org/downloads/2014.03.03/youtube-dl -o /usr/local/bin/youtube-dl

sudo chmod a+x /usr/local/bin/youtube-dl

and it when I try to download a video stop here and just sits
[youtube] B07iK9uh9qY: Downloading js player vfl4_saJa
I have tried a couple of different videos
UPDATE:
I ran
/usr/local/bin/youtube-dl -U

now it downloads the video again. Thanks for your help :)


text:
Q: Python 3.x: My function returns 'TypeError: object of type 'function' has no len()' I have a function all_word_pairs (which gets all words from all .txt files from the same directory and creates a list of lists containing two elements: the word itself and the file from which it originates) and it's defined like this:
def all_word_pairs():
"""Return list of word + filename tuples from .txt files in current directory"""
# collect .txt filenames
filenames = []
# scan all files in current directory
for f in os.listdir("."):
    # test if f ends with .txt
    if f.endswith(".txt"):
        # yes it does, so add it to filenames
        filenames.append(f)
# collect word pairs from all filenames
return word_pairs(filenames)

This is what print(all_word_pairs()) will return.
Now I build a function to sort the lists (within the list given by the all_word_pairs function) by their first element (the retrieved word):
def merge_pairs(data):
if len(data) <= 1:
    res = data
    return res

else:
    res = []
    fi = 0
    si = 0
    imid = len(data) // 2
    fst = merge_pairs(data[:imid])
    snd = merge_pairs(data[imid:])
    while fi <= len(fst)-1 and si <= len(snd) - 1:
        if fst[fi][0] < snd[si][0]:
            res.append(fst[fi])
            fi = fi + 1
        else:
            res.append(snd[si])
            si = si + 1
    if fi <= len(fst) - 1:
            res.extend(fst[fi:])
    elif si <= len(snd) - 1:
        res.extend(snd[si:])

i = 0
while i < len(res) - 1:
    while res[i][1] == res[i + 1][1]:
        res[i], res[i + 1] = res[i + 1], res[i]
    i = i + 1
return res

When I call the function merge_pairs it gives me a TypeError: objectof the type 'function' has no len(). This is what it looks like.
Does anyone know what goes wrong? I'd greatly appreciate your help!

A: You're doing:
print(merge_pairs(all_merge_pairs))

This passes in the function all_merge_pairs as data, not its result.
You need to do:
print(merge_pairs(all_merge_pairs()))

redpajama_set_name: RedPajamaStackExchange


text:
Q: FLANN hiearchical kmeans How to determine which vector is assigned to which cluster? Hi everyone i am new to FLANN,
I would like to perform a hiearchical kmeans clustering using FLANN,
how can i determine which vector belongs to which cluster?
Thanks in advance


text:
Q: How can I multiply a linear transformation by a antilinear transformation Well, I have the following inquiry: I have an element $g \in \mathrm{O}(V)$. I know that such element can be decomposed as the sum of two operators: $$g=p_g+q_g,$$ where $p_g$ is linear and $q_g$ is antilinear.
I'm are working over (finite) vector spaces over $\mathbb{C}$.
I'm trying to calculate $$T:=q_gp_g^{-1},$$ (assuming that $p_g$ is invertible) for a specific $g$. I already expressed $p_g$ in matrix form and calculated it's inverse. However, since $q_g$ is not linear, it doesn't hace a matrix representation. ¿How can I calculate $q_gp_g^{-1}$? Specifically, $$p\sim \begin{bmatrix} \alpha & -\overline\beta\\ \beta & \overline\alpha \end{bmatrix}$$ and $q=-\beta \overline{\beta}v+\overline\alpha \beta u$, where $\{ v,u\}$ is a basis of $V$ and $\alpha, \beta \in \mathbb{C}$. If $q$ were a linear transformation, I could put it in matrix form…
What's the matrix form of an antilinear transformation?
Thanks in advance!


text:
Q: sources for all infinite series? I'm looking for a source for all of the known infinite series, if such a source exists.
The following site is the best source that I have found so far, but I do not know if it is complete and it does not seem to have a way to contact in order to add additional series.  I am hoping that there is a better source--something like the OEIS provides for sequences.  Any suggestions?  Thanks.
http://pi.physik.uni-bonn.de/~dieckman/InfProd/InfProd.html
For instance, how does one know if an infinite series is new or already exists?

A: I'd doubt you'd find all known infinite series in any text, but a very famous and comprehensive treatise is the one by Gradshteyn and Ryzhik.

A: L. B. W. Jolley, Summation of Series, is a very useful compendium.


text:
Q: How to manage files in ipod with kubuntu I'm trying KDE plasma.
I've found I can't manage files (not just music and photos) in my ipod like a U-disk with Kubuntu 14.04.
But when I use Ubuntu and Nautilus, my ipod performs like a simple U-disk.
which lib should I install to manage my files in ipod?

A: maybe ifuse+kio_afc is the solution.
sudo apt-get install ifuse

and then, download and compile kio_afc
However, aio_afc's last update was in 2010...

A: There is a application named as gtkpod, install it with
sudo apt-get install gtkpod

and open it.
Source: ubuntu-apps


text:
Q: How to add custom wizards in typo3 7 TCA? When I try to add the wizard named wizard_geo_selector in TCA ,there arised an error "module not registered".Please tell me how to register the wizard properly in the TCA.?

A: In TYPO3 Version 7.6 new wizards are added like this:

*

*Inside your extension create the directory Configuration/Backend/

*In the new directory create a file Routes.php, it will be found automatically, no mentioning in ext_localconf.php or ext_tables.php is required. If you still need Ajax you can add the file AjaxRoutes.php in the same folder.

*Content for Routes.php:
return array(
    'my_wizard_element' => array(
        'path' => '/wizard/tx_geoselecotor/geo_selector_wizard',
        'target' => \Path\To\your\class\WizardGeoSelector::class . '::WizardAction'
    ),
);

Content for AjaxRoutes.php
<?php

 /**
  * Definitions for routes provided by EXT:backend
  * Contains all AJAX-based routes for entry points
  *
  * Currently the "access" property is only used so no token creation + validation is made
  * but will be extended further.
  */
 return array('my_ajax_element' => array(
         'path' => 'tx_geoselecotor/my_ajax_route',
         'target' => \Path\To\your\class\MyAjaxController::class .'::myAjaxFunction'
 ));

If you're unsure about the notation you can compare with existing entries in the Global Variables in the Backend:

Navigate to System -> Configuration -> Backend Routes

The route of the paths is handled different, for Ajax it's always "ajax" prepended, so you've never to add it to the path, else it's twice in the route. For the common route there is no change concerning the defined string.

*Now the wizard can be used and even it never has to be defined in ext_tables.php it has to be mentioned there from any table-field in the configuration-area (module[name]):
'table_field_for_wizard' => array(
    'label' => 'LLL:EXT:my_extension/Resources/Private/Language/locallang.xml:table_name.tx_myextension_wizard',
    'config' => array (
        'type' => 'user',
        'userFunc' => 'Path/to/class/without/wizard->renderForm',
        'wizards' => array(
          'my_wizard' => array(
            'type' => 'popup',
            'title' => 'MyTitle',
            'JSopenParams' => 'height=700,width=780,status=0,menubar=0,scrollbars=1',
            'icon' => 'EXT:' . $_EXTKEY . '/Resources/Public/img/link_popup.gif',
            'module' => array(
              'name' => 'my_wizard_element',
              'urlParameters' => array(
                'mode' => 'wizard',
                'ajax' => '0',
                'any' => '... parameters you need'
              ),
            ),
          ),
          '_VALIGN' => 'middle',
          '_PADDING' => '4',
        ),
        # Optional
        #'softref'=>'something',
    ),
),

In the userFunc Path/to/class/without/wizard->renderForm you've to create a button which is linking to the wizard and onClick the wizard will open with the route you defined in Routes.php and the optional urlParameters.
Currently I never found this whole item explained in the core-documentation.
Edit:
Details about routing can be found here: Routing
The rendering process can be found here: Rendering / NodeFactory
You should probably read also the outer context of the linked paragraph.
Edit 2:
An example extension can be found here, some things never work 100% but the wizard is working. The extension is for TYPO3 Version 7:
https://github.com/DavidBruchmann/imagemap_wizard

A: IN TCA add the wizard like follows:
'module' => array(
'name' => 'wizard_geo_selector',
),

In ext_tables.php register the wizard.
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addModulePath(
        'wizard_geo_selector',
        \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath($_EXTKEY) . 'Modules/Wizards/Yourwizardname/'
 );

Keep in mind this is deprecated since Typo3 7 and removed in Typo3 8.So you can use this method upto Typo3 7.For Typo3 8 do use the method specified by David below.

A: Ricky's answer doesn't really work anymore, since addModulePath ist deprecated since version 7.
Also, just registering the module like this still give's you said error.
The only thing that keeps the wizard going again is this:
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addModule('wizard','pbsurvey_answers',"",\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath($_EXTKEY).'wizard/');

But when you add this, the module appears as a new point in your TYPO3 backend.


text:
Q: Как вывести ФИО сотрудников вместо чисел столбца Kod_sotr
Я сделал программу, которая отображает данные о хранилище фруктов в Grid, я хочу, чтобы вместо чисел в столбце Kod_sotr отображался ФИО, а также удалить последние два столбца?
Класс который Выводиться
 class FruitStorage
    {
        [Key]
        public int FruitStorageKod { get; set; }
        public int Kod_sotr {get;set;}
        public int Kod_cell { get; set; }
       public int Kod_chamber { get; set; }
       public  DateTime Date_fill { get; set; }
        public virtual Sotr Sotr { get; set; }
        public virtual Сhamber Chamber { get; set; }

    }

Присвоение форме
  List<FruitStorage> Interface1.fruitOut
     {
            set => dataGridView.DataSource = value;
        }

public FruitSoragePresenter()
        {
            var fruit = new FruitS<FruitStorage>();

            fruit.Show();

        }

 public FruitSoragePresenter(Interface1 view)
        {

            sotrView.fruitOut = db.FuitStorages.ToList();
}


text:
Q: TargetSdkVersion 26 i got a main please clarify Recently i got a mail from google to change the targetsdkversion to 26 or above
but i have a question regarding this :
In my console i have around 50 android applications of which there are only 8 apps which are under production(in Live) and the rest apps i have already unpublished it and i will not use it any more (means  i will not publish those apps again) so my point is should i need to update the unpublished app to change the targetsdkversion to 26 or above as in mail i got if account has more than 20 apps which are not targetsdkverion 26 it may affect account
please help me what to do

A: If you will not publish those apps again then don't worry for account. Just update apps those are under production

A: From android docs:

Google Play will require that new apps target at least Android 8.0
  (API level 26) from August 1, 2018, and that app updates target
  Android 8.0 from November 1, 2018

You don't need to update your production apps until you actually wanted to release new update.
One more important fact:

Configuring your app to target a recent API level ensures that users
  can benefit from these improvements, while still allowing it to run on
  older Android versions.


text:
Q: ASP.NET Core - Hash character (#) sent in a Facebook signon redirection is causing problems I want to sign users on to Facebook from a new ASP.NET Core app.  I am not using an SDK for a number of reasons. Everything's going fine.  I redirect the user to the Facebook sign on page.  The user signs in. Facebook redirects to the following Uri string, which I copied from the browser after the redirection:
http://localhost:5000/signonok?#state=testsession&access_token=bbbbtokeneeee&expires_in=510000

The signonokController activates but the query collection is empty and the QueryString is "?".  It would appear that the hash character(#) in the string is causing ASP.NET to stop further parsing.  I rummaged around the HttpContext for a few hours and cannot find the state, access_token or expires_in key value pairs.
No errors are being thrown, or issues logged to the logger.
I thought that perhaps I could get to the information, or reformat the Uri, by inserting my own Middleware function into the pipeline.  As suspected I got the same result.
My guess is that it will be easier to work around this issue on my side than it would be to get Facebook to change their response.
Java script is something I would rather avoid in this case, again for a number of reasons not relevant here.
Any thoughts on how to deal with this # character?  I either did something wrong that caused it to be emitted or I have to figure out how to consume the Uri in the pipeline.
Cheers...

A:
It would appear that the hash character(#) in the string is causing ASP.NET to stop further parsing.

The hash part of the URL is not even send to the server; there is nothing for your code to parse here.

My guess is that it will be easier to work around this issue on my side than it would be to get Facebook to change their response.

All you have to do is pass the right value for response_type in your login dialog call, see https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow#login:

response_type
  Determines whether the response data included when the redirect back to the app occurs is in URL parameters or fragments.

A: You can get the original, unparsed URL using the RawUrl property.  From there  you can:

*

*Remove the # symbol and parse the remaining arguments yourself with a bit of code, or

*Issue a self-redirect, passing the cleansed URL.  When your server receives the redirect you can then access the querystring parameters using the usual means.


text:
Q: Unable to automatically map azure storage share using terraform and Azure VM extensions on Windows VM Problem statement
I am trying to automatically map an Azure file share to Windows VMs using Azure VM extension. The VM extension installs successfully, the command runs but on logging into the VM I see that my drive is disconnected.
On trying to access it, I get an incorrect username or password error. However, running the PowerShell script on the machine correctly maps the network drive and I can access it.
Code
resource "azurerm_virtual_machine_extension" "test" {
  # Custom VM extension documentation https://learn.microsoft.com/en-us/azure/virtual-machines/extensions/custom-script-windows
  # additional documentation http://teknews.cloud/bootstrapping-azure-vms-with-terraform/, https://github.com/terraform-providers/terraform-provider-azurerm/issues/728
  name = "network_share"
  location = "${azurerm_resource_group.main.location}"
  resource_group_name = "${azurerm_resource_group.main.name}"
  #virtual_machine_name = "${azurerm_virtual_machine.vm.name}"
  virtual_machine_name = "${element(azurerm_virtual_machine.vm.*.name, count.index)}"
  publisher = "Microsoft.Compute"
  type = "CustomScriptExtension"
  type_handler_version = "1.9"
  count = "${var.vm_count}"

  settings = <<SETTINGS
  {
      "commandToExecute": "powershell -command \"[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('${base64encode(data.template_file.net_fileshare_script.rendered)}')) | Out-File -filepath net_fileshare_script.ps1\" && powershell -File net_fileshare_script.ps1"
  }
  SETTINGS

  depends_on = ["azurerm_virtual_machine.vm"]
}

data "template_file" "net_fileshare_script" {
  template = "${file("./scripts/net_fileshare_script.ps1")}"
}

A: I found out the script works as it is. The problem is that the credentials for the storage share aren't available to the remote user once logged in.
Once the remote user logs in, running this command
Invoke-Expression -Command "cmdkey /add:storageaccount.file.core.windows.net /user:AZURE\storageaccount /pass:storagekey"

makes the storage share accessible to the remote user account.
NB: Is it possible to make a credential available to multiple user accounts via a one time script?

A: I tried the solutions above, but without success.
1 - I did it another way, I kept the powershell that makes the connection in storage
2 - I created a powershell script to create a windows task scheduler pointing to item 1
3 - In Terraform I created a line to execute the taskScheduller created in item


text:
Q: AngularJS - input type="number" not clearable for non-number (NaN) Clear number input type does not work for 'e' number
When I clear the input field with input eee in number type, it does not get cleared. Any other input numbers get cleared. Check the JSFiddle. Any hints would be appreciated.
http://jsfiddle.net/2ankx9up/

    <input type="number" class="form-control" data-ng-model="searchAll">
    </input>
    X

var app = angular.module("app", []);
 app.controller("MainCtrl", function ($scope) {
    $scope.searchAll = "";
    $scope.clearSearch = function () {
       $scope.searchAll = "";
    };
});

A: The ng-model directive is unable to clear the content of an <input type="number"> element when that content parses to NaN (not a number). This can happen when a user pastes invalid content or simply types "eee".
One fix is to add a custom directive:
app.directive('clearNan', function() {
  return {
    require: 'ngModel',
    link: function(scope, elem, attrs, ngModel) {
      ngModel.$formatters.push(function(value) {
        if (!value) elem.val(null);
        return value;
      });
    }
  };
})

Usage:
<input type="number" clear-nan ng-model="x" />

The DEMO

angular.module('numfmt-error-module', [])
.directive('clearNan', function() {
  return {
    require: 'ngModel',
    link: function(scope, elem, attrs, ngModel) {
      ngModel.$formatters.push(function(value) {
        if (!value) elem.val(null);
        return value;
      });
    }
  };
})
.run(function($rootScope) {
  $rootScope.typeOf = function(value) {
    return typeof value;
  };
})

  <input clear-nan type="number" ng-model="x" />

  {{ x }} : {{ typeOf(x) }}

  <button ng-click="x=''">Clear input</button>


text:
Q: Extract all possible pairs within group in data.table Currently, I am struggling with a problem related to obtaining all possible  permutation within group using data.table.
To explain my problem, let me show you an example.
x <- c(1, 1, 1, 2, 2)
y <- c('red', 'blue', 'black', 'orange', 'red')
dt1 <- as.data.table(cbind(x,y))
dt1
   x      y
1: 1    red
2: 1   blue
3: 1  black
4: 2 orange
5: 2    red

Now I want to see every possible pair of color(y) within group(x). So my ideal result would be....
x   y1      y2
1   black   blue
1   black   red
1   blue    black
1   blue    red
1   red     black
1   red     blue
2   orange  red
2   red     orange

To find a solution for this, I did googling it and I found a function, permutation, which is what I am looking for but I find it hard to squeeze it into data.table framework.
y <- c('red', 'blue', 'black')
permutations(n=3, r=2, v=y, repeats.allowed=F)

     [,1]    [,2]
[1,] "black" "blue"
[2,] "black" "red"
[3,] "blue"  "black"
[4,] "blue"  "red"
[5,] "red"   "black"
[6,] "red"   "blue"

So I tried to do the following but obviously it has errors..
dt1[, .(j = lapply(.SD, permutations, n=.N, r=2, v=y, repeats.allowed=F)), by=x]

Any suggestion for this?
I will really appreciate it.

A: First off, don't use as.data.table(cbind(...)) to create the data table. You will get unexpected column classes due to cbind coercing to matrix.  Use
dt1 <- data.table(x, y)

That said, you can do
dt1[, {
        p <- gtools::permutations(.N, 2, y, repeats=FALSE)
        .(y1 = p[, 1], y2 = p[, 2])
    }, by = x]

which gives

   x     y1     y2
1: 1  black   blue
2: 1  black    red
3: 1   blue  black
4: 1   blue    red
5: 1    red  black
6: 1    red   blue
7: 2 orange    red
8: 2    red orange

There is no need to loop since we are operating on groups.  permutations creates a matrix, so we create our desired result columns from the resulting matrix columns of permutations.


text:
Q: SageMaker delete Models and Endpoint configurations with python API I've tried deleting/recreating endpoints with the same name, and wasted a lot of time before I realized that changes do not get applied unless you also delete the corresponding Model and Endpoint configuration so that new ones can be created with that name.
Is there a way with the sagemaker python api to delete all three instead of just the endpoint?

A: I believe you are looking for something like this? :
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html#SageMaker.Client.delete_endpoint_config
Examples:
import boto3

deployment_name = 'my_deployment_name'
client = boto3.client('sagemaker')
response = client.describe_endpoint_config(EndpointConfigName=deployment_name)
model_name = response['ProductionVariants'][0]['ModelName']
client.delete_model(ModelName=model_name)
client.delete_endpoint(EndpointName=deployment_name)
client.delete_endpoint_config(EndpointConfigName=deployment_name)

A: It looks like AWS is currently in the process of supporting model deletion via API with this pull request.
For the time being Amazon's only recommendation is to delete everything via the console.
If this is critical to your system you can probably manage everything via Cloud Formation and create/delete services containing your Sagemaker models and endpoints.


text:
Q: Not able to insert data into table using Nodejs exports.creategroup= function(callback,name,email,firstname)
 {
//  var connection=pool.getConnection();
var connection=connect();
console.log(email);
console.log(firstname);
var query="CREATE TABLE "+name+"(membername varchar(50) NOT NULL,email varchar(50) NOT NULL)";

  var query1="INSERT  INTO'"+name+"'(membername,email) VALUES('"+email+"','"+firstname+"')";
console.log(query);
connection.query(query,function(err,result){
    if(err)
        {
        console.log("ERROR:"+err.message);
        }
    else
        {
        if(result.length!==0)

        {
            console.log("DATA : "+JSON.stringify(result));
            callback(err, result);
        }
        else
        {
            callback("Invalid Username", result);
        }
        }
    //pool.returnConnection(connection);
     });

//The insert into query gives an error. I can't figure out what syntax error i have made. Could someone please help. The table is being created. The error I am facing in the insert is

ERROR:ER_PARSE_ERROR: You have an error in your SQL syntax; check the
  manual that corresponds to your MySQL server version for the right
  syntax to use near ''sad'(membername,email) VALUES('hunur','Sachin
  Mallikarjun')' at line 1

here sad was passed as the argument for table name

A: You've put the table Name in ' ticks, that's not valid. Below will work:
var query1="INSERT  INTO "+name+" (membername,email) VALUES('"+email+"','"+firstname+"')";

Please note that you absolutely shouldn't run a query like this as it is vulnerable to mysql injection. Use the escaped query node-mysql offers instead.
 var query = "INSERT INTO ?? (??,??) VALUES (?,?)";
 var values = [name,'membername','email',firstname,email];
 mysql.query(mysql.format(query, values), function(err,result,tableInfo){/*...*/})

Like this, node-mysql prepares the query for you. Every ?? represents a table or column name while every ? stands for a value to be inserted. You can verify this by
console.log(mysql.format(query,values));


text:
Q: Win32 Raw Ethernet Programming / NPCap I need a good Win32 VC++ API for Raw Ethernet Programming.
I have written an application in VC++ win32 to communicate to a microcontroller having Gigabit Ethernet. Both windows side and microcontroller side software is written by me. The application is a CNC controller, so I need a high-speed, low-latency communication interface at a distance of 10 metres with superior noise immunity capabilities, and Ethernet just fits. Just to be clear, there is no TCP/IP layer, and the communication works on raw Ethernet II frames for low latency constraints.
Currently, I am using NPCap, and everything works OK, but there are some problems. First to use it from windows, NPCap drivers need to be installed to make it work on every PC. Second, the NPCap API seems underpowered for my needs. I don't know if I am using it correctly or not, but the API itself does not respond to high-performance IO requests. after writing some benchmarking tests. In a transmit test, the NPCap API managed a modest 3.2 Mbps with a packet size of 76 bytes. The receive test was not so accurate but was in the ballpark of 56 kbps speed, which just seems so wrong. Having said that, the latency is very good. When I wrote such a receive and transmit test on the microcontroller side, it went to a whooping 700 Mbps range, and my Windows task manager just lit up like Christmas.
The WireShark application, which I think is built on NPCap, does not feel so slow and seems to be able to capture all frames no matter what speed one throws at it. I don't know if I'm doing something wrong with NPCap, but here is the code for reference:
#include <pcap.h>
#pragma comment (lib, "Packet.lib")
#pragma comment (lib, "wpcap.lib")

#include <tchar.h>

BOOL LoadNpcapDlls()
{
    _TCHAR npcap_dir[512];
    UINT len;
    len = GetSystemDirectory(npcap_dir, 480);
    if (!len) {
        fprintf(stderr, "Error in GetSystemDirectory: %x", GetLastError());
        return FALSE;
    }
    _tcscat_s(npcap_dir, 512, _T("\\Npcap"));
    if (SetDllDirectory(npcap_dir) == 0) {
        fprintf(stderr, "Error in SetDllDirectory: %x", GetLastError());
        return FALSE;
    }
    return TRUE;
}

struct Ethernet
{
    pcap_t* handle;
    int8 Open()
    {
        char errbuf[PCAP_ERRBUF_SIZE];
        pcap_if_t* networkdevice;
        if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &networkdevice, errbuf) == -1)
            return -1;
        while (networkdevice != NULL)
        {
            String networkdevicedescription = networkdevice->description;
            String networkdevicetargettplink = "Network adapter 'TP-LINK Gigabit Ethernet USB Adapter' on local host";
            String networkdevicetargerealtek = "Network adapter 'Realtek Gaming GbE Family Controller' on local host";
            if (networkdevicedescription == networkdevicetargettplink)
            {
                if (LoadNpcapDlls() == 0)
                    return -3;
                handle = pcap_open_live(networkdevice->name, 65535, PCAP_OPENFLAG_PROMISCUOUS, 1, errbuf);
                if (handle == 0)
                    return -4;
                pcap_freealldevs(networkdevice);
                return 0;
            }if (networkdevicedescription == networkdevicetargerealtek)
            {
                if (LoadNpcapDlls() == 0)
                    return -3;
                handle = pcap_open_live(networkdevice->name, 65535, PCAP_OPENFLAG_PROMISCUOUS, 1, errbuf);
                if (handle == 0)
                    return -4;
                pcap_freealldevs(networkdevice);
                return 0;
            }
            networkdevice = networkdevice->next;
        }
        return -2;
    }
    char* Send(void* _data, uint32 lenght)
    {
        if (pcap_sendpacket(handle, (const uint8*)_data, lenght))
            return pcap_geterr(handle);
        return 0;
    }

    void* Recieve()
    {
        struct pcap_pkthdr* header = 0;
        const u_char* data = 0;
        pcap_next_ex(handle, &header, &data);
        return (void*)data;
    }
    void* Recieve(uint32 *bytes)
    {
        struct pcap_pkthdr* header = 0;
        const u_char* data = 0;
        pcap_next_ex(handle, &header, &data);
        *bytes = header->len;
        return (void*)data;
    }
    Ethernet()
    {
        ZeroMemory(this, sizeof(Ethernet));
    }
    ~Ethernet()
    {
        ZeroMemory(this, sizeof(Ethernet));
    }
};

Honestly I dont like this NPCap thing. Isn't there a native Win32 API like the Win32 socket programming API for raw Ethernet frames?


text:
Q: javascript: .innerHTML in to table not adding new rows My js is not adding rows to the end of my table
HTML:

LifePath

Style

js:
//LIFE EVENTS
var d61 = Math.floor(Math.random()*6)+1;
var d62 = Math.floor(Math.random()*6)+1;
var Age = d61+d62+16;

document.getElementById("LifeEvents").innerHTML = "Life Events	";
document.getElementById("LifeEvents").innerHTML += "

Age	"+Age+"	";

i dont mind useing jquery.

A: As provided by @Guruprasad Rao
var d61 = Math.floor(Math.random()*6)+1;
var d62 = Math.floor(Math.random()*6)+1;
var Age = d61+d62+16;

document.getElementById("LifeEvents").innerHTML = "Life Events	";
document.getElementById("tbLIFE").innerHTML += "
Age	"+Age+"	";


text:
Q: How to get separate fields data with IF() statement in single query I am trying to get the unpaid and partial amount separately in single query
select
    if(i.status = 'unpaid', sum(i.total_amount), '') unpaid,
    if(i.status = 'partial', sum(i.paid_amount), '') partial
from {CI}invoices i
where
    i.customer_id = ? and
    date(i.invoice_date) < '2014-01-01' and
    i.status not like 'paid%'

But i am getting blank i think that is because i used '' in if statement, i also tried with
if(i.status = 'unpaid', sum(i.total_amount) as unpaid, sum(i.paid_amount) as paid)

which is wrong because i can't use as in IF() condition. Can anyone please help me to resolve this query or suggest any alternative way??

A: Try the following:
SELECT
    SUM( IF(i.status = 'unpaid', i.total_amount, 0) ) unpaid,
    SUM( IF(i.status = 'partial', i.paid_amount, 0) ) partial
FROM {CI}invoices i
WHERE
    i.customer_id = ? AND
    date(i.invoice_date) < '2014-01-01' AND
    i.status IN ('unpaid', 'partial')

A: Give this a go:
select
    sum(case when i.status = 'unpaid' then i.total_amount else 0 end) as unpaid,
    sum(case when i.status = 'partial' then i.paid_amount else 0 end) as partial
from {CI}invoices i
where
    i.customer_id = ? and
    date(i.invoice_date) < '2014-01-01' and
    i.status not like 'paid%'

A: You have to cross join table to itself to get paid and unpaid in the same row:
SELECT
    sum(iu.total_amount) unpaid,
    sum(ip.paid_amount) partial
FROM {CI}invoices iu
   CROSS JOIN {CI}invoices ip
where
    ip.customer_id = ? AND iu.customer_id = ? AND
    date(ip.invoice_date) < '2014-01-01' AND date(iu.invoice_date) < '2014-01-01' AND
    iu.status = 'unpaid' AND ip.status = 'partial'


text:
Q: Conditional rendering with reactjs I want to add a div to my render objects depending on a condition. Right now I am using this code
render() {
    return (

            {this.test === this.someValue ?
 some view
 :
 /div>}
            ...... // other components

    )
}

this is working but I don't like the :
 /div> because I don't need it. Is there any way to just use an if instead of if else?

A: You can also use only the first condition and return your desired component right away since JavaScript has short-circuit evaluation.
render() {
  return (

     {this.test === this.someValue &&
 some view
}
     ......

  )
}

A: Instead of returning an empty div just because you have to have a second condition, you could return null instead like
render() {
    return (

            {this.test === this.someValue ?
 some view
 : null}
            ...... // other components

    )
}


text:
Q: Duplicity missing backup chains I backed up my system a while ago and now when i reinstall  Ubuntu 19.10, i tried to restore it from the backup but after a lot of trials i could not get duplicity to work, it always return the error
duplicity.dup_collections.CollectionsError: No backup chains found

My command is
duplicity restore "file:///media/user/2bhd/backup/" /back

I checked the path several times by adding, removing slashes but it is still the same so that could not be the reason why.
It turns out that there is no duplicity signature file
duplicity-full-signatures.XXXX.diftar.gz

in the backup directory so that maybe is the reason duplicity does not work so i wanted to ask if there is any possibility of restoring my files without the signature file.

A: if
duplicity collection-status "file:///media/user/2bhd/backup/"

does not return any valid backup chains, then your backup is corrupted unfortunately.
..ede/duply.net


text:
Q: Display specific content for visitors coming from specific sites For the same website (html), I need to display specific content based on where did they come from (referrer).
Example:
Inside 0.html we have something like:
<html>
<content for visitors from example1.com>
<content for visitors from example2.com>
</html>

So:
Visitor1 clicks on link from example1.com pointed to otherexample.com/0.html --> Display only
<content for visitors coming from example1.com>

Visitor2 clicks on link from example3.com pointed to otherexample.com/0.html --> Display only
<content for visitors coming from example2.com>

*

*Is this possible with javascript/html?

*What about displaying an external .html inside the 0.html using this rules?

A: Found the solution:
    <script>
var ref = document.referrer;
if (ref.match(/^https?:\/\/([^\/]+\.)?subdomain\.example\.com(\/|$)/i)) {
   document.write('<img src="https://example.com/img/logo.png" width="60%">');
}
    </script>

This will load an image only for visitors who come from a specific subdomain.


text:
Q: synchronize concept in java doesn't work? We have one hundred accounts in the bank and two clerks, implemented as threads, who transfer each 1000 times money from account with number accountNumberFrom to account accountNumberTo, using the synchronized method transferMoney. Since all accounts start with balance 0 and the money retrieved from one account is transferred to another, the balance should be zero after all the transactions. This is true most of the time, but not always. Although it occurs seldom, but sometimes the balance after the transactions is not equal to 0. What is wrong?
public class Clerk extends Thread {
    private Bank bank;

    public Clerk(String name, Bank bank) {
        super(name);
        this.bank=bank;
        start();
    }

    public void run() {
        for (long i=0; i<1000; i++) {
            int accountNumberFrom = (int) (Math.random()*100);
            int accountNumberTo = (int) (Math.random()*100);
            float amount = (int) (Math.random()*1000) - 500;
            bank.transferMoney(accountNumberFrom, amount);
            bank.transferMoney(accountNumberTo, -amount);
        }
    }
}

and a class Bank

public class Bank {
    Account[] account;

    public Bank() {
        account = new Account[100];
        for (int i=0; i < account.length; i++)
            account[i] = new Account();
    }

    public synchronized void transferMoney(int accountNumber, float amount) {
        float oldBalance = account[accountNumber].getBalance();
        float newBalance = oldBalance + amount;
        account[accountNumber].setBalance(newBalance);
    }
}

public class Banking {
    public static void main (String[] args) {
        Bank myBank = new Bank();
        /**
         * balance before transactions
         */
        float sum=0;
        for (int i=0; i<100; i++)
            sum+=myBank.account[i].getBalance();
        System.out.println("before: " + sum);

        new Clerk ("Tom", myBank);
        new Clerk ("Dick", myBank);

        /**
         * balance after transactions
         */
        for (int i=0; i<100; i++)
            sum+=myBank.account[i].getBalance();

        System.out.println("after: " + sum);
    }
}

A: One issue is that the synchronized transferMoney method only takes one account and so it's possible another thread could access the account balances after the transfer amount has been added to the "to" account but before it has been deducted from the "from" account. If all accounts start at zero, we could have this sequence of events:

*

*Clerk Tom adds $100 to account 1.

*Main thread totals account balances.

*Clerk Tom deducts $100 from account 2.

At step 2 we see that the total of all accounts is $100 instead of zero.
So it's important that the transferMoney method update both accounts while holding the synchronized lock.
Another issue is that while the transferMoney is synchronized, the code that totals the account balances (step 2 above) is not. So even if you update both accounts in the transferMoney method, the sequence of events above can still happen because the main thread doesn't synchronize before executing step 2.
I would move the code that totals up the accounts to Bank and make it synchronized too. That will make both methods synchronized on the Bank instance and prevent the sequence of events that gives the wrong error.
A secondary issue is that in the main thread, you don't wait for the clerks to finish their transfers. Your code is performing all 1,000 transfers, but you just check the balances right after you start the clerk threads, so you may be looking at the balances after 0 transfers, or after all 1,000, or after 639 transfers, who knows. Doing the synchronization correctly will prevent you from seeing a non-zero total balance, but you should still wait for the clerks to finish. (Give it a try and if you can't figure it out, post a new question.)

A: In your example synchronized only block all thread call to myBank.transferMoney, but it doesn't ensure every threads done on main thread, you can update source code like this:
class Clerk extends Thread {
    private Bank bank;
    private volatile boolean done;

    public Clerk(String name, Bank bank) {
        super(name);
        this.done = false;
        this.bank=bank;
        start();
    }

    public void run() {
        for (long i=0; i<1000; i++) {
            int accountNumberFrom = (int) (Math.random()*100);
            int accountNumberTo = (int) (Math.random()*100);
            float amount = (int) (Math.random()*1000) - 500;
            bank.transferMoney(accountNumberFrom, amount);
            bank.transferMoney(accountNumberTo, -amount);
        }
        this.done = true;
    }

    public boolean isDone() {
        return done;
    }
}

class Account {

    protected float balance;

    public float getBalance() {
        return balance;
    }

    public void setBalance(float newBalance) {
        this.balance = newBalance;
    }

}

class Bank {
    Account[] account;

    public Bank() {
        account = new Account[100];
        for (int i=0; i < account.length; i++)
            account[i] = new Account();
    }

    public synchronized void transferMoney(int accountNumber, float amount) {
        float oldBalance = account[accountNumber].getBalance();
        float newBalance = oldBalance + amount;
        account[accountNumber].setBalance(newBalance);
    }
}

public class Banking {
    public static void main (String[] args) throws Exception {
        for(int j = 0 ; j < 1000 ; ++j) {
            Bank myBank = new Bank();
            /**
             * balance before transactions
             */
            float sum=0;
            for (int i=0; i<100; i++)
                sum+=myBank.account[i].getBalance();
            System.out.println("before: " + sum);

            Clerk a = new Clerk ("Tom", myBank);
            Clerk b = new Clerk ("Dick", myBank);

            while(!a.isDone() || !b.isDone()) // wait util all thread done
                Thread.sleep(1);

            /**
             * balance after transactions
             */
            for (int i=0; i<100; i++)
                sum+=myBank.account[i].getBalance();

            System.out.println("after: " + sum);
        }
    }
}

A: Thanks a lot for the helpful answers. I modified my code and now it is working as it should:
public class Bank
{
    Account[] account;

    public Bank() {
        account = new Account[100];
        for (int i=0; i < account.length; i++)
            account[i] = new Account();
    }

    public void transferMoney(int accountNumber, float amount) {
        synchronized (account[accountNumber]) {
            float oldBalance = account[accountNumber].getBalance();
            float newBalance = oldBalance - amount;
            account[accountNumber].setBalance(newBalance);
        }
    }
}

public class Account {
    private float balance;

    public void setBalance(float balance) {
        this.balance=balance;
    }

    public float getBalance() {
        return this.balance;
    }
}

public class Clerk extends Thread {
    private Bank bank;

    public Clerk(String name, Bank bank) {
        super(name);
        this.bank=bank;
    }

    public void run() {
        for (long i=0; i<100; i++) {
            int accountNumberFrom = (int) (Math.random()*100);
            int accountNumberTo = (int) (Math.random()*100);
            float amount = (int) (Math.random()*1000);
            bank.transferMoney(accountNumberFrom, -amount);
            bank.transferMoney(accountNumberTo, amount);
        }
    }
}

public class Accountant extends Thread
{
    Bank bank;

    public Accountant(String name, Bank bank)
    {
        super(name);
        this.bank=bank;
    }

    @Override public void run() {
        getBalance();
    }

    public synchronized void getBalance() {
        float sum=0;

        System.out.println(Thread.currentThread().getName());
        for (int i=0; i<100; i++)
            sum+=bank.account[i].getBalance();

        System.out.println("Bilanz: " + sum);
    }
}

public class Banking {

    public Banking() {
    }

    public static void main(String[] args) {
        Bank myBank = new Bank();
        Clerk tom = new Clerk ("Tom", myBank);
        Clerk dick = new Clerk ("Dick", myBank);
        Accountant harry = new Accountant("Harry", myBank);

        tom.start();
        dick.start();

        try {
            System.out.println("Current Thread: " + Thread.currentThread().getName());
            tom.join();
            dick.join();
        }
        catch(Exception x) {
            System.out.println("Exception has " + "been caught" + x);
        }

        harry.start();
    }
}


text:
Q: Degree of a map between orientable closed manifolds Let $f:X\rightarrow Y$ be a local diffeomorphism, where $X^n$, $Y^m$ are compact and orientable manifolds. I'd like to show that $deg(f)=\text{#}(f^{-1}(z))$ or $deg(f)=-\text{#}(f^{-1}(z))$, for $z \in Y$, where # means the number of elements in the set.
It is clear to me that, in this case, $f$ must be a cover with a finite number of leaves, but I do not know how to go further on this.

A: It was quite a dumb question. It is enough to prove that, for any $y$ regular value of $f$, $deg(f,y)=deg(f)$.
Its the Theorem 13, of Elon Lages Lima's homology book.


text:
Q: Factory-girl factory using reserved word I have a model named "Case" and another model named "CaseUpdateLog" which has a belongs to association in its model.
class CaseUpdateLog < ApplicationRecord
  belongs_to :case
end

If case is not added to the case_update_log Factory then I get an error:
* case_update_log - Validation failed: Case must exist (ActiveRecord::RecordInvalid).

If I add "case" to the case_update_log Factory get error: unexpected tIDENTIFIER, because case here gets interpreted as the kickoff of a switch statement.
FactoryGirl.define do
  factory :case_update_log do
    case
  end
end

I have tried
factory :case, :aliases => [:a_case] do

in the case Factory and then used a_case in the case_update_log Factory but it still gives me error: * case_update_log - undefined method `a_case=' for # Did you mean?  case= (NoMethodError).  Please advise if you have a solution.  Thank you.


text:
Q: Metric for sequences proof Suppose $X = \{\{x_n\}_{n \in \mathbb{N}} : x_n \in \mathbb{R}$ $\forall n\geq 1\}$. Prove that $d: X \times X \rightarrow \mathbb{R}$ such that $d(\{x_n\}_{n \in \mathbb{N}}, \{y_n\}_{n \in \mathbb{N}}) = \sum_{n = 1}^{\infty} 2^{-n}\frac{|x_n - y_n|}{1 + |x_n - y_n|}$ is a metric on $X$.
My attempt:
I was given the hint that I should check each of the following: (1) a function $f(x) = \frac{x}{x+1}$ is montone increasing, (2) the triangle inequality applies to $\frac{|x_n - y_n|}{(1 + |x_n - y_n|)}$ and (3) the metric itself satisfies the inequality.
(1) $f$ is monotone increasing:
If $x \geq 0$, $f'(x) = \frac{1}{(1 + x)^2} > 0$.
So $f$ is increasing.
(2) Triangle inequality applies:
We have $|x_n-y_n|≤|x_n-z_n|+|z_n-y_n|$ and so
$\frac {|x_n-y_n|}{1+|x_n-y_n|}≤ \frac {|x_n-z_n|+|z_n-y_n|}{1+|x_n-z_n|+|z_n-y_n|}=\frac {|x_n-z_n|}{1+|x_n-z_n|+|z_n-y_n|} + \frac {|z_n-y_n|}{1+|x_n-z_n|+|z_n-y_n|}≤\frac{|x_n-z_n|}{1+|x_n-z_n|}+\frac {|z_n-y_n|}{1+|z_n-y_n|}$
Therefore $\frac{|x_n - z_n|}{1 + |x_n - z_n|}+\frac{|z_n-y_n|}{1 + |z_n-y_n|} \geq \frac{|x_n-y_n|}{1 + |x_n-y_n|}$.
(3) Metric satisfies triangle inequality:
We know $\frac{|x_n - z_n|}{1 + |x_n - z_n|}+\frac{|z_n-y_n|}{1 + |z_n-y_n|} \geq \frac{|x_n-y_n|}{1 + |x_n-y_n|}$. So
$$2^{-n}(\frac{|x_n - z_n|}{1 + |x_n - z_n|}+\frac{|z_n-y_n|}{1 + |z_n-y_n|}) \geq 2^{-n}\frac{|x_n-y_n|}{1 + |x_n-y_n|}$$
and
$$\sum_{n = 1}^{\infty} 2^{-n}(\frac{|x_n - z_n|}{1 + |x_n - z_n|}+\frac{|z_n-y_n|}{1 + |z_n-y_n|}) \geq \sum_{n = 1}^{\infty} 2^{-n}\frac{|x_n-y_n|}{1 + |x_n-y_n|}$$
QED.
First of all, is this correct? If so, is that it? Is that sufficient to show that $d$ is a metric on $X$? Although I understood how to prove the hints, I still am not sure how these hints actually show that $d$ is a metric on $X$, presuming they are sufficient to show this. Any insight is much appreciated.

A: The definition of a metric $d$ has 3 requirements for all points $x, y \in X$.

*

*$d(x, y)=0 \iff x=y$

*$d(x, y)=d(y, x)$

*triangle inequality.

You've proved the last requirement successfully, now all you need to do is prove the first two (this is quite straight forward).


text:
Q: How to reinstall a LAMP server? I want to reinstall the whole LAMP server under Debian Lenny. This means, using 'apt-get remove' is not enough, I want to remove completely all components, and start again.
I tried but files are always there so I can't make a new configuration for everything. What can I do?
Thanks!

A: 1 su aptitude purge apache2 apache2-mpm-prefork apache2-utils apache2.2-common libapache2-mod-php5 libapr1 libaprutil1 libdbd-mysql-perl libdbi-perl libmysqlclient15off libnet-daemon-perl libplrpc-perl libpq5 mysql-client-5.0 mysql-common mysql-server mysql-server-5.0 php5-common php5-mysql
2 apt-get update
3 apt-get upgrade  --> opt
4 apt-get install apache2 php5 libapache2-mod-php5
5 vim /var/www/apache2-default/test.php
   then copy the below code into the test.php
6 apt-get install mysql-server mysql-client php5-mysql
7 mysql -u root
 mysql> USE mysql;
 mysql> UPDATE user SET Password=PASSWORD('new-password') WHERE user='root';
 mysql> FLUSH PRIVILEGES;
8 apt-get install phpmyadmin
9 vim  /etc/phpmyadmin
  copy below line
   Include /etc/phpmyadmin/apache.conf
10 /etc/init.d/apache2 restart

or
apt-get reinstall apache2 php5 libapache2-mod-php5 mysql-server mysql-client php5-mysql phpmyadmin

A: If you just want to do the configuration over again, you can use dpkg-reconfigure [packagename] to re-run the initial setup scripts.
To completely start over, you'll need to purge all of the previous packages.  I am not sure that purging Debian's mysql packages will delete the database data itself though, you may need to remove the folder with the mysql database files manually after purging the packages if you don't want to keep the data.
sandeep's "or" command should read apt-get install --reinstall ...  but even then it won't do what you want since the --reinstall option will "upgrade" from the existing configuration.


text:
Q: Can I not submit a form to a servlet from JSF? *  Unable to find matching navigation case with from-view-id '/home.xhtml' for action 'MemoServlet' with outcome 'MemoServlet'

I try to accomplish it through:
<h:commandButton type="submit" value="add" action="MemoServlet"/>

but all the tutorials in the world only do it with a bean, which i don't want. I've come across any navigation rule that accomplishes my request.

A: Why a servlet? What exactly is the functional requirement? Doesn't the servlet contain "too much" code which you could just refactor into a separate class and import/call that in both the original servlet and the JSF bean action method?
Anyway, to fix the particular problem, you need either a plain vanilla HTML <form> element whose action points to the servlet URL or to call ExternalContext#dispatch() on the servlet URL inside the bean's action method.


text:
Q: What is the shortcut to insert multiple line comment with * in the beginning in VS Code? I know the shortcut Ctrl+shift+A in VS Code Linux to insert the multiple lines comment, but it just insert like this:
/*
my comment
my code i want to hide
etc
*/

How to get a comment like this?
/**
 * my comment
 * my code i want to hide
 * etc
*/

If I want to get comment like above, I need to insert manually like this
/**
*/

And every time I hit "Enter" inside that comment, VS Code automatically insert * like this
/**
 *
 *
 *
 *
 *
*/

It looks like that kind of comment is supported in VS Code,
But I dont know the short cut to insert the new one without typing manually.
Anyone know the answer ? Thanks,

A: UPDATE : VS CODE has update about this, more info : https://code.visualstudio.com/docs/languages/javascript#_jsdoc-support
When you type /** VS code will know what you want and show like this
hit enter and move your code inside that comment block

Look like there is no shortcut key for this till now, and if we want to that kind of comment style, we need to do it manually by typing this:
/**
*/

and hit "Enter" inside that comment


text:
Q: Table View not shown in Interface Builder Attributes of a NSTableView in Xcode 5 When viewing the attributes of a NSTableView table in Xcode 5, only Scroll View and View appears, whereas in tutorials online I should be accessing the Table View.
I need to access the items in Table View, such as number of columns, etc.
I have searched the internet but couldn't see a reason why this does not appear.
Do the options to change columns etc appear in a different location than in Xcode 4?
Screenshot:

A: the tableview is embedded in a scrollview and a clipview which makes it hard to click.
select it by using your sidebar on the left


text:
Q: Reagent - methods of storing ui state together with (or separate from?) server-persisted state? I'm using multiple atoms within a map called app-state and it's working quite well architecturally so far. The state distributed across those atoms is normalised, reflecting as it is stored in datomic, and of course what the client is initialised with is a specific subset of what's in datomic. This is me preparing the way to try out datascript (which is what gave me the aha moment of why client state is so much better fully normalised, even if not using datascript).
I have a question at this point. We all know that some state in reagent is a reflection of what's in the server's database (typically), but there's also state in reagent concerning solely the current condition of the ui. That state will vanish when the page is re-loaded and there's (typically) no need to store that on the server.
So, I'm looking at my list of atoms and realising that I have some atoms which hold database-record-like maps, i.e. they contain exact reflections of datomic entities, (which arrive by transit), which is great.
But now I notice I also want some ui state per datomic entity.
So the question arises whether to (this seems wrong to me) add some keys to what came from datomic, of the ui state that is irrelevant to datomic, but that the client needs (i.e., dump it into the same nested map).  That is entirely possible, but seems wrong, and so suggests....   (this being my idea as of now), How about a parallel atom per "entity", like @<entity-name>-ui, containing a map (or even a vector of maps, if multiple entities), with a set of keys for ui state.
That seems an improvement on what I have ended up with by default as of now, which is separate atom for every piece of ui state (I've avoided component local state up to now). (Currently the ui only holds ui state for one record at a time, so these ui atoms need only be concerned with a single current entity).
But if, say, I made a parallel atom (to avoid mixing ephemeral ui and server state), then ui state could perhaps manageably extend deeper. We could hold, say, ui state per entity so switching current-entity back and forth would remember ui state.
Since this is Stack Overflow, I have to ask a specific question, rather than this just be discussion, so: given what I've described, what are some sensible architectural choices in this case, to store state in reagent?

A: If you are storing your app state in several component-independent reagent atoms already - you can check https://github.com/day8/re-frame which is a widely-adopted reagent-powered framework exactly for your case. Essentially it stores all the application state in a reagent atom but has a well-developed infrastructure to support coordinated storage and updates. They have brilliant documentation with a great high-level explanation of the idea.
Regarding your initial question about server/ui state separation - I think you should definitely go this way. It'll give you a better way of separating concerns and give you an easier way to update server/ui data separately. It is very easy to achieve this with re-frame by storing both parts of the state under separate top-level keys in re-frame application db. E.g.
{:server {:entity-name ...}
 :ui     {:entity-name ...}}

and then create suitable subscriptions(see re-frame docs) to retrieve it.


text:
Q: Are there any drawback if i use a virtual disk located in a different server? I'm using a virtualized OsX Server into a physical Hp server (Server A) through VirtualBox.
Because i don't have free space in my HP Server, i've created a VDI into a second Nas Storage Server (Server B) and i've mounted this VDI into my OsX server using CIFS/Samba.
I'm wondering are there any drawback using with this solutions ?
Is the file access, file operations (like copy moving etc.) more limited compared to a 'simpler' solutions like use only Server A ?
How to improove this situations ? Maybe mounting Server B into Server A with iSCSI o fibre channel ?
Thanks

A: the only limitation is going to be performance. any other potential problems will all have performance as a root cause.


text:
Q: BigQuery: Extra rows when doing cross join and adding another field to be partitioned Question is somewhat related to my previous Fill in missing values for joined tables in BigQuery.
Basically I have 2 tables. One with stock transactions other with stock prices. Goal is to have table where for every day for which there is price, value is calculated. This was answered in previous question. (Doing CROSS JOIN and ARRAY_AGG to fill in missing amount for date where stock price exists, but there wasn't any transaction).
Now if I want to add other values like "running amount / balance" then result is broken, basically every row is doubled (date and stock symbol) since I am adding other field (running_amount) to by partitioned (which I have to do). Here my understanding of SQL ends :) so I would appreciate any help or suggestion. Goal is to have one line per date and stock symbol.
Here is full sample query:
WITH `trans` AS (
SELECT DATE '2018-10-02' trans_date, 10.0 stock_amount, 'TX' stock_symbol UNION ALL
SELECT DATE '2018-10-03', 5.0, 'TX' UNION ALL
SELECT DATE '2018-10-05', 11.0, 'AX' UNION ALL
SELECT DATE '2018-10-10', 10.0, 'AX'

),
`prices` AS (
 SELECT DATE '2018-10-01' price_date, 1.0 price, 'TX' symbol UNION ALL
  SELECT DATE '2018-10-02', 2.0, 'TX' UNION ALL
  SELECT DATE '2018-10-03', 3.0, 'TX' UNION ALL
  SELECT DATE '2018-10-04', 4.0, 'TX' UNION ALL
  SELECT DATE '2018-10-05', 5.0, 'TX' UNION ALL
  SELECT DATE '2018-10-06', 6.0, 'TX' UNION ALL
  SELECT DATE '2018-10-07', 7.0, 'TX' UNION ALL
  SELECT DATE '2018-10-08', 8.0, 'TX' UNION ALL
  SELECT DATE '2018-10-08', 8.0, 'AX' UNION ALL
  SELECT DATE '2018-10-09', 9.0, 'TX' UNION ALL
  SELECT DATE '2018-10-09', 9.0, 'AX' UNION ALL
  SELECT DATE '2018-10-10', 10.0, 'TX' UNION ALL
  SELECT DATE '2018-10-10', 10.0, 'AX' UNION ALL
  SELECT DATE '2018-10-11', 11.0, 'TX' UNION ALL
  SELECT DATE '2018-10-11', 11.0, 'AX' UNION ALL
  SELECT DATE '2018-10-12', 11.0, 'AX' UNION ALL
  SELECT DATE '2018-10-12', 12.0, 'TX'
)

SELECT
  price_date,
  tx.stock_symbol AS token_symbol,
  IFNULL(
    ARRAY_AGG(
      IF(p.price_date >= tx.trans_date AND p.symbol = tx.stock_symbol, stock_amount, NULL)
      IGNORE NULLS ORDER BY trans_date DESC LIMIT 1
      )[OFFSET(0)],
  -1234567890) stock_amount,
  running_amount,
  price

FROM (
   SELECT
       trans_date,
       stock_symbol,
       stock_amount,
       SUM(stock_amount) OVER (PARTITION BY stock_symbol ORDER BY trans_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_amount
   FROM `trans`
   ORDER BY stock_symbol, trans_date
)
AS tx
CROSS JOIN `prices` as p
GROUP BY price_date, price, token_symbol
,running_amount
HAVING stock_amount != -1234567890
ORDER BY stock_symbol, price_date

This result is expected:
Row price_date  token_symbol    stock_amount    running_amount  price
1   2018-10-08  AX  11  11  8
2   2018-10-09  AX  11  11  9
3   2018-10-10  AX  10  21  10
4   2018-10-11  AX  10  21  11
5   2018-10-12  AX  10  21  11
6   2018-10-02  TX  10  10  2
7   2018-10-03  TX  5   15  3
8   2018-10-04  TX  5   15  4
9   2018-10-05  TX  5   15  5
10  2018-10-06  TX  5   15  6
11  2018-10-07  TX  5   15  7
12  2018-10-08  TX  5   15  8
13  2018-10-09  TX  5   15  9
14  2018-10-10  TX  5   15  10
15  2018-10-11  TX  5   15  11
16  2018-10-12  TX  5   15  12

A: For BigQuery Standard SQL
#standardSQL
WITH `trans` AS (
  SELECT DATE '2018-10-02' trans_date, 10.0 stock_amount, 'TX' stock_symbol UNION ALL
  SELECT DATE '2018-10-03', 5.0, 'TX' UNION ALL
  SELECT DATE '2018-10-05', 11.0, 'AX' UNION ALL
  SELECT DATE '2018-10-10', 10.0, 'AX'

), `prices` AS (
  SELECT DATE '2018-10-01' price_date, 1.0 price, 'TX' symbol UNION ALL
  SELECT DATE '2018-10-02', 2.0, 'TX' UNION ALL
  SELECT DATE '2018-10-03', 3.0, 'TX' UNION ALL
  SELECT DATE '2018-10-04', 4.0, 'TX' UNION ALL
  SELECT DATE '2018-10-05', 5.0, 'TX' UNION ALL
  SELECT DATE '2018-10-06', 6.0, 'TX' UNION ALL
  SELECT DATE '2018-10-07', 7.0, 'TX' UNION ALL
  SELECT DATE '2018-10-08', 8.0, 'TX' UNION ALL
  SELECT DATE '2018-10-08', 8.0, 'AX' UNION ALL
  SELECT DATE '2018-10-09', 9.0, 'TX' UNION ALL
  SELECT DATE '2018-10-09', 9.0, 'AX' UNION ALL
  SELECT DATE '2018-10-10', 10.0, 'TX' UNION ALL
  SELECT DATE '2018-10-10', 10.0, 'AX' UNION ALL
  SELECT DATE '2018-10-11', 11.0, 'TX' UNION ALL
  SELECT DATE '2018-10-11', 11.0, 'AX' UNION ALL
  SELECT DATE '2018-10-12', 11.0, 'AX' UNION ALL
  SELECT DATE '2018-10-12', 12.0, 'TX'
)
SELECT
  price_date,
  tx.stock_symbol AS token_symbol,
  IFNULL(
    ARRAY_AGG(
      IF(p.price_date >= tx.trans_date AND p.symbol = tx.stock_symbol, stock_amount, NULL)
      IGNORE NULLS ORDER BY trans_date DESC LIMIT 1
      )[OFFSET(0)],
  -1234567890) stock_amount,
  SUM(
    IF(p.price_date >= tx.trans_date AND p.symbol = tx.stock_symbol, stock_amount, 0)
  ) running_amount,
  price
FROM `trans` AS tx
CROSS JOIN `prices` AS p
WHERE stock_symbol = symbol
GROUP BY price_date, price, token_symbol
HAVING stock_amount != -1234567890
-- ORDER BY stock_symbol, price_date

with result
Row price_date  token_symbol    stock_amount    running_amount  price
1   2018-10-08  AX              11.0            11.0            8.0
2   2018-10-09  AX              11.0            11.0            9.0
3   2018-10-10  AX              10.0            21.0            10.0
4   2018-10-11  AX              10.0            21.0            11.0
5   2018-10-12  AX              10.0            21.0            11.0
6   2018-10-02  TX              10.0            10.0            2.0
7   2018-10-03  TX              5.0             15.0            3.0
8   2018-10-04  TX              5.0             15.0            4.0
9   2018-10-05  TX              5.0             15.0            5.0
10  2018-10-06  TX              5.0             15.0            6.0
11  2018-10-07  TX              5.0             15.0            7.0
12  2018-10-08  TX              5.0             15.0            8.0
13  2018-10-09  TX              5.0             15.0            9.0
14  2018-10-10  TX              5.0             15.0            10.0
15  2018-10-11  TX              5.0             15.0            11.0
16  2018-10-12  TX              5.0             15.0            12.0


text:
Q: Cannot find 'taskCellVM' in scope I'm following a tutorial to make a reminders app in swiftui. I'm pretty new to more complex apps in swiftui and there were these errors in the debugger. What do they mean and how I can solve them. If it helps, the tutorial that I'm watching is this: https://www.youtube.com/watch?v=4RUeW5rUcww
Thank you in advance.
1)TaskListView.swift:15:25: error: failed to produce diagnostic for expression; please file a bug report
    var body: some View {

2) TaskListView.swift:20:45: error: cannot find 'taskCellVM' in scope
                    in TaskCell(taskCellVM: taskCellVM)
                                            ^~~~~~~~~~

TaskListView.swift
import SwiftUI

struct TaskListView: View {
    @ObservedObject var taskListVM = TaskListViewModel()

    let tasks = testDataTasks

    var body: some View {
        NavigationView {
            VStack(alignment: .leading) {
                List(taskListVM.taskCellViewModels){
                    TaskCellVM
                    in TaskCell(taskCellVM: taskCellVM)

                }
                Button(action: {}) {
                    HStack {
                        Image(systemName: "plus.circle.fill").resizable().frame(width: 20, height: 20)
                        Text("Add New Task")
                    }
                }
            }
            .padding()
        }
        .navigationBarTitle("Tasks")
    }
}

struct TaskListView_Previews: PreviewProvider {
    static var previews: some View {
        Group {
            TaskListView()
                .previewDevice("iPhone 12 Pro Max")
        }
    }
}

struct TaskCell: View {
    @ObservedObject var taskCellVM: TaskCellViewModel

    var body: some View {
        HStack {
            Image(systemName: taskCellVM.task.completed ? "checkmark.circle.fill" :  "circle").resizable().frame(width: 20, height: 20)
            Text(taskCellVM.task.title)
        }
    }
}

TaskCellViewModel.swift
import Foundation
import Combine

class TaskCellViewModel: ObservableObject, Identifiable {
    @Published var task: Task

    var id = ""
    @Published var completionStateIconName = ""

    private var cancellables = Set<AnyCancellable>()

    init(task: Task) {
        self.task = task

        $task
            .map{
            task in task.completed ? "checkmark.circle.fill" : "circle"
        }
        .assign(to: \.completionStateIconName, on: self)
        .store(in: &cancellables)

        $task
            .map { task
                in task.id
            }
            .assign(to: \.id, on: self)
            .store(in: &cancellables)
    }
}

TaskListViewModel.swift
import Foundation
import Combine

class TaskListViewModel: ObservableObject {
    @Published var taskCellViewModels = [TaskCellViewModel]()

    private var cancellables = Set<AnyCancellable>()

    init() {
        self.taskCellViewModels = testDataTasks.map{
            task in TaskCellViewModel(task: task)
        }
    }
}

A:                 List(taskListVM.taskCellViewModels){
                    TaskCellVM
                    in TaskCell(taskCellVM: taskCellVM)

                }

You used TaskCellVM as the parameter to the List's closure, but you used taskCellVM in the TaskCell initializer. Capitalization needs to match.


text:
Q: Постить новости curl'ом на odnoklassniki.ru Подскажите, может быть кто-то уже сталкивался с подобной проблемой и знает, где глянуть пример. Необходимо постить новости с сайта (есть rss) через curl на страницу одноклассников. С ссылочкой и картинкой.

A: Ну здесь уже чистое автозаполнение формы курлом, методом POST. Вот кусок кода:
 $cont = "Email=email@gmail.com&pass=12345"; // параметры запроса
 ...
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, "https://accounts.google.com/ServiceLogin");
 curl_setopt($ch, CURLOPT_POST, 1); // указываем метод отправки данных
 curl_setopt($ch, CURLOPT_POSTFIELDS,$cont); // данные поста
 $result=curl_exec($ch);
 if($result) echo("Готово!"); else echo("No...");
 curl_close($ch);


text:
Q: How to use ssh to run a local .sh file (present on a local linux machine) on a remote linux machine (an AWS ec2 instance) I am having a tough time figuring out a way to execute a .sh file present on my local linux machine on to a remote linux machine which happens to be an AWS ec2 instance.
Here's what I am doing on my local machine:
ssh -i sample.pem ec2-user@server_name.amazon.com 'bash -s' < file_to_remotely_execute.sh

Error that I get is:
Warning: Identity file sample.pem not accessible: No such file or directory.
Pseudo-terminal will not be allocated because stdin is not a terminal.
Host key verification failed.
This was referred to arrive at the above approach.

A: Possible issues :

*

*The PEM file doesn't exist.

*The PEM file doesn't have proper permissions.

*The host is not allowed in ~/.ssh/known_hosts file.

Solutions :

*

*Navigate to the location where PEM file exists or give full path of PEM file.

*Give 400 permissions to the PEM file, (sudo chmod 400 /path/to/file.pem).

*Login to the server by ssh once, and allow the host.


text:
Q: Getting started on smart signage dev I wanted to develop a stand alone HTML5 app on Samsung Smart Signage. I am trying to find the sdk and some documentation to get started but I couldn't find any. Could anyone please point me … to the right resources to get started on Digital Signage development in HTML5? Thanks a lot in advance!

A: Check this out: http://displaysolutions.samsung.com/aboutUs/faqList?method=list&sflag2=534&sflag3=542&sflag4=545&pageNo=1
I was unable to get to the SDK download page though, as the Samsung Logins are still notoriously bad as they have always been.


text:
Q: Do gravitational waves disperse/refract (like EM waves in a prism)? I have read this question:
What is the relationship between a gravitational wave and a graviton?
where kingledion says:

Gravitational waves were theorized a century ago and recently discovered, leading to the awarding of the 2017 Nobel Prize in Physics. According to Wikipedia:
    Gravitational waves transport energy as gravitational radiation, a form of radiant energy similar to electromagnetic radiation.

Why do prisms work (why is refraction frequency dependent)?

where Ben Crowell says:

What is actually observed is the superposition of this wave with the incident wave. This superposition has two parts, a reflected wave and a transmitted one. In the limit of a low-density medium (such as a gas), the index of refraction is given by n2=1−ω2pf(ω), where ωp, called the plasma frequency, is given by ω2p=Ne2/mϵ0, where N is the number density of electrons. The plasma frequency has an e/m in it from the amplitude of the driven harmonic oscillator, and another factor of e because the amplitude of the reemitted wave is proportional to the amount of charge oscillating. In the case of silica glass, I think the 0.1 μm resonance is probably what is described by the above mechanism, while the other resonances are similar mathematically but involve other effects than oscillation of bound electrons. E.g., the Si-O-Si bridges would resonate at a lower frequency due to the greater inertia of the nuclei compared to electrons.
    The above does seem to suggest that there's some very universal behavior going on in the interaction of EM waves with matter.

where annav says:

A photon impinging on the surface of the lattice, finds not two slits , but a depth of slits all the way through. The observed effect of the different angular distribution according to the impinging frequency of the photon must be the result of the quantum mechanical interference of the photon, which must be constructive in the angle of refraction given by its frequency and index of refraction and destructive everywhere else, otherwise we would be seeing interference fringes ( actually we do get a second rainbow, but that is a different story :) , though should be similar).
    Then the problem is reduced to explaining the frequency dependence. I will hand wave again and say that the smaller the frequency the larger the distances in the interference pattern of the probability wave ; the photon will see the lattice gaps differently according to its wavelength, as is true for the double slit experiment, so a fanning out is to be expected.

Now there is a classical and a QM explanation both for dispersion/refraction of EM waves/photons through a prizm.

In optics, dispersion is the phenomenon in which the phase velocity of a wave depends on its frequency.n optics, one important and familiar consequence of dispersion is the change in the angle of refraction of different colors of light,2 as seen in the spectrum produced by a dispersive prism and in chromatic aberration of lenses.The most familiar example of dispersion is probably a rainbow, in which dispersion causes the spatial separation of a white light into components of different wavelengths (different colors).

https://en.wikipedia.org/wiki/Dispersion_(optics)
Now even in the classical explanation of EM waves', it is easily explainable why the wavelength of different EM waves creates the dispersion we see in a prizm.
Now GW have been experimentally observed, they do exist.
I have not found anything about whether GWs do get dispersed based on their wavelength. Some GWs have their own specific wavelength, and some must be a combination of different wavelength waves (just like white light is a combination of all visible wavelength EM waves).
Now if we already observed GWs, did we observe their dispersion, they must obey the same physical laws, and they must undergo dispersion, as they change media.

The phase of gravitational waves in the dispersive case and non-dispersive case and dephasing between two waveforms. The total Mass M=106 M⊙, the symmetric mass ratio ν=10−5, e=0.5, p=12M and a=0.9. We set DL=1.00 Gpc, where Z≈0.20 and D≈0.83 Gpc. The Compton wavelength of graviton λg=1.6×1013 km. The cyan, orange and red curves represent the non-dispersive's, dispersion's phase and dephasing respectively.

In principle, gravitational waves could exist at any frequency. However, very low frequency waves would be impossible to detect and there is no credible source for detectable waves of very high frequency.

https://en.wikipedia.org/wiki/Gravitational_wave
http://inspirehep.net/record/1708562/plots
Question:

*

*Do GWs disperse at the edge of different media (like EM waves in a prizm)?

*Have we ever experimentally seen different wavelength GWs disperse at the edge of different media?

A: In physics we call waves to any physical perturbation of some quantity that propagates through space or time or or both and that obeys D'Alembert's wave equation or some generalization of it.
This equation doesn't care about the perturbation been on the water (ocean waves), on the pressure of air (sound waves), on the mechanical stresses of Earth's crust (sismic waves), on the field lines of the electromagnetic field (light) or on the curvature of space-time (gravitational waves). For a fixed number of dimensions this equation yields the same predictions for all of them. There can be polarization, difraction, refraction, coherence, reflection and other phenomena, the only major difference is what devices or physical systems should be the ones responsible for those.
Gravitational waves differ from electromagnetic waves in some fundamental aspects. For example; the straing of a gravitational wave depends on $r^{-1}$ while the intensity of light depends on $r^{-2}$ (where $r$ is the distance of the detector from the source). There is also the fact that matter is transparent to gravitational waves of any frequency. But still we can rescue some of the shared phenomenology.
We now know that gravitational waves with microwave frequencies (still as high for any known astrophysical phenomena) can be reflected from thin superconducting films. The gravitational waves move matter and matter that changes its motions generates gravitational waves, the over all effect can yield a coherent reflection from these films (just like electromagnetic waves reflect because the oscilating electric field moves charges in the mirror and in turn those generate their own electromagnetic waves).
See this research paper: Do Mirrors for Gravitational Waves Exist?
It is also known that light can move in non-straight paths on curved geometries of space-time. For example light can make a full circle around a black hole in what is known as the photon sphere. And it is also known that there are even solutions where a light ray can come back to the emmiting source after circling the black hole.

So, the surroundings of a black hole can act like a mirror (you can see yourself). The same goes for gravitational waves, they get diffracted so much that could go back to where it came. Thus black holes are mirrors for larger gravitational waves, just a very complicated mirror with a weird distorted image of yourself. By the way, the animation comes from a series of videos done by Viascience (highly recommended).
The search for echoes (like those of sound waves) by reflections of gravitational waves on certain space-times that could behave as "walls" has been investigated.
See this research paper: Gravitational wave sources: reflections and echoes
Diffraction of gravitational waves can happen in stellar clusters so maybe we could use those as your "prism"
See this research paper: Emission of gravitational waves from binary systems in the galactic center anddiffraction by star clusters
In fact the idea of diffracting gravitational waves can be extended to focus them. We can immagine some astrophysical objects as analogous to optical elements in an optical system. If we focus gravitational waves we can make gravitational telescopes (and not just observatories). In fact black holes not only can magnify light sources far away but also can magnify gravitational waves, this phenomenon is called gravitational lensing of gravitational waves and there are some papers exploring the subject.
See this research paper: Gravitational lensing of gravitational waves: wave natureand prospects for detection
See this research paper: Gravitational lensing of gravitational waves: A statisticalperspective
See this research paper: Effect of gravitational lensing on the distribution of gravitational waves from distant binary black hole mergers
See this research paper: Wave Effects in Gravitational Lensing of Gravitational Wavesfrom Chirping Binaries

A: Gravitational waves are a disturbance in space and time and move by penetrating space-time so no refraction occurs.
The wavelength of gravity waves is much shorter than electron and protons.


text:
Q: Can't get background image to work on stacklayout I've got a JSON file returning any number of images as base64. In my component.html, I'm trying to set the images as the background to a StackLayout like so:
<StackLayout height="200" *ngFor="let image of selectedProperty.images">
   <StackLayout height="100%" ng-style="{'background-image':'url('+image.base64+')'}"></StackLayout>
   <!--<Image src="{{ image.base64 }}"></Image>-->
</StackLayout>

I know that image.base64 holds the correct base64 strings, because if I uncomment the <Image> element, it displays the images fine. It seems like the issue is the background-image css property itself, because even if I try to do it using a normal image from google (for example style="background-image:url('https://pbs.twimg.com/profile_images/839721704163155970/LI_TRk1z_400x400.jpg')"
), it doesn't work either. I'm feeling extremely silly because this just has to be something very simple, but I just cannot figure it out.
Any help would be very much appreciated.

A: I have done a similar thing in one of my projects. I set a div to be hidden until the image has loaded. To track this event, I am listening to the load event on the img tag.
<!-- the div is hidden until the image is loaded -->
<div *ngIf="photo.url" class="image" [hidden]="loading"
     [ngStyle]="{'background-image': 'url(' + photo.url + ')'}" >
</div>
<!-- hidden img tag to load the image and toggle loading status -->
<img src="{{photo.url}}" alt="{{photo.description}} photo" hidden (load)="imageLoaded()">

And in the controller:
imageLoaded() {
  this.loading = false;
}

So when browser fetches is ready to render the image, the event handler sets loading to be false, which updates the view, and the <div> is not hidden anymore, which causes it to render.
I assume you can adapt the code to use NativeScript, but tell me if not.


text:
Q: Response Headers "Name two headers that, if present n an http response, always have to be processed in a particular order. state the order and explain."
I have researched this online and in my textbook: Web Application Architecture by Shklar and Rosen.
My initial thought was that it was "www authentication" and "location"  however with other  research i have become more confused.
Any help would be greatly appreciated.

A: HTTP headers are independant of each other.  They can appear in any order, and be processed in any order.  I have never seen multiple HTTP headers that were meant to work together, let alone require being processed in a particular order.
The WWW-Authentication and Location headers have nothing to do with each other.  WWW-Authentication is used to request/negotiate auth credentials for a single URL.  Location is used during redirect responses (3xx other than 304) to specify a different URL to send a request to.
There was a recent discussion about the processing semantics of the Accept and Accept-Charset headers, but that relationship is not officially defined, and it applies to request headers, not response headers.


text:
Q: Invoke client side button click from server event (asp.net) I'am building an asp.net application that have a gridview inside an update pannel.
In this grid, I added a command field that raise a server event to fill fields on my modal popup hiden div section.
Off course, once filled, I want to display the modal popup to the user.
my issue is : how do I make that popup visible?
I use http://www.ericmmartin.com/projects/simplemodal/
the same way it work in the sample, the modal work well when I click on a client side link, but how may I invoke the show event from a server side even with asp.net (VB or C#)?
I am totally new to JQuery and AJAX, thanks for your help
Steph

A: Add this code to command button's click handler method:
ScriptManager.RegisterStartupScript((Control)sender, sender.GetType(), Guid.NewGuid().ToString(),
    string.Format("$('#{0}').modal();", modalDiv.ClientID ), true);


text:
Q: stripe checkout not not working like in the demo Hi i'm trying to insert Stripe on my php website, i took the Stripe sample from the their website but all i receive instead of a nice checkout page is nothing more than text, i'm in local using Wamp, stripe php is install through composerthe create-checkout-session.php [the server part]  `
<?php

require 'vendor/autoload.php';
\Stripe\Stripe::setApiKey('sk_test_51GnYWKFeoY7b2LtguaCMHEyazW1Ly9SsOhpig3V27QwSURm8xTXZQIe7toFA39v5A34CIzBrZL7o0Y5lYJkiVToC00V1gsNvwi');

header('Content-Type: application/json');

$YOUR_DOMAIN = 'http://localhost:4242';

$checkout_session = \Stripe\Checkout\Session::create([
  'payment_method_types' => ['card'],
  'line_items' => [[
    'price_data' => [
      'currency' => 'usd',
      'unit_amount' => 2000,
      'product_data' => [
        'name' => 'Stubborn Attachments',
        'images' => ["https://i.imgur.com/EHyR2nP.png"],
      ],
    ],
    'quantity' => 1,
  ]],
  'mode' => 'payment',
  'success_url' => $YOUR_DOMAIN . '/success.html',
  'cancel_url' => $YOUR_DOMAIN . '/cancel.html',
]);

echo json_encode(['id' => $checkout_session->id]);``

the checkout.html [the front part]
    <!DOCTYPE html>

    <title>Buy cool new product</title>
    <link rel="stylesheet" href="style.css">

Stubborn Attachments

$20.00

      <button type="button" id="checkout-button">Checkout</button>

Here what i receive when i go on localhost 4242
{"id":"cs_test_a1jEBgtlzTJrv4MMwTCgsKgHrCLM0k31Ztrk620EV2H8StQApoptTudXrZ"}

A: Sounds like localhost:4242 is pointing to your create-checkout-session.php file, which is returning a Checkout Session ID as json as expected.
You need to make sure that localhost:4242 points to your checkout.html file instead. Look into your server set up to see if you can find out why it's pointing to the wrong file.
As a side note, you left your secret test API key in the question. That key is now compromised, you should roll it immediately at https://dashboard.stripe.com/test/apikeys


text:
Q: Handle wrong password event on fb integration using FBSDKLoginBehaviorWeb Hello i have used below code for integrating fb in my ios application and it is working successfully. But here one strange thing is happens when i try wrong id/password and then after i enters the correct id and password it redirects me to the facebook webview and my profile open strange one. It should redirect to my app. Any help regarding this will be appreciated.
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
login.loginBehavior = FBSDKLoginBehaviorWeb;
[login logInWithReadPermissions:@[@"email"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
    if (error)
    {
        NSLog(@"Login Error : %@", error.description);
    }
    else if(result.isCancelled)
    {
        NSLog(@"Login Cancel By User");
    }
    else
    {
        [self fetchUserDataForFacebookLogin];
        //[login logOut];
    }
}];

A: This is a facebook SDK bug check here is the submitted bug And as par facebook developer team that will be fix in next update:


text:
Q: How to fix drag area of bootstrap model I using Bootstrap v3.3.4 version, I want to prevent model move out of window.
I try with below code for fix drag area for dialog but it not working.
$("[role=dialog]").draggable({
            handle: ".modal-header",
            containment: "window"
        });

A: I spent 2-3 days on googling and other source and finally found solution
for prevent drag area in browser window only. just need to set containment property window.
Solution is as below:
$("[role=dialog]").draggable({
        containment: "window"
    })

A: Bootstrap doesn't have draggable(), you need to add JqueryUi for that.

$(function() {
  $("#draggable").draggable();
});
<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Draggable - Default functionality</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

Panel Heading

Drag me around


text:
Q: Creating multiple objects using for loop What I want is to create multiple view in for loop
example
for(int i =1; i<5; i++){
GridView view = new Gridview(this);
}

But It creates 5 gridview with the same name.. so in future i can't set different option to a specific gridview. How do I get, that gridivew created in a loop get view + i name

A: Use a List
List<GridView> views = new ArrayList<GridView>();
for(int i = 1; i < 5; i++) {
    views.add(new GridView(this));
}

Then you can get your views with
views.get(i);

A: Also, in your example, when a step of the for loop ends, the reference to that object is lost as the scope in which they were created is left. With no reference to the objects, the Garbage Collector comes in and frees that memory, deleting the objects.
So, you won't be able to access not even the last object created. If you modify the code like this, at the end of this code you will have only the last object instantiated:
GridView view;
for(int i =1; i<5; i++){
    view = new Gridview(this);
}

Now the object exists in the scope you are in at the end of the code snippet. But only one object really exists.
So, the solution is to store the objects in some additional structure: an array if you know precisely how many objects you want, or some self dynamically allocated collection structure. And you have examples of both in the other answers.

Added: What you are actually asking for (to dynamically build the object's reference name) is called metaprogramming. I don't know if it is possible in Java, but here is an example of this done in PHP:
class Object {
    function hello(){
        echo "Hello \n";
    }
}

for($i =1; $i<5; $i++){
    $name = "view".$i;
    $$name = new Object();
}

$view1->hello();
$view2->hello();
$view4->hello();

Here is runnable code: http://codepad.org/bFqJggG0

A: Use a List of GridViews.
List<GridView> grids = new ArrayList<GridView>();
for(int i =1; i<5; i++){
    grids.add(new Gridview(this));
}

A: I think this code will create 5 GridViews, 4 of which will become immediately available for Garbage Collection as your code no longer has a reference to them.
If you create them in a loop, then I think I'd be looking to store them in a data structure such as a List or Map and then accessing them via an index or key.

A: i think you can do something like this :
for(int i =1; i<5; i++){
GridView view = new Gridview(this);
view.setId(i);
}

and then , you can difference between all views

A: GridView[] view=new GridView[5];
for(int i=1;i<5;i++){
view[i]=new GridView(this);}

Now I think you can set specified options.


text:
Q: Using Returned SQL Array with Random Result Picker I am writing a new feature plugin for a website I develop and am stuck with how to go about implementing such feature. I'm trying to return an SQL query to an array that I can then pass to a function in either PHP or JavaScript, to perform a random option picker, and display the results to the user. I'm trying to perform the random picker by an on-click functionality.
So far, I have figured out how to successfully select my SQL query, return statements, and in JavaScript, work with a random option picker. However, I have not been able to find a good way to combine all these things together to produce my result.
I was wondering if anyone knew of a way to do this. Is it better to perform the entire program functionality in PHP or better to pass it to a JavaScript function and return results through the JS code?
Here are some examples of my code. Please assume that my query works. I do not need the display option in my code. It is implemented to check query results. I was hoping to hide the array in the real plugin from users and use the returned results for the on-click functionality attached to an HTML element.
<?php
    function choices() {
        $config = parse_ini_file(*database file*);
        $con = mysqli_connect(*database information*);
        if(!$con){
            exit("Please try again later.");
        }

        $query = "SELECT * FROM *query*";
        $result = @mysqli_query($con, $query);
        $num = mysqli_num_rows($result);
        if ($num > 0) {

            echo "
There are currently $num restaurants.
\n";

            echo '

                Restaurant Title:
                Link:

        ';

            while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
                echo '
' . $row['post_title'] . '	' . $row['guid'] . '

                ';
            }

            echo '

';

            mysqli_free_result($result);
        }

        else {
            echo '
The results could not be retrieved.
';
        }

        mysqli_close($con);
    }

    $foo = choices();
?>

My JS code.
var favorites = ["choice #1, choice #2, choice #3, choice #4"];
var favorite = favorites[Math.floor(Math.random() * favorites.length)];

Thank you very much for any input regarding this question! I understand this is a rather lengthy question and I do appreciate time took to help me understand it.

A: Why not just have your database return a single random result since that's all you need?
SELECT * FROM tbl ORDER BY RAND() LIMIT 1

Take a look at this post about getting random rows

A: Put the results of the query in a PHP array. Then use json_encode() to convert that to a Javascript array. Then the onclick functionality can display a random element of the array.
$array = array();
while ($row = mysqli_fetch_assoc($result)) {
    $array[] = $row['post_title'];
}
?>


text:
Q: What is wrong with this PHP code? I have two database tables, one for allowances and one for deductions. I want to calculate net salaries.
I'm using CodeIgniter. Here's my current code:
function get_allowances($eid)
{
    $this->db->from('allowances');
    $this->db->where('eid',$eid);
    $query = $this->db->get();

    if($query->num_rows()==1)
    {
        return $query->row();
    }
    else
    {
        //Get empty base parent object, as $item_id is NOT an item
        $salary_obj=new stdClass();

        //Get all the fields from items table
        $fields = $this->db->list_fields('allowances');

        foreach ($fields as $field)
        {
            $salary_obj->$field='';
        }

        return $salary_obj;
    }
}

function get_deductions($eid)
{
    $this->db->from('deductions');
    $this->db->where('eid',$eid);
    $query = $this->db->get();

    if($query->num_rows()==1)
    {
        return $query->row();
    }
    else
    {
        //Get empty base parent object, as $item_id is NOT an item
        $salary_obj=new stdClass();

        //Get all the fields from items table
        $fields = $this->db->list_fields('deductions');

        foreach ($fields as $field)
        {
            $salary_obj->$field='';
        }

        return $salary_obj;
    }
}

and in controller,
function net_salary($eid)
{
    $allownces[] = $this->Salary->get_allowances($eid);
    $deductions[] = $this->Salary->get_deductions($eid);

    return $net_salary = array_sum($allownces) - array_sum($deductions);
}

My net_salary() function gives me a result of 0. What am I doing wrong, and how can I fix it?

A: Your models with plural names are only going to return a single object.
so what you are ending up with is...
Array
(
    [0] => allowance_object
)

and
Array
(
    [0] => deduction_object
)

While we really need the schema of your database try this (and make same edits for deductions)...
function get_allowances($eid)
{
    $this->db->from('allowances');
    $this->db->where('eid',$eid);
    $query = $this->db->get();

    if($query->num_rows()==1)
    {
        return $query->row_array();  //<--- return an Array
    }
    else
    {
        // make an array instead of object
        $salary_obj = array();

        //Get all the fields from items table
        $fields = $this->db->list_fields('allowances');

        foreach ($fields as $field)
        {
            $salary_array[$field] = 0;   //<---- add array keys and set to integer 0 instead of empty string.
        }

        return $salary_array;
    }
}

then in your net_salary function
function net_salary($eid)
{
    $allownce = $this->Salary->get_allowances($eid);
    $deduction = $this->Salary->get_deductions($eid);

    return array_sum($allownce) - array_sum($deduction);
}

A: Try something like this:
function get_values($eid, $table_name)
{
    $this->db->where('eid',$eid);
    $query = $this->db->get($table_name);

    $salary_obj = $query->result();

    $values = array();
    foreach($salary_obj as $row){
        $values[] = $row->value_column_name;
    }

    return $values;
}

where value_column_name is the name of the table column (filedname) where the desired value stands.
call in controller:
function net_salary($eid)
{
    $allownces = $this->Salary->get_values($eid, 'allowances');
    $deductions = $this->Salary->get_values($eid, 'deductions');

    return $net_salary = array_sum($allownces) - array_sum($deductions);
}


text:
Q: django-registration custom fields on form I have successfully managed to extend basic django-registration form, with custom fields on the form and it works fine.What is bugging me now is, the way it works.I have defined new Backend with register method that extends DefaultBackend
class MyBackend(DefaultBackend):
   def register(self, request, **kwargs):

created UserProfile model that holds User object as a Foreign Key
class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    custom_filed = models.CharField(max_length=200, blank=True)

and defined form
class UserRegistrationForm(RegistrationForm):
    custom_field = forms.CharField(widget=forms.TextInput(attrs=attrs_dict))

    model = UserProfile

that was supplied in urls
url(r'^accounts/register/$',  register, {'backend': 'app.regbackend.MyBackend','form_class':UserRegistrationForm},name='registration_register')

and it works fine, custom_field get saved the way I defined it in register method.What bothers me is that register form(template) only shows fields defined in RegistrationForm(username,email,password)model, and I have to add my custom_field manualy into the form class.I don't understand why is that, because model attribute points to UserProfile, and if I  remove custom_field from form class it won't be shown.Why is that?