text:
Q: Unable to inject AutoWired Enviroment when using Spring Boot 1.4 testing annotations I am running my Integration Tests on a Spring Boot application using Cucumber and in my step definitions, my code had been bootstrapping the Spring Boot app using this:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Application.class, loader = SpringApplicationContextLoader.class)
@WebAppConfiguration
@IntegrationTest
@Slf4j
public class CreditCardStepdefs {

....

}

Now, I'm trying to refactor my code to make use of the simplified annotations in Spring Boot 1.4 and the same piece of code looks like this now:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
@Slf4j
public class CreditCardStepdefs {

...

}

However, I'm facing some problems in picking up environment variables in this particular piece of code:
@Autowired
private Environment env;

@Before("@RUN, @POST")
public void setUp() {
    this.host = env.getProperty("test.url") + env.getProperty("server.contextPath");
    this.results = new HashMap<>();
    this.paramKeyList = new ArrayList<>();
    this.retry = false;
    this.isPassed = true;
}

When I run the test, "env.getProperty()" would always throw an NPE. It seems that @AutoWired for Environment doesn't work anymore using the annotations above. What do I need to do in order to get the Environment injected into the context?


text:
Q: An easy way to send a file from one app to another (on a different device) What's the easiest way to transfer a file between two apps running on two different devices? The app is written in Flutter.

A: You can do that using a database. File will be saved on cloud and from your app you can update it.
Like from X device you read the file parse it to JSON and POST to database.
Then from Y device you can request to database to return that file. That will be returned as JSON than you can read and map at your model and access the file datas using yourModel.yourField() .

A: You can store your files on a Database such as Cloud Storage for Firebase which allows you to store different file formats
You can then add more files from any device running your Flutter App & make network calls

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can i get user who deleted file? I need to know which user deleted file in filesystem from c# code.
Only one idea is to use audit, but it seem to be very slow...

A: You can use the FileSystemWatcher.Deleted event to capture deletes happening on the filesystem.
Depending on the application, you may at that point also be able to find out what user caused this event to occur (it is not part of FileSystemEventArgs).

A: I don't know if this can be retrieved from the filsystem, but one possible way is to use av FileSystemWatcher object to trigger an event on Deleted.  The downside is that you need to have the watcher application running all the time.  One upside is that you can monitor just a spesific folder if that's feasible.


text:
Q: Writingminds ffmpeg 64 bit architecture support I am using FFMpeg in one of my project for audio video mixing and it is working fine.
Now I have requirement for 64-bit architecture support so i have generated .so files for 64-bit architecture support. Now the problem is like in java code there is a class CpuArch.java in which some architecture are define with some alphanumeric value like below:
x86("0dd4dbad305ff197a1ea9e6158bd2081d229e70e"),
ARMv7("871888959ba2f063e18f56272d0d98ae01938ceb")
Now I have to add two more value for ARMv8 and x86_64. From where I got these alphanumeric values.
And one more thing like assets folder contain ffmpeg files During .so file generation nothing updates in assets folder so how could I generate those files for other architecture as well.
Please help.
I followed this library for audio video mixing : https://github.com/WritingMinds/ffmpeg-android-java


text:
Q: Python + SQLAlchemy + Oracle + sequences = unable to insert new row First, some background and problem description:
I have to work with Oracle DB and need to cover it with DBAL (SQLAlchemy). My local development DB that is used for BDD/CI etc. uses MySQL hence the need for DBAL. Everything is develop in Python.
Connecting, reading operations are not a problem however I cannot Insert anything due to more than likely two problems: sequence and dates.
Just to clarify my requirements:

*

*Sequence: is a string field and is prefixed e.g. "ABC123". In the database it's solved by just setting 'ABC'||TEST_SEQUENCE.NEXTVAL as default. That works on the DB level. I have no idea how to make it work and use string prefix.

*Dates: as MySQL is happy with just string (e.g. 2019-01-01 12:02:03) Oracle is obviously temperamental. I have used datetime object however that generates sql with datetime.datetime(2013, 1, 1, 12, 2, 3) as date value which is not a valid SQL for Oracle, unless SQLAlchemy does some magic before executing it in the DB.

Bottom line is, I need a DBAL config that works both with Oracle and MySQL that uses string prefix sequences.
Here's an example code:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, DateTime, Float, create_engine, Sequence
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class Person(Base):
    __tablename__ = 'PERSONS'

    id_seq = Sequence('PERSONS_SEQ', metadata=Base.metadata)
    id = Column('ID', String(20), id_seq, primary_key=True)
    created_date = Column('CREATED_DATE', DateTime)

    def __init__(self, created_date):
        self.created_date

engine = create_engine("<some connection string trolololo>")
Session = sessionmaker(bind=engine)
session = Session()

created_at = datetime.strptime('2019-01-01 12:02:03', '%Y-%m-%d %H:%M:%S')
new_person = Person(
    created_date=created_at
)
session.add(new_account_payments)
session.flush()
session.commit()

The errors/problems
The initial problem is the sequence which is resulting in this error:
sqlalchemy.orm.exc.FlushError: Instance <Person at 0x7f1d7fb2de48> has a NULL identity key.  If this is an auto-generated value, check that the database table allows generation of new primary key values, and that the mapped Column object is configured to expect these generated values.  Ensure also that this flush() is not occurring at an inappropriate time, such as within a load() event.

I have tried adding autoincrement="auto" but that just gave me different error suggesting it's only working with INTs and not STRINGs.
I did not manage to check if the date format is working yet due to aforementioned problem however I will update the thread once that is solved.
Thanks in advance!

A: According to the docs

While the above is a prominent idiomatic pattern, it is recommended that the Sequence in most cases be explicitly associated with the MetaData, using the Sequence.metadata parameter

So try adding the meta data and using the orm definition (shown in the docs)
class Person(Base):
    __tablename__ = 'PERSONS'

    id_seq = Sequence('PERSONS_SEQ', metadata=Base.metadata)
    id = Column(String(20), id_seq, server_default=id_seq.next_value(), primary_key=True)

    created_date = Column('CREATED_DATE', DateTime)

A: After long experimentation the above example minus the __init__ function and session.flush() started to work. I might have overcomplicated the issue by experimenting with couple things at a time.
I still don't know how to force prefix on the Sequence. Please let me know if you do.


text:
Q: Two Port Circuit I hope all are well.
Please can you help me with the below, I have a idea of doing it but I am so confused in determining the correct ANSWER. I am using the linear and nonlinear text book by Leon O. Chuao 1987, does anyone have the solution manual for this book?
The question is for the two-port circuit determine the conductance matrix?
I attempted the solution but not sure how to add the annoying dependent source in my equations please help me.
thank you all.

Thank you very much, I really appreciate your response.
Please can you tell me in the Matrix will now it become alter since it will be 2- 1/R2

A: I don't have the solutions book but I can see a simple mistake in your third equation. Everything else seems ok to me.
You should had written: \$i_2=2v_1+i_3'-i_2'\$ instead of \$i_2=i_3'-i_2'\$
because you must take into account the \$2v_1\$ current drawn by the dependent voltage controlled current source.


text:
Q: CakePHP subdomains with htaccess I've used the following rules in my htaccess file in other applications to redirect users from a folder to a subdomain but load the content from that folder when accessing that subdomain.
# REWRITE SUBDOMAIN TO FOLDER
RewriteCond %{HTTP_HOST} ^admin\.cameron\.com$
RewriteRule !^admin/? admin%{REQUEST_URI} [NC,L]

# REWRITE FOLDER TO SUBDOMAIN
RewriteCond %{THE_REQUEST} \s/admin/([^\s]*) [NC]
RewriteRule ^ http://admin.cameron.com/%1 [R=301,L]

So if I go to: http://cameron.com/admin I end up on http://admin.cameron.com/
But the content is loaded from http://cameron.com/admin
However this doesn't work for CakePHP 2.x because of its rewriting apparently...
In my htaccess file in /app/webroot I have:
<IfModule mod_rewrite.c>

    RewriteEngine On

    # CAKEPHP RULES
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php [QSA,L]

    # REWRITE SUBDOMAIN TO FOLDER
    RewriteCond %{HTTP_HOST} ^admin\.cameron\.com$
    RewriteRule !^admin/? admin%{REQUEST_URI} [NC,L]

    # REWRITE FOLDER TO SUBDOMAIN
    RewriteCond %{THE_REQUEST} \s/admin/([^\s]*) [NC]
    RewriteRule ^ http://admin.cameron.com/%1 [R=301,L]

</IfModule>

If I go to: http://cameron.com/admin it just tries to load the AdminController and doesn't redirect you, and if I go to: http://admin.cameron.com/ I just get a 500 Internal Server Error.
Any ideas on how to get this working for CakePHP?

A: CakePHP and almost any other PHP framework parse $_SERVER['REQUEST_URI'] in order to route your request to particular controller
more info here: https://github.com/cakephp/cakephp/blob/2.6/lib/Cake/Network/CakeRequest.php#L230 ,
so you simply need to have the SAME request URI parameters for your redirect to get app working.
For your old location it was "/admin", for new location it should be the same, but you do not want to pass it, so it is better to change the task like this:
"When you go to admin.site.com you will be redirected to site.com/admin".
This can be done simply like this:
RewriteRule ^([^.]+)\.example\.com http://example.com/$1
It is not a working example of rule because you also need to rewrite subdomain's request URI to to get everything working and it depends on your requirements, but can be smth like this:
RewriteRule ^([^.]+)\.example\.com(.*) http://example.com/$1/$2
UPD: real example
$ cat app/webroot/.htaccess
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
    RewriteCond %{HTTP_HOST} ^admin.example.com
    RewriteRule ^(.*)$ http://example.com/admin/$1 [P,L,NC]
</IfModule>

A:   <IfModule mod_rewrite.c>
  #standard cake htaccess stuff
  ...

  RewriteCond %{HTTP_HOST} ^profile\.thechatfun\.com$ [NC]
  RewriteRule ^(.*)$ http://www.thechatfun.com/users/profile/$1 [R=301,L]

  RewriteCond %{HTTP_HOST} ^chat\.thechatfun\.com$ [NC]
  RewriteRule ^(.*)$ http://www.thechatfun.com/chats/index/$1 [R=301,L]

</IfModule>


text:
Q: VLC and Python architecture comatibility issue When I open vlc.py with the python 2.7 interpreter it works, but when I open it with the python 3.4 interpreter it doesn't work. I get the below error.
I am pretty sure the issue is that the architecture is different for my python 3.4 (64bit in conda) and python 2.7 (32bit not in conda), so vlc.py will only work with my python 2.7.
I understand that when the Python version and VLC are compatible, i.e. 32bit Python architecture, it works fine. But, I can't create this architecture in my conda because my conda root is 64bits. Even if I create a new environment in conda and install Python 2 there, the root will still be 64bit. I tried this and it doesn't work.
For some reason, VLC only seems to work when the platform architecture is 32bit. I just can't wrap my head around this issue.
Traceback (most recent call last):
  File "C:\Users\Acer\Desktop\VLC Player\Main.py", line 28, in <module>
    import vlc
  File "C:\Users\Acer\Desktop\VLC Player\vlc.py", line 175, in <module>
    dll, plugin_path  = find_lib()
  File "C:\Users\Acer\Desktop\VLC Player\vlc.py", line 152, in find_lib
    dll = ctypes.CDLL('libvlc.dll')
  File "C:\Users\Acer\Miniconda3\envs\updated\lib\ctypes\__init__.py", line 347, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: [WinError 126] The specified module could not be found

A: Currently your 32bit VLC works with your 32bit python (which happens to be 2.7)
Uninstall your 32bit VLC, and download 64bit VLC. It'll work with 64bit python (which happens to be 3.4) now.


text:
Q: Regarding the update of the custom field in salesforce apex language I need some suggestions for the code which overrides the custom field which already stored as record in object.  I have created one object signup with some fields like mail id, password and confirm password with validation, then I have created page with those fields  and I have save those details to the signup object.
Then I have created another page with mail id and new password, so here i am facing one problem that i am unable to update the new password with the password field in signup object.the password field in signup object should override with the new password.
If any suggestions with code is very helpful to me.

A: First off, keep in mind that storing passwords in salesforce is frowned upon, especially if you are an app builder (see here)
In order to update a field on the form you must first load it in the background, the simplest way is to use builtin standard controller features since that controller automatically loads all fields referenced in the visualforce page that uses it.


text:
Q: Angularjs ui-modal is not working properly with $http request I am using Angularjs 1.5.x and AngularUI Bootstrap
I am trying to open a bootstrap modal and populate it with remote data using $http request.
I am using resolve method of modal's open instance to trigger $http request and fetch the data. After that I am updating a local variable and return it. However, the $http is fetching data properly but local scope variable is not updating properly and its keep showing as empty array in template.
Code:
app.controller('ModalCtrl', function ($uibModal, $log, $document, $rootScope, $http) {
      var $cctrl = this;

      $cctrl.modalData = [];

      $cctrl.animationsEnabled = true;

      $cctrl.open = function (size, templateUrl, parentSelector) {
         var parentElem = parentSelector ?
            angular.element($document[0].querySelector('.modal-demo ' + parentSelector)) : undefined;
         var modalInstance = $uibModal.open({
            animation: $cctrl.animationsEnabled,
            ariaLabelledBy: 'modal-title',
            ariaDescribedBy: 'modal-body',
            templateUrl: templateUrl,
            controller: 'ModalInstanceCtrl',
            controllerAs: '$cctrl',
            size: size,
            appendTo: parentElem,
            resolve: {
               modalData: function () {
                  var url;
                  var reqData;
                  var config = {
                     headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'responseType': 'json',
                        'cache': false
                     }
                  };

                  if (templateUrl == 'test.html') {
                     reqData = $.param({
                        lclasses: ($rootScope.activeTruck.truck.LicenceClassesRequired || ''),
                        subbie: ($rootScope.activeTruck.truck.subbie || '0')
                     });

                     url = 'index.php?module=test&task=fetchJSON';
                  }

                  $http.post(url, reqData, config).then(function (response) {
                     console.log("Success");
                     console.log(response); //here, response fetched data success
                     $cctrl.modalData = response.data;
                     console.log($cctrl.modalData); //here, its [] data
                     return $cctrl.modalData;
                  }, function (response) {
                     console.log("Failed");
                     console.log(response);
                  });
               }
            }
         });

         modalInstance.result.then(function (selectedItem) {
            console.log("opened");
         }, function () {
            $log.info('Modal dismissed at: ' + new Date());
         });
      };
   });

// Please note that $uibModalInstance represents a modal window (instance) dependency.
// It is not the same as the $uibModal service used above.

   app.controller('ModalInstanceCtrl', function ($uibModalInstance, modalData) {
      var $cctrl = this;
      console.log(modalData);
      $cctrl.modalData = modalData;

      $cctrl.ok = function () {
         //$uibModalInstance.close($cctrl.selected.item);
         $uibModalInstance.close();
      };

      $cctrl.cancel = function () {
         $uibModalInstance.dismiss('cancel');
      };
   });

A: Here it's working fine...

angular.module('ui.bootstrap.demo', ['ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('ModalDemoCtrl', function ($scope, $uibModal, $log) {
var $cctrl = this;

  $cctrl.items = [
    {
        "id": 0,
        "picture": "https://ultimatemotorcycling.com/wp-content/uploads/2011/11/2012-ducati-panigale-1199-preview-5.jpg",
        "age": 31,
        "name": "Mathews Goff",
        "company": "FXA"
    },
    {
        "id": 1,
        "picture": "http://placehold.it/32x32",
        "age": 36,
        "name": "Collins Alston"
    },
    {
        "id": 2,
        "picture": "http://placehold.it/32x32",
        "age": 27,
        "name": "Jasmine Rollins"
    },
    {
        "id": 3,
        "picture": "http://placehold.it/32x32",
        "age": 32,
        "name": "Julie Jefferson"
    },
    {
        "id": 4,
        "picture": "http://placehold.it/32x32",
        "age": 23,
        "name": "Wilder King"
    },
    {
        "id": 5,
        "picture": "http://placehold.it/32x32",
        "age": 23,
        "name": "Stanley Moore"
    },
    {
        "id": 6,
        "picture": "http://placehold.it/32x32",
        "age": 36,
        "name": "Reynolds Bishop"
    },
    {
        "id": 7,
        "picture": "http://placehold.it/32x32",
        "age": 26,
        "name": "Bryant Flowers"
    },
    {
        "id": 8,
        "picture": "http://placehold.it/32x32",
        "age": 38,
        "name": "Jenifer Martinez"
    },
    {
        "id": 9,
        "picture": "http://placehold.it/32x32",
        "age": 40,
        "name": "Mcguire Pittman"
    },
    {
        "id": 10,
        "picture": "http://placehold.it/32x32",
        "age": 34,
        "name": "Valdez Hyde"
    },
    {
        "id": 11,
        "picture": "http://placehold.it/32x32",
        "age": 34,
        "name": "Marla Mayo"
    },
    {
        "id": 12,
        "picture": "http://placehold.it/32x32",
        "age": 30,
        "name": "Brown Ortega"
    },
    {
        "id": 13,
        "picture": "http://placehold.it/32x32",
        "age": 32,
        "name": "Jeannette William"
    },
    {
        "id": 14,
        "picture": "http://placehold.it/32x32",
        "age": 30,
        "name": "Bridges Ashley"
    },
    {
        "id": 15,
        "picture": "http://placehold.it/32x32",
        "age": 33,
        "name": "Latasha Hewitt"
    },
    {
        "id": 16,
        "picture": "http://placehold.it/32x32",
        "age": 35,
        "name": "Alma Sawyer"
    },
    {
        "id": 17,
        "picture": "http://placehold.it/32x32",
        "age": 21,
        "name": "Liz Mcbride"
    },
    {
        "id": 18,
        "picture": "http://placehold.it/32x32",
        "age": 26,
        "name": "Mcintosh Chandler"
    },
    {
        "id": 19,
        "picture": "http://placehold.it/32x32",
        "age": 20,
        "name": "Alford Hartman"
    },
    {
        "id": 20,
        "picture": "http://placehold.it/32x32",
        "age": 29,
        "name": "Tiffany Green"
    },
    {
        "id": 21,
        "picture": "http://placehold.it/32x32",
        "age": 38,
        "name": "Stafford Riggs"
    },
    {
        "id": 22,
        "picture": "http://placehold.it/32x32",
        "age": 40,
        "name": "Elinor Chambers"
    },
    {
        "id": 23,
        "picture": "http://placehold.it/32x32",
        "age": 27,
        "name": "Carly Howard"
    },
    {
        "id": 24,
        "picture": "http://placehold.it/32x32",
        "age": 27,
        "name": "Rosalind Sanchez"
    },
    {
        "id": 25,
        "picture": "http://placehold.it/32x32",
        "age": 28,
        "name": "Jaclyn Shelton"
    },
    {
        "id": 26,
        "picture": "http://placehold.it/32x32",
        "age": 25,
        "name": "Hughes Phelps"
    },
    {
        "id": 27,
        "picture": "http://placehold.it/32x32",
        "age": 36,
        "name": "Rosetta Barrett"
    },
    {
        "id": 28,
        "picture": "http://placehold.it/32x32",
        "age": 29,
        "name": "Jarvis Wong"
    },
    {
        "id": 29,
        "picture": "http://placehold.it/32x32",
        "age": 23,
        "name": "Kerri Pennington"
    }
];

  $cctrl.open = function (size) {

    var modalInstance = $uibModal.open({
      templateUrl: 'myModalContent.html',
      controller: 'ModalInstanceCtrl',
      controllerAs:'$cctrl',
      resolve: {
        items: function () {
          return $cctrl.items;
        },
        size: function() {
         // console.log('size: ', size);
          return size;
        }
      }
    });

  };
});

// Please note that $modalInstance represents a modal window (instance) dependency.
// It is not the same as the $modal service used above.

angular.module('ui.bootstrap.demo').controller('ModalInstanceCtrl', function ($scope, $uibModalInstance, items, size) {
var $cctrl = this;
  $cctrl.items = items;
  $cctrl.selected = {
    item: $cctrl.items[0]
  };
  $cctrl.size = size;
 // console.log('size in ctrl: ', size);

  $cctrl.ok = function () {
    $uibModalInstance.close($cctrl.selected.item);
  };

  $cctrl.cancel = function () {
    $uibModalInstance.dismiss('cancel');
  };
});
<!doctype html>

    <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
    <link href="style.css" rel="stylesheet">

      <input type="text" ng-model="nameFilter" />
      Order by id
      Order by name
      Order by age

              {{item.name}}

 Age: {{item.age}}

 Company: {{item.company}}

Try like below..
$http.post(url, reqData, config).then(function (response) {
 return response.data; //return your response data directly
}

In ModalInstanceCtrl controller you can get like below.
  $cctrl.modalData = modalData;


text: Q: How do you build your own calorimeter in your garage? I have seen people built their own calorimeter at home but when I messaged them, they didn't reply how exactly they did it. I want to try building one that is similar to this one but I'm not sure how to do it. They had this one at the Uni I previously went to and I could use it for an upcoming project.


text:
Q: Elasticsearch adding custom analyzer to all fields I'm new to Elasticsearch and I created a custom analyzer(See Below)
    "analyzer":{
        "custom-analyzer": {
            "type": "custom",
            "tokenizer": "whitespace"
        }
    }

Now i want to add this analyzer for ALL fields in my mappings, I know I can add to each field like this
"test_field":{
      "type": "text,
       ...
      "analyzer": "custom_analyzer"
 }

This works perfectly but  I have like 50 fields so I dont want to go and add this analyzer line in each field in my mappings, I was wondering if there is a way too add this for ALL fields.
Thanks in advance.

A: In the index settings, define an analyzer named default which defines the analyzer when a field mapping does not define an analyzer.
"settings": {
  "analysis": {
    "analyzer": {
      "default": {
        "type": "custom_analyzer"
      }
    }
  }
}


text:
Q: Generating a countable mutually disjoint collection of arbitarally small measurable sets. More specifically

Assume that X has a collection of arbitarally small measurable sets. Is it possible to then generate a countable mutually disjoint collection of arbitarally small measurable sets.

It is obvious that you can make a countable collection. It isn't so obvious that you can make a disjoint collection.

A: If I understand correctly, the hypothesis is that for every $\epsilon > 0$ there exists $A$ a measurable subset of $X$ such that $\epsilon > m(A) > 0$. You want to show that there exists a sequence of disjoint measurable subsets $A_n$ such that $m(A_n)>0$ and $m(A_n)\to 0$.
Consider a sequence of measurable subsets $B_n$ so that $0<m(B_{n+1})<\frac{1}{2}\cdot m(B_n)$ for all $n\ge 0$.  Now take
$$A_n \colon = B_n \backslash (\cup_{m>n} B_{m})$$
It is easy to see that $m(A_n) > 0$ for all $n$ and $m(A_n)\to 0$. Moreover, the $A_n$'s are pairwise disjoint.


text:
Q: MS Access 2007 - Update a Field in a Table with data from another Table Ok - I have spent 2 hours trying to figure this out. Searching StackOverflow, Google, MSDN etc. I am lost.
I have found apparent valid answers for MSSQL and other SQL platforms in here, but they do NOT work for MS Access 2007 SQL.
Table 1 has fields ID and Name, Table 2 has the same fields.
In Table 1 I need to update the Name field with the same field from Table 2, Joined on the ID fields.
I have tried numerous Update queries to no avail.
UPDATE table1
SET table1.Name = table2.Name
WHERE table1.ID=table2.ID

No worky!
UPDATE table1
SET table1.Name = (
SELECT Name From table2 Where Table2.ID=Table1.ID
)

The dreaded "must use an updateable query" message which I can't figure out a solution to.
UPDATE table1
SET table1.Name=table2.Name
FROM table1 INNER JOIN table2 ON table1.ID = table2.ID

"Syntax error"!
My brain is fried. I swear I have done this numerous times in the past, but can't figure it out. I am sure this is simple and someone has a quick answer.

A: MS Access has slightly different syntax for update with join.  You can try:
UPDATE table1 INNER JOIN
       table2
       ON table1.ID = table2.ID
    SET table1.Name = table2.Name;


text:
Q: Is it possible to register the same class / interface multiple times in Spring4D? I'm currently playing around with the Spring4D framework and think it's pretty cool.  I'm trying to achieve the following
  GlobalContainer.RegisterComponent<TPerson>.Implements<IPerson>('Normal');
  GlobalContainer.RegisterComponent<TPerson>.Implements<IPerson>('TestData').DelegateTo(
    function: TPerson
    begin
      result := TPerson.Create;
      result.SetFirstName('Bob');
      result.SetSurname('Smith');
    end
  );

With TPerson/IPerson having the obvious definitions. But regardless if I try
  Person := ServiceLocator.GetService<IPerson>('Normal');

or
  Person := ServiceLocator.GetService<IPerson>('TestData');

I always get Bob, is this possible or am I doing something wrong?

A: This is fixed in the latest version of Spring4D


text:
Q: Composing Global Classes in CSS Modules from SCSS How do I compose from a global class in CSS Modules, when writing in SCSS?
According to (my understanding of) CSS Module's Composing from global class names documentation, the following should work:
:global {
  .bar {
    color: purple;
  }
}

.my-icon {
  composes: bar from global;
}

But I receive the following error:
referenced class name "bar" in composes not found
How can I change the above to properly compose from a global class?


text:
Q: Which logger should I use to get my data in Cloud Logging I am running a PySpark job using Cloud Dataproc, and want to log info using the logging module of Python. The goal is to then push these logs to Cloud Logging.
From this question, I learned that I can achieve this by adding a logfile to the fluentd configuration, which is located at /etc/google-fluentd/google-fluentd.conf.
However, when I look at the log files in /var/log, I cannot find the files that contain my logs. I've tried using the default python logger and the 'py4j' logger.
logger = logging.getLogger()
logger = logging.getLogger('py4j')

Can anyone shed some light as to which logger I should use, and which file should be added to the fluentd configuration?
Thanks

A: tl;dr
This is not natively supported now but will be natively supported in a future version of Cloud Dataproc. That said, there is a manual workaround in the interim.
Workaround
First, make sure you are sending the python logs to the correct log4j logger from the spark context.  To do this declare your logger as:
import pyspark
sc = pyspark.SparkContext()
logger = sc._jvm.org.apache.log4j.Logger.getLogger(__name__)

The second part involves a workaround that isn't natively supported yet.  If you look at the spark properties file under
/etc/spark/conf/log4j.properties

on the master of your cluster, you can see how log4j is configured for spark.  Currently it looks like the following:
# Set everything to be logged to the console
log4j.rootCategory=INFO, console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.target=System.err
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{yy/MM/dd HH:mm:ss} %p %c: %m%n

# Settings to quiet third party logs that are too verbose
...

Note that this means log4j logs are sent only to the console.  The dataproc agent will pick up this output and return it as the job driver ouput.  However in order for fluentd to pick up the output and send it to Google Cloud Logging, you will need log4j to write to a local file.  Therefore you will need to modify the log4j properties as follows:
# Set everything to be logged to the console and a file
log4j.rootCategory=INFO, console, file
# Set up console appender.
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.target=System.err
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{yy/MM/dd HH:mm:ss} %p %c: %m%n

# Set up file appender.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=/var/log/spark/spark-log4j.log
log4j.appender.file.MaxFileSize=512KB
log4j.appender.file.MaxBackupIndex=3
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.conversionPattern=%d{yy/MM/dd HH:mm:ss} %p %c: %m%n

# Settings to quiet third party logs that are too verbose
...

If you set the file to /var/log/spark/spark-log4j.log as shown above, the default fluentd configuration on your Dataproc cluster should pick it up.  If you want to set the file to something else you can follow the instructions in this question to get fluentd to pick up that file.


text:
Q: How could i create a buttons in a loop i'm trying to create a simple table of buttons in a loop, but my code does not work. There is no errors, but i don't see result of execution.
import sys
from PyQt4 import QtGui, QtCore

names = ['X+', 'X-', 'Y+',\
        'Y-', 'Z+', 'Z-',\
        'A1+', 'A1-', 'A2+',\
        'A2-', 'A3+', 'A3-',\
        'Hand']

pos = [(50, 100), (200, 100), (50, 200),\
        (200,200), (50, 300), (200,300),\
        (370, 100), (520, 100), (370, 200),\
        (520, 200), (370, 300), (520, 300),\
        (50, 400)]

size = [(74, 74), (74, 74), (74, 74),\
        (74, 74), (74, 74), (74, 74),\
        (74, 74), (74, 74), (74, 74),\
        (74, 74), (74, 74), (74, 74),\
        (226, 74)]

class Window(QtGui.QMainWindow):

    ...........

    def createButtons(self):
        index = 0
        self.buttons = []

        for i in names:
            self.buttons.append(index)
            self.buttons[index] = QtGui.QPushButton(self)
            self.buttons[index].setText(i)
            self.buttons[index].setGeometry(pos[index][0], pos[index][1], size[index][0], size[index][1])
            index += 1

def runApp():
    app = QtGui.QApplication(sys.argv)
    gui = Window()
    gui.createButtons()
    gui.show()
    sys.exit(app.exec_())

runApp()

Can you help me?
names - a list of names,
pos - a list of position[x,y],
size - a list of w and h.

A: You only need to change the size so you can see the buttons. You must use resize()
import sys
from PyQt4 import QtGui, QtCore

names = ['X+', 'X-', 'Y+',\
        'Y-', 'Z+', 'Z-',\
        'A1+', 'A1-', 'A2+',\
        'A2-', 'A3+', 'A3-',\
        'Hand']

pos = [(50, 100), (200, 100), (50, 200),\
        (200,200), (50, 300), (200,300),\
        (370, 100), (520, 100), (370, 200),\
        (520, 200), (370, 300), (520, 300),\
        (50, 400)]

size = [(74, 74), (74, 74), (74, 74),\
        (74, 74), (74, 74), (74, 74),\
        (74, 74), (74, 74), (74, 74),\
        (74, 74), (74, 74), (74, 74),\
        (226, 74)]

class Window(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent=parent)

    def createButtons(self):
        index = 0
        self.buttons = []

        for i in names:
            self.buttons.append(index)
            self.buttons[index] = QtGui.QPushButton(self)
            self.buttons[index].setText(i)
            self.buttons[index].setGeometry(pos[index][0], pos[index][1], size[index][0], size[index][1])
            index += 1

        self.resize(650, 500)

def runApp():
    app = QtGui.QApplication(sys.argv)
    gui = Window()
    gui.createButtons()
    gui.show()
    sys.exit(app.exec_())

runApp()

Screenshot:


text:
Q: Automate creating configurations from template and excel I'm having trouble in automation of a configuration.
I have a template of a configuration and need to change all the hostname (marked as YYY) and IP (marked as XXX(only 3rd octet needs replacement)) according to a list of excel values.
Now I have a list of 100 different sites and IPs and I want to have also 100 different configurations.
A friend suggested to use the following Powershell code but it doesn't any create files..:
    $replaceValues = Import-Csv -Path "\\ExcelFile.csv"
    $file = "\\Template.txt"
    $contents = Get-Content -Path $file

    foreach ($replaceValue in $replaceValues)
    {
            $contents = $contents -replace "YYY", $replaceValue.hostname
            $contents = $contents -replace "XXX", $replaceValue.site
        Copy-Item $file "$($file.$replaceValue.hostname)"
        Set-Content -Path "$($file.$replaceValue.hostname)" -Value $contents
        echo "$($file.$replaceValue.hostname)"
     }

A: Your code tries to overwrite the same $contents string in the loop, so if the values are replaced the first time you enter the loop, there won't be any YYY or XXX values to replace left..
You need to keep the template text intact, and create a new copy from the template inside the loop. That copy can then be altered the way you want. Every next iteration wil then start off with a fresh copy of the template.
There is no need to first copy the template text to a new location and then overwrite this file with the new contents. Set-Content is happy to create a new file for you if it does not already exist.
Try
$replaceValues = Import-Csv -Path 'D:\Test\Values.csv'
$template      = Get-Content -Path 'D:\Test\Template.txt'

foreach ($item in $replaceValues) {
    $content = $template -replace 'YYY', $item.hostname -replace 'XXX', $item.site
    $newFile = Join-Path -Path 'D:\Test' -ChildPath ('{0}.txt' -f $item.hostname)
    Write-Host "Creating file '$newFile'"
    $content | Set-Content -Path $newFile
}


text:
Q: Why is `write()` performed via a `call` instruction instead of an interrupt? I was trying to play a bit in assembly.
My understanding is that sys calls are made through an interrupt generated by the syscall instruction.
However after compiling a simple program on my computer using clang -S:
int main() {
  write(0, "HI", 2);
  return 0;
}

The relevant assembly generated is:
    movl    $0, -4(%rbp)
    leaq    L_.str(%rip), %rsi
    movl    $2, %edx
    movb    $0, %al
    callq   _write

Why is that ?
Is there a way to see the actually sys call being performed on OS X ?

A: Because you're calling a function from the C standard library. That function may or may not wrap a syscall, could use an unexpected syscall (e.g. a more modern one than the original), and generally has to perform various setup and teardown operation to adapt between the C and syscall calling conventions.
The wrapper is usually fairly thin, but it's still a wrapper (e.g. on linux syscalls usually return either a success or -errno in case of failure, the libc then has to check for failure, stash the errno in the corresponding threadlocal and return the "proper" value defined by the standard or POSIX instead).

A: As @user207421 mentioned in the comment write being a C standard library function must eventually wrap a platform specific write system call. In MacOS facade layer is defined in libsystem_kernel.dylib which is utilised by MacOS C standard library implementation libSystem.B.dylib. The system calls number are not public interface and are subject to change across MacOS versions. Furthermore to excellent @fuz point some of them might even become obsolete and have no direct syscall entry/number anymore but will remain supported by the wrapper layer.
When you launch your program you can verify the actual syscall in action in lldb with:
lldb ./a.out
b write
run
* thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
    frame #0: 0x00007fff63e0f040 libsystem_kernel.dylib`write
libsystem_kernel.dylib`write:
->  0x7fff63e0f040 <+0>:  mov    eax, 0x2000004
    0x7fff63e0f045 <+5>:  mov    r10, rcx
    0x7fff63e0f048 <+8>:  syscall
    0x7fff63e0f04a <+10>: jae    0x7fff63e0f054            ; <+20>
Target 0: (a.out) stopped.
(lldb)


text:
Q: Permitir acceso FTP a enlace simbólico fuera de la "jaula" del usuario Hola utilizo vsftpd bajo debían y habilitando chroot_local_user eh enjaulado a todos los usuarios en su carpeta home mediante:

local_root=/home/$USER/ftp

Ahora e insertado un enlace simbólico dentro de su carpeta ah otra carpeta fuera de su directorio home pero no pueden acceder a el mediante FTP (si mediante shell) ¿Alguna idea de como configurar correctamente esto?

A: Pienso que no puedes hacerlo porque un link simbólico no es realmente un punto de montaje sino una referencia a otro archivo. Ves la referencia, pero como el archivo está fuera de tu alcance no puedes entrar a esa "carpeta".
Lo que puedes hacer es crear un verdadero punto de montaje usando la opción bind.
mount --bind /mi_carpeta /home/nombre_usuario/mi_carpeta

Eso durará hasta que se reinicie la máquina, por lo que te aconsejo probar mi sugerencia, ver si resulta y en caso afirmativo, crear una entrada en tu /etc/fstab señalando
/mi_carpeta /home/nombre_usuario/mi_carpeta none defaults,bind 0 0

Eso sobrevivirá a los reinicios.


text:
Q: Deep Q Learning **WITHOUT** OpenAI Gym Does anyone have or know of any tutorials / courses that teach q learning without the use of open ai gym.
I'm trying to make a convolutional q learning model and I have no problem doing this with pytorch and open ai gym, easy! but when I try and apply it all to an environment that isn't in open ai gym its a whole different story, trying to apply this to other games that aren't Atari so I don't have access to the env.reset and all those other nice options, it becomes a whole new ball game. If someone knows of a place to learn this or who is willing to teach me / help me with it I am more than willing to pay for any help as well.
Thanks.

A: If you want to make deep learning algorithms work for games, you can actually use openai gym for that!
The workaround
You can use from PIL import ImageGrab to take a screenshot, and control the game using pyautogui Then load it with opencv, and convert it to a greyscale image. Then you can use this code for the Q-Learning:
# imports for DQNAgent
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Dropout, Conv2D, MaxPooling2D, Activation, Flatten
from tensorflow.keras.optimizers import Adam
from keras.callbacks import TensorBoard
import tensorflow as tf
from collections import deque
import time
import random
import os

# Hide GPU from visible devices
# (If you don't have a GPU, uncomment the next line)
#tf.config.set_visible_devices([], 'GPU')

DISCOUNT = 0.99
REPLAY_MEMORY_SIZE = 50_000  # How many last steps to keep for model training
MIN_REPLAY_MEMORY_SIZE = 1_000  # Minimum number of steps in a memory to start training
MINIBATCH_SIZE = 64  # How many steps (samples) to use for training
UPDATE_TARGET_EVERY = 5  # Terminal states (end of episodes)
MODEL_NAME = 'BOX'

# Exploration settings
ELIPSON_DECAY = 0.999988877665
MIN_EPSILON = 0.0001

# For stats
ep_rewards = [-200]

# For more repetitive results
random.seed(1)
np.random.seed(1)

# Memory fraction, used mostly when training multiple agents
#gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=MEMORY_FRACTION)
#backend.set_session(tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)))

# Create models folder
if not os.path.isdir('models'):
    os.makedirs('models')

# Own Tensorboard class
class ModifiedTensorBoard(TensorBoard):

    # Overriding init to set initial step and writer (we want one log file for all .fit() calls)
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.step = 1
        self.writer = tf.summary.create_file_writer(self.log_dir)

    # Overriding this method to stop creating default log writer
    def set_model(self, model):
        pass

    # Overrided, saves logs with our step number
    # (otherwise every .fit() will start writing from 0th step)
    def on_epoch_end(self, epoch, logs=None):
        self.update_stats(**logs)

    # Overrided
    # We train for one batch only, no need to save anything at epoch end
    def on_batch_end(self, batch, logs=None):
        pass

    # Overrided, so won't close writer
    def on_train_end(self, _):
        pass

    # Custom method for saving own metrics
    # Creates writer, writes custom metrics and closes writer
    def update_stats(self, **stats):
        self._write_logs(stats, self.step)

# Agent class
class DQNAgent:
    def __init__(self, env):
        self.env = env

        # Main model
        self.model = self.create_model()

        # Target network
        self.target_model = self.create_model()
        self.target_model.set_weights(self.model.get_weights())

        # An array with last n steps for training
        self.replay_memory = deque(maxlen=REPLAY_MEMORY_SIZE)

        # Custom tensorboard object
        self.tensorboard = ModifiedTensorBoard(log_dir="logs/{}-{}".format(MODEL_NAME, int(time.time())))

        # Used to count when to update target network with main network's weights
        self.target_update_counter = 0

    def create_model(self,):
        model = Sequential()

        observation_space = 60000, IMAGE_WIDTH, IMAGE_HEIGHT, 1
        action_space = self.env.action_space.n

        model.add(Conv2D(32, (3, 3), activation='relu', input_shape=observation_space[1:]))
        model.add(Activation('relu'))
        model.add(MaxPooling2D(pool_size=(2, 2)))
        model.add(Dropout(0.2))

        model.add(Conv2D(256, (3, 3)))
        model.add(Activation('relu'))
        model.add(MaxPooling2D(pool_size=(2, 2)))
        model.add(Dropout(0.2))

        model.add(Flatten())  # this converts our 3D feature maps to 1D feature vectors
        model.add(Dense(64))

        model.add(Dense(action_space, activation='linear'))  # ACTION_SPACE_SIZE = how many choices (9)
        model.compile(loss="mse", optimizer=Adam(lr=0.001), metrics=['accuracy'])
        return model

    # Adds step's data to a memory replay array
    # (observation space, action, reward, new observation space, done)
    def update_replay_memory(self, transition):
        self.replay_memory.append(transition)

    # Trains main network every step during episode
    def train(self, terminal_state, step):

        # Start training only if certain number of samples is already saved
        if len(self.replay_memory) < MIN_REPLAY_MEMORY_SIZE:
            return

        # Get a minibatch of random samples from memory replay table
        minibatch = random.sample(self.replay_memory, MINIBATCH_SIZE)

        # Get current states from minibatch, then query NN model for Q values
        current_states = np.array([transition[0] for transition in minibatch])/255
        current_qs_list = self.model.predict(current_states)

        # Get future states from minibatch, then query NN model for Q values
        # When using target network, query it, otherwise main network should be queried
        new_current_states = np.array([transition[3] for transition in minibatch])/255
        future_qs_list = self.target_model.predict(new_current_states)

        X = []
        y = []

        # Now we need to enumerate our batches
        for index, (current_state, action, reward, new_current_state, done) in enumerate(minibatch):

            # If not a terminal state, get new q from future states, otherwise set it to 0
            # almost like with Q Learning, but we use just part of equation here
            if not done:
                max_future_q = np.max(future_qs_list[index])
                new_q = reward + DISCOUNT * max_future_q
            else:
                new_q = reward

            # Update Q value for given state
            current_qs = current_qs_list[index]
            current_qs[action] = new_q

            # And append to our training data
            X.append(current_state)
            y.append(current_qs)

        # Fit on all samples as one batch, log only on terminal state
        self.model.fit(np.array(X)/255, np.array(y), batch_size=MINIBATCH_SIZE, verbose=0, shuffle=False, callbacks=[self.tensorboard] if terminal_state else None)

        # Update target network counter every episode
        if terminal_state:
            self.target_update_counter += 1

        # If counter reaches set value, update target network with weights of main network
        if self.target_update_counter > UPDATE_TARGET_EVERY:
            self.target_model.set_weights(self.model.get_weights())
            self.target_update_counter = 0

    # Queries main network for Q values given current observation space (environment state)
    def get_qs(self, state):
        return self.model.predict(np.array(state).reshape(-1, *state.shape)/255)[0]

Dont't forget to replace IMAGE_WIDTH and IMAGE_HEIGHT!
In your env.update function, take a screenshot, and update the replay memory of the agent with agent.update_replay_memory. Then in the same function, use agent.train. To get the next move of the agent, use agent.get_qs.
import random, time, gym, cv2
from PIL import ImageGrab
import pyautogui

class MyEnv(gym.Env):
    def __init__(self):
        super().__init__(self)

        self.observation_space = gym.Box()
        self.action_space = gym.Discrete(N_ACTIONS) #number of controls

        self.model = DQNAgent()
        self.previous_observation = None

    def step(self, action):
        # Conditional logic for what to do with actions
        # an example
        if action == 0:
            pyautogui.press('w') # Go forwards
            reward = 1

        shot = np.array(ImageGrab.grab(bbox=("""x, y, width, height of game window""")))
        gray = cv2.cvtColor(Screen, cv2.COLOR_BGR2GRAY)
        if self.previous_observation is not None:
            self.model.update_replay_memory((self.previous_observation, action, reward, gray))

        self.prevoius_observation = gray

        # check if the player has lost, and call self.reset()

        return observation, action, reward, {}

    def reset(self):
        # reset the game (re-open it, or something like that)

env = MyEnv()
epsilon = 0.1
decay = 0.99998
min = 0.001
steps = 60000

# open the game here
# ...

for i in range(0, steps):
    if random.random() < epsilon:
        env.step(env.action_space.sample())
        elipson *= decay
    else:
        try:
            env.step(env.model.get_qs(env.previous_observation))

env.reset()
env.model.save('models/player.h5')
# close the game here
# ...

A: You can take a code of an environnement such as a game and then you implement your algorithms.
But think to be explicit in your code for the rewards and the actions. Return a reward for each action.
If you want to start RL without Gym. Try to do a simple game and implement NEAT algorithm. And then try to implement Q-learning and modify your code to add a reward for each action.


text:
Q: How do you change which vehicle to give custom plate GTA V Online PC I've seen videos of people customizing their cars and they put their plate on in the LS Customs, however when I tried it, I was unable to find an option for that. I downloaded the app and tried to do it from there, but I was only able to do it to one vehicle, and there is no option to change vehicle. Is there a better way to do this? Am I missing something?

A: Once you have navigated to the garage tab under Los Santos customs you will need to scroll past the three main character's cars. At the bottom of the tab you should see your Rockstar Social Club account. Any cars that you currently have stored in your multiplayer garage will show up here. You can swipe left or right to navigate through the cars that are currently stored in your garage.
I looked into this a little further, and some people have encountered a bug where it will only show them the latest car they stored in their garage (I do not have this bug, I am able to swipe left/right to select my car). So you might possibly try driving the car you want to edit out of your garage, and then driving it back in again. Annoying and time-consuming, but it seems to work for other players that have encountered this bug.


text:
Q: Bad request when running ASP.NET 2.0 application I am developing website in ASP.NET 2.0. I am running a page. In button click event I deal with data readers (first it gives me different error). So I debug it, and when I debug my 2 datareaders, then it gives me the error HTTP 400 bad request. I don't know how to recover. I check path but it is correct.

A: I think there may be a permission problem to this file. But I can't really some thing accurate unless you give us more information about your problem.


text:
Q: IOS : Unable to setup GCM using cordova plugin phonegap-plugin-push I have set provisioning profiles, certificates and cocoapods by following:
https://developers.google.com/cloud-messaging/ios/client link.
I do not know whether I have to register in APNS through cocoapod or cordova plugin and how to do it. GCM is not registering through ios device. I would prefer to not use native code, I am new to both xcode and cordova.

A: cocoapod is only the dependency management tool for Objective-C and Swift. So my guess is that you'll have to register it on  a Cordova plugin. I think this pubnub tutorial will be beneficial to on how to set it up using phonegap/cordova.
Hope it helps!


text:
Q: SQLDelight FTS5 insert trouble I created a table in DBBrowser:
CREATE VIRTUAL TABLE IF NOT EXISTS Students USING FTS5
(
    GroupId          UNINDEXED,
    StudentName
);

and insert values to it. After that I add DB with this table to my project.
It is declaration of this table in sqldelight .sq file:
CREATE VIRTUAL TABLE IF NOT EXISTS Students USING FTS5
(
    GroupId          INTEGER AS Int,
    StudentName      TEXT,
    rank             REAL
);

I need to explicit declare rank because I want to apply HAVING MIN(rank) for it when SELECT from table (otherwise it is not compile), but when I trying to insert values in table like that:
insert:
INSERT INTO Students VALUES (?,?);

I receive an error:

Unexpected number of values being inserted. found: 2 expected: 3

If I do like that:
insert:
INSERT INTO Students VALUES (?,?,?);

I receive an exception:

SQLiteException - table Students has 2 columns but 3 values were supplied (code 1): , while compiling: INSERT INTO Students VALUES (?,?,?)

How I can perform insert? Or maybe I can apply HAVING MIN(rank) without explicit declare?

A: does
insert:
INSERT INTO Students(GroupId, StudentName) VALUES (?,?);

work?


text:
Q: Casting error with a native SQL query JPA Eclipse Link I'm working with JPA implemented with EclipseLink. I need to do a native SQL query about my MRAEmpleado entity.
This is my code:
    private List<MRAProyecto> ordenarProyectos (){
      Query q = em.createNativeQuery("Select *From MRAProyecto ORDER BY PROY_ID");
       return (List<MRAProyecto>)q.getResultList();
    }
        List<MRAProyecto> consultaProyectos = startup.ordenarProyectos();
        System.out.println("Lista de proyectos ordenados por su identificador");
         for (MRAProyecto proyecto:(List<MRAProyecto>)consultaProyectos){

             System.out.println(proyecto.toString());
        }

but This error is launched when I execute my application:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to entity.MRAProyecto
at Startup.main(Startup.java:39)

I have tried with all casting posibilities, but the cast error doesn't dissapear.

A: Use the following call to do the parse.
Query     createNativeQuery(java.lang.String sqlString, java.lang.Class resultClass)
          Create an instance of Query for executing a native SQL query.
http://docs.oracle.com/javaee/6/api/javax/persistence/EntityManager.html#createNativeQuery%28java.lang.String,%20java.lang.Class%29
You need to define in resultSetClass the entitiy you want to retrieve


text:
Q: Using Custom AWS Lambda Runtimes with asp.net core Recently amazon announced support for a custom .net core runtime: https://aws.amazon.com/blogs/developer/announcing-amazon-lambda-runtimesupport/
My current aws lambda project is written C# using the .NET Core 2.1; 2.2 is not supported yet hence I'd like to use custom runtime.
However, it seems that in order to use the custom runtime, it is necessary to use LambdaBootstrap.
From the docs it is not clear to me if it is possible to use it alongside asp.net core:
https://github.com/aws/aws-lambda-dotnet/tree/master/Libraries/src/Amazon.Lambda.RuntimeSupport
p.s. currently my aws lambda is using asp.net core for authentication and other

A: Here's a good demo / tutorial that shows how the author approaches using the lambda bootstrap:
https://medium.com/@dimoss/asp-net-core-2-2-3-0-serverless-web-apis-in-aws-lambda-with-a-custom-runtime-and-lambda-warmer-ce19ce2e2c74
The author uses the following code to switch between local debugging and the lambda entry:
public class LocalEntryPoint
{
    private static readonly LambdaEntryPoint LambdaEntryPoint = new LambdaEntryPoint();
    private static readonly Func<APIGatewayProxyRequest, ILambdaContext, Task<APIGatewayProxyResponse>> Func = LambdaEntryPoint.FunctionHandlerAsync;

    public static async Task Main(string[] args)
    {
#if DEBUG
        BuildWebHost(args).Run();
#else
        // Wrap the FunctionHandler method in a form that LambdaBootstrap can work with.
        using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(Func, new JsonSerializer()))

        // Instantiate a LambdaBootstrap and run it.
        // It will wait for invocations from AWS Lambda and call the handler function for each one.
        using (var bootstrap = new LambdaBootstrap(handlerWrapper))
        {
            await bootstrap.RunAsync();
        }
#endif
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}


text:
Q: How to link manually created ViewControllers into TabBar application i created a tabBar app with ARC. So the default set up would automatically provide 2 viewControllers;
1) FirstViewController.h,FirstViewController.m;FirstViewController_iPhone.xib, FirstViewController_iPad.xib
2) SecondViewController.h, SecondViewController.m, SecondViewController_iPhone.xib, SecondViewController_iPad.xib
I wanted to create a new view controller 'ViewController3' but during the file creation process, i can only opt to create for iPad or just iPhone (checkbox 'Targeted for iPad'). I need both iPhone and iPad xibs just like the FirstViewController and SecondViewControllers created for me. So i decided to create the xib manually and continued with the file creation without xibs.
So naturally after that i went on to manually create 2 news xibs; ThirdViewController_iPhone.xib and ThirdViewController_iPad.xib
i added this line into the  original AppDelegeate file:
UIViewController *viewController1, *viewController2, *viewController3;
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
    viewController1 = [[FirstViewController alloc] initWithNibName:@"FirstViewController_iPhone" bundle:nil];
    viewController2 = [[SecondViewController alloc] initWithNibName:@"SecondViewController_iPhone" bundle:nil];
    viewController3 = [[ThirdViewController alloc] initWithNibName:@"ThirdViewController_iPhone" bundle:nil];
} else {
    viewController1 = [[FirstViewController alloc] initWithNibName:@"FirstViewController_iPad" bundle:nil];
    viewController2 = [[SecondViewController alloc] initWithNibName:@"SecondViewController_iPad" bundle:nil];
    viewController3 = [[ThirdViewController alloc] initWithNibName:@"ThirdViewController_iPad" bundle:nil];
}
self.tabBarController = [[UITabBarController alloc] init];
self.tabBarController.viewControllers = [NSArray arrayWithObjects:viewController1, viewController2, viewController3, nil];

I then run the project and got this: Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UIViewController _loadViewFromNibNamed:bundle:] loaded the "ThirdViewController_iPhone" nib but the view outlet was not set.'
How do i set the outlet?

A: For your ThirdViewController_iPhone.xib, follow the instruction here. I think you need to do this step:

*

*You should see "outlets" with "view" under it. Drag the circle next to it over to the "view" icon on the left bar


text:
Q: "Asymptotic " transformation for principal curvature lines on positive Gauss curvature K surfaces If we have lines of curvature for a  $ \mathbb R^2 $ surface in 3-space $ $(x,y,z)$  as
$$ [ f(u,v), \ g(u,v), \ h(u,v) ] $$
for negative Gauss curvature surfaces then
$$  f(u+v,u-v), g(u+v,u-v) , h(u+v,u-v) $$
represent asymptotic lines whose normal curvature vanishes.
What is characteristic about the corresponding lines for positive K surfaces? What are its properties? I appreciate any remarks.. intuitive, qualitative, or equation-based regarding what curvature vanishes or remains constant, or basically why is it not considered important or interesting.
EDIT1:
How do lines rotate in tangent plane by virtue of such transformation in either case? Secondly are they conceptually linked to (eg Struik's Differential Geometry book) "Imaginaries in surface theory"?

A: If I understand, you're asking:
Let $M$ be a surface in Euclidean $3$-space and $p$ a point of $M$. If the Gaussian curvature at $p$ is negative, then the asymptotic directions at $p$ can be expressed as "linear combinations" of the principal directions. What do the corresponding linear combinations means if the Gaussian curvature is positive at $p$?

Assuming that's correct:
Let $k_{1}$ and $k_{2}$ be the (non-zero) principal curvatures of $M$ at $p$. By a Euclidean motion, we may assume $p$ is the origin, and $T_{p}M$ is the $(x, y)$-plane with the coordinate axes as principal directions. In a sufficiently small neighborhood of $p$, the surface $M$ is a graph
$$
z = \tfrac{1}{2}(k_{1} x^{2} + k_{2}y^{2}) + o(x^{2} + y^{2}).
$$
For purposes of curvatures, we may neglect the higher-order terms and look at the quadratic approximation.
The asymptotic directions at $p$ are the lines of intersection (if any) of $\{z = 0\}$, the tangent plane at $p$, with the graph $z = \tfrac{1}{2}(k_{1} x^{2} + k_{2}y^{2})$. If the Gaussian curvature $k_{1} k_{2}$ is negative, put $k^{2} = -k_{1}/k_{2}$ and write
$$
0 = \tfrac{1}{2}(k_{1} x^{2} + k_{2}y^{2})
  = -\tfrac{1}{2} k_{2} (k^{2}x^{2} - y^{2})
  = -\tfrac{1}{2} k_{2} (kx - y)(kx + y).
$$
That is, the asymptotic directions are the lines $y = \pm kx$.
If the Gaussian curvature is positive, by contrast, the preceding factorization is non-real: Putting $k^{2} = k_{1}/k_{2}$, we have
$$
0 = \tfrac{1}{2}(k_{1} x^{2} + k_{2}y^{2})
  = \tfrac{1}{2} k_{2} (k^{2}x^{2} + y^{2})
  = \tfrac{1}{2} k_{2} (kx - iy)(kx + iy).
$$
Geometrically, the graph of a positive- or negative-definite quadric touches the tangent plane only at the point of tangency, so long as we work over the reals. In that sense, the corresponding directions are non-real, and therefore "uninteresting".
(Incidentally, if $M$ is real-analytic, then $M$ can be viewed locally as the "real points" of a complex surface in $\mathbf{C}^{3}$ by "allowing the power series variables to be complex". In this setting, the preceding factorization has geometric meaning. In retrospect there's no mystery, however, since all quadratic forms are equivalent over $\mathbf{C}$.)


text:
Q: How to count number of duplicates in a list of tuples? I have a python list of tuples as shown below:
listoftups = [('A', 'B'), ('C','D'), ('E','F'), ('G','H'), ('A','B'), ('C','D')]

I want to count the number of duplicates in this list of tuples and want the output as follows:
A -> B 2
C -> D 2
E -> F 1
G -> H 1

How can I do this in python? I was thinking about using counter but not sure. Thank You.

A: You can use Counter
listoftups = [('A', 'B'), ('C','D'), ('E','F'), ('G','H'), ('A','B'), ('C','D')]
from collections import Counter
for k, v in Counter(listoftups).most_common():
    print "{} -> {} {}".format(k[0], k[1], v)

Output
A -> B 2
C -> D 2
G -> H 1
E -> F 1

A: You can use the list's count method:
listoftups = [('A', 'B'), ('C','D'), ('E','F'), ('G','H'), ('A','B'), ('C','D')]
tup = listoftups.count(('A', 'B')) # returns 2

and to count them all into a dictionary:
result = dict()
for tup in set(listoftups):
    result[tup] = listoftups.count(tup)

or more succinctly with a dictionary comprehension:
result = {tup:listoftups.count(tup) for tup in set(listoftups)}

After you would have a dictionary of:
result = { ('A', 'B'): 2, ('C', 'D'): 2, ('E','F'): 1, ('G', 'H'): 1}

and you can print it the same way that fourtheye does it or:
for k, v in result.items():
    print k[0] + "->" + k[1] + " ", v

A: import collections
result = collections.defaultdict(int)
def f(tup):
    result[tup] += 1
map(lambda t: f(t), listoftups)

defaultdict(<type 'int'>, {('G', 'H'): 1, ('A', 'B'): 2, ('C', 'D'): 2, ('E', 'F'): 1})

A: First of all, get a list with non-duplicated items using a set. Then iterate through them, and print them in the format desired, using count:
listoftups = [('A', 'B'), ('C','D'), ('E','F'), ('G','H'), ('A','B'), ('C','D')]

listoftups = list(set(listoftups))
for el in listoftups:
    print "{} -> {} {}".format(el[0], el[1], listoftups.count(el))

If you want to preserve the order, create the unique values like this:
tmp = []
for el in listoftups:
    if el not in tmp:
        tmp.append(el)

And then do the for loop i did in the first example.

A: from collections import Counter

tuples = [('A', 'B'), ('C', 'D'), ('E', 'F'), ('G', 'H'), ('A', 'B'), ('C', 'D')]

counted = Counter(tuples).most_common()

s_t = sorted(counted, key=lambda x: x[0][0])

for key, value in s_t:
    print key, value

The above code will also sort according to the value of the first string in the tuple.
Console session:
>>> from collections import Counter
>>> tuples = [('A', 'B'), ('C', 'D'), ('E', 'F'), ('G', 'H'), ('A', 'B'), ('C', 'D'), ('C', 'D'), ('C', 'D')]
>>> counted = Counter(tuples).most_common()
>>> counted
Out[8]: [(('C', 'D'), 4), (('A', 'B'), 2), (('G', 'H'), 1), (('E', 'F'), 1)]
>>> sorted_tuples = sorted(counted, key=lambda x: x[0][0])
>>> sorted_tuples
Out[10]: [(('A', 'B'), 2), (('C', 'D'), 4), (('E', 'F'), 1), (('G', 'H'), 1)]


text:
Q: Selecting which parts of an email mutt saves Using the ignore function it is possible to cherry pick which header information is displayed in the pager.
This works perfectly.
Saving mail, using the standard s bound functionality or a tagged ;s batch still includes all of the cruft. It does not matter if I save in the mailbox overview or from inside the pager.

A: The decode-save function, bound to <Esc>s, or the decode-copy function, bound to <Esc>C, should do what you want, although they may do more decoding of the message than you want.


text:
Q: Why does Nservicebus not use WCF? I see that NServiceBus uses MSMQ as its transport. Why doesn't it use WCF with MSMQ as the underlying transport?

A: The primary reason was that the MSMQ code was written before WCF even existed. As time progressed, most of the work focused on adding new features rather than revisiting the already solution MSMQ integration.
There's also things that NServiceBus does with respect to MSMQ that WCF doesn't do. For example, NServiceBus will create a queue if it doesn't exist. This makes it much smoother to work with NServiceBus than with WCF.
This does not imply that this functionality could not be preserved if migrated to work on top of WCF/MSMQ but the main thing is that it is just too low a priority as compared to all the other things slated for the next release.

A: Once you realise that the Microsoft of today is a lot of teams who may (or most likely) may not use each others code. The NserviceBus guys made a decision that they didn't want to use WCF for whatever reason, and that's that.
Years ago, I was at a conference where a guy from MS was telling us about MTS and I asked him why the security groups in there didn't use Local Groups (ie WinNT security groups). He ummed and ahhem and said "yes, I see where you're coming from with that question, next question please". See, the group security in MTS was exactly the same as local groups were designed for - but the MTS guys decided that they would implement their own groups and ignore the underlying NT security system. I would be really nice if we could have 1 place to set security and have it apply to all Microsoft products, but that's not the way it goes. even by Microsoft's own devs.


text:
Q: Handling variables in function with parallel spawning in Python I have a Monte Carlo simulator that has a calculation function it calls many (millions or more) times in a loop.  In order to speed this up, I would like split it into multiple parallel thread calls to the simulator.  ie.  If I want a to run it a total of 1 million times, split it up into maybe 4 - 250,000 runs all going in parallel.  With each thread using the same variable names, how do I handle this so there are no clashes?  Do I have to create 4 seperate versions of my simulator with differently named variables?
I have started to write a version using the Python threading module, but am certain there will still be issues with the variables.
Any suggestions?
Thanks for your time.
Kyle

A: If your code is pure Python, and you are using CPython, threading likely won't speed up your code due to the global interpreter lock.  What you are probably looking for is the multiprocessing module, specifically its Pool.map() method.
Since using mulitprocessing means using separate processes instead of just separate threads, things like locking will become much less an issue.
That said, vectorising your code using NumPy or writing the inner loop in an efficient compiled language like C or Cython are likely to give you much more speed-up than parallelising it to four cores.


text:
Q: Simple SharePoint Flow to Send Email Issues I am at a loss of 4+ hours trying to understand why this flow will not work. I have SharePoint Library with a Yes/No choice column for whether a file Needs Updating that I want to trigger an email. Everything I try either results in the condition being false which it shouldn't be or the flow failing. Here is my latest code that fails. Originally I wasn't using the value version of the field and the flow would run but result in a false condition even when the Needs Updating field was set to Yes. I also was using is equal to Yes, but then I read another thread that suggested you should use the expression true. I'm unsure of what to do/try next. This should have been a 10 minute job. It has to be something silly that I am missing.
I am using NeedsUpdating Value as condition field.

Another pic after changed from True to Yes

A: The problem is that your condition assumes that theNeesUpdating field is a yes/no field. However, NeesUpdating field is simply a text/choice field. So you can't compare text to the boolean values (true and false).
So, to fix the issue, simply update your Condition to compare with Yes like on the screenshot below:

Remember, you don't need any quotes or formula, you simply need to type Yes in the condition.


text:
Q: Error while submit link on reddit with php curl I am trying to submit link Post on reddit.com using php curl. I am having  access token of user but i am unable to post on reddit and getting an error code 403. Here is sample code what I am trying to execute :
$subreddit='funny';
$kind='link';

$postVals = sprintf("kind=%s&sr=%s&title=%s&r=%s",
            $kind,
            $subreddit,
            urlencode('Test Post'),
            $subreddit);
$postVals .= "&url=" . urlencode( 'http://seextra.com');

$urlSubmit = "http://www.reddit.com/api/v1/submit";
$ch = curl_init($urlSubmit);
$options = array(
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CONNECTTIMEOUT => 5,
    CURLOPT_TIMEOUT => 10
);

if (!empty($_SERVER['HTTP_USER_AGENT'])){
    $options[CURLOPT_USERAGENT] =      $_SERVER['HTTP_USER_AGENT'];
}

if ($postVals != null){
    $options[CURLOPT_POSTFIELDS] = $postVals;
    $options[CURLOPT_CUSTOMREQUEST] = "POST";
}

$headers = array("Authorization:bearer".$access_token , "User-Agent:".$_SERVER['HTTP_USER_AGENT']);
$options[CURLOPT_HEADER] = false;
$options[CURLINFO_HEADER_OUT] = false;
$options[CURLOPT_HTTPHEADER] = $headers;
$options[CURLOPT_USERPWD] = Reddit_Client_Id . ":" . Reddit_Client_secret;

// Reddit_Client_Id client id
// Reddit_Client_secret secret key
$options[CURLOPT_SSLVERSION] = 4;
$options[CURLOPT_SSL_VERIFYPEER] = false;
$options[CURLOPT_SSL_VERIFYHOST] = 2;
pr($options);

curl_setopt_array($ch, $options);
$apiResponse = curl_exec($ch);
$response = json_decode($apiResponse);
curl_close($ch);
print_r($response);

Here is response from reddit :
stdClass Object
(
    [error] => 403
)

Could you help me out regarding this.
Thanks,
Sachin


text:
Q: How to sort an Array using If in PHP I have the following Array which contains data such as: Card, Month and Year. However, I receive it in a disorganized way and I would like to treat these values to follow the pattern. No Card, Year and Month or Month, Card and Year. I tried to use the sort() functions of php, but without success!
Array                                                                                (
[0] => Array
(
    [0] => 5522 8600 0000 0000
    [1] => 2020
    [2] => 09
)

[1] => Array
(
    [0] => 09
    [1] => 5522 8600 0000 0000
    [2] => 2020
)

[2] => Array
(
    [0] => 5522 8600 0000 0000
    [1] => 20
    [2] => 9
)
)

I would like to create a function in which the Array is organized as follows:
 Array                                                                                (
    [0] => Array
    (
        [0] => 5522 8600 0000 0000
        [1] => 09
        [2] => 2020
    )

    [1] => Array
    (
        [0] => 5522 8600 0000 0000
        [1] => 09
        [2] => 2020
    )

    [2] => Array
    (
        [0] => 5522 8600 0000 0000
        [1] => 9
        [2] => 20
    )
)

Then comes the point of conditions, if as the Array the year 2020 is defined with only 2 decimal places, that is, 20 (19, 20, 21, 22, 23, ...) I would check if the value does not is greater than 12, following the number of months we have in 1 year, knowing this, to identify the year in this Array, I would apply another validation to check if the value is greater than 12 and if it has 2 or 4 digits, however I can't apply it in any way!
Thank you very much in advance!

A: As per your comment you can go with this solution:
$finalArray = [];
foreach($array as $key=>$arr){
    $arry = [];
    foreach($arr as $ar){

        if(strlen($ar) > 4){
            $arry[0] = $ar;
        }else if((strlen($ar) ==1 || strlen($ar) == 2) && (int)$ar <=12){
            $arry[1] = $ar;
        }else{
            $arry[2] = $ar;
        }
    }
    ksort($arry);
    $finalArray[$key] = $arry;
}

print_r($finalArray);

Output: https://3v4l.org/BZIFX

A: We can do this by comparing the number of values in the array then assign them the index position by going through the loop within the array.
But there is an issue.
[0] => Array
(
    [0] => 5522 8600 0000 0000
    [1] => 20
    [2] => 20
)

According to your scenario, at one point you are showing 2020 as 20. So this can be possible that it can be a date too as I mentioned the above array. So by using this approach every logic will become failed.


text:
Q: Reordering Columns in a Gridview Dynamically I have a gridview I'm trying to reorder the columns for, but I'm getting an object not found error.
The code works when I don't include the code under "//code to move columns", but when I include that code, I get an object not found error that "s += txtAD.Text.Trim();" object reference is not set to an instance. It's weird because no matter which columns I switch, it always throws the error that it can't find column 1.
Any ideas?
My HTML:
<asp:GridView ID="gridviewtxSLds" ClientIDMode="Static" runat="server" CssClass="gridclassscrolledtx" CellPadding="0" ForeColor="#333333" AutoGenerateColumns="False">
    <Columns>
        <asp:TemplateField HeaderText="Metric">
            <ItemTemplate>
                <asp:TextBox runat="server" Text='<%# Bind("item") %>'
                    ID="txtctrltype" class="modalpopup2" AutoPostBack="false"></asp:TextBox>
            </ItemTemplate>
            <HeaderStyle HorizontalAlign="Center" />
            <ItemStyle HorizontalAlign="Center" />
        </asp:TemplateField>
        <asp:TemplateField HeaderText="AD">
            <ItemTemplate>
                <asp:TextBox runat="server" Text='<%# Bind("AD") %>'
                    ID="txtAD" onfocus="blur()" class="txttime" AutoPostBack="false" ReadOnly="false"></asp:TextBox>
            </ItemTemplate>
            <HeaderStyle HorizontalAlign="Center" />
            <ItemStyle HorizontalAlign="Center" />
        </asp:TemplateField>
        <asp:TemplateField HeaderText="BD">
            <ItemTemplate>
                <asp:TextBox runat="server" Text='<%# Bind("BD") %>'
                    ID="txtBD" onfocus="blur()" class="txttime" AutoPostBack="false" ReadOnly="false"></asp:TextBox>
            </ItemTemplate>
            <HeaderStyle HorizontalAlign="Center" />
            <ItemStyle HorizontalAlign="Center" />
        </asp:TemplateField>
        <asp:TemplateField HeaderText="CD">
            <ItemTemplate>
                <asp:TextBox runat="server" Text='<%# Bind("CD") %>'
                    ID="txtCD" onfocus="blur()" class="txttime" AutoPostBack="false" ReadOnly="false"></asp:TextBox>
            </ItemTemplate>
            <HeaderStyle HorizontalAlign="Center" />
            <ItemStyle HorizontalAlign="Center" />
        </asp:TemplateField>
    </Columns>
</asp:GridView>

code in codebehind to fill gridview
using (var cmdtx2 = new SqlCommand(sqlcmd, conn))
{
    DataTable dv = new DataTable();
    SqlDataAdapter db = new SqlDataAdapter(cmdtx2);

    //code to move columns
    var columnMove = gridviewtxSLds.Columns[3];
    gridviewtxSLds.Columns.RemoveAt(3);
    gridviewtxSLds.Columns.Insert(2, columnMove);

    db.Fill(dv);
    gridviewtxSLds.DataSource = dv;
    gridviewtxSLds.DataBind();
}

Update code, which throws the error:
protected void Bulk_Insert(object sender, EventArgs e)
{
    var timeinitid = hfptstate.Value;
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < gridviewtxSLds.Rows.Count; i++)
    {
        #region textbox declarations
        TextBox txtitem = gridviewtxSLds.Rows[i].FindControl("txtctrltype") as TextBox;
        TextBox txtAD = gridviewtxSLds.Rows[i].FindControl("txtAD") as TextBox;
        TextBox txtBD = gridviewtxSLds.Rows[i].FindControl("txtBD") as TextBox;
        TextBox txtCD = gridviewtxSLds.Rows[i].FindControl("txtCD") as TextBox;
        #endregion textbox declarations

        #region command string
        string s = "update 1874tx set AD";
        s += "='";
        //following line throws the error
        s += txtAD.Text.Trim();
        s += "', ";
        s += "BD";
        s += "='";
        s += txtBD.Text.Trim();
        s += "', ";
        s += "CD";
        s += "='";
        s += txtCD.Text.Trim();
        s += "' where item";
        s += "='";
        s += txtitem.Text.Trim();
        s += "';";
        #endregion
        sb.Append(s.ToString());
        SqlCommand cmd = new SqlCommand(sb.ToString(), con);
        con.Open();
        cmd.ExecuteNonQuery();
    }
}

Edit: And before anyone comments on concatenation of SQL queries, I know, and for this specific use it doesn't matter.


text:
Q: I created a UIAlertController using UIAlertControllerStyleActionSheet and then added some buttons, but prompted me to have a layout problem I created a UIAlertController using UIAlertControllerStyleActionSheet and then added some buttons, but prompted me to have a layout problem. I am sure my code is fine, but I don't know where the problem is, please let me know if you know the reason.
And I tested the style as UIAlertControllerStyleAlert and didn't have this problem.
My project only supports iphone and does not support iPad. My development environment: Xcode: 10.2.1, iOS: 12.3.1
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"title" message:@"message" preferredStyle:UIAlertControllerStyleActionSheet];

    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"cancle" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        //NSLog(@"");
    }];

    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"sure" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        //NSLog(@"");
    }];

    [alertController addAction:cancleAction];
    [alertController addAction:sureAction];
    [self presentViewController:alertController animated:true completion:nil];

Debug output area printing:
[LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fix it.
(
    "<NSLayoutConstraint:0x282e9c5a0 UIView:0x1019286f0.width == -16>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x282e9c5a0 UIView:0x1019286f0.width == -16>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.


text:
Q: How to achieve following result in Javascript? I have a code like this:
var exist_file = document.getElementById('exist_file').value;
        document.getElementById('dialog-confirm-upload').innerHTML=

             "The file" +
             for (var i=0;i<exist_file.length;i++){
                 exist_file + ","
             }

             +
             "has been already transferred? Do you want to overwrite?"

exist_file is an array which contains one or more than one element: ['hello', 'ok']. I want to pass the value to innerHTML like this.
 "The file hello, ok has been already transferred? Do you want to overwrite?" I tried the following above code but it turns out that's not a valid syntax. How can I achieve this?

A: var exist_file = document.getElementById('exist_file').value,
     msg = "The file" + exist_file.toString() + "has been already transferred? Do you want to overwrite?";
    document.getElementById('dialog-confirm-upload').innerHTML= msg;

This snippet works for both cases where exist_file is an array or a string.

A: First you have to parse the string into an array, then you can format it with commas:
var exist_file = document.getElementById('exist_file').value;
document.getElementById('dialog-confirm-upload').innerHTML=
  "The file " +
  exist_file.substr(3, exist_file.length - 5).split("', u'").join(", ") +
  " has already been transferred. Do you want to overwrite?"

Note: This is the most basic form of parsing. It works with strings containing regular characters, but escaped characters are not unescaped.


text:
Q: how to find tomcat server system information using java code? i am developing web application and i host it in tomcat server. my requirement is client system wants to know the ip address of the system where the tomcat server located in a network.Before make any request to the server using java.or any possible to set default ip address for the tomcat server.and how can i use the default ip address to make a request if system ip and tomcat ip are different.

A: I don't know if I understood your question right. So the server is running in a local area network and your client software does not know which address/ip to connect to? You could add a multicast server to your servers app and a multicast receiver to your clients. The server will send a boardcast packet frequently to a specified boardcast address/channel, i.e. 203.0.113.0.
Once your client starts, it will receive the boardcast packet send by the server, as long as he is connected to the same channel. The packet is containing the servers address. You can than use that address to connect to the server.
Update
This is a very simplyfied example of a sender, receiver and a constants class to share the settings. It sends a String (Server is here) as packet data, but in a real world application, you should create an object serialize it at the server and deserialize it at the client. That object could hold more information about the server an could be verified at client side.
Server/Client side shared code:
public final class MulticastConstants {
 public static final String MULTICAST_PACKET_DATA = "Server is here!";
 public static final String MULTICAST_CHANNEL = "230.0.0.1";
 public static final int MULTICAST_PORT = 8881;
 public static final int MULTICAST_PACKET_SIZE = MULTICAST_PACKET_DATA.getBytes().length;
}

Server Side code:
The sender is a WebListener and will start and stop with your application.
@WebListener
public class MulticastSender implements ServletContextListener {

private MulticastSocket socket;
private boolean running = true;
private Thread mcss;

public MulticastSender() {
    System.out.println("New " + this.getClass().getSimpleName());
    try {
        socket = new MulticastSocket(MulticastConstants.MULTICAST_PORT);
        mcss = new MulticastServerThread();
    } catch (IOException e) {
        System.out.println("Error creating MulticastSender: " + e.getMessage());
    }
}

@Override
public void contextInitialized(ServletContextEvent sce) {
    System.out.println("Starting " + this.getClass().getSimpleName());
    mcss.start();
}

@Override
public void contextDestroyed(ServletContextEvent sce) {
    System.out.println("Stopping " + this.getClass().getSimpleName());
    this.running = false;
    socket.disconnect();
    socket.close();
}

private class MulticastServerThread extends Thread {

    public MulticastServerThread() {
        super("MulticastServer");
    }

    public void run() {

        System.out.println("Start sending multicast packets ...");
        while (running) {
            System.out.println("Sending multicast packet ...");
            try {
                byte[] dataBuffer = MulticastConstants.MULTICAST_PACKET_DATA.getBytes();
                InetAddress group = InetAddress.getByName(MulticastConstants.MULTICAST_CHANNEL);
                DatagramPacket packet = new DatagramPacket(dataBuffer, dataBuffer.length, group, MulticastConstants.MULTICAST_PORT);
                socket.send(packet);
                System.out.println("Packet send ...");
                try {
                    sleep(2000);
                } catch (InterruptedException e) {
                }
            } catch (IOException e) {
                System.out.println("Error sending multicast packet: " + e.getMessage());
                running = false;
                break;
            }
        }
        socket.close();
    }
}
}

Client side code:
The client only receives a single packet for simplicity. You might create a thread to not to freeze your clients gui.
public class MulticastReceiver {

private MulticastSocket socket;
private InetAddress address;

public static void main(String[] args) throws InterruptedException {
    new MulticastReceiver();
}

public MulticastReceiver() {
    System.out.println("Starting MulticastReceiver ...");
    try {
        address = InetAddress.getByName(MulticastConstants.MULTICAST_CHANNEL);
        socket = new MulticastSocket(MulticastConstants.MULTICAST_PORT);
        socket.joinGroup(address);

        DatagramPacket packet;
        try {
            byte[] buf = new byte[MulticastConstants.MULTICAST_PACKET_SIZE];
            packet = new DatagramPacket(buf, buf.length);
            System.out.println("Waiting for packets ...");
            socket.receive(packet);
            System.out.println("Received a packet (" + packet.getLength() + " bytes) ...");
            // deserialize packet.getData() to your own object (for simplicity a String is used) ...
            // check if type and serialVersionId are ok, otherwise dispose packet ...
            System.out.println("Server is located at: " + packet.getAddress());
            socket.close();
            // connect to server ...
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    } catch (UnknownHostException e) {
        System.out.println("Could not connect to host \"" + address + "\": " + e.getMessage());
    } catch (Exception e) {
        System.out.println("Error initializing: " + e.getMessage());
    }
}
}

Tested on Glassfish 4, hope that helps.


text:
Q: ES6 equivalent to SQL cross join Is there a way in JS to take these two arrays, scenarios and items, and essentially cross join them to end up with the output shown in result?
const scenarios = ['a/2020-12-01', 'b/2020-12-04'];
const items = ['201/17', '201/28', '207/3', '208/4', '208/12'];

const result = [
    'a/2020-12-01/201/17', 'a/2020-12-01/201/28', 'a/2020-12-01/207/3', 'a/2020-12-01/208/4', 'a/2020-12-01/208/12',
    'b/2020-12-04/201/17', 'b/2020-12-04/201/28', 'b/2020-12-04/207/3', 'b/2020-12-04/208/4', 'b/2020-12-04/208/12'
];

I have had no success searching online for how to do this - possibly because I don't know the correct name for what this is in JS terminology.

A: You can do this with .reduce and .map as follows:

const scenarios = ['a/2020-12-01', 'b/2020-12-04'];
const items = ['201/17', '201/28', '207/3', '208/4', '208/12'];

const res = scenarios.reduce((acc,scen) => {
  acc.push(
    ...items.map(item => `${scen}/${item}`)
  );
  return acc;
}, []);

console.log(res);

Another simple solution using two for-loops:

const scenarios = ['a/2020-12-01', 'b/2020-12-04'];
const items = ['201/17', '201/28', '207/3', '208/4', '208/12'];

const res = [];

for(let i = 0; i < scenarios.length; i++)
  for(let j = 0; j < items.length; j++)
    res.push(`${scenarios[i]}/${items[j]}`);

console.log(res);

A: Use Array.flatMap() to iterate the scenarios and flatten the results, with Array.map() to iterate the items, and combine them with the scenarios:

const scenarios = ['a/2020-12-01', 'b/2020-12-04'];
const items = ['201/17', '201/28', '207/3', '208/4', '208/12'];

const res = scenarios.flatMap(scen =>
  items.map(item => `${scen}/${item}`)
);

console.log(res);


text:
Q: How does port publishing from a docker container to a kubernetes pod work? While working through the tutorial Get Started, Part 3: Deploying to Kubernetes I stumbled over the Pod template within the deployment definition of the manifest file. There are no ports specified, neither in the pod nor in the container section.
That led me to my initial question: How does the port publishing work from the docker container into the pod?
The following quote sounds like kubernetes obtains an insight into the running container once started and gets the port from the service listening at 0.0.0.0:PORT and maps it to the same port in the pod environment (network namespace).

Not specifying a port here DOES NOT prevent that port from being exposed. Any port which is listening on the default "0.0.0.0" address inside a container will be accessible from the network. Source

If my assumption goes in the right direction, what does this mean for pods with multiple containers? Does kubernetes only allow containers with internal services listening on different ports? Or is it possible to map the container internal ports to different ports in the pod environment (network namespace)?
According to the following quote, I assume port mapping from container to pod is not possible.
Indeed it does not make too much sens to specify two services within two containers with the same ports, just to change them via a mapping immediately following this.

Exposing a port here gives the system additional information about the network connections a container uses, but is primarily informational. Source

UPDATE 2019-10-15
As the following quote states, a docker container does not publish any port to the outside world by default.

By default, when you create a container, it does not publish any of its ports to the outside world. To make a port available to services outside of Docker, or to Docker containers which are not connected to the container's network, use the --publish or -p flag. Source

That means kubernetes must configuer the docker container running within a pod somehow, so that the container's ports are published to the pod.
Regarding the following quote, is it possible that kubernetes runs the docker containers by using the --network host configuration? Assumed the pod is the docker host in kubernetes.

If you use the host network mode for a container, that container's network stack is not isolated from the Docker host [...] For instance, if you run a container which binds to port 80 and you use host networking, the container's application is available on port 80 on the host's IP address. Source

A: Containers running in a pod are similar to processes running on a node connected to a network. Pod gets a network address, and all containers share the same network address. They can talk to each other using localhost.
A container running in a pod can listen to any port on that address. If there are multiple containers running in a pod, they cannot bind to the same port, only one of them can. Note that there is no requirement about publishing those ports. A container can listen to any port, and traffic will be delivered to it if a client connects to that port of the pod.
So, port mapping from container to pod is not possible.
The exposed ports of containers/pods are mainly informational, and tools use them to create resources.


text:
Q: Проблема получения токена OAuth Хотелось бы разобраться, как получить токен авторизации для запроса на Twitch API.
В документации API есть вот такой запрос.
GET https://id.twitch.tv/oauth2/authorize
?client_id=<your client ID>
&redirect_uri=<your registered redirect URI>
&response_type=<type>
&scope=<space-separated list of scopes>

В этом запросе мне непонятен redirect_uri.
Токен мне нужен для разовых запросов на API, например для получения ID канала, а не для приложения.


text:
Q: tkinter getting slow after initiating some custom made ttk.Frame I am trying to create GUI for calculating all travel expenses. It's not finished yet due to a problem where at the certain point tkinter is getting very slow. I have no idea what I did wrong.
I made most of the widgets as a class. Everything is fine until I try to make TravelReportExpensesFrame(ttk.Labelframe) with a a few ExpenseFrame(ttk.Frame).
The creation of the class is in class TravelReportPicker(ttk.Frame) in method travel_id_cbo_index_change(self) [gui.py, line 515]. If you want to see the difference. Run gui.py with and without lines 535, 536, 537, where I actually call the creation of TravelReportExpensesFrame(ttk.Labelframe).
I ran cProfile and the difference (with/without) is significant  while the mainloop cumtime call is about the same.
{method 'call' of '_tkinter.tkapp' objects}
with three lines mentioned above:
ncalls  tottime  percall  cumtime  percall
77780/10976   43.917    0.001   46.279    0.004

without 3 lines:
ncalls  tottime  percall  cumtime  percall
1622/1224    0.660    0.000    0.683    0.001

I am relatively new to python. This is my first post and I am not native english speaker, so please be gentle with me.
I published my code at github and the link is below.
Here is the whole project


text:
Q: duplicate names are being created even when I choose an option from the predefined dropdown list Hi all I am trying to use Ruby on Rails Devise to create a new Company that a User belongs_to. While I am able to create associated company objects (under fields_for), new company objects with duplicate names are being created even when I choose an option from the predefined dropdown list. By right I should be able to select the option from the dropdown list. How can I amend my codes such that I can select and use an option from the dropdown list instead of creating a new object with duplicate names?
My codes are as shown below:-
#new.html.erb

<% resource.build_company %>
<%= form_for resource, as: resource_name, url: registration_path(resource_name), :html => {class: "ui small form"} do |f| %>

   <%= f.fields_for :company do |builder| %>
     <%= builder.select :name, Company.all.collect{ |p| [p.name, p.id] }, {prompt: "Company"}, :class => "company_options ui fluid search selection dropdown"  %>
   <%end%>

<%= f.submit "Sign up" %>

#companies_controller.rb

class Users::RegistrationsController < Devise::RegistrationsController
  before_action :configure_sign_up_params, only: [:create]

  protected

  def configure_sign_up_params
    devise_parameter_sanitizer.permit(:sign_up, keys: [:lastname, :firstname,company_attributes:[:name]])
  end
end

#user.rb

class User < ApplicationRecord
  belongs_to :company
  accepts_nested_attributes_for :company
end

#company.rb

class Company < ApplicationRecord
  has_many :users
end

A: Instead of building a new company and accepting nested attributes for the new company, just allow to choose a company_id:
# in your view
<%= f.collection_select :company_id, Company.all, :id, :name %>

# in your controller
def configure_sign_up_params
  devise_parameter_sanitizer.permit(:sign_up, keys: [:lastname, :firstname, :company_id])
end

And remove the accepts_nested_attributes_for :company line from your User model.