text:
Q: android 5 and onClick in xml layout I have set android:onclick in xml for an imageButton and put that method in my activity. In android s below 5 it works fine but in android 5 it gives me Error.
My imageButton code:
<ImageButton
     android:id="@+id/photo_detail"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:src="@drawable/detail_icon"
     android:layout_alignParentLeft="true"
     android:layout_centerVertical="true"
     android:background="@drawable/image_background"
     android:onClick="photoDetailButtonMethod"/>

My method code:
public void photoDetailButtonMethod(View theButton)
{
  //something
}

The error:
java.lang.IllegalStateException: Could not find a method photoDetailButtonMethod(View) in the activity class android.view.ContextThemeWrapper for onClick handler on view class android.widget.ImageButton with id 'photo_detail'
            at android.view.View$1.onClick(View.java:3994)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
     Caused by: java.lang.NoSuchMethodException: photoDetailButtonMethod [class android.view.View]
            at java.lang.Class.getMethod(Class.java:664)
            at java.lang.Class.getMethod(Class.java:643)
            at android.view.View$1.onClick(View.java:3987)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

By looking the error I can see it searching for my method in android.view.ContextThemeWrapper class so it endup with NoSuchMethodException.
I can't figure out how to solve this, any help?
1) I already added tools:context=".PhotoViewerActivity" in the root of my layout.
2) The activiy extends ActionBarActivity with appCompat theme.

A: i can't find what is the real problem, maybe some incompatiblity between eclipse and api 21 or something else.
for now i just set an onClickListener for that button.

A: finally i found the problem.
all i need is to associate the xml layout to an activity. for this in the design tab of xml layout make sure you selected the right activity.

A: It happens when you have declared the public void onClick(View view) method inside the fragment instead of activity

A: I had a very similar problem, it happens only on Android Lollipop, whilst it works fine on the older versions. Looks like a bug or undocumented feature in 5.0.
Make sure that in the layout file where your ImageButton resides there is no android:theme set, i.e. nothing like this:
android:theme="@style/Base.Theme.AppCompat.Light"

Instead, define your application theme in AndroidManifest.xml application element:
<application
         ...
         android:theme="@android:style/Theme.Holo.Light"
         ...  >

A: Be sure that your onClick method
public void photoDetailButtonMethod(View theButton)
{
  //something
}

is written outside onCreate() method and in your Activity class.

A: I was doing this with a "menuItem", and had this:
public void photoDetailButtonMethod(View theButton)
{
  //something
}

Which is wrong for menuItems. Then you must have this:
public void photoDetailButtonMethod(MenuItem theButton)
{
  //something
}

It was throwing the same error as mentioned by the OP.
Hope this helps someone...

A: Its just google play services issue and nothing to do with your coding or settings blah blah...
just update your google play services of phone and add dependencies in build.gradle file like:
compile 'com.google.android.gms:play-services:7.5.0'


text:
Q: Version control workflow with 'external' binary files I'm working with an embedded system software project right now, and we're facing some problems dealing with some precompiled binaries living inside our repository.
We have several repositories for different parts of our project: One for the application itself, one for the OS, one for the bootloader and several libraries. All of them, except the one for our application, are shared with other teams, for other projects. We are using git (and changing is not an option right now), but I think we'd have the same problem with any VCS.
Right now, we have a precompiled binary for each of those components living inside our application repository. The idea was to speed up the build time, since the OS alone takes about 20 minutes to build from scratch and most guys work only with the application.
Problem is, there are several bugs/features in those binaries (and related application code) to be integrated at any time and, as you know, diffing and merging binaries won't work.
So, how do you guys do when you have to work with those external dependencies?
Thanks a lot =)

A: One viable solution is to use an external binary repository like Nexus.

*

*It is not linked to a VCS, meaning you can easily clean up old versions of said binaries you don't need anymore

*It is light-weight (simple HTTP client-server protocol, no need to clone all the repo with all the versioned binaries like you would with a DVCS -- git or mercurial --)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get inserted row immediately after query execution in cassandra? I am trying to get last inserted row in cassandra but I am getting undefined
Here is how code looks for insert:
const cassandra = require('cassandra-driver');
const client = new cassandra.Client({ contactPoints: ['h1', 'h2'], keyspace: 'ks1' });

let query = "INSERT INTO users (id, name, email ) values (uuid(), ?, ?)";

client.execute(query, [ 'badis', 'badis@badis.com' ])
  .then(result => console.log('User with id %s', result.rows[0].id));

A: Remember you are dealing with NoSQL ("non relational")

If I were to run a SELECT * FROM users LIMIT 1 on this table, my
  result set would contain a single row. That row would be the one
  containing the lowest hashed value of username (my partition key),
  because that's how Cassandra stores data in the cluster. I would have
  no way of knowing if it was the last one added or not, so this
  wouldn't be terribly useful to you.

The workings are very different from those that you might be used to in MySQL.
If obtaining the last inserted row's information is needed for your system, then you will have to know it before you insert it.
Generating UUID
const Uuid = require('cassandra-driver').types.Uuid;
const id = Uuid.random();

Then you can use the id as another value for the prepared insert query
const cassandra = require('cassandra-driver');
const client = new cassandra.Client({ contactPoints: ['h1', 'h2'], keyspace: 'ks1' });

let query = "INSERT INTO users (id, name, email ) values (?, ?, ?)";

client.execute(query, [id, 'badis', 'badis@badis.com' ])
  .then(result => console.log('User with id %s', id));


text:
Q: Accessing items in lists within dictionary python I have a dictionary that has keys associated with lists.
mydict = {'fruits': ['banana', 'apple', 'orange'],
         'vegetables': ['pepper', 'carrot'],
         'cheese': ['swiss', 'cheddar', 'brie']}

What I want to do is use an if statement that if I search for item and its in any of the lists within the dictionary it will return the key. This is what I was trying:
item = cheddar
if item in mydict.values():
    print key

but it doesn't do anything, the output should be:
cheese

This seems like a simple thing but I just can't figure it out. Any help is awesome.

A: mydict = {'fruits': ['banana', 'apple', 'orange'],
     'vegetables': ['pepper', 'carrot'],
     'cheese': ['swiss', 'cheddar', 'brie']}

item = "cheddar"

for key, values in mydict.iteritems():
    if item in values:
        print key

If you are going to do a lot of this kind of searching, I think you can create a reverse index for the original mydict to speed up querying:
reverse_index = {}

for k, values in mydict.iteritems():
     for v in values:
         reverse_index[v] = k

print reverse_index.get("cheddar")
print reverse_index.get("banana")

This way you don't have to traverse the values list every time to find an item.

A: mydict = {'fruits': ['banana', 'apple', 'orange'],
     'vegetables': ['pepper', 'carrot'],
     'cheese': ['swiss', 'cheddar', 'brie']}

item = "cheddar"
if item in mydict['cheese']:
    print ("true")

this works, but you have to reference the keys in the dictionary like cheese, vegetables etc instead because of the way you made the dictionary, hope this helps!

A: You'll have to use a for, a simple if is not enough to check an unknown set of lists:
for key in mydict.keys():
    if item in mydict[key]:
        print key

An approach without an explicit for statement would be possible like this:
foundItems = (key for key, vals in mydict.items() if item in vals)

which returns all keys which are associated with item. But internally, there's still some kind of iteration going on.


text:
Q: $V \subset H \subset V^*$, what's $\langle h, v \rangle_{V^*, V}$? If $V \subset H \subset V^*$ is Hilbert triple, and $h \in H$ what's $\langle h, v \rangle_{V^*, V}$?
I know we interpret it to be $(h,v)_H$. But is this correct:
$$\langle h, v \rangle_{V^*, V} := \langle Rh, v\rangle_{V^*, V} = Rh(v) = (h,v)_H$$
where $R:H \to H^*$ is the Riesz map and the last equality follows by Riesz representation.
I am still a bit confused about the relation between $V$ and its dual and what we identify and what we don't.

A: There are three maps in play here:

*

*the embedding $\iota : V \to H$,

*its transpose, the embedding $\iota^T : H^\ast \to V^\ast$,

*and the Riesz (anti)isomorphism $R : H \to H^\ast$.

In particular, the inclusion $H \to V^\ast$ is actually given by the composition $\iota^T \circ R$. Thus,
$$ \left\langle h,v \right\rangle_{V^\ast,V} := \left\langle (\iota^T \circ R)(h), v\right\rangle_{V^\ast,V} = \left\langle R(h),v \right\rangle_{H^\ast,H} = \left(h,v\right)_H,$$ as you indeed computed.
EDIT: Note that since $V$ will be a proper subspace of $H$, endowed with a topology (typically, that of a nuclear Fréchet space) finer than the subspace topology inherited from $H$, you'll really have that $V \subsetneq H \subsetneq V^\ast$.


text:
Q: Updating multiple level properties in Entity Framework I have an entity structure having multiple level of properties, each header table entry has multiple child table entries, and the relation goes through multiple level. Table diagram is shown here:

I need to get all data related to one entry in ECNEntries table to display in a grid. The user may edit the entries, delete some, add more entries at all levels.
I can get all the data for a particular entry like this:
var ECNEntryInDb = ECNEntriesRepo.FindAll(f => f.ECNStages
                                .Select(i => i.ECNComponentDetails
                                    .Select(j => j.ECNMaterialReferenceDetails
                                        .Select(k => k.ECNComponentDetails))))
                                        .Where(x => x.Id == ECNEntriesData.Id).FirstOrDefault();

But I can't find a way to update this data back to the database.
When I tried like this:
var xx = Mapper.Map<DAL.Entities.ECNEntries>(ECNEntriesData);
ECNEntriesRepo.Update(xx);

I'm getting an exception:

Attaching an entity of type 'ProductionControl.DAL.Entities.ECNEntries' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

And when I tried this:
var ECNEntryInDb = ECNEntriesRepo.FindAll(f => f.ECNStages
                                    .Select(i => i.ECNComponentDetails
                                        .Select(j => j.ECNMaterialReferenceDetails
                                            .Select(k => k.ECNComponentDetails)))).Where(x => x.Id == ECNEntriesData.Id).FirstOrDefault();
                                //var ECNEntryInDb = ECNEntriesRepo.FindById(ECNEntriesData.Id);

Mapper.Map<BL.DTO.ECN.ECNEntries, DAL.Entities.ECNEntries>(ECNEntriesData, ECNEntryInDb);
ECNEntriesRepo.Update(ECNEntryInDb);

This is what I get:

The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

I tried some solutions suggested in this page like adding composite keys and all. It didn't work either.
Gives an exception like:

Adding a relationship with an entity which is in the Deleted state is
  not allowed

This is the sample data structure:

"EcnEntries": [
                {
                    "Id": 49,
                    "ECNHeaderId": 11,
                    "ECNVersionId": 8,
                    "ECNVersion": null,
                    "ECNPartNumber": "280384-01/01M",
                    "ECNStages": [
                        {
                            "Id": 25,
                            "ECNEntriesId": 49,
                            "OperationNo": "006",
                            "WorkCenterId": 198,
                            "ChangesRequired": "asxa",
                            "ReasonForChanges": "erte",
                            "ECNComponentDetails": [
                                {
                                    "Id": 31,
                                    "ECNStagesId": 25,
                                    "CurrentBOMPartNumber": "jhjhk",
                                    "ReplacementComponentPartnumber": "uyuyuy",
                                    "ECNMaterialReferenceDetails": [
                                        {
                                            "Id": 38,
                                            "ECNComponentDetailsId": 31,
                                            "MaterialReferenceNumber": "323"
                                        },
                                        {
                                            "Id": 39,
                                            "ECNComponentDetailsId": 31,
                                            "MaterialReferenceNumber": "12"
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                }
            ]

EDIT
This is what the Update function in the repository implementation does. How can i change the status of the referencing child table objects also?
public void Update(T entity)
        {
            contextFactory.GetDataContext().Entry(entity).State = EntityState.Modified;
        }

Can anyone suggest a way to update this data? Do I need to iterate through each child and update the data? In that case also I'm confused how to iterate through the data coming from UI and the entity from the database simultaneously to apply the change. I'm not sure if I'm messing up something which is really simple.
Thanks in advance.

A: As @jdweng said, the problem was with Automapper.
Found this link useful.
The automapper was replacing the referencing child table objects, which eventually set the reference to null. it was triggering the error.


text:
Q: Route cloud not find driver I am new whit Laravel and write my first route , but have my first problem.
Server : Php5.6 + Mysql + apache2 , Linux Mint
First install whit :
 composer create-project laravel/laravel test 5.0 --prefer-dist

And permisions in :
 chmod 777 -R ./storage/ && chmod 777 -R ./bootstrap/

In route php
Route::get('/test',function (){
    echo "Batman like the black color.";
});

This can go to direction localhost/<nameproyect>/test. This not go , but i write for check this route is create fine , write php artisan route:list.
This is a broblem:
[PDOException]
  could not find driver

In php.ini , i have :
extension = pdo.so
extension = pdo_mysql.so

Solution :
sudo apt-get install php-mysql

And other problem :
[2016-11-10 16:15:24] local.ERROR: PDOException: SQLSTATE[HY000] [1045] Access denied for user 'admin'@'localhost' (using password: YES)

Solution whit .env :
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=forge
DB_USERNAME=root
DB_PASSWORD=1234

A: You can install MySQL PDO driver installing php5-mysql

sudo apt-get install php5-mysql


text:
Q: Powershell Script that references a text doc and moves everything NOT in that doc I created a powershell script that copies the name of every file in a given folder (it creates filename.txt, not C:\path\filename.txt) and places it all in a text doc.
I'm now trying to write a powershell script that ONLY copies items to a different directory that are not contained in that text doc.
Any ideas? Thank you all.

A: The following code will do exactly what you're after in a more PowerShell way. Better to use an array to hold the names to be ignored. If you need to use the .txt then just useGet-Content to load the .txt into the $ignoreFiles variable.
#-file gets files only (not folders)
$ignoreFiles = (Get-ChildItem -Path "C:\Users\YOURS" -file).name
$checkFolder = Get-ChildItem -Path "C:\Users\YOURS" -file
$targetFolder = "C:\Users\YOURS"

foreach ($t in $checkFolder){
    if($t.name -notin $ignoreFiles){
        Copy-Item $t.fullname $targetFolder
    }
}

A: #-file gets files only (not folders)
$listPath = "\\server\C$\exclusionpath\list.txt"
$downloadPath = "\\adifferentserver\download\"
$targetFolder = "\\adifferentserver\Processing\"
$ignoreFiles = Get-Content -Path $listPath
$checkFolder = Get-ChildItem -Path $downloadPath -File -Exclude $ignoreFiles -
 Name
foreach ($t in $checkFolder){
#Copy-Item $t.fullname $targetFolder
Copy-Item (Get-ChildItem -Path $downloadPath -File | Where-Object {$_.Name -eq
$t}).FullName $targetFolder
}


text:
Q: OSX 10.10 file change event from dispatch queue I try to monitor file changes on OSX 10.10, starting with a fresh Cocoa application in Xcode, just adding the following code.
If I uncomment the last line in the snippet then I receive the file change events perfectly fine.  But I can not make this last call because it should be a Cocoa GUI application.
I digged through a lot of documentation and can't find my error. Do I have to initialize or start this whole dispatch subsystem somehow?
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
  int fd = open("<FILENAME>", O_EVTONLY);
  if (fd == -1) return;
  dispatch_queue_t qu = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
  if (!qu) {
    printf("can not get queue");
    return;
  }
  unsigned long mask =
    DISPATCH_VNODE_DELETE |
    DISPATCH_VNODE_WRITE |
    DISPATCH_VNODE_EXTEND |
    DISPATCH_VNODE_ATTRIB |
    DISPATCH_VNODE_LINK |
    DISPATCH_VNODE_RENAME |
    DISPATCH_VNODE_REVOKE;
  dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, fd, mask, qu);
  printf("source created\n");
  if (!source) {
    close(fd);
    return;
  }
  printf("source valid\n");
  dispatch_source_set_event_handler(source, ^{
    printf("FILE CHANGED\n");
  });
  dispatch_resume(source);
  printf("source resumed\n");

  // If I call dispatch_main() I will receive the file system events as expected.
  // But as a Cocoa application, I must not call this.
  // Instead, I was under the impression that NSApplicationMain handles this.
  //dispatch_main();
}

A: Grand Central Dispatch objects, such as dispatch sources, are automatically retained and released by ARC in recent versions of the compiler and frameworks.
At the end of your method, the last strong reference to source is lost and ARC is issuing an automatic dispatch_release(source). (It would also release the queue, but the source has another strong reference to that. So, if the source survived, so would the queue.)
You need to keep a strong reference to the source in an instance variable.


text:
Q: Add dynamically TinyMCE Textarea on Newly tabs I using tab's JQuery plugin UI each tab contains TextArea then are manage by TinyMCE librarie.
I want to do : When you click on tab "+" , that add new tab which contains textarea too.
To create new tab with textearea , it's good. The problem is : I can't edit textarea value and if i click on TinyMCE 's option ( like Bold ) : J is null error on Javascript console
My JS Code :
$('li > a.moretxt').click(function(){

    // Number of element in tabs
    var size = $( "#tabs" ).tabs("length");
    // Content to add on new tab
    var content = "
<textarea id=\'txtcontent"+size+"'\' cols=\'60\' rows=\'5\'></textarea>
";
    // Some variable
    var path = '#divcontent'+size;
    var title = 'content'+size;
    var idtxt = 'txtcontent'+size;
    // Add new div Textarea before the end
    $('div#morecontent').before(content);
    //Add control ?
    tinyMCE.execCommand('mceAddControl', true, idtxt);
    // Add new TAB
    $( "#tabs" ).tabs("add",path,title,(size));
    var index = $( "#tabs" ).tabs("option", "selected");

});

The follow code , well add tab with tiny TextArea but it doesn't works ...

A: TinyMCE needs to have the object in the DOM to apply itself. I'm not sure why TinyMCE isn't working as you appear to be are adding the container prior to adding TinyMCE, however if you move the "addControl" to after you've added the new Tab it should work.


text:
Q: Can I run an apk in device while the apk is stored on cloud? Just being curious to know, if it is possible to run any .apk file on my device while the apk file is hosted on a cloud server.
Being curious and thinking of an idea, if it happens? Thanks.

A: No, the APK has to be installed to be run, for conventional definitions of the term "run". You can download the APK from "the cloud" and prompt the user to install it, though.


text:
Q: C# XML Serialization not working as intended I have this class model here:
    public class Config
    {
        public ConnectionConfig ConnectionConfig { get; set; }
        [XmlAttribute(AttributeName="advanced")]
        public bool AdvancedEnabled { get; set; }
    }

    public class ConnectionConfig
    {
        [XmlElement(ElementName = "instance")]
        public List<InstanceConfig> Instances { get; set; }
    }

    public class InstanceConfig
    {
        [XmlText]
        public string Uri { get; set; }
        [XmlAttribute(AttributeName="username")]
        public string Username { get; set; }
        [XmlAttribute(AttributeName="password")]
        public string Password { get; set; }
    }

Serialized it is this XML:
<config advanced="false">
  <ConnectionConfig>
    <instance username="user1" password="123">http://localhost:1234</instance>
    <instance username="user2" password="1234">http://localhost:1235</instance>
    <instance username="user3" password="12345">http://localhost:1236</instance>
  </ConnectionConfig>
</config>

But I want to have a XML like this:
<config advanced="false">
    <instance username="user1" password="123">http://localhost:1234</instance>
    <instance username="user2" password="1234">http://localhost:1235</instance>
    <instance username="user3" password="12345">http://localhost:1236</instance>
</config>

So basically without "ConnectionConfig". But in my model I need "ConnectionConfig" as an own object.
What am I missing or not understanding?
I tried to move the [XmlElement(ElementName = "instance")] attribute to ConnectionConfig but still not my desired output.

A: I haven't verified it, but I think you might need to decorate the ConnectionConfig property to indicate that it is an element in its own right.
public class Config
{
    [XmlElement("ConnectionConfig")]
    public ConnectionConfig ConnectionConfig { get; set; }
    [XmlAttribute(AttributeName="advanced")]
    public bool AdvancedEnabled { get; set; }
}


text:
Q: Which test to perform for significance testing when comparing accuracies from two models I need to perform a test to show that accuracy results from different models are statistically significant (or not). I have been looking into https://www.socscistatistics.com/tests/ but I do not know which test makes sense to perform.
I have multiple models with one accuracy score for each model. Which test should I perform for significance testing?
I have tried using the Single Sample Z Score Calculator, which gave me 3.7261 and T-Test Calculator for 2 Independent Means that returned 2769.93978, but I am not sure whether these tests are appropriate

A: A z test and similar tests are not appropriate since the data are paired.  A better test would be McNemar's test, but this assumes both models predict on a single hold out set.
Even better would be to adopt a proper scoring rule and select models on that criterion.  Frank Harrell writes about this in his book Regression Modelling Strategies if I recall correctly.


text:
Q: Why this task hangs? [TestMethod]
public void Y()
{
    int i = 0;
    new Task(() => i++).Wait();

    Assert.AreEqual(1, i);
}

For what reason is the Task in the above example waiting forever? How should I Wait() for the Task so it does not hang?

A: You did not start the Task. Try this:
[TestMethod]
public void Y()
{
    int i = 0;
    Task task = new Task(() => i++);
    task.Start();
    task.Wait();
    Assert.AreEqual(1, i);
}

or even better (as Damien suggested) use Task.Run():
[TestMethod]
public void Y()
{
    int i = 0;
    Task.Run(() => i++).Wait();
    Assert.AreEqual(1, i);
}

A: There are generally 3 reasons why someTask.Wait "hangs":

*

*You've deadlocked the synchronization context that was captured

*There is no synchronization context at all

*You're waiting for a task that is never started

In the first example, windows forms applications would be a likely scenario but the [TestMethod] attribute tells a different story. You can get out of this mess however by using .ConfigureAwait(false) but before going down this route please read up on the subject. async/await looks easy on the surface but you're treading into a minefield.
In unit test projects you need a test runner that processes messages posted to the synchronization context. This could be a likely problem if you're using a test runner that does not.
However, in your current method you're not starting the task. A task never started never completes.
However, if you start the task you might end up with point 2 above.
Conclusion: Make sure you start your task, and if that still blocks take a look at the unit test framework you're using.
To start the task:
var task = new Task(() => i++);
task.Start();
task.Wait();

Also, in general unless you build some kind of framework around handling tasks you should probably not use new Task(...) at all but instead opt for Task.Run:
Task.Run(() => i++).Wait();

If your test runner supports async/await properly I would rather rewrite the entire method to be async:
[TestMethod]
public async Task Y()
{
    int i = 0;
    await new Task(() => i++);

    Assert.AreEqual(1, i);
}


text:
Q: Scala why flatMap treats (x => x) different than (identity) First, map treats x => x identical than identity
List(1,2,3).map(x => x)   //res0: List[Int] = List(1, 2, 3)
List(1,2,3).map(identity) //res1: List[Int] = List(1, 2, 3)

Now let's transform a List[Option[Int]] into List[Int] discarding all None. We can do that by .flatten. But the point of this question is to understand how flatMap treats identity
val maybeNums = List(Some(1), None, Some(-2), None, None, Some(33))

// Works OK, result = List[Int] = List(1, -2, 33)
maybeNums.flatMap(x => x)
maybeNums.flatMap(x => x.map(identity))

// Not working:
maybeNums.flatMap(identity)

Error:(5, 20) type mismatch;
 found   : Option[Int] => Option[Int]
 required: Option[Int] => scala.collection.GenTraversableOnce[?]

Question: why does maybeNums.flatMap(identity) give a compilation error while maybeNums.flatMap(x => x) works OK?

A: Funny thing i had a similar problem to yours. This behavior is caused by the fact that Option is not GenTraversableOnce but there exists an implicit conversion to one. Compiler informs you what is wrong, but unfortunately as it is the case frequently in Scala it does not point the real reason of a mistake. If your collection was containing elements of GenTraversableOnce type, flatMap method would work just fine.
At first i thought that implicit conversion would solve this problem, but it turns out that eta expansion needs types to match explicitly. What's more interesting is that the following code compiles:
ys.flatMap(identity(_))

I assume that in this case implicit conversion from Option[Int] => Option[Int] to Option[Int] => GenTraversableOnce[Int] happens.
In the case of x => x right x is converted with the previously mentioned implicit conversion so the code compiles

A: A bit more detailed explanation of Lampart's answer.
It comes down to how type inference works in Scala and use of expected types.
For maybeNums.flatMap(???) to work, ??? must have type Option[Int] => GenTraversableOnce[?A] (where ?A stands for some unknown type). That's the expected type.
When ??? is a lambda expression like x => x, the argument is typed as Option[Int] and the body is typed with the expected type GenTraversableOnce[?A]. The type of the body without expected type is Option[Int], so the implicit conversion from Option[Int] to GenTraversableOnce[Int] is found and inserted.
When ??? is identity, it's short for identity[?B] for some yet unknown type ?B (in the same sense as ?A above, but they don't have to be the same, of course), and so has type ?B => ?B. So the compiler needs to solve an equation with two unknown types: ?B => ?B == Option[Int] => GenTraversableOnce[?A]. It matches argument types to pick ?B = Option[Int] for ?B, but can't find a suitable ?A. When the error is printed, ?B is substituted and the type which I wrote as ?A above is printed as ? (because it's the only remaining unknown).
In case identity(_), it's expanded to x => identity(x). Again, the type of the argument is inferred to be Option[Int] and the body has calculated type Option[Int] and expected type GenTraversableOnce[?A].


text:
Q: Using PHP in Joomla 2.5, is there a decent way to create groups without going through the menu or SQL? I have been working on a custom component but now hit on an issue where I need to set up groups for ACL reasons. However, I cannot seem to find a valid method - I've crashed things so far. The group setup happens in the installation script, or at least should. A previous answer suggested this:
    JModelLegacy::addIncludePath( JPATH_ADMINISTRATOR .
                    '/components/com_users/models/', 'UsersModel' );
    $groupModel = JModelLegacy::getInstance( 'Group', 'UsersModel' );

    $groupData = array(
        'title' => "NHCommision",
        'parent_id' => 5,
        'id' => 9
    );

    $groupModel->save( $groupData );

However, it doesn't seem to be working in the final version of 2.5. Based on the "Legacy" add it might be ment for 3.0 - is there a 2.5 equivalent?


text:
Q: Edit category listing in adding a new post screen of WordPress admin I have 2 menus to add a new post to Wordpress database, one is type "post" of default Wordpress and one custom type is "listing".
These posts belong to different categories type. And the thing I want to do is, how can I customize "category selection" when I add a new post in default WordPress screen so it can have both categories of type "post" itself as well as all categories for "listing" type.


text:
Q: How to modify Gatsby Starter Lightbox to query specific image directories? I'm trying to utilize the Lightbox component from Gatsby Starter Lightbox to display a few image galleries on different pages.
As the starter component is setup by default, it only supports one directory of images, as set in gatsby-config.js
   `gatsby-plugin-styled-components`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `cars`,
        path: `${__dirname}/src/images/cars/`,
      },

Then in pages/index.js it passes the Lightbox component all of the images.
<Lightbox images={data.allImageSharp.edges} />

    allImageSharp {
      edges {
        node {
          sizes(maxWidth: 1800) {
            ...GatsbyImageSharpSizes
          }
        }
      }
    }

So I'm trying to figure out how to provide it a custom set of images, based on different image directories.
I'm new to Gatsby and React and couldn't figure out how to filter allImageSharp by directory, but I did figure out a way with allFile...though I ran into a type error trying to use it.
What I tried:
  gallery: allFile(filter: {relativeDirectory: {eq: "screenshots/producta"}, extension: {regex: "/(jpg)|(png)/"}}) {
    edges {
      node {
        id
        name
        relativeDirectory
        extension
      }
    }
  }

But in trying to utilize that with:
<Lightbox images={props.data.gallery} />

I got the error "TypeError: images.map is not a function"

A: So I think I may have figured it out. What I've done appears to be working, but I would caution that I don't know how "right" or good of a solution it is.
I seemed to have been on a working path earlier in my question, but had a few things off.
Here's what I've done:
I updated my query so it would return childImageSharp for each node, so now it's returning the equivalent of what was being returned in with allImageSharp from the starter pack. However, this structure is slightly different, so I also had to update the Lightbox.js component to properly reference these changes. You'll notice that my query has a subfield called 'fluid', instead of 'sizes'. This is because I noticed 'sizes' is deprecated in Gatsby 2.x. Fluid appears to return the same fields though. So I updated 'sizes' to 'fluid' everywhere it was referenced in Lightbox.js.
<Lightbox images={props.data.gallery.edges} />

    gallery: allFile(
      filter: {
        relativeDirectory: { eq: "screenshots/producta" }
        extension: { regex: "/(jpg)|(png)/" }
      }
    ) {
      edges {
        node {
          id
          name
          relativeDirectory
          extension
          childImageSharp {
            fluid {
              base64
              tracedSVG
              aspectRatio
              src
              srcSet
              srcWebp
              srcSetWebp
              sizes
              originalImg
              originalName
              presentationWidth
              presentationHeight
            }
          }
        }
      }
    }

A: It's entirely possible to resolve several paths with gatsby-source-filesystem:
{
  resolve: `gatsby-source-filesystem`,
    options: {
      name: `cars`,
      path: `${__dirname}/src/images/cars/`,
    },
},
{
  resolve: `gatsby-source-filesystem`,
    options: {
      name: `productScreenshots`,
      path: `${__dirname}/src/screenshots/products/`,
    },
},

Notice the name property? It could be used to query exactly that subset:
query getCarImages {
  allFile(
    filter: {sourceInstanceName: {eq: "cars"}}
  ) {
    nodes {
      childImageSharp {
        fluid {
          ...
        }
      }
    }
  }
}

Alternatively, you can dump all your images into src/images, point plugin at it once and then filter based on subdirectories' paths as mentioned in your examples.


text:
Q: Can't load assembly libphonenumber Version=5.0.0.0 on Windows Phone 8.0
*

*I add libphonenumber library C# port with nuget to Windows Phone 8.0 project.

*Write code

*Run, then app crash on this Line _phoneNumberUtil = PhoneNumberUtil.GetInstance();
With this error

Could not load file or assembly 'libphonenumber_csharp_portable, Version=5.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

Please, help me! What I doing wrong?
public partial class EnterPage
{
    private readonly EnterPageViewModel _viewModel;
    private readonly PhoneNumberUtil _phoneNumberUtil;
    public EnterPage()
    {
        InitializeComponent();
        _viewModel = new EnterPageViewModel();
        DataContext = _viewModel;
        _phoneNumberUtil = PhoneNumberUtil.GetInstance();
    }
}

In Windows Phone 8.1 project this code run without any errors.

A: Ok, guys it's my bad.
I use in Windows Phone 8.1 libphonenumber-csharp-portable, not full version.
Add this lib also to WP8 project and all run correct.


text:
Q: duplicate React components in the UI I am using React.js (without Redux or other State management library)
I have a single page app with two screens:
"MainL list" AND "My List"
When a user selects an item from the "Main list", then this item is being added to "My List".
The problem that I have is that when a user selects an item or two from the Main List and then switches to "My List", then he sometimes will see same items replicated twice.
It seems to be an issue with an array mutation of wrong usage of key IDs.
The items in both of the screens are represented by an array. So one array of items for the Main List and one array for the My List
To toggle the visibility of the screens, I use the following code:
this.state.screenLocation === "MainList" ? (
  this.state.cardsMainList.map((value, index) => (
    <ItemCard key={index} card={value} location={"MainList"} />
  ))
) : this.state.screenLocation === "MyList" ? (
  this.state.cardsMyList.map((value, index) => (
    <ItemCard
      key={index + 100000}
      card={value}
      location={"MyList"}
      added={true}
    />
  ))
) : (
  <div> Error: Wrong Screen Location </div>
);

When I switch to My List screen, I get the items info from the database and then change the array of the My List:
let cards = [];

//then an API call to the server to retrieve items from the DB
// ........
//then the following:

cards = response.data.results[0];

this.setState({ cardsMyList: cards });

Do I mutate the array wrongly? Do I use

Thank you in advance.


text:
Q: Inserting NSObjects to static Array Swift [Shortcut] Am really like to think of shortcut codes to do the workspace as a piece of cake and am not expert with Swift so there is any shortcut way for below code/scenario
let Item1 = MenuItem()
Item1.titleEn = "item 1"
let Item2 = MenuItem()
Item2.titleEn = "item 2"
let Item3 = MenuItem()
Item3.titleEn = "item 3"
let Item4 = MenuItem()
Item4.titleEn = "item 4"
let Item5 = MenuItem()
Item5.titleEn = "item 5"
let Item6 = MenuItem()
Item6.titleEn = "item 6"
self.items.append(Item1)
self.items.append(Item2)
self.items.append(Item3)
self.items.append(Item4)
self.items.append(Item5)
self.items.append(Item6)

A: Add an initializer to MenuItem to pass the title
class MenuItem {
    let title : String
    init(title: String) { self.title = title }
}

then use an array of the titles and map them
var items = [MenuItem]()

let titles = ["item 1", "item 2", "item 3", "item 4", "item 5", "item 6"]
let menuItems = titles.map { MenuItem(title: $0) }
items.append(contentsOf: menuItems)

For two items use a tuple
class MenuItem {
    let title : String
    let icon : String
    init(title: String, icon: String) { self.title = title; self.icon = icon }
}

var items = [MenuItem]()

let titles = [("item 1", "icon 1"), ("item 2", "icon 2"), ("item 3", "icon 3"), ("item 4", "icon 4"), ("item 5", "icon 5"), ("item 6", "icon 6")]
let menuItems = titles.map { MenuItem(title: $0.0, icon: $0.1) }
items.append(contentsOf: menuItems)

Note:
In most cases it's sufficient to use a struct. The benefit is you get the initializer for free
struct MenuItem {
    let title : String
    let icon : String
}

A: Simply, do it in for in loop:
func appendItem(_ title: String) {
    var item = MenuItem()
    item.titleEn = title

    items.append(item)
}

var items = [MenuItem]()

for i in 0...5 {
    appendItem("Item \(i+1)")
}

dump(items)

/*
 6 elements
 ▿ __lldb_expr_48.MenuItem
 ▿ titleEn: Optional("Item 1")
 - some: "Item 1"
 ▿ __lldb_expr_48.MenuItem
 ▿ titleEn: Optional("Item 2")
 - some: "Item 2"
 ▿ __lldb_expr_48.MenuItem
 ▿ titleEn: Optional("Item 3")
 - some: "Item 3"
 ▿ __lldb_expr_48.MenuItem
 ▿ titleEn: Optional("Item 4")
 - some: "Item 4"
 ▿ __lldb_expr_48.MenuItem
 ▿ titleEn: Optional("Item 5")
 - some: "Item 5"
 ▿ __lldb_expr_48.MenuItem
 ▿ titleEn: Optional("Item 6")
 - some: "Item 6"
 */


text:
Q: How to indicate an argument is passed by reference to the function To indicate an argument is passed by reference to the function, what character should I use before the argument in the parenthesis??
I'm reading in one book:

When you use a function that passes an argument by reference, do not prefix the argument with an ampersand. The ampersand is used only in the function definition.

So what character is used? I'm just confused on this entirely.

A: As explained in the documentation, to define a function taking arguments by reference you prefix each such argument with &:
function getsArgumentByRef(&$argument) { /* ... */ }

When calling the function, do not use an ampersand:
$result = getsArgumentByRef($input);

A: An ampersand (&) is used in the function definition like:
function something( &$parameter ){ ... }

But nothing is used in the call:
$variable = 3;
$other = something( $variable );

A: The & ampersand is used, as Jon mentioned in his comment.
However, the important part to take away from this in my opinion is what they mean by "...function definition."
The function definition is the actual source code that completes your function's task, or in the case of an interface what dependencies that function has.
This is a function definition:
function doCoolStuff(array &$data) {
    ...
}

The important part here isn't the implementation but the name doCoolStuff and the need for an array parameter to be passed.
Calling code is when you actually use the function.
$data = ('favorite_site' => 'stackoverflow');
doCoolStuff($data);

Notice, in the function definition up top there is an ampersand before the parameter name, this indicates the array is passed by reference.  Changes made to the array in the function change the array that was passed.  Also notice, there was no need to use the & in the calling code, the pass-by-reference is taken care of by the function definition.


text:
Q: Subdomínio para arquivos, Otimização do Site Bom, ouvi falar que para maior numero de downloads em paralelo a indicação é coloca-las em um subdomínio, e até um fato de que os cookies não irem na requisição também já deixaria mais rápida.
Enfim, verdade ou mito, até onde essa prática pode ajudar? (JS, CSS) é valido também?

A: Depende de varios fatores,
1- se o subdominio continuar a ficar no mesmo servidor que o website, eu acho que nao ira arreceber optimizacao nenhuma.
2- se utilizar algum tipo de tecnologia para proteger o seu website como a cloudflare podera sim atrasar os seus downloads ou ate mesmo optimizar, tudo depende de onde o utilizador esta localizado e a sua velocidade de Internet.
3- Nao acho que as cookies poderam atrasar os downloads, nao vejo razao para a mesma acontecer.
Basicamente, se quiser ter um site que faz upload dos ficheiro rapido para os utilizadores, sim poderas criar um subdominio em que o subdominio aponte para outro servidor teu, em que esse servidor apenas sirva para o download e upload de ficheiros. Ai teras um website suberbo em que os download poderam ser super rapidos exemplo (downloads1.seuwebsite.com podera apontar para 1 servidor seu downloads2.seuwebsite.com podera apontar para outro servidor seu) normalmente essa tecnica e utilizada quando a 1 maquina nao tem mais espaco disponivel, ou ate mesmo 1 outro servidor com internet super rapida para ficheiros de maior porte.
Espero ter ajudado.

A: Se for no mesmo servidor o subdominio, não irá ajudar em nada, pois continuará baixando do mesmo local!
O interessante para seu caso seria contratar uma CDN(Content Distribution Network), assim você poderá saber a localização da pessoa e indicar o servidor mais próximo com seus arquivos sem nenhum trabalho braçal!
A CDN pode ser a CloudFlare, pode ser a MaxCDN e várias outras empresas como a Amazon que oferecem produtos parecidos com CDN ou com funções bem similares aos de uma!
Minificar os JS e CSS podem ajudar sim a velocidade!
Esta prática pode te ajudar a indexar no Google em uma posição mais alta, atrair mais pessoas a seu site por ser rápido e dispor de maior rapidez para qualquer mudança!

A: Por meio do plugin YSlow do Firefox (depende de ter o Firebug também) cheguei a esta página:
http://yuiblog.com/blog/2007/04/11/performance-research-part-4/
. É de 2007, pode ter mudado bastantes coisas desde a publicação, mas apresenta um estudo exatamente sobre o que perguntou.
Em resumo:
Parte do principio que aumentando o número de domínios deve melhorar o tempo até carregar todos os elementos requisitados, porque a especificação HTTP/1.1 sugere que os navegadores deveriam baixar dois componentes em paralelo por hostname (apontado por Henrique acima). Este limite pode ser mudado via configuração tanto no I.E. quanto no Firefox (não há informação de outros), mas quem mexe no servidor não vai configurar nenhum navegador de cliente, e o modo de configurar não é muito user-friendly.
Só que os resultados do teste dele não foram exatamente os esperados. Tem dois testes, 20 imagens cada um, sendo um imagens pequenas e outro médias. Ambos tiveram melhoria no aumento de 1 para 2 hosts, porém o de imagens pequenas não teve impacto significativo ao aumentar mais o número de hosts e o de imagens médias teve impacto negativo! Sendo que com 3 hosts já ficava pior que com 1 host. No final ele chega à conclusão que o melhor deve ser de 2 a 4 hosts.
O CDN que o Vinicius citou ajuda bastante também, tentando diminuir a distância entre o navegador do cliente e a fonte do conteúdo requisitado.
Outro motivo para colocar mais hosts seria ter hostname(s) com conteúdo dinâmico e outro(s) com conteúdo estático, usando cabeçalho de expiração de conteúdo para que seja gravado em cache, mas isto pode ser feito em um único hostname por meio de configuração com o módulo mod_expires do apache por exemplo.
Se a intenção é saber o que melhorar em uma página para deixa-la mais rápida ou leve, o Firefox com o Firebug e o YSlow pode ajudar bastante, não conheço ferramenta semelhante em outros navegadores, mas deve haver.
Se tiver recursos disponíveis para fazer testes, o Safari (pelo menos no OS X) tem um recurso muito bom de cronometrar o tempo que leva ao carregar uma página indicando cada ação. Não estou certo, mas acho que já vi isto no Chrome no Windows também.

A: Esse é um problema do HTTP 1.1, que usamos atualmente ele é um protocolo sequencial. Isso quer dizer que, quando abrimos a conexão, podemos fazer 1 request por vez. Vai 1 request, esperamos, chega a resposta; só aí podemos disparar outro request.
Para tentar diminuir o impacto negativo desse comportamento, os navegadores com HTTP 1.1 abrem mais de uma conexão ao mesmo tempo. Hoje em dia esse número costuma ser de 4 a 8 conexões simultâneas por hostname.
O HTTP 2.0 já vai ter multiplexing, evitando de fazer essas gambiarras que fazemos de subdominios, mas você já pode usar o SPDY que é um protocolo feito pela google, que já tem essa opção, porem para instala-lo você tem que ter HTTPS instalado no seu servidor.
E deixando os arquivos CSS e JS em um arquivo só ajuda sim, pois só vai fazer uma requisição por arquivo.


text:
Q: JButton Small Button I am writing a swing program. But the problem is that the JButton I want to be small. It should be up to me to decide its height and width but the code below creates a long horizontal button.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingExample
{
         //Create the GUI and show it. For thread safety, this method should be
        //invoked from the event-dispatching thread

        private static void createAndShowGUI()
        {
            //create and setup the window
            JFrame frame=new JFrame("Swing Demo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            //Set the size of the window
            frame.setPreferredSize(new Dimension(300,300));

            //Centre the window on the screen
            WinUtilities wu=new WinUtilities();
            wu.centerWindow(frame);

            //Create a panel
            JPanel panel=new JPanel(new BorderLayout());

            //Create three buttons

                //Button1
                    JButton But1=new JButton("Add");
                    But1.setText("Add Data");
                    But1.setSize(new Dimension(10,20)); //Using it has no effect
                    But1.setMnemonic('A');
                    But1.setMargin(new Insets(12,7,20,10)); //Using it has no effect
                    But1.setBorder(null); //Using it has no effect
                    panel.add(But1,BorderLayout.WEST);

                //Button2
                    JButton But2=new JButton("Edit");
                    But2.setText("Edit Data");
                    But2.setMnemonic(KeyEvent.VK_E);
                    But2.setPreferredSize(new Dimension(5,5));

                    panel.add(But2,BorderLayout.CENTER);

               //Button3
                    JButton But3=new JButton("Display");
                    But3.setText("Display Data");
                    But3.setMnemonic(KeyEvent.VK_D);
                    But3.setPreferredSize(new Dimension(5,5));
                    panel.add(But3,BorderLayout.EAST);

            //Set window characteristics
            frame.setContentPane(panel);
            //frame.add(panel);
            frame.pack();

            //Display the window
            frame.setVisible(true);
        }

        public static void main(String args[])
        {
            //Schedule a job for the event dispatching thread

            //creating and showing this application's GUI
            javax.swing.SwingUtilities.invokeLater(new Runnable()
            {
                public void run()
                {
                    createAndShowGUI();
                }
            });

        }
}

class WinUtilities
{
    public void centerWindow(JFrame frm)
    {
        frm.setLocationRelativeTo(null);
    }
}

Please Help

A: for example

suggestion

*

*JPanel has implemented in API FlowLayout (pretty accepting PreferredSize),

*then  BoderLayout could be wrong LayoutManager,

*or to use GridLayout (then all JButtons will be have the same size, based on largest Item)
code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingExample {

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("Swing Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        JButton but1 = new JButton("Add");
        but1.setText("Add Data");
        but1.setMnemonic('A');
        but1.setBorderPainted(false);
        but1.setBackground(Color.red);
        but1.setBorder(null);
        but1.setFocusable(false);
        but1.setMargin(new Insets(0, 0, 0, 0));
        //but1.setContentAreaFilled(false);
        panel.add(but1);
        JButton but2 = new JButton("Edit");
        but2.setText("Edit Data");
        but2.setMnemonic(KeyEvent.VK_E);
        panel.add(but2);
        JButton but3 = new JButton("Display");
        but3.setText("Display Data");
        but3.setMnemonic(KeyEvent.VK_D);
        panel.add(but3);
        frame.add(panel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String args[]) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                createAndShowGUI();
            }
        });
    }
}

A: Buttons are big, because:

*

*you've set frame's preferred size to 300x300

*you've set content's layout to BorderLayout

*buttons were enlarged to fit so big frame

Simply delete the frame.setPreferredSize() and the buttons will be small (the frame size will be determined by the preferred sizes of inner components by calling frame.pack() method).
By the way:

*

*the But1.setSize(...); was ignored - you should always call: setMinimumSize/setMaximumSize/setPreferredSize instead, the layout determines the sizes according to constraints

*it's very unlikely to display texts: 'Edit data', 'Add data' correctly on buttons with preferred size 5x5, consider using icons or make the buttons bigger


text:
Q: callout pops up behind the pins in MKMapView - iPhone I have 10 custom annotations on my map but sometimes the callout pops out behind the pins.. any idea to resolve this?
I have checked out this link
Z-ordering of MKAnnotationViews
but since my callouts are not popping up by tap but they are popping up by click on button so this answer is worthless to me.
Any kind of help will be really appreciated.

A: The reason behind this is because some where in your code you are calling bringSubviewToFront on the annotationView.


text:
Q: Show maintenance page during Wildfly startup I have a WildFly installation which takes some time during startup due to the count and size of the deployments. So I would like to show a maintenance page until the full application is ready.
In one of the previous WildFly versions I used default-web-module as configuration option and registered a small WAR file, which was visible right away and was replaced as soon as the big application was available.
Unfortunately this is no longer possible with WildFly 22, instead an exception is thrown as soon as the real root application is deployed:
org.jboss.msc.service.DuplicateServiceException: Service jboss.undertow.deployment.default-server.default-host./.UndertowDeploymentInfoService is already registered

I know that I could put a small web server (nginx or similar) in front of WildFly to return my maintenance webpage as long as WildFly returns a 503 error. The only thing which prevents that is the fact, that the maintenance page still contains some logic which I would need to emulate on nginx.
Is there any other option which ensures that my maintenance page is delivered immediately while the other apps are still starting?

A: If I do understand your question correctly, what you want is to show error page of status 503 when server is down or 404 when server is replacing deployments.
But for your environment which don't have a web server in front of application server, we just need to consider 404 situation.
503 is for web server when the application server is down, therefore, 503 service unavailable.
First:  Console -> Configuration tab
Head over to management console of Wildfly. And depends on what mode(domain or standalone) you are using ,there will be a little different inside configuration tab.
Second: Configuration -> Web -> Filters
If using domain mode, choose the profile you are using it.
And head over to Subsystem -> Web(Undertow) -> filters -> click 'View'.

*

*I used profile 'full' in my local machine with domain mode, therefore, this is what my console looks like.
Path_to_Filters
Third: Choose Error page tab inside Filters
Set code and path like this, where code is what status code you hope the static page to show. And path is the file location of your static page.
setPathAndCode
You can see Wildfly doc for error-page settings.
Fourth: Configuration tab -> Web(Undertow) -> Server -> default-server(or what you used)
HeadToServer
Fifth: Choose Hosts tab inside servers
Choose 'Hosts' tab, and click add filter button.
Select the filter we just set in step three, and set predicate to true.

*

*I'm not sure what will be effected if didn't set as true or left empty, cause it's not required fields.

Last: Restart the server in order to let your configuration works.

Now you should able to see your static page showed when you undeploy or re-deploy your application.
Sorry for not answering in too good answer format because I didn't answer any questions before.
** You can also set your standalone.xml or domain.xml like this to get the same result.
setXmlFile


text:
Q: IOS - Can Smack API library for Android be used for IOS connect to Ejabberd Server? I want to connect to native a app en IOS to Ejabberd Server I work with the library: https://github.com/robbiehanson/XMPPFramework , but not have more support
XMPPFramework is very complete, they know some alternative. Regards!!

A: XmppFramework is better choice for implementation iOS app Side support, It can connect with mentioned server and can communicate with smack for android as well


text:
Q: Using λ to define function in Racket Following function works:
(define (testfn)
  (define (contains sl item)    (ormap (λ(x)(equal? item x)) sl))
  (if (contains (list 1 2 3) 2)    "yes" "no"))

(testfn)

Output:
"yes"

But following, which uses λ symbol, does not:
(define (testfn2)
  (λ (contains sl item)    (ormap (λ(x)(equal? item x)) sl))
  (if (contains (list 1 2 3) 2)    "yes" "no"))

Error is:
contains: unbound identifier in module in: contains

Can λ symbol be used to define inner (or general) functions which may be called at multiple places?

A: Yes, but you need to define it like you would with any other identifier.
(define (testfn2)
  (define contains (λ (sl item) (ormap (λ(x)(equal? item x)) sl)))
  (if (contains (list 1 2 3) 2)    "yes" "no"))

Your code creates a function but (1) it is not bound to anything and (2) it actually takes three arguments, the first of which is "contains".


text:
Q: Smartwatch Access I'm currently working on a project which needs access to sensors from a smartwatch. However, is it possible to get access to know whether the user is sleeping or not at the particular moment?
Edit: http://developers.google.com/fit/scenarios/read-sleep-data
Can anyone help me find the variable which actually records the sleep factor in the above link? Anyone acquainted with smart watches and their science?


text:
Q: What credential type should I use to login to AWS API? I'm trying to integrate AWS API (AWSSDK 2.3.55.2) to my asp.net mvc4 project and I'm not sure what type of credential I should use. Manually i log-in to AWS using the third-party app (okta), so I don't have credentials directly from the AWS. Can I get\generate access key or smth else for login throught API by myself ? Or I should ask my AWS admin anyway to provide some creds ?
What is the simpliest way to login in this situation ?
Now I have smth like:
public static void RestartInstance()
        {
            var ec2Client = new AmazonEC2Client();

            try
            {
                var response = ec2Client.RebootInstances(new RebootInstancesRequest
                {
                    // Frankfurt
                    InstanceIds = new List<string> {
                    "MYInstanceID"
                }
                });
            }
            catch (AmazonEC2Exception ex)
            {
                if ("InvalidInstanceID.NotFound" == ex.ErrorCode)
                {
                    Logger.Instance.Info($"AWS1 Error during rebooting. Please, check the Instance ID Ex: {ex.Message}");
                }
            }
        }

I have 2 choices according to client realization: http://prntscr.com/kt13al . But as far as I understand I cannot use "AWSCredentials", because I don't have this one (I log-in using another app), so I need awsAccessKeyId and awsSecretAccessKey ? Is it right ?

A: AWS has concept of IAM (Identity Access Management) for authentication and authrozation. AWS IAM documentation.
Locally you need to have AWS Access keys(Access key and Secret access key) generated for your IAM user, this can be done for example from the AWS web console, and you need to configure the credentials. See AWS CLI Documentation for help
If you are running your application in the AWS EC2/ECS/Fargate/Elastic Beanstalk You need to specify IAM Role for the server/service to access private AWS resources. See for example AWS documentation for EC2 IAM
Configuring credentials for C# see documentation
Generally SDK looks for named environment variables for access key and secret key and uses them to access AWS resources.
And yes you need the access key and secret access key to locally use SDK.


text:
Q: How to share Image file from flutter app to other apps I have app that app display one image to the user. that image I was saved it in MySQL database as a link and image in folder into server. Now I try to make user can share that image to other apps  like WhatsApp or Facebook from my app.
I use share_plus 3.0.5 packages to make that:
share_plus 3.0.5
  await Share.shareFiles([//////////////////here/////////////], text: 'Image Shared');

Get image by this code:
  Future MakeShare() async {
var response = await http.get(
    Uri.parse("https://*********/ImageMakeShare.php?ID=" + widget.IDS.toString()),
    headers: {"Accept": "application/json"});

setState(() {

  var convertDataToJson = json.decode(response.body);
  dataImage = convertDataToJson['result'];
  if (dataImage != null) {

    imageMaine = dataImage[0]['image'];

}}); }

I try to make it like that
  await Share.shareFiles([imageMaine ], text: 'Image Shared');

But I get error:
E/flutter (10763): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: PlatformException(https:/*******0ee2e.png (No such file or directory), null, null, null)

Now I need to know how can I make user can share that image to other apps.
Anyone can help me?

A: As you can see from the documentation shareFiles() function expects a list of String pointing to a local path, on the device. You are passing a URI (imageMaine), which is not a local path, so the plugin throws and exception.
If you wanna share a link, than you should use the share() function.
If you wanna share a file you should first fetch your fine and then send it with the shareFiles function:
  final url = Uri.parse("myLink");
  final response = await http.get(url);
  await File('/yourPath/myItem.png').writeAsBytes(response.bodyBytes);

  await Share.shareFiles(['/yourPath/myItem.png'], text: 'Image Shared');

A: You can use my library app_utils which allows you to launch Android and iOS with provided parameters. You can pass your image URI to other applications as an arguments.

eg.

await AppUtils.launchApp(
androidPackage: "com.whatsapp",
iosUrlScheme: "whatsapp://",
params: {"imageUrl": "https://image.png"});

A: Pass the username and network image URL in this method, it will return XFile.
fileFromImageUrl(String url, String userName) async {
        final response = await http.get(
          Uri.parse(url),
        );

        final documentDirectory = await getApplicationDocumentsDirectory();

        var randomNumber = Random();

        final file = File(
          join(
            documentDirectory.path,
            "${randomNumber.nextInt(100)}_$userName.png",
          ),
        );

        file.writeAsBytesSync(response.bodyBytes);

        return XFile(file.path);
      }

call this method like this,
XFile fileForShare = await fileFromImageUrl(
                      fileURL, empName);

Share.shareXFiles(
                    [fileForShare],
                    text: widget.postData.title.toString(),
                 );

A:   static Future<String> shareScreenShort(String title, {required GlobalKey previewContainer, int originalSize = 1600}) async {
    try {
      RenderRepaintBoundary boundary = previewContainer.currentContext!.findRenderObject() as RenderRepaintBoundary;
      double pixelRatio = originalSize / MediaQuery.of(previewContainer.currentContext!).size.width;
      ui.Image image = await boundary.toImage(pixelRatio: pixelRatio);
      ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
      Uint8List pngBytes = byteData!.buffer.asUint8List();

      String filePathAndName = Service.documentDirectoryPath + '/images/$title.png';
      File imgFile = File(filePathAndName);
      await imgFile.writeAsBytes(pngBytes);
      await Share.shareXFiles(
        [XFile(imgFile.path)],
        sharePositionOrigin: boundary.localToGlobal(Offset.zero) & boundary.size,
        text: title,
      );

      return "success";
    } catch (ex) {
      return ex.toString();
    }
  }


text:
Q: PHP file upload keeps throwing error I am uploading an rsa private key (.pem file) to my website and using fopen to read the contents but lately I keep getting the same error over and over without making much sense.
HTML
  <form enctype="multipart/form-data" action="upload.php" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
    Choose a file to upload: <input name="uploaded_file" type="file" />
    <input type="submit" value="Upload" />
  </form>

Upload.php
<?php
session_start();

if( $_SERVER['SERVER_PORT'] == 80) {
    header('Location:https://'.$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"]);
    die();
}

echo $_FILES['uploaded_file']['name'];

//Сheck that we have a file
if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) {
  $filename = basename($_FILES['uploaded_file']['name']);
  $ext = substr($filename, strrpos($filename, '.') + 1);
  if (($ext == "pem") && ($_FILES["uploaded_file"]["type"] == "text/plain")) {

$fh = fopen($_FILES['uploaded_file']['name'], 'r');

//continue with code
  } else {
     echo "Error: Only pem files are accepted for upload";
  }
} else {
 echo "Error: No file uploaded";
}
?>

The site keeps returning the error:

Warning: fopen(mykey.pem)
  [function.fopen]: failed to open
  stream: No such file or directory in
  .... on line 38

(which is fopen line). The fact it gets to the fopen state proves to me it does in fact upload but using fopen (also tried using file_get_contents($_FILES['uploaded_file']['name']); as well unsuccessfully) returns an error.
what da puh!
FINAL NOTES:
For whatever reason, fopen() does not like reading OpenSSL certificates and returns an eror:

openssl_private_decrypt(): supplied
  resource is not a valid OpenSSL
  X.509/key resource

if you use file_get_contents it works however.

A: I believe you're trying to open a wrong file(name). Since I don't see move_uploaded_file() anywhere in your code, you should probably be reading the tmp_name instead of name from the $_FILES array:
$fh = fopen($_FILES['uploaded_file']['tmp_name'], 'r');

A: try
  $fh = fopen($_FILES['uploaded_file']['tmp_name'], 'r');


text:
Q: How can I append to class variables using multiprocessing in python? I have this program where everything is built in a class object. There is a function that does 50 computations of a another function, each with a different input, so I decided to use multiprocessing to speed it up. However, the list that needs to be returned in the end always returns empty. any ideas? Here is a simplified version of my problem. The output of main_function() should be a list containing the numbers 0-9, however the list returns empty.
class MyClass(object):
    def __init__(self):
        self.arr = list()

    def helper_function(self, n):
        self.arr.append(n)

    def main_function(self):
        jobs = []

        for i in range(0,10):
            p = multiprocessing.Process(target=self.helper_function, args=(i,))
            jobs.append(p)
            p.start()

        for job in jobs:
            jobs.join()

        print(self.arr)

A: arr is a list that's not going to be shared across subprocess instances.
For that you have to use a Manager object to create a managed list that is aware of the fact that it's shared between processes.
The key is:
self.arr = multiprocessing.Manager().list()

full working example:
import multiprocessing

class MyClass(object):
    def __init__(self):
        self.arr = multiprocessing.Manager().list()

    def helper_function(self, n):
        self.arr.append(n)

    def main_function(self):
        jobs = []

        for i in range(0,10):
            p = multiprocessing.Process(target=self.helper_function, args=(i,))
            jobs.append(p)
            p.start()

        for job in jobs:
            job.join()

        print(self.arr)

if __name__ == "__main__":
    a = MyClass()
    a.main_function()

this code now prints: [7, 9, 2, 8, 6, 0, 4, 3, 1, 5]
(well of course the order cannot be relied on between several executions, but all numbers are here which means that all processes contributed to the result)

A: multiprocessing is touchy.
For simple multiprocessing tasks, I would recomend:
from multiprocessing.dummy import Pool as ThreadPool

class MyClass(object):
    def __init__(self):
        self.arr = list()

    def helper_function(self, n):
        self.arr.append(n)

    def main_function(self):
        pool = ThreadPool(4)
        pool.map(self.helper_function, range(10))
        print(self.arr)

if __name__ == '__main__':
    c = MyClass()
    c.main_function()

The idea of using map instead of complicated multithreading calls is from one of my favorite blog posts: https://chriskiehl.com/article/parallelism-in-one-line


text:
Q: Java:JSON to map using GSON I have a string like this
{"key0":"value0","key1":"value1","key0":"value3"}

I want to store it in a map and the desired result is {"key0":"value3","key1":"value1"}
Using org.json.JsonObject: I passed the string to the constructor and Duplicate key exception is thrown
Using GSON: Same exception when I tried through new Gson.fromJson(string,Type)
Using Jackson: It does work
Is there a workaround to achieve the same using JSONObject and Gson

A: Interestingly if you first cast that json to an Object and then to a Map<String,String> your desired result happens:
String json = "{\"key0\":\"value0\",\"key1\":\"value1\",\"key0\":\"value3\"}";
Gson gson = new Gson();
Object obj = gson.fromJson(json, Object.class);
try {
    Map<String,String> map = (Map<String, String>)obj;
    // Outputs...
    // key0=value3
    // key1=value1
    for (Map.Entry<String,String> entry : map.entrySet()) {
        System.out.println(entry.getKey() + "=" + entry.getValue());
    }
} catch (ClassCastException e) {
    e.printStackTrace();
}

A: GSON uses MapTypeAdapterFactory to deserialioze map. Below is a short excerpt of its source code where a new entry is put in a map:
V replaced = map.put(key, value);
if (replaced != null) {
    throw new JsonSyntaxException("duplicate key: " + key);
}

Knowing that there is at least one way to bypass this strict behavior: create your own map that overrides the method put(..) to return always null, like:
public class DuploMap extends HashMap<String, String>{
    @Override
    public String put(String key, String value) {
        super.put(key, value);
        return null;
    }
}

then deserailizing to it like:
gson.fromJson(JSON, DuploMap.class);

will not throw that exception.

A: You can use GSON's JsonReader if you do not mind the manual effort.
On the plus side:

*

*faster (no reflection, no casts)

*fully under your control

--
String json = "{"key0":"value0","key1":"value1","key0":"value3"}";
JsonReader jsonReader = new JsonReader(new StringReader(json));
HashMap<String,String> map = new HashMap<String, String>()
String currKey;
try {
    while(jsonReader.hasNext()){
        JsonToken nextToken = jsonReader.peek();
           if(JsonToken.NAME.equals(nextToken)){
               currKey = jsonReader.nextName();
           }
           if(JsonToken.STRING.equals(nextToken)){
               map.put(currKey, jsonReader.nextString())
           }
    }
} catch (IOException e) {
   e.printStackTrace();
}


text:
Q: Allow typing mobile numbers starting with 7,8 or 9 I need the realtime validation to use in the input tag to allow user typing only the number starting with 7,8 or 9. right now I have the following thing which is not working. Only if the user types the digits 7 to 9 as the first digit on the input field then only it should be appearing in the input field.
<input type="tel" label="Mobile Number" pattern="^[7-9][0-9]{8}$" maxLength="10"/>

A: Pattern on input is validated only on submit.
If you want to validate on real time, You can achieve it using javascript
(function() {
    var input = document.getElementById('YOUR_INPUT_ID');
    var pattern = /^[7-9][0-9]{0,8}$/;
    var value = input.value;
    !pattern.test(value) && (input.value = value = '');
    input.addEventListener('input', function() {
        var currentValue = this.value;
        if(currentValue && !pattern.test(currentValue)) this.value = value;
        else value = currentValue;
    });
})();


text:
Q: phalcon partial for multiple module $this->partial('partials/header');

This function for phalcon single module.
What can i do for this multiple-modules.
Can't work for this modules design.
I Went to use in multiple-modules design.
$this->partial('partials/header');

Please tell me
module1/
     views/
         about/      <- AboutController
         index/      <- IndexController
         index.phtml
module2/
     views/
         about/      <- AboutController
         index/      <- IndexController
         index.phtml
module3/
     views/
         about/      <- AboutController
         index/      <- IndexController
         index.phtml
         partials/   <- ()Store partials
             header.phtml
             footer.phtml

A: Just go back few directories. For example if you want to include header.phtml from module3 in module1 (you may need to modify for your path):
$this->partial('../../module3/views/partials/header');

A: Better create seperate view directory which will be used in every module. Add it to view compomnent and then you shouldn't need to go to this directory.


text:
Q: WARNING: Can't mass-assign protected attributes for User: login I created two models user.rb and cart.rb
user.rb
class User < ActiveRecord::Base

  attr_accessor :login

  has_one :cart

end

cart.rb
class Cart < ActiveRecord::Base

  belongs_to :user

end

when I create a user in rails console, message appears : WARNING: Can't mass-assign protected attributes for User: login
E:\work\my_store>rails c
DL is deprecated, please use Fiddle
Loading development environment (Rails 4.1.8)
irb(main):001:0> user1 = User.new(login: "user1")
WARNING: Can't mass-assign protected attributes for User: login

=> #<User id: nil, login: nil, created_at: nil, updated_at: nil>
irb(main):002:0>

help me to solve this

A: There is a huge difference between attr_accessor and attr_accessible - you want to use the other one. :)

A: This is a security feature in Rails that prevents mass-assignment. If you'd like to whitelist certain attributes you can do
class User < ActiveRecord::Base
  attr_accessible :login
end

Or just not use mass-assignment when creating your models.


text:
Q: How to restrict file size while writing to text file from an Android app My Android App continiously writing logs in a .txt file. I want to restrict this file size.ie, if file size exceeds 1MB it will not write any more log and notification will be sent to the user that no more space in your log file.How can I implement that?

A: try this code for calculating size:
File file = new File("text.txt");
                long filesize = file.length();
                long filesizeInKB = filesize / 1024;
                long filesizeinMB=filesizeInKB/1024;


text:
Q: Using mysqli with Wordpress and future upgrades All,
I'm trying to be good and get away from the mysql* php coding. I'm using wordpress for a new project and want to use the correct syntax for my database queries in my pages that I create. I want to use mysqli* but it looks like Wordpress uses mysql* commands when connecting with the database. For example, they have some code like this in the wp-include/wp-db.php file:
if ( !@mysql_select_db( $db, $dbh ) ) {

I did read I can adjust this file wp-includes/load.php to use my own database code which is called before the wpdb variable is set.
I also want this to be scalable, so I can upgrade to future versions of Wordpress. If I update these values and then need to upgrade Wordpress, I think these values will get overwritten and my site has potential to not work correctly.
I tried to use the $wpdb value in creating a query on one my pages from within Wordpress. I tried to do this following:
<?php
    global $wpdb;
    $info = $wpdb->get_results('Select * from vendor_types order by description ASC');
    foreach($info as $table) {
        echo $table->description;
    }
?>

When I do this, I get the correct output and it's what I would expect it to be. However, is this the best way to do this from a Wordpress perspective? I want to try and avoid using deprecated code in my applications?
Thanks!


text:
Q: Array without undefined validation with io-ts We are using io-ts to validate external data from HTTP services. I have written a codec that takes another codec C and returns Either<t.Errors, C | undefined> but actually never fails (just to satisfy t.Type). This is because from the service we get an array of different types and new ones can be added in the future so we want it to continue working but just ignore those that are undefined. Looks like:
export function tryDecode<C extends io.Mixed>(
  codec: C,
  onLeft?: (validation: io.Validation<unknown>) => void,
) {
  return new io.Type<io.TypeOf<C> | undefined, io.OutputOf<C>, unknown>(
    'tryDecode',
    (input: unknown): input is C | undefined => {
      return codec.is(input) || input === undefined;
    },
    (u, c) => {
      const validation = codec.validate(u, c);

      return fold(
        () => {
          if (onLeft) {
            onLeft(validation);
          }

          return io.success(undefined as C | undefined);
        },
        (right: C | undefined) => io.success(right),
      )(validation);
    },
    io.identity,
  );
}

I am trying to write a codec arrayWithoutUndefined that works just like io.array but removes any element that is undefined. It should not fail (unless it's not an array). My attempt so far:
export function arrayWithoutUndefined<C extends io.Mixed>(
  codec: C,
  name = `arrayWithoutUndefined<${codec.name}>`,
) {
  const arr = io.array(codec);

  return new io.Type(
    name,
    (u): u is Array<io.TypeOf<C>> => arr.is(u) && !u.includes(undefined),
    (u, c) =>
      either.chain(codec.validate(u, c), as =>
        io.success(as.filter(notUndefined)),
      ),
    arr.encode,
  );
}

The notUndefined is a helper that ensures (a: A | undefined): a is A => .... Then I would use them together as const Modules = arrayWithoutUndefined(tryDecode(UnionOfDifferentModules)) but Modules is still expressed as Array<UnionOfDifferentModules | undefined> when I want it to just be Array<UnionOfDifferentModules>. Is this possible to express with TypeScript/io-ts somehow? I looked into conditional types but unfortunately have no idea how to express.

A: This problem may have solved itself in newer versions of typescript that support type guards in array filter statements.
It's also possible that explicit generics for the t.Type would help here.
type Subtract<A, B> = A extends B ? never : A;

return io.Type<Subtract<t.TypeOf<C>, undefined>, unknown[], unknown>(...);


text:
Q: Postgresql's substring expression I have a field message with strings like <pika> [SOME_TEXT_WITH|ACTION] And other stuff....
I wish to capture what's inside the brackets. I use the following form:
SELECT
  substring(message FROM '%> \[#"[A-Z_\|]+#"\] %' FOR '#') AS my_info
FROM my_table;

But it always fail with the same ennoying error message: «Invalid regular expression: parentheses () not balanced». What do I do wrong ?

A: Personally, I'd use a perl-compatible modern regexp instead of the horrid POSIX-esque regexps:
regress=> SELECT (regexp_matches('<pika> [SOME_TEXT_WITH|ACTION] And other stuff...', '\[(.*?)\]'))[1];
    regexp_matches
-----------------------
 SOME_TEXT_WITH|ACTION
(1 row)

If you want to use the POSIX syntax you have to use the same escape consistently, not \ in some places and # in others. eg:
regress=> SELECT substring(
            '<pika> [SOME_TEXT_WITH|ACTION] And other stuff...'
            FROM '%#"#[%#]#"%' FOR '#'
          );
        substring
-------------------------
 [SOME_TEXT_WITH|ACTION]
(1 row)

The docs don't make it very clear that the capture operator is actually <ESCAPECHAR>", not #" specifically. This is equally valid, using a regular backslash escape:
regress=> SELECT substring(
              '<pika> [SOME_TEXT_WITH|ACTION] And other stuff...'
              FROM '%\"\[%\]\"%' FOR '\'
          );
        substring
-------------------------
 [SOME_TEXT_WITH|ACTION]
(1 row)

The cause of the odd error is that PostgreSQL translates the POSIX SIMILAR TO style expression into a real regular expression under the covers. Your mixed-escapes regex:
'%> \[#"[A-Z_\|]+#"\] %' FOR '#'

is being turned into something like:
'.*> \\[([A-Z_\\|]+)\\] .*'

resulting in:
regress=> SELECT (regexp_matches('<pika> [SOME_TEXT_WITH|ACTION] And other stuff...', '.*> \\[([A-Z_\\|]+)\\] .*'))[1];
ERROR:  invalid regular expression: parentheses () not balanced

A: I think the following does what you want:
SELECT substring(cast(message as varchar(1000)) FROM '.*\[([A-Z_\|]*)\].*'
                )
FROM my_table;


text:
Q: Convert character to variable names used in formula in R I am beginner of R, I met a problem which might be simple for you. Thanks in advance if could give me some help. I am not sure whether the title does reflect the problem I want to ask. To make my problem clear, I will use a simple example.
Let's say we have data frame containing two factors (FE and DI) and three variables (SR1, SR2 and SR3) like:
df<-data.frame(FE=rep(c("FL","FM","FH"),4),DI=rep(c("DL","DH"),each=6),
SR1=rpois(12,10),SR2=rpois(12,15),SR3=rpois(12,20))

I know how to calculate the means of variables according to the factors by using "aggregate", for example:
df.me1<-aggregate(SR1~FE,df,mean)
df.me2<-aggregate(cbind(SR1,SR2,SR3)~FE+DI,df,mean)

Then, I make two characters (vars and facs) consisting of names of the three variables and the two factors:
vars<-c("SR1","SR2","SR3")
facs<-c("FE","DI")

Now, I want to do the calculations in the following formula for some reason
df.me1<-aggregate(vars[1]~facs[1],df,mean)
df.me2<-aggregate(cbind(vars[1],vars[2],vars[3])~facs[1]+facs[2],df,mean)

The codes certainly do not work, so what should I do to make them work in this way?

A: There are two ways to do this. One would be through aggregate's formula interface, which is what you're currently trying to do. In order to make this work, you'd have to create a string that includes your dependent and independent variables. Then you'd convert that string to a formula object using as.formula(). This is overcomplicated, since it requires a lot of witchcraft with sprintf and/or paste.
A simpler way to do this would be through aggregate's by argument, which is a little more friendly for substitutions made through variable names.
df.me1 <- aggregate(df[vars[1]], by = df[facs[1]], FUN = mean)

  FE   SR1
1 FH 10.00
2 FL 10.00
3 FM  9.25

df.me2 <- aggregate(df[vars], by = df[facs], FUN = mean)

  FE DI  SR1  SR2  SR3
1 FH DH  9.0 11.5 22.5
2 FL DH  8.0 16.5 21.5
3 FM DH 10.0 14.5 21.0
4 FH DL 11.0 16.5 18.0
5 FL DL 12.0 18.0 15.0
6 FM DL  8.5 13.0 24.0

A: For a more generic solution for dealing with strings in equations I like using the functionality eval(parse(text = "A string to execute")) for example in your code
eval(parse(text = paste("df.me1<-aggregate(",vars[1],"~",facs[1],",df,mean)",sep="")))

and I get the following result
> df.me1
  FE   SR1
1 FH  9.75
2 FL 10.75
3 FM 10.25

I also find that functionality useful when retrieving information in a list that is referenced by a string.
here is the paste command
> paste("df.me1<-aggregate(",vars[1],"~",facs[1],",df,mean)",sep="")
[1] "df.me1<-aggregate(SR1~FE,df,mean)"

For the second part
eval(parse(text = paste("df.me2<-aggregate(cbind(",vars[1],",",vars[2],",",vars[3],")~",facs[1],"+",facs[2],",df,mean)",sep="")))

A: @jdobres' answer is cleaner and probably better in most instances, but if you must do this exactly as you've written it, then referencing this answer, you can just use get().
df.me2<-aggregate(cbind(SR1,SR2,SR3)~FE+DI,df,mean)
df.me2.get<-aggregate(cbind(get(vars[1]),get(vars[2]),get(vars[3]))~get(facs[1])+get(facs[2]),df,mean)

And checking if they are the same:
df.me2 == df.me2.get

       FE   DI  SR1  SR2  SR3
[1,] TRUE TRUE TRUE TRUE TRUE
[2,] TRUE TRUE TRUE TRUE TRUE
[3,] TRUE TRUE TRUE TRUE TRUE
[4,] TRUE TRUE TRUE TRUE TRUE
[5,] TRUE TRUE TRUE TRUE TRUE
[6,] TRUE TRUE TRUE TRUE TRUE


text:
Q: Where does the Lorentz boost for a Dirac spinor come from? I have read, that if you have a Dirac spinor
\begin{equation}
\psi =
\begin{pmatrix}
\phi_R\\
\phi_L
\end{pmatrix}
\end{equation}
that you can apply a Lorentz boost along the $z$-direction with
rapidity $y$ like this:
\begin{equation}
\phi_R\rightarrow e^{-\frac{1}{2}\sigma_zy}\phi_R; \quad\phi_L\rightarrow e^{+\frac{1}{2}\sigma_zy}\phi_L
\end{equation}
and a general boost like this:
\begin{equation}
\phi_R\rightarrow e^{-\frac{1}{2}\mathbf{\hat n}\cdot{\bf\sigma}}\phi_R; \quad\phi_L\rightarrow e^{+\frac{1}{2}\mathbf{\hat n}\cdot{\bf\sigma}}\phi_L
\end{equation}
Why is this the correct way to transform the spinor? Also are opposite signs in the exponentials just convention or do they have deeper meaning?

A: You may wish to look at the derivation of Lorentz transformations for Dirac spinors, say in the book by Itzykson, Zuber. They are derived from the condition of relativistic covariance of the Dirac equation. The generators of Lorentz transformations are $[\gamma^\mu,\gamma^\nu]$ (up  to a constant factor). This expression gives the different signs for boosts for the right-handed and left-handed parts of the Dirac spinor in the chiral representation.

A: Comments to the question (v3):

*

*Recall that the restricted Lorentz group
$$\tag{1} SO^+(3,1)~\cong~ SL(2,\mathbb{C})/\mathbb{Z}_2$$
is locally isomorphic to the Lie group of complex $2\times 2$ matrices with unit determinant, cf. e.g. my Phys.SE answer here. The Lie group of 3D rotations
$$\tag{2} SO(3)~\cong~ SU(2)/\mathbb{Z}_2$$
is a subgroup thereof.

*The left-handed Weyl spinor representation is the fundamental representation of $SL(2,\mathbb{C})$. A left-handed Weyl spinor $\psi^{\alpha}_L$ (with upper indices) transforms as
$$\tag{3} \psi_L~\longrightarrow~\psi^{\prime}_L ~=~g  \psi_L, \qquad g~\in~SL(2,\mathbb{C}). $$

*The right-handed Weyl spinor representation is mathematically speaking the complex conjugate representation. This means a right-handed Weyl spinor $\psi^{\dot{\alpha}}_R$ (with upper indices) transforms as
$$\tag{4} \psi^{\bullet}_R~\longrightarrow~\psi^{\prime\bullet}_R ~=~g^{\ast}  \psi^{\bullet}_R, \qquad g~\in~SL(2,\mathbb{C}), $$
where $g^{\ast}$ denotes the complex conjugate $2\times 2$ matrix.

*Phycisists often lower the index of the right-handed Weyl spinor
$$\tag{5}\psi_{\dot{\alpha}}^R~=~\varepsilon_{\dot{\alpha}\dot{\beta}}\psi^{\dot{\beta}}_R$$ with the Levi-Civita tensor $\varepsilon_{\dot{\alpha}\dot{\beta}}$. The right-handed Weyl spinor $\psi_{\dot{\alpha}}^R$ (with lower indices) transforms as the Hermitian conjugate representation
$$\tag{6}\psi_{\bullet}^R~\longrightarrow~ \psi^{\prime R}_{\bullet} ~=~(g^{-1})^{\dagger}  \psi_{\bullet}^R, \qquad g~\in~SL(2,\mathbb{C}), $$
due to special properties of $2\times 2$ matrices.

*In summary, the difference between the transformations (3) and (6) is rendered moot for compact 3D rotations [since they are implemented by unitary $2\times 2$ matrices, cf. eq. (2)], but induces an important relative minus sign in the non-compact Lorentz boosts transformation rule between the left-handed and the right-handed Weyl spinors.


text:
Q: Call the same function for two types of events The code calculates the total price of a list of services. I have an input tag to for each service. When the price of a service is modified, the total price is calculated.
$(document).on('change key paste keyup', '[id^="bill_servicesPerformed"][id$="unitPrice"]', function() {

  //here the code to calculate the total price
}

Now I would like to calculate also the total when one of the services is remove from the list. How can I do that reusing the code to calculate the total price?
NOTE: of course, next to each service I have a link with a class "remove-service".

A: You'd have to manually start that logic when they are removed.  Currently until Observers are more broadly implemented, there isn't a great way of detecting that an element has been added/removed from the DOM and as a result do something.  This is, of course, as far as I am aware.

A: Give your function a name.  Then you can call it.  Anonymous functions are useful only when you need to pass it as an argument only once.
Example:
function updatePrices() {
  //here the code to calculate the total price
}

$(document).on('change key paste keyup', '[id^="bill_servicesPerformed"][id$="unitPrice"]', updatePrices);

$(document).on('click', 'a.remove-service', updatePrices);

A: var calculateTotalPrice = function() {
    //calculator algorithm here
}

$(document).on('change key paste keyup', '[id^="bill_servicesPerformed"][id$="unitPrice"]', calculateTotalPrice);

$('a.remove-service-link').click(function(e) {
    // to prevent run the a href
    e.preventDefault();

    // your remove service code here

    // then call calculate function
    calculateTotalPrice();
});


text:
Q: Why do programming language (open) standards cost money? Isn't it counter-productive to ask for 384 Swiss franks for C11 or 352 Swiss franks for C++11, if the aim is to make the standards widely adopted?
Please note, I'm not ranting at all, and I'm not against paying; I would like to understand the rationale behind setting the prices as such, especially knowing that ISO is network of national standard institutes (i.e. funded by governments). And I also doubt that these prices would generate enough income to fund an organization like that, so there must be another reason.

A: Some points:

*

*IIRC, the price of an ISO standard is directly a function of the number of pages in the standard, whatever the standard is.

*Programming languages is one of the very few matter for which individuals may want to get a copy of the standard.  For most matters, only companies (and sometimes an handful of them) will want a copy.  And for companies, the price is indeed nominal compared to other costs (such as ensuring that their product comply effectively with the standard -- even for PL, if you are writing a compiler, 300 euros for the standard is what? 1 or 2 days for one person?, and people writing compilers, the standard libraries or books are the market for standard, most other uses aren't really pertinent).

*When selling the standards, ISO is in competition with its member. ANSI, AFNOR, BSI, ... are also in the process of selling the documents.  Those won't accept ISO to cut its price too much.  Note that some of them sold the C and C++ for far less (ANSI had the previous version in electronic form at 30$, BSI co-published an hard copy edition; I've not found yet such a source for the latest version)

*People of the committee are already contributing quite a lot of the costs (sometimes there is a fee, and then their time, they travel of their own expense, they provide sponsorship for the meetings)

*Other standardization may be cheaper to get but participation can be more costly (ECMA gives freely its standards, but the fee for participation is far higher).

A: Many of the older standards organisations do still charge for their standards, but IMHO it acts as a barrier to wider adoption of the standards.
Many standards organisations already manage to provide their standards free. IMHO organisations like ISO and ANSI seem quite outdated by still charging.
Here is an arbitrary personal selection of important standards that can apparently be published free.

*

*W3C. Here's the XML standard and the HTTP standard to download for free.

*Unicode standard published free online.

*ECMA. Here's the C# standard as a free download. Or, if you need a tax loss, it's 238 Swiss Francs from ISO.

*Open Geospatial Consortium standards which are important in GIS and web maps.

A: With regards specifically to ISO standards, there is a question/answer in their FAQ that addresses why ISO standards cost money:

ISO standards cost money to develop, publish and distribute. Someone has to pay. The current system whereby users are requested to pay for the standards they use, not only sustains the development process but also, very importantly, ensures that the balance of independent vs. government, private vs. public interests can be maintained.

With regards to other standards organizations, I suspect that Yannis Rizos is correct in his comment and that it is similar to the ISO's stance. It takes a lot of time and effort to develop a standard, and then transform it into a format that is consumable. You are paying for the time and resources that it took to turn that standard into the format that you are using and then have it delivered to you.


text:
Q: Android 4.3 Eclipse Android Device Chooser states version unknown I recently upgraded my Samsung Galaxy Nexus via an OTA update to 4.3. After doing the update, I am unable to install new debug software, because the "Target" is set to UNKNOWN. I have tried the following tricks that have been shown to work:

*

*Reboot phone

*Turn on/off debugging on phone

*Restart Eclipse

*Updating SDK tools (Both ADT and plugin)

I never had this problem when I was with 4.2, so I suspect is has something to do with the upgrade, but I'm not sure. Any thoughts?

A: Turns out a combination of things did the trick.

*

*On the device, go to the debug options (Debug activity in notifications)

*Revoke USB debugging information

*Restart Eclipse

*Look for a pop-up on the device asking for permission to connect to the device. Give it permission.

That seemed to do the trick.


text:
Q: How to have a custom button within a list view in JQuery Mobile? I want to have a custom button to appear on the right side of my list view header named 'Click Me', which will perform an action via the 'on click' event. As far as I know JQuery does not have a standard way to achieve this but perhaps you know how to achieve this.
As an illustration to what I want to achieve, take a look at http://jquerymobile.com/test/docs/buttons/buttons-icons.html.
Imagine now that you are looking at list headers where the data icon is on the right side and instead of it being an icon it says 'Click Me'. Furthermore, the List Header cannot be clickable like its elements, instead the data icon must be the only clickable element in here.
Please let me know if you have any ideas, even if this is simply impossible to achieve due to JQuery, thanks!

A: This is what I was looking for:

        Fruits

                Button

Apples

Grapes

Others

Note that the list divider contains a SPAN which acts as a button... quite ingenious :)
Anyways, thanks for your help!

A: You are looking for a Split Button list

A: This is an example you can put two icon buttons inside:
*

Opciones de platillo

Notas

                                Tiempo

                              Plus
                              Minus

                                Comensal

                              Plus
                              Minus

Modificadores

Terminadores


text:
Q: An experiment is repeated, and the first success occurs on the 8th attempt. What is the success probability for which this is most likely to happen? An experiment is repeated, and the first success occurs on the 8th attempt. What is the success probability for which this is most likely to happen?
So we want to find $p$ between $0$ and $1$ which maximizes $(1-p)^{7}p$. To do this we could take the derivative and find all the critical points:
$$(1-p)^7 - 7(1-p)^6p = 0$$
But I don't know how to get the roots of this equation by hand. What can I do instead to solve this problem?

A: $$(1-p)^7-7(1-p)^6p=(1-p)^6(1-p-7p)=(1-p)^6(1-8p)$$
Thus, for extremum,
$$(1-p)^6(1-8p)=0$$
$$p=1 \text{ or }p=\frac18$$
The boundary values are $p=0$ and $p=1$, both which constitute zero probability. Moreover, by the second derivative test, it can be seen that $p=\frac18$ is a point of maximum.
Hence,
$$p=\frac18$$

A: Go ahead and solve for where the derivative is zero:
$$(1-p)^7-7(1-p)^6p=0$$
$$(1-p)^6(1-p-7p)=0$$
$$(1-p)^6(1-8p)=0$$
$$1-p=0\text{ or }1-8p=0$$
$$p=1\text{ or }p=\frac18$$
We reject $p=1$ because then the experiment would succeed on the first try. $p=0$ can also be rejected for obvious reasons, so $p=\frac18$.


text:
Q: Assertions in C89? I'm writing C89 on MSFT Visual Studio 2010 Beta. How can I make an assertion, similar to Java's assert keyword? I think I need to define a macro, but I'm not sure how. (It seems like this is something that's been done before, so I'd rather use that than try to roll my own.)
Here's a guess:
int assert(int truth_value) {
   // crash the program with an appropriate error message
}

A: C89 has <assert.h>, which contains the macro you're looking for.
#include <assert.h>
assert(expression);

From the documentation:

The assert() macro tests the given expression and if it is false, the
  calling process is terminated.  A diagnostic message is written to stderr
  and the abort(3) function is called, effectively terminating the program.
If expression is true, the assert() macro does nothing.


text:
Q: What is the problem with my Love2D Support extension for VS Code? I am trying to run Lua directly from VS Code. I installed the Love2D Support extension for this. But the program does not run with Ctrl+L.
Here is where Love is installed on my computer:

These are my settings for the Love2D Support extension:

I don't understand why Love is not working from VS Code with Ctrl+L.

A: I'm not sure what's happening in VSCode, but you can drag the folder your main.lua file is in and drop it onto LÖVE2D to run it.

A: The command to run Lua directly from VS Code using the LOVE2D extension is alt + L and
Not ctrl + L which selects the full line.
If the problem proceeds, make sure that LOVE is installed in Program Files because this is where the LOVE2D extension is going to look for LOVE by default.
Alternatively, you can specify LOVE's file path in the LOVE2D extension's settings.