text:
Q: ¿Qué significan los símbolos "&" y ">>" en Python? No encuentro en Internet qué significan estos símbolos en Python: & y >>.
Encontré que & sería intersección, pero no creo que aplique en el siguiente código que no logro entender:
def numberOfSteps (self, num: int) -> int:
    stepCount = 0 if num else 1
    while num:
        stepCount += (num & 1) + 1
        num >>= 1
    return stepCount - 1

A: Operadores Bitwise
Los operadores Bitwise se utilizan para hacer operaciones entre los bits de un numero, comúnmente son llamadas operaciones bit a bit.
Operador >> (bitwise right shift)
El operador >> se llama rshift o right shift el cual indica un desplazamiento a la derecha por n bits. aquí un ejemplo
a = 60            #0011 1100
b = 13            #0000 1101

#si   hacemos a >> 2 se moverá 2 bits a la derecha
r = a >> 2
#r = 0000 1111
print(r) #15

En algunas partes se dice que es similar a hacer num/pow(2,n) lo cual no es muy correcto, púes estos operadores se usan en números enteros y una división como esa nos devolverá un decimal, hacemos un ejemplo
#operador
60 >> 2
#15

#formula
60/pow(2,2)
#15

#otra vez
60 >> 3
#7

60/pow(2,3)
#7.5

En el ultimo caso no es lo mismo ya que no es igual desplazar los bits de un numero que dividir u operar con el. La forma correcta seria convirtiendolo a entero int(60/pow(2,3)) ya que operamos con enteros. Otra forma seria la que dijo @tincopasan en los comentarios, con la doble barra // la cual devuelve la parte entera de la división 60//pow(2,3).
Operador & (bitwise and)
Como dije en un principio las operaciones bitwise son de bit a bit por lo que está no tiene el mismo efecto que el operador and ya que este se utiliza con valores boleanos. Además la operación que realice  & será distinta según el tipo de dato, algo interesante de este operador es que se puede redefinir sus métodos como __and__ y __rand__.
En este caso el operador hace lo mismo que haría con los conjuntos una intersección pero con los bits del numero, retornando 1 si ambos números son 1 y 0 si no lo son. Vamos a ver un ejemplo con los mismos valores
a = 60            #0011 1100
b = 13            #0000 1101

r = a & b
#calculamos la interseccion entre 0011 1100 y 0000 1101
#0011 1100
#0000 1101
#interseccion -> 0000 1100
print(r) #12

Esto nos da como resultado esta cadena de bits 0000 1100 el cual representa al numero 12.
Tu código
Lo que hace tu codigo es, que recibe un numero el cual verifica si es True o False, sera True cuando sea cualquier numero o cadena no vacia; False cuando sea 0 o una cadena vacia "" y le asigna el valor de 0 o 1. Luego haya la intersección con 1 (en bits), ahora pasamos al ciclo while
#supongamos que num es 7
#por lo que la condición es True asi que stepCount= 0

while num:
    stepCount += (num & 1) + 1 #aqui se haya la interseccion con 1 y luego +1
    #seria 0 += (1) +1 = 2
    num >>= 1 #aqui se correra un bit a la derecha
    #en este caso los bits representaran al 3
    #el ciclo se repetira hasta que num sea 0 bits ->0000 0000
return stepCount - 1 # se retornara el valor acumulado en la variable -1

Como ves tu codigo mueve una posicion de bits del numero hasta que sea 0000 0000 y retornara un valor que se ha ido acumulando


text:
Q: Use library that may not be loaded I want to create a plugin A for a software that other plugins B/C may be able to use it. Now the tricky part is that I need it to follow these rules:

*

*B depends on A, and it will only load if A is present.

*C uses A, but it should function if A is not present.

For B it's easy to solve, it will just throw an error since A is not present.
Now for C, how can I achieve this? I want to use be able to use A, but it shouldn't break if A is not present.

A: For 1 case - just adding dependency to A at class level of B will fail loading of class B.
To allow optional failures - wrap all calls to A into methods and try/catch around calls to those methods so JIT failures can be caught:
 class C
 {
   // no references to A at class level

   int MethodUsingA()
   {
      // use A here
   }

   int MethodTryingToUseA()
   {
      try
      {
        return MethodUingA(); // will throw loader error
                              // during JIT if A assembly is missing
      }
      catch // use specific exception, LoaderException?
      {
        return 42; // JIT of MethodUingA failed
      }
 }

If you need solution for larger number of classes/methods you may instead consider reflection to load manually and provide alternative implementations if loading failed.

A: If by "library" you mean ".net assembly" then you may want to try to use AppDomain.GetAssemblies to check if the assembly is loaded (MSDN) and look for your assembly in this array.
To call some methods from the assembly you may want to inspect this example
on MSDN

redpajama_set_name: RedPajamaStackExchange


text:
Q: Relate Multiple Tables to Single General Purpose Table in Entity Framework Code First Many times I have a general purpose entity that other entities contain a collection of.  I don't want to have a new collection entity for each parent entity type that needs it but would like to re-use a single general purpose entity.  For performance reasons, I also don't want to explicitly define many-to-many relationships as in this answer. The simplest example would be a collection of strings.
public class MyString
{
    public Guid Id { get; set; }
    public string Value { get; set; }
}

public class MyEntity
{
    public Guid Id { get; set; }
    public virtual List<MyString> { get; set; }
}

public class MyOtherString
{
    public Guid Id { get; set; }
    public string Value { get; set; }
}

public class MyOtherEntity
{
    public Guid Id { get; set; }
    public virtual List<MyOtherString> { get; set; }
}

I'd really like to combine MyString and MyOtherString into a single entity:
public class GeneralPurposeString
{
    public Guid Id { get; set; }
    public string Value { get; set; }
}

public class MyEntity
{
    public Guid Id { get; set; }
    public virtual List<GeneralPurposeString> { get; set; }
}

public class MyOtherEntity
{
    public Guid Id { get; set; }
    public virtual List<GeneralPurposeString> { get; set; }
}

Except now I'm going to have an additional foreign key in GeneralPurposeString for every entity that contains a collection of GeneralPurposeString.
What I would like would be a way to have an additional parent category column on the GeneralPurposeString table (but not the entity) that would specify which entity the item belongs to.  I use Guid for primary keys, so the tables could look something like this:
CREATE TABLE [GeneralPurposeString]
(
    [Id] uniqueidentifier NOT NULL
         CONSTRAINT PK_GeneralPurposeString PRIMARY KEY,
    [ParentEntityCategory] uniqueidentifier NOT NULL,
    [ParentEntityId] uniqueidentifier NOT NULL,
    [Value] nvarchar(MAX)
)

And some how in Code First to specify that MyEntity has a certain category, and that it's collection of GeneralPurposeString uses that category, and MyOtherEntity uses another category (Guid) for it's collections of GeneralPurposeString.
The key would be that GeneralPurposeString could be a collection in any other entity and that loading the parent entity and including the collection would automatically load without having to explicitly specify the category.
The purposes for all of this are

*

*Allow .NET code to have GeneralPurposeString code that wasn't replicated everywhere (actual utility or business logic code).  This can probably also be accomplished through inheritance and explicit mapping but that would still leave multiple tables in the database (see #2).

*Have only one table in the database for GeneralPurposeString.  This is more of a tidiness issue.  Performance would possibly be better with multiple tables, but indexing on ParentEntityCategory/ParentEntityId and covering Value should be good performance for lookups.

*Not have to explicitly code this relationship and the lookups everywhere it's needed.

A: I'm thinking if I can get over #2 and be OK with a separate table behind the scenes and implementing a derived class, that will be the simplest route to go.
So just:
public class GeneralPurposeString
{
    public Guid Id { get; set; }
    public string Value { get; set; }
}

// It's just a GeneralPurposeString with a fancy MyEntity membership pin
public class MyEntityString: GeneralPurposeString {}

public class MyEntity
{
    public Guid Id { get; set; }
    public virtual List<MyEntityString> Strings { get; set; }
}

// Cool GeneralPurposeStrings belong to MyOtherEntity
public class MyOtherEntityString: GeneralPurposeString {}

public class MyOtherEntity
{
    public Guid Id { get; set; }
    public virtual List<MyOtherEntityString> Strings { get; set; }
}

public class MyContext: DbContext
{
    public DbSet<MyEntity> MyEntities { get; set; }
    public DbSet<MyOtherEntity> MyOtherEntities { get; set; }
}

I don't have to add the derived classes to the DbContext and the tables get named with the plural of the derived class by default, so it's actually pretty straight forward.
My previous train of thought with the Parent Category would require additional coding/annotation even if EF supported it.  This uses purely convention and nothing extra needed in annotations or in OnModelCreating().
I'm not seeing any harm in extra tables at this point in time.  I don't see a need (currently) to have all of the data in one table for reporting, but that really depends on the type of general purpose entity, so I may need to revisit this in the future, or I may just take the many-to-many route if I do need the data in one table.
And I can still have:
public static class GeneralPurposeStringExtensions
{
    public static void SassThatHoopyFrood(this GeneralPurposeString s)
    {
        // do stuff
    }
}


text:
Q: Pizza Problem, percents A medium size pizza at Ristorante Porcupine is 10 inches in diameter. A large pizza is 21 inches in diameter. What percent larger is the area of a large pizza?
Express your answer to the nearest whole percent.
So I know that the area of the medium is 5pi and the bigger is 10.5pi but what do I do now?

A: Let $A_L$ and $A_M$ denote the areas of large and medium pizzas, then
$$
\frac{A_L}{A_M} = \frac{\pi (21/2)^2}{\pi (10/2)^2} = \frac{21^2}{100} = 1 + \frac{?}{100},
$$
can you now complete the problem?


text:
Q: JavaMail Api: Read mail that has attachment I am able to read the mail that has only the message body in it.
However if,
1) append an attachment  or/and
2) send reply to the mail
I am not able to read the message body.
if (StringUtils.contains(msg.getContentType(), "text/html") || StringUtils.contains(msg.getContentType(), "text/plain")){
            textMsg = msg.getContent().toString();

        } else if (StringUtils.contains(msg.getContentType(), "multipart")){
            Multipart multiPart = (Multipart) msg.getContent();
            int partCount = multiPart.getCount();
            textMsg=  multiPart.getBodyPart(0).getContent().toString();

            for (int j = 0; j < partCount; j++){
                BodyPart part = multiPart.getBodyPart(j);
                String disposition = part.getDisposition();
                InputStream inputStream = null;
                if (disposition == null){
                    // Check if plain
                    MimeBodyPart mbp = (MimeBodyPart) part;
                    if(mbp.getContent() instanceof MimeMultipart){
                        MimeMultipart mmp = (MimeMultipart) mbp.getContent();
                    }
                    else{
                        textMsg=  multiPart.getBodyPart(0).getContent().toString();
                        inputStream=part.getInputStream();
                    }

                }else{
                    textMsg = part.getContent() != null ? part.getContent().toString() : "";
                }
            }
        }

Thank You !!


text:
Q: BIG QUERY SQL: How to find different sets of duplicates within a visit with same unique keys but different period of the visit? WHAT IS THIS POST FOR?
In bigquery, I need to remove duplicated rows with a caveat
that duplication happened within the same visit for a visitor for page visits with the same pagename.
GROUP BY DOES NOT RESOLVE THE ISSUE
Below,I have explained the data, issue, possible resolution and measure taken to the best of my ability.
WHAT DATA AM I USING?
Adobe data imported to Bigquery ( no issues in importing )
Each row is the data collected by page-view for a visitor.
Each time a visitor moves to new page it counts a visit_page_num + 1 in the same visit_num and for same visitor_id.
The pagename is recorded for each page visited.
ISSUE :
In this image,

some of the visit_page_num are counted as unique on unique visitor_id, visit_num but are duplicated as the pagename is same.
ISSUE
visit_page_num      pagename
       1               a
       2               b
       3               c  -issue
       4               c  -issue
       5               d
       6               d
       7               d
       8               e
       9               c  -issue
      10               c  -issue
      11               c  -issue

Solution so far with GROUP BY
visit_page_num      pagename
       1               a
       2               b
       3               c  -issue
       5               d
       8               e

  GOAL
visit_page_num      pagename
       1               a
       2               b
       3               c  -Goal
       5               d
       8               e
       9               c  -Goal

When duplicates on same pagename occur but at different time in the visit then how do we insure the later duplication are not eliminated but counted as different page visit.
QUERY USED :
SELECT visitor_id
,visit_num
,pagename
,first (visit_page_num) AS first
,ROW_NUMBER() OVER(PARTITION BY visitor_id, visit_num ORDER BY visitor_id, visit_num, pagename) AS int_var
FROM [table]
GROUP BY visitor_id, visit_num, pagename
ORDER BY visitor_id, visit_num, first

OUTPUT :
Everything is Good EXCEPT the,

visitor_id = A on visit_num = 1 and pagename = c
ACTIONS TAKEN :

*

*I have tried the LEAD and LAG function with MIN and MAX function in second step>>> SAME OUTPUT

*CHECKED the web, normal SQL functions that can be translated into BIGQUERY >> SAME OUTPUT

*Asked my team lead >> SAME OUTPUT

*5 hours of experimenting >> SAME OUTPUT
CAVEAT
Cannot use field_date OR any time field OR any other field beside the one mentioned in the table

A: try locating only the transitions between pages e.g.
SELECT
    visitor_id
  , visit_num
  , pagename
FROM (
    select
    *
    , lead(pagename) over(partition by visitorid order by visit_page_num)
      as nxt_page
    from table1
    ) derived
WHERE nxt_page <> pagename or nxt_page IS NULL
ORDER BY visitor_id, visit_num


text:
Q: Retrieving the proper file from a directory with ~280,000 files I have ~280,000 files that will need to be searched through, and the proper file returned and opened.  The file names are exact matches of the expected search terms.
The search terms will be taken by an input box using PHP.  What is the best way to accomplish this so that searches do not take a large amount of time?
Thanks!

A: I suspect the file system itself will struggle with 280,000 files in one directory.
An approach I've taken in the past is to put those files in subdirectories based upon the initial letters of the filename e.g.
1/100000.txt
1/100001.txt
...
9/900000.txt

etc. You can subdivide further using the second letter etc.

A: Its good you added mysql to your tags. Ideally i would have a CRON task that would index the directories into a mysql table and use that to do the actual search. Algebra is faster than File System iteration. You could run the task daily or hourly depending on how often your files change. Or use something like Guard to monitor the file system for changes and make appropriate updates.
See: https://github.com/guard/guard


text:
Q: How does pushing to git and deploying on the server at the same time work I would like to set up an environment, where I push my code to a git and the code is deployed on the server right away. And to be honest I was wondering how that would work out? Let's say I have an Java project using Maven and some JSF included. Now I could build this to a WAR-File using Maven and push it into my tomcat, then restart the tomcat and it got deployed.
How does that work when it is pushed into a git? Is there some kind of module in the git included, where I can configure a directory where it should be build & pushed afterwards? Or is it just a certain branch that is pushed right away?

A: Below mentioned link might be useful. Please check
https://medium.com/@francoisromain/vps-deploy-with-git-fea605f1303b


text:
Q: Send data from Activity to Fragment when fragment is onCreateView Sorry for my english. I have one activity and in this activity in FragmentPagerAdapter exist 5 fragments. All fragments use one object model for inforation(product name, product image ...).
My activity get data from data base. And then it data send to all fragments. My example Activity:
           @BindView(R.id.tabs_sep_prod) TabLayout tabs_sep_prod;
            @BindView(R.id.viewpager_sep_prod) ViewPager viewpager_sep_prod;
            PrepBaseProdFragment prepBaseProdFragment;

         @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_sep_product);
                ButterKnife.bind(this);

                prepBaseProdFragment = new PrepBaseProdFragment();
                // there i have another fragments
                // ...
                setupViewPager(viewpager_sep_prod);
                tabs_sep_prod.setupWithViewPager(viewpager_sep_prod);
        }

         private void setupViewPager(ViewPager viewPager) {
                SepProductActivity.ViewPagerAdapter adapter = new SepProductActivity.ViewPagerAdapter(
                adapter.addFrag(prepBaseProdFragment, getString(R.string.sep_prep_base));
                 // there i have another addFrag
                // ...
                viewPager.setOffscreenPageLimit(5);
                viewPager.setAdapter(adapter);
            }

     @Override
        public void onResume() {
            super.onResume();
        // this i call method from presenter, it return data in method setData
            if(idCat != null && idProd != null)
                sepProductPresenter.getSepProd(idCat, idProd);
        }

    @Override
        public void setData(SepProductModel sepProductModel) {
        // there i send data to fragment
            prepBaseProdFragment.setDataInf(sepProductModel);
        // ...
        }

class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFrag(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }

my fragment
public class PrepBaseProdFragment extends BaseFragment {

    @BindView(R.id.text) TextView text;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_about_prod_prepare_base, parent, false);
        ButterKnife.bind(this, view);
        Log.e("PrepBaseProdFragment", "PrepBaseProdFragment");

        return view;
    }

    public void setDataInf(SepProductModel sepProductModel) {
        text.setText(sepProductModel.getPROPERTY_PR_SUBSTRPREP_UA_VALUE().getTEXT());
    }

}

My question:  when i send data from activity to fragment, my view do not have time to initialize. In fragment line text.setText(sepProductModel.getPROPERTY_PR_SUBSTRPREP_UA_VALUE().getTEXT()); error

java.lang.NullPointerException: Attempt to invoke virtual method 'void
  android.widget.TextView.setText(java.lang.CharSequence)' on a null
  object reference

Please, help me solve my problem. I spend many times for this

A: You can check if the text view is null save the data in a variable inside the fragment and in onCreateView use the data variable if it is filled and set the textview text.
Something like this:
// Inside the Fragment body
private SepProductModel sepProductModel;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_about_prod_prepare_base, parent, false);
    ButterKnife.bind(this, view);
    Log.e("PrepBaseProdFragment", "PrepBaseProdFragment");
    if(this.sepProductModel != null)
        text.setText(this.sepProductModel.getPROPERTY_PR_SUBSTRPREP_UA_VALUE().getTEXT());
    return view;
}

public void setDataInf(SepProductModel sepProductModel) {
     if(text != null){
         // use text
     }
     else this.sepProductModel=sepProductModel;
}

A: I can advise you to wait for your data and then show fragments to adapter, moreover all of them use the same model. While you dont have data, you can show progress bar.
When you have needed model, you can create instances of your fragments and set bundle arguments for them. You can use method like this:
public static MyFragment newInstance(MyModel model){
    MyFragment fragment = new MyFragment();
    Bundle args = new Bundle();
    args.putSerializable(KEY, model);//or args.putParcelable(KEY, model);
    fragment.setArguments(args);
    return fragment;
}

Notice: your model need to implement Serializable or Parcelable to be putted in bundle. You may read about difference here.
Then in your set data method, when you already have your model you can setup your adapter and set it to view pager, but with this approach:
adapter.addFrag(MyFragment.newInstance(model), getString(R.string.sep_prep_base));

It have to help you, ask me if you have some questions.


text:
Q: Step Property for a circular slider Could anyone please help me in creating a stepper function that would take a parameter 'n' and would increment my slider according to n's value. Circular slider I'm using is this :
https://github.com/fseehawer/react-circular-slider
This is how the knob is being set based on different angles, but what if I want to set the knob at angles separated with 20 degree angle.
const setKnobPosition = useCallback(
    (radians) => {
      const radius = state.radius - trackSize / 2;
      const offsetRadians = radians + knobOffset[knobPosition];
      const degrees = (offsetRadians > 0 ? offsetRadians : 2 * Math.PI + offsetRadians)
          * (spreadDegrees / (2 * Math.PI));

      const pointsInCircle = (state.angles.length - 1) / spreadDegrees;
      const currentPoint = Math.round(degrees * pointsInCircle);
      if (state.angles[currentPoint] !== state.currentPoint) {
        onChange(state.angles[currentPoint]);
      }

      dispatch({
        type: 'setKnobPosition',
        payload: {
          displayedCompassAngle: state.angles[currentPoint],
          knob: {
            x: radius * Math.cos(radians) + radius,
            y: radius * Math.sin(radians) + radius,
          },
        },
      });
    },
    [
      state.radius,
      state.angles,
      state.displayedCompassAngle,
      knobPosition,
      trackSize,
      direction,
      onChange,
    ],
  );

These are initial state and different props I am using.
const CircularSlider = (props) => {
  const {
    width = 280,
    direction = 1,
    knobPosition = 'top',
    hideLabelValue = false,
    knobDraggable = true,
    trackSize = 8,
    angles = [],
    compassAngle = 0,
    onChange = () => {},
  } = props;

  const initialState = {
    mounted: false,
    isDragging: false,
    width,
    radius: width / 2,
    knobPosition,
    displayedCompassAngle: 0,
    angles,
    radians: 0,
    offset: 0,
    knob: {
      x: 0,
      y: 0,
    },
  };


text:
Q: How to enable error highlighting in HTML with "create method" feature in WebStorm? I used to have this feature running but not after a recent update!
On line #33, I am getting the expected red color and suggestion to create the variable.
On line #34, I want to have the same feature enabled for the method, which in this case - continue2() - is not present in the Angular component, but I am no longer seeing a red text color, no suggestion, and not even a runtime error!

A: If you run into the same issue, look into your .idea/ folder, then inside an inspectionProfiles/ folder. There, I found this file below. Line 7 says it all. How that got into my folder structure I am not sure, seems I clicked the wrong option while trying to get rid of popups quickly maybe.
When comparing to other projects, this file doesn't exist! So I deleted it, or you could cherrypick what to delete/leave in it.

From a Settings perspective, I had the "Unresolved TypeScript function" option unselected as shown in the image below; so another way to fix the issue of the post is to select it back.
For this part of the answer: Thanks to Lena P from JetBrains Support.


text:
Q: Find the set of points in euclidian and taxicab metric that are the same distance from $(0,1)$ and $(1,0)$ Find the set of points in euclidian and taxicab metric that are the same distance from A = $(0,1)$ and B =$(1,0)$.
So I just started doing metric spaces and I have got to this simple problem.
My understanding:
We can define a metric as:
$$d((x_1,x_2,...,x_n),(y_1,y_2,...,y_n)) = [\sum_{i=1}^{p}|x_i-y_i|^{1/p}]^p $$ , where if $p = 1$ we call it taxicab metric and if $p  = 2$ we call it euclidian metric.
However for this problem I do not know how to begin it. Do I have to look the taxicab metric as only in $\mathbb{R^1}$ space and thus we have a point $x_1 = 1$ and a point $y_1 = 0$ and then for euclidian metric as in $\mathbb{R^2}$ and $x_1 = 1, x_2 = 0$ and $y_1 = 0, y_2 = 1$ .
My question is how to go about problems like these?

A: These are the points $(x,y)$ such that
$$d((x,y),(0,1))=d((x,y),(1,0).$$
That is, $$|x|+|y-1|=|x-1|+|y|$$


text:
Q: Google Apps Scripts - Send url with permissions I have a google spreadsheet with a function to send via email a url to the sheet. How do I set this url with read only permissions?
function createAndSendDocument() {
// set active spreadsheet
var doc = SpreadsheetApp.getActiveSpreadsheet();

// Get the URL of the document.
var url = doc.getUrl();

// Get the email address of the active user - that's you.
var email = "email@gmail.com";

//add email
var ui = SpreadsheetApp.getUi();
var response = ui.prompt('Who do you want to send this to?', 'Type email below:', ui.ButtonSet.YES_NO);

// Get the name of the document to use as an email subject line.
var subject = doc.getName();
// Append a new string to the "url" variable to use as an email body.
var body = 'See the latest file: ' + url;

// Process the user's response.
if (response.getSelectedButton() == ui.Button.YES) {
email = email + ", " + response.getResponseText();
Logger.log('The user\'s name is %s.', response.getResponseText());
} else if (response.getSelectedButton() == ui.Button.NO) {
Logger.log('The user didn\'t want to provide a name.');

} else {
Logger.log('The user clicked the close button in the dialog\'s title bar.');
// Send yourself an email with a link to the document.
GmailApp.sendEmail(email, subject, body);

}

}

A: You can check this option to add a viewer for that sheet.
doc.addViewer(emailAddress);

Hope that helps!


text:
Q: Pre-selection in a CollectionView from code-behind without Binding I cannot make some items selected in the CollectionView.
I'm trying to add pre-selected items into a CollectionView via code-behind, but the application throws me an exception
This is my XAML code
<CollectionView
            x:Name="CategoryView"
            ItemsSource="{Binding list}"
            Margin="10,0,10,0"
            SelectionMode="Multiple"
            SelectionChanged="CategoryView_SelectionChanged">
            <CollectionView.ItemsLayout>
                <GridItemsLayout Orientation="Vertical" Span="2" VerticalItemSpacing="15" HorizontalItemSpacing="3"/>
            </CollectionView.ItemsLayout>
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Grid RowSpacing="0">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="25"/>
                            <RowDefinition/>
                            <RowDefinition Height="150"/>
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="2*"/>
                        </Grid.ColumnDefinitions>

                        <Label Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" Text="{Binding Titolo}" FontSize="19" FontAttributes="Bold" TextColor="Black" Margin="13,0,0,0"/>
                        <!--Label Grid.Row="1" Grid.Column="0"  Text="{Binding Descrizione}" FontSize="12" TextColor="Black" Margin="13,0,0,0"/-->
                        <Image Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2" Source="{Binding Image}"/>
                        <Image Grid.Row="2" Grid.Column="0" VerticalOptions="Start" Source="checked.png" IsVisible="{Binding IsVis}"  Margin="20,10,0,0"/>
                    </Grid>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>

This is my c# code:
List<string> list = new List<string>();
....
listCat = new ObservableCollection<ClassCategory>
        {
            new ClassCategory {ID=1, Titolo=set.Obiettivi, Image="CatObiettivo.png", Descrizione="Il miglior modo per raggiungere i propri obiettivi"},
            new ClassCategory {ID=2, Titolo=set.Ambizioni, Image="CatAmbizione.png", Descrizione="Chi ha ambizioni e non vuole perdere la motivazione"},
            new ClassCategory {ID=3, Titolo=set.Amicizia, Image="CatAmicizia.png", Descrizione="Una celebrazione all'amiciza"},
            new ClassCategory {ID=4, Titolo=set.Felicita, Image="CatFelicita.png"},
            new ClassCategory {ID=5, Titolo=set.Tempo, Image="CatTempo.png"},
            new ClassCategory {ID=6, Titolo=set.Umore, Image="CatUmore.png"},
            new ClassCategory {ID=7, Titolo=set.Coraggio, Image="CatCoraggio.png"},
            new ClassCategory {ID=8, Titolo=set.Intelligenza, Image="CatIntelligenza.png"},
            new ClassCategory {ID=9, Titolo=set.Sogno, Image="CatSogno.png"},
            new ClassCategory {ID=10, Titolo=set.Cambiamento, Image="CatCambiamento.png"},
            new ClassCategory {ID=11, Titolo=set.Abitudine},
            new ClassCategory {ID=12, Titolo=set.Perdono, Image="CatPerdono.png"},
            new ClassCategory {ID=13, Titolo=set.Ansia, Image="CatAnsia.png"},
            new ClassCategory {ID=14, Titolo=set.Autostima},
            new ClassCategory {ID=15, Titolo=set.Ricchezza, Image="CatRicchezza.png"},
            new ClassCategory {ID=16, Titolo=set.Procastinare},
            new ClassCategory {ID=17, Titolo=set.CapireDonne, Image="CatDonne.png"},
            new ClassCategory {ID=18, Titolo=set.CapireUomini, Image="CatUomini.png"},
            new ClassCategory {ID=19, Titolo=set.Amore, Image="CatAmore.png"},
            new ClassCategory {ID=20, Titolo=set.Amarsi},
            new ClassCategory {ID=21, Titolo=set.Leader, Image="CatLeader.png"},
            new ClassCategory {ID=22, Titolo=set.Vivere},
            new ClassCategory {ID=23, Titolo=set.Benessere, Image="CatBenessere.png"},
            new ClassCategory {ID=24, Titolo=set.Solitudine, Image="CatSolitudine.png"},
        };

        CategoryView.ItemsSource = listCat;

        foreach (string sr in list)
        {

            var ObjFinded = listCat.First(s => s.Titolo.Contains(sr));
            var Index = listCat.IndexOf(ObjFinded);
            CategoryView.SelectedItems.Add(listCat[Index]);
        }

This exception is thrown when I try to add items inside the foreach loop
System.InvalidOperationException
Message=Collection was modified; enumeration operation may not execute.


text:
Q: How can I make the apa6-document class NOT print a short title? I am writing my master's thesis on TeXmaker. As for following the APA citation rules, I started using the apa6 document class. But even in the doc-mode, it still puts a short title (in capital letters) on top of every page, but I don't think that is appropriate in a master's thesis.
So my question is: how can I either erase that short title so it doesn't appear at all, or at least change it into normal letters?
I tried \renewcommand{\shorttitle}[1]{} which I found in this forum, it seems to work for suppressing the abstract, but it didn't work for me.

A: I found a nice workaround: just leaving the \shorttitle{} -command empty helped.
My MWE:
\documentclass[12pt,a4paper,doc]{apa6}
\usepackage[english, ngerman]{babel}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}

\begin{document}

\title{title}
\author{C.Zet}
\affiliation{master's thesis}
\date{\today}
\shorttitle{ }
\maketitle
\end{document}

A: Try adding \thispagestyle{empty} in the title section, in addition to \shorttitle{ }. This removes "Running head:" for me.


text:
Q: Calculation of the standard deviation of the power in dB I wanted to find out the stability of my system so for that i calculated standard deviation of power samples data which is in dB but I am not sure whether i have used correct formula or not.
As far as I know, I can not directly take standard deviation of the dB, so i converted dB the linear using formula as follow :

After that I take a mean of this linear samples then I calculated variance after that standard deviation and finally calculated standard error and then I converted back this result into dB using following formula:

After converting back to the db the result is very strange I don't know why.
Any guidance on this matter would be highly appreciated.


text:
Q: geometric interpretation of Taylor's theorem Deriving Taylor's theorem is not a problem. But I am curious if there is any nice
geometric interpretation of the theorem.

A: You're approximating the given function by a polynomial. The polynomial approximation is constructed so that its derivatives agree with the given function at one particular point.
Geometrically, a Taylor series with two terms is a straight-line approximation; the straight line is the tangent at the given point. One with three terms is a parabola approximation, whose tangent and curvature agree with the given function at the given point. And so on.
Given their myopic focus on a single point, the approximations produced this way are often less than ideal -- you often need an approximation that's good throughout some interval. But at least they're easy to construct.

A: I think the answers in the link I added in the comment are really useful. But my own interpretation, possibly not so refined would be two fold.
1) If you consider a "reasonably good-mannered" geometric object, say a curve or a surface, then depending on where you truncate your Taylor series, you can compare it with other well behaved, reference objects locally at least. That is, say for a curve, you can see as to how far it is not a straight line or a parabola/circle and so on.
2) Another possible thread not much different from the first one would be using analyticity, in that the geometric counterparts of such functions(which have a valid Taylor series expansion) are "predictably smooth", in that the smoothness is as you would expect it.
I guess there are a bit too many loose/cheesy words in this answer, but I do hope it helps a little.

A: If a function is differentiable in a given domain, then, the functional value of the function at each point is the sum of the functional values of several polynomials at that point.
Visualise several graphs in the $R$ plane, then, their functional values all add up.


text:
Q: Php classname здравствуйте, пишу на пхп вордпресс темы плагины и очень хочу правильно решить вот какую проблемку:
для работы создал дополнительный статический класс например class Additional, и если в проекте подключены два моих плагина, и в обоих есть этот класс, это вызывает ошибку, т.е. я пока пишу в разных проектах Additional001, Additional002..
возможности Additional используются в другом рабочем классе например: Additional001::func();
я так понимаю для решения этого я так и должен дальше декларировать Additional001, Additional002.., только в рабочем классе я должен создать некую instance для него..
может быть в конструкторе рабочего класса я должен создать переменную этого рабочего класса, которая будет ссылаться на Additional001 например, и  в рабочем классе в любом месте я смог бы испльзовать что то вроде $this, self -> AD
надеюсь понятно пояснил и собственно вопрос: как правильно это решается? без неймспейсов


text:
Q: form keydown event interrupt the working of textBox keypress event c# I have a form, where I am using Form_keyDown Event and KeyPreview=true.
The code is as follows
private void MainForm_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.C)
            button2_Click(sender, e);
        if (e.KeyCode == Keys.P)
            button3_Click(sender, e);
        if (e.KeyCode == Keys.B)
            button4_Click(sender, e);
        if (e.KeyCode == Keys.U)
            button5_Click(sender, e);
        if (e.KeyCode == Keys.T)
            button6_Click(sender, e);
        if (e.KeyCode == Keys.W)
            button7_Click(sender, e);
        if (e.KeyCode == Keys.X)
            button8_Click(sender, e);
    }

But when I press the keys (i.e. C,P,B,U,T,W and X) on a textBox the event fires. What I need is the Skip the TextBox from Form_keyDown event. Is this possible?
The Function keys are already in use and the user does not prefer to user alt or ctrl.
Is there is any away to form_keyDown event and textBox KeyPress works differently?

A:     private void MainForm_KeyDown(object sender, KeyEventArgs e)
    {
        if (ActiveControl.Name!="textBox20")
        {
            if (e.KeyCode == Keys.C)
                button2_Click(sender, e);
            if (e.KeyCode == Keys.P)
                button3_Click(sender, e);
            if (e.KeyCode == Keys.B)
                button4_Click(sender, e);
            if (e.KeyCode == Keys.U)
                button5_Click(sender, e);
            if (e.KeyCode == Keys.T)
                button6_Click(sender, e);
            if (e.KeyCode == Keys.W)
                button7_Click(sender, e);
            if (e.KeyCode == Keys.X)
                button8_Click(sender, e);
        }
    }


text:
Q: Send on-hold order status email notification to admin I want the admin to receive on hold order notification as well in WooCommerce. Right now, only customers get that notification.
I have tried the following codes but it doesn't seem to work.
Here is my code:
add_filter( 'woocommerce_email_headers', 'mycustom_headers_filter_function', 10, 2);
function mycustom_headers_filter_function( $headers, $object ) {
    if ($object == 'customer_on_hold_order') {
        $headers .= 'BCC: My name <my@email.com>' . "\r\n";
    }
    return $headers;
}

What should be the correct filter/hook to use?
Thanks

A: The correct $email_id for "on-hold" order status email notification is 'customer_on-hold_order'.
So your code is going to be:
add_filter( 'woocommerce_email_headers', 'custom_admin_email_notification', 10, 3);
function custom_admin_email_notification( $headers, $email_id, $order ) {

    if( 'customer_on-hold_order' == $email_id ){
        // Set HERE the Admin email
        $headers .= 'Bcc: My name <my@email.com>\r\n';
    }
    return $headers;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Code is tested and works.

Similar answers: How to get order ID in woocommerce_email_headers hook

A: It has been 3 years and the WooCommerce states seem to have changed. I tried using the new states customer_on-hold_order => pending_to_on-hold or woocommerce_order_status_pending_to_on-hold, but no emails came and the headers were not changed. so I resulted in just using single words for the check:
// Send on-hold order status email notification to admin
add_filter( 'woocommerce_email_headers', 'custom_admin_email_notification', 10, 3);
function custom_admin_email_notification( $headers, $email_id, $order ) {

    if( strpos($email_id,'hold') > 0 ){
        $headers .= 'Bcc: Admin User <admin@example.com>'. "\r\n";
    }
    return $headers;
}

I thank you @LoicTheAztec, however for pointing me in the right direction.

A: The correct $email_id for "on-hold" order status email notification is NOT 'customer_on-hold_order' as sugested in the answer bellow (sorry no reputation to comment) but the right one is 'customer_on_hold_order'
So change the on-hold to on_hold


text:
Q: How to connect single-phase power source to 3-phase motor My 3-phase, wye wound, 9-lead motor has:

*

*wires 1 & 7 connected to wire L1

*2 & 8 connected to L2

*3 & 9 connected to L3

*and 4, 5, 6 wired together.

I put a plug on one end of a cable, that is plugged into a 220 V dryer outlet. How are the three wires in the cable, connected to the motor wires?

A: It's not optimal but there is a way to run small 3-phase induction motors at reduced torque from a single phase supply.
It's called "Steinmetz connection" (Steinmetz being one of the developers of said motors). In short you can use a capacitor to create a 'fake' phase from the supply line. Search the web for formulas and details.


text:
Q: Change style of Indeterminate Progress Bar I want to change what I have now and is hardly visible:

to this:

It's a customized progress Dialog without text, title nor background. Only the spinner.
I used this implementation for a progress Dialog:
public class IndeterminateProgressSpinner extends Dialog {
static Dialog dialog;

public static IndeterminateProgressSpinner show(Context context,
        OnCancelListener cancelListener) {
    dialog = new IndeterminateProgressSpinner(context);
    dialog.setTitle(null);
    dialog.setCancelable(false);
    dialog.setOnCancelListener(cancelListener);
    /* The next line will add the ProgressBar to the dialog. */
    ProgressBar pb = new ProgressBar(context);
    dialog.addContentView(pb, new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT));
    dialog.show();
    return (IndeterminateProgressSpinner) dialog;
}

public IndeterminateProgressSpinner(Context context) {
    super(context, R.style.indeterminateProgressSpinner);
}

And this is the style R.style.indeterminateProgressSpinner
    <style name="indeterminateProgressSpinner">
    <item name="android:windowFrame">@null</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowTitleStyle">@null</item>
    <item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
    <item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
    <item name="android:backgroundDimEnabled">false</item>
    <item name="android:background">@android:color/transparent</item>
    <item name="android:indeterminateOnly">true</item>
    </style>

thank you


text:
Q: For Java's ScheduledExecutorService's scheduleAtFixedRate method does it return 1 ScheduledFuture or many? I ask this question because there is a command that executes multiple times. Does it return a ScheduledFuture every time the command executes or does it return a single ScheduledFuture at some point?

A: Only a single ScheduledFuture<?> is returned upon scheduling the Runnable command.
According to the Javadoc, scheduleAtFixedRate returns

a ScheduledFuture representing pending completion of the series
of repeated tasks

You can also see this in the method signature:
ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)

The Runnable command continues to be executed according to the configured interval without further intervention.

The sequence of task executions continues indefinitely until one of
the following exceptional completions occur:

*

*The task is explicitly cancelled via the returned future.

*The executor terminates, also resulting in task cancellation.

*An execution of the task throws an exception.

Having a single ScheduledFuture returned by scheduleAtFixedRate provides a useful mechanism to programmatically discontinue all future scheduled executions of Runnable command through a call to cancel on the Future.


text:
Q: How to get unobtrusive validator params for an input? I have an input with custom unobtrusive validator. There is a number of parameters passed to the validator. Can I access those parameters (outside of my custom validator) using javascript/jQuery and if so how?
Something like:
var validationParams = $('#MyInput').validator.unobtrusive.myvalidator.params;

A: The answer turned out to be in a place I didn't expect. The unbotrusive validator puts those params in data attributes of the input.
$('#MyInput').attr('data-val-myvalidator-myparam');

or
$('#MyInput').data('val-myvalidator-myparam');

Edit: As haim770 pointed out, it's not the unobtrusive validator that puts the params in the data attributes. Those are there from the start (my html is generated with those already). So the unobtrusive validator is actually reading those params from the data attributes.


text:
Q: MySQL query does not return proper results Very simple question from a MySQL newbie :
I have a table with some information on transactions (amount_paid, date, product_type...). Each transaction has a unique ID, and I also have a list of transactions. I have to inspect based on this ID. So I'm doing a query like...
SELECT amount_paid, date, ID FROM transactions WHERE ID = 10 OR ID = 12 OR ID = 34 OR ID = 76

etc... (I've got something like 200 transactions to inspect)
What's weird is that in the result I have IDs that I didn't ask for, and I miss ID I asked for... For example, I query ID = 435 OR ID = 439 and I got 435, 436 and 439 and on the contrary, I query ID = 578 OR ID = 587 OR ID = 588 and I got only 578 and 588.
I still have most of what I'd queried, but with these strange discrepancies...
Following suggestions below, I tried to do the query with WHERE ID IN (435, 439...) but I got the same problematic results
If someone could explain to me what I'm doing wrong, it would be great...
I'm doing my query from phpmyadmin.

A: As we know, the sql format for selecting data is SELECT * FROM yourTable. You miss FROM part

A: Have you tried something like:
SELECT * FROM TABLE WHERE ID IN (id1, id2, ..., idn)

Maybe you have a problem with the OR

A: See query
SELECT amount_paid, date, ID WHERE ID = 10 OR ID = 12 OR ID = 34 OR ID = 76

you're forgetting FROM table should fix using this:
SELECT amount_paid, date, ID FROM mytable WHERE ID = 10 OR ID = 12 OR ID = 34 OR ID = 76

OR You can also try like this , something new for you
SELECT amount_paid, date, ID FROM mytable WHERE ID in (10,12,34,76)


text:
Q: How to use carousel with a vertical thumbnail I want to use slickjs carousel for an e-commerce product single page
with a vertical thumbnail and zoom
if you have an idea please help, thanks in advance

A: You could use css with flexbox and change the flex-direction: coumn; on the same container that you are targeting with slick. You might have to change some other properties such as margin and padding to position them properly, but that would be a simple css based solution.


text:
Q: How is TRIM Support Handled on an SSD Accessed by Two Different Operating Systems? I have a Lenovo T410 ThinkPad running Windows 7 Professional as the host OS, and Windows XP Professional running as a guest OS under Windows 7 Virtual PC.
I am thinking of installing a 128GB SSD to host the Virtual PC, but XP does not support the SSD TRIM command, whereas Windows 7 does.  In addition, I was thinking of using that same SSD to support some caching of the Windows 7 environment.

*

*Is it possible, under Windows 7 with a multiple drive configuration, to specify things such as the drive location of Windows 7 virtual memory?

*Assuming it is, since both Windows XP and Windows 7 would be accessing the same drive, if I put some Windows 7 files there, would the TRIM support available under Windows 7 effectively handle the TRIM function for the whole drive? Or am I missing something here?

A: Your question could use a bit of clean up, I'll attempt that when done. For now...
With all versions of Windows from at least 2000, you can assign a different drive for the page file

*

*Right-click on My Computer and click on Properties

*Vista/Windows 7 and server versions: Select the Continue or Yes option for UAC

*Select Advanced System Settings

*Select Settings under Performance

*Select Advanced

*Select Change

*Choose a different drive for the page file

For the guest being Windows XP, it will not control TRIM unless it has full access to the hard drive and the hard drive is removed from Windows 7. This does not sound like what you have. Virtual Machines typically use Virtual Hard Drives, which are just files. I say typically, because there are some products that will let a VM control an actual device.
Windows 7 should control the actual device for you, and Windows XP should not know the difference in most cases


text:
Q: Multiple Checkboxes in Android I am designing contact list page in android in which it has an image box then Name and a Checkbox.When i select all contacts that are showing in screen and scrolled down for further contacts to select by doing this the contacts which i selected in previous page gets unselected automatically.
Here is My XML code
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:divider="?android:dividerVertical"
    android:dividerPadding="8dp"
    android:minHeight="?android:listPreferredItemHeight"
    android:orientation="horizontal"
    android:showDividers="middle">

    <ImageButton
        android:id="@+id/image"
        android:layout_width="@dimen/contact_image"
        android:layout_height="match_parent"
        android:src="@drawable/ic_action_user"/>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:clickable="false"
        android:focusable="true"
        android:gravity="center_vertical"
        android:orientation="vertical">

        <TextView
            android:id="@+id/text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="15sp"
            android:text="@string/dummy_title"  />

    </LinearLayout>

    <CheckBox
        android:layout_width="@dimen/standard_touch_target_size"
        android:layout_height="match_parent"
        android:clickable="true"
        android:gravity="center"
        android:paddingLeft="50dp"/>

</LinearLayout>

A: Could you provide the rest of the code, like the adapter? Are you setting somewhere the selected state for the positions you've selected? That's probably the reason you always get unselected checkboxes.


text:
Q: MSVC 2012 detecting number of template arguments of a template function via SFINAE What I'm trying to do: I've got a template object incoming which, as part of an interface, should have a "process" function defined with a number of arguments (I don't know how many) some of which are template arguments.
I.e.
struct A { static void process(int a); };
struct B { template <typename B0> static void process(int a, B0 b0); };

are both valid handlers to receive. So now I need to detect a signature for a handler: static-typed parameters and a number of template parameters.
To do so, I'm using a number of template magic hacks which may be narrowed down to the problematic part - detecting a number of template args (or just retrieving a templated signature).
The way I'm trying to find out the required info is by checking for a explicitly specialized signature using the method described in Is it possible to write a template to check for a function's existence?
struct _D;

template <typename T>
struct get_template_args_count
{
private:
    template <int count> struct R { enum { value = count }; };

    template <typename C>
    static R<0> retrieve(decltype(&C::process));

    template <typename C>
    static R<1> retrieve(decltype(&C::template process<_D>));

    template <typename C>
    static R<-1> retrieve(...);

public:
    typedef decltype(retrieve<T>(nullptr)) Result;
    enum { value = Result::value };
};

int main(int argc, char* argv[])
{
    std::cout
        << "A::process " << get_template_args_count<A>::value << "\n"
        << "B::process " << get_template_args_count<B>::value << "\n";
    std::cin.get();

    return 0;
}

With clang (built with msvc2013 or linux version, built with gcc-4.9.2) it compiles and outputs:
 A::process 0
 B::process 1

With msvc2012 it compiles too, but outputs:
 A::process 0
 B::process -1

When cornered in by commenting out the fallback case (the one with (...)) msvc2012 freaks out:
main.cpp(28): error C2893: Failed to specialize function template 'get_template_args_count<T>::R<count> get_template_args_count<T>::retrieve(unknown)'
          with [ T=B, count=1 ]
          With the following template arguments: 'B'
          v:\test\test\test\main.cpp(63) : see reference to class template instantiation 'get_template_args_count<T>' being compiled
          with [ T=B ]
main.cpp(28): error C2893: Failed to specialize function template 'get_template_args_count<T>::R<count> get_template_args_count<T>::retrieve(unknown)'
          with [ T=B, count=0 ]
          With the following template arguments: 'B'
main.cpp(29): error C2825: 'get_template_args_count<T>::Result': must be a class or namespace when followed by '::'
          with [ T=B ]
main.cpp(29): error C2039: 'value' : is not a member of '`global namespace''
main.cpp(29): error C2275: 'get_template_args_count<T>::Result' : illegal use of this type as an expression
          with [ T=B ]
main.cpp(29): error C2146: syntax error : missing '}' before identifier 'value'
main.cpp(29): error C2143: syntax error : missing ';' before '}'
main.cpp(29): error C2365: 'value' : redefinition; previous definition was 'enumerator'
        main.cpp(29) : see declaration of 'value'

(the log is slightly reformatted to take less lines)
I've also tried to use different techniques described in comments of the question above (using char[sizeof], using typeof and moving the check into return type), to no avail - it either produce the same results or falls apart with even weirder errors (including "unexpected end-of-file" with no obvious reason).
I've also checked out a similar question Deduce variadic args and return type from functor template parameter (MSVC-specific) with another technique (comparing prototypes via SFINAE), but I can't see how to use it when I don't know exact signature (i.e. I don't know a number and types of static parameters). I may brute-force them for a specific task at hand, of course, but...
So I've got two questions:

*

*Why it should be always so hard with MSVC?.. Ok, that's a rhetoric one, no answer is needed.

*Am I abusing some kindness of clang/gcc and actually MSVC is doing the right thing by throwing meaningless errors at my face? Are there any workarounds or right ways to do this, other than brute-forcing all possible static/template parameters combinations and comparing them using a full signature prototype?

A: The problem here is that MSVC refuses to extract the type of &C::template process<_D> to use in overload resolution (Note the absence of any meaningful error message). It appears that it considers the instanciated function to be an overload-set of only one function; probably an implementation goof.
You can force it to convert the overload-set to a function pointer type by feeding it into a function parameter:
template<typename T>
T* fn_id(T* func) {
    return nullptr;
}

Once T has been flattened into a function type, you can use it into decltype.
template <typename C>
    static R<1> retrieve(decltype(fn_id(&C::template process<_D>)));

With this hack I get the same output as you had with clang.


text:
Q: if formula not working as expected entire formula which is not working properly:
=IF(VLOOKUP(K28,AD:AF,3,FALSE)="offset","offset",IF(L28="",VLOOKUP(N28,AM:AN,2,FALSE),VLOOKUP(L28,AJ:AN,5,FALSE)))

This part of the formula by itself, works properly and returns what I need:
=IF(L28="",VLOOKUP(N28,AM:AN,2,FALSE),VLOOKUP(L28,AJ:AN,5,FALSE))

However once combined with the rest of the formula, this part of it doesn't work:
VLOOKUP(N28,AM:AN,2,FALSE).

Every other part of the formula works though.
Appreciate the help in advance.

A: If K28 is found in AD:AD, then that formula should work regardless of whether offset is found in AF:AF or not. However, if K28 is not found in AD:AD, then that first VLOOKUP returns an #N/A error and everything stops there. You need error control on at least that first VLOOKUP.
=IF(iferror(VLOOKUP(K28,AD:AF,3,FALSE), "err")="offset", "offset", IF(L28="", VLOOKUP(N28,AM:AN,2,FALSE), VLOOKUP(L28,AJ:AN,5,FALSE)))

'alternate
=iferror(VLOOKUP(K28,AD:AF,3,FALSE), IF(L28="", VLOOKUP(N28,AM:AN,2,FALSE), VLOOKUP(L28,AJ:AN,5,FALSE)))

I always error control each and every VLOOKUP I implement but that is a personal choice. You can add a couple more IFERROR wrappers if you wish.


text:
Q: Is the Keras Embedding layer dependent on the target label? I learned how to 'use' the Keras Embedding layer, but I am not able to find any more specific information about the actual behavior and training process of this layer. For now, I understand that the Keras Embedding layer maps distinct categorical features to n-dimensional vectors, which allows us to find, for example, how similar two features are.
What I do not understand is how these vectors in the embedding layer are trained. Here is an explanation where there is information that these vectors are not computed with any operation, but working only as a lookup table, but I always thought that they are somehow "trained" to find similarities between distinct features.
If they are trained, are they trained from target labels, or from the order in which they appear (similar to GloVe, word2vec, etc.) or from both?
I have the following example of two pairs of rows in a dataset. y is the model target label and X are the features encoded to integers to be used in the embedding layer:
#pair 1
dataset_y_row1 = [1]
dataset_y_row2 = [0]
dataset_X_row1 = [3,5,8,45,2]
dataset_X_row2 = [3,5,8,45,2]

#pair 2
dataset_y_row3 = [1]
dataset_y_row4 = [1]
dataset_X_row3 = [3,5,8,45,2]
dataset_X_row4 = [3,5,45,8,2]

My questions are the following:

*

*Will the embedding layer see any difference between rows 1 and 2 (i.e. is
it 'target-label-sensitive')?

*Will the embedding layer see any difference between rows 3 and 4 (i.e. is it sensitive to order of features like word2vec, GloVe, etc.)?

A: Embeddings layer for vocabulary of size $m$, that encodes each word into embeddings vector of size $k$ is a shorthand for having the words one-hot encoded using into $m$ features and then putting dense layer with $k$ units over it. Word2vec and GloVe are specialized algorithms for learning the embeddings, but the end product is a matrix of weights that is multiplied by the one-hot encoded words.
If you are interested in detailed, yet accessible introductory source on word embeddingss, check the series of blog post by Sebastian Ruder .
To answer your question, one would need to consider what is your network architecture and the data. Algorithms like word2vec and GloVe are trained on language data, to predict things like next word in a sequence. On another hand, if you use the embeddingss layer that is trained from the scratch and used as a part of larger network, that has some utilitarian purpose (e.g. spam detection, sentiment classification), then the layers work as any other dense layers, so they serve purpose of automatic feature engineering. In the latter case, you would expect to see more specialised embeddingss, that would learn features related to the objective of your network.


text:
Q: Regex match string with at least one uppercase and at least one number from 0-9 I am having a problem with the regex expressions. I am trying to match a string, which should contain at least one uppercase charracter and at least one number from 0-9
Lets say we have these strings:
   sdsFg3n match
   asdfghf not match
   aewag3t not match

The order of the charracters and numbers is not important.. The string should just contain them. The expression I tried is [A-Za-z0-9], but that doesn't help me...

A: How about something simple, like this?
([A-Z].*[0-9])|([0-9].*[A-Z])


text:
Q: Union of N intersecting translucent 3D objects I confused with the problem of intersecting translucent 3D objects.
I have a plenty of translucent objects which (potentially) can intersect each other. So, when I'm displayng them, in the case of intersection happened, I can see common parts of intersected objects inside each other.
What I want to do is to hide this common parts while rendering is being performed (it should looks like as a union of objects).
I'm new to OpenGL, but I've done some research and found that potentially it could be done by playing with Stencil/Depth/Color buffers and multi-rendering.
I wonder if someone can give me some advises about this proccess or techniques. Thanks.


text:
Q: What is meant by 2D fourier transform of an image? I have some questions about this interesting concept I came across about 2D Fourier transform, please...
Firstly, the Fourier transform of a 1D signal (such as a sound recording) is as follows:

The first picture is a graph of the real sound file, and the second picture is the sorted frequency bins of the analysed original recording. Although the the graphs are often plotted next to each other, the frequency domain graph really is not at all related to space dimensions, as it has no relations at all to the physical shape of the sound waves (or images file) etc. It is just a histogram of the strength of the different frequencies found after analysis, from bin 1, 2, 3... into a chart.
But, when we come to the 2D Fourier transform for images, suddenly I have trouble even picturing what this might possibly mean?

What is meant by the Fourier transform of a 2D signal? Do we take many 1D Fourier charts in the x-direction as before and do another meta Fourier transform in the y-direction on these frequency charts?
Since frequency charts are not even about spatial relationships, but really about histograms of tabulated frequencies, what does the frequency picture even represent? How to calculate the color value for each of the point $(x,y)$ in the frequency image, and what does the $x$-axis represent, what does the $y$-axis represent in this frequency image?
EDIT: Forward Fourier transform results

A: Yeah, this can be tricky to wrap your head around! Let's simplify. I can't guarantee you'll ever have an intuition for your more complex transforms. But after reading this, hopefully you'll have a place to start.
Here is a cosine wave, $\cos(x)$, 5 periods discretized into 101 points (since images on your computer are discrete, let's work with discrete data here). The x-axis is just the point number, not $x$. To the right is the absolute value of its discrete Fourier transform, $F(\cos(x))$ (I used the Mathematica default options for this).

We can interpret the peaks in this transform as the frequencies which comprise $\cos(x)$, one at positive frequency, and one at negative frequency. Since there are five periods within the range on the left, the transform peaks occur on the fifth points from the left and right (actually, the sixth point from the left including the zero frequency point). If the wave had a higher frequency, then there would be more periods within the range, and the transform peaks would appear further from the left and right, respectively.
Okay, now here's the 2D version of the same plot, along with the 2D Fourier transform of the image (absolute value, again):

You'll notice, at the very bottom of the transform image, two blips corresponding to the peaks in the first image. How do we interpret this? Well, again, the peaks represent the frequencies comprising $\cos(x)$. Since now we're plotting $\cos(x)$ in the $x$-$y$ plane, the fact that the peaks occur at the very bottom indicates that the image is constant in the $y$ direction (i.e., the only existing frequency in that direction is zero).
Here's what it looks like if we plot $\cos(y)$ instead:

Okay, cool. Now, generally in 2D, a wave could propagate in any direction within the $x$-$y$ plane, with any frequency: $\cos(k \cdot r)=\cos(k_x x+k_y y)$. So here is $\cos(x+y)$:

And here's $\cos(x+3y)$:

Of course, in the end, a complete image will be comprised of a linear combination of waves with all the wavevectors. Any image can be broken down this way. Here's $\cos(x+y)+\cos(x+3y)+\cos(3x+2y)$:

So what do I mean by "frequency" in all of this? I mean the number of periods which fit within the range of the image in a particular direction. In your first plots, the 1D example, the axis is understood to be representative of time. Therefore, the frequencies of the transform are temporal frequencies. However, if the axis were in units of length, the transform would show spatial frequencies. Since images are often in units of length, then the 2D transform is often interpreted as the spatial frequency spectrum which comprises the image.

A: I'll give you a mathematical expression to augment Gilbert's answer. The Fourier transform in 1D is given by
$$\hat f(k)=\int\mathrm dx \, e^{ikx}f(x).$$
There are ofcourse other conventions but I chose a convenient one. You can then consider a (grayscale) image as a 2D function $f(x,y)$ which gives the intensity of the image at every point $(x,y)$. The Fourier transform in 2D is given by
$$\hat f(k_x,k_y)=\int\mathrm dx\,\mathrm dy \, e^{i(k_xx+k_y y)}f(x,y).$$
The output is, just like $f(x,y)$, a two dimensional function. So the output is again an image! This image will generally be complex so to show this image often the absolute value is taken of the output. Also the log is often taken to bring out details with low intensity. It looks like this happened for your images as well but I'm not sure.
For implemnting this on images you can have a look at the discrete Fourier transform. Note that depending on the implementation the $(0,0)$ might end up either in the corners or in the center of your image. If you want to use the discrete Fourier transform a lot you should always use a library/predefined function because there exists an algorithm to compute the discrete Fourier transform called the Fast Fourier Transform which, like the name implies, is much faster.


text:
Q: Locking a table using VBA macro I have made a table which auto fills using a user form. Currently, you can add new rows and edit the text within the table. I want to be able to lock the table so that you cannot edit the table at all unless you enter it through the user form. I tried the code:
Private Sub Lock_Table()
    Dim NewArea As Table
    Set NewArea = ActiveDocument.Tables(1)
    NewArea.Locked = True
End Sub

But that came back with the error "method or data member not found"
any help would be appreciated
Thanks!

A: The following code will insert a table inside a new Rich Text Content Control.
Selection.Range.ContentControls.Add (wdContentControlRichText)
ActiveDocument.Tables.Add Range:=Selection.Range, NumRows:=2, NumColumns:= _
    2, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:= _
    wdAutoFitFixed

That is from a recorded macro and certainly could be improved to not use the selection object. It gives a 2x2 table inside a rich text content control.
The following locks the first content control in a document.
ActiveDocument.ContentControls(1).Range _
    .LockContents = True

That cannot be edited. Obviously, you would change this to False before editing in your userform.


text:
Q: "intend that ..." vs "intend for"
*

*I intended that the sentence means "Meaning Of The Sentence Comes Here".

*I intended for the sentence to mean "Meaning Of The Sentence Comes Here".

Are above sentences correct and natural?
What I want to mean by the above sentences is:

*

*The previous sentence I said/wrote is intended to mean "Meaning Of The Sentence Comes Here".

A: I'd say

*

*" I intended the sentence to mean "Meaning Of The Sentence Comes Here" omitting "for"".

That would be also OK to say

*

*"I intended to mean "Meaning Of The Sentence Comes Here" by the sentence I just wrote. "


text:
Q: Plugin base URL In a question that is related to, but not the same as, How to link to images in my plugin regardless of the plugin folder's name

*

*plugin-folder/plugin-main-file.php

*plugin-folder/images/ containing all images

*plugin-folder/classes/ containing class definitions

*plugin-folder/classes/class1-files containing additional files for class 1

*plugin-folder/classes/class2-files containing additional files for class 2

*etc

To access images, I can use relative addressing, such as plugins_url( '../images/image.png', dirname( __FILE__ ) ) but this requires a knowledge of the file structure, and a level of hard-coding that leads to potential maintenance issues.
Alternatively, I can define a global constant (eg) define('PLUGIN_ROOT', basename(dirname(__FILE__)) . '/' . basename(__FILE__)); in my main-file.
Ideally, there is a Wordpress function that would give me the plugin base name, from anywhere in my plugin (ie always return /plugin-folder/)... but I haven't found one.  Is there such a beastie?
-- EDIT TO ADD --
I am also aware of plugins_url() with no parameters... but this returns http://mydomain.ext/wp-content/plugins - ie without my plugin name!

A: I think you are looking for plugin_dir_url:
$url = plugin_dir_url(__FILE__);

$imageurl = $url.'images/someimage.png';

EDIT: Sorry I misread the question... that is only an answer to the linked question. You could check the parent directory recursively until you find the right one:
function base_plugin_dir($dirpath) {
    if (substr(dirname($dir),-7) == 'plugins') {return $dirpath;}
    else {$dirpath = base_plugin_dir($dirpath);}
    return $dirpath;
}

function base_plugin_dir_url($filepath) {
    $baseplugindir = base_plugin_dir(dirname($filepath));
    $url = plugin_dir_url(trailingslashit($baseplugindir));
    return $url;
}

Then you can get the URL using that function from whatever file:
$basepluginurl = base_plugin_dir_url(__FILE__);
$imageurl = $basepluginurl.'/images/wordpress.png';

OR
Better yet just set a constant from your main plugin file to use it later:
$url = plugin_dir_url(__FILE__);
define('MY_UNIQUE_PLUGIN_URL',$url);

So as to use in say /plugin/my-plugin/class/class1.php
$imageurl = MY_UNIQUE_PLUGIN_URL.'/images/wordpress.png';

A: Sorry for the late answer, below is the function I use to retrieve the plugin directory name in the format requested by @Andrew (i.e. with a trailing slash as mentioned in the comment to Kevin)
/**
 * Retrieve the Plugin Directory
 *
 * Returns the root directory for current plugin with a trailing slash
 */
function current_plugin_dir() {
  $base = plugin_basename( __FILE__ );
  $slash = strpos($base,'/');
  $plugin_dir = $loc? substr( $base, 0, $loc + 1): $base;
  return $plugin_dir;
}

To remove the slash just leave out the '+ 1' in the $plugin_dir line.

A: Edit
My bad, in that case I can think of this.
$x = WP_PLUGIN_URL.'/'.str_replace(basename( __FILE__),"",plugin_basename(__FILE__));

It should return
http://[url-path-to-plugins]/[custom-plugin]/
But straight forward class I don't think wordpress has one

Yes it is
from https://codex.wordpress.org/Function_Reference/plugin_basename
$x = plugin_basename( __FILE__ );

A: plugin_basename may be what you want. If your plugin file is located at /wp-content/plugins/my-plugin/my-plugin.php this would return:
$file = plugin_basename( __FILE__ ); // "my-plugin/my-plugin.php"

If you called the same thing from a sub-directory in your plugin, such as /wp-content/plugins/my-plugin/inc/my-plugin-include.php it would return:
my-plugin/inc/my-plugin-include.php

If you want the current root directory for a plugin, then this custom function should do the trick:
/**
 * Current Plugin Directory
 *
 * Returns the root directory for current plugin
 */
function current_plugin_dir() {
    $basename = plugin_basename( __FILE__ );

    return str_replace( __FILE__, '', $basename );
}


text:
Q: This CSS Stuffing Works, But Is This A Good Practice? I am trying to include a dynamic css in my plugin, I have been searching anywhere but doesn't find any case that is similar to what I do. And what I use to do it is by adding a css file directly into the end of my plugin php file after the closing php tag ?> without adding any other stuffs like calling wp head etc.
Here is the example of the code I put directly into the end of my plugin's file:
<style type="text/css">

   .innertrow { background-color: <?php get_options('css_value');?>}

</style>

Is that a good practice?

A: Of course it is not a good practice, since it will be considered as plugin error by Wordpress. It will output an error message on plugin activation like this:
The plugin generated xxx characters of unexpected output during activation. If you notice "headers already sent" messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.

Where the xxx is the amount of the codes + spaces you put after the ?> tag. It is just the same as locating space/s or unaccepted codes before the first <?php tag in your main plugin and or after it.

A: You can use wp_add_inline_style() to add to a stylesheet that you've already defined, such as in your plugin. This way an options screen or other user settings can affect the final style output.
That could become very tedious, however, depending on how many changes you are giving the user the power over. However, it is the "best practice" as far as I know.

A: I believe it's possible to dynamically write a CSS file using PHP, but you'd have to find out more on it, I don't know much about it myself. I'm planning on doing it soon, as I noticed people putting a LOT of CSS in the  on a theme I was working on. It's bad practice in many ways, so best to avoid where possible. Sadly there are only 24hrs in a day...!

A: If you need to add dynamic CSS and don't have a stylesheet already added that you want to append it to, you can hook in and output it in the wp_head action hook:
<?php
function wpse_111373_output_plugin_css() {
    ?>
    <style type="text/css">
        .innertrow { background-color: <?php get_option('css_value'); ?>;}
    </style>
    <?php
}
add_action( 'wp_head', 'wpse_111373_output_plugin_css' );

Don't just add the CSS to the end of your plugin file. However, as far as this being a "best practice" I don't know. :)


text:
Q: dateTime stored in database in UTC, but when reading as C# objects it's automatically converted to Local Time, I want UTC only, how? In database I am storing the datetime in UTC,

I have class property like below,
public DateTime CollectionTimeUtc { get; set; }

Now when I am reading from database into C# object, it's automatically converted back to local time,

How to avoid this conversion ? I want it UTC. Thanks!

A: Write your own explicit getter and setter, like the old way of writing properties in C#.
private DateTime collectionTimeUtc;

public DateTime CollectionTimeUtc
{
    get { return collectionTimeUtc; }
    set { collectionTimeUtc = value.ToUniversalTime(); }
}


text:
Q: Remove dagger generated classes from Android Studio's global search? It is really irritating. I need more time to find some class because of dagger 2.

A: If you are talking about the generated MembersInjector and Factory classes:
MyClass_MembersInjector.java
MyClass_Factory.java

you can prevent these from coming up in the Ctr-N or Cmd-O dialog by adding them to the ignored files list in File / Settings / Editor / FileTypes and adding the appropriate wildcards to the Ignore files and folders edittext:

*_MembersInjector.java; *_Factory.java; will cause most of the generated classes to be ignored:
Before:

After:

You can even add Dagger*.java to the list if you don't even want to see the generated component (even though this is rather useful for the project).
Update:
If you are talking about not having the classes appear in auto-import/auto-complete this is done through Settings / Editor / General / Auto Import:

A: In Android Studio Dolphin there is a new option in Find Usages dialog, so you can ignore usages in generated code.

A: In Android Studio, go to

File -> Settings -> Editor -> File Types -> Ignored Files and Folders

and add wild cards. Enter apply.
For Hilt, you can add following flags/wildcards *_MembersInjector.java; *_Factory.java; *_Providers.java; *_Bindings.java; *_HiltComponents_*.java; *_Provide*.java

A: David Rawson's answer doesn't help to get rid of not showing _Factory classes when performing Find Usages on the class name. This is what will be shown:

This can be resolved with creating a new scope which will disregard generated files.

Here's the regex for generated files in app module: !file[app]:build/generated//*. But you may as well use "Exclude recursively" button locating the directory you want to get rid of.

Now, change the search scope to newly created:

And this will be the output:

No _Factory classes. You may as well get rid of classes in test packages, thus only classes from production package will be found.


text:
Q: General Search Query in Solr I have tried to run a single term search in Solr 9.0 through by using
q=term
(e.g. http://localhost:8983/solr/windowstest/select?indent=true&q.op=OR&q=yelp).
I've noticed that older versions of Solr were able to handle such a request but now I can only search all fields for that term by adding using OR
q=id:yelp OR subject:yelp OR body:yelp
(e.g. http://localhost:8983/solr/windowstest/select?indent=true&q.op=OR&q=id%3Ayelp%20OR%20subject%3Ayelp%20OR%20body%3Ayelp).
Is there a way to not have to indicate the fields?

A: There is no setting for "searching all fields"; however, what is usually done is to have a single field as the copyField destination for all fields. You can do this by defining a catch-all field (by default named _text_, and then configuring <copyField src="*" dest="_text_"> - making the content of all the fields get copied into _text_.
You can then set the default search field (i.e. where there isn't a field name given) with the df parameter in the query - the default field.
http://localhost:8983/solr/windowstest/selectq.op=OR&q=yelp&df=_text_

If you want to set this as the default, you configure it as a default parameter in solrconfig.xml under the specific request handler:
<requestHandler name="/select" class="solr.SearchHandler">
  <lst name="defaults">
    <str name="df">_text_</str>
    <int name="rows">10</int>
  </lst>
</requestHandler>

.. or by using initparams:
<initParams path="/update/**,/query,/select,/tvrh,/elevate,/spell">
  <lst name="defaults">
    <str name="df">_text_</str>
  </lst>
</initParams>


text:
Q: How configure a RESTful controller in Spring 3 with annotations? I am trying to create a RESTful controller using Spring 3.0. The controller is for a management API for a portal application. The operations I want to perform are:

*

*GET /api/portals to list all the portals

*POST /api/portals to create a new portal

*GET /api/portals/{id} to retrieve an existing portal

*PUT /api/portals/{id} to update an existing portal

*DELETE /api/portal/{id} to delete an existing portal

After annotating the controller as illustrated below I find the the operations to list all the portals or create a new portal do not get mapped.
So my questions are:

*

*Have I annotated the class correctly?

*Am I following the correct conventions for implementing a RESTful web service?

*Might there be something broken in Spring?

The code extract below shows how I have annotated my class:
@Controller
@RequestMapping("/api/portals")
public final class PortalAPIController
{
    private final static Logger LOGGER = LoggerFactory.getLogger(PortalAPIController.class);

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String listPortals(final Model model)
    {
         PortalAPIController.LOGGER.debug("Portal API: listPortals()");
         .
         .
         return "portals";
    }

    @RequestMapping(value = "/", method = RequestMethod.POST)
    public String createPortal(@RequestBody final MultiValueMap<String, String> portalData, final Model model)
    {
        PortalAPIController.LOGGER.debug("Portal API: createPortal()");
        .
        .
        return "portal";
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String getPortal(@PathVariable("id") final String portalId, final Model model, final HttpServletResponse response)
        throws IOException
    {
        PortalAPIController.LOGGER.debug("Portal API: getPortal()");
        .
        .
        return "portal";
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public String updatePortal(@PathVariable("id") final String portalId,
        @RequestBody final MultiValueMap<String, String> portalData, final Model model, final HttpServletResponse response)
        throws IOException
    {
        PortalAPIController.LOGGER.debug("Portal API: updatePortal()");
        .
        .
        return "portal";
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public String deletePortal(@PathVariable("id") final String portalId, final Model model, final HttpServletResponse response)
        throws IOException
    {
        PortalAPIController.LOGGER.debug("Portal API: deletePortal()");
        .
        .
        return "portal";
    }

    .
    .
}

During start-up I am seeing that Spring things it has registered the end-points:
2010-02-19 01:18:41,733 INFO [org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping] - Mapped URL path [/api/portals/] onto handler [com.btmatthews.mars.portal.web.controller.PortalAPIController@141717f]
2010-02-19 01:18:41,734 INFO [org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping] - Mapped URL path [/api/portals/{id}] onto handler [com.btmatthews.mars.portal.web.controller.PortalAPIController@141717f]
2010-02-19 01:18:41,734 INFO [org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping] - Mapped URL path [/api/portals/{id}.*] onto handler [com.btmatthews.mars.portal.web.controller.PortalAPIController@141717f]
2010-02-19 01:18:41,735 INFO [org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping] - Mapped URL path [/api/portals/{id}/] onto handler [com.btmatthews.mars.portal.web.controller.PortalAPIController@141717f]
2010-02-19 01:18:41,735 INFO [org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping] - Mapped URL path [/api/portals] onto handler [com.btmatthews.mars.portal.web.controller.PortalAPIController@141717f]
2010-02-19 01:18:41,735 INFO [org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping] - Mapped URL path [/api/portals.*] onto handler [com.btmatthews.mars.portal.web.controller.PortalAPIController@141717f]

But when I try to invoke my API using cURL
curl http://localhost:8080/com.btmatthews.minerva.portal/api/portals/

or
curl http://localhost:8080/com.btmatthews.minerva.portal/api/portals

I get the following errors:
2010-02-19 01:19:20,199 WARN [org.springframework.web.servlet.PageNotFound] - No mapping found for HTTP request with URI [/com.btmatthews.minerva.portal/api/portals] in DispatcherServlet with name 'portal'
2010-02-19 01:19:32,360 WARN [org.springframework.web.servlet.PageNotFound] - No mapping found for HTTP request with URI [/com.btmatthews.minerva.portal/api/portals/] in DispatcherServlet with name 'portal'

I get the same problem when I try to do a create:
curl -F ...... --request POST http://localhost:8080/com.btmatthtews.minerva/api/portals

But if try to operate on an existing resource (retrieve, update or delete) it works okay.
Update: The solution was provided in a comment by @axtavt. I was using <url-pattern>/api/*</url-pattern> in my web.xml servlet mapping. It needed to be changed to <url-pattern>/</url-pattern>

A: Double check the url-pattern in your web.xml and compare it to your curl argument.
Here is an example I wrote which walks you through the whole Spring MVC process.

A: The URL you post in your curl excerpt
http://localhost:8080/portal/api/portals

does not match the URL in the Spring warning
/com.btmatthews.minerva.portal/api/portals

Without knowing how your webapp is set up, what context path it's at, what the Spring context looks like, etc., it's pretty hard to diagnose but this sounds like a big clue to me.

A: You Have done few Mistakes.
@RequestMapping(value = "/", method = RequestMethod.GET)

public String listPortals(final Model model)
{
}

Over here the method must accept some parameter Model, but that's not passed.
you must write that inside method. or if u want to pass that, u must sent it as path variable or as a request Param.
@RequestMapping(value = "/{id}", method = RequestMethod.GET)

public String getPortal(@PathVariable("id")

here the correct syntax is  @PathVariable(value="id")
And if this doesn't work
then try this:
@RequestMapping(value = "/SOMETHING", method = RequestMethod.GET)

A: In Spring 3, the Rest Controller is no more than a regular controller (@Component) and the only difference is that a Rest controller returns JSON/XML instead of "Views". So I think you are doing ok with respect to annotations. However, two missing things I can't see:
1- Every method needs to have a "produce" value (for content negotiation):
   @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = "application/json")
2- You need an ObjectMapper of some type (ex: Marshaller and Unmarshaller) to be able to map objects to JSON/XML and vice-versa. Those two should be in your servlet config, instead of configuring a view resolver.
And that should be it.


text:
Q: Hibernate one to one unidirectional - ids not assigned On my unit tests I get the JpaSystemException: ids for this class must be manually assigned before calling save() error.  I have reworded my entities to make the question shorter and more readable.
So student has an optional one to one relation with the table EnrolledInfo.
Student Entity
@Entity
@Table(name = "Student")
public class Student  {

    @Id
    @Column(name = "studentId")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long studentId;

    @OneToOne(fetch = FetchType.LAZY, mappedBy = "student", cascade = CascadeType.ALL)
    private EnrolledInfo enrolledInfo;

    private String firstName;

    private String lastName;

    // setters&getters etc..
}

EnrolledInfo Entity
@Entity
@Table(name = "EnrolledInfo")
public class EnrolledInfo implements Serializable {

    @Id
    private Long studentId;

    @OneToOne(fetch = FetchType.Eager)
    @PrimaryKeyJoinColumn
    @JsonBackReference
    private Student student;

    @Column(name = "enrolledDate")
    private Date enrolledDate;

    @Column(name = "paidTuition")
    private Boolean paidTuition;

    // setters&getters etc..
}

Putting it together in a test (this errors)
Surely I dont have to save the enrolledInfo entity before I save the student one?
@Test
public void student_test() {

  Student student = new Student();
  EnrolledInfo enrolledInfo = new EnrolledInfo();
  enrolledInfo.setPaidTuition(true);

  student.setEnrolledInfo(enrolledInfo);
  studentDao.save(student);
  // errors on // JpaSystemException: ids for this class must be manually assigned before calling save():
}

A: Your EnrolledInfo has studentId as its Id, and no generation strategy cause its ids comes from the relationship as it is its parent id (the student). For that to work the student must be known during the save.
So the EnrolledInfo must know its student, jpa does not handle both sides of relationship itself, so they can be set manually.
  Student student = new Student();
  EnrolledInfo enrolledInfo = new EnrolledInfo();
  enrolledInfo.setPaidTuition(true);
  enrolledInfo.setStudent(student);

  student.setEnrolledInfo(enrolledInfo);
  studentDao.save(student);

Now in JPA2, the proper annotation would be:
@Entity
@Table(name = "EnrolledInfo")
public class EnrolledInfo implements Serializable {

    @Id
    private Long studentId;

    @OneToOne(fetch = FetchType.Eager)
    @Id
    @JsonBackReference
    private Student student;

in JPA1 with @PrimaryKeyJoinColumn you would need to provide the full mappings (you should now use the JPA2, so there is no reason for the old one but just in case):
@Entity
@Table(name = "EnrolledInfo")
public class EnrolledInfo implements Serializable {

    @Id
    @Column(name="STUDENT_ID")
    private Long studentId;

    @OneToOne(fetch = FetchType.Eager)
    @PrimaryKeyJoinColumn(name="STUDENT_ID", referencedColumnName="STUDENT_ID")
    @JsonBackReference
    private Student student;


text:
Q: Reducing Dataset Using SAS Programming I have a dataset i.e. -
Coverage_Start  Termination_Date    Member_Id
24-Jul-19       1-Jun-21            42968701
24-Jul-19       1-Mar-21            42968701
29-Feb-20       1-Mar-20            42968701
16-Feb-19       1-Mar-19            42968701
1-Mar-17        1-Mar-18            42968701
1-Mar-16        1-Mar-17            42968701
1-Dec-15        31-Dec-16           42968701

I want to reduce this dataset, suppose in last three rows minimum coverage_start- 1-Dec-15 and maximum termination_date- 1-Mar-18, so I want to combine all three bottom rows because it has continuous coverage.
As result the bottom three rows will be reduced to "1-Dec-15  1-Mar-18  42968701".
Reduced Dataset should be like -
Coverage_Start  Termination_Date    Member_Id
24-Jun-19       1-Jun-21            42968701
16-Feb-19       1-Mar-19            42968701
1-Dec-15        1-Mar-18            42968701

I want to achieve this task using SAS programming.
Can anyone please help me with this? I'm trying this since a very log time but couldn't achieve it.

A: This is how I would do it.  I do not get same answer as you for rng 2 not sure if I don't understand or you have it wrong.
proc datasets kill nolist; quit;
/*
Coverage_Start  Termination_Date    Member_Id
29-Feb-20       1-Jun-21            42968701
16-Feb-19       1-Mar-19            42968701
1-Dec-15        1-Mar-18            42968701
*/
filename FT15F001 temp;
data cover0(keep=id date) / view=cover0;
   infile FT15F001 firstobs=2;
   input (start term) (:date.) id:$10.;
   do date=start to term;
      output;
      end;
   format date date11.;
   parmcards;
Coverage_Start  Termination_Date    Member_Id
24-Jul-19       1-Jun-21            42968701
24-Jul-19       1-Mar-21            42968701
29-Feb-20       1-Mar-20            42968701
16-Feb-19       1-Mar-19            42968701
1-Mar-17        1-Mar-18            42968701
1-Mar-16        1-Mar-17            42968701
1-Dec-15        31-Dec-16           42968701
;;;;
   run;
proc sort nodupkey data=cover0 out=cover1;
   by id date;
   run;

data cover2/ view=cover2;
   set cover1;
   by id;
   dif = dif(date);
   if first.id then do;
      dif=1;
      rng = 0;
      end;
   if dif ne 1 then rng + 1;
   run;

proc summary data=cover2 nway missing;
   class id;
   class rng / descend;
   output out=reduce(drop=_type_) min(date)=Start max(date)=Term;
   run;
proc print;
   run;


text:
Q: ld cannot find udev I'm trying to compile a program but it throws the following error:
[cc] /usr/bin/ld: cannot find -ludev

I checked other topics on SO but the responses were to install something while I seem to be having libudev installed.
In /lib/x86_64-linux-gnu I also have:
lrwxrwxrwx 1 root root      16 lut 19 21:30 libudev.so.1 -> libudev.so.1.3.5
-rw-r--r-- 1 root root   67600 lut 19 21:31 libudev.so.1.3.5

I've tried linking libudev.so.0 to libudev.so.1 but it's still not working. What is ld looking for and why is it not working? How can I solve this?

A: When you use -lfoo the linker will look for a file named libfoo.a or libfoo.so.
So in your case, you need libudev.so without any suffix number.
Some Linux distributions, such as Debian and derivates (Ubuntu?), do not install these symlinks by default. So instead of creating that symlink yourself, try first looking for the *-dev package (libudev-dev).

A: ld is the command for linker,  you need to update your LIBPATH variable to include the library location.
check the value of the env variable LIBPATH and change it to LIBPATH=LIBPATH:<lib location> and compile again.


text:
Q: polymer + jquery gridster I am trying to create a polymer component out of jquery gridster. Here is my basic shell for the component.
<link rel="import" href="../bower_components/polymer/polymer.html">

<dom-module id="grid-layout">

  <template>

  </template>

</dom-module>

And I am trying to use it as

  <paper-drawer-panel force-narrow>

        <paper-menu>
                <paper-item>Item 1</paper-item>
                <paper-item>Item 2</paper-item>
            </paper-menu>

        <paper-toolbar>
          <iron-icon icon="menu" paper-drawer-toggle></iron-icon>
        </paper-toolbar>
        <grid-layout></grid-layout>

  </paper-drawer-panel>

The issue I have is the drawer panel is sliding under the jquery webcomponent instead of over it. Am I mssing any jquery+polymer gotcha ?

A: Gridster declares it's rows to be z-index: 2 and therefore above the standard stacking plane. You can defeat this with
.gridster .gs-w {
  z-index: 0;
}

but I don't know why they did that in the first place so there may be some other side-effect from changing the z-index.
http://jsbin.com/kiziho/edit?html,output