问:
I want to show tab bar icon left side of text
I want to show icon left side of the text but the problem is that the icon is showing above the text. it's taking much more space.
I want keep the icon left sode of the text(title) . what should i do?

The main activity is given below

java.class

```<code>public class Tabsadar extends AppCompatActivity {
ExpandableRelativeLayout
expandableLayout1,
expandableLayout2,
expandableLayout3,
expandableLayout4;

private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
        R.drawable.ic_action_name,
        R.drawable.thanatottho,
        R.drawable.proyojonio
};

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

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    viewPager = (ViewPager) findViewById(R.id.container);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    setupTabIcons();
}

private void setupTabIcons() {
    tabLayout.getTabAt(0).setIcon(tabIcons[0]);
    tabLayout.getTabAt(1).setIcon(tabIcons[1]);
    tabLayout.getTabAt(2).setIcon(tabIcons[2]);
}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFrag(new tabsadarc1(), "ফিচার");
    adapter.addFrag(new tabsadarc2(), "তথ্যাবলি");
    adapter.addFrag(new tabsadarc3(), "প্রয়োজনীয়");
    viewPager.setAdapter(adapter);
}

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

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

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

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

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

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

   }'
</code>```

i want something like that

in my case something happend like that

any solution?

答:
As per your requirement I'll suggest you to create a custom view for tabs.

custom_tab_view.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:gravity="center"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="@dimen/_6sdp"
        android:background="@drawable/ic_menu_gallery"/>

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginLeft="@dimen/_3sdp"
        android:textColor="@drawable/tab_text_selector"
        android:textSize="@dimen/_15sdp" />
</LinearLayout>

</RelativeLayout>
</code>```

And this layout of custom tab with PagerAdapter as

```<code> //On  Create
for (int i = 0; i < mPagerAdapter.getCount(); i++) {
        View customView = mPagerAdapter.getCustomView(getActivity(), i);
        mainTabLayout.getTabAt(i).setCustomView(customView);
    }

//Pager Adapter
public static class ViewPagerAdapter extends SmartFragmentStatePagerAdapter {
    private List<Map<String, Object>> maps = new ArrayList<>();

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

    public View getCustomView(Context context, int pos) {
        View mView = LayoutInflater.from(context).inflate(R.layout.custom_tab_view, null);
        TextView mTextView = (TextView) mView.findViewById(R.id.textView);
        ImageView imageView = (ImageView) mView.findViewById(R.id.imageView);
        mTextView.setGravity(Gravity.CENTER);
        mTextView.setTypeface(Typeface.createFromAsset(context.getAssets(),
                "fonts/aller_regular.ttf"));
        mTextView.setText(getPageTitle(pos));
        return mView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        super.destroyItem(container, position, object);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return fragments[position];
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return new CompletedTaskFragment();
            case 1:
                return new PendingTaskFragment();
        }
        return null;
    }

    @Override
    public int getCount() {
        return 2;
    }
}
</code>```

Hope it'll help you.

Body:
I want to show icon left side of the text but the problem is that the icon is showing above the text. it's taking much more space.
I want keep the icon left sode of the text(title) . what should i do?

The main activity is given below

java.class

public class Tabsadar extends AppCompatActivity {
ExpandableRelativeLayout
expandableLayout1,
expandableLayout2,
expandableLayout3,
expandableLayout4;

private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
        R.drawable.ic_action_name,
        R.drawable.thanatottho,
        R.drawable.proyojonio
};

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

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    viewPager = (ViewPager) findViewById(R.id.container);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    setupTabIcons();
}

private void setupTabIcons() {
    tabLayout.getTabAt(0).setIcon(tabIcons[0]);
    tabLayout.getTabAt(1).setIcon(tabIcons[1]);
    tabLayout.getTabAt(2).setIcon(tabIcons[2]);
}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFrag(new tabsadarc1(), "ফিচার");
    adapter.addFrag(new tabsadarc2(), "তথ্যাবলি");
    adapter.addFrag(new tabsadarc3(), "প্রয়োজনীয়");
    viewPager.setAdapter(adapter);
}

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

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

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

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

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

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

   }'

i want something like that

in my case something happend like that

any solution?

Body:
As per your requirement I'll suggest you to create a custom view for tabs.

custom_tab_view.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:gravity="center"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="@dimen/_6sdp"
        android:background="@drawable/ic_menu_gallery"/>

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginLeft="@dimen/_3sdp"
        android:textColor="@drawable/tab_text_selector"
        android:textSize="@dimen/_15sdp" />
</LinearLayout>

</RelativeLayout>

And this layout of custom tab with PagerAdapter as

 //On  Create
for (int i = 0; i < mPagerAdapter.getCount(); i++) {
        View customView = mPagerAdapter.getCustomView(getActivity(), i);
        mainTabLayout.getTabAt(i).setCustomView(customView);
    }

//Pager Adapter
public static class ViewPagerAdapter extends SmartFragmentStatePagerAdapter {
    private List<Map<String, Object>> maps = new ArrayList<>();

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

    public View getCustomView(Context context, int pos) {
        View mView = LayoutInflater.from(context).inflate(R.layout.custom_tab_view, null);
        TextView mTextView = (TextView) mView.findViewById(R.id.textView);
        ImageView imageView = (ImageView) mView.findViewById(R.id.imageView);
        mTextView.setGravity(Gravity.CENTER);
        mTextView.setTypeface(Typeface.createFromAsset(context.getAssets(),
                "fonts/aller_regular.ttf"));
        mTextView.setText(getPageTitle(pos));
        return mView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        super.destroyItem(container, position, object);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return fragments[position];
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return new CompletedTaskFragment();
            case 1:
                return new PendingTaskFragment();
        }
        return null;
    }

    @Override
    public int getCount() {
        return 2;
    }
}

Hope it'll help you.


来源: stackexchange

答:
Based on the edit in the OP's post, if we need to grab the 'y' elements in the list of vectors, then, loop through the list, get the names get a logical index by checking with 'y' and subset the elements

```<code>lapply(lst, function(x) x[names(x)=='y'])
</code>```

Or use [

```<code>lapply(lst, `[`, 'y')
</code>```

We can remove the nested part with [[

```<code>lapply(lst, `[[`, 'y')
</code>```

data

```<code>lst <- list(gene949 = list(x = 1:5, y = 6:10), gene950 = list(x = 11:20, y = 21:30))
</code>```

ContentLicense: CC BY-SA 3.0

Title: get rid of slashes after capture.output in R

Body:
In R, I need to write the output of paste0 to variable and need to get rid of slashes before doublequotes.

paste0('interpol_df[["gene',i, '"]][["y"]]')
[1] "interpol_df[[\"gene1565\"]][[\"y\"]]"

With cat one cat get rid of \

cat(paste0('interpol_df[["gene',i, '"]][["y"]]'))
interpol_df[["gene1565"]][["y"]]

To write the result to a variable, one cat use capture.output:

capture.output(cat(paste0('interpol_df[["gene',i, '"]][["y"]]')))

But \ is back again!

[1] "interpol_df[[\"gene1565\"]][[\"y\"]]"

sprintf also did not help. Any suggestion on how to get rid of it?

EDIT:

That piece of code is withing a for loop, which looks like:

inter_data<-NULL
for (i in 0:1565){
  y_col<-cat(paste('interpol_df[["gene',i, '"]][["y"]]'))
  inter_data<-rbind(inter_data,y_col)
  }

EDIT2:

By this loop I want to grab of y values from the following dataframe:

$gene949
$gene949$x
 [1] 1.000000 1.061224 1.122449 1.183673 1.244898 1.306122 1.367347 1.428571 1.489796 1.551020 1.612245 1.673469 1.734694 1.795918 1.857143 1.918367 1.979592 2.040816
[19] 2.102041 2.163265 2.224490 2.285714 2.346939 2.408163 2.469388 2.530612 2.591837 2.653061 2.714286 2.775510 2.836735 2.897959 2.959184 3.020408 3.081633 3.142857
[37] 3.204082 3.265306 3.326531 3.387755 3.448980 3.510204 3.571429 3.632653 3.693878 3.755102 3.816327 3.877551 3.938776 4.000000

$gene949$y
 [1] 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000
[15] 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000
[29] 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.02984865 0.11939459 0.20894053 0.29848647 0.38803241 0.47757835 0.56712429 0.65667023 0.74621616
[43] 0.83576210 0.92530804 1.01485398 1.10439992 1.19394586 1.28349180 1.37303774 1.46258368

$gene950
$gene950$x
 [1] 1.000000 1.061224 1.122449 1.183673 1.244898 1.306122 1.367347 1.428571 1.489796 1.551020 1.612245 1.673469 1.734694 1.795918 1.857143 1.918367 1.979592 2.040816
[19] 2.102041 2.163265 2.224490 2.285714 2.346939 2.408163 2.469388 2.530612 2.591837 2.653061 2.714286 2.775510 2.836735 2.897959 2.959184 3.020408 3.081633 3.142857
[37] 3.204082 3.265306 3.326531 3.387755 3.448980 3.510204 3.571429 3.632653 3.693878 3.755102 3.816327 3.877551 3.938776 4.000000

$gene950$y
 [1]  0.00000000 -0.15429366 -0.30858732 -0.46288099 -0.61717465 -0.77146831 -0.92576197 -1.08005564 -1.23434930 -1.38864296 -1.54293662 -1.69723029 -1.85152395
[14] -2.00581761 -2.16011127 -2.31440493 -2.46869860 -2.34260266 -2.07631192 -1.81002118 -1.54373044 -1.27743971 -1.01114897 -0.74485823 -0.47856749 -0.21227675
[27]  0.05401399  0.32030472  0.58659546  0.85288620  1.11917694  1.38546768  1.65175842  1.83847450  1.86604127  1.89360805  1.92117482  1.94874159  1.97630836
[40]  2.00387514  2.03144191  2.05900868  2.08657546  2.11414223  2.14170900  2.16927578  2.19684255  2.22440932  2.25197610  2.27954287

As it was suggested, there are for sure much better ways to achieve it than I do...

Body:
Based on the edit in the OP's post, if we need to grab the 'y' elements in the list of vectors, then, loop through the list, get the names get a logical index by checking with 'y' and subset the elements

lapply(lst, function(x) x[names(x)=='y'])

Or use [

lapply(lst, `[`, 'y')

We can remove the nested part with [[

lapply(lst, `[[`, 'y')

data

lst <- list(gene949 = list(x = 1:5, y = 6:10), gene950 = list(x = 11:20, y = 21:30))


问:
Attached property not working
I am using DevExpress control TreeListControl to display data. This control has columns, like datagrid. I want to show values in the center of the cell. For that I'm using CellTemplate:

```<code><dxg:TreeListColumn HorizontalHeaderContentAlignment="Center" Header="January">
    <dxg:TreeListColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding RowData.Row.January}" TextAlignment="Center"/>
        </DataTemplate>
    </dxg:TreeListColumn.CellTemplate>
</dxg:TreeListColumn>
</code>```

But I have a lot of columns, and the only difference is value to display. So I decided to use a style and pass value with attached property. Style:

```<code><Style x:Key="TreeListColumnStyle" TargetType="{x:Type dxg:TreeListColumn}">
   <Setter Property="HorizontalHeaderContentAlignment" Value="Center"/>
   <Setter Property="CellTemplate">
       <Setter.Value>
           <DataTemplate>
               <TextBlock Text="{TemplateBinding ap:BenDatagridValueProperty.DataGridValue}" TextAlignment="Center"/>
           </DataTemplate>
       </Setter.Value>
   </Setter>
</Style>
</code>```

And here is my AttachedProperty:

```<code>public static class BenDatagridValueProperty
{
    public static readonly System.Windows.DependencyProperty DataGridValueProperty = System.Windows.DependencyProperty.RegisterAttached(
    "DataGridValue",
    typeof(string),
    typeof(BenDatagridValueProperty),
    new System.Windows.FrameworkPropertyMetadata("", System.Windows.FrameworkPropertyMetadataOptions.Inherits));

    public static string GetDataGridValue(System.Windows.DependencyObject obj)
    {
        return (string)obj.GetValue(DataGridValueProperty);
    }

    public static void SetDataGridValue(System.Windows.DependencyObject obj, string value)
    {
        obj.SetValue(DataGridValueProperty, value);
    }
}
</code>```

Remade column now looks like:

```<code>  <dxg:TreeListColumn Header="January" Style="{StaticResource TreeListColumnStyle}" ap:BenDatagridValueProperty.DataGridValue="15">
</code>```

15 is just a test value. And it does not sets value in datagrid columns to 15 (it does not call method SetDataGridValue(DependencyObject obj, string value). If I will write a default value in AttachedProperty, then I can see default value in cells.
Not sure where is error.

答:
Try modify TreeListColumnStyle:

```<code><Style x:Key="TreeListColumnStyle" TargetType="{x:Type dxg:TreeListColumn}">
   <Setter Property="HorizontalHeaderContentAlignment" Value="Center"/>
   <Setter Property="CellTemplate">
       <Setter.Value>
           <DataTemplate>
               <TextBlock ap:BenDatagridValueProperty.DataGridValue="{TemplateBinding ap:BenDatagridValueProperty.DataGridValue}" Text="{Binding Path=(ap:BenDatagridValueProperty.DataGridValue), RelativeSource={RelativeSource Self}}" TextAlignment="Center"/>
           </DataTemplate>
       </Setter.Value>
   </Setter>
</Style>
</code>```

Title: Attached property not working

Body:
I am using DevExpress control TreeListControl to display data. This control has columns, like datagrid. I want to show values in the center of the cell. For that I'm using CellTemplate:

<dxg:TreeListColumn HorizontalHeaderContentAlignment="Center" Header="January">
    <dxg:TreeListColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding RowData.Row.January}" TextAlignment="Center"/>
        </DataTemplate>
    </dxg:TreeListColumn.CellTemplate>
</dxg:TreeListColumn>

But I have a lot of columns, and the only difference is value to display. So I decided to use a style and pass value with attached property. Style:

And here is my AttachedProperty:

public static class BenDatagridValueProperty
{
    public static readonly System.Windows.DependencyProperty DataGridValueProperty = System.Windows.DependencyProperty.RegisterAttached(
    "DataGridValue",
    typeof(string),
    typeof(BenDatagridValueProperty),
    new System.Windows.FrameworkPropertyMetadata("", System.Windows.FrameworkPropertyMetadataOptions.Inherits));

    public static string GetDataGridValue(System.Windows.DependencyObject obj)
    {
        return (string)obj.GetValue(DataGridValueProperty);
    }

    public static void SetDataGridValue(System.Windows.DependencyObject obj, string value)
    {
        obj.SetValue(DataGridValueProperty, value);
    }
}

Remade column now looks like:

  <dxg:TreeListColumn Header="January" Style="{StaticResource TreeListColumnStyle}" ap:BenDatagridValueProperty.DataGridValue="15">

15 is just a test value. And it does not sets value in datagrid columns to 15 (it does not call method SetDataGridValue(DependencyObject obj, string value). If I will write a default value in AttachedProperty, then I can see default value in cells.
Not sure where is error.

Body:
Try modify TreeListColumnStyle:

<Style x:Key="TreeListColumnStyle" TargetType="{x:Type dxg:TreeListColumn}">
   <Setter Property="HorizontalHeaderContentAlignment" Value="Center"/>
   <Setter Property="CellTemplate">
       <Setter.Value>
           <DataTemplate>
               <TextBlock ap:BenDatagridValueProperty.DataGridValue="{TemplateBinding ap:BenDatagridValueProperty.DataGridValue}" Text="{Binding Path=(ap:BenDatagridValueProperty.DataGridValue), RelativeSource={RelativeSource Self}}" TextAlignment="Center"/>
           </DataTemplate>
       </Setter.Value>
   </Setter>
</Style>


问:
MySQL Join Scenario
I know there are many "similar" questions, but I cannot figure out how to make this work. I am hoping it is quite simple for someone else!

I have a query that looks like the following:

```<code>SELECT
    d.name DishName,
    alt.name AllergyName
FROM meals_dish d
JOIN meals_dishingredient di ON di.dish_id = d.id
LEFT JOIN meals_food_allergytypes fat ON fat.food_id = di.food_id
LEFT JOIN meals_allergytypes alt ON alt.id = fat.allergytypes_id
GROUP BY d.id, alt.id
ORDER BY d.name
</code>```

that is giving me table similar to the following:

```<code>Dish Name               |    AllergyName
-----------------------------------------
Almond Pudding          |     NULL
Almond Pudding          |     Egg
Apple Cake              |     Milk
Apple Cake              |     Lactose
Apple Cake              |     Egg
Apple Cake              |     NULL
Avocado Chocolate Cream |     Milk
Avocado Chocolate Cream |     Lactose
Avocado Chocolate Cream |     NULL
Avocado Chocolate Cream |     Peanuts
Avocado Chocolate Cream |     Tree Nuts
Avocado Chocolate Cream |     Soy
Avocado Egg             |     NULL
Avocado Egg             |     Egg
Bacon Wrapped Asparagus |     NULL
Baked Cauliflower       |     NULL
Baked Cauliflower       |     Milk
Baked Cauliflower       |     Lactose
Baked Salmon            |     NULL
Baked Salmon            |     Milk
Baked Salmon            |     Lactose
</code>```

Now, what I would like to do, is to make a list of all dishes where any of the allergy names for a specific dish is not 'Egg', or etc.

For example, if I wanted to only get dishes that someone who could not eat Egg was, then I would run this query and should get back the dishes of Avocado Chocolate Cream, Bacon Wrapped Asparagus, Baked Cauliflower and Baked Salmon.

I have tried to set up some WHERE NOT IN, and other similar ones, but I continue to only remove a certain ingredient from the dish instead of just not selecting the dish. For example, in my attempted queries, with the 'Egg' example, Apple Cake would simply still return, but the specific row of 'Egg' would now not show.

答:
First, think about how to determine which dishes have "Egg" in them.

```<code>SELECT
   FoodAllergyTbl.dish_id
FROM
    `meals_food_allergytypes` AS FoodAllergyTbl
INNER JOIN
    `meals_allergytypes` AS AllergyTbl
     ON FoodAllergyTbl.allergy_types_id = AllergyTbl.id
WHERE
    AllergyTbl.name = 'Egg';
</code>```

Then you can select the list of dishes where the id isn't in the above listing.

```<code>SELECT
    name
FROM
    `meal_dish`
WHERE
    `id` NOT IN (
    SELECT
       FoodAllergyTbl.dish_id
    FROM
        `meals_food_allergytypes` AS FoodAllergyTbl
    INNER JOIN
        `meals_allergytypes` AS AllergyTbl
         ON FoodAllergyTbl.allergy_types_id = AllergyTbl.id
    WHERE
        AllergyTbl.name = 'Egg'
);
</code>```

Title: MySQL Join Scenario

Body:
I know there are many "similar" questions, but I cannot figure out how to make this work. I am hoping it is quite simple for someone else!

I have a query that looks like the following:

SELECT
    d.name DishName,
    alt.name AllergyName
FROM meals_dish d
JOIN meals_dishingredient di ON di.dish_id = d.id
LEFT JOIN meals_food_allergytypes fat ON fat.food_id = di.food_id
LEFT JOIN meals_allergytypes alt ON alt.id = fat.allergytypes_id
GROUP BY d.id, alt.id
ORDER BY d.name

that is giving me table similar to the following:

Dish Name               |    AllergyName
-----------------------------------------
Almond Pudding          |     NULL
Almond Pudding          |     Egg
Apple Cake              |     Milk
Apple Cake              |     Lactose
Apple Cake              |     Egg
Apple Cake              |     NULL
Avocado Chocolate Cream |     Milk
Avocado Chocolate Cream |     Lactose
Avocado Chocolate Cream |     NULL
Avocado Chocolate Cream |     Peanuts
Avocado Chocolate Cream |     Tree Nuts
Avocado Chocolate Cream |     Soy
Avocado Egg             |     NULL
Avocado Egg             |     Egg
Bacon Wrapped Asparagus |     NULL
Baked Cauliflower       |     NULL
Baked Cauliflower       |     Milk
Baked Cauliflower       |     Lactose
Baked Salmon            |     NULL
Baked Salmon            |     Milk
Baked Salmon            |     Lactose

Now, what I would like to do, is to make a list of all dishes where any of the allergy names for a specific dish is not 'Egg', or etc.

For example, if I wanted to only get dishes that someone who could not eat Egg was, then I would run this query and should get back the dishes of Avocado Chocolate Cream, Bacon Wrapped Asparagus, Baked Cauliflower and Baked Salmon.

I have tried to set up some WHERE NOT IN, and other similar ones, but I continue to only remove a certain ingredient from the dish instead of just not selecting the dish. For example, in my attempted queries, with the 'Egg' example, Apple Cake would simply still return, but the specific row of 'Egg' would now not show.

Body:
First, think about how to determine which dishes have "Egg" in them.

SELECT
   FoodAllergyTbl.dish_id
FROM
    `meals_food_allergytypes` AS FoodAllergyTbl
INNER JOIN
    `meals_allergytypes` AS AllergyTbl
     ON FoodAllergyTbl.allergy_types_id = AllergyTbl.id
WHERE
    AllergyTbl.name = 'Egg';

Then you can select the list of dishes where the id isn't in the above listing.

SELECT
    name
FROM
    `meal_dish`
WHERE
    `id` NOT IN (
    SELECT
       FoodAllergyTbl.dish_id
    FROM
        `meals_food_allergytypes` AS FoodAllergyTbl
    INNER JOIN
        `meals_allergytypes` AS AllergyTbl
         ON FoodAllergyTbl.allergy_types_id = AllergyTbl.id
    WHERE
        AllergyTbl.name = 'Egg'
);


问:
Magento - Dynamic Product Attribute Only Pulling Data from Single CMS Block
I have set up 2 extra tabs on my individual product pages which should be pulling information from a different CMS Block for each product.  However, when I view the product pages they are all pulling the exact same information from 1 of the CMS Blocks I've created and not from the CMS Block for that particular product.

Here's a few more things I noticed while trying to troubleshoot:

1) If I refresh the Magento cache and then go to a product page the correct information is displayed for that page.  Then if I navigate to any other product page it always shows the information from the first product I viewed after I refreshed the Magento cache.

2) This seems to be related to product categories as well.  I have 2 product categories.  Every product in Category 1 will show the same CMS Block's info.  Every product in Category 2 will show the same CMS Block's info, but the CMS Block's info for these products are actually different from the products in Category 1, but all the same.

Here's how I've set everything up:

1) Created separate CMS Blocks for each product each with different information.

2) Created a textarea attribute and added it to the correct attribute set.  For each product I have entered the ID to the CMS Block for that product.  I've double checked and every product has a different ID entered.

3) In app/design/frontend/rwd/default/layout/catalog.xml I have added the following to display the 2 new tabs:

```<code><!-- Features -->
<block type="catalog/product_view_attributes" name="product.features" as="features" template="catalog/product/view/features.phtml">
<action method="addToParentGroup"><group>detailed_info</group></action>
<action method="setTitle" translate="value"><value>Features</value></action>
</block>
<!-- END Features -->

<!-- TECH SPECS -->
<block type="catalog/product_view_attributes" name="product.tech_specs" as="techspecs" template="catalog/product/view/tech_specs.phtml">
<action method="addToParentGroup"><group>detailed_info</group></action>
<action method="setTitle" translate="value"><value>Tech Specs</value></action>
</block>
<!-- END TECH SPECS -->
</code>```

4) Lastly, I've created the 2 files

app/design/frontend/rwd/default/template/catalog/product/view/features.phtml
app/design/frontend/rwd/default/template/catalog/product/view/tech_specs.phtml

Here's the code:

features.phtml

```<code><?php
$_product = $this->getProduct();
$attribute = $_product->getResource()->getAttribute('features');

if ( is_object($attribute) ) {
    $identifier = $_product->getData("features");
}
?>

<?php if ($_sizeBlock = Mage::app()->getLayout()->createBlock('cms/block')->setBlockId($identifier)): ?>
    <div class="std">
        <?php echo $_sizeBlock->toHtml() ?>
    </div>
<?php endif; ?>
</code>```

tech_specs.phtml

```<code><?php
$_product = $this->getProduct();
$attribute = $_product->getResource()->getAttribute('tech_specs');
if ( is_object($attribute) ) {
    $identifier = $_product->getData("tech_specs");
}
?>

<?php if ($_sizeBlock = Mage::app()->getLayout()->createBlock('cms/block')->setBlockId($identifier)): ?>
    <div class="std">
        <?php echo $_sizeBlock->toHtml() ?>
    </div>
<?php endif; ?>
</code>```

Anyone have a clue what's going on here?

答:
If the attribute is dynamic, you can due a a hash with it's content and add it to the cache tag, see the example to a attribute that is a "yes" or "no" but if it changes the caches reloads ;)

After rewrites the bock from Magento 2.1 vendor in di.xml, do this:

```<code>namespace Dpl\Xxx\Block\Catalog\Product\View;

use Magento\Framework\Pricing\PriceCurrencyInterface;

class Attributes extends \Magento\Catalog\Block\Product\View\Attributes
{
    /**
     * Retrieve current product model
     *
     * @return \Magento\Catalog\Model\Product
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Framework\Registry $registry,
        PriceCurrencyInterface $priceCurrency,
        array $data = []
    ) {

        parent::__construct($context, $registry, $priceCurrency, $data);
        $this->setCacheTag($this->getProduct()->getId().'-'.$this->getProduct()->getXxxopen();
    }
}
?>
</code>```

Regards ;)

Body:
I have set up 2 extra tabs on my individual product pages which should be pulling information from a different CMS Block for each product.  However, when I view the product pages they are all pulling the exact same information from 1 of the CMS Blocks I've created and not from the CMS Block for that particular product.

Here's a few more things I noticed while trying to troubleshoot:

1) If I refresh the Magento cache and then go to a product page the correct information is displayed for that page.  Then if I navigate to any other product page it always shows the information from the first product I viewed after I refreshed the Magento cache.

2) This seems to be related to product categories as well.  I have 2 product categories.  Every product in Category 1 will show the same CMS Block's info.  Every product in Category 2 will show the same CMS Block's info, but the CMS Block's info for these products are actually different from the products in Category 1, but all the same.

Here's how I've set everything up:

1) Created separate CMS Blocks for each product each with different information.

2) Created a textarea attribute and added it to the correct attribute set.  For each product I have entered the ID to the CMS Block for that product.  I've double checked and every product has a different ID entered.

3) In app/design/frontend/rwd/default/layout/catalog.xml I have added the following to display the 2 new tabs:

<block type="catalog/product_view_attributes" name="product.features" as="features" template="catalog/product/view/features.phtml">
<action method="addToParentGroup"><group>detailed_info</group></action>
<action method="setTitle" translate="value"><value>Features</value></action>
</block>

<block type="catalog/product_view_attributes" name="product.tech_specs" as="techspecs" template="catalog/product/view/tech_specs.phtml">
<action method="addToParentGroup"><group>detailed_info</group></action>
<action method="setTitle" translate="value"><value>Tech Specs</value></action>
</block>

4) Lastly, I've created the 2 files

app/design/frontend/rwd/default/template/catalog/product/view/features.phtml
app/design/frontend/rwd/default/template/catalog/product/view/tech_specs.phtml

Here's the code:

features.phtml

<?php
$_product = $this->getProduct();
$attribute = $_product->getResource()->getAttribute('features');

if ( is_object($attribute) ) {
    $identifier = $_product->getData("features");
}
?>

<?php if ($_sizeBlock = Mage::app()->getLayout()->createBlock('cms/block')->setBlockId($identifier)): ?>

        <?php echo $_sizeBlock->toHtml() ?>

<?php endif; ?>

tech_specs.phtml

<?php
$_product = $this->getProduct();
$attribute = $_product->getResource()->getAttribute('tech_specs');
if ( is_object($attribute) ) {
    $identifier = $_product->getData("tech_specs");
}
?>

<?php if ($_sizeBlock = Mage::app()->getLayout()->createBlock('cms/block')->setBlockId($identifier)): ?>

        <?php echo $_sizeBlock->toHtml() ?>

<?php endif; ?>

Anyone have a clue what's going on here?

Body:
If the attribute is dynamic, you can due a a hash with it's content and add it to the cache tag, see the example to a attribute that is a "yes" or "no" but if it changes the caches reloads ;)

After rewrites the bock from Magento 2.1 vendor in di.xml, do this:

namespace Dpl\Xxx\Block\Catalog\Product\View;

use Magento\Framework\Pricing\PriceCurrencyInterface;

class Attributes extends \Magento\Catalog\Block\Product\View\Attributes
{
    /**
     * Retrieve current product model
     *
     * @return \Magento\Catalog\Model\Product
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Framework\Registry $registry,
        PriceCurrencyInterface $priceCurrency,
        array $data = []
    ) {

        parent::__construct($context, $registry, $priceCurrency, $data);
        $this->setCacheTag($this->getProduct()->getId().'-'.$this->getProduct()->getXxxopen();
    }
}
?>

Regards ;)


问:
Why is Arrays.setAll faster than Arrays.parallelSetAll in this case?
Why is Arrays.setAll faster than Arrays.parallelSetAll in this case?</p>

```<code>int[] array = new int[30000000];
Random rnd = new Random();
Arrays.parallelSetAll(array, i->rnd.nextInt(200));
</code>```

答:
From the javadoc:

Instances of java.util.Random are threadsafe. However, the concurrent
  use of the same java.util.Random instance across threads may encounter
  contention and consequent poor performance. Consider instead using
  ThreadLocalRandom in multithreaded designs.

ContentLicense: CC BY-SA 4.0

Body:
Why is Arrays.setAll faster than Arrays.parallelSetAll in this case?

int[] array = new int[30000000];
Random rnd = new Random();
Arrays.parallelSetAll(array, i->rnd.nextInt(200));


问:
How can I forward a message back to MessageReceived when I've called context.Wait in a LuisDialog intent handler?
I am building a small bot, which is working out nicely, but I am facing one flow issue that I just can't seem to get out of. I use a LuisDialog that interprets the user's message. Within a certain intent handler method, I display a carousel with a 'Unsubscribe' button in the panel, and call context.Wait(Uitschrijven) to handle the user's selection from the carousel.

This means that the next incoming message will hit this method:

```<code>private async Task Uitschrijven(IDialogContext context,IAwaitable<IMessageActivity> result)
{
    ...
}
</code>```

In this method, I'm expecting the user to have clicked a button from the carousel, which will send a message formatted something like "id:3". Of course, the user can just type some other new message rather than continuing this flow. The problem is that if they do, I that next message is received by my 'Uitschrijven' method, where it won't be handled correctly. How can I send it back to be re-interpreted by the LuisDialog, so that the correct intent is matched?

Ideally I would like to forward the message again to my MessageReceived function from my LuisDialog.

However, the Forward() method expect a resumeafter method, which I don't need.
There's also EndConversation, but it just ends the conversation without interpreting.

Does anyone know how to ensure that these new messages will be processed by the MessageReceived method so the user is able to continue in this scenario?

答:
This may be a good use case for a Scorable.  There will be some tradeoffs though.

Your user would just have to type "unsubscribe" at any point or click a button with the postback/imback value of "unsubscribe".  You can choose any text you desire as the recognized value.  This way your unsubscribe logic will run independent of any other logic and you will not get trapped in your flow as you are now.  Since the unsubscribe event will be handled by the global handler (Scorable)  you can just handle any other message sent by the user as you normally would, in your case in a LuisDialog.

If you do not want your user to be able to unsubscribe at any point this solution will probably not work for you.  In this case please post your code as @Ezequiel asked so we can better understand your flow.  This would not be the only way in which to handle your flow.

Here is some info to look over:

Scorable Video

Scorable Blog

Scorable Blog

Body:
I am building a small bot, which is working out nicely, but I am facing one flow issue that I just can't seem to get out of. I use a LuisDialog that interprets the user's message. Within a certain intent handler method, I display a carousel with a 'Unsubscribe' button in the panel, and call context.Wait(Uitschrijven) to handle the user's selection from the carousel.

This means that the next incoming message will hit this method:

private async Task Uitschrijven(IDialogContext context,IAwaitable<IMessageActivity> result)
{
    ...
}

In this method, I'm expecting the user to have clicked a button from the carousel, which will send a message formatted something like "id:3". Of course, the user can just type some other new message rather than continuing this flow. The problem is that if they do, I that next message is received by my 'Uitschrijven' method, where it won't be handled correctly. How can I send it back to be re-interpreted by the LuisDialog, so that the correct intent is matched?

Ideally I would like to forward the message again to my MessageReceived function from my LuisDialog.

However, the Forward() method expect a resumeafter method, which I don't need.
There's also EndConversation, but it just ends the conversation without interpreting.

Does anyone know how to ensure that these new messages will be processed by the MessageReceived method so the user is able to continue in this scenario?


问:
NotReadableError: Failed to allocate audiosource in Firefox for getUserMedia
Running the below snippet in my Firefox console returns the following error [FF/56.0.2 (64-bit) on Mac OS 10.13.1]:

MediaStreamError { name: "NotReadableError", message: "Failed to
  allocate audiosource", constraint: "", stack: "" }  (unknown)

```<code>// Sippet
navigator.mediaDevices
      .getUserMedia({
  audio: true,
  video: true
})
      .then(stream=>{
console.log(stream.getAudioTracks())
document.getElementById('storybook-preview-iframe').contentWindow.document.getElementById('video-camera').srcObject = stream
mr = new window.MediaRecorder(stream,  {
      mimeType: 'video/webm'
    })
mr.ondataavailable = console.log
})
      .catch(console.log)
</code>```

What is most troubling is it worked at one point, and then it stopped. As if something is permanently locked up... I have no way (as far as I can tell) to see what is wrong with the audio source.

I ran these insanity checks to no avail:

No other browsers or app were open and/or using camera

Restarted browser, and eventually restarted computer

I'm on a mac, and heard this would help #> sudo killall AppleCameraAssistant;sudo killall VDCAssistant. It did not.

Ran a separate script (https://jsfiddle.net/App7P/348/) but when I turned the audio to true (https://jsfiddle.net/3k89sy27/2/), I got the same error as above.

This example/demo page on getusermedia also garnered the same error: https://webrtc.github.io/samples/src/content/getusermedia/record/

Update: I've simplified the failure code even more.

```<code>navigator.mediaDevices.getUserMedia({
    audio: true
}).then(function (stream) {
    console.log(stream)
}).catch(console.log)
</code>```

Audio does not want to register.....

Even tried FF's own Test Pilot and that failed too https://testpilot.firefox.com/experiments/voice-fill/

答:
as @mrchestnut suggested, I downloaded Firefox Quantum (which was released as of Nov. 14th 2017) and it worked!

Blog Post on Mozilla:

https://blog.mozilla.org/blog/2017/11/14/introducing-firefox-quantum/

Download Quantum:

https://www.mozilla.org/en-US/firefox/new/?scene=2

Although this doesn't explain why it didn't work, it sure has sugar solved my problem.

Body:
Running the below snippet in my Firefox console returns the following error [FF/56.0.2 (64-bit) on Mac OS 10.13.1]:

MediaStreamError { name: "NotReadableError", message: "Failed to
  allocate audiosource", constraint: "", stack: "" }  (unknown)

// Sippet
navigator.mediaDevices
      .getUserMedia({
  audio: true,
  video: true
})
      .then(stream=>{
console.log(stream.getAudioTracks())
document.getElementById('storybook-preview-iframe').contentWindow.document.getElementById('video-camera').srcObject = stream
mr = new window.MediaRecorder(stream,  {
      mimeType: 'video/webm'
    })
mr.ondataavailable = console.log
})
      .catch(console.log)

What is most troubling is it worked at one point, and then it stopped. As if something is permanently locked up... I have no way (as far as I can tell) to see what is wrong with the audio source.

I ran these insanity checks to no avail:

No other browsers or app were open and/or using camera

Restarted browser, and eventually restarted computer

I'm on a mac, and heard this would help #> sudo killall AppleCameraAssistant;sudo killall VDCAssistant. It did not.

Ran a separate script (https://jsfiddle.net/App7P/348/) but when I turned the audio to true (https://jsfiddle.net/3k89sy27/2/), I got the same error as above.

This example/demo page on getusermedia also garnered the same error: https://webrtc.github.io/samples/src/content/getusermedia/record/

Update: I've simplified the failure code even more.

navigator.mediaDevices.getUserMedia({
    audio: true
}).then(function (stream) {
    console.log(stream)
}).catch(console.log)

Audio does not want to register.....

Even tried FF's own Test Pilot and that failed too https://testpilot.firefox.com/experiments/voice-fill/


问:
Xamarin forms application login using ASP.Net Web API
I have completed web part of my Project and deployed my website on azure. My project is designed on Web API Entity Framework. Now I need to design Mobile App of my project Cross Platform Xamarin. I know basics of Xamarin development but having difficulties in Login part. Following this tutorial I have done the followings

ApiServices.cs

```<code>public async Task LoginAsync(string userName, string password)
{
    var keyValues = new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("username",userName),
        new KeyValuePair<string, string>("password",password),
        new KeyValuePair<string, string>("grant_type","password"),
    };
    var request = new HttpRequestMessage(HttpMethod.Post, "http://epolleasy.azurewebsites.net/Token");

    request.Content = new FormUrlEncodedContent(keyValues);
    var client = new HttpClient();
    var response = await client.SendAsync(request);
    var content = await response.Content.ReadAsStringAsync();
    Debug.WriteLine(content);
}
</code>```

LoginViewModel.cs

```<code>public class LoginViewModel {

private ApiServices _apiServices = new ApiServices();
public string Username { get; set; }
public string Password { get; set; }
public ICommand LoginCommand
{
    get
    {
        return new Command(async() =>
        {
            await _apiServices.LoginAsync(Username, Password);
        });
    }
}
}
</code>```

LoginPage.xaml

```<code><StackLayout>
<Entry Text="{Binding Username}" Placeholder="Username"/>
<Entry Text="{Binding Password}" IsPassword="True" Placeholder="Password"/>
<Button Command="{Binding LoginCommand}" Text="Login"/>
<Button Text="Signup" Clicked="Button_OnClicked"/>
</StackLayout>
</code>```

The problem is, this all only generates a token just as shown in tutorial. I want to know what i need to do with this token or how can I get user to login in my application using my builtin project web APIs. I searched a lot but unable to find any good tutorial regarding this topic.

答:
Its probably a CSRF Token. PAss this in your Headers along with any further requests. The CSRF has a lifetime and is basically alive for that one session.

For further info see https://developer.xamarin.com/guides/xamarin-forms/enterprise-application-patterns/authentication-and-authorization/

Body:
I have completed web part of my Project and deployed my website on azure. My project is designed on Web API Entity Framework. Now I need to design Mobile App of my project Cross Platform Xamarin. I know basics of Xamarin development but having difficulties in Login part. Following this tutorial I have done the followings

ApiServices.cs

public async Task LoginAsync(string userName, string password)
{
    var keyValues = new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("username",userName),
        new KeyValuePair<string, string>("password",password),
        new KeyValuePair<string, string>("grant_type","password"),
    };
    var request = new HttpRequestMessage(HttpMethod.Post, "http://epolleasy.azurewebsites.net/Token");

    request.Content = new FormUrlEncodedContent(keyValues);
    var client = new HttpClient();
    var response = await client.SendAsync(request);
    var content = await response.Content.ReadAsStringAsync();
    Debug.WriteLine(content);
}

LoginViewModel.cs

public class LoginViewModel {

private ApiServices _apiServices = new ApiServices();
public string Username { get; set; }
public string Password { get; set; }
public ICommand LoginCommand
{
    get
    {
        return new Command(async() =>
        {
            await _apiServices.LoginAsync(Username, Password);
        });
    }
}
}

LoginPage.xaml

<StackLayout>
<Entry Text="{Binding Username}" Placeholder="Username"/>
<Entry Text="{Binding Password}" IsPassword="True" Placeholder="Password"/>
<Button Command="{Binding LoginCommand}" Text="Login"/>
<Button Text="Signup" Clicked="Button_OnClicked"/>
</StackLayout>

The problem is, this all only generates a token just as shown in tutorial. I want to know what i need to do with this token or how can I get user to login in my application using my builtin project web APIs. I searched a lot but unable to find any good tutorial regarding this topic.


问:
How to group result by region with pig latin?
I'm new to Hadoop PIG and I have a dataset that looks like this:

```<code>region_id        region         participation   score

    1             SSA               YES          10
    1             SSA               NO           22
    2             MONTPELIER        YES          15
    ....
</code>```

I want to calculate the sum of scores for each region. The final display that I'm looking for is :
REGION - SCORE, for example:

```<code>SSA - 32
</code>```

I loaded my data:

```<code>data = load '/user/cloudera/datapi/pigdata.csv' using PigStorage (',') AS
 (id:int, region:chararray, participation:chararray, score:int);
</code>```

Then grouped the data by region:

```<code>split_region = GROUP data by region;
</code>```

Finally:

```<code>RES= foreach split_region GENERATE SUM(data.score), data.region;
</code>```

the RES variable contains the sum of score for each region but it display all the occurrences of the region like so:

```<code>(32 , {SSA,SSA})
</code>```

What is the missing command/instruction to display (32, SSA) instead?

答:
Use  group instead of data.region

```<code>RES = foreach split_region GENERATE SUM(data.score), group;
</code>```

See here for source. When you use the GROUP operator,
The first field is named "group" (do not confuse this with the GROUP operator) and is the same type as the group key.

Body:
I'm new to Hadoop PIG and I have a dataset that looks like this:

region_id        region         participation   score

    1             SSA               YES          10
    1             SSA               NO           22
    2             MONTPELIER        YES          15
    ....

I want to calculate the sum of scores for each region. The final display that I'm looking for is :
REGION - SCORE, for example:

SSA - 32

I loaded my data:

data = load '/user/cloudera/datapi/pigdata.csv' using PigStorage (',') AS
 (id:int, region:chararray, participation:chararray, score:int);

Then grouped the data by region:

split_region = GROUP data by region;

Finally:

RES= foreach split_region GENERATE SUM(data.score), data.region;

the RES variable contains the sum of score for each region but it display all the occurrences of the region like so:

(32 , {SSA,SSA})

What is the missing command/instruction to display (32, SSA) instead?

Body:
Use  group instead of data.region

RES = foreach split_region GENERATE SUM(data.score), group;

See here for source. When you use the GROUP operator,
The first field is named "group" (do not confuse this with the GROUP operator) and is the same type as the group key.


答:
This looks like UTF-16 data.  So try

```<code>data[0].rstrip("\n").decode("utf-16")
</code>```

Edit (for your update):  Try to decode the whole file at once, that is

```<code>data = open(...).read()
data.decode("utf-16")
</code>```

The problem is that the line breaks in UTF-16 are "\n\x00", but using readlines() will split at the "\n", leaving the "\x00" character for the next line.

ContentLicense: CC BY-SA 2.5

Title: python: unicode problem

Body:
I am trying to decode a string I took from file:

file = open ("./Downloads/lamp-post.csv", 'r')
data = file.readlines()
data[0]

'\xff\xfeK\x00e\x00y\x00w\x00o\x00r\x00d\x00\t\x00C\x00o\x00m\x00p\x00e\x00t\x00i\x00t\x00i\x00o\x00n\x00\t\x00G\x00l\x00o\x00b\x00a\x00l\x00
  \x00M\x00o\x00n\x00t\x00h\x00l\x00y\x00
  \x00S\x00e\x00a\x00r\x00c\x00h\x00e\x00s\x00\t\x00D\x00e\x00c\x00
  \x002\x000\x001\x000\x00\t\x00N\x00o\x00v\x00
  \x002\x000\x001\x000\x00\t\x00O\x00c\x00t\x00
  \x002\x000\x001\x000\x00\t\x00S\x00e\x00p\x00
  \x002\x000\x001\x000\x00\t\x00A\x00u\x00g\x00
  \x002\x000\x001\x000\x00\t\x00J\x00u\x00l\x00
  \x002\x000\x001\x000\x00\t\x00J\x00u\x00n\x00
  \x002\x000\x001\x000\x00\t\x00M\x00a\x00y\x00
  \x002\x000\x001\x000\x00\t\x00A\x00p\x00r\x00
  \x002\x000\x001\x000\x00\t\x00M\x00a\x00r\x00
  \x002\x000\x001\x000\x00\t\x00F\x00e\x00b\x00
  \x002\x000\x001\x000\x00\t\x00J\x00a\x00n\x00
  \x002\x000\x001\x000\x00\t\x00A\x00d\x00
  \x00s\x00h\x00a\x00r\x00e\x00\t\x00S\x00e\x00a\x00r\x00c\x00h\x00
  \x00s\x00h\x00a\x00r\x00e\x00\t\x00E\x00s\x00t\x00i\x00m\x00a\x00t\x00e\x00d\x00
  \x00A\x00v\x00g\x00.\x00
  \x00C\x00P\x00C\x00\t\x00E\x00x\x00t\x00r\x00a\x00c\x00t\x00e\x00d\x00
  \x00F\x00r\x00o\x00m\x00
  \x00W\x00e\x00b\x00
  \x00P\x00a\x00g\x00e\x00\t\x00L\x00o\x00c\x00a\x00l\x00
  \x00M\x00o\x00n\x00t\x00h\x00l\x00y\x00
  \x00S\x00e\x00a\x00r\x00c\x00h\x00e\x00s\x00\n'

Adding ignore do not really help...:

In [69]: data[2]
  Out[69]: u'\u6700\u6100\u7200\u6400\u6500\u6e00\u2000\u6c00\u6100\u6d00\u7000\u2000\u7000\u6f00\u7300\u7400\u0900\u3000\u2e00\u3900\u3400\u0900\u3800\u3800\u3000\u0900\u2d00\u0900\u3300\u3200\u3000\u0900\u3300\u3900\u3000\u0900\u3300\u3900\u3000\u0900\u3400\u3800\u3000\u0900\u3500\u3900\u3000\u0900\u3500\u3900\u3000\u0900\u3700\u3200\u3000\u0900\u3700\u3200\u3000\u0900\u3300\u3900\u3000\u0900\u3300\u3200\u3000\u0900\u3200\u3600\u3000\u0900\u2d00\u0900\u2d00\u0900\ua300\u3200\u2e00\u3100\u3800\u0900\u2d00\u0900\u3400\u3800\u3000\u0a00'

In [70]: data[2].decode("utf-8",
  "replace")
  ---------------------------------------------------------------------------
  Traceback (most recent call last)

/Users/oleg/ in
  ()

/opt/local/lib/python2.5/encodings/utf_8.py
  in decode(input, errors)
       14
       15 def decode(input, errors='strict'):
  ---> 16     return codecs.utf_8_decode(input, errors,
  True)
       17
       18 class IncrementalEncoder(codecs.IncrementalEncoder):

:
  'ascii' codec can't encode characters
  in position 0-87: ordinal not in
  range(128)

In [71]:

Body:
This looks like UTF-16 data.  So try

data[0].rstrip("\n").decode("utf-16")

Edit (for your update):  Try to decode the whole file at once, that is

data = open(...).read()
data.decode("utf-16")

The problem is that the line breaks in UTF-16 are "\n\x00", but using readlines() will split at the "\n", leaving the "\x00" character for the next line.


问:
Code creates the Layers but does not draw the lines in autocad
This code does not work correctly. It does not draw the line and the polyline but creates the layers. I think the problem may be related to the transactions, but I'm not sure and I do not know how to solve it either.

This method is responsible for sending the parameters to the creation methods.

```<code>public static void DrawingLines()
{
    Document document = Application.DocumentManager.MdiActiveDocument;
    Database database = document.Database;

    // Verificando a existencia dos Layers, caso não existam, são criados
    CreatingLayer("P04", 4);
    CreatingLayer("TEXTO", 3);
    CreatingLayer("P01", 1);

    // Start a transaction
    using (Transaction transactionManager =
           database.TransactionManager.StartTransaction())
    {
        // Cria o triangulo da função
        var acPoly = new Polyline();
        acPoly.AddVertexAt(0, new Point2d(Variaveis.pt.X - 225,
                           Variaveis.pt.Y - 175), 0, 0, 0);
        acPoly.AddVertexAt(1, new Point2d(Variaveis.pt.X + 225,
                           Variaveis.pt.Y - 175), 0, 0, 0);
        acPoly.AddVertexAt(2, new Point2d(Variaveis.pt.X + 225,
                           Variaveis.pt.Y - 55), 0, 0, 0);
        acPoly.AddVertexAt(3, new Point2d(Variaveis.pt.X - 225,
                           Variaveis.pt.Y - 175), 0, 0, 0);
        acPoly.Layer = "P01";

        // Desenha a linha central cyan
        var acLine = new Line()
        {
            StartPoint = new Point3d(Variaveis.pt.X + 53, Variaveis.pt.Y -
                                     270, 0),
            EndPoint = new Point3d(Variaveis.pt.X + 53, Variaveis.pt.Y -
                                   513, 0)
        };

        acLine.Layer = "P04";

        // Add the new object to the block table record
        AddToModelSpace(acPoly);
        AddToModelSpace(acLine);
    }
}
</code>```

This method is responsible for checking if the Layer exists. If it does not exist, it creates.

```<code>public static void CreatingLayer(string layer, short color)
{
    Document document = Application.DocumentManager.MdiActiveDocument;
    Database database = document.Database;

    using (Transaction tr = database.TransactionManager.StartTransaction())
    {
        // Get the layer table from the drawing
        LayerTable lt = (LayerTable)tr.GetObject(database.LayerTableId,
                         OpenMode.ForRead);

        // Create our new layer table record...
        LayerTableRecord ltr = new LayerTableRecord();

        // Checa a existencia de P01, caso não exista, é criada
        if (lt.Has(layer) == true)
        {
            database.Clayer = lt[layer];
        }
        else
        {
            // ... and set its properties
            ltr.Name = layer;
            ltr.Color = Color.FromColorIndex(ColorMethod.ByAci, color);

            // Add the new layer to the layer table
            lt.UpgradeOpen();
            ObjectId ltId = lt.Add(ltr);
            tr.AddNewlyCreatedDBObject(ltr, true);

            // Set the layer to be current for this drawing
            database.Clayer = lt[layer];
        }

        // Se tudo ocorreu bem, grava a transação
        tr.Commit();
    }
}
</code>```

This method is responsible only for insert the entity in model space

```<code>public static void AddToModelSpace(Entity ent)
{
    Document document = Application.DocumentManager.MdiActiveDocument;
    Database database = document.Database;

    using (Transaction tr = database.TransactionManager.StartTransaction())
    {
        var blTbl = tr.GetObject(database.BlockTableId, OpenMode.ForRead) as
                                 BlockTable;
        var blTblRec = tr.GetObject(blTbl[BlockTableRecord.ModelSpace],
                                    OpenMode.ForWrite) as BlockTableRecord;

        blTblRec.AppendEntity(ent);
        tr.AddNewlyCreatedDBObject(ent, true);
        tr.Commit();
    }
}
</code>```

答:
I have never coded anything in AutoCAD environment, but inspecting your code it seems you are not committing the transaction in DrawingLines.

And that brings up an interesting point; why are you even creating a transaction in DrawingLines and immediately creating another one in AddToModelSpace? One of them seems absolutely unnecessary.

Body:
This code does not work correctly. It does not draw the line and the polyline but creates the layers. I think the problem may be related to the transactions, but I'm not sure and I do not know how to solve it either.

This method is responsible for sending the parameters to the creation methods.

public static void DrawingLines()
{
    Document document = Application.DocumentManager.MdiActiveDocument;
    Database database = document.Database;

    // Verificando a existencia dos Layers, caso não existam, são criados
    CreatingLayer("P04", 4);
    CreatingLayer("TEXTO", 3);
    CreatingLayer("P01", 1);

    // Start a transaction
    using (Transaction transactionManager =
           database.TransactionManager.StartTransaction())
    {
        // Cria o triangulo da função
        var acPoly = new Polyline();
        acPoly.AddVertexAt(0, new Point2d(Variaveis.pt.X - 225,
                           Variaveis.pt.Y - 175), 0, 0, 0);
        acPoly.AddVertexAt(1, new Point2d(Variaveis.pt.X + 225,
                           Variaveis.pt.Y - 175), 0, 0, 0);
        acPoly.AddVertexAt(2, new Point2d(Variaveis.pt.X + 225,
                           Variaveis.pt.Y - 55), 0, 0, 0);
        acPoly.AddVertexAt(3, new Point2d(Variaveis.pt.X - 225,
                           Variaveis.pt.Y - 175), 0, 0, 0);
        acPoly.Layer = "P01";

        // Desenha a linha central cyan
        var acLine = new Line()
        {
            StartPoint = new Point3d(Variaveis.pt.X + 53, Variaveis.pt.Y -
                                     270, 0),
            EndPoint = new Point3d(Variaveis.pt.X + 53, Variaveis.pt.Y -
                                   513, 0)
        };

        acLine.Layer = "P04";

        // Add the new object to the block table record
        AddToModelSpace(acPoly);
        AddToModelSpace(acLine);
    }
}

This method is responsible for checking if the Layer exists. If it does not exist, it creates.

public static void CreatingLayer(string layer, short color)
{
    Document document = Application.DocumentManager.MdiActiveDocument;
    Database database = document.Database;

    using (Transaction tr = database.TransactionManager.StartTransaction())
    {
        // Get the layer table from the drawing
        LayerTable lt = (LayerTable)tr.GetObject(database.LayerTableId,
                         OpenMode.ForRead);

        // Create our new layer table record...
        LayerTableRecord ltr = new LayerTableRecord();

        // Checa a existencia de P01, caso não exista, é criada
        if (lt.Has(layer) == true)
        {
            database.Clayer = lt[layer];
        }
        else
        {
            // ... and set its properties
            ltr.Name = layer;
            ltr.Color = Color.FromColorIndex(ColorMethod.ByAci, color);

            // Add the new layer to the layer table
            lt.UpgradeOpen();
            ObjectId ltId = lt.Add(ltr);
            tr.AddNewlyCreatedDBObject(ltr, true);

            // Set the layer to be current for this drawing
            database.Clayer = lt[layer];
        }

        // Se tudo ocorreu bem, grava a transação
        tr.Commit();
    }
}

This method is responsible only for insert the entity in model space

public static void AddToModelSpace(Entity ent)
{
    Document document = Application.DocumentManager.MdiActiveDocument;
    Database database = document.Database;

    using (Transaction tr = database.TransactionManager.StartTransaction())
    {
        var blTbl = tr.GetObject(database.BlockTableId, OpenMode.ForRead) as
                                 BlockTable;
        var blTblRec = tr.GetObject(blTbl[BlockTableRecord.ModelSpace],
                                    OpenMode.ForWrite) as BlockTableRecord;

        blTblRec.AppendEntity(ent);
        tr.AddNewlyCreatedDBObject(ent, true);
        tr.Commit();
    }
}


问:
When to close a UDP socket
I have a client-server application that uses a UDP socket to send the data , the data only have to travel from client to server , and the server will always have the same IP. The only requirement is that I have to send messages about 10 messages per second

Currently I am doing it the following way :

```<code>public void SendData(byte[] packet)
{
    IPEndPoint end_point = new IPEndPoint(serverIP, serverPort);
    UdpClient udpChannel = new UdpClient(sourcePort);
    udpChannel.Connect(end_point);
    udpChannel.Send(packet, packet.Length);
    udpChannel.Close();
}
</code>```

The problem I have is that when I use the command "udpChannel.Close()" it takes 2-3 seconds to be performed when the server is not listening. (I've seen the same problem in: What is the drawback if I do not invoke the UdpClient.Close() method?)

My question would be, if I always send packets to the same IP address and port, is it necessary to connect the socket and close it after each send request?

The code I intend to use would be as follows:

```<code>UdpClient udpChannel;

public void SendData(byte[] packet)
{
    udpChannel.Send(packet, packet.Length);
}

public void Initialize(IPAddress IP, int port)
{
    IPEndPoint end_point = new IPEndPoint(serverIP, serverPort);
    UdpClient udpChannel = new UdpClient(sourcePort);
    udpChannel.Connect(end_point);
}

public void Exit()
{
    udpChannel.Close();
}
</code>```

Doing it this way, would it be necessary to do some checking in the "SendData" method before sending the data?
Is there any problem in the above code?

Thank you!

答:
```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System.Text;
using System.Net.Sockets;
using System;
using System.Net;

public class Server : MonoBehaviour
{
    //int[] ports;
    UdpClient udp; // Udp client

    private void Start()
    {
        udp = new UdpClient(1234);
        udp.BeginReceive(Receive, null);
    }

    void Send(string msg, IPEndPoint ipe)
    {
        UdpClient sC = new UdpClient(0);
        byte[] m = Encoding.Unicode.GetBytes(msg);
        sC.Send(m, msg.Length * sizeof(char), ipe);
        Debug.Log("Sending: " + msg);
        sC.Close();
    }

    void Receive(IAsyncResult ar)
    {
        IPEndPoint ipe = new IPEndPoint(IPAddress.Any, 0);
        byte[] data = udp.EndReceive(ar, ref ipe);
        string msg = Encoding.Unicode.GetString(data);
        Debug.Log("Receiving: " + msg);

        udp.BeginReceive(Receive, null);
    }
}
</code>```

At the Send() I use new UDP CLient and close it after every time. Its better, u can send and receive at the same time.

Title: When to close a UDP socket

Body:
I have a client-server application that uses a UDP socket to send the data , the data only have to travel from client to server , and the server will always have the same IP. The only requirement is that I have to send messages about 10 messages per second

Currently I am doing it the following way :

public void SendData(byte[] packet)
{
    IPEndPoint end_point = new IPEndPoint(serverIP, serverPort);
    UdpClient udpChannel = new UdpClient(sourcePort);
    udpChannel.Connect(end_point);
    udpChannel.Send(packet, packet.Length);
    udpChannel.Close();
}

The problem I have is that when I use the command "udpChannel.Close()" it takes 2-3 seconds to be performed when the server is not listening. (I've seen the same problem in: What is the drawback if I do not invoke the UdpClient.Close() method?)

My question would be, if I always send packets to the same IP address and port, is it necessary to connect the socket and close it after each send request?

The code I intend to use would be as follows:

UdpClient udpChannel;

public void SendData(byte[] packet)
{
    udpChannel.Send(packet, packet.Length);
}

public void Initialize(IPAddress IP, int port)
{
    IPEndPoint end_point = new IPEndPoint(serverIP, serverPort);
    UdpClient udpChannel = new UdpClient(sourcePort);
    udpChannel.Connect(end_point);
}

public void Exit()
{
    udpChannel.Close();
}

Doing it this way, would it be necessary to do some checking in the "SendData" method before sending the data?
Is there any problem in the above code?

Thank you!

Body:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System.Text;
using System.Net.Sockets;
using System;
using System.Net;

public class Server : MonoBehaviour
{
    //int[] ports;
    UdpClient udp; // Udp client

    private void Start()
    {
        udp = new UdpClient(1234);
        udp.BeginReceive(Receive, null);
    }

    void Send(string msg, IPEndPoint ipe)
    {
        UdpClient sC = new UdpClient(0);
        byte[] m = Encoding.Unicode.GetBytes(msg);
        sC.Send(m, msg.Length * sizeof(char), ipe);
        Debug.Log("Sending: " + msg);
        sC.Close();
    }

    void Receive(IAsyncResult ar)
    {
        IPEndPoint ipe = new IPEndPoint(IPAddress.Any, 0);
        byte[] data = udp.EndReceive(ar, ref ipe);
        string msg = Encoding.Unicode.GetString(data);
        Debug.Log("Receiving: " + msg);

        udp.BeginReceive(Receive, null);
    }
}

At the Send() I use new UDP CLient and close it after every time. Its better, u can send and receive at the same time.


问:
Bigquery job fails if input data doesn't follow the table datatype
I'm used to running Hive queries on Hadoop and as per my experience even if input data doesn't follow the table datatype, the job doesn't fail.
For example: if input data "abc" routes to a table column having 'Integer' datatype then 'NULL' gets inserted for that particular value.

In Big query, I have observed that the job fails in case of data value not strictly following the column datatype.

file-00000000: CSV table encountered too many errors, giving up. Rows: 1; errors: 1. (error code: invalid)
query: Could not parse '2017-11-23' as a timestamp. Required format is YYYY-MM-DD HH:MM[:SS[.SSSSSS]]; Could not parse '2017-11-23' as datetime for field date (position 1) starting at location 0 (error code: invalidQuery)

For this example, if '2017-11-23' doesn't follow timestamp datatype then 'NULL' should have been inserted in the column rather than failing the job.

Is there any way to restrict this behavior? My job shouldn't fail whatever the data is. Any insights?

答:
A couple of options:

Use a STRING for the column type instead. With a query, you can transform the data e.g. using SAFE_CAST(timestamp_string AS TIMESTAMP) to get NULL values for invalid timestamps.

Use the configuration.load.maxBadRecords property to skip rows with invalid data. Note that this will omit the entire row if there is a bad value, however.


问:
Is Processing.js worth it?
I am holding back on seriously pursuing ProcessingJS pieces mostly due to the bloat of the library. I have found that pieces like Ball Droppings do not use the library's Processing syntax parser, which is good, since I imagine it would slow down the page more, especially adding to the initial load and setup time. Still, I am wondering if it's worthwhile to use it basically as a big utility library like UnderscoreJS. For example, how good is its implementation with SVG compared with the other libraries out there today like RaphaelJS? Has anyone gone through the implementation of the Processing API extensively enough? When I skim through the I see a lot of boilerplate I don't really need, as well as a couple instances of questionable coding practices. But the library still seems to perform decently, at least on the ProcessingJS homepage, although the examples are set to run at 15fps, and not the (in my opinion) minimally acceptable 24fps.

答:
I think it strongly depends on the project you are working on and the background knowledge you have with the processing library.

Processing.js is a great choice if you already have learned the original processing api (java) and want to leverage your existing knowledge in the web environment. It might be the only choice if you want to port an existing project to the web - actually this is probably the best time to use it.

If you are a JavaScript programmer and don't know much about processing you probably will dislike to write Java syntax in the browser and everything becomes even more problematic if you have to mix it with js. The API doesn't feel like JavaScript and there is a lot of code that could be written more elegantly.

Regarding performance it is not a bad choice, actually most projects run smoothly and I can definitely recommend using processing.js on circumstances like those explained above.

Here is great list of various javascript engines out there:
Javascript Graphic/Game Engines

It is hard to recommend a single library, as the requirements are specific to each project.
For simple graphics/diagrams: RaphaelJs is really nice and performs decently

Title: Is Processing.js worth it?


问:
How to turn off hover with Jquery?
I have a keyframe animation that lasts 6 seconds. What I want is : Every time I click on '.box', wait animation end (6 seconds),

```<code>$('.box').click(function() {
        $('.content').addClass("my-animation"); // this animation last 6 seconds
    });
</code>```

then activate this hover fonction :

```<code> $('.content').hover(function() {
// ... specific animation
}, function() {
// ...
});
</code>```

In other words I want to "turn off" the hover function only when #content is animated, because if I hover on my content while "my-animation" is running, it cancels.

EDIT html :

```<code><p class="box">see</p>
<p class="content faconC button-p"> title </p>
</code>```

答:
You can use off method to remove all handlers attached to hover event when animation start:</p>

```<code>$('.box').click(function() {
     // detach hover handler
     $('.content').off('hover', handler);

     // start animation
     $('.content').addClass("my-animation");

     // reattach handler after 6s
     setTimeout(function() {
         $content.on('hover', handler);
     }, 6000);
});

$content.on('hover', handler);

function handler(e) {

    if (e.type == "mouseenter") {
        // ... Specific animation
    } else { // mouseleave
        // ...
    }

}
</code>```

Title: How to turn off hover with Jquery?

Body:
I have a keyframe animation that lasts 6 seconds. What I want is : Every time I click on '.box', wait animation end (6 seconds),

$('.box').click(function() {
        $('.content').addClass("my-animation"); // this animation last 6 seconds
    });

then activate this hover fonction :

 $('.content').hover(function() {
// ... specific animation
}, function() {
// ...
});

In other words I want to "turn off" the hover function only when #content is animated, because if I hover on my content while "my-animation" is running, it cancels.

EDIT html :

see

 title

Body:
You can use off method to remove all handlers attached to hover event when animation start:

$('.box').click(function() {
     // detach hover handler
     $('.content').off('hover', handler);

     // start animation
     $('.content').addClass("my-animation");

     // reattach handler after 6s
     setTimeout(function() {
         $content.on('hover', handler);
     }, 6000);
});

$content.on('hover', handler);

function handler(e) {

    if (e.type == "mouseenter") {
        // ... Specific animation
    } else { // mouseleave
        // ...
    }

}


问:
Code splitting/react-loadable issue
I'm trying to introduce code splitting into my app using react-loadable.  I tried it on a very simple component:

```<code>const LoadableComponent = Loadable({
    loader: () => import('components/Shared/Logo/Logo'),
    loading: <div>loading</div>,
});
</code>```

However, when this component is rendered, I get the following error:

```<code>Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.

Check the render method of `LoadableComponent`.
    in LoadableComponent (created by AppHeader)
    in div (created by AppHeader)
    in AppHeader (created by PlainChatApp)
    in div (created by PlainChatApp)
    in PlainChatApp (created by DragDropContext(PlainChatApp))
    in DragDropContext(PlainChatApp) (created by Connect(DragDropContext(PlainChatApp)))
    in Connect(DragDropContext(PlainChatApp))
    in Provider
    in AppContainer
    in ErrorBoundary

The above error occurred in the <LoadableComponent> component:
    in LoadableComponent (created by AppHeader)
    in div (created by AppHeader)
    in AppHeader (created by PlainChatApp)
    in div (created by PlainChatApp)
    in PlainChatApp (created by DragDropContext(PlainChatApp))
    in DragDropContext(PlainChatApp) (created by Connect(DragDropContext(PlainChatApp)))
    in Connect(DragDropContext(PlainChatApp))
    in Provider
    in AppContainer
    in ErrorBoundary
</code>```

I don't see anything obvious that I'm doing wrong, and I'm unable to file an issue in that repo.

答: Turns out that you need to pass a component to the loading option and not JSX.  The documentation clearly says this, I just missed it.

Title: Code splitting/react-loadable issue

Body:
I'm trying to introduce code splitting into my app using react-loadable.  I tried it on a very simple component:

const LoadableComponent = Loadable({
    loader: () => import('components/Shared/Logo/Logo'),
    loading:
loading
,
});

However, when this component is rendered, I get the following error:

Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.

Check the render method of `LoadableComponent`.
    in LoadableComponent (created by AppHeader)
    in div (created by AppHeader)
    in AppHeader (created by PlainChatApp)
    in div (created by PlainChatApp)
    in PlainChatApp (created by DragDropContext(PlainChatApp))
    in DragDropContext(PlainChatApp) (created by Connect(DragDropContext(PlainChatApp)))
    in Connect(DragDropContext(PlainChatApp))
    in Provider
    in AppContainer
    in ErrorBoundary

The above error occurred in the <LoadableComponent> component:
    in LoadableComponent (created by AppHeader)
    in div (created by AppHeader)
    in AppHeader (created by PlainChatApp)
    in div (created by PlainChatApp)
    in PlainChatApp (created by DragDropContext(PlainChatApp))
    in DragDropContext(PlainChatApp) (created by Connect(DragDropContext(PlainChatApp)))
    in Connect(DragDropContext(PlainChatApp))
    in Provider
    in AppContainer
    in ErrorBoundary

I don't see anything obvious that I'm doing wrong, and I'm unable to file an issue in that repo.


问:
Python Code to Display fullscreen in main object (tkinter and PIL)
With this code I can display an Image in full screen mode.

```<code>from tkinter import *
from PIL import Image, ImageTk

def showPIL(pilImage):
    root = Tk()
    w, h = root.winfo_screenwidth(), root.winfo_screenheight()
    root.overrideredirect(1)
    root.geometry("%dx%d+0+0" % (w, h))
    root.focus_set()
    root.bind("<Escape>", lambda e: (e.widget.withdraw(), e.widget.destroy()))
    canvas = Canvas(root, width=w, height=h)
    canvas.pack()
    canvas.configure(background='black')
    imgWidth, imgHeight = pilImage.size
    if imgWidth > w or imgHeight > h:
        ratio = min(w / imgWidth, h / imgHeight)
        imgWidth = int(imgWidth * ratio)
        imgHeight = int(imgHeight * ratio)
        pilImage = pilImage.resize((imgWidth, imgHeight), Image.ANTIALIAS)
    image = ImageTk.PhotoImage(pilImage)
    imagesprite = canvas.create_image(w / 2, h / 2, image=image)
    root.mainloop()

img1 = Image.open("img1.png")
img2 = Image.open('img2.png')

while True:
    n = int(input('Numero: '))
    if n == 1:
        showPIL(img1)
        continue
    elif n == 2:
        showPIL(img2)
        continue
    else:
        break
</code>```

But I have a problem...
The image that opens does not come as the main object on the screen, sometimes it is behind some open window or program ... How do I leave as the main screen?

答:
You can put this root.attributes("-topmost", True) under that
  root.bind. @StevoMitric

that solved my question.

Body:
With this code I can display an Image in full screen mode.

from tkinter import *
from PIL import Image, ImageTk

def showPIL(pilImage):
    root = Tk()
    w, h = root.winfo_screenwidth(), root.winfo_screenheight()
    root.overrideredirect(1)
    root.geometry("%dx%d+0+0" % (w, h))
    root.focus_set()
    root.bind("<Escape>", lambda e: (e.widget.withdraw(), e.widget.destroy()))
    canvas = Canvas(root, width=w, height=h)
    canvas.pack()
    canvas.configure(background='black')
    imgWidth, imgHeight = pilImage.size
    if imgWidth > w or imgHeight > h:
        ratio = min(w / imgWidth, h / imgHeight)
        imgWidth = int(imgWidth * ratio)
        imgHeight = int(imgHeight * ratio)
        pilImage = pilImage.resize((imgWidth, imgHeight), Image.ANTIALIAS)
    image = ImageTk.PhotoImage(pilImage)
    imagesprite = canvas.create_image(w / 2, h / 2, image=image)
    root.mainloop()

img1 = Image.open("img1.png")
img2 = Image.open('img2.png')

while True:
    n = int(input('Numero: '))
    if n == 1:
        showPIL(img1)
        continue
    elif n == 2:
        showPIL(img2)
        continue
    else:
        break

But I have a problem...
The image that opens does not come as the main object on the screen, sometimes it is behind some open window or program ... How do I leave as the main screen?


问:
TypeConverter vs. Convert vs. TargetType.Parse
As far as I know, there are at least 3 ways to convert data types in .NET:

using System.ComponentModel.TypeConverter

```<code>var conv = System.ComponentModel.TypeDescriptor.GetConverter(typeof(int));
var i1 = (int)conv.ConvertFrom("123");
</code>```

using System.Convert.ChangeType():

```<code>var i2 = (int) Convert.ChangeType("123", typeof (int));
</code>```

using the Parse/TryParse methods of the destination type:

```<code>var i3 = int.Parse("123"); // or TryParse
</code>```

Are there any guidelines or rules-of-thumb when to use which method to convert between the .NET base data types (especially from string to some other data type)?

答:
Convert

Convert class uses the IConvertible methods implemented in the target type.

Unfortunately, implementing IConvertible means writing lots of boilerplate code and Convert.ChangeType causes boxing if the target type is a struct.

TypeConverterAttribute

TypeDescriptor.GetConverter uses the TypeConverterAttribute and IMHO offers both a better API to convert a type and a more elegant way to make a type convertible. But it suffers the same performance issues with the Convert class, caused by the methods not being generic.

Parse/TryParse

Using T.Parse/T.TryParse methods is the de facto way of creating an object from a string since it doesn't involve unnecessary boxing. They also usually have overloads that provide greater control of how to parse the string.

TryParse methods allow you to handle cases where the string you want to parse is obtained from user input or another mean that doesn't guarantee a properly formatted string, without throwing exceptions.

So you should call the type's Parse/TryParse methods when you can and fallback to the other ways only when you don't know the target type in the compile time, i.e. when you only have a Type object that represents your target type.

You can also have look at my little library called ValueString that finds the most suitable parsing method of a type and uses it to parse the string.

Body:
As far as I know, there are at least 3 ways to convert data types in .NET:

using System.ComponentModel.TypeConverter

var conv = System.ComponentModel.TypeDescriptor.GetConverter(typeof(int));
var i1 = (int)conv.ConvertFrom("123");

using System.Convert.ChangeType():

var i2 = (int) Convert.ChangeType("123", typeof (int));

using the Parse/TryParse methods of the destination type:

var i3 = int.Parse("123"); // or TryParse

Are there any guidelines or rules-of-thumb when to use which method to convert between the .NET base data types (especially from string to some other data type)?


问:
So I'm trying to make a code where you make an array with inputs and the outputs aren't quite right?
Ok so this is my code:

```<code>import java.util.Scanner;
public class Bubble {

    public static void main(String[] args) {
        String prefix;
        int arr[];
        Scanner reader = new Scanner(System.in);
        System.out.println("What size would you like your array to be?");
        int arrSize = reader.nextInt();
        arr = new int[arrSize];
        for(int i = 1; i==arrSize; i++) {
            if((i % 10)==1 && i != 11) {
                prefix = "st";
            }else if((i % 10)==2 && i != 12) {
                prefix = "nd";
            }else if((i % 10)==3 && i != 13) {
                prefix = "rd";
            }else{
                prefix = "th";
            }

            System.out.println("What would you like the"+ i + prefix +"number in the array to be?");
            int arrNum = reader.nextInt();

        }
        System.out.println(arr);
    }

}
</code>```

Now when I press run I get this:

What size would you like your array to be?

Then I put in an integer, say 3, then I get this:

[I@55f96302

It stays the same no matter what integer i use.

答:
Use Arrays.toString().  Here's a great writeup of exactly the issue you're running into. By writing System.out.println(arr); you're printing a default string representation of your array. Check this answer.

As far as I could understand, you're trying to allow a user to create an array with arrSize and after this allow him to put values inside the array. However, your code has some issues:

1 - Your condition in your for loop is never verified for arrSize != 1.

2 - To save the values inside the defined array you should assign the value read from scanner arrNum to the array position i-1 (in order to avoid an ArrayIndexOutOfBoundsException).

3 - DO NOT FORGET to close Scanner. It is very important, since it can lead to memory leaks during the execution of a program if you don't close it.

Below you can find the modifications to your code.

Full Code

```<code>import java.util.Arrays;
import java.util.Scanner;
public class Bubble {

    public static void main(String[] args) {
        String prefix;
        int arr[];
        Scanner reader = new Scanner(System.in);
        System.out.println("What size would you like your array to be?");
        int arrSize = reader.nextInt();
        arr = new int[arrSize];
        for(int i = 1; i<=arrSize; i++) {

            if((i % 10)==1 && i != 11) {
                prefix = "st";
            }else if((i % 10)==2 && i != 12) {
                prefix = "nd";
            }else if((i % 10)==3 && i != 13) {
                prefix = "rd";
            }else{
                prefix = "th";
            }

            System.out.println("What would you like the "+ i + prefix +" number in the array to be?");
            int arrNum = reader.nextInt();
            arr[i-1] = arrNum;
        }

        reader.close();
        System.out.println(Arrays.toString(arr));
    }
}
</code>```

Body:
Ok so this is my code:

import java.util.Scanner;
public class Bubble {

    public static void main(String[] args) {
        String prefix;
        int arr[];
        Scanner reader = new Scanner(System.in);
        System.out.println("What size would you like your array to be?");
        int arrSize = reader.nextInt();
        arr = new int[arrSize];
        for(int i = 1; i==arrSize; i++) {
            if((i % 10)==1 && i != 11) {
                prefix = "st";
            }else if((i % 10)==2 && i != 12) {
                prefix = "nd";
            }else if((i % 10)==3 && i != 13) {
                prefix = "rd";
            }else{
                prefix = "th";
            }

            System.out.println("What would you like the"+ i + prefix +"number in the array to be?");
            int arrNum = reader.nextInt();

        }
        System.out.println(arr);
    }

}

Now when I press run I get this:

What size would you like your array to be?

Then I put in an integer, say 3, then I get this:

[I@55f96302

It stays the same no matter what integer i use.

Body:
Use Arrays.toString().  Here's a great writeup of exactly the issue you're running into. By writing System.out.println(arr); you're printing a default string representation of your array. Check this answer.

As far as I could understand, you're trying to allow a user to create an array with arrSize and after this allow him to put values inside the array. However, your code has some issues:

1 - Your condition in your for loop is never verified for arrSize != 1.

2 - To save the values inside the defined array you should assign the value read from scanner arrNum to the array position i-1 (in order to avoid an ArrayIndexOutOfBoundsException).

3 - DO NOT FORGET to close Scanner. It is very important, since it can lead to memory leaks during the execution of a program if you don't close it.

Below you can find the modifications to your code.

Full Code

import java.util.Arrays;
import java.util.Scanner;
public class Bubble {

    public static void main(String[] args) {
        String prefix;
        int arr[];
        Scanner reader = new Scanner(System.in);
        System.out.println("What size would you like your array to be?");
        int arrSize = reader.nextInt();
        arr = new int[arrSize];
        for(int i = 1; i<=arrSize; i++) {

            if((i % 10)==1 && i != 11) {
                prefix = "st";
            }else if((i % 10)==2 && i != 12) {
                prefix = "nd";
            }else if((i % 10)==3 && i != 13) {
                prefix = "rd";
            }else{
                prefix = "th";
            }

            System.out.println("What would you like the "+ i + prefix +" number in the array to be?");
            int arrNum = reader.nextInt();
            arr[i-1] = arrNum;
        }

        reader.close();
        System.out.println(Arrays.toString(arr));
    }
}


问:
Is this the right way to test if a field has been left empty?
This is inside a function, so that any textField passed as argument can respond to the method checkForEmptyFields:

```<code>textField.addTarget(self, action: #selector(checkForEmptyFields(sender:)),
for: UIControlEvents.editingChanged)
</code>```

This is the method checkForEmptyFields:

```<code> func checkForEmptyFields(sender:UITextField){

        self.loginButton.isEnabled = (sender.text?.trim().isEmpty)! == false

    }
</code>```

This is a simple extension of String for manage the trimming:

```<code>extension String
{
    func trim() -> String
    {
        return self.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
    }
}
</code>```

Anything seems to work just fine but I'd like to know if this is the right way to proceed and if I forgot something important (or I made any mistake). Thanks!

答:
It would probably be safer to also ensure that the text is not nil.

```<code>func checkForEmptyFields(sender: UITextField) {
    let isTextEmpty = sender.text?.trim().isEmpty ?? true
    self.loginButton.isEnabled = !isTextEmpty
}
</code>```

Your overall approach seems fine though.

As @matt has suggested in the comments, it's possible to encapsulate some of this behavior into an extension on UITextField.

```<code>extension UITextField {
    var isEmpty: Bool {
        return self.text?.trim().isEmpty ?? true
    }
}
</code>```

Your function could be simplified to this:

```<code>func checkForEmptyFields(sender: UITextField) {
    self.loginButton.isEnabled = !sender.isEmpty
}
</code>```

A side note: The "Swiftier" name for your extension is trimmed(), as it is returning a new String instance. This adheres to the Swift API Design Guidelines.

Body:
This is inside a function, so that any textField passed as argument can respond to the method checkForEmptyFields:

textField.addTarget(self, action: #selector(checkForEmptyFields(sender:)),
for: UIControlEvents.editingChanged)

This is the method checkForEmptyFields:

 func checkForEmptyFields(sender:UITextField){

        self.loginButton.isEnabled = (sender.text?.trim().isEmpty)! == false

    }

This is a simple extension of String for manage the trimming:

extension String
{
    func trim() -> String
    {
        return self.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
    }
}

Anything seems to work just fine but I'd like to know if this is the right way to proceed and if I forgot something important (or I made any mistake). Thanks!

Body:
It would probably be safer to also ensure that the text is not nil.

func checkForEmptyFields(sender: UITextField) {
    let isTextEmpty = sender.text?.trim().isEmpty ?? true
    self.loginButton.isEnabled = !isTextEmpty
}

Your overall approach seems fine though.

As @matt has suggested in the comments, it's possible to encapsulate some of this behavior into an extension on UITextField.

extension UITextField {
    var isEmpty: Bool {
        return self.text?.trim().isEmpty ?? true
    }
}

Your function could be simplified to this:

func checkForEmptyFields(sender: UITextField) {
    self.loginButton.isEnabled = !sender.isEmpty
}

A side note: The "Swiftier" name for your extension is trimmed(), as it is returning a new String instance. This adheres to the Swift API Design Guidelines.


问:
CSS for making an image responsive both to width and visible height of the containing element
I need the image to take the entire width of the container unless the resulting height is bigger then the available container's viewport height.

Basically I want the image to be responsive but also that it should still fit the screen. If it doesn't fit the screen it should be scaled down, horizontally centered, and preferably added with black tiles on its sides.

Currently, my CSS class looks like this:

```<code>.img-responsive{
  display: block;
  max-width: 100%;
  min-width: 100%;
  height: auto;
}
</code>```

I've tried to play around with max-height on the image, or on a dedicated container, nothing seemed to do the trick by pure CSS.

Clarifications:

I don't know the images dimensions in advance so can't just put them in a container with a preset size.

Basically, my goal is for the images to be always fully visible on the screen (if you scroll to the image) and take up the largest possible surface.

Here's a more detailed example:

Let's say I have scrollable container with a lot of content. The container takes up the entire viewport width (let's say its 500px) and the available visible height of the container is the entire viewport height minus a navbar height (let's say 1000px).

I can't know in advance what's the container's visible dimensions as it can always change.

Inside the container there's whatever, text, images, etc.

Now, for a given image, here are possible scenarios:

If the image is 500x800, it should be presented as is, as it takes up the entire available width, and height is no bigger then the container's visible height.

If the image is 500x2000, it should be scaled down to 250x1000
and horizontally centered. This will take up the entire visible container's height, and keep the image's aspect ratio

If the image is 250x300, it should be scaled up to 500x600, taking up the entire available width

If the image is 200x500, it should be scaled up to 400x1000, taking up the entire available height

If the image is 1000x1000, it should be scaled down to 500x500, taking up the entire available width

Here's a JSFiddle explaining the problem

答:
evilgenious448 answer comes really close, just that it only works with background images. What I have is:

```<code><html>
<head>
<style>
    body {
        margin: 0px;
    }

    .holder {
        background-image: url('image1.JPG');
        background-size: contain;
        background-position: center center;
        width: 100vw;
        height: 100vh;
        background-repeat: no-repeat;
    }
</style>
</head>
<body>
    <div class="holder">
        <div class="inner">
        </div>
    </div>
</body>
</html>
</code>```

I do not know how to size the inner div equally to the image.

Body:
I need the image to take the entire width of the container unless the resulting height is bigger then the available container's viewport height.

Basically I want the image to be responsive but also that it should still fit the screen. If it doesn't fit the screen it should be scaled down, horizontally centered, and preferably added with black tiles on its sides.

Currently, my CSS class looks like this:

.img-responsive{
  display: block;
  max-width: 100%;
  min-width: 100%;
  height: auto;
}

I've tried to play around with max-height on the image, or on a dedicated container, nothing seemed to do the trick by pure CSS.

Clarifications:

I don't know the images dimensions in advance so can't just put them in a container with a preset size.

Basically, my goal is for the images to be always fully visible on the screen (if you scroll to the image) and take up the largest possible surface.

Here's a more detailed example:

Let's say I have scrollable container with a lot of content. The container takes up the entire viewport width (let's say its 500px) and the available visible height of the container is the entire viewport height minus a navbar height (let's say 1000px).

I can't know in advance what's the container's visible dimensions as it can always change.

Inside the container there's whatever, text, images, etc.

Now, for a given image, here are possible scenarios:

If the image is 500x800, it should be presented as is, as it takes up the entire available width, and height is no bigger then the container's visible height.

If the image is 500x2000, it should be scaled down to 250x1000
and horizontally centered. This will take up the entire visible container's height, and keep the image's aspect ratio

If the image is 250x300, it should be scaled up to 500x600, taking up the entire available width

If the image is 200x500, it should be scaled up to 400x1000, taking up the entire available height

If the image is 1000x1000, it should be scaled down to 500x500, taking up the entire available width

Here's a JSFiddle explaining the problem

Body:
evilgenious448 answer comes really close, just that it only works with background images. What I have is:

<html>
<head>
<style>
    body {
        margin: 0px;
    }

    .holder {
        background-image: url('image1.JPG');
        background-size: contain;
        background-position: center center;
        width: 100vw;
        height: 100vh;
        background-repeat: no-repeat;
    }
</style>
</head>
<body>
    <div class="holder">
        <div class="inner">
        </div>
    </div>
</body>
</html>

I do not know how to size the inner div equally to the image.


问:
RecyclerView scroll to drag and dissmiss
I have overlay view that is animated from top. In that scene i have recycler view with elements list.

When user scrolls list to the end, scrolling further should scroll the whole recyclerview up (uncovering view beneath) and on ACTION_UP should animate recycler out of the screen.

overriding onTouch events doesn't work :

RecyclerView.setOnTouch() - causes dragging to glitch

ParentView.setOnTouch() - works only when dragging other views (not RecyclerView it self).

It's like new Tinder scroll that uncovers reactions (2017-11-17)

Any ideas how to do it?

答:
Try this :

```<code>  recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
        }
    });
</code>```

In the onScrolled method you can translate the whole recyclerView.

To check if you have reached the end then use this method in the onScrolled method

```<code>recyclerView.canScrollVertically(1);
</code>```

This will return a boolean. Then you can check and move the view.
Hope this helps.

Body:
Try this :

  recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
        }
    });

In the onScrolled method you can translate the whole recyclerView.

To check if you have reached the end then use this method in the onScrolled method

recyclerView.canScrollVertically(1);

This will return a boolean. Then you can check and move the view.
Hope this helps.