text:
Q: Custom URLConnectionDataDelegate I'm stuck whilst trying to create a custom URLConnectionDataDelegate for my NSURLConnection requests. The problem is that I can create a class that implements the delegate protocol and make a request doing:
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:myDelegate];

But then in the delegate functions, like (void)connectionDidFinishLoading:(NSURLConnection *)connection, I have to modify some UI elements and I don't know how to do that.

A: If you have a dedicated class (not a UIViewController class) that implements the NSURLConnectionDelegate protocol, you should not modify the UI elements in your connectionDidFinishLoading: method. This method is for "internal" use of your "connection" class.
What you need is a way to obtain the eventual result of the request from your "connection" object. That is, the response data or - possibly - an error.
One way to achieve this is to provide a property in your "connection" class that takes a completion block and this block will be called by your class when the connection finished.
typedef void (^completion_block_t)(id result);
@property (nonatomic, copy) completion_block_t completionHandler;
Then, whenever your connection finished (for whatever reason) you call the block with the result which is either the response data (possibly a NSMutableData which contains the accumulated data chunks) or an NSError object which you got from the connection or created yourself - for example when you didn't get the correct Content-Type or when the connection actually finished but the status code doesn't mean a successful request in your apps logic.
An example how you would use it in your View Controller:
// somewhere in your UIViewController:
MyConnection* con = [[MyConnection alloc] initWithRequest:request];
__weak MyViewController* weakSelf = self;  // idiom to avoid circular references
con.completionHandler = ^(id result){
    if (![result isKindOfClass:[NSError error]]) {
        // do something with the response data:
        NSString* string = [[NSString alloc] initWithData:result
                                                 encoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
             // UIKit methods:
            weakSelf.myLabel.text = string;
        });
    }
    else {
        // Error
    }
};

// Start the connection:
[con start];

A: You can either make your view controller the delegate and modify UI element in the callbacks, or have the custom delegate object message the view controller when updates happened. The latter can be done using KVO/binding, notifications, delegation, blocks or another way.


text:
Q: Mongodb sharding: Chunk split failed with Hashed Shard Key I am trying to split few jumbo chunks in mongodb sharded cluster sharded using hashed shard key: {group_id:"hashed"}.
I used the following command from mongodb docs to split these jumbo chunks:
db.runCommand( { split: "test.people",
                  bounds : [ { group_id: NumberLong("-5838464104018346494") },
                             { group_id: NumberLong("-5557153028469814163") }
             ] } )

But getting following error:
{ "cause" : { }, "ok" : 0, "errmsg" : "split failed" }.

What is the possible cause of this failure? The shard key group_id has cardinality 26231 against total 4521157 documents.
Have checked this disussion but unable to find the cause.
P.S : The group_id is ObjectId.

A: Your cardinality is way too small. One chunk will split automatically when he reaches 64mb.
Currently, with a cardinality of 26231, your collection can't be bigger than 26231*64mb maximum without jumbo chunks... And you will probably have problems a long time before that unless you have a perfect distribution.
In your case, you don't have any value of group_id resulting in a hashed value between NumberLong("-5838464104018346494") and NumberLong("-5557153028469814163")...
So you can't split it because your cardinality is too small.
To sum up, you need a better shard key immediately which means mongodump everything and then mongorestore with the new shard key.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Running multiple sites Nginx on Ubuntu 18.04 I'm beginner with Nginx (also using PHP 7.2) and I have no idea how to access multiple sites using separated folders.
So as default folder I set /home/user/php;.
There I have few folders named: site1, site2, site3 etc.
Using terminal I start the server on my default folder with command php -S localhost:8000.
And here's the problem, when I type in browser localhost:8000/site1/ it shows what's in the index.php file, but messes with other files in that location. For example pictures. I have folder with png files located in /php/site1/images/. But they don't show up on the page in browser, because, according to terminal log, it's searching those png files in /php/images/ (which not exists) and not in /php/site1/images/. Everything is searched in default server folder, not in subfolders with sites. How to change config file or what to do to make it read separate folders??
Here's my Nginx configuration (/etc/nginx/sites/available/default):
https://pastebin.com/pZHgPkCZ

A: The steps would be (assumptions:- Nginx installed):

*

*Create server blocks for both or all your sites in the /var/www/folder:
sudo mkdir -p /var/www/mytest1.com/public_html
sudo mkdir -p /var/www/mytest2.com/public_html

*Modify permissions to allow regular users read and write access:
sudo chown -R $(whoami):$(whoami) /var/www/mytest1.com/public_html
sudo chown -R $(whoami):$(whoami) /var/www/mytest2.com/public_html

*Set permissions so pages can be served correctly:
sudo chmod -R 755 /var/www

*Create two pages for the test sites:
sudo echo "Welcome to mytest1.com!" > /var/www/mytest1.com/public_html/index.html
sudo echo "Welcome to mytest2.com!" > /var/www/mytest2.com/public_html/index.html

*Create Server Blocks:

*

*Copy over the default nginx homepage default file:
sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/mytest1.com

*Edit the copied file:
sudo nano /etc/nginx/sites-available/mytest1.com

*

*Scroll down and change this root /var/www/html; to root /var/www/mytest1.com/public_html;

*Change this server_name _; to server_name mytest1.com www.mytest1.com;

*Change this index index.html index.htm index.nginx-debian.html; to this index index.php index.html index.htm index.nginx-debian.html;

*Make value for fastcgi_pass socket path is correct:

*

*Run: ls /var/run/php/

*

*Results:
php7.2-fpm.pid php7.2-fpm.sock

*Add the php7.2-fpm.socket location in the server block file if note pointing in the right direction and see that the location  portion of the file looks like so, remove the # to achieve this in some areas:
...
    location ~ \.php$ {
                           include snippets/fastcgi-php.conf;
          #
          #                 # With php-fpm (or other unix sockets):
                            fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
          #                 # With php-cgi (or other tcp sockets):
          #                 fastcgi_pass 127.0.0.1:9000;
           }
 ...

*Close the editor and test nginx configuration with sudo nginx -t. See any errors repeats the steps backwards. For a valid syntax you will see:
 nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
 nginx: configuration file /etc/nginx/nginx.conf test is successful

*Repeat step 5 and 6 for the other site using mytest2.com where we had mytest1.com for site one, additionally for second site do the follow when editing the /etc/nginx/sites-available/mytest2.com file change this:
listen 80 default_server;
listen [::]:80 default_server;

to this:
listen 80;
listen [::]:80;

*

*Reason:

Only one server block can have the default_server specification. This tells Nginx which block to revert to if the server_name requested does not match any of the available server blocks.

*Create Symbolic links:
sudo ln -s /etc/nginx/sites-available/mytest1.com /etc/nginx/sites-enabled/
sudo ln -s /etc/nginx/sites-available/mytest2.com /etc/nginx/sites-enabled/

*Remove the Symbolic link for default server block:
sudo rm /etc/nginx/sites-enabled/default

*Restart Nginx:
sudo service nginx restart

11: Optional: Edit Hosts file:
 127.0.0.1 mytest1.com
 127.0.0.1 mytest2.com

Now go to your browser and type localhost, or mysite1.com if you made entries in the /etc/hosts file. Now also note that nginx listens on port 80 not 8080. Not the php server.
Resource:
https://devanswers.co/installing-nginx-ubuntu-18-04-multiple-domains/
https://devanswers.co/installing-php-nginx-ubuntu-18-04/


text:
Q: How I can multiply my each row of matrix separetly by matrix? Can't solve it without for, but I think it's not a good idea.
I want to implement ellipse throw multipling row of points(size 2xN), where each column is pair of (x,y), by matrix (size 2x2, because is 2d) and afterthat multiply by column (size Nx2), where each row is same pair of (x,y) like in a first 2xN-row.
Finally, I expect have Nx2 or 2xN vector, which will contain set of points.


text:
Q: Dotted lines using Chart.js Is it possible to draw dotted lines using Chart.js?
This is an example of what I want to do:

The current options I'm using is not letting me do what I aim to do:
var lineChartData = {
    "datasets": {
        "label": "defi score",
        "data": dataset[i],
        "pointStrokeColor": "#fff",
        "fillColor": "rgba(220,220,220,0.5)",
        "pointColor": "rgba(220,220,220,1)",
        "strokeColor": "rgba(220,220,220,1)",
        pointHighlightFill: "#19283F",
        pointHighlightStroke: "#28AFFA",
        bezierCurve: false
    },
    "labels": labels
};

var ctx = document.getElementById("chart_per_week").getContext("2d");
var myLine = new Chart(ctx).Line(lineChartData, {
    responsive: true,
    scaleFontColor: "#FF5972",
    bezierCurve: false
});

A: Dotted Line using Chart.js
You can extend the line chart type to do this

Preview

Script
Chart.types.Line.extend({
  name: "LineAlt",
  initialize: function (data) {
    var strokeColors = [];
    data.datasets.forEach(function (dataset, i) {
      if (dataset.dottedFromLabel) {
        strokeColors.push(dataset.strokeColor);
        dataset.strokeColor = "rgba(0,0,0,0)"
      }
    })

    Chart.types.Line.prototype.initialize.apply(this, arguments);

    var self = this;
    data.datasets.forEach(function (dataset, i) {
      if (dataset.dottedFromLabel) {
        self.datasets[i].dottedFromIndex = data.labels.indexOf(dataset.dottedFromLabel) + 1;
        self.datasets[i]._saved = {
          strokeColor: strokeColors.shift()
        }
      }
    })
  },
  draw: function () {
    Chart.types.Line.prototype.draw.apply(this, arguments);

    // from Chart.js library code
    var hasValue = function (item) {
      return item.value !== null;
    },
        nextPoint = function (point, collection, index) {
          return Chart.helpers.findNextWhere(collection, hasValue, index) || point;
        },
        previousPoint = function (point, collection, index) {
          return Chart.helpers.findPreviousWhere(collection, hasValue, index) || point;
        };

    var ctx = this.chart.ctx;
    var self = this;
    ctx.save();
    this.datasets.forEach(function (dataset) {
      if (dataset.dottedFromIndex) {
        ctx.lineWidth = self.options.datasetStrokeWidth;
        ctx.strokeStyle = dataset._saved.strokeColor;

        // adapted from Chart.js library code
        var pointsWithValues = Chart.helpers.where(dataset.points, hasValue);
        Chart.helpers.each(pointsWithValues, function (point, index) {
          if (index >= dataset.dottedFromIndex)
            ctx.setLineDash([3, 3]);
          else
            ctx.setLineDash([]);

          if (index === 0) {
            ctx.moveTo(point.x, point.y);
          }
          else {
            if (self.options.bezierCurve) {
              var previous = previousPoint(point, pointsWithValues, index);
              ctx.bezierCurveTo(
                previous.controlPoints.outer.x,
                previous.controlPoints.outer.y,
                point.controlPoints.inner.x,
                point.controlPoints.inner.y,
                point.x,
                point.y
              );
            }
            else {
              ctx.lineTo(point.x, point.y);
            }
          }

          ctx.stroke();
        }, this);
      }
    })
    ctx.restore();
  }
});

and then
var data = {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [
        {
            ...
            dottedFromLabel: "April"
        }
    ],
};

...
new Chart(ctx).LineAlt(data);

Fiddle - https://jsfiddle.net/3gxjfndm/3/

A: With chart.js V3 you can make use of segments to achieve this:

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      borderColor: 'orange',
      segment: {
        borderDash: ctx => ((ctx.chart.data.datasets[ctx.datasetIndex].data.length - 1) === ctx.p1DataIndex ? [2, 2] : undefined)
      }
    }]
  },
  options: {}
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>


text:
Q: Extract a JSON DATA table in html using VBA; converting Apps Script into VBA I want to retrieve a  table from the URL of https://s.cafef.vn/screener.aspx#data using VBA. This task is difficult because the table contains JSON data embedded in an html file, but it was so kind of Tanaike, an GAS expert who helped  me to create a custom function for Google Apps Scripts.
(IMPORTHTML() doesn't work in this webpage structure)
The function looks like:
function SAMPLE(url) {
   const res = UrlFetchApp.fetch(url, {muteHttpExceptions: true});
   const html = res.getContentText().match(/var jsonData \=([\S\s\w]+\}\])/);

   if (!html) return "No tables. Please confirm URL again.";

       const table = JSON.parse(html[1].replace(/\n/g, ""));

       const header = ["", "FullName", "Symbol", "CenterName", "ChangePrice", "VonHoa", "ChangeVolume", "EPS", "PE", "Beta", "Price"];

       return table.reduce((ar, e, i) => {

       const temp = header.map(f => f == "" ? i + 1 : e[f]);
       ar.push(temp);
       return ar;
   }, [header]);  }

This function works perfect in Google Sheets environment, but my goal now is to convert it into VBA, or in other words, writing a VBA module which can get the table at https://s.cafef.vn/screener.aspx#data.
Many thanks for any help or suggestions
Cao Doremi


text:
Q: ng-repeat showing functions names and data I'm a beginner with angularjs and mongolab ..
I have this code, to edit a record in mongolab :
function EditCtrl($scope, $location, $routeParams, Project) {
    var self = this;
    Project.get({id: $routeParams.projetId}, function(projet) {
        self.original = projet;
        $scope.projet = new Project(self.original);
    });

    $scope.save = function() {
        $scope.projet.update(function() {
            $location.path('/list');
        });
    };
}

It works perfectly.
I wanted to display all the keys and values from the record, this is the code :

{{key}}:{{val}}

And this is the result :
_id:{}
destroy:
name:Test test
rang:4
update:
In my record, i only have the _id, name and rang. I don't know why "destroy:" dans "update:" are displayed! probably because i use this code to connect to mongolab :
angular.module('mongolab', ['ngResource']).
        factory('Project', function($resource) {
    var Project = $resource('https://api.mongolab.com/api/1/databases' +
            '/_____/collections/_________/:id',
            {apiKey: '___________________'}, {
        update: {method: 'PUT'}
    }
    );

    Project.prototype.update = function(cb) {
        return Project.update({id: this._id.$oid},
        angular.extend({}, this, {_id: undefined}), cb);
    };

    Project.prototype.destroy = function(cb) {
        return Project.remove({id: this._id.$oid}, cb);
    };

    return Project;
});

What should i do to only display the record data ?
thanks

A: Return  a service and pass the item you receive from get() back to update and destroy.
factory('Project', function($resource) {
return {
     get: function() {
         return $resource('https://api.mongolab.com/api/1/databases' +
        '/_____/collections/_________/:id',
        {apiKey: '___________________'}, {
         update: {method: 'PUT'}
      },

update : function(itm, cb) {
    return item.update({id: item._id.$oid},
    angular.extend({}, item, {_id: undefined}), cb);
},

destroy : function(item, cb) {
    return item.remove({id: item._id.$oid}, cb);
};

Otherwise you can instantiate only one and reference it
factory('Project', function($resource) {
var item =$resource('https://api.mongolab.com/api/1/databases' +
        '/_____/collections/_________/:id',
        {apiKey: '___________________'}, {
         update: {method: 'PUT'}
return {

update : function(cb) {
    return item.update({id: item._id.$oid},
    angular.extend({}, item, {_id: undefined}), cb);
},

destroy : function(cb) {
    return item.remove({id: item._id.$oid}, cb);
};


text:
Q: flutter app is not running by flutter build ios but runs by xcode I wrote flutter application, I opened ios section by xcode and the application is running , but when I run application by vscode by flutter build ios  I got this error:
Automatically signing iOS for device deployment using specified development team in Xcode project: FHDGDHARTT
Running pod install...                                              4.1s
Running Xcode build...
Xcode build done.                                            4.1s
Failed to build iOS app
Error output from Xcode build:
↳
    2021-08-27 15:20:15.391 XCBBuildService[25359:181696] Failed to remove: /Users/alt/Library/Developer/Xcode/DerivedData/Runner-cwssrvwaltuodobbealdvrytptog/Build/Intermediates.noindex/XCBuildData/7c6f3b0142d0b109056c8c9053a39860-manifest.xcbuild: unlink(/Users/alt/Library/Developer/Xcode/DerivedData/Runner-cwssrvwaltuodobbealdvrytptog/Build/Intermediates.noindex/XCBuildData/7c6f3b0142d0b109056c8c9053a39860-manifest.xcbuild): No such file or directory (2)
    2021-08-27 15:20:15.617 XCBBuildService[25359:181696] Failed to remove: /Users/alt/Library/Developer/Xcode/DerivedData/Runner-cwssrvwaltuodobbealdvrytptog/Build/Intermediates.noindex/XCBuildData/7c6f3b0142d0b109056c8c9053a39860-desc.xcbuild: unlink(/Users/alt/Library/Developer/Xcode/DerivedData/Runner-cwssrvwaltuodobbealdvrytptog/Build/Intermediates.noindex/XCBuildData/7c6f3b0142d0b109056c8c9053a39860-desc.xcbuild): No such file or directory (2)
    ** BUILD FAILED **

Xcode's output:
↳
    note: Using new build system
    note: Building targets in parallel
    note: Planning build
    note: Analyzing workspace
    note: Constructing build description
    note: Build preparation complete
    /Users/alt/Mobile/Projects/shave-machine-app/ios/Pods/Pods.xcodeproj: warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 14.5.99. (in target 'FMDB' from project 'Pods')
    error: No profiles for 'com.shavemachine.shaveMachineApp' were found: Xcode couldn't find any iOS App Development provisioning profiles matching 'com.shavemachine.shaveMachineApp'. Automatic signing is disabled and unable to generate a profile. To enable automatic signing, pass -allowProvisioningUpdates to xcodebuild. (in target 'Runner' from project 'Runner')
    /Users/alt/Mobile/Projects/shave-machine-app/ios/Pods/Pods.xcodeproj: warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 14.5.99. (in target 'Reachability' from project 'Pods')
    /Users/alt/Mobile/Projects/shave-machine-app/ios/Pods/Pods.xcodeproj: warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 14.5.99. (in target 'Flutter' from project 'Pods')
    /Users/alt/Mobile/Projects/shave-machine-app/ios/Pods/Pods.xcodeproj: warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 14.5.99. (in target 'TOCropViewController-TOCropViewControllerBundle' from project 'Pods')
    /Users/alt/Mobile/Projects/shave-machine-app/ios/Pods/Pods.xcodeproj: warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 14.5.99. (in target 'TOCropViewController' from project 'Pods')
    /Users/alt/Mobile/Projects/shave-machine-app/ios/Pods/Pods.xcodeproj: warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 14.5.99. (in target 'Toast' from project 'Pods')

Encountered error while building for device.
alt@alts-MacBook-Pro shave-machine-app % ff clean
Cleaning Xcode workspace...                                      2,742ms
Deleting build...                                                   50ms
Deleting .dart_tool...                                               2ms
Deleting .packages...                                                0ms
Deleting Generated.xcconfig...                                       0ms
Deleting flutter_export_environment.sh...                            0ms
Deleting Flutter.podspec...                                          0ms
Deleting .flutter-plugins-dependencies...                            0ms
Deleting .flutter-plugins...                                         0ms
alt@alts-MacBook-Pro shave-machine-app % ff pub get
Running "flutter pub get" in shave-machine-app...                 1,147ms
alt@alts-MacBook-Pro shave-machine-app % ff build ios
Building com.shavemachine.shaveMachineApp for device (ios-release)...
Automatically signing iOS for device deployment using specified development team in Xcode project: FHDGDHARTT
Running pod install...                                              5.5s
Running Xcode build...
Xcode build done.                                            4.4s
Failed to build iOS app
Error output from Xcode build:
↳
    ** BUILD FAILED **

Xcode's output:
↳
    note: Using new build system
    note: Building targets in parallel
    note: Planning build
    note: Analyzing workspace
    note: Constructing build description
    note: Build preparation complete
    /Users/alt/Mobile/Projects/shave-machine-app/ios/Pods/Pods.xcodeproj: warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 14.5.99. (in target 'FMDB' from project 'Pods')
    /Users/alt/Mobile/Projects/shave-machine-app/ios/Pods/Pods.xcodeproj: warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 14.5.99. (in target 'TOCropViewController' from project 'Pods')
    error: No profiles for 'com.shavemachine.shaveMachineApp' were found: Xcode couldn't find any iOS App Development provisioning profiles matching 'com.shavemachine.shaveMachineApp'. Automatic signing is disabled and unable to generate a profile. To enable automatic signing, pass -allowProvisioningUpdates to xcodebuild. (in target 'Runner' from project 'Runner')
    /Users/alt/Mobile/Projects/shave-machine-app/ios/Pods/Pods.xcodeproj: warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 14.5.99. (in target 'Reachability' from project 'Pods')
    /Users/alt/Mobile/Projects/shave-machine-app/ios/Pods/Pods.xcodeproj: warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 14.5.99. (in target 'Flutter' from project 'Pods')
    /Users/alt/Mobile/Projects/shave-machine-app/ios/Pods/Pods.xcodeproj: warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 14.5.99. (in target 'TOCropViewController-TOCropViewControllerBundle' from project 'Pods')
    /Users/alt/Mobile/Projects/shave-machine-app/ios/Pods/Pods.xcodeproj: warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 14.5.99. (in target 'Toast' from project 'Pods')

Encountered error while building for device.

.this is doctor :
✓] Flutter (Channel stable, 2.2.3, on macOS 11.5.2 20G95 darwin-x64, locale en-US)
    • Flutter version 2.2.3 at /Users/alt/fvm/versions/stable
    • Framework revision f4abaa0735 (8 weeks ago), 2021-07-01 12:46:11 -0700
    • Engine revision 241c87ad80
    • Dart version 2.13.4

[✓] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
    • Android SDK at /Users/alt/Mobile/Sdk/Andriod/
    • Platform android-31, build-tools 31.0.0
    • ANDROID_HOME = /Users/alt/Mobile/Sdk/Andriod
    • Java binary at: /Library/Java/JavaVirtualMachines/jdk1.8.0_301.jdk/Contents/Home/bin/java
    • Java version Java(TM) SE Runtime Environment (build 1.8.0_301-b09)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 12.5.1, Build version 12E507
    • CocoaPods version 1.11.0.rc.1

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[!] Android Studio (version 2020.3)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    ✗ Unable to find bundled Java version.
    • Try updating or re-installing Android Studio.

[✓] VS Code (version 1.59.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.25.0

[✓] Connected device (2 available)
    • iPod touch (7th generation) (mobile) • 9318977C-48B1-4E5E-A483-460F582C9794 • ios            • com.apple.CoreSimulator.SimRuntime.iOS-14-5 (simulator)
    • Chrome (web)                         • chrome                               • web-javascript • Google Chrome 92.0.4515.159

! Doctor found issues in 1 category.

A: First step:

second step:

flutter clean

Then,

pod install

after that

flutter build ios

hope this will resolve your issue, Happy fluttering :)


text:
Q: Can't get NextGen gallery in translated post I'm creating a custom WordPress theme. So far, it was only in one language, and getting galleries in the code was working fine. That's the code I've been using:
// Sometimes this
echo nggShowGallery( $id );

// Sometimes this, as well
echo do_shortcode("[nggallery id='{$id}']");

Now, when creating a second language, using Polylang, this code will only get the gallery for the original page or any other page in the former language, but it won't work for any page in any other language. Also, the page stays absolutely blank even though I've set WP_DEBUG to true.
Googling this issue I've found that there seems to be a lot of trouble using NextGen in multilingual sites.
Any clue?

A: Well, I finally managed the site to work by making a new WordPress install and using WPML as the plugin for translations. Everything's working fine now. So I guess there was some kind of incompatibility between Polylang and NextGen. Not even installing WPML on the first site solved the issue; I had to begin from scratch.
In case this is useful to someone, I was using NextGen 2.0.65 with Polylang 1.3.1. This didn't work.
Now I'm using NextGen 2.0.66 and WPML 3.1.5. Works fine.


text:
Q: Error: Unsupported argument terraform ecs with load balancer appreciate your support in solving this issue i have main.tf file like below
resource "aws_ecs_service" "nodejs-service" {
  name            = "nodejs-service"
  cluster         = aws_ecs_cluster.project_cluster.id
  task_definition = aws_ecs_task_definition.nodejs.arn
  launch_type     = "FARGATE"
  desired_count   = 1

  load_balancer {
    target_group_arns = module.alb.target_group_arns
    container_name   = "${aws_ecs_task_definition.nodejs.family}"
    container_port   = 8080 # Specifying the container port
  }

  network_configuration {
    subnets          = var.vpc.public_subnets
    assign_public_ip = true
  }
}

module "alb" {
  source             = "terraform-aws-modules/alb/aws"
  version            = "~> 8.0"
  name               = var.namespace
  load_balancer_type = "application"
  vpc_id             = var.vpc.vpc_id
  subnets            = var.vpc.public_subnets
  security_groups    = [var.sg.lb]

  http_tcp_listeners = [
    {
      port               = 80
      protocol           = "HTTP"
      target_group_index = 0
    }
  ]

  target_groups = [
    { name_prefix      = "nodejs-service"
      backend_protocol = "HTTP"
      backend_port     = 8080
      target_type      = "instance"
    }
  ]
}

i receive error
│ Error: Unsupported argument
│
│   on modules/ecs/main.tf line 58, in resource "aws_ecs_service" "nodejs-service":
│   58:     target_group_arns = module.alb.target_group_arns
│
│ An argument named "target_group_arns" is not expected here. Did you mean "target_group_arn"?

even if i changed target_groups on the service parameters to be target_group_arn i receive error "target_group_arn" is not defined
also with module.alb.target_groups[0] the same error appear with terraform plan
  load_balancer {
    target_group_arn   = module.alb.target_groups[0]
    container_name   = "${aws_ecs_task_definition.nodejs.family}"
    container_port   = 8080 # Specifying the container port
  }

Error:
│ Error: Unsupported attribute
│
│   on modules/ecs/main.tf line 58, in resource "aws_ecs_service" "nodejs-service":
   58:     target_group_arn   = module.alb.target_groups[0]
     ├────────────────
     │ module.alb is a object

 This object does not have an attribute named "target_groups".

as per main.tf file how can i select the target group which is defined in alb module
Thanks,
tried: terraform plan and expected alb with target group pointing on nodejs-service container
terraform {
  required_version = ">= 1.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = ">= 4.27"
    }
    null = {
      source  = "hashicorp/null"
      version = ">= 2.0"
    }
  }
}

A: output from the module alb is an array.
In your case it would be module.alb.target_group_arns[0]
Replace it with this code
load_balancer {
    target_group_arns = module.alb.target_group_arns[0]
    container_name   = "${aws_ecs_task_definition.nodejs.family}"
    container_port   = 8080 # Specifying the container port
  }

A: The issue is not in the module, rather in the argument you are trying to use in the aws_ecs_service resource. You are currently setting it to target_group_arns while the argument is singular, i.e., target_group_arn [1]:
  load_balancer {
    target_group_arn = module.alb.target_group_arns[0]
    container_name   = "${aws_ecs_task_definition.nodejs.family}"
    container_port   = 8080 # Specifying the container port
  }

The example is with the first of the target groups returned from the module, so make sure you are using the correct one.

[1] https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ecs_service#target_group_arn


text:
Q: trying to learn nested structs concept, I have written a short program for understanding but I am running into errors as mentioned below //Program to understand Nested structs in C
#include <stdio.h>

typedef union test {
    float tet;
    struct {
        int bite;
    } p;
} U_test;

//union test U_test;
struct U_test.p = {.bite=150};

int main()
{
    printf("%d\n", U_test.p.bite);
    U_test.tet = 0.0;
    printf("%d", U_test.p.bite);

    return 0;
}

Here is the error code I keep seeing below. Not sure I am doing something wrong here or am I typing something wrong?Please advise. Thanks in advance.
error: expected identifier or '(' before '.' token
    struct U_test.p = {.bite=150};

A: struct U_test.p = {.bite=150};

That is not the correct syntax to create a variable of the defined union type. It should be:
U_test u_test = { .p.bite = 150 };

After making that change all the references in main which are currently U_test need to be changed to u_test.
Here is the full program corrected:
#include <stdio.h>

typedef union test{

    float tet;
    struct{
        int bite;
    }p;
}U_test;

//union test U_test;
U_test u_test = { .p.bite=150 };

int main()
{
    printf("%d\n", u_test.p.bite);
    u_test.tet = 0.0;
    printf("%d", u_test.p.bite);

    return 0;
}


text:
Q: Retrieve 1st item ID for Active Accordion tab in jQuery I have an accordion with some list items inside (code below). Is there any way to find out the 1st item data-id of the active accordion tab. For example., on page load, the active tab is Temperature Gauge which is the 2nd tab. Now I want to retrieve the 1st option data-id which is 11.

Pressure Gauge

                Pressure Gauge

                Diff. Pressure Gauge

                Diaphragm Seal

Temperature Gauge

                Temperature Gauge

                Thermowell

Switch

                Pressure Switch

                Temperature Switch

A: To get active tab:
var active = $( ".selector" ).accordion( "option", "active" ); //get active tab

To get first li data ID:
$(active).find('.SubCatFakeClass:eq(0)').data('id');

or
$(active).find('li:eq(0)').data('id');

A: You could use the :eq selector to get the nth div:
var intID = $(this).children("div:eq(" + activeTab + ")")
                   .find('.SubCatFakeClass')
                   .attr("data-id");

You could use .find('.SubCatFakeClass:first-child'), but .attr will return the result of the first one regardless.
Fiddle Here


text:
Q: django bulk remove and add many to many relationships Im having a problem with bulk many to many relationship removing and adding.
This is the JS that sends the pk of the user to be updated and the pk of the skills that will be added to the many to many.
function attachskillls(){

var checkedValues = $('input:checkbox:checked').map(function() {
  return this.value;
}).get();

console.log(checkedValues)

data = {
  'skills' : checkedValues,
  'pk' : getUrlVars()["id"]
}
console.log(data)

$.ajax({
  type: "POST",
  url: "/api/skill/attch/",
  data: JSON.stringify(data),
  contentType: "application/json",
  dataType: "json"
})

data is packed like this
{"skills":["1","2","3"],"pk":"1"}

This is the model the skills will be related to
class Resource(models.Model):

    title = models.CharField(max_length=10)
    preferred_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=30)
    employstatus = models.CharField(max_length=20)
    employer = models.ForeignKey('Employer')
    role = models.ForeignKey('Role')
    location = models.ForeignKey('Location')
    workphone = models.CharField(max_length=25, blank=True, null=True)
    mobile_phone = models.CharField(max_length=15, blank=True, null=True)
    email = models.CharField(max_length=15, blank=True, null=True)
    notes = models.CharField(max_length=200, blank=True, null=True)
    updated_by = models.CharField(max_length=30, blank=True, null=True)
    skillset = models.ManyToManyField('ReferenceSkillList')

This is my api so far I am trying to filter resource by pk so I have the correct user to add the skills to then to clear all relationships that may already be added then to bulk add the new relationships.
def Skillattachment(request):
    body = json.loads(request.body)
    if request.method == "POST":
        pk = body['pk']
        skills = body
        res = Resource.objects.filter(pk=pk)
        res.skillset.clear()
        res.skillset.add(skills)

    else:
        search_id = ''

    return HttpResponse(json.dumps(body), content_type='application/json')

Is there  a better way to do what I am trying todo?
I I currently get the error
'QuerySet' object has no attribute 'skillset'
though I am unsure why? maybe I have made the M2M incorrectly but I have followed the docs

A: You should use res = Resource.objects.get(pk=pk) instead. filter would give you a queryset as result.
Also your variable skills is just a data structure not objects. You might need:
skills = ReferenceSkillList.objects.filter(id__in=body['skills'])
res = Resource.objects.get(pk=pk)
res.skillset.clear()
res.skillset.add(*skills)

Django docs.


text:
Q: how to Place an AdMob ad at the bottom of the screen iam trying to place admob add at bnottom of my application ...for that i wrote the following code ....am getting entire application except adds...can u please help me
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
android:orientation="vertical"
android:id="@+id/LinearLayout01"
xmlns:android="http://schemas.android.com/apk/res/android"
android:background="@drawable/wp"
android:gravity="right"
android:layout_width="wrap_content"
android:layout_height="match_parent">
        <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:background="@color/black"
        android:orientation="horizontal"
        android:layout_height="wrap_content">

            <ImageView
            android:layout_width="wrap_content"
            android:src="@drawable/header"
            android:id="@+id/ImageView01"
            android:layout_height="wrap_content"></ImageView>
            <TextView
            android:layout_width="fill_parent"
            android:textColor="@color/white"
            android:text="Tip Calculator"
            android:typeface="sans"
            android:textSize="26sp"
            android:layout_height="fill_parent"
            android:gravity="center_vertical|center_horizontal"
            android:id="@+id/TextView07"></TextView>

        </LinearLayout>

<AbsoluteLayout

android:id="@+id/widget0"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

>

<TextView

android:id="@+id/widget28"

android:layout_width="wrap_content"

android:layout_height="17px"

android:text="Amount of Bill          $"

android:layout_x="40px"

android:layout_y="48px"

android:textColor="@color/white"

>

</TextView>

<TextView

android:id="@+id/widget29"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Percentage to Tip"

android:textColor="@color/white"

android:layout_x="40px"

android:layout_y="98px"

>

</TextView>

<TextView

android:id="@+id/widget30"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Number of People"

android:textColor="@color/white"

android:layout_x="40px"

android:layout_y="148px"

>

</TextView>

<TextView

android:id="@+id/widget31"

android:layout_width="wrap_content"

android:layout_height="18px"

android:text="Tip Amout                 $"

android:textColor="@color/white"

android:layout_x="40px"

android:layout_y="262px"

>

</TextView>

<TextView

android:id="@+id/widget32"

android:layout_width="wrap_content"

android:layout_height="18px"

android:text="Total Per Person       $"

android:textColor="@color/white"

android:layout_x="40px"

android:layout_y="302px"

>

</TextView>

<Button

android:id="@+id/btncalculate"

android:layout_width="87px"

android:layout_height="wrap_content"

android:text="Calculate"

android:textColor="@color/black"

android:layout_x="40px"

android:layout_y="198px"

>

</Button>

<Button

android:id="@+id/btnreset"

android:layout_width="86px"

android:layout_height="wrap_content"

android:text="Reset"

android:textColor="@color/black"

android:layout_x="140px"

android:layout_y="198px"

>

</Button>

<EditText

android:id="@+id/txtbillamount"

android:layout_width="99px"

android:layout_height="36px"

android:text=""

android:textSize="18sp"

android:layout_x="200px"

android:layout_y="38px"

>

</EditText>

<EditText

android:id="@+id/txtpercentage"

android:layout_width="51px"

android:layout_height="36px"

android:text=""

android:textSize="18sp"

android:layout_x="200px"

android:layout_y="88px"

>

</EditText>

<EditText

android:id="@+id/txtpeople"

android:layout_width="51px"

android:layout_height="36px"

android:text=""

android:textSize="18sp"

android:layout_x="200px"

android:layout_y="138px"

>

</EditText>

<TextView

android:id="@+id/txttipamount"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text=""

android:textColor="@color/white"

android:layout_x="200px"

android:layout_y="262px"

>

</TextView>

<TextView

android:id="@+id/txtperperson"

android:layout_width="wrap_content"

android:layout_height="99px"

android:text=""

android:textColor="@color/white"

android:layout_x="200px"

android:layout_y="302px"

>

</TextView>

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="%" android:textColor="@color/white"

android:id="@+id/percentageview"

android:layout_x="265dip"

 android:layout_y="92dip">

 </TextView>

</AbsoluteLayout>

<LinearLayout
    android:id="@+id/linearLayout"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
</LinearLayout>
</LinearLayout>

A: *

*use below on your remaining elements except admob.
layout_weight="1.0"
layout_height="0dp"

*use below on your admob wrapper layout
android:gravity="bottom"

For example,
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:background="#000000">
        <LinearLayout
            android:layout_width="fill_parent"
            android:orientation="vertical"
            android:layout_height="0dp"
            android:layout_weight="1.0">
           // here is remaining elements
        </LinearLayout>
        <LinearLayout
            android:layout_width="fill_parent"
            android:orientation="vertical"
            android:id="@+id/ad_layout"
            android:layout_height="wrap_content"
            android:gravity="bottom">
           // admob element here
        </LinearLayout>
    </LinearLayout>

and insert admob by code,
adView = new AdView(this, AdSize.SMART_BANNER, MY_AD_UNIT_ID);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
    ViewGroup.LayoutParams.MATCH_PARENT,
    ViewGroup.LayoutParams.WRAP_CONTENT);
adView.setLayoutParams(params);

LinearLayout layout = (LinearLayout)findViewById(R.id.ad_layout);
layout.addView(adView);
adView.loadAd(new AdRequest());

A: <RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true">
<Button android:id="@+id/btnGetMoreResults"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
 android:text="Get more"
android:layout_alignParentBottom="true" />
</RelativeLayout>

Use your AdMob Design Parameters in place of Button code here.

A: This blog post will certainly help you:
http://www.ahotbrew.com/how-to-put-admob-banner-on-the-bottom
The important part here are android:layout_alignParentBottom="true" for the AdView and android:layout_alignParentTop="true" for the LinearLayout afterwards.


text:
Q: Problema con las url de laravel (rutas) tengo varias rutas de la siguiente forma
Route::get('/{slug}','EventoController@mostrar')->name('verevento');
Route::get('/{slug}','ActividadController@mostrar')->name('veractividad');

en las vistas las llamó de la siguiente manera
 $evento['slugEvento']])}}">
 $evento['slugActividad']])}}">

el problema es que causan conflicto al ser iguales (/{slug})
hay alguna forma de arreglar eso? sin la necesidad de agregar (actividad/{slug}, evento/{slug})
trate agregando un parámetro para distinguirlas en un controlador diferente y dependiendo del tipo manda a llamar a la ruta que es pero sale el mismo error
existe alguna forma de hacer un return tipo
return view('eventoDetalle')->with(['act' => $act])->with(['img' => $img]);

junto con un redirect para así pasarle el slug cómo parámetro en una vista diferente?
o no se que otras opciones haya.

A: Me atrevo a escribir esta respuesta sin conocer el error registrado en el Log, pero, de ser necesario, eliminaré esta respuesta posteriormente.
Las dos rutas son «conflictivas», por así decirlo, puesto que en cierta forma es la misma ruta, pero en una el parámetro slug es opcional y en la otra es obligatorio, adicional a esto, están en el raíz de la URL, lo cual puede potencialmente traer algún otro problema.
Lo más probable, es que Laravel esté intentando usar una de las dos «siempre», esto dependiendo del orden de estas en el archivo de rutas (asumiendo que sea web.php), y al acceder a dicha ruta, no esté recibiendo alguna información en el Request que sea necesaria.

En pocas palabras, si la url es mipagina.com/nueva-publicacion, vemos que el patrón encaja en ambas rutas, por lo cual Laravel ingresará a la primera que esté listada en el archivo de rutas.

Para resolver este inconveniente, lo más sencillo sería reorganizar la estructura de las dos rutas, porque no veo coherente que sean iguales, Laravel no es «tan inteligente» como para determinar que dos rutas iguales van a controladores distintos.
Route::get('/{slug?}','actividadController@show')->name('veractividad');

Route::get('/evento/{slug}','EventoController@show')->name('vistaEvento');

En caso que definitivamente no puedas cambiar su estructura, tendríamos que evaluar otras opciones.


text:
Q: Looping through RadioButtonList I am creating a site that contains 3 surveys stored in one SQL table, so based on the selected SurveyID the page will then be populated by the Questions and an answer line, now I have achieved this but now I need to be able to retrieve the information.
Using a DataList, each question generates a line, and within the itemtemplate of my DataList (QuestionList) I have put the following:
<asp:DataList ID="QuestionList" runat="server" DataKeyField="QuestionID" DataSourceID="QuestionData">
    <ItemTemplate>

                <asp:Label ID="Higher_ReadingLabel" runat="server" Text='<%# Eval("Higher_Reading") %>' />

                <asp:Label ID="Lower_ReadingLabel" runat="server" Text='<%# Eval("Lower_Reading") %>' />

            <asp:RadioButtonList ID="AnswerList" runat="server" RepeatDirection="Horizontal" RepeatLayout="Table">
                <asp:ListItem Text="Excellent" Value="Excellent"></asp:ListItem>
                <asp:ListItem Text="Very Good" Value="Very Good"></asp:ListItem>
                <asp:ListItem Text="Good" Value="Good"></asp:ListItem>
                <asp:ListItem Text="Fair" Value="Fair"></asp:ListItem>
                <asp:ListItem Text="Bad" Value="Bad"></asp:ListItem>
            </asp:RadioButtonList>

    </ItemTemplate>
</asp:DataList>

When the submit button is clicked, I want to retrieve the following:

*

*DataKeyField of the QuestionList

*Value of Checked Radio Button within AnswerList

I admit I am pretty stumped atm, everything I have tried hasnt worked at all, as the SQL isnt wrote yet I just wanted to see if the output could just output using Response.Write(value,datakeyfield).
Hope you guys can help,
Neil

A: This may be helpfull for you:
foreach (DataListItem datalistItem in QuestionList.Items)
        {
            if (datalistItem.ItemType == ListItemType.Item || datalistItem.ItemType == ListItemType.AlternatingItem)
            {
                var radioButtonList = datalistItem.FindControl("AnswerList") as RadioButtonList;
                if (radioButtonList != null)
                {
                    var selectedRadioButtonValue = radioButtonList.SelectedValue;
                    var itemDataKeyValue = QuestionList.DataKeys[datalistItem.ItemIndex];
                    Response.Write(string.Format("QuestionID :{0}, selected option: {1}
", itemDataKeyValue, selectedRadioButtonValue));
                }
            }
        }


text:
Q: PyTorch DataLoader shuffle I did an experiment and I did not get the result I was expecting.
For the first part, I am using
trainloader = torch.utils.data.DataLoader(trainset, batch_size=128,
                                          shuffle=False, num_workers=0)

I save trainloader.dataset.targets to the variable a, and trainloader.dataset.data to the variable b before training my model. Then, I train the model using trainloader. After the training is finished, I save trainloader.dataset.targets to the variable c, and trainloader.dataset.data to the variable d. Finally, I check a == c and b == d and they both give True, which was expected because the shuffle parameter of the DataLoader is False.
For the second part, I am using
trainloader = torch.utils.data.DataLoader(trainset, batch_size=128,
                                          shuffle=True, num_workers=0)

I save trainloader.dataset.targets to the variable e, and trainloader.dataset.data to the variable f before training my model. Then, I train the model using trainloader. After the training is finished, I save trainloader.dataset.targets to the variable g, and trainloader.dataset.data to the variable h. I expect e == g and f == h to be both False since shuffle=True, but they give True again. What am I missing from the definition of DataLoader class?

A: I believe that the data that is stored directly in the trainloader.dataset.data or .target will not be shuffled, the data is only shuffled when the DataLoader is called as a generator or as iterator
You can check it by doing next(iter(trainloader)) a few times without shuffling and with shuffling and they should give different results
import torch
import torchvision

transform = torchvision.transforms.Compose([
        torchvision.transforms.ToTensor(),
        ])
MNIST_dataset = torchvision.datasets.MNIST('~/Desktop/intern/',download = True, train = False,
                                           transform = transform)
dataLoader = torch.utils.data.DataLoader(MNIST_dataset,
                                         batch_size = 128,
                                         shuffle = False,
                                         num_workers = 10)
target = dataLoader.dataset.targets

MNIST_dataset = torchvision.datasets.MNIST('~/Desktop/intern/',download = True, train = False,
                                           transform = transform)

dataLoader_shuffled= torch.utils.data.DataLoader(MNIST_dataset,
                                         batch_size = 128,
                                         shuffle = True,
                                         num_workers = 10)

target_shuffled = dataLoader_shuffled.dataset.targets

print(target == target_shuffled)

_, target = next(iter(dataLoader));
_, target_shuffled = next(iter(dataLoader_shuffled))

print(target == target_shuffled)

This will give :
tensor([True, True, True,  ..., True, True, True])
tensor([False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False,  True,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False,  True, False, False, False, False, False,
        False,  True, False, False, False, False, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False,  True,  True, False, False, False, False,
        False, False, False, False, False, False, False, False, False, False,
        False, False, False, False, False,  True, False, False,  True, False,
        False, False, False, False, False, False, False, False])

However the data and label stored in data and target is a fixed list and since you are trying to access it directly, they will not be shuffled.

A: I was facing a similar issue while loading the data using the Dataset class. I stopped loading the data using Dataset class, and instead use the following code which is working fine with me
X = torch.from_numpy(X)
y = torch.from_numpy(y)

train_data = torch.utils.data.TensorDataset(X, y)
train_loader = torch.utils.data.DataLoader(train_data, batch_size=32, shuffle=True)

where X & y are numpy array from csv file.


text:
Q: AccessDeniedException when changed a cljs file I am trying out the tutorials in
https://github.com/magomimmo/modern-cljs/blob/master/doc/second-edition/tutorial-02.md
I started it by using the command
boot serve -d target watch cljs target -d target

When I changed the cljs file, I see this exception

Writing main.cljs.edn...
  Compiling ClojureScript...
  ò main.js
  Writing target dir(s)...
  java.util.concurrent.ExecutionException: java.nio.file.AccessDeniedException: target\main.out\modern_cljs\core.js
      java.nio.file.AccessDeniedException: target\main.out\modern_cljs\core.js
      file: "target\main.out\modern_cljs\core.js"

my boot.properties contains:
#http://boot-clj.com
#Tue Jan 03 23:11:53 CST 2017
BOOT_CLOJURE_NAME=org.clojure/clojure
BOOT_CLOJURE_VERSION=1.8.0
BOOT_VERSION=2.5.5
BOOT_EMIT_TARGET=no
BOOT_HOME=D:/onemoretime/temp

the problem happens without the BOOT_HOME property too.


text:
Q: Execute a SQL query from C# console application and get its result written in a file I have written the below code to execute a set of SQL Server scripts placed in a directory.
The code is working fine but I want to get the script execution result written into a file (like writing the results in a log file). Please help.
static void Main(string[] args)
{
    string ConnectionString = ConfigurationManager.ConnectionStrings["UtilsDBConnection"].ConnectionString;
    string path = ConfigurationManager.AppSettings["folderPath"];

    DirectoryInfo d = new DirectoryInfo(path);

    FileInfo[] sqlfiles = d.GetFiles("*.sql");

    SqlCommand cm;

    using (SqlConnection cnn = new SqlConnection(ConnectionString))

    try
    {
        cnn.Open();

        // Console.WriteLine("Connection Open ! ");
        foreach (FileInfo file in sqlfiles)
        {
            string script = file.OpenText().ReadToEnd();

            using (cm = cnn.CreateCommand())
                cm.CommandText = script;

            cm.ExecuteNonQuery();
        }

        cnn.Close();
    }
    catch (Exception ex)
    {
       // Console.WriteLine("Can not open connection ! ", ex);
    }
}

A: ExecuteNonQuery is used for update,insert and delete, and returns a integer.
You can simply save it to a file using File.WriteAllText() method.
If your query are select, consider instead using ExecuteReader() method.
So iterate over the response and write a line for each row returned.


text:
Q: Curvilinear Coordinates to Solve Integrals I get the idea of curvilinear coordinates, but don't understand how it would make corresponding symmetrical integrals easier to solve.
How would you evaluate an integral, for simplicity's sake say
$$
\iint_{S}\textbf{r}\cdot d\textbf{S},
$$
where S is the surface of a sphere with radius R, centered at the origin using polar spherical coordinates?
Would you just convert everything into Cartesians? Wouldn't that just defeat the point of working with curvilinear coordinates?

A: Well,in this case,you certainly wouldn't. At least,you'd be crazy to do it given how simple the equation becomes in spherical coordinates! This is really a triple integral in $R^{3}$ unless the integral is taken over a level surface.
This is really a poor example-there are many cases where the transformation of coordinates yields a much simpler computation. Several very good examples can be found here. Pay particular attention to the example of the transformation of coordinates for the volume of an ice cream cone. Trying to do this one in Cartesian coordinates would reduce the most battle hardened computational student to tears. The geometry and expression of the final integral in spherical coordinates is amazingly simple. These kinds of transformations arise regularly not only in calculus, but geometry and physics. Indeed-Newton deduced the three laws of motion in classical mechanics from converting the complex equations for the point masses of the planets around the sun into polar coordinates!
That help?


text:
Q: Calculating Array Length from Array of Averages? I want to calculate The Array.Size() with only a small subset of information.
I am writing a program that analyses the results of unreadable code, which would tell the user the most probable Size of the array which is random length, and based on this Size, a calculation can be made about the probability of receiving an exact element in real-time.

There is an array which contains potentially 1-10000 elements, but the exact length of that array, or the total number of elements, Array.Size() is unknown each time.
Every few seconds there is a "roll", the roll() method picks and then displays 4 random elements from that array, for example:
re, to, ha, pi
I am now aware that at least these 4 elements exist within the array.
I decide to watch the element [ha]
The roll() method continues "rolling", which continues to select and then display 4 elements at random.
I count how many "rolls" it takes [ha] to appear again. And repeat/record that result 10 times.
12, 21, 48, 26, 12, 89, 32, 11, 42, 51
On average, it took 34.4 times for [ha] to appear again.
Then I select a new element [pi]
The roll() method continues "rolling", which continues to select and then display 4 elements at random.
I count how many "rolls" it takes [pi] to appear again. And record the results 10 times.
2, 6, 75, 53, 23, 12, 22, 12, 34, 11
On average, it took 25 times for [ha] to appear again.

One way to solve this would be noting each new value that appears. although this would be time intensive. I could accurately discover all Elements eventually - and then simply count them. I am attempting to do this in far less time with far less roll()'s


text:
Q: Transfering of 565RGB images through socket in java I want to transfer images through socket in java.
There is a convenient method to send Image like a sequence of bytes.
ImageIO.write(image, "PNG", socket.getOutputStream());

But I don't need any format ("PNG","JPEG", etc.).
Server is implemented on C-language within microcontroller evaluation board and doesn't support them.
I want to send an image like a sequence of RGB565-pixels.
for example: 12_1F      24_C3      ...      67_02 .

Server receives it, sets (unsigned short *) pointer on data-field and I have acceses to
 pixel [0][0] (12_1F)

of image-matrix through this pointer. After operation pointer++ we have access to the next
 pixel [0][1] (24_C3)

and so on... Is it posible with ImageIO.write(...) or in other way?

A: you could write your own imageWriter...
http://download.oracle.com/javase/1,5.0/docs/guide/imageio/spec/extending.fm4.html


text:
Q: Implications of caching objects (per user) and garbage collection When you store something in ASP.NET's build in cache, how does this work with the garbage collector?
Example:
if( not in cache)
{
  List<UserSales> sales = SalesService.GetByUserId(loggedInUser.id);

  InsertToCache(cacheKey, sales);
}
else
{
   // loads from cache
}

So for each user, I first check if the data is in cache.
What I want to know is, what effect does this have on the garbage collector?  If the sales object has say 200-500 rows for some users, how will the GC behave in this situation?
What if I have a sliding expiration for 20 minutes so it is removed from the cache, just because it is removed, it still has to be GC'd correct?
The only thing holding a reference to sales would be the cache system, and the mvc view page but that goes out of scope when the requests ends.

A: The cache will simply remove it's reference to the cached item when it expires.  If a reference is also held by a page that is running then the cache item will not be eligible for GC until the request ends.


text:
Q: Alternate sky colors? Ok, so the sky is blue because of Rayleigh scattering - blue wavelengths of light scatter off atmospheric particles in the air (more/more easily than others) - I understand this pretty well.
So, if our atmosphere had a different chemical composition, would the sky be a different color (barring things like clouds and dust)? I assume that the size of nitrogen molecules happens to be the perfect size to scatter blue light, so what if we had 78% helium instead, or hydrogen, or gaseous zinc?
If this is correct - which elements would need to be predominant in the atmosphere to produce red, orange, yellow, green, indigo and/or violet skies? If not, what am I misunderstanding about Rayleigh scattering?

A: Aside from scattering, an important contribution to sky color in a purely gaseous atmosphere is absorption. Already on the Earth we have stratospheric ozone which makes twilights blue (see Why is there a "blue hour" after the "golden hour"?).
So, if the atmosphere were made of (or contained a large enough amount of) chlorine, nitrogen dioxide, iodine, or any other colored gas, the sky colors would be quite different.

A: Rayleigh scattering results in scattering inversely proportional to the fourth power of the wavelength. So, no matter what the composition of the scatterer is, the blue will be scattered more than the red, as long as the main process is Rayleigh scattering.
If you want to have another color for the sky, this will need to be the result of a different process or processes. Or the light from the star may have a different spectrum, with blue light being very weak or missing.
An example of a non-blue atmospheric color is the orange haze in atmospheres rich in methane, like on Titan or on the early Earth. Rayleigh scattering has nothing to do with this color. It seems to be due to chemical reactions produced by UV in the atmospheric methane, resulting in hydrocarbons emitting some orangy light.
The red color of sky at sunset on Earth (or after volcanic eruptions) is due to a different type of scattering, Mie scattering. This happens when the scattering particles are much larger than a molecule, comparable to or larger than the wavelength.


text:
Q: COUNT(*) not working in C# Hi Believe the problem is with the C# code itself and not the SQL statement, as I have outputted the SQL to the screen and run it direct into the database.
For example
 SELECT COUNT(*)
 FROM meeting_room.meeting_acceptance
 WHERE meeting_id = 'AAMkADY3MDk3NTdiLTE4M2ItNDk4ZS1hNmZjLWJmMDhkYTBiMDVjYgBGAAAAAAB+oqKzNnIvRZgdzn8wIE0XBwC62mlG2pRhSKvV6Bc2NH7rAAAALqU/AAC62mlG2pRhSKvV6Bc2NH7rAAAp5DTDAAA=';

Returns 1, although when outputting the "NoRows" variable, 0 still appears, any ideas?
if ((Appoint.End > DateTime.Now) && (Appoint.Start < DateTime.Now))
{
   MySql.Data.MySqlClient.MySqlConnection mycon3 = new MySqlConnection(GetConnectionString());

   if (mycon3.State != ConnectionState.Open)
       try
       {
           mycon3.Open();

       }
       catch (MySqlException ex)
       {
           throw (ex);
       }

   using (mycon3)
   sql = "SELECT count(*) from meeting_room.meeting_acceptance where meeting_id = '" + Appoint.Id + "';";

   Label1.Text = sql;
    using (MySqlCommand mcmd = new MySqlCommand(sql, mycon3))
        try
        {
                using (MySqlDataReader datareader = mcmd.ExecuteReader())
                {
                    while (datareader.Read())
                    {
                        NoRows = Convert.ToInt32(datareader.GetValue(0));
                    }
                }
        }
       catch
       {
           Error.Text = "SQL Exception 2" ;
           sqlerror = true;
       }

    Success.Text = NoRows.ToString();
    if ( NoRows == 0 )
    {
        ConfirmLink.Text = "

";
        if (DateTime.Now.AddMinutes(-2) > Appoint.Start)

{
        Error.Text = "Would have deleted meeting";
    //  Appoint.CancelMeeting("The meeting you created for the " + resource_name + " on " + Appoint.Start + " Subject: " + Appoint.Subject + " has been deleted as you did not accept the meeting");
    }
}

}

A: You need to use ExecuteScalar method
int count = (int) (mcmd.ExecuteScalar() ?? 0);

Also you have not enclosed the using block properly..Your code should look like
using(MySqlConnection mycon3 = new ....)
{
    try
    {
        mycon3.Open();
        //your commands
    }
    catch(SqlException e){}
}

Also your query is vulnerable to sql injection attack..Consider using SqlParameter

A: Convert.ToInt32(cmd.ExecuteScalar());

if you try to do explict conversion then it make a exception. Convert.ToInt32 will gave you 0 if result is null.
Your code doesn't use SQL-Parameter so it will be unsafe. use Sql parameter to make your code safer from Sql-injection.


text:
Q: Is it possible to compile potrace for iOS? Looking at the cross-platform nature of potrace http://potrace.sourceforge.net/, is it possible to compile this for iOS? If so, how?

A: Yes, it is possible to compile potrace for iOS.
As a matter of fact, most open source libraries using standard (GNU) configure tools that compile on MacOS X will easily compile on iOS, because they are likely free of platform-specific code (e.g. linuxisms) and standard configure tools allow cross-compilation.
You can compile these libraries in the shell by pointing configure to the proper toolchain and SDKs. Paths changed with Mavericks and Xcode 5, but fortunately automated scripts exist for more popular libraries such as expat.
The proposed solution is based on the x2on/expat-ios project on GitHub. Their script fixes expat's config.sub which doesn't know about arm64 target. Do does potrace 1.11's config.sub. However, a simpler approach consists in downloading a more recent version of config.sub. Unlike expat, potrace doesn't seem to need any patch to compile for iOS.
Full script build-potrace.sh is available here:
https://gist.github.com/pguyot/dce18af64a71b93c0204
Please note that potrace is licensed under the GPLv2. You might want to check Is it legal to publish iOS apps under the GNU GPLv3 open-source license? question.


text:
Q: Как закрыть прямой доступ к файлам в папке через .htaccess, но разрешить если есть ?key=secret? Нужно запретить прямой URL-доступ к файлам из папки orders на сервере, при этом разрешить доступ по URL'у который содержит определенную GET-переменную key с значением: secret.
Вот к примеру, есть у нас папка orders и в ней файл 1.* - расширение может быть любым, например 1.jpg
Нужно чтобы обращение через /orders/1.jpg - выдавало бы ошибку доступа или переадресацию в 404
И наоборот обращение вида: /orders/1.jpg?key=secret было бы успешным!
Возможно ли такое реализовать с помощью настроек в .htaccess?
p.s.: а в идеале если бы еще можно было secret как-то генерировать - чтобы везде был бы не просто одинаковый ?key=secret, а какой-нить ?key=ХХХХХХХ, где ХХХХХХХ какой-нибудь кэш от имени файла к которому идет обращение.

A:
Возможно ли такое реализовать с помощью настроек в .htaccess?

Сделать подобное можно, но я бы (если бы был фронтенд девелопером) делал бы такое с помощью движка сайта.
Можете попробовать такой вариант:
RewriteCond %{REQUEST_URI} ^/orders/.*
RewriteCond %{QUERY_STRING} !^key=secret$
RewriteRule .* - [R=404,L]


text:
Q: django - How to get parameters from "def save" function Is there a way to get parameters from the "save" function? Even if I shoot debug,
models.py
def save(self, *args, **kwargs):
    super().save(*args, **kwargs)

http://127.0.0.1:8000/photo?h=2020&w=8020
I have to save using "h=2020&file_w=8020".
Adding "request" gives me an error.

A: You can print the data inside of it like this
def save(self, *args, **kwargs):
    print(args, kwargs)
    super().save(*args, **kwargs)

args is a tuple with the arguments and kwargs is a dictionary with the keyword arguments.
Example:
function('this is an argument', this_is_keyword='value of keyword')


text:
Q: Tomcat7 Java Servlet Crashes after a few minutes I have a java servlet running on a tomcat7 web server.  I've written a program that loads a page from the server every 10 seconds.  The page is called up with a PHP script that uses the CURL function to trigger Tomcat to serve up the web page  The page is very simple and takes less than 1 second to load.
After about 5 minutes or so, the server crashes. Checking my log files, I get inconsistent errors as to why.
Frequently I received java.util.zip.ZipException: error in opening zip file as the error right before the site crashes.  Most recently I received a null pointer exception before the crash.  These error resulted form the same initial conditions (I simply restarted Tomcat between crashes and did not alter any code)
I used Eclipse to build my servlet.  I'm new to Tomcat and I'd like to fix it so that it is stable.  Any advice would be greatly appreciated.
I'm using tomcat 7, and my java version is:
Java(TM) SE Runtime Environment (build 1.6.0_26-b03)
Java HotSpot(TM) 64-Bit Server VM (build 20.1-b02, mixed mode)

Stack Trace (#### is for removed content):
SEVERE: Servlet.service() for servlet [##################] in context with path [/##################] threw exception
java.lang.RuntimeException: java.util.zip.ZipException: error in opening zip file
    at org.apache.hadoop.conf.Configuration.loadResource(Configuration.java:1387)
    at org.apache.hadoop.conf.Configuration.loadResources(Configuration.java:1251)
    at org.apache.hadoop.conf.Configuration.getProps(Configuration.java:1192)
    at org.apache.hadoop.conf.Configuration.get(Configuration.java:415)
    at org.apache.hadoop.hbase.HBaseConfiguration.checkDefaultsVersion(HBaseConfiguration.java:63)
    at org.apache.hadoop.hbase.HBaseConfiguration.addHbaseResources(HBaseConfiguration.java:89)
    at org.apache.hadoop.hbase.HBaseConfiguration.create(HBaseConfiguration.java:100)
    ########################
    ###########################
    #########################
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:928)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:539)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:298)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:662)
Caused by: java.util.zip.ZipException: error in opening zip file
    at java.util.zip.ZipFile.open(Native Method)
    at java.util.zip.ZipFile.<init>(ZipFile.java:127)
    at java.util.jar.JarFile.<init>(JarFile.java:135)
    at java.util.jar.JarFile.<init>(JarFile.java:72)
    at sun.net.www.protocol.jar.URLJarFile.<init>(URLJarFile.java:72)
    at sun.net.www.protocol.jar.URLJarFile.getJarFile(URLJarFile.java:48)
    at sun.net.www.protocol.jar.JarFileFactory.get(JarFileFactory.java:70)
    at sun.net.www.protocol.jar.JarURLConnection.connect(JarURLConnection.java:104)
    at sun.net.www.protocol.jar.JarURLConnection.getInputStream(JarURLConnection.java:132)
    at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(XMLEntityManager.java:653)
    at com.sun.org.apache.xerces.internal.impl.XMLVersionDetector.determineDocVersion(XMLVersionDetector.java:186)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:772)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
    at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:235)
    at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:284)
    at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:180)
    at org.apache.hadoop.conf.Configuration.loadResource(Configuration.java:1300)


text:
Q: Linq query using generics & interfaces I have several entity framework classes that implement the following an IInactive interface.
public interface IInactive
{
    bool inactive { get; set; }
}

For example, my Order class is defined as follows:
public class Order : IInactive
{
    [Key]
    [Required]
    public Guid orderId { get; set; }
    ...
    public bool inactive { get; set; }
}

I am trying to implement a generic method that can be used against all objects (entities) whether they implement the IInactive interface or not. It would be called as follows:
var query = GetAllActive<Order>();

My code for this generic method looks like this:
public IQueryable<T> GetAllActive<T>() where T : class
{
    DbSet<T> dbSet = this._db.Set<T>();

    // Does the entity implement the IInactive interface.
    // If yes, only return "active" row, otherwise return all rows
    if (typeof(T)is IInactive)
    {
        // Problem: the code in this block never executes, that is,
        // (typeof(T)is IInactive) never evaluates to true

       ...

    }

    return dbSet;
}

I would greatly appreciate some help solving this issue! Thanks.

A: Instead of
if (typeof(T) is IInactive)

try
if (typeof(IInactive).IsAssignableFrom(typeof(T)))


text:
Q: How to convert pseudo code to Python 2.x? Here is the pseudo-code for an Over Produced Management System:
Add memory library module

Prompt; 1)search for item, 2)add over produced item

If search for item
Prompt input item number

    If item number in database print available quantity

    Else print "None available"

Else if add over produced item
Prompt input item number
    If item number in database
    Prompt "how many"
    Add quantity to inventory
    Else if item number not in inventory
    Add item to inventory with quantity

A: db = {}
while True:
    if raw_input("Prompt; 1)search for item, 2)add over produced item > ") == "1":
        item = raw_input("Item number? > ")
        if item in db:
            print("Available: " + str(db[item]))
        else:
            print("None available")
    else:
        item = raw_input("Item number? > ")
        qty = int(raw_input("Quantity? > "))
        if item in db:
            db[item] += qty
        else:
            db[item] = qty


text:
Q: How Does The Debugging Option -g Change the Binary Executable? When writing C/C++ code, in order to debug the binary executable the debug option must be enabled on the compiler/linker.  In the case of GCC, the option is -g.  When the debug option is enabled, how does the affect the binary executable?  What additional data is stored in the file that allows the debugger function as it does?

A: -g tells the compiler to store symbol table information in the executable.  Among other things, this includes:

*

*symbol names

*type info for symbols

*files and line numbers where the symbols came from

Debuggers use this information to output meaningful names for symbols and to associate instructions with particular lines in the source.
For some compilers, supplying -g will disable certain optimizations. For example, icc sets the default optimization level to -O0 with -g unless you explicitly indicate -O[123].  Also, even if you do supply -O[123], optimizations that prevent stack tracing will still be disabled (e.g. stripping frame pointers from stack frames.  This has only a minor effect on performance).
With some compilers, -g will disable optimizations that can confuse where symbols came from (instruction reordering, loop unrolling, inlining etc).  If you want to debug with optimization, you can use -g3 with gcc to get around some of this.  Extra debug info will be included about macros, expansions, and functions that may have been inlined. This can allow debuggers and performance tools to map optimized code to the original source, but it's best effort.  Some optimizations really mangle the code.
For more info, take a look at DWARF, the debugging format originally designed to go along with ELF (the binary format for Linux and other OS's).

A: In addition to the debugging and symbol information
Google DWARF (A Developer joke on ELF)
By default most compiler optimizations are turned off when debugging is enabled.
So the code is the pure translation of the source into Machine Code rather than the result of many highly specialized transformations that are applied to release binaries.
But the most important difference (in my opinion)
Memory in Debug builds is usually initialized to some compiler specific values to facilitate debugging. In release builds memory is not initialized unless explicitly done so by the application code.
Check your compiler documentation for more information:
But an example for DevStudio is:

*

*0xCDCDCDCD  Allocated in heap, but not initialized

*0xDDDDDDDD  Released heap memory.

*0xFDFDFDFD  "NoMansLand" fences automatically placed at boundary of heap memory. Should never be overwritten. If you do overwrite one, you're probably walking off the end of an array.

*0xCCCCCCCC  Allocated on stack, but not initialized

A: -g adds debugging information in the executable, such as the names of variables, the names of functions, and line numbers.  This allows a debugger, such as gdb to step through code line by line, set breakpoints, and inspect the values of variables.  Because of this additional information using -g increases the size of the executable.
Also, gcc allows to use -g together with -O flags, which turn on optimization.  Debugging an optimized executable can be very tricky, because variables may be optimized away, or instructions may be executed in a different order.  Generally, it is a good idea to turn off optimization when using -g, even though it results in much slower code.

A: Just as a matter of interest, you can crack open a hexeditor and take a look at an executable produced with -g and one without. You can see the symbols and things that are added. It may change the assembly (-S) too, but I'm not sure.

A: There is some overlap with this question which covers the issue from the other side.

A: Some operating systems (like z/OS) produce a "side file" that contains the debug symbols.  This helps avoid bloating the executable with extra information.

A: A symbol table is added to the executable which maps function/variable names to data locations, so that debuggers can report back meaningful information, rather than just pointers. This doesn't effect the speed of your program, and you can remove the symbol table with the 'strip' command.


text:
Q: Rails ActiveRecord - association returns redundant rows I have my 2 models:
class Machine < ActiveRecord::Base
  has_many :channels
  #...

class Channel < ActiveRecord::Base
  belongs_to :machine
  #...

In Machine, if I do
channels.each do |channel|

I see the rows repeated (even many times) in an unintelligible order.
What's up?  Any ideas.  It sure looks like an ActiveRecord bug to me.
I'm on PostgreSQL.  Rails 3.0.3.
Thanks, Oz


text:
Q: Overlay unrelated data in tableau I'm new to Tableau.
I wish to overlay two sources of data on top of each other in a line graph. The two data sources contain different types of information but both have timestamps.
Source 1:
Computer CPU Temp measured over time (weeks)
This is shown as a line graph.
Source 2
Events which occur over time which are picked up by an agent installed on the computer.
These event vary but could be "Low Battery" or "Thermal Warning". There is no value, just a timestamp when it occurred.
I want to overlay the events which occur on the computer along the same timeline as the temperature reading line graph. ideally following the track of the CPU Temp.
How can the two be combined?


text:
Q: Changing android actionbar button style I'm currently changing the view on my ActionBar MenuItem like so:
MenuItem menuItem = menu.add(title);

TextView tv = new TextView(context);
tv.setTypeface(myTypeface);
tv.setText("hello");

menuItem.setActionView(tv);

However this disabled the function of the button, which I'm assuming is because I've changed the ActionView. Is there anyway I can do this whilst retaining the button function?

A: Here's an example of creating a custom MenuItem for the ActionBar.
First: Create the View that will serve as your MenuItem.
ActionLayoutExample
/**
 * A {@link RelativeLayout} that serves as a custom {@link MenuItem}
 */
public class ActionLayoutExample extends RelativeLayout {

    /** The MenuItem */
    private TextView mHello;

    /**
     * Constructor for ActionLayoutExample
     *
     * @param context The {@link Context} to use
     * @param attrs The attributes of the XML tag that is inflating the view
     */
    public ActionLayoutExample(Context context, AttributeSet attrs) {
        super(context, attrs);
        // Ensure the MenuItem is accessible
        CheatSheet.setup(this);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        // Initialize the TextView
        mHello = (TextView) findViewById(android.R.id.text1);
        mHello.setTypeface(myTypeface);
        mHello.setText("Hello");
    }

}

Second: Create the layout that you'll actually apply to the MenuItem.
action_layout_example
<your.package.name.ActionLayoutExample xmlns:android="http://schemas.android.com/apk/res/android"
    style="?android:attr/actionButtonStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="?android:attr/selectableItemBackground"
    android:clickable="true"
    android:contentDescription="@string/hello_world" >

    <TextView
        android:id="@android:id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</your.package.name.ActionLayoutExample>

It's important to include the style style="?android:attr/actionButtonStyle" to make sure the layout properly reflects ActionBar items. It's also important to include a android:contentDescription in your layout. Normally when you long press a MenuItem with an icon, a tooltip is shown to indicate what that MenuItem is for. In your case, you'll need to take an extra step to make sure this tooltip is still accessible.
A great helper for this is Roman Nurik's CheatSheet. You can see how I'm using it in the constructor of the action layout.
You specifically asked about the MenuItem being selectable. To do this, make sure you include the android:background="?android:attr/selectableItemBackground" and android:clickable="true" attributes.
Third: Use the android:actionLayout attribute to set your layout and inflate the menu normally within your Activity or Fragment.
your_menu
<item
    android:id="@+id/action_typeface"
    android:actionLayout="@layout/action_layout_example"
    android:showAsAction="ifRoom"
    android:title="@string/hello_world"/>

Using the MenuItem
In onCreateOptionsMenu call MenuItem.getActionView and on View.onClickListener. This is because onOptionsItemSelected will not be called for a custom View
final View example = menu.findItem(R.id.action_typeface).getActionView();
example .setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        // Do something
    }
});

The results

A: try this
tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //handle
            }
        });


text:
Q: Forcing 'who' utility to use date format: "%Y-%m-%d %H:%M" [LC_TIME] How to force 'who' core utility to use "%Y-%m-%d %H:%M" date format?
I have tried modifying my LANG, LC_ALL, LC_TIME, but none of them produced the required result.
I have manged to get it working on by the following command:
env -i ssh me@remotemachine 'who -s'
Well in this case SSH didn't send my LANG and LC_* variables to the remote machine.
Let's look at 'who' utility source code:
if (hard_locale (LC_TIME))
    {
      time_format = "%Y-%m-%d %H:%M";
      time_format_width = 4 + 1 + 2 + 1 + 2 + 1 + 2 + 1 + 2;
    }
  else
    {
      time_format = "%b %e %H:%M";
      time_format_width = 3 + 1 + 2 + 1 + 2 + 1 + 2;
    }

Well, I need this to on Linux and Mac OS X (BSD), but 'who' behaves identically on both. hard_locale() code is right here: http://opensource.apple.com/source/text_cmds/text_cmds-81/sort/hard-locale.c
It checks LC_TIME and if it's "C" or "POSIX" it's not hard locate, in that case it's free not to use any locale.
Setting:
export LANG=en_US.UTF-8
export LC_TIME=en_US.UTF-8
export LC_ALL=en_US.UTF-8

Does not modify the date format on 'who' output.
Another interesting observation:
# 2012-01-13 13:56 is used on remote machine (en_US.UTF-8)
# Now let's do this:
# env -i ssh me@remotemachine 'who -s'
# Jan 13 14:33 is used on remote machine

Any ideas? Or maybe setting variables is not enough?
Thanks!


text:
Q: Adjust estimate precision by sample size I wish to find comparable SDs/Confidence Intervals for two parameters.
One parameter has been measured by only one (new) study that reports the standard error. Here, t value, sample size and SD are provided.
The other (a correlation coefficient) has been measured by 10 (older) studies, in some as a mean across subjects, in some across all trials (ignoring subjects). The only values available for all studies are n of participants and the mean correlation coefficient; many don't report sufficient information to compute comparable SDs. I believe that all in all, r is roughly comparable across the 10 studies in this set.
I don't think I can directly compare the sample SD between subjects in set 1 with the between-study SD in set 2. How can I find comparable CIs/SDs for the two values while somehow controlling for the low sample size in the first study?
I'm not trying to compare the two values using a test (they're physiologically incommensurable), I simply want to look at them on a similar scale.
If I cannot come up with a proper quantification, I would simply be informal and focus on one SD for the 10-study set and two SDs for the one-study set, to reflect that one of them has been estimated "a lot more" precisely than the other.


text:
Q: Protractor not finding the same element after a promise I'm trying to obtain the text from a  element in protractor, and after doing something with the text, i want to click on the same  element. This is what i have
HTML:
 {{user?.login}}

Protractor test:
describe('Login OK with correct pass', () => {
    it('should login successfully with admin account', () => {
        // logging

        username.clear();
        username.sendKeys('admin');
        password.clear();
        password.sendKeys('admin');
        element(by.css('button[type=submit]')).click();
        // check if the username  has the current login username

        const expect2 = /admin/;
        const spanuser = element(by.css('span#spanuser'));
        spanuser.getText().then((value) => {
            console.log('inside');
            console.log(value ? value : 'no value');
            expect(value).toMatch(expect2);
        });
        // then i try to click on the same span, to do some stuff

        spanuser.click().then(() =>  {
            console.log('It has been pressed!');
        });
    });
});

The first part works just fine, it gets the test and it passes the expect, but when i try to do the click() function on the span, i get the following error:

Failed: Timed out waiting for asynchronous Angular tasks to finish after 5 seconds. This may be because the current page is not an Angular application. Please see the FAQ for moredetails: https://github.com/angular/protractor/blob/master/docs/timeouts.md#waiting-for-angular
While waiting for element with locator - Locator: By(css selector,
  span#spanuser)

What have i tried:

*

*browser.waitForAngular() before spanuser.click()

*browser.wait(10000) before spanuser.click()

*also i have a waitForAngular() in the beforeAll function.
Does anyone has a idea on this? It doesn't really make any sense to me, why wouldn't find the same element that has already found before?
Thanks a lot!

A: add browser.waitForAngularEnabled('false') in onPrepare of protractor conf.js
onPrepare: function() {
   browser.waitForAngularEnabled('false')
   // if you set this in onPrepare(), it will be a global setting, will
   // effect all script, so you no need to set it in other place.
}

A: use the jasmin defaulttimeoutinterval in config instead of manual sleep
jasmineNodeOpts: {
   defaultTimeoutInterval: 250000
    },
     allScriptsTimeout: 180000


text:
Q: How to control setTimeout with promises var functionsArray = [
  function() {
        setTimeout(function() {
        console.log(1);
    }, 100);
  },
  function() {
    setTimeout(function() {
        console.log(2);
    }, 200);
  },
    function() {
        setTimeout(function() {
            console.log(3);
    }, 10);
  }
],

Say I have an array of functions like above(the number of functions in it is not known). I want to write a function which takes this array as parameter and executes them in sequence. In the example above, I want it to log 1,2,3 in the sequence. Since Promise.all does not guarantee the order of execution, is it possible to achieve this without callback hell?

A: You can't get a promise from a function that just calls setTimeout - it needs some help, e.g.:
function after(n, f) {
  return () => new Promise(resolve => {
    setTimeout(() => {
        resolve(f());
    }, n);
  });
}

with usage:
var functionsArray = [
  after(100, () => console.log(1)),
  after(200, () => console.log(2)),
  after( 10, () => console.log(3)),
];

With that array you can then just await each function in turn:
for (let f of functionsArray) {
  await f();
}

A: You can write an simple setTimeoutPromise function:
function timeoutPromise(time = 0){
  return new Promise(resolve => setTimeout(resolve, time)
}

await timeoutPromise(10);
console.log('waited 10 sec')
timeoutPromise(20).then(() => console.log('waited 20 sec')

//make a new array as you like

Promise.all([
 timeoutPromise(100).then(() => console.log(1)),
 timeoutPromise(200).then(() => console.log(2)),
 timeoutPromise(300).then(() => console.log(3))
])


text:
Q: Is it possible to levitate an object with piezoelectricity? The delay for transmit pressure depend of speed of sound in the material. A lot of piezo slip-stick actuator can generate an asymetric wave. Like the differential pressure is not the same the force to up can cancel gravity ?
In example, with 400 actuators, each actuator give force to down in 1/1000000s enough for cancel gravity while 1/1000000s, wait 10/1000000s and a force to up in (1/400 - 11/1000000)s. But next actuator action at time 1/1000000s. etc.

A:
Like the differential pressure is not the same the force to up can
  cancel gravity ?

You cannot cancel gravity, you can simply counteract it with another force.

Is it possible to levitate an object with piezoelectricity?

Yes. It is possible. But the piezoelectricty part is misleading. Better to say acoustic levitation, because you are using the vibration of the piezo to generate acoustic waves which interact in a medium to COUNTERACT gravity.
See link for a demonstration.
http://www.youtube.com/watch?v=669AcEBpdsY


text:
Q: Measure the period of an unknown signal using TC1 in AVR (Assembly) I'm learning Assembly and I find the part of timer/counter quite confusing for me... In class, we had this example of period measurement using TC1 in AVR (metaAVR 328P):

Use the TC1 to measure the period of an unknown signal. The period is known to be shorter than 128 ms. Assume that the clock frequency is 16 MHz. Use the number of clock cycles as the unit of the period.

The solution given to us was:

Since the input-capture register is 16-bit, the longest period of the signal that can be measured with no prescaler is: 2^16 ÷ 16 MHz = 4.096 msec.
To measure a period that is equal to 128 ms, we have two options:

*

*Set the pre-scale factor to 1 and keep track of the number of times the timer counter overflows.

*Set the pre-scale factor to 64 and do not keep track of the number of times the timer counter overflows.
We will use the pre-scale factor of 64.

I get that the longest period that can be measured is 4.096 ms. But where do the two options come from? If we set the prescalor to 1, the clock frequency would be 16 MHz, so what happens? If then we set it to 64, the clock period would be 16MHz / 64 = 250 000 Hz = 250 KHz, then what happens? I just fail to see how setting the frequency relates to keep track of the number of times the timer counter overflows... Why do we need to to prescale the frequency anyway? Are we trying to find out the number of clock cycles, so

clock cyles * clock frequency after prescaling = period?

Is the above equation right? At this point I feel like I'm confusing myself, so any hint would be really appreciated.

A: No, the equation is not right.
The frequency is the reciprocal of the time of one tick. At 16 Mhz, the tick is 1/16000000 of a second. That is why the 16-bit timer overflows after 65536/16000000 = 4096/100000 seconds.
The formula you are looking for is in units of seconds, so
ticks / frequency = period
will do.


text:
Q: jQuery + If Statement I'm trying to teach myself some basic jquery and am having trouble with an if statement I'm trying to use. My code is as follows:
var animate = 0;

$('a').click(function () {
if (animate == 0) {
$('#shadow').fadeOut(500);
var animate = 1;
}
});

I'm hoping to use some else statements further down the line, so that depending on the value of "animate" it will perform a different jquery action when clicked.  I'm sure I've overlooked something obvious, but I'm banging my head against a wall trying to figure out what it is.
Any help would be most appreciated!

A: When you use var to declare a variable, then it becomes a local variable, which means it's new within that scope.
The quick (and dirty) way for you to get the goal you want is something like:
var animate = 0;
$('a').click(function() {
    if (animate === 0) {
        $('#shadow').fadeOut(500);
        animate = 1;  // note the lack of "var"
    }
});

Note that this is probably a pretty imperfect solution; in particular animate doesn't set itself back to 0 (you can do this with a callback function as the second argument to fadeOut, though).
A still better solution is probably to place (and remove) a class on the particular item you're working with:
$('a').click(function() {
    if (!$('#shadow').hasClass('animating')) {
        $('#shadow').addClass('animating').fadeOut(500, function() {
            $(this).removeClass('animating');
        });
    }
});

However, I don't know the details of your implementation, so I'll let you figure out what is right for your particular needs.

A: You shouldn't use the var keyword again when assigning 1 to animate. By doing this, you are causing a syntax error since animate has already been declared within the same scope.

A: You're redefining animate by using var inside the click function.
change
var animate = 1;

to
animate = 1;

This will make it so you set the value of the animate variable in the outer scope and not animate that you are creating in scope within the click function.
HTH


text:
Q: Filtering documents by length of an array of objects I have the following schema:
const RecipeSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        trim: true
    },
    ingredients: [
        {
            name: {
                type: String,
                required: true,
                trim: true
            },
            amount: {
                type: Number,
                required: true
            }
        }
    ]
});

const Recipe = mongoose.model('Recipe',RecipeSchema);
export {Recipe as default}

I am stuck on filtering the recipes by providing two numbers: min and max, and return the list of recipes that have the number of ingredients ( length of ingredients array ) greater than min and less than max.
Can you help me on this one?

A:
here I have used the $expr operator to filter out all those documents
which have sizes greater than or equal to min and less than or equal
to max.

   let min = 1
   let max  = 2

RecipeModel.find({"$expr":{$gte:[{$size:"$ingredients"},min], $lte:[{$size:"$ingredients"},max]}})

A: This sequence finally did it:
{$where: "this.ingredients.length >= " + min + " && this.ingredients.length <= " + max}


text:
Q: Where are the OpenCMIS unit tests referred to in the documentation? I'm implementing CMIS support for my client's document database using OpenCMIS. I've been following the guide here for creating the server. This has mostly gone well, but when I got to the section "testing the server" I couldn't find the jUnit tests they're referring to - the classes where not in any of the packages one was told to import. When looking through the Javadocs they weren't documented there either. Am I simply looking in the wrong place or is that guide out of date?

A: The unit tests aren't in the main jars.
As is common with Maven based projects, if you look at the Apache OpenCMIS Source in SVN, within each module you have directories src/main/java and src/test/java .
When Maven builds the project, it compiles both, but only puts the main outputs into the binary jar. The test ones are used locally to run the tests, but aren't packaged. (The OpenCMIS test helpers, however, are built and packaged, they have artificats like chemistry-opencmis-test-util and chemistry-opencmis-test-tck)
If you wanted to run the TCK tests, you can just grab the artifacts from Maven and run. To run the project internal tests, you'll need to either download the source package, or checkout from SVN, then build. At that point, you'll have all the unit tests available to run

A: I can find more about creating and testing an OpenCMIS server here:
https://github.com/cmisdocs/ServerDevelopmentGuide