text:
Q: Giving Id to the View pager Items like buttons are not going to work I want to implement View Pager containing two pages with the data and both contain search bar, a button, and a list view, Both of the view pager needs to get data from SQLite...
When I try to give ids to the buttons and list in the Java file the application got crashes and say this is not possible here.
Here is my Main Fragment
{
ListView listViewclients;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_fragment);
    Toolbar toolbar = findViewById(R.id.toolbar);
    toolbar.setTitle("Dynamic ERPMini");
    TabLayout tabLayout = findViewById(R.id.tab_layout);

    //listViewclients=findViewById(R.id.listclient);

    tabLayout.addTab(tabLayout.newTab().setText("Clients"));
    tabLayout.addTab(tabLayout.newTab().setText("Products"));
    tabLayout.addTab(tabLayout.newTab().setText("Invoices"));

    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    final ViewPager viewPager = findViewById(R.id.pager);
    final PagerAdapter adapter = new PagersAdapter(getSupportFragmentManager(), tabLayout.getTabCount());

    viewPager.setAdapter(adapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });
}
}

Here is the clients.java
{
ListView listView;
Button btnAll;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.clients, container, false);
}

}

Here is the second slide
{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.products, container, false);
}
}

Here is the XML files of the product and client
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimary"
android:orientation="vertical">

<SearchView
    android:id="@+id/searchclient"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layoutDirection="rtl"
    android:layout_alignParentRight="true">

</SearchView>

<Button
    android:id="@+id/searchall"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/searchclient"
    android:layout_marginTop="15dp"
    android:background="@color/colorPrimaryDark"
    android:padding="10dp"
    android:text="Search All"
    android:textColor="@color/colorPrimary" />

<android.support.v7.widget.RecyclerView
    android:layout_below="@+id/searchall"
    android:id="@+id/recyclerViewclients"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Here is product xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimaryDark"
android:orientation="vertical">

<SearchView
    android:id="@+id/searchproduct"
    android:layout_width="match_parent"
    android:outlineSpotShadowColor="@color/colorPrimary"
    android:layout_height="wrap_content"
    android:layoutDirection="rtl"
    android:layout_alignParentRight="true">
</SearchView>

<Button
    android:id="@+id/searchallproducts"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/searchproduct"
    android:layout_marginTop="15dp"
    android:background="@color/colorPrimary"
    android:padding="10dp"
    android:text="Search All"
    android:textColor="@color/colorPrimary" />

<android.support.v7.widget.RecyclerView
    android:layout_below="@+id/searchallproducts"
    android:id="@+id/recyclerViewUsers"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

The Error is over Here Error Location Image
Here is Logcat
ava.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tablewithlist/com.example.tablewithlist.MainFragment}: java.lang.NullPointerException
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
    at android.app.ActivityThread.access$600(ActivityThread.java:130)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4745)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
    at com.example.tablewithlist.MainFragment.onCreate(MainFragment.java:29)
    at android.app.Activity.performCreate(Activity.java:5008)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
    at android.app.ActivityThread.access$600(ActivityThread.java:130)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4745)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    at dalvik.system.NativeStart.main(Native Method)

Here is the image after passing ids to client.java class

Here is my main fragment.xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimary"
tools:context="com.example.tablewithlist.MainFragment">
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:background="@color/colorHeaderBackground"
        android:elevation="6dp"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/toolbar"
        android:background="@color/colorHeaderBackground"
        android:elevation="6dp"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_below="@id/tab_layout"/>

A: You have to get the inflated view to initialized the button and other views.
{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view= inflater.inflate(R.layout.products, container, false);
    buttonAll= view.findViewById(R.id.button);

    buttonAll.setOnClickListener(new OnClickListener()
    {
             @Override
             public void onClick(View v)
             {
                // do something
             }
    });

    return view;
}

Initialized all the views like this in the fragment. This will fix the issue. You also can use the ButterKnife library to bind the view.
here is the link : ButterKnife
MainFragment
public class MainFragment extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_fragment);

        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setTitle("Dynamic ERPMini");

        TabLayout tabLayout = findViewById(R.id.tab_layout);

        tabLayout.addTab(tabLayout.newTab().setText("Clients"));
        tabLayout.addTab(tabLayout.newTab().setText("Products"));
        tabLayout.addTab(tabLayout.newTab().setText("Invoices"));

        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        final ViewPager viewPager = findViewById(R.id.pager);
        final PagerAdapter adapter = new PagersAdapter(getSupportFragmentManager(), tabLayout.getTabCount());

        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }
}

Clients.Java
public class Clients extends Fragment {
    ListView listView;
    Button btnAll;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.clients, container, false);
        btnAll=view.findViewById(R.id.searchall);
        listView=view.findViewById(R.id.Viewclients);

        btnAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity(), "Usman", Toast.LENGTH_SHORT).show();
            }
        });

        return view;
    }

}


text:
Q: My Nintendo has a blinking light and no video; is it fixable? Every game I try in my Nintendo Entertainment System just flashes the red power LED on and off and never sends a signal to the TV.  I've tried inserting several different games.  I've tried inserting them in all the way or just barely enough to push down.  I've cleaned the cartridges as best as I can (mostly blowing really hard).  Can I fix this problem or should I retire the trusty old friend?

A: This is due to a poor connection between the cartridge's contacts and the pin connectors. There are a few fixes for the problem:

*

*Use rubbing alcohol with a cotton swab on the cartridge's contacts.

*Try turning on the system without pushing the cart down into the NES. Just insert the cart so it connects into the slot, but leave the door open and don't push it downwards.

*Lastly, you can replace your pin connector. It requires opening the system up, but it is a relatively painless process, and you can get replacement 72 pin connectors dirt cheap on ebay. There is a good tutorial for it here: http://www.jandar.net/nes72pin/

A: The trick I always used was to fully insert the cartridge, then try to power up. If you get the blinking, turn the power back off, pull the cartridge out slighty (1/8 inch or less), then try powering up again.
Repeat this process until the game works, or until you're frustrated enough to go buy a Rumblepad 2 and download FCEUX.

A: If you're not able to repair it and don't want to go the emulator route, you can buy new Nintendo-compatible hardware such as the FC Super Loader or this one from ThinkGeek.  The FC in particular takes NES controllers as well as games; a couple of my family members have it and have been happy with it.

A: It could be that the console itself is dusty.
Try blowing into the cartridge slot, maybe that will help.
Or you could open it up and clean it, but if you do, be careful so you don't damage anything inside it.

A: It is likely a bad connection between the cartridge's edge connector and the slot connector inside the console. Start by using a cotton swab with a bit of rubbing alcohol to wipe off any patina that has accrued on the edge connector of the cartridge. If that doesn't help, try doing the same thing with the console's connector (if it's not a top-loading console, you'll need an extra long swab).
Standard pencil erasers are usually great for wiping off patinas from electronic connectors, but they are extremely hard to use on the connectors involved here (they are better for things like computer RAM).
If all else fails, I have had some success by using an emery board (one of the cheap cardboard nail files that come in packs of a dozen) to scrape off the patina from the connector of the console.
HTH

A: Another option (though it takes some skill) is to disable the NES10 lockout chip, as that is the component that actually causes this problem.
See https://en.wikipedia.org/wiki/Nintendo_Entertainment_System#Lockout (3rd paragraph) and
And

A: Try to press the reset button multiple times fairly quickly while the light is flashing and see if you can get the light to stay on / a picture on your TV.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Redirect bookmarked URLS via IIS Rewrite Module is not working properly even though URL pattern matches in testing I've read so many forums and I did possibly whatever I could. My outbound rule to works in terms of rewriting the URL for SEO purposes but my Redict URL which in case the changed URLs marked in our users' bookmarks does not work.
I am using IIS 10.0.
The URL that needs changing:
http://agmodel.com/files/content/insights/publishing/e_clouds.pdf
To:
http://agmodel.com/assets/content/insights/publishing/e_clouds.pdf
So only thing I am changing is the string "files" to "assets".
Here is what I've tried:
Attempt 1:
<rule name="Redirect" stopProcessing="true">
   <match url="(https?:\/\/[^\/]+)\/" />
   <conditions trackAllCaptures="true">
      <add input="{QUERY_STRING}" pattern="(https?:\/\/[^\/]+)\/files\/(.*)" />
      <add input="{REQUEST_URI}" pattern="^/assets" negate="true" />
   </conditions>
   <action type="Redirect" url="{R:1}/assets/{C:2}" appendQueryString="false" redirectType="Found" />
</rule>

I tried to make sure that the first pattern is always the domain the second pattern is files.
Attempt 2:
<rule name="assets-to-files" stopProcessing="true">
   <match url="(https?:\/\/[^\/]+)\/files\/(.*)" />
   <action type="Redirect" url="{R:1}/assets/{C:1}" appendQueryString="false" logRewrittenUrl="true" />
   <conditions>
      <add input="{QUERY_STRING}" pattern="\/files\/(.*)" />
   </conditions>
</rule>

So whenever I test whether the bookmarked old URL will change to the new one, it does not work. It gets green light during pattern match testing in IIS 10.
What am I doing wrong here?

A: You may use a very simple rule here:
<rule name="assets-to-files">
  <match url="^files/(.*)" />
  <action type="Rewrite" url="assets/{R:1}" />
</rule>

The URL you want to match is http://agmodel.com/files/content/insights/publishing/e_clouds.pdf. The url attribute in match node will receive files/content/insights/publishing/e_clouds.pdf as input, so you want
 ^files/(.*)

It will match files/ at the start of the string and then will capture into {R:1} any 0 or more chars other than newline.
In the action node url attribute, all you need  is to specify the  assets/ new path and append what you captured into {R:1}.


text:
Q: How to filter Pandas Unique Result by only Non-Numeric Values? Context
I have a Pandas Series and am calling the .unique() Method to get all unique Values. I now would like to filter this result to only see unique Values that are Non-Numeric. However, I get the following Error:

Error: AttributeError: 'float' object has no attribute 'isnumeric'

Code
values = data['Column Name'].unique()
non_numeric_values = [value for value in values if not value.isnumeric()] # Error

Question

*

*How can I achieve my goal of being able to select only those Values, that are Non-Numeric?

*Please note, that the Column may has an Object dtype and the Values may be of type String.

A: You can use the built-in isinstance:
from numbers import Number
import pandas as pd

elements = ["99.99", 1.0, "foo", 2, "bar", 3.0, "baz", 4, "qux"]
df = pd.DataFrame(elements, columns=["column name"])

uniques = df["column name"].unique()

types = [type(x) for x in uniques]
print(types)  # [str, float, str, int, str, float, str, int, str]

uniques_non_numeric = [x for x in uniques if not isinstance(x, Number)]
print(uniques_non_numeric)  # ['99.99', 'foo', 'bar', 'baz', 'qux']

or switching the list-comprehension with pandas apply:
non_num_rows = df["column name"].apply(lambda x: not isinstance(x, Number))
non_num_uniques = df[non_num_rows]["column name"].unique()
print(non_num_uniques)  # ['99.99' 'foo' 'bar' 'baz' 'qux']

A: Lets try:

data[data['Column Name'].str.isnumeric()].unique()

If you have mixed types, coerce it to str and then query
data[data['Column Name'].astype(str).str.isnumeric()]

A: The below solution could help where we try to convert to float if it converts then we skip and rest all we add to array
output = []
for x in actors['actor'].unique():
    try:
        float(str(x).strip())
    except:
        output.append(x)

A: import pandas as pd
import numpy as np

data = np.array(['a', 'e', 'i', 'o', 'u',1.2,3.5,1,5])
df = pd.DataFrame(data, columns=['col1'])

values = df['col1'].unique()

def isfloat(num):
    try:
        float(num)
        return True
    except ValueError:
        return False

list1 = []
for item in values:
    if not (item.isdigit() or isfloat(item)):
        list1.append(item)

print(list1)


text:
Q: Android: How to recreate Action bar when fragment changed I have an activity showing a few fragments.
Activity view contains only ViewPager initialized with custom FragmentPagerAdapter.
This adapter provide navigation among 3 fragments.
All seems to work fine except Action bar.
I override onCreateOptionsMenu() method in my fragments to create individual Action bar for any fragment:

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
    {
        super.onCreateOptionsMenu(menu, inflater);
        menu.clear();

        //fragment specific menu creation
    }

When I do swipe, new fragment appears, but Action bar stay the same for a few seconds. Probably after a few seconds this method are called and Action bar get changed.
This looks pretty bad when action bar are changed in a while after swipe is finished.
How can I recreate action bar immediately, before swipe begin?

A: It can be done by implementing onCreateOptionsMenu and calling setHasOptionsMenu(true) in the onAttach callback in each fragment and change the actions accordingly.
To show the fragment without any actions setHasOptionsMenu(false) in it

A: You can ask android to re-create the actionbar before it automatically does by calling invalidateOptionsMenu();
Do this somewhere close to the point where you change fragments to try and decrease the 'lag' between the fragment and actionbar changing.
Edit
a complete solution may look like this:
class activity extends Activity{

private void switchFragment(){

...do fragment changing stuff

activity.invalidateOptionsMenu();

}

}

class someFragment extends Fragment{

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
    super.onCreateOptionsMenu(menu, inflater);
    menu.clear();

    //fragment specific menu creation
}

}

whichever fragment is open during the
activity.invalidateOptionsMenu();

will then call its
 onCreateOptionsMenu

and you can do fragment specific menu creation in there

A: If you are using ActionBar tabs, You would like to see this answer:
How can I change Action Bar actions dynamically?

A: Finally I couldn't find any sound way to achieve this.
The best would be to make actionbar a part of fragment, not activity, but it's impossible.
I end up with clearing actionbar menu and title when swipe begins(you can set special listener in PageView) and setting menu and title again when swipe complete and new fragment are shown.
In gives some time lag and actionbar looks strangely empty during swipe, but it's best you can do.
Android API is c...


text:
Q: Persian characters are displayed as some Squares in Netbeans I use Scanner class for taking a string from user, the user must type something in Persian but when I print the string, it displays each Persian character as a square.
Also, I have set ٍEncoding of the project to UTF-8 (properties/source/Encoding---> UTF-8).
Can someone help me, please?
Bets,


text:
Q: tmux - Environment variables don't show up in session I'm trying to move from screen to tmux (to eventually using tmux from within byobu). However, I have a severe problem with environment variables not being applied, especially PS1. None of them get copied to the session (or window) environments. I found this thread that seemed relevant:
How do I start tmux with my current environment?
However, I actually can see all my right variables when I do
:show-environment -g

But none of them get carried over to the session environment, so I don't see anything when I do
:show-environment

I do have the right update-environment statement in my ~/.tmuxrc file:
# start a non-login shell by default for each new window
set -g default-command 'bash'

# Prefix is C-a like in screen
unbind C-b
set -g prefix C-a

# Carry over the PS1
set-option -ga update-environment "PS1"

Frankly this all seems like a mess to me. I can see the benefit of starting from a clean session for each screen, but for the most part this seems like a pain. I export the variable I intend to use in sub-processes, such as as the Python virtualenvwrapper functions, and expect them to be available.
Is there a way to disable this behavior? If not, what should I try to carry over my PS1 variable to tmux?
EDIT 11/13/2013
I realized that removing the first line (default-command bash) does carry over all of the environment variables. However, I really don't want each new screen of tmux to launch as a login shell. For instance, I specifically declared my PS1 variable in a login shell, so that it wouldn't be overwritten whenever I open a new screen.
Based on the following post, every new screen in tmux should launch as a non-login shell:
https://superuser.com/questions/614277/profile-and-bash-profile-ignored-when-starting-tmux-from-bashrc
Why is this not happening by default for me?

A: Tmux cannot update running processes (e.g. bash), it can only update its own environment. If you were to start a new window/pane it would pick up the new environment. My suggestion would be to use a utility function like this:
#!/bin/bash

tmup ()
{
    echo -n "Updating to latest tmux environment...";
    export IFS=",";
    for line in $(tmux showenv -t $(tmux display -p "#S") | tr "\n" ",");
    do
        if [[ $line == -* ]]; then
            unset $(echo $line | cut -c2-);
        else
            export $line;
        fi;
    done;
    unset IFS;
    echo "Done"
}

This goes through all the updated environment that tmux has learned about and updates your shell.


text:
Q: SolrNet commit error with waitFlush First of all, ich have tried som published solutions like this:

*

*SolrNet: SolrConnectionException (400) bad request when attempting to Add and Commit

*https://code.google.com/p/solrnet/issues/detail?id=172

*and so one

I have no access to the Build Server, seams to be down. So i work with the fIles that i get.
First i have testet the Nuget Package version. (Oldes one) I get the errors.
After that i load the current version from the guthub repo version 0.4.0.2002
I always get the excaption with the 400 Bad Request and the waitFlush error.

My Code looks like that:
public void SolrInitialSetup()
    {
        if (doorValue)
        {
            try
            {
                Startup.Init<Document>("http://localhost:8080/solr");
                System.Diagnostics.Debug.WriteLine("Solr Connection successfull!");
                doorValue = false;
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Solr Connection failed with error: " + e);
            }

        }
        else
        {
            System.Diagnostics.Debug.WriteLine("Solr Connection already exist!");
        }

        var solr = ServiceLocator.Current.GetInstance<ISolrOperations<Document>>();
        var docList = sampledocsDb.Docs.ToList();
        foreach (var doc in docList)
        {
            var d = new Document()
            {
                Id = doc.FieldId,
                Title = doc.FieldTitle,
                Content = doc.FieldContent
            };
            solr.Add(d);
            solr.Commit();
        }

    }

A: OK. Strange. The Build Server is now online. Perhaps down yesterday. Now with that Build it works fine.
Problem is that it is the same version number, but it is an other version. When a new Version is published, they should increment the Build Version Number.


text:
Q: how to vertically sum a range of dynamic variables in sas? I have a dataset in SAS in which the months would be dynamically updated each month. I need to calculate the sum vertically each month and paste the sum below, as shown in the image.
Proc means/ proc summary and proc print are not doing the trick for me.
I was given the following code before:
`%let month = month name;
%put &month.;

data new_totals;
set Final_&month. end=end;
&month._sum + &month._final;
/*feb_sum + &month._final;*/
output;
if end then do;
measure = 'Total';
&month._final = &month._sum;
/*Feb_final = feb_sum;*/
output;
end;
drop &month._sum;
run; `

The problem is this has all the months hardcoded, which i don't want. I am not too familiar with loops or arrays, so need a solution for this, please.
enter image description here

A: It may be better to use a reporting procedure such as PRINT or REPORT to produce the desired output.
data have;
  length group $20;
  do group = 'A', 'B', 'C';
    array month_totals jan2020 jan2019 feb2020 feb2019 mar2019 apr2019 may2019 jun2019 jul2019 aug2019 sep2019 oct2019 oct2019 nov2019 dec2019;
    do over month_totals;
      month_totals  = 10 + floor(rand('uniform', 60));
    end;
    output;
  end;
run;

ods excel file='data_with_total_row.xlsx';

proc print noobs data=have;
  var group ;
  sum jan2020--dec2019;
run;

proc report data=have;
  columns group jan2020--dec2019;
  define group / width=20;
  rbreak after / summarize;
  compute after;
    group = 'Total';
  endcomp;
run;

ods excel close;

Data structure
The data sets you are working with are 'difficult' because the date aspect of the data is actually in the metadata, i.e. the column name.  An even better approach, in SAS, is too have a categorical data with columns

*

*group (categorical role)

*month (categorical role)

*total (continuous role)

Such data can be easily filtered with a where clause, and reporting procedures such as REPORT and TABULATE can use the month variable in a class statement.
Example:
data have;
  length group $20;
  do group = 'A', 'B', 'C';
    do _n_ = 0 by 1 until (month >= '01feb2020'd);
      month = intnx('month', '01jan2018'd, _n_);
      total = 10 + floor(rand('uniform', 60));
      output;
    end;
  end;
  format month monyy5.;
run;

proc tabulate data=have;
  class group month;
  var total;
  table
    group all='Total'
    ,
    month='' * total='' * sum=''*f=comma9.
  ;
  where intck('month', month, '01feb2020'd) between 0 and 13;
run;

proc report data=have;
  column group (month,total);
  define group / group;
  define month / '' across order=data ;
  define total / '' ;

  where intck('month', month, '01feb2020'd) between 0 and 13;
run;

A: Here is a basic way. Borrowed sample data from Richard.
data have;
  length group $20;
  do group = 'A', 'B';
    array months jan2020 jan2019 feb2020 feb2019 mar2019 apr2019 may2019 jun2019 jul2019 aug2019 sep2019 oct2019 oct2019 nov2019 dec2019;
    do over months;
      months  = 10 + floor(rand('uniform', 60, 1));
    end;
    output;
  end;
run;

proc summary data=have;
    var _numeric_;
    output out=temp(drop=_:) sum=;
run;

data want;
    set have temp (in=t);
    if t then group='Total';
run;


text:
Q: neighborhood of elements in a matrix I am trying to check whether the difference between elements of the neighborhood of an element in a matrix are greater than some tolerance value and if they are, then give the value of 1 at the same index of the element in the neighborhood in a new matrix. Somehow I always end up with all ones in the new matrix, which is wrong. This is my code. Also, I get the matrix by converting a picture to a matrix.
from PIL import Image
import numpy as np
from numpy.lib.stride_tricks import as_strided

imo = Image.open("/home/gauss/Pictures/images.jpg")

matrix_pic = np.array(imo.convert('L')).astype(float)
dim = matrix_pic.shape

# start 1 step out of the outer borders of the matrix

def binary_edges(pic_mat , tolerance):
    dim = pic_mat.shape
    binary_mat = np.zeros((dim[0],dim[1]))
    for i in range(1  , dim[0]-1):
        for j in range(1  ,dim[1]-1):
            center = pic_mat[i,j]
            if (abs(pic_mat[i+1,j] - center ) > tolerance):
                binary_mat[i+1,j] = 1
            if (abs(pic_mat[i,j+1] - center ) > tolerance):
                binary_mat[i,j+1] = 1
            if (abs(pic_mat[i+1,j+1] - center ) > tolerance):
                binary_mat[i+1,j+1] = 1
            if (abs(pic_mat[i-1,j] - center ) > tolerance):
                binary_mat[i-1,j] = 1
            if (abs(pic_mat[i,j-1] - center ) > tolerance):
                binary_mat[i,j-1] = 1
            if (abs(pic_mat[i-1,j-1] - center ) > tolerance):
                binary_mat[i-1,j-1] = 1
    return binary_mat

myarray = binary_edges(matrix_pic, 60)
im = Image.fromarray(myarray)
im.show()

A: Edit: Not sure how I missed that this was posted many years ago, oh well, I'll leave this answer for the sake of those who follow.
Based on the comments it looks as though you may have solved one of your issues, however it seems to me that your function binary_edges is incorrect for your intended purpose in another way.
def binary_edges(pic_mat , tolerance):
    dim = pic_mat.shape
    binary_mat = np.zeros((dim[0],dim[1]))
    for i in range(1  , dim[0]-1):
        for j in range(1  ,dim[1]-1):
            center = pic_mat[i,j]
            if (abs(pic_mat[i+1,j] - center ) > tolerance):
                binary_mat[i+1,j] = 1
            if (abs(pic_mat[i,j+1] - center ) > tolerance):
                binary_mat[i,j+1] = 1
            if (abs(pic_mat[i+1,j+1] - center ) > tolerance):
                binary_mat[i+1,j+1] = 1
            if (abs(pic_mat[i-1,j] - center ) > tolerance):
                binary_mat[i-1,j] = 1
            if (abs(pic_mat[i,j-1] - center ) > tolerance):
                binary_mat[i,j-1] = 1
            if (abs(pic_mat[i-1,j-1] - center ) > tolerance):
                binary_mat[i-1,j-1] = 1
            #If I understand your intention correctly, then I think you're missing these two lines (notice that each element should have 8 neighbours)
            if (abs(pic_mat[i+1,j-1] - center ) > tolerance):
                binary_mat[i+1,j-1] = 1
            if (abs(pic_mat[i-1,j+11] - center ) > tolerance):
                binary_mat[i-1,j+11] = 1
    return binary_mat

Might I suggest an alternative method which will be significantly faster for reasonably sized pic_mat matrices and in my opinion has less clutter.
def binary_edges_np(pic_mat, tolerance):
    dim = pic_mat.shape
    binary_mat = np.zeros((dim[0],dim[1]), dtype=bool)
    for i,j in [0,1],[1,0],[1,1],[1,-1]:
        s = pic_mat.shape
        slice1 = np.s_[max(0, 0+i):s[0]+i, max(0+j,0):s[1]+j]
        slice2 = np.s_[max(0-i,0):s[0]-i, max(0-j,0):s[1]-j]
        bool_slice = np.abs(pic_mat[slice1] - pic_mat[slice2]) > tolerance
        binary_mat[slice1] += bool_slice
        binary_mat[slice2] += bool_slice
    return binary_mat

As follows:
matrix_pic = np.random.randint(0,255, (1000,1000))
s = time.time()
a = binary_edges(matrix_pic, 60)
print("binary_edges:", time.time() - s)
s = time.time()
b = binary_edges_np(matrix_pic, 60)
print("binary_edges_np:", time.time() - s)

binary_edges: 5.694662809371948,
binary_edges_np: 0.01562666893005371
Furthermore, note that your original function has certainly boundary effects where elements within 2 rows/cols of the edges will not be marked properly as exceeding the threshold, I assume this was not intentional. The new method gives the correct values for the edges too:
print((a == b).all()) # = False
print((a[2:-2,2:-2] == b[2:-2,2:-2]).all()) # True


text:
Q: What does $x^TA$ mean intuitively? $Ax$ means apply transformation $A$ on $x$, we can look at the null space and range of A and have an understanding of what's going to happen to the vector after we apply transformation $A$.
Just wondering what the equivalent reasoning is for $x^TA$?
I am asking because in my computational optimization course we are often asked to prove properties of the quadratic form $x^TAx$ which involves computing $x^TA$. Apologies if I am missing something and this is trivial

A: $x^TA$ is a transformation $A$ on $x^T$, with column operations instead of row operations.

A: $X^T$ is defined as the transpose of $X$, so if $X$ is a vertical vector, it would become horizontal starting with the value at the top of the vector and vice versa if it's horizontal. It's mainly so that you are able to do vector-matrix multiplication and in order to do vector-matrix multiplication, the number of columns in the matrix must correspond to the number of rows in the vector.

A: Just as $Ax$ takes a linear combination of the columns of $A$ (summing $x_j$ times the $j$th column), $x^\top A$ takes a linear combination of the rows of $A$ (summing $x_i$ times the $i$th row).
Nevertheless, I think the right answer to your question about the quadratic form $x^\top Ax$ is to interpret
$$x^\top Ax = x\cdot Ax$$
as the dot product of two vectors in $\Bbb R^n$, giving you the quadratic function $\sum\limits_i x_i\sum\limits_j a_{ij}x_j = \sum\limits_{i,j}a_{ij}x_ix_j$.


text:
Q: docker-compose useradd tells me user already exists I am using Docker on Windows with the following docker file:
FROM php:7.4-fpm

ARG uid=1000
ARG user=devuser

USER root
# Install system packages
RUN apt-get update && apt-get install -y apt-transport-https && apt-get install -y git curl zip unzip libicu-dev

# Cleanup apt
RUN apt-get clean && rm -rf /var/lib/apt/lists/*

# Install php extensions
RUN docker-php-ext-install pdo_mysql intl iconv

RUN useradd -G www-data,root -u $uid -d /home/$user $user

RUN mkdir -p /home/$user/.composer && chown -R $user:$user /home/$user

# Install composer
COPY --from=composer:latest /usr/bin/composer /usr/local/bin/composer

# Copy project files to image
COPY . /var/www

# Set working directory
WORKDIR /var/www

RUN composer install

# Change user
USER $user

docker-compose.yaml
version: "3.7"

services:

  app:
    container_name: app
    build:
      context: ./
      dockerfile: Dockerfile
    image: php:7.4-fpm
    ports:
      - 9000:9000
    working_dir: /var/www/
    volumes:
      - ./:/var/www
    networks:
      - dev
    depends_on:
      - database

  server:
    container_name: server
    image: nginx:1.21.0-alpine
    ports:
      - 8000:80
    volumes:
      - ./:/var/www
      - ./docker/nginx:/etc/nginx/conf.d
    networks:
      - dev

  database:
    container_name: database
    image: mariadb:10-bionic
    environment:
      MYSQL_ROOT_PASSWORD: root
    networks:
      - dev
    volumes:
      - database-data:/var/lib/mysql

volumes:
  database-data:
networks:
  dev:
    external: true

It worked on the first run but when I wanted to make changes I get the below error. I have already tried stopping, killing, downing all containers but nothing works.
When I run docker-compose up --force-recreate --build -d I get the following output:
 => ERROR [stage-0  5/10] RUN useradd -G www-data,root -u 1000 -d /home/devuser devuser                                                                                0.4s
------
 > [stage-0  5/10] RUN useradd -G www-data,root -u 1000 -d /home/devuser devuser:
#8 0.354 useradd: user 'devuser' already exists
------
executor failed running [/bin/sh -c useradd -G www-data,root -u $uid -d /home/$user $user]: exit code: 9
ERROR: Service 'app' failed to build : Build failed

Why does this happen?
Arent containers encapsulated? How does it conflict when setting up a new environment?
I have stoped all running containers
EDIT:
When I change uid and user to, for example, 1001 and devuser1 it works again once.

A: You've named the image you are building the same as your base image:
image: php:7.4-fpm

That means every time you run a build you add more layers and mutate from the last build rather than recreating from the original base image.
The fix is to name your image something unique to you, rather than stepping on the upstream library image name.
image: <your_hub_user>/app:latest

And then pull the upstream library image again to revert it to a known clean state:
docker pull php:7.4-fpm


text:
Q: Label in the middle of linestring in OpenLayers Is there anyone can put label in the middle of the linestring dynamically? I've used labelAlign option. I've changed this value from bc, cc, cm, etc. But it doesn't work at all. There's also option for x offset and y offset. But I don't know how to calculate the right position so the label can show at the middle of linestring. Not at the first line string.
Do you have any idea how to do it?
Thanks,

A: Check out this answer here may help you if u glance at the code.
i hope it helps you...

A: It's poccinle to calculate position manually;

*

*Define function which will calculate deltaX and deltaY:

..
this.labelDeltaPixels = function (f) {
    var vert = f.geometry.getVertices();
    var startPoint = vert[0];
    var middlePoint = vert[Math.floor(vert.length/2)];
    var pixelStart = self.mapPanel.map.getPixelFromLonLat(new      OpenLayers.LonLat(startPoint.x, startPoint.y));
    var pixelMiddle = self.mapPanel.map.getPixelFromLonLat(new OpenLayers.LonLat(middlePoint.x, middlePoint.y));
    var deltaX = pixelMiddle.x - pixelStart.x;
    var deltaY = pixelStart.y - pixelMiddle.y;
    return {x: deltaX, y: deltaY};
}

2.define context for template
var context = {
          getLableOffsetX: function(f) {
            var zoom = self.mapPanel.map.getZoom();
            if (zoom < self.centreLabelsZoom) {
                return 0;
            }

            if (f.geometry) {
                if (!self.centrelineMiddleCoordsMap[zoom]) {
                    self.centrelineMiddleCoordsMap[zoom] = {};
                }
                if (!self.centrelineMiddleCoordsMap[zoom][f.id]) {
                    self.centrelineMiddleCoordsMap[zoom][f.id] =     self.labelDeltaPixels(f);
                }
                return self.centrelineMiddleCoordsMap[zoom][f.id].x;
                    return 0;
            } else {
                return 0;
            }
        },
        getLableOffsetY: function (){//similar as for x}

}

*

*define template.
var template = {strokeColor:"${getColor}", label: "${getLabel}", cursor: "crosshair",     fontSize: '11px', labelAlign: 'cm', labelXOffset: '${getLableOffsetX}', labelYOffset:  '${getLableOffsetY}'};

*define style and stylemap
var style = new OpenLayers.Style(template, {context: context, title: 'default'});
    var styleSelect = new OpenLayers.Style({'strokeColor':  self.colors['centreline'].selectColor});

A: Although it's quite old question, this solution may help other looking for similar problem.
To display the line label at center of line, you need to create another point feature at the centroid of the lineFeature. The code for this is as follows
var VectorLayer = new OpenLayers.Layer.Vector("LineVector",{displayInLayerSwitcher: false,renderers: ["Canvas", "SVG", "VML"]});
//Create line geometry
var lineString = new OpenLayers.Geometry.LineString([source,target]);
//create line feature
var lineFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Collection([lineString]));
        lineFeature.style = {
                strokeColor: '#ff0000',
                  strokeOpacity: 0.7,
                  strokeWidth: 2
            };//after this create label feature i.e. point feature
        var lableFeature = new OpenLayers.Feature.Vector(lineString.getCentroid(true));/*Important pass true parameter otherwise it will return start point as centroid*/

        var length = Math.round(lineString.getLength());
        lableFeature.style = {
                fontFamily: "arial, monospace",
                fontWeight: "bold",
                fontColor: "red",
                label : length +"m",
                labelAlign: "tr"//set to top right
        };
        VectorLayer.addFeatures([lineFeature,lableFeature]);
        VectorLayer.redraw();
        map.addLayers([VectorLayer]);


text:
Q: Replace part of URL using .htaccess I have a case like this :

*

*http://example.com/

*http://example.com/test/

*http://example.com/auth/

*http://example.com/auth/login

*http://example.com/auth/forget_password
I need to change example.com into my IP (1.1.10.7) when user accessing path that containing auth.
The results I need are:

*

*http://example.com/ => http://example.com/

*http://example.com/test/ =>  http://example.com/test/

*http://example.com/auth/ => http://1.1.10.7/auth/

*http://example.com/auth/login => http://1.1.10.7/auth/login

*http://example.com/auth/forget_password => http://1.1.10.7/auth/forget_password
I tried several times from reading on another StackOverflow question, but still not resolved.
Can anyone help?

A: You can use this rule in your site root .htaccess:
RewriteEngine On

RewriteCond %{HTTP_HOST} !=1.1.10.7
RewriteRule ^auth/ http://1.1.10.7%{REQUEST_URI} [L,NC,NE,R=301]


text:
Q: Get current parameter in route - Angular 4 I'd like to just receive the current parameter in the Angular router whenever it changes.
Per another SO post, my component will not auto-refresh if the router navigates to another param within the same component, but I'm having trouble getting the parameter when the route is activated (so I can update the view).
The Angular docs have something like this:
  ngOnInit() {
    this.hero$ = this.route.paramMap
      .switchMap((params: ParamMap) =>
        this.service.getHero(params.get('id')));
  }

However, this isn't working for me, or at least, it would be nice to have something that isn't abstracted into other methods or services.
Is there a simple straightforward way to subscribe to the current parameter?

A: The simplest way with the new paramMap:
import { ActivatedRoute } from '@angular/router';
...
constructor(private activeRoute: ActivatedRoute) {
       this.subscription = this.activeRoute.paramMap
        .subscribe(params => {
            if(params.get('id') !== this.myParam) {
                this.myParam= params.get('id');
                //Do things with new parameter - e.g. reload data
            }
        });
}

You can additionally use the params.getAll or params.keys to get information about what parameters are available.
If the ActivatedRoute is not populating any params, you can troubleshoot by subscribing to all router events & seeing where your params are going:
this.routeChangeDetection = this.router.events.subscribe((event) => {
    console.log(this.activeRoute);
    console.log(this.activeRoute.snapshot);
    console.log(this.activeRoute.snapshot.params);
    console.log(this.activeRoute.snapshot.children);
})

This may be useful if your params are getting loaded into a child/related component but not the component looking for the parameter change.


text:
Q: DependencyProperty.Register() or .RegisterAttached() What's the difference between the two, when should RegisterAttached() be used instead of .Register()?

A: I assume you meant DependencyProperty.Register and DependencyProperty.RegisterAttached.
DependencyProperty.Register is used to register normal DependencyProperty. You can see those as just regular properties, with the added twist that they can take part in WPF's DataBinding, animations etc.
In fact, they are exposed as normal property (with the get and set accessors) on top of the untyped DependencyObject.SetValue / GetValue.
You declare those as part of your type.
Attached properties on the other hand are different. They are meant as an extensibility system. If you have ever used Extenders in Windows Forms, they are kind of similar.
You declare them as part of a type, to be used on another type.
They are used a lot for layout-related information. For example, Canvas needs Left/Top coordinates, Grid needs a Row and a Column, DockPanel needs a Dock information etc. It would be a mess if all of this had to be declared on every Control that can be layouted. So they are declared on the corresponding panel, but used on any Control.
You can use the same thing to attach any information to a DependencyObject if you need to. It can come in handy to just declare a piece of information that you can set in xaml just to be used later in a style for an existing class for example.
So those two kind of DependencyProperty serve a very different purpose. Regular properties (registered through Register() ) are used just like normal properties as part of the interface of your type. Attached properties (registered through RegisterAttached() ) are used as an extensibility point on existing classes.
Hope that clarifies it a bit.

A: A property registered with either Register or RegisterAttached can be attached to any DependencyObject with SetValue and GetValue. But if you attach a property registered with Register to an object of type other than the ownerType, its metadata will not be used (except for a default value). It means that attributes such as Inherits or AffectsMeasure will not work for these properties. You should use RegisterAttached if you are interested in metadata on attached properties.
For details, see my answer to a similar question: Difference between Attached and non-Attached Dependency Properties in Silverlight

A: The difference between DependencyProperty.Register() and DependencyProperty.RegisterAttached() is that .Register() is used to register a 'regular' dependency property on a DependencyObject, while .RegisterAttached() is used to set an 'attached' dependency property.
The difference between the two types of dependency properties is reasonably straightforward: regular dependency properties are set on a particular DependencyObject just like you would any other .NET property.  Attached properties, on the other hand, are associated with a particular DependencyObject (e.g. Grid) but are set on a completely separate DependencyObject, often a child of the DependencyObject that defines the attached property (e.g. Grid.Row, an attached property, is set on the children of a parent Grid).
More details on attached properties are on MSDN.

A: In my case RegisterAttached only set the bound field once, while Register worked dynamically as intended.
Taken from a scenario, where a Button in a List needed to show a preview on MouseHover and CommandParam was taken, already.
public static DependencyProperty MouseCommandParamProperty = DependencyProperty.Register(
                                                                        "MouseCommandParam",
                                                                        typeof(object),
                                                                        typeof(MouseBehaviour),
                                                                        new PropertyMetadata(defaultValue:null, new PropertyChangedCallback(MouseCommandParamChanged)));
        public static void SetMouseCommandParam(DependencyObject target, object value)
        {
            target.SetValue(MouseBehaviour.MouseCommandParamProperty, value);
        }
        public static object GetMouseCommandParam(DependencyObject target)
        {
            return (object)target.GetValue(MouseBehaviour.MouseCommandParamProperty);
        }
        private static void MouseCommandParamChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
        {
            UIElement element = target as UIElement;
            if (element != null)
            {
                element.SetValue(MouseBehaviour.MouseCommandParamProperty, e.NewValue);
            }
        }


text:
Q: Faithful traces on quasi-diagonal C*-algebras Recall that a separable C*-algebra $A$ is quasi-diagonal if there are completely positive and contractive maps $\varphi_k \colon A \rightarrow M_{n(k)}$ such that $||\varphi_k(ab) - \varphi_k(a)\varphi_k(b)|| \rightarrow 0$ and $||\varphi_k(a)|| \rightarrow ||a||$ for every $a, b \in A$, where $M_{n(k)}$ denotes the algebra of $n(k) \times n(k)$ complex matrices.
The following ought to be known to experts, but I've had some issues trying to prove it.
Question: Let $A$ be a quasi-diagonal separable C*-algebra. Does $A$ admit a faithful trace?
Observe we do not assume that $A$ is simple. The idea would be to use an ultralimit of the cp maps $\varphi_k \colon A \rightarrow M_{n(k)}$ composed with the usual traces $tr_{n(k)} \colon M_{n(k)} \rightarrow \mathbb{C}$. This does not necessarily yield a faithful trace, though, as the traces $tr_{n(k)}(\varphi_k(a^*a))$ might be very small while $||\varphi_k(a^*a)||$ remains large.  However, one could in some cases tweak $\varphi_k$ by adding a factor that enlarges the trace, maintains the asymptotic multiplicativity and the norm. The actual proof requires to do this everywhere at once, that is, for every possible element $a^*a$, and this seems impossible (or unreasonably hard).
Note, moreover, that there is no obvious K-theoretic obstruction, as every countable abelian group $K_0(A)$ embeds into $\mathbb{R}$.
Any help is greatly appreciated.

A: No, separable (unital) quasi-diagonal $C^\ast$-algebras do not necessarily admit a faithful tracial state. For instance, the $C^\ast$-algebra
\begin{equation}
A= \{ f\in C([0,1], \mathcal O_2) : f(0) \in \mathbb C 1_{\mathcal O_2}\}
\end{equation}
(where $\mathcal O_2$ is the Cuntz algebra with two canonical generators) is homotopic to $\mathbb C$, and hence is quasi-diagonal by the homotopy invariance of quasi-diagonality due to Voiculescu. However, any trace on $A$ vanishes on the ideal $C_0((0,1], \mathcal O_2)$, since this is purely infinite in the sense of Kirchhberg-Rørdam [Kirchberg, Eberhard; Rørdam, Mikael Non-simple purely infinite C∗-algebras. Amer. J. Math. 122 (2000), no. 3, 637–666.]. So the only tracial state on $A$ is the one factoring through evaluation at 0.
If you consider non-unital $C^\ast$-algebras, $C_0((0,1], \mathcal O_2)$ is an example of a separable quasi-diagonal $C^\ast$-algebra with no tracial states.
On the other hand, if you consider separable residually finite-dimensional (RFD) $C^\ast$-algebras, then they always admit a faithful tracial state: a separable $C^\ast$-algebra is RFD if it embeds into $\prod_{n\in \mathbb N} M_{k(n)}(\mathbb C)$ for some sequence $k(n)$ of natural numbers. As $\prod_{n\in \mathbb N} M_{k(n)}(\mathbb C)$ has a faithful tracial state, e.g. $\sum_{n\in \mathbb N} 2^{-n} \mathrm{tr}_{k(n)}$, so does any $C^\ast$-subalgebra.


text:
Q: correct implementation of plupdate i´m implementing this upload library, maybe not much people use this, but maybe somebody can help me to figure how to solve this.
So i'm already uploading, the thing is that i want to implement the "uploader" objet, like
upload.bind();

i would like to know if anybody here can provide me links or maybe clear my idea.
thank you so much.
This is my code:
        uploader = $("#uploader").plupload({
        // General settings
        runtimes: 'html5,flash,silverlight,html4',
        url: objMaterial.geturl(),
        urlstream_upload: true, //cambiar url en tiempo real
        multi_selection: multiSelection,
        unique_names: unicoNombre,
        // User can upload no more then 20 files in one go (sets multiple_queues to false)
        max_file_count: 1,
        chunk_size: '1mb',
        // Resize images on clientside if we can
        filters: {
            // Maximum file size
            max_file_size: '50mb',
            // Specify what files to browse for
            mime_types: [
                {
                    title: titulo,
                    extensions: extensiones
                }
            ]
        },
        // Rename files by clicking on their titles
        rename: true,
        // Sort files
        sortable: true,
        // Enable ability to drag'n'drop files onto the widget (currently only HTML5 supports that)
        dragdrop: true,
        // Views to activate
        views: {
            list: true,
            thumbs: true, // Show thumbs
            active: 'thumbs'
        },
        // Flash settings
        flash_swf_url: '../../js/Moxie.swf',
        // Silverlight settings
        silverlight_xap_url: '../../js/Moxie.xap'
    });
    //uploader = $("#uploader").plupload();
   uploader = $('#uploader').plupload();
   console.log(uploader);
    //uploader = $("#flash_uploader").pluploadQueue();

    uploader.bind('QueueChanged', function (up, files)
    {
        files_remaining = uploader.files.length;
    });

A: i want to answer this question, i found a solution.
so all these objects are events.
here you have a complete example of how to implement them.
uploader = $("#uploader").plupload({
        // General settings
        runtimes: 'html5,html4',
        url: objMaterial.geturl(),
        // Maximum file size
        max_file_size: '50mb',
        chunk_size: '1mb',
        max_file_count: 1,
        // Resize images on clientside if we can
        resize: {
            width: 200,
            height: 200,
            quality: 90,
            crop: true // crop to exact dimensions
        },
        // Specify what files to browse for
        filters: [
            {title: "PDF", extensions: "PDF"}
        ],
        // Rename files by clicking on their titles
        rename: true,
        // Sort files
        sortable: true,
        // Enable ability to drag'n'drop files onto the widget (currently only HTML5 supports that)
        dragdrop: true,
        // Views to activate
        views: {
            list: true,
            thumbs: true, // Show thumbs
            active: 'thumbs'
        },
        // Post init events, bound after the internal events
        init: {
            PostInit: function () {
                // Called after initialization is finished and internal event handlers bound
                log('[PostInit]');
                document.getElementById('uploadfiles').onclick = function () {
                    uploader.start();
                    return false;
                };
            },
            Browse: function (up) {
                                // Called when file picker is clicked
                        },
                        Refresh: function (up) {
                                // Called when the position or dimensions of the picker change
                        },
                        StateChanged: function (up) {
                                // Called when the state of the queue is changed
                        },
                        QueueChanged: function (up) {
                                // Called when queue is changed by adding or removing files
                        },
            OptionChanged: function (up, name, value, oldValue) {
                // Called when one of the configuration options is changed
            },
            BeforeUpload: function (up, file) {
                // Called right before the upload for a given file starts, can be used to cancel it if required
            },
                        UploadProgress: function (up, file) {
                                // Called while file is being uploaded
                        },
            FileFiltered: function (up, file) {
                // Called when file successfully files all the filters
            },
                        FilesAdded: function (up, files) {
                                // Called when files are added to queue
                                plupload.each(files, function (file) {
                                });
                        },
                        FilesRemoved: function (up, files) {
                                // Called when files are removed from queue
                                plupload.each(files, function (file) {
                                });
                        },
                        FileUploaded: function (up, file, info) {
                                // Called when file has finished uploading
                jQueryMessage('El archivo se ha enviado exitosamente!', 1);
                        },
                        ChunkUploaded: function (up, file, info) {
                                // Called when file chunk has finished uploading
                        },
            UploadComplete: function (up, files) {
                // Called when all files are either uploaded or failed
            },
            Destroy: function (up) {
                // Called when uploader is destroyed
            },
                        Error: function (up, args) {
                                // Called when error occurs
                        }
            },
        // Flash settings
        flash_swf_url: '/plupload/js/Moxie.swf',
        // Silverlight settings
        silverlight_xap_url: '/plupload/js/Moxie.xap'
    });

i hope this can help you


text:
Q: How to correctly mock class with Runnable implements Hi!
I have a class:
public class RecovererService {
    private final ConfigServiceProvider serviceProvider;
    private final ErrorRecordRepository recordRepository;
    private final SimpleWriterTest simpleWriterTest;
    private final AuditRecordProcessor itemProcessor;
    private ScheduledExecutorService scheduledExecutorService;

    private boolean isRunning;

    @Override
    public void startService() {
        if (serviceProvider.isRecoveryServiceAllowed()) {
            log.info("========================== Starting Recoverer process ==========================");
            isRunning = true;
            scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
            scheduledExecutorService.scheduleWithFixedDelay(new RecovererThread(recordRepository,
                    simpleWriterTest,
                    itemProcessor),
                    0,
                    5000L,
                    TimeUnit.MILLISECONDS);
        }

As a parameter in the singleThreadScheduleExecutor, I pass the following class, which implements the Runnable interface:
public class RecovererThread implements Runnable {

    @Override
    public void run() {
                deleteFailedRowFromDb("id");
    }

    private AuditRecordDto getFailedRowFromDb(String id) {
        return null;
    }

To check the correct operation of the class, I wrote a unit test:
@RunWith(MockitoJUnitRunner.class)
public class RecovererServiceTest {
    private final ConfigServiceProvider serviceProvider = mock(ConfigServiceProvider.class);
    private final ErrorRecordRepository recordRepository = mock(ErrorRecordRepository.class);
    private final SimpleWriterTest simpleWriterTest = mock(SimpleWriterTest.class);
    private final AuditRecordProcessor itemProcessor = mock(AuditRecordProcessor.class);
    private final Runnable recovererThread = mock(Runnable.class);
    ThreadFactory mock = mock(ThreadFactory.class);
    private final ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(mock);
    private final RecovererService recovererService = new RecovererService(serviceProvider, recordRepository, simpleWriterTest, itemProcessor);

    @Test
    public void testRecovererServiceStart() {
        doReturn(true).when(serviceProvider).isRecoveryServiceAllowed();
        recovererService.startService();
        verify(recovererThread, timeout(6000)).run();
    }
}

But I get an error in the test:
Wanted but not invoked:
recovererThread.run();

At the same time, in the unit test logs, I see that this method is called
Thanks!

A: You're creating the RecovererThread object instance using new in your code:
scheduledExecutorService.scheduleWithFixedDelay(new RecovererThread(...))

The mock instance in your test (Runnable recovererThread = mock(Runnable.class)) is not injected into your actual code. The mock is a separate object, which is not interacted with in any way, so Mockito does not register the call.
To actually verify the call on the mocked thread you would have to pass it to the RecovererService and use it there or define a factory class that would be used to create threads (actually Runnables) instead of using new. That way you could use a default implementation in the production code and a mocked implementation in the test code.


text:
Q: Redirection domain with https and a dot at the end of url How can I get a domain redirect, e.g. https://google.com. (with dot) to https://google.com/
Redirection works with htaccess but only for http:// queries
How can I get this redirect? Maybe I need to add some DNS record? Or maybe there is a separate htaccess rule for https://?
I currently have the following rule for http:// and it works:
RewriteCond% {HTTP_HOST} \. $
RewriteRule (. *) Https://google.com/$1 [R = 301, L]

Is there anyone here who can solve the problem?
Please help


text:
Q: Generate combinations in SQL Server I need to generate combinations from the string of numbers
3,4,5,6,7 digit combinations
for example from this string
01;05;06;03;02;10;11;

here 7 numbers are there. for 3 digit 35 combinations will be there and it should be in order of order numbers in the string.
like
01;05;06;|
01;05;03;|
01;05;02;|
01;05;10;|
01;05;11;|
01;06;03;|
01;06;02;|
01;06;10;|
01;06;11;|
01;03;02;|
01;03;10;|
01;03;11;|
01;02;10;|
01;02;11;|
01;10;11;|

05;06;03;|
05;06;02;|
05;06;10;|
05;06;11;|

05;03;02;|
05;03;10;|
05;03;11;|
05;02;10;|
05;02;11;|
05;10;11;|

06;03;02;|
06;03;10;|
06;03;11;|
06;02;10;|
06;02;11;|
06;10;11;|

03;02;10;|
03;02;11;|

03;10;11;|

02;10;11;|

A: You can do this with two inner joins after splitting the string.
rextester: http://rextester.com/JJGKI77804
String Splitter for the test:
/* Jeff Moden's http://www.sqlservercentral.com/articles/Tally+Table/72993/ */
create function dbo.DelimitedSplitN4K (@pString nvarchar(4000), @pDelimiter nchar(1))
returns table with schemabinding as
return
  with e1(n) as (
    select 1 union all select 1 union all select 1 union all
    select 1 union all select 1 union all select 1 union all
    select 1 union all select 1 union all select 1 union all select 1
  )
  , e2(n) as (select 1 from e1 a, e1 b)
  , e4(n) as (select 1 from e2 a, e2 b)
  , cteTally(n) as (select top (isnull(datalength(@pString)/2,0))
      row_number() over (order by (select null)) from e4)
  , cteStart(n1) as (select 1 union all
      select t.n+1 from cteTally t where substring(@pString,t.n,1) = @pDelimiter)
  , ctelen(n1,l1) as(select s.n1
  ,   isnull(nullif(charindex(@pDelimiter,@pString,s.n1),0)-s.n1,4000)
    from cteStart s
  )
 select Itemnumber = row_number() over(order by l.n1)
      , Item       = substring(@pString, l.n1, l.l1)
   from ctelen l;
go

the query
declare @str nvarchar(4000)= '01;05;06;03;02;10;11;';
with cte as (
  select ItemNumber, Item
  from dbo.DelimitedSplitN4K(@str,';')
  where Item != ''
)
select combo=a.Item+';'+b.Item+';'+c.Item
  from cte as a
    inner join cte as b on a.ItemNumber<b.ItemNumber
    inner join cte as c on b.ItemNumber<c.ItemNumber;
  order by a.ItemNumber, b.ItemNumber, c.ItemNumber

ordered by ItemNumber results:
01;05;06
01;05;03
01;05;02
01;05;10
01;05;11
01;06;03
01;06;02
01;06;10
01;06;11
01;03;02
01;03;10
01;03;11
01;02;10
01;02;11
01;10;11
05;06;03
05;06;02
05;06;10
05;06;11
05;03;02
05;03;10
05;03;11
05;02;10
05;02;11
05;10;11
06;03;02
06;03;10
06;03;11
06;02;10
06;02;11
06;10;11
03;02;10
03;02;11
03;10;11
02;10;11

If you want to return a single string, pipe delimited then:
with cte as (
  select ItemNumber, Item
  from dbo.DelimitedSplitN4K(@str,';')
  where Item != ''
)
select combo=stuff(
  (select '|'+a.Item+';'+b.Item+';'+c.Item
    from cte as a
      inner join cte as b on a.ItemNumber<b.ItemNumber
      inner join cte as c on b.ItemNumber<c.ItemNumber
    order by a.ItemNumber, b.ItemNumber, c.ItemNumber
    for xml path (''), type).value('.','nvarchar(max)')
  ,1,1,'')

results:
01;05;06|01;05;03|01;05;02|01;05;10|01;05;11|01;06;03|01;06;02|01;06;10|01;06;11|01;03;02|01;03;10|01;03;11|01;02;10|01;02;11|01;10;11|05;06;03|05;06;02|05;06;10|05;06;11|05;03;02|05;03;10|05;03;11|05;02;10|05;02;11|05;10;11|06;03;02|06;03;10|06;03;11|06;02;10|06;02;11|06;10;11|03;02;10|03;02;11|03;10;11|02;10;11

splitting strings reference:

*

*Tally OH! An Improved SQL 8K "CSV Splitter" Function

*Splitting Strings : A Follow-Up - Aaron Bertrand

*Split strings the right way – or the next best way

A: I had nearly the same query but resulted somehow different
Please check
/*
create table Combination (id char(2))
insert into Combination values ('01'),('05'),('06'),('03'),('02'),('10'),('11')
*/
select c1.id, c2.id, c3.id, c1.id + ';' + c2.id + ';' + c3.id Combination
from Combination c1, Combination c2, Combination c3
where
  c2.id between c1.id and c3.id
  and c1.id <> c2.id
  and c2.id <> c3.id
order by c1.id, c2.id, c3.id

The output is


text:
Q: Getting type of second param of a method Using webext-bridge I can define my listeners like
// shims.d.ts
declare module 'webext-bridge' {
  export interface ProtocolMap {
    // define message protocol types
    // see https://github.com/antfu/webext-bridge#type-safe-protocols
    'event-name': { helloMessage: string };
  }
}

// code
onMessage('event-name', (message) => {
    // do something strict way
    console.log(message.data.helloMessage); // no ts error
});

How I can define the method for second param like
function onEventName(message: /* How to get message type dynamically here? */) {
    console.log(message.data.helloMessage); // ts not able to get type here
}
onMessage('event-name', onEventName);

A: It can be defined as:
import { onMessage, ProtocolMap, IBridgeMessage } from 'webext-bridge'

function onEventName(message: IBridgeMessage<ProtocolMap['event-name']>) {
    console.log(message.data.helloMessage);
}
onMessage('event-name', onEventName);

TS play


text:
Q: Redux state changes but not reflected in component I'm trying to implement a shopping cart using redux. here is my cart-reducer:
export const cartReducer = (
state = { cartItems: JSON.parse(localStorage.getItem("cartItems") || "[]")},
action) => {
switch (action.type) {
 case ADD_TO_CART:
  return { ...state,cartItems: action.payload };
}}

Here is the component where I want to show the updated state value accessing it using props in connect and update the cartItems.length after every state update
class Cartsidebar extends Component {
    constructor(props) {
        super(props);
        this.state = {
            grandTotal: '',toggle:true
        }
    }
    handleHide(){
        this.setState({ toggle: !this.state.toggle})
    }
    render() {

     const {cartItems}=this.props;
     console.log(cartItems);
        return (
            <div>
               {cartItems.length}

            </div>
        )
    }
}

export default connect(
    (state) => ({
        cartItems: state.cart.cartItems,
    }),
    { incrementToCart, decreaseToCart, removeFromCart }
)(Cartsidebar);

States are updating fine and state-difference is also showing in redux-dev-tools on every update of redux state but it is not reflecting in cart component.what am i doing wrong here?Thanks in advance.
EDIT:
this is function that execute on add to cart button onclick event:
handleAddToCart=(p)=>{
const cartItems = store.getState().cart.cartItems;
  let alreadyExists = false;
  cartItems.forEach((x) => {
    if (x.discountPer === p.discountPer) {
      alreadyExists = true;
    }
  });
  if (!alreadyExists) {
    cartItems.push({ ...p });
  }

store.dispatch(addToCart(cartItems));

}

And addToCart action creator looks like this:
export const addToCart = (cartItem) => {
  return({
    type: ADD_TO_CART,
    payload: cartItem,
  });
};

A: What you are doing in handleAddToCart is a big no no, and goes against the pattern that Redux tries to enforce. I made some changes to your logic to make it easier, and updated the reducer. In theory, if you make these changes, it should work.
handleAddToCart:
handleAddToCart = (p) => {
  const cartItems = store.getState().cart.cartItems;

  for (const item of cartItems) {
    if (item.discountPer === p.discountPer) {
      return;
    }
  }

  store.dispatch(addToCart({ ...p }));
};

reducer:
export const cartReducer = (
  state = { cartItems: JSON.parse(localStorage.getItem("cartItems") || "[]") },
  action
) => {
  switch (action.type) {
    case ADD_TO_CART:
      return { ...state, cartItems: [...state.cartItems, action.payload] };
  }
};

A: Issues

*

*You are mutating the state object. You are accessing a reference to the cart array in state and directly pushing into it.

*You aren't leveraging the power of Redux and reducers properly.

code
handleAddToCart = (p) => {
  const cartItems = store.getState().cart.cartItems; // cartItems is reference to state
  let alreadyExists = false;
  cartItems.forEach((x) => {
    if (x.discountPer === p.discountPer) {
      alreadyExists = true;
    }
  });
  if (!alreadyExists) {
    cartItems.push({ ...p }); // mutation!!
  }

  store.dispatch(addToCart(cartItems));
}

Solution
Pass the item you want to add to the cart in the action and move all the logic to update the cart into your reducer.
UI
handleAddToCart = (p) => {
  this.props.addToCart(p);
}

...

export default connect(
  (state) => ({
    cartItems: state.cart.cartItems,
  }),
  { addToCart, incrementToCart, decreaseToCart, removeFromCart }
)(Cartsidebar);

reducer
case ADD_TO_CART:
  const { payload } = action;
  const found = state.cartItems.find(item => item.discountPer === payload.discountPer);

  if (found) {
    return state;
  }

  return {
    ...state,
    cartItems: state.cartItems.concat(payload),
  };


text:
Q: Is csproj the same as the manifest? I have a project created with VS2017 and if I edit the csproj file I can see the PackageReference that set the dependencies with the DLLs.
If I am not wrong, this is set too in the manifest file, so I am wondering if csproj is the same as the manifest file? If true, then the manifest file is not needed then?
I'm wondering, if I go to the properties of the project and go to application, I can't set the manifest because this option is disabled.
What I want is to set the dependencies of the assembly to be able to load it at runtime and check if there are new versions available for update.

A: No, a csproj is a description of the files needed to build the project with Visual Studio.
An application manifest is a special file (included in the csproj) that is included in the built application; telling windows different things about the application (such as if it requires admin access).
Certain settings in the csproj may affect the manifest, but they are definitely not the same.


text:
Q: JSF 1.1 equivalent of f:event I am trying to re-retrieve data from my database whenever the user clicks on a link (just in case any information has changed)
But I am using JSF 1.1,
In JSF 2.0 we have
        <f:metadata>
            <f:event type="preRenderView" listener="#{refreshDataTable}"> </f:event>
        </f:metadata>

or even PhaseListeners, but in 1.1 we don't.
Does anyone know an equivalent, or anything that can invoke an action on a bean when a link is clicked?
Thanks.

A: Put the bean in the request scope and do the job in its constructor.
Don't put the bean in the session scope. That's only bad for user experience and server memory. If you want to simulate the view scope in JSF 1.x, have a look at Tomahawk's <t:saveState> or RichFaces' <a4j:keepAlive>.


text:
Q: Package jdk.internal.jrtfs in both module java.base and module jrt.fs private JFrame frame;
/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                GUI window = new GUI();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public GUI() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

Console:
Error occurred during initialization of boot layer
java.lang.LayerInstantiationException: Package jdk.internal.jrtfs in both module jrt.fs and module java.base
I'm trying to create a GUI on Eclipse using windowbuilder and all the time i run into the same error and i can't launch my class to create a JFrame.


text:
Q: How to zoom whole RecyclerView in android I've created a zoom function which is working zooming for LinearLayout and FrameLayout but not working for RecyclerView.
XML file :
<com.nm.esign.entities.ZoomLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/zoom_main1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/fl_zoom"
    android:orientation="vertical"

    android:layout_width="match_parent"
    android:layout_height="match_parent">

      <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_view_template_img"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="30dp"

            android:scrollbars="vertical" />

    </LinearLayout>

     </com.nm.esign.entities.ZoomLayout>

Main activity:
  protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_view_template);

        //  prevBtn=(android.support.v7.widget.AppCompatButton)findViewById(R.id.btnDocumentPrev_temp);
        // nextBtn=(android.support.v7.widget.AppCompatButton)findViewById(R.id.btnDocumentNxt_temp);
    RecyclerView    recyclerView = (RecyclerView) findViewById(R.id.recycler_view_template_img);

    LinearLayout    fl_zoom=(LinearLayout)findViewById(R.id.fl_zoom)

        ZoomLayout myZoomView = new ZoomLayout(ViewTemplate.this);

      fl_zoom.addView(myZoomView); // working fine
// recyclerView.addView(myZoomView); // not working

....................................

}

ZoomLayout class:
/**
 * Created by Lenovo5 on 3/16/2017.
 */

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.FrameLayout;

/**
 * Layout that provides pinch-zooming of content. This view should have exactly one child
 * view containing the content.
 */
public class ZoomLayout extends FrameLayout implements ScaleGestureDetector.OnScaleGestureListener {

    private enum Mode {
        NONE,
        DRAG,
        ZOOM
    }

    private static final String TAG = "ZoomLayout";
    private static final float MIN_ZOOM = 1.0f;
    private static final float MAX_ZOOM = 4.0f;

    private Mode mode = Mode.NONE;
    private float scale = 1.0f;
    private float lastScaleFactor = 0f;

    // Where the finger first  touches the screen
    private float startX = 0f;
    private float startY = 0f;

    // How much to translate the canvas
    private float dx = 0f;
    private float dy = 0f;
    private float prevDx = 0f;
    private float prevDy = 0f;

    public ZoomLayout(Context context) {
        super(context);
        init(context);
    }

    public ZoomLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public ZoomLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context) {
        final ScaleGestureDetector scaleDetector = new ScaleGestureDetector(context, this);
        this.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
                    case MotionEvent.ACTION_DOWN:
                        Log.i(TAG, "DOWN");
                        if (scale > MIN_ZOOM) {
                            mode = Mode.DRAG;
                            startX = motionEvent.getX() - prevDx;
                            startY = motionEvent.getY() - prevDy;
                        }
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if (mode == Mode.DRAG) {
                            dx = motionEvent.getX() - startX;
                            dy = motionEvent.getY() - startY;
                        }
                        break;
                    case MotionEvent.ACTION_POINTER_DOWN:
                        mode = Mode.ZOOM;
                        break;
                    case MotionEvent.ACTION_POINTER_UP:
                        mode = Mode.DRAG;
                        break;
                    case MotionEvent.ACTION_UP:
                        Log.i(TAG, "UP");
                        mode = Mode.NONE;
                        prevDx = dx;
                        prevDy = dy;
                        break;
                }
                scaleDetector.onTouchEvent(motionEvent);

                if ((mode == Mode.DRAG && scale >= MIN_ZOOM) || mode == Mode.ZOOM) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                    float maxDx = (child().getWidth() - (child().getWidth() / scale)) / 2 * scale;
                    float maxDy = (child().getHeight() - (child().getHeight() / scale))/ 2 * scale;
                    dx = Math.min(Math.max(dx, -maxDx), maxDx);
                    dy = Math.min(Math.max(dy, -maxDy), maxDy);
                    Log.i(TAG, "Width: " + child().getWidth() + ", scale " + scale + ", dx " + dx
                            + ", max " + maxDx);
                    applyScaleAndTranslation();
                }

                return true;
            }
        });
    }

    // ScaleGestureDetector

    @Override
    public boolean onScaleBegin(ScaleGestureDetector scaleDetector) {
        Log.i(TAG, "onScaleBegin");
        return true;
    }

    @Override
    public boolean onScale(ScaleGestureDetector scaleDetector) {
        float scaleFactor = scaleDetector.getScaleFactor();
        Log.i(TAG, "onScale" + scaleFactor);
        if (lastScaleFactor == 0 || (Math.signum(scaleFactor) == Math.signum(lastScaleFactor))) {
            scale *= scaleFactor;
            scale = Math.max(MIN_ZOOM, Math.min(scale, MAX_ZOOM));
            lastScaleFactor = scaleFactor;
        } else {
            lastScaleFactor = 0;
        }
        return true;
    }

    @Override
    public void onScaleEnd(ScaleGestureDetector scaleDetector) {
        Log.i(TAG, "onScaleEnd");
    }

    private void applyScaleAndTranslation() {
        child().setScaleX(scale);
        child().setScaleY(scale);
        child().setTranslationX(dx);
        child().setTranslationY(dy);
    }

    private View child() {
        return getChildAt(0);
    }
}

Error  coming for:-
  recyclerView.addView(myZoomView);

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.nm.esign, PID: 6028
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nm.esign/com.nm.esign.activity.ViewTemplate}: java.lang.IllegalStateException: RecyclerView has no LayoutManager
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3319)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
    at android.app.ActivityThread.access$1100(ActivityThread.java:229)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:7331)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
 Caused by: java.lang.IllegalStateException: RecyclerView has no LayoutManager
    at android.support.v7.widget.RecyclerView.generateDefaultLayoutParams(RecyclerView.java:3869)
    at android.view.ViewGroup.addView(ViewGroup.java:4431)
    at android.view.ViewGroup.addView(ViewGroup.java:4409)
    at com.nm.esign.activity.ViewTemplate.onCreate(ViewTemplate.java:112)
    at android.app.Activity.performCreate(Activity.java:6904)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
    at android.app.ActivityThread.access$1100(ActivityThread.java:229)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:7331)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

A: You must have this line in your code
LinearLayoutManager manager = new LinearLayoutManager(this);
manager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(manager);

A: The solution was simple, you can create the layout manager manager manually.
Code snippet from https://github.com/kanytu/example-parallaxrecycler/blob/master/app/src/main/java/com/poliveira/apps/exampleparallaxrecycler/MainActivity.java#L24
Add this
LinearLayoutManager manager = new LinearLayoutManager(this);
manager.setOrientation(LinearLayoutManager.VERTICAL);
myRecycler.setLayoutManager(manager);


text:
Q: Change page color and image with JS

const element = document.querySelector("body")
element.addEventListener('click', changeBackground)

function changeBackground (){
    element.classList.toggle('active')
}

const newImg = document.getElementById("newImage")
newImg.addEventListener('click', changeImage)

function changeImage(){
   newImg.setAttribute('src', './public/SwitcherLight.svg')
}

When I click on the image it changes the image and the background color of the page, but when I click back, only the background color goes back to how it was before, I want the same to happen with the image but I can't

A:

image = document.querySelector("#image");
changed_img=false

image.addEventListener('click', function(){
  document.body.classList.toggle('blue');
  if (changed_img) {
    image.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/640px-Image_created_with_a_mobile_phone.png";
    changed_img=false
  } else {
  image.src="https://i.insider.com/602ee9ced3ad27001837f2ac?width=700"
    changed_img=true
  }
})
.red {
  background-color: red;
}

.blue {
  background-color: blue;
}
<html>
<body class="red">
  <img height="200" src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/640px-Image_created_with_a_mobile_phone.png" id="image">
</body>
</html>

Hope this helped.


text:
Q: Django CMS - How to add multiple (zero or more) links on a model in admin I'm fairly new to Django CMS, and I've inherited a website with these specs:

*

*Django 1.10.8

*Django CMS 3.4.5

*Python 2.7

Unfortunately, there is no option to upgrade at the moment. Also, please pardon if I the terminology wrong - I'd appreciate corrections.
I have a Staff app with models for Staff and StaffTranslation (etc), and I have a task to update the admin to allow adding one or more links to each StaffTranslation. However, I'm having trouble identifying the best way to do this, and what components to use.
I have identified the djangocms-link plugin, which could be a possibility, but I can't find instructions on how to add multiple instances to a model or admin page. Also, the latest version requires Django 1.11, at minimum.
I have also found the PageSmartLinkField - which seems smart - but I haven't been able to discover how to integrate it with data for the StaffTranslation object or how to display it on the admin page for that object.
I would appreciate any suggestions as to how to structure this - it seems like a simple enough task, I think I am just missing a piece or two, of the puzzle.
The end purpose is to have zero-or-many links on a StaffTranslation (which has its own admin page), with the ability to add at least url and link text to each of them. It would be smart if there is some UI helper, allowing for easy selection of internal links, but a text field would be ok.
EDIT: the StaffTranslation model
class StaffTranslation(TimeStampedModel):
    staff = models.ForeignKey(Staff, related_name='translations')
    language = models.ForeignKey(Language)

    specialist_work_title = HTMLField(max_length=128, null=True, blank=True)  # SpecialistWorkTitle
    description = HTMLField(null=True, blank=True)  # PersonText
    experience = HTMLField(null=True, blank=True)  # Experience

    phone_office = models.CharField(max_length=128, null=True, blank=True)  # OfficePhone
    phone_cell = models.CharField(max_length=128, null=True, blank=True)  # CellPhone

    mentions = HTMLField(null=True, blank=True)  # Mentions
    education = HTMLField(null=True, blank=True)  # Education

    other_qualifications = HTMLField(null=True, blank=True)  # OtherQualifications

    meta_title = models.TextField(null=True, blank=True)  # MetaTitle
    meta_keywords = models.TextField(null=True, blank=True)  # MetaKeywords
    meta_description = models.TextField(null=True, blank=True)  # MetaDescription

    legacy_data = models.TextField(null=True, blank=True)

    objects = querysets.StaffTranslationQuerySet.as_manager()

    # I would like to add something here like links = models.ForeignKey(Link, related_name='links') - so should I make a Link model and add as a many to many relation, and how do I integrate that into the admin?

I left out the functions defined on the model.
Again, it would be nice to upgrade, but that won't happen until the summer at the earliest, and this task has to be resolved now. :)

A: I think a solution for you here will be a placeholder field so you can add CMS plugins like any other plugin, for each instance of this model. For example;
from cms.models.fields import PlaceholderField

class StaffTranslation(TimeStampedModel):
    ...
    content = PlaceholderField(
        'staff_translation'
    )

Then in your detail view template you do {% render_placeholder object.content %} and it'll show a placeholder for that object like it would for placeholders in any standard page template.
You can obviously then add any CMS plugins, links or otherwise, and the'll render alongside the other attributes on your StaffTranslation instance.
The docs on this are here; http://docs.django-cms.org/en/latest/how_to/placeholders.html


text:
Q: Show button on hover of parent and hide it on hover of sibling using only CSS I apologize in advance if this might be a re-post, I searched a bit for showing div on :hover of parent.
None of them helped me.
However I have bit different scenario.
If there is any other question with same scenario please share the link of the same.
What I want is to show a button on :hover of .image-wrapper and hide it on :hover of its share text.
Here is the code what I have done so far.
Here is the js solution, but I am looking for CSS solution.
It should be working on IE8 too. So + selector will also not work. Is is possible using only CSS?

A: Yes it can be done only with CSS.
What you need to do is get both the siblings in one div (e.g .innerWrap) and hide the button on hover of .innerWrap.
Here is the demo for it.


text:
Q: Efficient way to map new values to a sql query (i.e 4 columns each with same credentials) First I am new to Postgres so I may be describing this problem incorrectly so please point me to an answer if it has already been answered.
I have a database with 10 columns. Lets say 4 columns all use the same codes for values (i.e the letter a, b, d, e) I want to rename all of these in the query to what they are matched with values in another table.
I have a very long approach at this stage involving a nested With  statements. Is there a easy way to go from say:
table1:
id    | col1 | col2 | col3 | col4
------+------+------+------+------
Row_1 | a    | c    | d    | e
Row_2 | c    | c    | c    | c
Row_3 | e    | d    | d    | c

Lookup Table:
code | value
-----+---------
a    | apple
b    | banana
c    | catfish
d    | dog
e    | egg

Desired result:
Row_1 | apple   | catfish | dog     | egg
Row_2 | catfish | catfish | catfish | dog
Row_3 | egg     | dog     | dog     | catfish

A: Yes, https://dba.stackexchange.com/questions/145038/how-to-join-to-the-same-table-multiple-times should basically work for you. But you want an UPDATE, which is a bit different:
Either way, code values in table lookup have to be UNIQUE for obvious reasons.
Updating a single column is simple:
UPDATE table1 t
SET    col1 = l.value
FROM   lookup l
WHERE  t.col1 = l.code;

If no match is found, the row it table1 is not updated.
But running separate updates for every column is considerably more expensive than updating all columns at once - which is a bit more tricky:
UPDATE table1 t
SET    col1 = COALESCE(l1.value, t.col1)
     , col2 = COALESCE(l2.value, t.col2)
     , col3 = COALESCE(l3.value, t.col3)
     , col4 = COALESCE(l4.value, t.col4)
FROM   table1 t1
LEFT   JOIN lookup l1 ON t.col1 = l1.code
LEFT   JOIN lookup l2 ON t.col2 = l2.code
LEFT   JOIN lookup l3 ON t.col3 = l3.code
LEFT   JOIN lookup l4 ON t.col4 = l4.code
WHERE  t1.id = t.id;

In this case, all rows are updated. While there can be NULL values in table1 or missing values in lookup we need LEFT [OUTER] JOIN to not exclude rows from the update. So we need another instance of table1 in the FROM clause and LEFT JOIN to that.
And the added COALESCE retains the original value for each individual column where no match was found. The optimal query depends on details not disclosed in your question ...
You might add another WHERE clause to exclude rows where nothing changes. See:

*

*How do I (or can I) SELECT DISTINCT on multiple columns?


text:
Q: Get Forum Files from Vanilla Forum I had homework of making a forum about a subject, tomorrow I have show my final work.
I used VANILLA FORUMS to make the webiste, created it, modified what needs to be modified got the themes and everything done, now im looking for someway to import only the website and database files ( html/css/js/php... files ) plus the database, like get all the files that make the website launch without re-opening Xampp everytime
to sum up Is there anyway I can import the webiste files from the XAMMP folder so its shareable ?
Or if somebody knows simply where they must be.
Appreciate your help

A: i believe they could be in Htdocs, but not sure if dragging them would save their state as it is displayed on the Localhost/yourforum

A: There are two ways and im guessing you need the first one:

*

*Make a dump of your database, store that file in your document root. And now zip everything. The other person can unzip it and load the database dump in their database and proceed.

*You add it to a repository and send the link to the other party. The other party pulls it from the repository, does (something similar to) composer install and npm build and a form of migration the database.
In either case, it's recommended that you create a readme.md, explaining how to set up the project.
Based on the fact that you're asking, I think you're looking for the first solution, which is the most simple and acceptable for entry level programmers/students.


text:
Q: Setting SwitchTile toggle based on database values flutter We are using SwitchTiles for a settings screen. I am pulling values from the database to set them to on or off accordingly. How is the initial toggle set to true or false? Is it switchValue?
Heres the Code for one.
 SettingsTile.switchTile(
            title: 'Check In',
            leading: Icon(Icons.check, color: Colors.blue,),
            switchValue: checkIn,
            onToggle: (bool value) {
              setState(() {
                checkIn = value;
                insertFeature(widget.user.userId, 'CheckIn', checkIn);
              });
            },
          ),

A: Its SwitchValue, I found it defined in an outside class.


text:
Q: oracle date format issue We use Oracle 10.2.0.4.0 database, oracle form builder and report builder for creating forms and reports.
Now the problem is in our production database nls_date_format is dd-mon-rr format. When developer create form in developer suit they give dd-mm-rr format at form level and when data stored in table that date format is dd-mm-rr.
Now when developer run form or report within form builder it gives dd-mm-rr format.but when same form or report run from application server side it gives junk characters in month.date and year print same as date format only month display in junk characters.
Hope you all guide well.

A: There are two issues.

when data stored in table that date format is dd-mm-rr.

This is completely wrong. Oracle doesn't store the date in the format you see, what you see is for display. Oracle stores DATE in an internal proprietary format in 7 bytes with each byte representing different elements of the DATE.
Byte    Description
----    -------------------------------------------------
1       Century value but before storing it add 100 to it
2       Year and 100 is added to it before storing
3       Month
4       Day of the month
5       Hours but add 1 before storing it
6       Minutes but add 1 before storing it
7       Seconds but add 1 before storing it

Do not depend on the locale_specific NLS_DATE_FORMAT. Always use:

*

*TO_CHAR to display the date in your desired format

*TO_DATE to explicitly convert the string into date.

Remember, TO_DATE is NLS dependent.
If you only have a date element, and if you do not care about the time element, then better use ANSI Date literal which follows a fixed format 'YYYY-MM-DD'.

only month display in junk characters

This is again because you are depending on the NLS_DATE_LANGUAGE. As I said, you should avoid depending on the locale-specific client settings. Explicitly mention the NLS_DATE_LANGUAGE or use ANSI Date literal if you are not concerned about the time element.
For example,
SQL> SELECT TO_CHAR(SYSDATE, 'DD-MON-RR') dt FROM DUAL;

DT
---------
26-OCT-15

SQL> alter session set nls_date_language='french';

Session altered.

SQL> SELECT TO_CHAR(SYSDATE, 'DD-MON-RR') dt FROM DUAL;

DT
-----------
26-OCT. -15

So, what happened above? for a person using FRENCH nls_date_language, the MONTH is showing junk value. Let's make it NLS independent by explicitly mentioning the nls_date_language.
SQL> SELECT TO_CHAR(SYSDATE, 'DD-MON-RR', 'nls_date_language=english') dt FROM DUAL;

DT
---------
26-OCT-15

Also, the NLS_LANG value might not be correctly set in the OS environmental variable. See Why are junk values/special characters/question marks displayed on my client?