text:
Q: Using Zend_Form to do validation in view and model In this book (the link goes to the part I'm interested in) it is suggested that you could use a single instance of Zend_Form to put both Model and View validations. I'm wondering exactly how to do this, considering the forms will probably not correspond exactly to the structure of the models. How can this be achieved? It sounds logical to not duplicate the code that does validation, but I have always done it separately.

A: This article from ZF Project Lead Matthew Weier O'Phinney explains one approach:
http://weierophinney.net/matthew/archives/200-Using-Zend_Form-in-Your-Models.html


text:
Q: Migrate normal sqlite3 database to core data? I have a normal pre-populated database. I want to migrate it to core data for my app. What is the best way to achieve this. By the way I have done these things, copied the recipes.sqlite database from apple's sample.exported a table sql. Rename the column names according to the core data table columns(something like this - id "primary key" with Z_PK). filled that table with my values. But i am unable to understand the columns names Z_ENT and Z_OPT. Does some one knows how do i migrate my prepopulated sqlite3 database to core data easily.
Thanks

A: Do not try and manually create a Core Data SQLite file. That is a road to failure; every time.
If you have a pre-existing SQLite file then use straight SQLite tools to access it and import it into Core Data using Core Data.  Once you have the data in a Core Data stack, save out that file and then use the resulting SQLite file.
The internal structure of the Core Data SQLite file is designed to be opaque and should not be reverse engineered.  Apple makes no guarantee that the file structure will stay the same. They have changed it several times already since Core Data was released.
Import
To do the import, it would be just like any other file:

*

*You stand up the core data stack.

*You walk through each table and each row in the non-Core Data database.

*Create a new Core Data object for each row.

*Insert the data from the old row into the new object.

A: Try the following tool which migrates the Standard SQLite to Core Data Compatible Sqlite
https://github.com/tapasya/Sqlite2CoreData

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mapping entities based on type in Doctrine I've got abstract class called Question.
Now, i've got many types of questions, like OneToChooseFrom or ManyToChooseFrom that extends Question class.
What i want to do, is to store all these types of questions in the single 'questions' table and when i retrieve them, i want them to be mapped properly to OneToChooeFrom class or ManyToChooseFrom class based on question_type column.
I know i can use Single Table Inheritance for that, but i'm already using Class Table Inheritance. So i can't use them both at once.
/**
 * @ORM\Entity()
 * @ORM\InheritanceType("JOINED")
 * @ORM\DiscriminatorColumn(name="type", type="string")
 * @ORM\DiscriminatorMap({
 *      "description" = "Acme\SurveyBundle\Entity\Description",
 *      "question" = "Acme\SurveyBundle\Entity\Question"
 *     })
 * @ORM\Table(name="survey_item")
 */
abstract class Item
{
}

/**
 * @ORM\Entity()
 * @ORM\Table(name="survey_question")
 */
abstract class Question extends Item
{
    /**
     * @ORM\Column(name="question_type", type="string")
     *
     * @var string
     */
     protected $questionType;
}

final class OneToChooseFrom extends Question
{
    protected $questionType = 'oneToChooseFrom';
}

final class ManyToChooseFrom extends Question
{
    protected $questionType = 'manyToChooseFrom';
}


text:
Q: How to publish a playlist with libspotify I couldn't find any way to publish a playlist with libspotify. When i create a new playlist it's also not published by default.

A: There is unfortunately no API in libspotify for publishing/unpublishing playlists.


text:
Q: Winforms to WPF, measure text width(Graphics.MeasureCharacterRanges) We are trying to measure the width of text, as displayed (not the number of characters).
In Winforms there is a method called Grapihcs.MeasureCharacterRanges. In WPF, the FormattedText.WidthIncludingTrailingWhitespace.  While it would seem these would give the same value, they don't.  Why not?  For us Graphics.MeasurecharacterRanges, but we can't really pullin winforms, just for one method. It is a WPF app.

A: We are using the following utility class to perform simple text measurements in WPF:
public static class TextUtilities
{
    public static Size MeasureText(string text,
        FontFamily family, double size, FontStyle style, FontWeight weight, FontStretch stretch, TextFormattingMode formattingMode)
    {
        FormattedText formattedText = new FormattedText(
            text,
            CultureInfo.CurrentCulture,
            FlowDirection.LeftToRight,
            new Typeface(family, style, weight, stretch),
            size,
            Brushes.Black,
            null,
            formattingMode);

        return new Size(formattedText.Width, formattedText.Height);
    }

    public static Size MeasureText(string text, TextBlock textBlock)
    {
        return MeasureText(text,
                    textBlock.FontFamily,
                    textBlock.FontSize,
                    textBlock.FontStyle,
                    textBlock.FontWeight,
                    textBlock.FontStretch,
                    TextOptions.GetTextFormattingMode(textBlock));
    }

    public static Size MeasureText(string text, Control control)
    {
        return MeasureText(text, control.FontFamily, control.FontSize,
            control.FontStyle, control.FontWeight, control.FontStretch,
            TextOptions.GetTextFormattingMode(control));
    }
}

A: WPF uses a device-independent unit for most measurements of graphics elements, and it's likely different than the units used for WinForms. See this link on MSDN regarding the Height property of FrameworkElements, and the units used.


text:
Q: Node 16 build fails in Dockerfile - class SocksProxyAgent extends agent_base_1.Agent The Dockerfile
FROM node:16.17.1-alpine

RUN apk add --no-cache \
    python3 \
    py3-pip \
    git \
    openssh-client \
    vim \
    jq \
    aws-cli \
    && rm -rf /var/cache/apk/*

RUN apk add --no-cache yarn

WORKDIR /app
COPY package.json ./
COPY yarn.lock ./

RUN HOME=/kaniko/ yarn install --frozen-lockfile

COPY . .
RUN yarn build
EXPOSE 4000
CMD ["sh", "startup.sh"]

When I run docker build I get the following error:
$ npm run build:types && npm run build:js
/usr/local/lib/node_modules/npm/node_modules/socks-proxy-agent/dist/index.js:110
class SocksProxyAgent extends agent_base_1.Agent {
                                           ^
TypeError: Class extends value undefined is not a constructor or null
    at Object.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/socks-proxy-agent/dist/index.js:110:44)
    at Module._compile (node:internal/modules/cjs/loader:1126:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
    at Module.load (node:internal/modules/cjs/loader:1004:32)
    at Function.Module._load (node:internal/modules/cjs/loader:839:12)
    at Module.require (node:internal/modules/cjs/loader:1028:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/make-fetch-happen/lib/agent.js:174:29)
    at Module._compile (node:internal/modules/cjs/loader:1126:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
    at Module.load (node:internal/modules/cjs/loader:1004:32)
    at Function.Module._load (node:internal/modules/cjs/loader:839:12)
    at Module.require (node:internal/modules/cjs/loader:1028:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/make-fetch-happen/lib/remote.js:7:18)
    at Module._compile (node:internal/modules/cjs/loader:1126:14)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
error building image: error building stage: failed to execute command: waiting for process to exit: exit status 1

The error started after I updated the Node to 16 instead of 14 and ran yarn upgrade.
Please advise how can I resolve this?

A: The issue was resolved after I replaced the various commands in package.json from npm to use yarn.


text:
Q: JSF Managed bean values return null I encountered a problem when I was deploying my Login.xhtml. I keep getting null values for my userName and passWord values even though I have use the userManagerBean.userName and userManagerBean.passWord to store the values input by the user.
Any help?
My codes are below.
Thanks! :)
Login.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <h:head>
        <title>Facelet Title</title>
    </h:head>
    <h:body>
        <h:form>
            <h:outputText value="Username: " />

            <h:outputText value="Password: " />

            <h:outputText id="status" value="#{userManagerBean.loginStatus}" />
        </h:form>
    </h:body>

UserManagerBean.java
package managedbean;

import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.event.ActionEvent;
import javax.inject.Named;
import session.stateless.SystemUserSession;

@Named(value = "userManagerBean")
@RequestScoped
public class UserManagerBean {

    @EJB
    private SystemUserSession systemUser;
    private String userName;
    private String passWord;
    private String eventNameLength;
    private String loginStatus;

    /**
     * @return the userName
     */
    public String getUserName() {
        return userName;
    }

    /**
     * @param userName the userName to set
     */
    public void setUserName(String userName) {
        this.userName = userName;
    }

    /**
     * @return the passWord
     */
    public String getPassWord() {
        return passWord;
    }

    /**
     * @param passWord the passWord to set
     */
    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    /**
     * @return the eventNameLength
     */
    public String getEventNameLength() {
        return eventNameLength;
    }

    /**
     * @param eventNameLength the eventNameLength to set
     */
    public void setEventNameLength(String eventNameLength) {
        this.eventNameLength = eventNameLength;
    }

    public void buttonAction(ActionEvent actionEvent) {
         System.out.println("Welcome to Primefaces!!");
    }

  public String loginResult()
  {
      System.out.println(userName +" "+passWord);
     if(systemUser.getSystemUser(userName,passWord) == null)
     {
         System.out.println("No user found");
         System.out.println(userName +" "+passWord);
         loginStatus = "No user found";
          return "No user found";
     }
     else
     {
         System.out.println("Successful login");
         loginStatus = "Successful login";
          return "Successful login";
     }

  }

    /**
     * @return the loginStatus
     */
    public String getLoginStatus() {
        return loginStatus;
    }

    /**
     * @param loginStatus the loginStatus to set
     */
    public void setLoginStatus(String loginStatus) {
        this.loginStatus = loginStatus;
    }
}

SystemUserSession.java
package session.stateless;

import entity.SystemUser;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
@LocalBean
public class SystemUserSession {

    @PersistenceContext
    private EntityManager entityManager;

    public SystemUser getSystemUser(String userName, String passWord) {
        Query query = entityManager.createQuery("SELECT u FROM SystemUser u WHERE u.userName = :inUserName AND u.password = :inPassWord");
        query.setParameter("inUserName", userName);
        query.setParameter("inPassWord", passWord);
        SystemUser systemUser = null;
        try {
            systemUser = (SystemUser) query.getSingleResult();
        } catch (NoResultException ex) {
            //ex.printStackTrace();
        }
        return systemUser;
    }
}

A: p:ajax defaults to processing @this, which means that the values of the inputText's will never be updated on the bean.
Besides, p:commandButton has ajax capabilities by itself, and it even defaults to process="@form" which is what you want.
So just change the button to

Besides I would make the bean @SessionScoped, since you need to remember the loginStatus for the whole session.


text:
Q: Using colors in a selector xml I want to set colors for clicking instead of images.  Doing so doesn't give any errors except for force-closing at runtime.  Is it even possible to do this or can selector only be used for images?
Code I'm trying below:

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_focused="true" android:state_pressed="true" android:background="#00C0FF" />
    <item android:state_focused="true" android:state_pressed="false" android:background="#0060FF" />
    <item android:state_focused="false" android:state_pressed="true" android:background="#00C0FF" />
    <item android:state_focused="false" android:state_pressed="false" android:background="#FFFFFF" />

</selector>

A: Not per the documentation
<item>
     Defines a drawable to use during certain states, as described by its attributes. Must be a child of a <selector> element.

    android:drawable
        Drawable resource. **Required.** Reference to a drawable resource.

You can create a simple shape drawable to hold the color
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#33FF33"/>
</shape>

A:
Is it even possible to do this or can selector only be used for images?

No, this doesn't make any sense (to me at least). Without a 'drawable', how will it know exactly 'what' to set to state_focused and state_pressed?
Why not just create some single colour drawables (bitmaps for example) and provide those as the drawables for each item?


text:
Q: mvc 5 code first userid as a Foreign Key - How to save data Using MVC5 code first approach.
I haven't changed the user store, added a property called Name in ApplicationUser Class. So it looks like as follows : -
public class ApplicationUser : IdentityUser
{
    [Required]
    [StringLength(100)]
    public string Name { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }
}

I have a company class, which looks like below :-
public class Company
{
    public int Id { get; set; }

    [Required]
    [StringLength(255)]
    public string Name { get; set; }
}

A company will definitely has more than one user, but in my design a user can be associated with more than one company. So I have a separate class for CompanyUsers which looks as follows :-
public class CompanyUsers
{
    public int Id { get; set; }

    [Required]
    public virtual Company Company { get; set; }

    [Required]
    public virtual ApplicationUser User { get; set; }
}

Now, when I register a user, I'm setting its role and also companies that the user belongs to, but seems like the UserManager defined in the built-in code has already saved it. So after adding CompanyUsers data, when I call applicationDbContext.Savechanges() it fails as the user has already been saved in the database. Can you tell me how I can achieve it? I can do it in some other logic, like after creating a user, in a separate function assign users to company(s), but I want to know the solution in this circumstances. Also I can redesign the user store.
My modified register function in AccountController is as follows :-
[HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email, Name = model.Name };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await UserManager.AddToRoleAsync(user.Id, model.Role);
                var userCompany = new CompanyUsers
                {

                    Company = _context.Companies.First(t => t.Id == model.CompanyId),
                    User = user
                };

                try
                {
                    _context.CompanyUsers.Add(userCompany);
                    _context.SaveChanges();// throws exception
                }
                catch (DbEntityValidationException dbEx)
                {
                    foreach (var validationErrors in dbEx.EntityValidationErrors)
                    {
                        foreach (var validationError in validationErrors.ValidationErrors)
                        {
                            Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                        }
                    }
                }
                return RedirectToAction("UserViewAll", "Manage");
            }
            AddErrors(result);
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

I have just started mvc code first approach, so I may not understand if you use technical jargon, thanks In Advance for your help!!!!!

A: Try adding the following code in the if (result.Succeeded) block:
_context.Entry(user).State = EntityState.Unchanged;

The issue appears to be that the data context in this method does not know the state of the user entity because UserManager.CreateAsync uses a separate context. The entity is attached when you assign it to the CompanyUser entity, and then this data context tries to save it as a new entity.


text:
Q: Changing position of words in a string I have a string let say,
string temp1 = "25 10 2012"

but I want this,
"2012 10 25"

what would be the best way of doing it. format will always be like this.

A: try this split string and reverse array , and this will work for string of any length ...
string[] myArray = temp1.Split(' ');
 Array.Reverse( myArray );
string reverse =string.Join(" ", myArray );

A: Looks like its a date. You can parse the string to DateTime, using DateTime.ParseExact and then use .ToString to return formatted result.
DateTime dt = DateTime.ParseExact(temp1, "dd MM yyyy", CultureInfo.InvariantCulture);
Console.Write(dt.ToString("yyyy MM dd"));

You may use that DateTime object later in your code, and also apply different formatting (if you need)

A: You could do it using the Split command and then recombining the sub strings:
String[] subStrs = temp1.Split( ' ' );
String   final   = subStrs[2] + " " + subStrs[1] + " " + subStrs[0];

A: So you want to split words and change the order, you can use LINQ:
var words = temp1.Split(' ');
String newWord = string.Join(" ", words.Reverse());

or if you don't want to swap all words but only swap the first and last word:
String first = words.Last();
String last = words.First();
String newWord = first + " "
                 + string.Join(" ", words.Skip(1).Take(words.Length - 2))
                 + " " + last;

A: You could either use a RegEx or split the string and rejoin it in reverse order.
string s = "2012 10 25";
string[] tokens = s.Split(' ');
Array.Reverse(tokens);
string final = string.Join(" ", tokens);

A: If Your string has always 10 character (with spaces), You can do the following:
string str = "26 10 2012"
str = str.Substring(6, 4) + " " + str.Substring(3, 2) + " " + str.Substring(0, 2)

A: you can use string.split(" ").reverse().join(" ").
You can use split, this function will split your string to array on white space as condition then reverse the array and re join based on white space

let string="25 10 2012";
let output=string.split(" ").reverse().join(" ");

console.log(output)


text:
Q: Routes not working without index.php Im using laravel 4.
I have a view nest.blade.php and the corresponding controller NestController.php:
Controller content:
class NestController extends BaseController {

    public function showView()
    {
        return View::make('nest');
    }

}

Route:
Route::get('/nest', 'NestController@showView');

When I go to url/nest it doesnt work.
When I go to url/index.php/nest it does work.
Obviously I just want it to be /nest without the index.php.
How can i resolve this?
My htaccess:
IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes...
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

A: I enabled the mod_rewrite module in the Apache HTTP server, restarted Apache service and tested again and it WORKED!!!
Below is the code i used to enable mode_rewrite;
1) Un-Hash this line in Apache/conf/httpd.conf

LoadModule rewrite_module modules/mod_rewrite.so

2) Create a new configuration for "sample-project" without modifying the default configuration in the httpd.conf file

Directory "C:/Apache24/htdocs/sample-project">
  Options Indexes FollowSymLinks MultiViews
  AllowOverride All
  Order allow,deny
  Allow from all
Directory>

A: Be Alert! If it is not working even after enabling rewrite module. You need to change the line "AllowOverride None" to "AllowOverride All" in httpd.conf.
As @The Alpha alerted, Laravel don't need to be configured for this purpose.

A: When you change the line AllowOverride None to AllowOverride All in httpd.conf be sure that you do it inside <directory ...> that contains valid path.
Example
<Directory "/var/www/html"> #check path
   Options Indexes FollowSymLinks
   AllowOverride All
</Directory>

A: For some reasons the answers above are not working for me, so here is the only one that worked for me.
I am using ubuntu 18.04 amd64 as my development server environment.
So I modified apache.conf file located at/etc/apache2

From:

<Directory /var/www/> Options Indexes FollowSymLinks AllowOverride None Require all granted

To:

<Directory /var/www/> Options Indexes FollowSymLinks AllowOverride All Require all granted

And Also From:

<Directory /usr/share> AllowOverride None Require all granted

To

<Directory /usr/share> AllowOverride All Require all granted

After that, you need to restart apache using sudo service apapche2 restart command in the terminal
Now I can access the page without using index.php in the URL
Credit goes to: joshymatheww @ Laracasts servers discussion channel on
Aug 5, 2017

A: Login to the terminal
sudo nano /etc/apache2/apache2.conf

After line
<Directory /var/www/>
.
.
.
</Directory>

and paste below code
<Directory /var/www/html/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride All
</Directory>

Now Ctrl+O and then Ctrl+M and then Ctrl+x
Now restart apache server
sudo service apache2 restart

A: First of All you need to set AllowOverride All in /etc/apache2/apache2.conf. Find the following block:
<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride All
        DirectoryIndex index.php
        Require all granted
</Directory>

then you need to modify /etc/apache2/mods-available/dir.conf and move index.php first :
<IfModule mod_dir.c>
        DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm
</IfModule>

AND DO NOT FORGET: Run a2enmode
sudo a2enmod rewrite

and then
sudo service apache2 restart

This way you apply it for all your laravel projects (inside /var/www/ folder).

A: Pretty URLs

The framework ships with a public/.htaccess file that is used to allow
  URLs without index.php. If you use Apache to serve your Laravel
  application, be sure to enable the mod_rewrite module.

If the .htaccess file that ships with Laravel does not work with your
 Apache installation, try this one:
Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

For more related help, check this answer.

A: set this in your .htaccess
DirectoryIndex index.php

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

RewriteEngine On

RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
RewriteRule ^(.*) - [E=BASE:%1]

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^index\.php(/(.*)|$) %{ENV:BASE}/$2 [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f
RewriteRule .? - [L]

RewriteRule .? %{ENV:BASE}/index.php [L]

A: Try the following .htaccess. I never had any trouble with that on a server or localhost environment.
DirectoryIndex index.php
    <IfModule mod_rewrite.c>
        <IfModule mod_negotiation.c>
            Options -MultiViews
        </IfModule>

        RewriteEngine On

        RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
        RewriteRule ^(.*) - [E=BASE:%1]

        RewriteCond %{ENV:REDIRECT_STATUS} ^$
        RewriteRule ^index\.php(/(.*)|$) %{ENV:BASE}/$2 [R=301,L]

        RewriteCond %{REQUEST_FILENAME} -f
        RewriteRule .? - [L]

        RewriteRule .? %{ENV:BASE}/index.php [L]

    </IfModule>


text:
Q: Event parent relationship fields are null in trigger I am populating a junction object on from Events and want to capture info from the Event but getting the Account from Account field pulls null. Same who the name via the Who. But if I query the Event record, the AccountId field is populated.
And of course, the code compiles properly. Can someone explain how to grab this related info?
trigger TripMeetingFromMeeting on Event (after insert, after update) {

    Set<id>EventId = new Set <ID>();
    List <Trip_Meeting__c> TMS = new List <trip_meeting__c>();

    for (Event E:trigger.new){
        if (e.Business_Trip__c!=null){
            TMS.add(new Trip_Meeting__c(Meeting__c =e.id, Business_trip__c=e.Business_Trip__c,
                                        Meeting_Date__c=e.ActivityDate, Meeting_subject__c=e.Subject,
                                       TripNameDELETE__c=e.Business_Trip__r.name,
                                        mWhatID__c=e.Whatid,
                                       Meeting_Company__c=e.Account.name,
                                       Meeting_Name__c=e.Who.name)
                                        );

        }
    }
    system.debug('TMS!!!============================'+TMS);
     Database.insert(tms, false);

}

A: This problem has a very simple solution, but first we need to understand the reason. You are using trigger context variables in iteration and trigger context variables i.e. trigger.new, trigger.old etc. do not query value of relationship field. So you can access e.AccountId, e.WhoId but not e.Account.Name or e.Who.Name. This is applicable to all triggers not just code that you have written.
To solve this problem you have two options:

*

*If you are in a after trigger, which you are in current situation you can write a query on your base object(Event) and query all fields that you need including relationship fields. so your code will be something like this:
trigger TripMeetingFromMeeting on Event (after insert, after update)
{
    Set<id>EventId = new Set <ID>();
    List<Trip_Meeting__c> TMS = new List <trip_meeting__c>();
    List<Event> events = [Select Id, Business_Trip__c, ActivityDate, Subject, Business_Trip__r.name, e.Whatid, Account.Name, Who.Name From Event Where Id in : trigger.new];
    for (Event E: events){
        if (e.Business_Trip__c!=null){
            TMS.add(new Trip_Meeting__c(Meeting__c =e.id, Business_trip__c=e.Business_Trip__c,
                                Meeting_Date__c=e.ActivityDate, Meeting_subject__c=e.Subject,
                               TripNameDELETE__c=e.Business_Trip__r.name,
                                mWhatID__c=e.Whatid,
                               Meeting_Company__c=e.Account.name,
                               Meeting_Name__c=e.Who.name)
                                );

        }
    }
    system.debug('TMS!!!============================'+TMS);
    Database.insert(tms, false);
}

*If you are in a before trigger, you need to process in three step, pre-process, query, post-process.
(a) Pre-Process - Build a set of Id for each related object that you want to access e.g. Account, User etc.
(b) Query - Write a query for each object and assign result to Map, where sobject should be your real object e.g. Account, User etc.
Map<Id, Account> accountMap = new Map<Id, Account>([Select Id, Name From Account Where Id in: accountIds]);

(c) Post-Process - In this step you iterate on trigger context variables and when it comes to access related object field you located that object from Map created in query step and access related field.
account.get(e.AccountId).Name;


text:
Q: How to use Linq group a order list by Date I have a order list and want to group them by the created date.
Each order's created datetime will be like "2010-03-13 11:17:16.000"
How can I make them only group by date like "2010-03-13"?
 var items = orderList.GroupBy(t => t.DateCreated)
 .Select(g => new Order()
 {
     DateCreated = g.Key

 })
 .OrderByDescending(x => x.OrderID).ToList();

Update: How can I group order by month? And the following code is not correct.
var items = orderList.GroupBy(t => t.DateCreated.Month)
 .Select(g => new Order()
 {
     DateCreated = g.Key

 })
 .OrderByDescending(x => x.OrderID).ToList();

Many thanks.

A: Use the Date property.
var items = orderList.GroupBy( t => t.DateCreated.Date )

A: Using the .Date will discard the time component, e.g.
var items = orderList.GroupBy(t => t.DateCreated.Date)

A: Use t => t.DateCreate.Date.


text:
Q: Are two sequences equal if the sums and sums of squares are equal? Are two sequences $(x_i)_{i=1,\ldots,n}$ and $(y_i)_{i=1,\ldots,n}$ equal if $\sum_{i=1}^nx_i=\sum_{i=1}^ny_i$ and $\sum_{i=1}^nx_i^2=\sum_{i=1}^ny_i^2$?

A: There are many examples. Here's the first in a long sequence:
$$
(1,4,6,7) \quad (2,3,5,8).
$$
This comes from the first eight entries in the Thue Morse sequence (third line below). The fourth line specifies two sets of eight numbers with the same sum, sum of squares and sum of cubes.
AB
AB BA
ABBA BAAB
ABBABAAB BAABABBA
...

The Prouhet-Tarry-Escott problem and generalized Thue-Morse sequences. J. Comb. 7 (2016), no. 1, 117--133, [Bolker, Ethan D. and Offner, Carl and Richman, Robert and Zara, Catalin]
Here's the preprint: https://arxiv.org/abs/1304.6756

A: No.
$$ x = (1,1,1,-3) $$
$$ y = (-1,-1,-1,3) $$
$$\sum x_i = \sum y_i = 0$$
$$ \sum x_i^2 = \sum y_i^2 =12$$

A: No! You need $n$ polynomial equations.
If I remember correctly, given a set of $n$ distinct real numbers $\mathcal Y :=\{y_1, y_2, \dots, y_n\}$, the following system of $n$ polynomial equations
$$\begin{array}{rl} x_1 + x_2 + \dots + x_n &= c_1\\ x_1^2 + x_2^2 + \dots + x_n^2 &= c_2\\ \vdots \\ x_1^n + x_2^n + \dots + x_n^n &= c_n\end{array}$$
where
$$c_k := y_1^k + y_2^k + \dots + y_n^k$$
has $n!$ solutions, namely, all $n!$ permutations of the $n$ distinct elements of $\mathcal Y$. One can use algebraic geometry to prove this. I vaguely recall this being related to moment problems.

Example
Let $\mathcal Y := \{1,3,6\}$. Intersecting the plane with the sphere,
$$\begin{array}{rl} x_1 + x_2 + x_3 &= 10\\ x_1^2 + x_2^2 + x_3^2 &= 46\end{array}$$
we obtain a circle on the plane, as depicted below

However, intersecting these two with the cubic surface,
$$\begin{array}{rl} x_1 + x_2 + x_3 &= 10\\ x_1^2 + x_2^2 + x_3^2 &= 46\\ x_1^3 + x_2^3 + x_3^3 &= 244\end{array}$$
we obtain the $3!=6$ permutations of the elements of $\mathcal Y$, which are colored in red

If we plot the quadratic and the cubic surfaces, but not the plane,

and, from another point of view, we have what looks like a stylish hat

A: Something interesting. On all $3 \times 3$ magic squares, the sums of the top and bottom rows is the same (of course) but, also, the sums of the squares of the top and bottom rows is the same. For example
\begin{array}{|c|c|c|}
\hline
   8 & 3 & 4 \\
\hline
   1 & 5 & 9 \\
\hline
   6 & 7 & 2 \\
\hline
\end{array}
$8 + 3 + 4 = 6 + 7 + 2 = 15$
$8^2 + 3^2 + 4^2 = 6^2 + 7^2 + 2^2 = 89$
Also
$8 + 1 + 6 = 4 + 9 + 2 = 15$
$8^2 + 1^2 + 6^2 = 4^2 + 9^2 + 2^2 = 101$
This seems to work for some families of larger order magic squares, but I haven't been able to prove it.

A: To consider an even more basic counterexample. What happens if you simply reorder your sequence? Take $x = (0,1)$ and $y = (1,0)$. (I assume you're talking about sequences, so above $x \neq y$; of course, as sets, $\{0,1\} = \{1,0\}$.)


text:
Q: Importing Anything in a Module Leads to 'Cannot resolve symbol' Error in Android Studio I simply wanted to create a Jar archive (.jar file) out of my classes using Android Studio. To do so, I created a module using File > New > New Module > Java Library. Then I wrote two classes (LocationAndroidPlugin, MyLocationService) in the module:

But Android Studio complains that it cannot resolve the import statements in the classes:

I tried File > Invalidate Cache in vain.
My Android Studio version is:
Android Studio 2.3.1
Build #AI-162.3871768, built on April 1, 2017
JRE: 1.8.0_112-release-b06 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o

A: You should not use Java Library option if you want to use serviceConnection, activity, or intent because it does not have Android classes. Instead, you must create the new module as an Android Library from File > New > New Module > Android Library.


text:
Q: How can I calculate the R-squared of a simple linear regression only with sample size, the coefficients and its standards deviations? I have the following estimated simple linear regression, which was estimated from a sample of 1217 individuals:
$\hat{y}=1.77663 + 0.0910103x$
where
$\hat{\beta_0} = 1.77663$ and standard deviation of $\hat{\beta_0} = 0.0865446$
$\hat{\beta_1} = 0.0910103$ and standard deviation of $\hat{\beta_1} = 0.0065643$
How can I calculate the R-squared?

A: The variance (squared standard error) of the slope is
$$\text{Var}(\hat{\beta_1}) = \frac{\hat\sigma^2}{ns_x^2} $$
The explained sum of squares is
$$ESS =  n\hat{\beta_1} ^2  s_x^2$$
The residual sum of squares is
$$RSS = (n-p)\hat\sigma^2$$
where $p$ is the number of parameters that are estimated in the regression.
So we have:
$$\frac{1}{R^2} -1 = \frac{RSS}{ESS} = \frac{n-p}{n} \frac{\hat\sigma^2}{ \hat{\beta_1}^2s_x^2} = \frac{(n-p)\text{Var}(\hat{\beta_1}) }{\hat{\beta_1^2}} = (n-p)\left(\frac{S.E. (\hat\beta_1)}{\hat{\beta_1}} \right)^2$$
And consequently
$R^2 =  \frac{1}{1+ (n-p)\left(\frac{S.E. (\hat\beta_1)}{\hat{\beta_1}} \right)^2}$
### Computational example

### create some data
set.seed(1)
n = 1217
x <- rnorm(n,0,1)
eps = rnorm(n,0,0.1)
y = 1 + 0.1*x + eps

### model
mod <- lm(y~x)
plot(x,y)
lines(x,predict(mod))
out <- summary(mod)

### compare R^2 formula
1/(1+(n-2)*(out$coefficients[2,2]/out$coefficients[2,1])^2)
out$r.squared

### output
# > 1/(1+(n-2)*(out$coefficients[2,2]/out$coefficients[2,1])^2)
# [1] 0.4852368
# > out$r.squared
# [1] 0.4852368

In your case it is
$$R^2 = \frac{1}{1+(1217-2)\left(\frac{0.0065643}{0.0910103}\right)^2} = 0.1365971$$


text:
Q: Problems turning on or restarting Ubuntu 20.04 LTS A few days ago I updated the repositories and since the date it does not start normally, I have to access the grub, choose a kernel and I can just start.
Ubuntu does not start in normal mode, I have to access the grub and choose the kernel version to start, in this case only 5.4.0-31-generic, otherwise it never starts the OS.

A: *

*can you tell, what kind of update you made? Was is 18.04 to 20.04?

*What kind of hardware do you use?

*Whats your setup (single boot or multiboot with Windows)?

*Legacy Bois or UEFI? If UEFI, try Legacy

*TPM 1.2 or TPM 2.0 activated? If yes, try to disable it

*is your BOIS version update2date?

Maybe this Links here can help you


text:
Q: Calculating min and max over a list of dictionaries for normalizing dictionary values I want to calculate certain statistics over a list of dictionaries which looks something like this:
list1 = [{'hello': "world", 'score': 1.2}, {'hello': "world", 'score': 1.5}, {'hello': "world", 'score': 1.02},
         {'hello': "world", 'score': 1.75}]

Specifically, I want to find the min, max, and normalized value of the values associated with score key (meaning I have to update the existing dictionary).
I have implemented it the obvious way which is as follows. However, I was wondering if there is a better way to achieve this?
list1 = [{'hello': "world", 'score': 1.2}, {'hello': "world", 'score': 1.5}, {'hello': "world", 'score': 1.02},
         {'hello': "world", 'score': 1.75}]

def min_value(rank_norm):
    list_values = []
    for x in rank_norm:
        list_values.append(x['score'])
    return min(list_values)

def max_value(rank_norm):
    list_values = []
    for x in rank_norm:
        list_values.append(x['score'])
    return max(list_values)

def normalize_dict(rank_norm, min_val, max_val):
    for x in rank_norm:
        x['score'] = (x['score']-min_val)/(max_val - min_val)
    return rank_norm

min_val_list = min_value(list1)
max_val_list = max_value(list1)

print(min_val_list)
print(max_val_list)

print("Original dict:  ", list1)
print("Normalized dict: ", normalize_dict(list1, min_val_list, max_val_list))

I am using Python 3.

A: You can update your original dictionary like this:
list1 = [{'hello': "world", 'score': 1.2}, {'hello': "world", 'score': 1.5}, {'hello': "world", 'score': 1.02},
     {'hello': "world", 'score': 1.75}]
values = [i["score"] for i in list1]
minimum = min(values)
maximum = max(values)
normalized_dict = [{a:b if a == "hello" else (b-minimum)/float(maximum-minimum) for a, b in i.items()} for i in list1]

Output:
[{'score': 0.24657534246575336, 'hello': 'world'}, {'score': 0.6575342465753424, 'hello': 'world'}, {'score': 0.0, 'hello': 'world'}, {'score': 1.0, 'hello': 'world'}]

A: Pure Python
Yes, you can use a generator or list comprehension to obtain the minimum and maximum:
from operator import itemgetter

def min_value(rank_norm):
    return min(map(itemgetter('score'),rank_norm))

def max_value(rank_norm):
    return max(map(itemgetter('score'),rank_norm))

Your code to normalize the dictionary is fine. You can however use list comprehension to construct a new list with dictionaries. If you do not need to update the values, it tends to be safer to construct a new list, since it could be possible that some part of your code can reference to the old list or old dictionaries, and you do not per se want to change these:
def normalize_dict(rank_norm, min_val, max_val):
    delta = max_val-min_val
    return [dict(d,score=(d['score']-min_val)/delta) for d in rank_norm]

Pandas
In case the number of items is huge, you can boost performance by using a pandas dataframe:
import pandas as pd

df = pd.DataFrame(list1)
sc = df['score']
sc_mi = sc.min()
df['score'] = (sc-sc_mi)/(sc.max()-sc_mi)

Then the dataframe is:
>>> df
   hello     score
0  world  0.246575
1  world  0.657534
2  world  0.000000
3  world  1.000000

You can keep processing the dataframe, or if you want a list of dictionaries, you can use:
>>> list(df.T.to_dict().values())
[{'hello': 'world', 'score': 0.24657534246575336}, {'hello': 'world', 'score': 0.6575342465753424}, {'hello': 'world', 'score': 0.0}, {'hello': 'world', 'score': 1.0}]

A: You can combine the min/max computation into one, instead of building the list of scores twice and going over the list multiple times
from operator import itemgetter

min_val, max_val = itemgetter(0, -1)(sorted([x['score'] for x in list1]))

A: Here are more pythonic ways of max and min functions:
def min_value(rank_norm):
    return min([x['score'] for x in rank_norm])

def max_value(rank_norm):
    return max([x['score'] for x in rank_norm])

Not so much faster, but simpler. Also, here is normalize function with a single-line expression, this doesn't look nice, but works:
def normalize_dict(rank_norm, min_val, max_val):
    return [{'hello':x['hello'] , 'score':(x['score']-min_val)/(max_val - min_val)} for x in rank_norm]

A: Pandas
import pandas as pd

your_list = [{'hello': "world", 'score': 1.2}, {'hello': "world", 'score': 1.5}, {'hello': "world", 'score': 1.02},
     {'hello': "world", 'score': 1.75}]

#Reading in to a pandas dataframe
d = pd.DataFrame.from_dict(your_list)

your_list mapped in to a dataframe
print(d)
   hello  score
0  world   1.20
1  world   1.50
2  world   1.02
3  world   1.75

Calulating the stats and updating the score column
d['score'] = (d['score'] - min(d['score']))/(max(d['score'] - min(d['score'])))

How d looks like now,
print(d)
hello     score
0  world  0.246575
1  world  0.657534
2  world  0.000000
3  world  1.000000

Writing the updated dataframe d to a dictionary
updated = pd.DataFrame.to_dict(d, orient = 'records')
print(updated)

[{'score': 0.24657534246575336, 'hello': 'world'}, {'score': 0.6575342465753424, 'hello': 'world'}, {'score': 0.0, 'hello': 'world'}, {'score': 1.0, 'hello': 'world'}]

A: And yet another way to use of operator.itemgetter: sort the list based on the score, extract the min and max score, process..
import operator
a = [{'hello': "world3", 'score': 1.2},  .... ]

score = operator.itemgetter('score')
a.sort(key = score)
minimum = score(a[0])
maximum = score(a[-1])
span = maximum - minimum
for d in a:
    d['score'] = (d['score'] - minimum) / span


text:
Q: Test connection of azure SecretClient to azure KeyVault I was looking for api documentation for SecretClient but couldn't find a method that would test connection of a SecretClient to azure keyvault in python. Is there a way to check connection? My scenario is something like this:
token = ManagedIdentityCredential(client_id="abc-def-ghi")
client = SecretClient(vault_url="https://<name>.vault.azure.net", credential=token)

# Check connection:
is_connected = client.check_connection()

# So if the connection is established continue
if is_connected:
    # do something


text:
Q: mac crontab open application behaves differently than opening from Dock i wrote a shell script that checks if Microsoft Lync is running and Opens the app if not running. if i execute the shell script directly from bash terminal, it opens up Lync and as Remember Username/password is clicked it logs on fine.
the same script i entered in crontab entries to be run every minute so i can start Lync if not running already. But for some reason when the Lync is opened from this crontab script execution, the Lync application does not auto sign-in and asks me for the Lync password.
why is this behavior different ?
crontab entry -

* 9-17 * * 1-5 $HOME/lync.sh

#!/bin/bash

LYNC_PID=$(launchctl list | grep "Lync" | awk '{print $1}')

if [ "$LYNC_PID" = "" ]
then
echo "Lync not running"

ERROR_REPORTER_PID=$(ps -ef | grep -i "[m]icrosoft error reporting" | awk '{print $2}')
if [ "$ERROR_REPORTER_PID" != "" ]
then
    echo "Killing Microsoft Error Reporter"
    kill -9 $ERROR_REPORTER_PID
fi
echo "Starting Lync"
open /Applications/Microsoft\ Lync.app

fi

A: The Dock and other interactive commands running in a session have access to the session's information, including your keyring and the screen.  Cron has none of this.  Attempting to run interactive programs from crontab is doomed to fail, in pesky corner cases if not outright in the regular main usage scenario.


text:
Q: Referencing nuget packages from nuget package I have a nuget package which depends on several other ones (e.g. Newtonsoft.Json).
Package is not intended to use as a class library it only adds custom MSBuild action so the structure of the package looks like that:
-package CustomBuildAction
|-lib/net45/CustomBuildAction.dll
|-build/CustomBuildAction.targets

When I install the package CustomBuildAction.targets is correctly referensed from csproj but when I'm trying to run build I get an error that:
The "CustomBuildAction" task couldn't be loaded from assembly "path to dll/CustomBuildAction.dll". Could not load file or assembly 'Newtonsoft.Json.dll, Version=...' or one of its dependencies.
I have included Newtonsoft.Json.dll into nuspec file as a package dependency, nuget shows it as a dependency but MSBuild is unable to resolve it. For me it looks like the problem is that I'm referencing CustomBuildAction.dll from .targets file using relative path (relative to build folder) in packages folder, i.e.:
../lib/net45/CustomBuildAction.dll

But this dll isn't intended to be placed into the build output folder where it could find all its dependencies.
How can I resolve this issue? Should I include dependencies right into the package or there is another way to solve it?

A: MSBuild will resolve task dependencies from the folder containing the task assembly. Unfortunately, this means you need to include Newtonsoft.Json.dll in your NuGet package along side your CustomBuildAction.dll file.
To prevent the assemblies from ending up in build output, put the assemblies into a different folder in the package. For examples, tools/  as long as it's not in lib, it won't be treated as an assembly that is available to reference.


text:
Q: access static file in public_html/tmp without going trough controller in cakephp I have uploaded my cakephp app to cpanel and adjust and configure it to works with cpanel. Everything mostly works, however i find out that try to retrieve static file from tmp in public_html result in error. It tries to go to controller i think.
My structure is like this :
/cakephp139
          /cake
          /vendors
          /renttycoons  <= this is app folder
/public_html
          /tmp
          /js
          ....

I tried to access www.domain.com/tmp/test.csv, but result in errors although the test.csv was there. This is the error :
Error: The requested address '/403.shtml' was not found on this server.
Any idea would be appreciated. Thanks

A: does it gives you cake like error? it seems like a permission error.
erorr 403 is forbidden error, not a not found or something like that. Your server gives you that error and tries to show you a page for that error that is not found so you are receiving a 404 for not having a page for a 403 error hehe.
It must be a permission error, try changing permission to 705 in the temp folder, your test.csv file included. If you are creating it with php, php normally creates them with the minimun permission, at least that happened to me... you may use chmod function in php to change the permissions after creating a file.


text:
Q: grep/ack on Mac OS X finding multiple strings and respecting file types I would like to run grep on Mac OS X that would meeting the following criteria:

*

*search all files with *.R or *.r as extension and ignore other files

*Find strings: wordA and wordB accounting for the fact that the strings may appear in the format someRubbishWordARubbish (this is a valid match)

*List only the files where both strings appear irrespectively of the order

*Print the lines where the strings appear

*Highlight the found words in colour

*Print the file name as a header and lines under the header. I'm inspired by the ack options.

*Ignoring the case

Approach
I was thinking of making use of this discussion and starting with the following grep syntax:
grep --include=*.R -r setHeader .

Then combining it with the following:
grep 'word1\|word2\|word3' /path

However, I would appreciate comments on ensuring that all of the criteria stated above will be evaluated correctly.
Groups
^(.*)(facet|map)(.*)(map|facet)(.*)$

regex101

Ack
Running ack -f shows that *.R files would be searched so solutions using ack will be accepted. For example, running:
ack wordA --colour -i -H --rr

gets the desired results with respect to the wordA. I was thinking of combining it the solutions discussed here but I would like to use AND not OR and ignore the order in which strings may appear. I further tried:
ack --match wordA --match wordB  --colour -i -H --rr

But this produced only the results for wordB.

A: Well, this is pretty inefficient, but assuming you aren't searching a large directory, this should work.
find . -iname "*.r"  | while read file
do
if (grep -qi "wordB" $file && grep -qi "wordA" $file)
  then
  echo "======== $file ======="
  grep --color=auto -iE "wordA|wordB" $file
  fi
done

A: Here's a script that combines the closely-named awk and ack commands:
find . -iname '*.r' | while read file; do
    awk '
        BEGIN { IGNORECASE=1; sawWordA = 0; sawWordB = 0 }
        /wordA/ { sawWordA = 1 }
        /wordB/ { sawWordB = 1 }
        sawWordA && sawWordB { exit } # stop reading lines if both matches seen
        END { exit !(sawWordA && sawWordB) }
        ' \
        "${file}" \
    && ack --nofilter -H -i 'wordA|wordB' "${file}"
done

The awk command...

*

*Lists only the files where both strings appear irrespectively of the order

*Ignores the case

...and the ack command...

*

*Prints the lines where the strings appear

*Highlights the found words in colour

*Prints the file name as a header and lines under the header inspired by the ack options

*Ignores the case

The awk script sets flags if there are search string matches. If both strings have been matched, then the snippet exit !(sawWordA && sawWordB) will return 0. If awk returns 0, then the ack command runs.
The ack --nofilter option tells ack to avoid reading from STDIN. Otherwise, ack would try to use the STDIN that the read command is using.
In the comments, Konrad asked how to use the above code when passing in variables in a shell script. Below is an example:
#!/bin/sh

if [ $# -ne 2 ]; then
    echo Usage: $0 {string1} {string2}
    E_BADARGS=65
    exit $E_BADARGS
fi

find . -maxdepth 1 -iname '*.r' | while read file; do
    awk "
        BEGIN { IGNORECASE=1; sawArg1 = 0; sawArg2 = 0 }
        /$1/ { sawArg1 = 1 }
        /$2/ { sawArg2 = 1 }
        sawArg1 && sawArg2 { exit } # stop reading lines if both matches seen
        END { exit !(sawArg1 && sawArg2) }
        " \
        "${file}" \
    && ack --nofilter -H -i "$1|$2" "${file}"
done

The above example doesn't escape any special characters in the arguments provided to the script. If escaping is needed, the script can be modified as needed.


text:
Q: How can i build a db_select, ->condition comparing a field with a value in drupal with php im trying to make a field with the results of a sql in php . im trying to make a condition with the field "manifestacionType" and compare with value 'compuesta'.
The problem is that i dont know to do that. I think the problem is that n.manifestacionType dont access to the real value of this field and never compare. I try some things like ['und']['value'], with ->node, but nothing work!!! i dont know to built this. im so desesperated!
Here is my code:
$query = db_select('node', 'n')
        ->fields('n', array('nid', 'title'))
        ->condition('n.type', 'manifestacion_cultural', '=')
        ->condition('status', 1,'=')
      **->condition('n.manifestacionType', 'compuesta', '=')**
                ->orderBy('title');
$result = $query->execute()->fetchAllKeyed();
return $result;

the result of this is nothing, and if i remove the condition in **, i receive all of 'manifestacion_cultural' with status =1 (publicated). I need to add a filter that with a condition to receive only with 'manifestacionType' (this a field) = 'compuesta'. Most probably there are some better solutions for creating a field or ways to do this querys but i dont know how.
thanks so much!

A: I don't know if I unerstood your question correctly, so, please correct me if doesn't what you want:
You have a field called "manifestacion Type", then you want to obtain those node results where the content type is "manifestacion_cultural" and "manifestacion Type" field value is equal to "compuesta".
In that case, you need to built a db_select using a join between the node table and the "manifestacion Type" field  table, please access to your database and check the name of the "manifestacion Type" field table, drupal always create a field table like this: field_data_fiel_machine_name
$query = db_select('node', 'n')
  ->fields('n', array('nid', 'title'))
  ->condition('n.type', 'manifestacion_cultural', '=')
  ->condition('status', 1, '=');
  ->join('fiel_data_manifestacionType_table', 'mt', 'n.nid = mt.nid');
  ->condition('mt.fiel_manifestacionType_value', 'compuesta', '=');
  ->orderBy('n.title', 'ASC');

$result = $query->execute()->fetchAllKeyed();


text:
Q: How to organize in folders the UnitTests when the source code is in many folders? THe source code of my the legacy application I am maintaining is in many folders and subfolders.
I am starting creating unittests as a base for refactoring.
Do you suggest I put all tests in a single place or for every folder of code i create a subfolder called \FolderNameTests ?
Or do you have other suggestions?

A: I think it makes sense to have a src folder for your source, and a tests folder for your tests, and the the directory structure under test should match the directory structure under source.
For Java, where packages affect member visibility, this is particularly important, because the directory structure reflects the packages.  So not following the convention will mean you might not be able to test protected/default visibility scoped methods.

A: I would replicate the structure so that you know where things are by looking at the original sources. If you have a lot of files, it wouldn't be a good idea to have them all in the one folder.
As mention here, in Java it would matter due to visibility access; not sure in other languages.


text:
Q: I'm having trouble in generating hash string in javascript I'm trying to integrate the payment gateway in WHMCS as a module; the script does not generate the hashkey as per following format; & payment gateway returns error of information not completed; thus; reference : the following URL works fine :
Sample Code by Gateway that works 100%:  https://websol.biz/order/modules/gateways/test.php
Hashkey Generated as per following format

99yv9hbw88&1000&TBANK&billRef&Description of transaction&EN&MC10761&9x19xxy1uv&RETL&https://websol.biz/&PKR&20200802112944
&20200803112944&T20200802112944&1.1&1&2&3&4&5

My Module Code:
<?php
/**
 * WHMCS Jazzcash Payment Gateway Module
 *
 * Payment Gateway modules allow you to integrate payment solutions with the
 * WHMCS platform.
 *
 * This sample file demonstrates how a payment gateway module for WHMCS should
 * be structured and all supported functionality it can contain.
 *
 * Within the module itself, all functions must be prefixed with the module
 * filename, followed by an underscore, and then the function name. For this
 * example file, the filename is "jazzcash" and therefore all functions
 * begin "jazzcash_".
 *
 * If your module or third party API does not support a given function, you
 * should not define that function within your module. Only the _config
 * function is required.
 *
 * For more information, please refer to the online documentation.
 *
 * @see https://developers.whmcs.com/payment-gateways/
 *
 * @copyright Copyright (c) WHMCS Limited 2017
 * @license http://www.whmcs.com/license/ WHMCS Eula
 */

if (!defined("WHMCS")) {
    die("This file cannot be accessed directly");
}

/**
 * Define module related meta data.
 *
 * Values returned here are used to determine module related capabilities and
 * settings.
 *
 * @see https://developers.whmcs.com/payment-gateways/meta-data-params/
 *
 * @return array
 */
function jazzcash_MetaData()
{
    return array(
        'DisplayName' => 'JazzCash Payment Gateway Module',
        'APIVersion' => '1.1', // Use API Version 1.1
        'DisableLocalCredtCardInput' => false,
        'TokenisedStorage' => false,
    );
}

/**
 * Define gateway configuration options.
 *
 * The fields you define here determine the configuration options that are
 * presented to administrator users when activating and configuring your
 * payment gateway module for use.
 *
 * Supported field types include:
 * * text
 * * password
 * * yesno
 * * dropdown
 * * radio
 * * textarea
 *
 * Examples of each field type and their possible configuration parameters are
 * provided in the sample function below.
 *
 * @return array
 */
function jazzcash_config()
{
    return array(
        // the friendly display name for a payment gateway should be
        // defined here for backwards compatibility
         'FriendlyName' => array(
            'Type' => 'System',
            'Value' => 'JazzCash',
        ),
        // a text field type allows for single line text input
        'merchantID' => array(
            'FriendlyName' => 'Merchant ID',
            'Type' => 'text',
            'Size' => '25',
            'Default' => '',
            'Description' => 'Enter your Merchant ID here',
        ),
        // a password field type allows for masked text input
        'salt' => array(
            'FriendlyName' => 'Integerity Salt',
            'Type' => 'text',
            'Size' => '25',
            'Default' => '',
            'Description' => 'Enter Integerity Salt key here',
        ),
        'password' => array(
            'FriendlyName' => 'Integerity Password',
            'Type' => 'password',
            'Size' => '25',
            'Default' => '',
            'Description' => 'Enter Integerity Password here',
        ),
        /*'securehash' => array(
            'FriendlyName' => 'SecureHash',
            'Type' => 'text',
            'Size' => '255',
            'Default' => '',
            'Description' => 'Enter SecureHash here',
        ),*/
    );
}

/**
 * Payment link.
 *
 * Required by third party payment gateway modules only.
 *
 * Defines the HTML output displayed on an invoice. Typically consists of an
 * HTML form that will take the user to the payment gateway endpoint.
 *
 * @param array $params Payment Gateway Module Parameters
 *
 * @see https://developers.whmcs.com/payment-gateways/third-party-gateway/
 *
 * @return string
 */
function jazzcash_link($params)
{

    // Gateway Configuration Parameters
    $merchantID = $params['merchantID'];
    $moduleDisplayName = $params['name'];
    $password = $params['password'];
    $salt = $params['salt'];
    //$securehash = $params['securehash'];

    // Invoice Parameters
    $invoiceId = $params['invoiceid'];
    $invoicenum = $params['invoicenum'];
    $dueDate = $params['dueDate'];
    $description = $params["description"];
    $amount = $params['amount'];
    $currencyCode = $params['currency'];

    // System Parameters
    $companyName = $params['companyname'];
    $systemUrl = $params['systemurl'];
    $returnUrl = $params['returnurl'];
    $langPayNow = $params['langpaynow'];
    $moduleName = $params['paymentmethod'];
    $whmcsVersion = $params['whmcsVersion'];

    $url = 'https://sandbox.jazzcash.com.pk/CustomerPortal/transactionmanagement/merchantform/';

    $postfields = array();
    $postfields['pp_Version'] = '1.1';

    //DD -Direct Debit
    //MIGS - Card Payment
    //MWALLET - Mobile Voucher
    //OTC - Voucher Payment

    $postfields['pp_TxnType'] = '';
    $postfields['pp_Language'] = 'EN';
    $postfields['pp_MerchantID'] = $merchantID;
    $postfields['pp_SubMerchantID'] = '';
    $postfields['pp_Password'] = $password;
    $postfields['pp_BankID'] = 'TBANK';
    $postfields['pp_ProductID'] = 'RETL';

    //generate the referenec number
    $postfields['pp_TxnRefNo'] = 'T'. $invoicenum . '' . rand(1111111111 , 9999999999) ;

    $postfields['pp_Amount'] = str_replace('.' , '' ,$amount);
    $postfields['pp_TxnCurrency'] = 'PKR';

    //Generate it Like 20180523111537 - yyyyMMddHHmmss
    $postfields['pp_TxnDateTime'] = date('YmdHis');

    $postfields['pp_BillReference'] = $invoiceId;
    $postfields['pp_Description'] = $description;

    //Generate The Time Like: 20180524111537
    $postfields['pp_TxnExpiryDateTime'] = date('YmdHis' , strtotime(date('YmdHis'). ' + 2 days'));

    //$postfields['callback_url'] = $systemUrl . '/modules/gateways/callback/' . $moduleName . '.php';
    $postfields['pp_ReturnURL'] = $returnUrl;
    //$postfields['pp_ReturnURL'] = urlencode('http://hosting.kayecommerce.net/viewinvoice.php');

    //pp_SecureHash
    //$securehash;
    $postfields['pp_SecureHash'] = '';
    $postfields['ppmpf_1'] = '1';
    $postfields['ppmpf_2'] = '2';
    $postfields['ppmpf_3'] = '3';
    $postfields['ppmpf_4'] = '4';
    $postfields['ppmpf_5'] = '5';

    ?>

    <?php

    $htmlOutput = '

';
                       $htmlOutput .= '<form name="jsform" method="post" action="' . $url . '">' ;

    foreach ($postfields as $k => $v) {
        $htmlOutput .= '<input type="text" name="' . $k . '" value="'.$v.'">' ;
    }

    $htmlOutput .= '<button type="button" class="text-center" onclick="submitForm()">' . $langPayNow . '</button>';
    $htmlOutput .= '</form>';

                                        $htmlOutput .= ''.$salt.'

                                                <input type="hidden" id="hashValuesString" value="">

';

    ?>

    <?php

    return $htmlOutput;

}
?>

<?php

/**
 * Refund transaction.
 *
 * Called when a refund is requested for a previously successful transaction.
 *
 * @param array $params Payment Gateway Module Parameters
 *
 * @see https://developers.whmcs.com/payment-gateways/refunds/
 *
 * @return array Transaction response status
 */
function jazzcash_refund($params)
{
    return true;
}

/**
 * Cancel subscription.
 *
 * If the payment gateway creates subscriptions and stores the subscription
 * ID in tblhosting.subscriptionid, this function is called upon cancellation
 * or request by an admin user.
 *
 * @param array $params Payment Gateway Module Parameters
 *
 * @see https://developers.whmcs.com/payment-gateways/subscription-management/
 *
 * @return array Transaction response status
 */
function jazzcash_cancelSubscription($params)
{
    return true;
}

?>

Generate the following Hashkey:
ad12f44e5e7dfd135d204b6e31229e3b13232a180493f26e61a15251333899a8

A: Why not you try in PHP, its very Easy and Clean way in PHP, Here is my code,
    ksort($postfields); //Sort in Assendig order
    $str = $integrity_salt;  //Your Seceret key to add
    foreach($postfields as $key => $value)
    {
        if(!empty($value) && $value != 'undefined' && $value != null && $value != '' && $value)
        {
            $str .=  "&".$value;
        }
    }

    $pp_SecureHash = hash_hmac('sha256', $str, $integrity_salt);


text:
Q: 3 Select Elements, But Produce 6 Value. Why? I have this HTML structure :

            <select class="tarif full-width" data-init-plugin="select2">
                <option value="1">Option 1</option>
                <option value="2">Option 2</option>
            </select>

            <select class="tarif full-width" data-init-plugin="select2">
                <option value="1">Option 1</option>
                <option value="2">Option 2</option>
            </select>

            <select class="tarif full-width" data-init-plugin="select2">
                <option value="1">Option 1</option>
                <option value="2">Option 2</option>
            </select>

and I have this jquery :
$(".tarif").change(function() {
    $(".tarif").each(function() {
        alert ($(this).val());
    });
});

why the alert produce 6 times dialog box, instead of 3?

*

*first : empty

*second : either 1 or 2 of first select element

*third : empty

*fourth : either 1 or 2 of second select element

*fifth : empty

*sixth : either 1 or 2 of third select element

how to get exact value of selected element and ignore empty value? please note that this is not just HTML select, but it use Select2 plugins.
UPDATE : here's my complete javascript code
(function($) {

    'use strict';

    $(document).ready(function() {

        $('#rootwizard').bootstrapWizard({
            onTabShow: function(tab, navigation, index) {
                var $total = navigation.find('li').length;
                var $current = index + 1;

                // If it's the last tab then hide the last button and show the finish instead
                if ($current >= $total) {
                    $('#rootwizard').find('.pager .next').hide();
                    $('#rootwizard').find('.pager .finish').show().removeClass('disabled hidden');
                } else if ($current == 2) {

                    if ($(".tarif").is(":disabled")) {
                        $('#rootwizard').find('.pager .next').hide();
                        $('#rootwizard').find('.pager .finish').hide();
                    }

                    $(".tarif").change(function() {
                        if ($(".tarif").is(':disabled')) {
                            $('#rootwizard').find('.pager .next').hide();
                        } else {

                            var emptySelect = false;
                            $('#kurir_list select').each(function(){
                                if (!$(this).find('option:selected').val()) {
                                    emptySelect = true;
                                }
                            });

                            if (emptySelect == false ) {
                                $('#rootwizard').find('.pager .next').show();
                            } else {
                                $('#rootwizard').find('.pager .next').hide();
                            }
                        }

                        $(".tarif").each(function() {
                            alert ($(this).val());
                        });

                        var selected_tarif = $(this).val();
                        var ongkir2 = $("#ongkir2").text();
                        ongkir2 = ongkir2.replace(/\D/g,"");

                        var new_ongkir2 = parseInt(ongkir2) + parseInt(selected_tarif);
                        new_ongkir2 = addCommas(new_ongkir2);
                        $("#ongkir2").text("Rp "+new_ongkir2);
                    });

                    $(".kurir").change(function() {
                        var selected_courier = $(this).val();
                        var token = $(this).data('token');
                        var productid = $(this).data('productid');
                        var city = $("#city").val();
                        var area = $("#area").val();
                        var quantity = $(".orderlist2").find("."+productid).find(".quantity").text();
                        quantity = quantity.replace(/\D/g,"");

                        var json_url = "SOME URL HERE";
                        $.ajax({
                            url: json_url,
                            dataType: "JSON",
                            success: function(json){

                                var rate_tarif = "";
                                var selected_tarif = "";

                                $.each(json, function(i,o){
                                    rate_tarif += "<option value="+o.tarif+">"+o.rate+"</option>";
                                });

                                $("#tarif-"+productid).append(rate_tarif).change();

                                event.preventDefault();
                                $("#tarif"+productid).prop("disabled", false);

                                selected_tarif = $("#tarif-"+productid).val();
                            }
                        });
                    });

                    $("#state").change(function() {
                        $('#rootwizard').find('.pager .next').hide();
                    });

                } else {
                    $('#rootwizard').find('.pager .next').show();
                    $('#rootwizard').find('.pager .finish').hide();
                }
            },
            onNext: function(tab, navigation, index) {
                console.log("Showing next tab");
            },
            onPrevious: function(tab, navigation, index) {
                console.log("Showing previous tab");
            },
            onInit: function() {
                $('#rootwizard ul').removeClass('nav-pills');
            }

        });
    });

})(window.jQuery);

A: Your subsequent comment explains it:

what you have is plain HTML, while in my case is using Select2 plugins

The way select2 works, it hides your select elements (without removing them) and creates a new structure, copying your classes and such to it. So you end up with .tarif elements that were in your HTML, and also .tarif elements created by select2.
You can limit the ones you respond to by narrowing your selector:
$("select.tarif").change(function() {
    $("select.tarif").each(function() {
        alert ($(this).val());
    });
});

You can see what select2 does on their examples page.
Here's the "before" of the first example:
<select class="js-states form-control">

</select>

Here's the "after":
<select class="js-example-basic-single js-states form-control select2-hidden-accessible" tabindex="-1" aria-hidden="true">

</select>
Alaska

Note how the original select is hidden, and the js-states and form-control classes were copied from the select to the select2-generated span.


text:
Q: How to send a double click message to the specified listview element How can I send a double click message to the specified listview element in Windows? I know that i need to use SendMessage function, but I'm not sure about an arguments to this function. Can you give me an example, please?

A: How to fake a NM_DBLCLK notification:
#include <Commctrl.h>
// ensure those variables are ok
HWND hWndListViewParent;
INT iListViewID;
HWND hWndListView;

[...]

NMITEMACTIVATE nmia;
nmia.hdr.code = NM_DBLCLK;
nmia.hdr.hwndFrom = hWndListView;
nmia.hdr.idFrom = iListViewID;
// set up the rest of NMITEMACTIVATE

[...]

SendMessage( hWndListViewParent, WM_NOTIFY, (WPARAM)iListViewID, (LPARAM)&nmia );

I don't think you can do that cross process, however. Try it. If that indedd doesn't work, you will have to fake mouse action via SendInput, or maybe use UIAutomation.


text:
Q: Backbone.js Models - syncing ID with the server I'm having some trouble understanding model synchronization in Backbone js. When I instantiate and save a new model, it's data is sent to the back end to be persisted. However, it's unique identifier is also generate on the back-end (an auto-incrementing integer). I need this ID attribute to be immediately available on the model after the server acknowledges success. How do I go about doing this?
Just to give a little more detail, I'm creating my models like so:
this.collection.create(modelData, {wait: true}

And I would like the newly created model to have an ID attribute, the value of which was generated on the backend.

A: Poor reading of the documentation in this case. Turns out backbone sync expects a JSON response from the server indicating extra/altered attributes you want set on the model, which is exactly what I was looking for.

A: You have to pass the ID of the generated model back to backbone in the response.  So in your controller you can do something like:
def create = Action { implicit request =>
    employeeForm.bindFromRequest.fold(
      errors => BadRequest,
      employee => {
        Ok(Employee.create(employee).toString())
    })
}

Then define the create method of your model like:
def create(employee: Employee): Long = {
    DB.withConnection { implicit connection =>
      SQL("insert into employee(first_name, last_name) values ({fname}, {lname})").on(
        'fname -> employee.fname,
        'lname -> employee.lname
      ).executeInsert()
    } match {
      case Some(long) => long
      case None => 0
   }
}

And in backbone.js in your view define the success callback for create like so:
app.employeeList.create(@model,
      wait: true

      success: _.bind((model, response)->
        @model.set("id", response)

You can also add some sort of error handling for a returned ID of 0.  Also, not sure what you're using for your backend but this code is for Play 2/Scala.  (And sorry for the CoffeeScript, if you need JS let me know)


text:
Q: Grey bar appears when installed plank dock I installed Ubuntu 16.04 and installed XFCE desktop environment right away. And then installed numix theme and icon pack. Then I installed plank. After installation a grey bar appears. When plank is closed it dissappears.
Here's an image:

A: Finally, I figured out the answer for my own question.

Steps:

*

*Open "Window Manager Tweaks" --> "Compositor" tab

*Uncheck "Show shadows under dock windows"

(I'm using XFCE desktop environment.)


text:
Q: Is it possible to set permission per field? I am building a rest api application with django-rest-framework. I came to the phase where I want to put in place some security.
I have a user ressources with the following fields firstname, lastname, dateofbirth (just to say a few). So in my user object they are private fields and fields which can be public.
Is there a way to limit the out put fields in the response base on the drf Permission, or if no what would the best practise in genera ?
for example :
When the user with the id 1 use : api/user/1 he gets:
{
   "id": "1",
   "firstname":"john",
   "lastname":"Smith",
   "dateofbirth":"2015-11-11"
}
When the user with the id 2 use : api/user/1 he gets:
{
   "id": "1",
   "firstname":"john",
   "lastname":"Smith"
 }
which only says that the dateofbirth is a private fie

A: you can do this by overriding the init method in your user serializer like:
class UserSerializer(serializers.ModelSerializer):

    def __init__(self, *args, **kwargs):
        super(UserSerializer, self).__init__(*args, **kwargs)
        if 'pk' in kwargs:
            if not self.context['request'].user.id == kwargs['pk']:
                self.fields.pop('dateofbirth')

    class Meta:
        model = User
        fields = ('id', 'firstname', 'lastname', 'dateofbirth')

you can also refer this question


text:
Q: Using Principal Component Analysis (PCA) to construct a Financial Stress Index (FSI) I am trying to construct a financial stress index. I have selected 12 variables that I use as indicators of financial market stress. These are all time series of daily data (VIX, credit spreads, etc.). I am trying to use principal component analysis (PCA) to decide on the weights these variables should get in my index. I am using Stata. If I run the pca command I get 12 components with eigenvalues. I then select only the components that have eigenvalue > 1 (Kaiser rule) and now I'm left with 3 components.
Stata commands:
pca $varlist, mineigen(1)
estat loadings
predict pc1 pc2 pc3, score

I now have 3 time series pc1, pc2, pc3 which are, if I understand correctly, the first three principal components.
I don't understand how I create an index out of a combination of these 3 components. What is the logical step to take now and how should I interpret the different factor loadings of the different variables in the different components?
Main question: what steps should I take to derive a time series of my financial stress index?
If you need any additional info to answer my question please say so and I'll try my best to make it as clear as possible.

A: First, I think this calls for factor analysis, not principal component analysis.  A "financial stress index" is a latent variable - that is, a variable that cannot be directly measured.
However, you are likely to get similar results.  If you want a single index, then you want the first factor.  If that factor does not explain much of the variance, then it's just not a very good index.


text:
Q: HCS12 INTERRUPT Shown below is a switch connected to the IRQ or XIRQ pin of the HCS12. Write a program to get the status of the switch and increment a counting sequence on the 7-segment display each time the key is pressed. The switch should be connected to IRQ/PE1 or XIRQ/PE0 of the Trainer (Dragon12P), namely pin 55 (for Maskable Interrupt) or pin 56 (for NonMaskable Interrupt) respectively.
You do not have to get any physical switch; all you need is represent the closure of a switch by grounding the appropriate pin.
Procedure:

*

*Initialize and Program the appropriate Interrupt Registers appropriately.

*Design an appropriate ISR (Interrupt Service Routine).

*Write down an Assembly code to create a dummy delay loop, and once the key has been pressed, the incremented sequence would appear on the on the 7-segment display and optionally on the LEDs.

Here's my code:
#include "C:\Users\CLOS\Desktop\New folder\Reg9s12.H"
TEMP    DC.B 1
RAMEnd  EQU     $1001
MAIN:
        LDS     #RAMEnd+1
        BSET    INTCR,%1100000
        CLR     TEMP
        CLI
        BSET    DDRB,%00010000
        BCLR    PORTB,%00010000
HERE    BRA     HERE
IRQ_EDGE
        LDAA    TEMP
        EORA    #%00010000
        STAA    TEMP
        RTI
        ORG     $FFF2
        DC.W    IRQ_EDGE
        ORG     $FFFE
        DC.W    MAIN

The ERROR I'm receiving on Asmide:
Can't Write Target Memory


text:
Q: for loop issue when cycling through images for Jlabel with button click in a java aplication I have a Jlabel which i want to assign a new image to every time i click a button, using a for loop i can get it to just display the last image skipping all in between images, i know there is a error in my logic here maybe i should not be using a for loop?? any advice
 private String imageList[];
 ImageIcon image;
 imageList =  new String[] {"src\\Tour_Eiffel_Wikimedia_Commons.jpg","src\\Ben.jpg", "src\\Rio.jpg", "src\\Liberty.jpg", "src\\Pyramid.jpg"};

 //constructor setting first image to display on load
public GeographyGameGUI() {
       image = new ImageIcon(imageList[0]);
            imageLbl.setIcon(image);
 }

  //button method
   private void nextBtnActionPerformed(java.awt.event.ActionEvent evt) {

      for (imgCount = 1; imgCount < imageList.length; imgCount++) {
            image = new ImageIcon(imageList[imgCount]);
            imageLbl.setIcon(image);

    }

if i dont use a for loop and simply use a counter (displayed below) which i declare outside of the button method it loops correctly displaying the images but runs into a ArrayIndexOutOfBoundsException. what is the best practice here? thanks
 image = new ImageIcon(imageList[imgCount]);
     imageLbl.setIcon(image);
    imgCount++;

A: You're, essentially, blocking the Event Dispatching Thread, prevent it from updating the UI.  See Concurrency in Swing for more details
Instead, you should use a javax.swing.Timer to loop over the images, allowing the UI to update before changing to the next one...
See How to use Swing Timers for more details.
Java arrays are zero indexed, this means that the first element in the array is a position 0, not 1
Don't reference src directly within your code, the src directory will not exist once the application is built and packaged
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JLabel label;
        private String[] imageList = new String[] {"/Tour_Eiffel_Wikimedia_Commons.jpg","/Ben.jpg", "/Rio.jpg", "/Liberty.jpg", "/Pyramid.jpg"};

        public TestPane() {
            setLayout(new BorderLayout());
            label = new JLabel();
            add(label);

            JButton btn = new JButton("Play");
            btn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    btn.setEnabled(false);
                    Timer timer = new Timer(1000, new ActionListener() {
                        private int count;
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            if (count < imageList.length) {
                                try {
                                    label.setIcon(
                                            new ImageIcon(
                                                    ImageIO.read(
                                                            TestPane.this.getClass().getResource(imageList[count]))));
                                } catch (IOException exp) {
                                    exp.printStackTrace();
                                }
                                count++;
                            } else {
                                ((Timer)e.getSource()).stop();
                            }
                        }
                    });
                    timer.stop();
                }
            });
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

    }

}

A: Your counter reaches the end of the array so you get out of bounds exception. After each increment you should check whether the end of array has been reached, and if so, set the counter to 0.
If you want to iterate over a few images with a delay on single click you need to use SwingWorker. Using delays in your action listener will suspend event dispatch thread, which means that no other updates or interactions with swing components will be available (it is likely that refreshes will not be done correctly too).
If you do a few updates (setIcon) in a very short time, Swing usually refreshes the component after the last of them, which means that only last image will be visible.
Have a look here: http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html


text:
Q: using PhoneGap, navigator.contacts.create() 'create' of undefined? I am going to achieve contact functionality using phonegap build, I have added required feature API, calling contact crate after device ready in index.html. but it is coming as create of undefined. Please tell me, where i am missing?. great appreciate. For more reference i have given code of config.xml and index.html files.
Config.xml
<?xml version='1.0' encoding='utf-8'?>
<widget id="com.example.AbsenceManagement" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0">
    <name>Add Contact</name>
    <description>
    </description>
    <author email="support@phonegap.com" href="http://phonegap.com">
    </author>

    <feature name="http://api.phonegap.com/1.0/battery"/>
    <feature name="http://api.phonegap.com/1.0/contacts"/>
    <feature name="http://api.phonegap.com/1.0/file"/>
    <feature name="http://api.phonegap.com/1.0/geolocation"/>
    <feature name="http://api.phonegap.com/1.0/media"/>
    <feature name="http://api.phonegap.com/1.0/network"/>
    <feature name="http://api.phonegap.com/1.0/notification"/>

    <feature name="Contacts">
        <param name="android-package" value="org.apache.cordova.contacts.ContactManager" />
    </feature>
    <feature name="Contacts">
        <param name="ios-package" value="CDVContacts" />
    </feature>

    <access origin="*" browserOnly="false" />
    <access origin=".*"/>

    <preference name="disallowOverscroll" value="true" />
    <preference name="webviewbounce" value="false" />
    <preference name="fullscreen" value="false" />
    <preference name="prerendered-icon" value="true" />
    <preference name="stay-in-webview" value="false" />
    <preference name="ios-statusbarstyle" value="white" />

    <preference name="detect-data-types" value="true" />
    <preference name="exit-on-suspend" value="false" />
    <preference name="show-splash-screen-spinner" value="true" />

    <preference name="auto-hide-splash-screen" value="true" />
    <preference name="disable-cursor" value="false" />
    <preference name="orientation" value="portrait" />

    <preference name="phonegap-version" value="3.0.0" />
    <gap:splash gap:platform="android"  />
    <gap:splash gap:density="ldpi" gap:platform="android" src="resources/icons/drawable-ldpi/splash_screen.png" />
    <gap:splash gap:density="mdpi" gap:platform="android" src="resources/icons/drawable-mdpi/splash_screen.png" />
    <gap:splash gap:density="hdpi" gap:platform="android" src="resources/icons/drawable-hdpi/splash_screen.png" />
    <gap:splash gap:density="xhdpi" gap:platform="android" src="resources/icons/drawable-xhdpi/splash_screen.png" />

    <icon src="resources/icons/Icon-Small@2x.png" gap:platform="ios" width="57" height="57" />
    <icon src="resources/icons/hdpi/72x72.png" gap:platform="android" gap:density="hdpi" />
    <icon src="resources/icons/ldpi/36x36.png" gap:platform="android" gap:density="ldpi" />
    <icon src="resources/icons/mdpi/48x48.png" gap:platform="android" gap:density="mdpi" />
    <icon src="resources/icons/xhdpi/96x96.png" gap:platform="android" gap:density="xhdpi" />
    <icon src="resources/icons/xxhdpi/144x144.png" gap:platform="android" gap:density="xxhdpi" />

</widget>

Index.html
------------
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no">

        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="apple-mobile-web-app-status-bar-style" content="white">
        <title>Add Contact</title>

A: Check this Config.xml I dont know what is your requirement but i think you are using contact and camera plugin so i have included both plugins for you. This should work.
<?xml version="1.0" encoding="UTF-8"?>

<widget xmlns     = "http://www.w3.org/ns/widgets"
    xmlns:gap = "http://phonegap.com/ns/1.0"
    id        = "com.XYZ.ABC"
    version   = "1.0.0">

  <name>Test</name>

  <description>Demo app</description>

  <author href="http://phonegap.com" email="support@phonegap.com">
    PhoneGap Team
  </author>

  <feature name="http://api.phonegap.com/1.0/device" />
  <feature name="http://api.phonegap.com/1.0/contacts"/>
  <feature name="Camera">
    <param name="android-package" value="org.apache.cordova.camera.CameraLauncher" />
  </feature>

  <preference name="permissions"                value="none"/>
  <preference name="phonegap-version"           value="3.3.0" />
  <preference name="orientation"                value="portrait" />
  <preference name="target-device"              value="universal" />
  <preference name="fullscreen"                 value="true" />
  <preference name="webviewbounce"              value="false" />
  <preference name="prerendered-icon"           value="true" />
  <preference name="stay-in-webview"            value="false" />
  <preference name="ios-statusbarstyle"         value="black-opaque" />
  <preference name="detect-data-types"          value="true" />
  <preference name="exit-on-suspend"            value="false" />
  <preference name="show-splash-screen-spinner" value="false" />
  <preference name="auto-hide-splash-screen" value="true" />
  <preference name="disable-cursor"             value="false" />
  <preference name="android-minSdkVersion"      value="7" />
  <preference name="android-installLocation"    value="auto" />
  <preference name="DisallowOverscroll" value="true" />

  <icon src="res/icon/android/icon-36-ldpi.png"   gap:platform="android"    gap:density="ldpi" />
  <icon src="res/icon/android/icon-48-mdpi.png"   gap:platform="android"    gap:density="mdpi" />
  <icon src="res/icon/android/icon-72-hdpi.png"   gap:platform="android"    gap:density="hdpi" />
  <icon src="res/icon/android/icon-96-xhdpi.png"  gap:platform="android"    gap:density="xhdpi" />

  <gap:plugin name="org.apache.cordova.device" />
  <gap:plugin name="org.apache.cordova.contacts" version="0.2.3" />
  <gap:plugin name="org.apache.cordova.camera" version="0.2.3" />
  <plugin name="InAppBrowser" value="org.apache.cordova.InAppBrowser" />
  <access origin="*" browserOnly="true"/>

</widget>


text:
Q: How can I get an h1 element to display over an image? I want to display my page's title, "Math Achievement Tutoring", over a photograph of a hiker. My first attempt was to create this html:

Math Achivement Tutoring

with this CSS, the idea being to position the h1 as absolute:
h1 {
  text-align:center;
  position: absolute;
  color: #a04040;
}

but this means the title is no longer centered. I may run into other trouble as well if I start to fiddle with margin and padding.

   h1 {
      text-align:center;
      position: absolute;
      color: #a04040;
    }

Math Achivement Tutoring

What are my options for achieving this, and does it depend on where I want to take this website eventually? (like adding a navigation menu below the image)? Is there any simple demonstration code?

A: First, add position relative to #wrapper, then :
if you want it to be vertically & horizontally centered
h1 {
  text-align:center;
  position: absolute;
  color: #a04040;
  left: 50%;
  top: 50%;
  transform: translate( -50%, -50% );
}

if you want it to be vertically centered
h1 {
  text-align:center;
  position: absolute;
  color: #a04040;
  top: 50%;
  transform: translateY( -50% );
}

if you want it to be horizontally centered
h1 {
  text-align:center;
  position: absolute;
  color: #a04040;
  left: 50%;
  transform: translateX( -50% );
}

A: Just as Loesh Gupta says: make the wrapper .wrapper { position: relative; }. To center the text you can use multiple options. I'd go with something like this:
h1 { position: absolute; left: 50%; right: 50%; transform: translate(-50%, -50%); }
I can also recommend this tool: http://howtocenterincss.com/

A: Here's a solution using flexbox:

#wrapper {
  display: flex;            /* establish flex container */
  flex-direction: column;   /* stack flex items vertically */
  position: relative;       /* establish neares positioned ancenstor for absolute positioning */

}
h1 {
  color: red;
}
.text {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  color: white;
  font-weight: bold;
}

.center-aligned {
  display: flex;
  align-items: center;
  justify-content: center;
}

Math Achivement Tutoring

A: Using a background image on a div and a display flex on the text might do it. Make sure to add the height on the text based on the image so it can be centered.

*{margin: 0 auto;}
.bg{
  background-image:url('http://michaelmossey.com/demo/home-hiker-grayish.jpg');
  height: 380px;
  background-repeat: no-repeat;
  background-size:cover;
  background-position: center center;
}
.bg h1{
  display: flex;
  justify-content: center;
  align-items: center;
  height: 380px;
  font-size: 3em;
  color: #ffffff;
  background-color: rgba(0,0,0,0.5);
}

Math Achivement Tutoring


text:
Q: How to provide custom name to column in pivoting I have a table like this:
id  unit
1   mm
2   cm
3   kg

When I perform pivot operation on this, I am getting result as follows:
1  2  3
mm cm kg

Is it possible to get custom column names here, something like this:
d1  d2  d3
mm  cm  kg

I am using Pivot for this as:
IF OBJECT_ID('tempdb..#t') IS NOT NULL
DROP TABLE #t
GO

CREATE  table #t
(id varchar(max),unit varchar(max))
insert into #t (id,unit)values
(1,'kg'),
(2,'cm'),
(3,'mm'),
(4,'m')

DECLARE @statement NVARCHAR(max)
   ,@columns NVARCHAR(max)

SELECT @columns = ISNULL(@columns + ',', '') + N'[' + cast(tbl.id as varchar(max)) + ']'
   FROM (
   SELECT DISTINCT id
   FROM #t
   ) AS tbl

   SELECT @statement =  'select *
                  INTO ##temp
                  from (
                    SELECT id,[unit]
                    FROM #t
                    ) as s
PIVOT
(max(unit) FOR id in(' + @columns + ')) as pvt
'

EXEC sp_executesql @statement = @statement

SELECT * FROM ##temp
DROP TABLE #t
DROP TABLE ##temp

Is it possible?
Thanks

A: IF OBJECT_ID('tempdb..#t') IS NOT NULL
    DROP TABLE #t
GO

CREATE TABLE #t (
    id VARCHAR(10),
    unit VARCHAR(100)
)
INSERT INTO #t (id, unit)
VALUES
    ('1', 'kg'),
    ('2', 'cm'),
    ('3', 'mm'),
    ('4', 'mm')

DECLARE @SQL NVARCHAR(MAX), @columns NVARCHAR(MAX)

SELECT @columns = STUFF((
    SELECT ',[D' + id + ']'
    FROM #t
    FOR XML PATH('')), 1, 1, '')

SELECT @SQL =  '
    SELECT *
    FROM (
        SELECT [unit], col = N''D'' + id
        FROM #t
    ) s
    PIVOT (MAX(unit) FOR col IN (' + @columns + ')) p'

EXEC sys.sp_executesql @SQL

A: Just add a prefix to your ID. Example
SELECT @statement = 'select * INTO ##temp from
                     ( SELECT [id] = ''d''+id,[unit] FROM #t ) as s
                     PIVOT
                     (max(unit) FOR id in(' + @columns + ')) as pvt '

Also it's terrible practice to use global temp tables! Especially one named ##temp

A: You can use a CASE expression with a dynamic sql query.
CREATE TABLE #t
(
    id INT,
    unit VARCHAR(2)
);

INSERT INTO #t VALUES
(1,'mm'),
(2,'cm'),
(3,'kg');

DECLARE @query AS VARCHAR(MAX);

SELECT @query = 'SELECT ' +
      STUFF
      (
         (
            SELECT DISTINCT ',MAX(CASE WHEN id =  '+ CAST(id AS VARCHAR(10))
              + ' THEN unit END) AS d' + CAST(id AS VARCHAR(10))
            FROM #t
            FOR XML PATH('')
          ),
      1,1,'');
SELECT @query += ' FROM #t;';

EXECUTE(@query);

Result
+----+----+----+
| d1 | d2 | d3 |
+----+----+----+
| mm | cm | kg |
+----+----+----+

A: SELECT @statement = 'select * INTO ##temp from ( SELECT ''d''+id AS [id],[unit] FROM #t ) as s PIVOT (max(unit) FOR id in(' + @columns + ')) as pvt '


text:
Q: create rows from columns in a apache spark dataset I'm trying from a dataset to create a row from existing columns.
Here is my case:
InputDataset

accountid
payingaccountid
billedaccountid
startdate
enddate

0011t00000MY1U3AAL
0011t00000MY1U3XXX
0011t00000ZZ1U3AAL
2020-06-10 00:00:00.000000
NULL

And I would like to have sometthing like this

accountid
startdate
enddate

0011t00000MY1U3AAL
2021-06-10 00:00:00.000000
NULL

0011t00000MY1U3XXX
2021-06-10 00:00:00.000000
NULL

0011t00000ZZ1U3AAL
2021-06-10 00:00:00.000000
NULL

In the input dataset the columns billedaccounid and payingaccounid are now also in accountid column.
Thank you in advance.

A: You can create an array column with 3 id columns then use explode function to get desired result.
val spark = SparkSession.builder().master("local[*]").getOrCreate()
spark.sparkContext.setLogLevel("ERROR")
import spark.implicits._

val df = List(("0011t00000MY1U3AAL", "0011t00000MY1U3XXX", "0011t00000ZZ1U3AAL", "2020-06-10 00:00:00.000000", "NULL"))
    .toDF("accountid", "payingaccountid", "billedaccountid", "startdate", "enddate")

df.select(
    explode_outer(array("accountid","payingaccountid","billedaccountid")).as("accountid"),
    'startdate,'enddate).show(false)
/*
+------------------+--------------------------+-------+
|accountid         |startdate                 |enddate|
+------------------+--------------------------+-------+
|0011t00000MY1U3AAL|2020-06-10 00:00:00.000000|NULL   |
|0011t00000MY1U3XXX|2020-06-10 00:00:00.000000|NULL   |
|0011t00000ZZ1U3AAL|2020-06-10 00:00:00.000000|NULL   |
+------------------+--------------------------+-------+ */