问:
android shared element transition with fragments doesn't show exit animation
I have a main activity that handles the static elements, attached to the main activity there is a fragment, this fragment has a tablelayout with a viewpager2, each page shows a recycler view.
The shared element transition works well from FRAGMENT A(Tab_1) to FRAGMENT B(ElementDetails), but when I press the back button, the return shared element transition doesn't work.

TAb_1(Fragment A):

```<code>public class tab1_anime extends Fragment {
    private RecyclerView recycler_view;
    public static AFSGAdapter adapter;
    private ArrayList<AddElement> a_list = new ArrayList<>();
    private Context context;

    public tab1_anime(){ };

    @Override
    public void onCreate(Bundle savedInstancesState) {
        super.onCreate(savedInstancesState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstancesState) {
        View view = inflater.inflate(R.layout.fragment_tab1_anime, container, false);
        recycler_view = view.findViewById(R.id.recycler_view);
        recycler_view.setHasFixedSize(true);
        context = getActivity();
        LinearLayoutManager layoutManager_anime_crucial = new GridLayoutManager(getContext(), 3, GridLayoutManager.VERTICAL, false);
        recycler_view.setLayoutManager(layoutManager_anime_crucial);
        recycler_view.setItemAnimator(new DefaultItemAnimator());
        int spanCount = 3; // 3 columns
        int spacing = 10; // 10 for my phone, 35 for the emulator
        boolean includeEdge = true;
        recycler_view.addItemDecoration(new GridSpacingItemDecoration(spanCount, spacing, includeEdge));
        adapter = new AFSGAdapter(a_list, getContext(), this);
        adapter.setDataSet(a_list);
        recycler_view.setAdapter(adapter);
        recycler_view.scheduleLayoutAnimation();
        adapter.notifyDataSetChanged();
        return view;
    }

    public void openShowElementFragment(int position, View view) {
        AddElement element = a_list.get(position);
        ShowElementFragment showElementFragment = new ShowElementFragment();
        Bundle bundle = new Bundle();
        bundle.putString("transitionName", "transition" + position);
        bundle.putSerializable("element", element);
        showElementFragment.setArguments(bundle);
        ((MainActivity) context).showFragmentWithTransition(this, showElementFragment, "showElementFragment", view, "transition" + position);
    }
}
</code>```

ShoeElementDetails(Fragment B):

```<code>public class ShowElementFragment extends Fragment {
private AddElement elemento;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_show_element, parent, false);
    //showelement_background_image.setTransitionName("example_transition");
    Bundle b = getArguments();
    if (b != null) {
        String transitionName = b.getString("transitionName");
        elemento = (AddElement) b.getSerializable("element");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            showelement_image.setTransitionName(transitionName);
        }
    }

    //postponeEnterTransition();

    Glide.with(this)
            .load(elemento.image_url)
            .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
            .skipMemoryCache(false)
            .apply(RequestOptions.bitmapTransform(new BlurTransformation(10, 3)))
            .into(showelement_background_image);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        getActivity().getWindow().getSharedElementEnterTransition().setDuration(800);//.setInterpolator(new AccelerateInterpolator());
        getActivity().getWindow().getSharedElementReturnTransition().setDuration(850);//.setInterpolator(new DecelerateInterpolator());
    }

    showelement_backarrow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            getActivity().getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fragmentHolder, new MainFragment())
                    .commit();
            //startActivity(new Intent(ShowElementActivity.this, AnimeActivity.class));
        }
    });
    return view;
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    postponeEnterTransition();
    OneShotPreDrawListener.add(view, this::startPostponedEnterTransition);
    super.onViewCreated(view, savedInstanceState);
   }

}
</code>```

Inside the adapter I handle the click of the element to start the transition:

inside adapter:

```<code>holder.itemView.setOnClickListener(new View.OnClickListener() {
        @SuppressLint("ClickableViewAccessibility")
        @Override
        public void onClick(View v) {
            fragment.openShowElementFragment(holder.getAdapterPosition(), v.findViewById(R.id.main_image));
        }
    });
</code>```

the openShowElementFragment called is inside main activity:

```<code>public void showFragmentWithTransition(Fragment current, Fragment newFragment, String tag, View sharedView, String sharedElementName) {
    FragmentManager fragmentManager = getSupportFragmentManager();
    // check if the fragment is in back stack
    boolean fragmentPopped = fragmentManager.popBackStackImmediate(tag, 0);
    if (fragmentPopped) {
        // fragment is pop from backStack
    } else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            current.setSharedElementReturnTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));
            current.setExitTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));

            newFragment.setSharedElementEnterTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));
            newFragment.setEnterTransition(TransitionInflater.from(this).inflateTransition(android.R.transition.no_transition));
        }
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.fragmentHolder, newFragment, tag);
        fragmentTransaction.addToBackStack(tag);
        fragmentTransaction.addSharedElement(sharedView, sharedElementName);
        fragmentTransaction.commit();
    }
}
</code>```

It's my first time approaching with fragments.

Body:
I have a main activity that handles the static elements, attached to the main activity there is a fragment, this fragment has a tablelayout with a viewpager2, each page shows a recycler view.
The shared element transition works well from FRAGMENT A(Tab_1) to FRAGMENT B(ElementDetails), but when I press the back button, the return shared element transition doesn't work.

TAb_1(Fragment A):

public class tab1_anime extends Fragment {
    private RecyclerView recycler_view;
    public static AFSGAdapter adapter;
    private ArrayList<AddElement> a_list = new ArrayList<>();
    private Context context;

    public tab1_anime(){ };

    @Override
    public void onCreate(Bundle savedInstancesState) {
        super.onCreate(savedInstancesState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstancesState) {
        View view = inflater.inflate(R.layout.fragment_tab1_anime, container, false);
        recycler_view = view.findViewById(R.id.recycler_view);
        recycler_view.setHasFixedSize(true);
        context = getActivity();
        LinearLayoutManager layoutManager_anime_crucial = new GridLayoutManager(getContext(), 3, GridLayoutManager.VERTICAL, false);
        recycler_view.setLayoutManager(layoutManager_anime_crucial);
        recycler_view.setItemAnimator(new DefaultItemAnimator());
        int spanCount = 3; // 3 columns
        int spacing = 10; // 10 for my phone, 35 for the emulator
        boolean includeEdge = true;
        recycler_view.addItemDecoration(new GridSpacingItemDecoration(spanCount, spacing, includeEdge));
        adapter = new AFSGAdapter(a_list, getContext(), this);
        adapter.setDataSet(a_list);
        recycler_view.setAdapter(adapter);
        recycler_view.scheduleLayoutAnimation();
        adapter.notifyDataSetChanged();
        return view;
    }

    public void openShowElementFragment(int position, View view) {
        AddElement element = a_list.get(position);
        ShowElementFragment showElementFragment = new ShowElementFragment();
        Bundle bundle = new Bundle();
        bundle.putString("transitionName", "transition" + position);
        bundle.putSerializable("element", element);
        showElementFragment.setArguments(bundle);
        ((MainActivity) context).showFragmentWithTransition(this, showElementFragment, "showElementFragment", view, "transition" + position);
    }
}

ShoeElementDetails(Fragment B):

public class ShowElementFragment extends Fragment {
private AddElement elemento;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_show_element, parent, false);
    //showelement_background_image.setTransitionName("example_transition");
    Bundle b = getArguments();
    if (b != null) {
        String transitionName = b.getString("transitionName");
        elemento = (AddElement) b.getSerializable("element");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            showelement_image.setTransitionName(transitionName);
        }
    }

    //postponeEnterTransition();

    Glide.with(this)
            .load(elemento.image_url)
            .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
            .skipMemoryCache(false)
            .apply(RequestOptions.bitmapTransform(new BlurTransformation(10, 3)))
            .into(showelement_background_image);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        getActivity().getWindow().getSharedElementEnterTransition().setDuration(800);//.setInterpolator(new AccelerateInterpolator());
        getActivity().getWindow().getSharedElementReturnTransition().setDuration(850);//.setInterpolator(new DecelerateInterpolator());
    }

    showelement_backarrow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            getActivity().getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fragmentHolder, new MainFragment())
                    .commit();
            //startActivity(new Intent(ShowElementActivity.this, AnimeActivity.class));
        }
    });
    return view;
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    postponeEnterTransition();
    OneShotPreDrawListener.add(view, this::startPostponedEnterTransition);
    super.onViewCreated(view, savedInstanceState);
   }

}

Inside the adapter I handle the click of the element to start the transition:

inside adapter:

holder.itemView.setOnClickListener(new View.OnClickListener() {
        @SuppressLint("ClickableViewAccessibility")
        @Override
        public void onClick(View v) {
            fragment.openShowElementFragment(holder.getAdapterPosition(), v.findViewById(R.id.main_image));
        }
    });

the openShowElementFragment called is inside main activity:

public void showFragmentWithTransition(Fragment current, Fragment newFragment, String tag, View sharedView, String sharedElementName) {
    FragmentManager fragmentManager = getSupportFragmentManager();
    // check if the fragment is in back stack
    boolean fragmentPopped = fragmentManager.popBackStackImmediate(tag, 0);
    if (fragmentPopped) {
        // fragment is pop from backStack
    } else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            current.setSharedElementReturnTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));
            current.setExitTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));

            newFragment.setSharedElementEnterTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));
            newFragment.setEnterTransition(TransitionInflater.from(this).inflateTransition(android.R.transition.no_transition));
        }
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.fragmentHolder, newFragment, tag);
        fragmentTransaction.addToBackStack(tag);
        fragmentTransaction.addSharedElement(sharedView, sharedElementName);
        fragmentTransaction.commit();
    }
}

It's my first time approaching with fragments.


来源: stackexchange

问:
MACOS | When I click on the "a" tag in the Swiper Slider it does not go to the page
When I click on the "a" tag in the swiper slider, it does not go to the page and the slider starts to slide

this problem happens on mac

``

```<code><div class="swiper-wrapper">
     <?php do { ?>
  <div class="swiper-slide">
    <div class="slider-left-box">
       <a href="<?php echo $SiteURL ?>tur-bilgisi/<?php echo $row_rsOneCikan['Seo']; ?>" title="<?php echo $row_rsOneCikan['Baslik']; ?>">
  <img src="<?php echo $SiteURL ?>images/turlar/<?php echo $row_rsOneCikan['ResimBuyuk']; ?>" alt="<?php echo $row_rsOneCikan['Baslik']; ?>">
  <div class="slider-left-box-content">
    <div class="slider-left-box-content-wrapper">
      <h3>ÖNE ÇIKAN TURLAR<span>yeni</span></h3>
      <h4><?php echo $row_rsOneCikan['Baslik']; ?></h4>
      <ul>
        <li>

            <h5><?php echo $row_rsOneCikan['KisaBilgi']; ?> </h5>

        </li>

      </ul>
      <span style="color:#fff">Rezervasyon Yap</span> <img src="<?php echo $SiteURL ?>images/view-icone.png" alt="Rezervasyon Yap">
    </div>
    </div>
    </a>
  </div>
  </div>
 <?php } while ($row_rsOneCikan = mysql_fetch_assoc($rsOneCikan)); ?>
</div>

<div class="swiper-pagination"></div>

<div class="swiper-button-prev"><i class="fa fa-angle-left"></i></div>
<div class="swiper-button-next"><i class="fa fa-angle-right"></i></div>
</code>```

```

ContentLicense: CC BY-SA 4.0

Body:
When I click on the "a" tag in the swiper slider, it does not go to the page and the slider starts to slide

this problem happens on mac

``

     <?php do { ?>

       <a href="<?php echo $SiteURL ?>tur-bilgisi/<?php echo $row_rsOneCikan['Seo']; ?>" title="<?php echo $row_rsOneCikan['Baslik']; ?>">
  <img src="<?php echo $SiteURL ?>images/turlar/<?php echo $row_rsOneCikan['ResimBuyuk']; ?>" alt="<?php echo $row_rsOneCikan['Baslik']; ?>">

ÖNE ÇIKAN TURLARyeni

<?php echo $row_rsOneCikan['Baslik']; ?>

<?php echo $row_rsOneCikan['KisaBilgi']; ?>

      Rezervasyon Yap <img src="<?php echo $SiteURL ?>images/view-icone.png" alt="Rezervasyon Yap">

 <?php } while ($row_rsOneCikan = mysql_fetch_assoc($rsOneCikan)); ?>

```


问:
How to update Persistent volume claim programmatically
I am partly new to Kubernetes advance concepts. I have PersistentVolume, PersistentVolumeClaim  and a Pod using this Claim. This is example of static provisioning. I have now installed CSI driver and have storage class "managed-csi-class" which uses this CSI driver. I wat to update this setup to dynamic provisioning. Using Python script, i tried to update Persistent volume claim. Below program returns output as "---updated----". But the claim storage class still remains as "Manual". At this stage, i tried to update the PersistentVolumeClaim Manually to update its "storageClassName" but it dosent allow me to do so. I tried deleting the Pod but still same issue.  Any idea what else needs to be done to update PersistentVolumeClaim's storage class  ?</p>
```<code>v1 = client.CoreV1Api()
body = {"spec": {"storageClassName": "managed-csi-class"}}
    try:
        api_response = v1.patch_namespaced_persistent_volume_claim('static-pv-claim', 'testnamespace', body, async_req=True)
        print("---updated----")
        print(api_response)
    except ApiException as e:
        print("Exception when calling CoreV1Api->patch_namespaced_persistent_volume_claim: %s\n" % e)
</code>```

Body:
I am partly new to Kubernetes advance concepts. I have PersistentVolume, PersistentVolumeClaim  and a Pod using this Claim. This is example of static provisioning. I have now installed CSI driver and have storage class "managed-csi-class" which uses this CSI driver. I wat to update this setup to dynamic provisioning. Using Python script, i tried to update Persistent volume claim. Below program returns output as "---updated----". But the claim storage class still remains as "Manual". At this stage, i tried to update the PersistentVolumeClaim Manually to update its "storageClassName" but it dosent allow me to do so. I tried deleting the Pod but still same issue.  Any idea what else needs to be done to update PersistentVolumeClaim's storage class  ?

v1 = client.CoreV1Api()
body = {"spec": {"storageClassName": "managed-csi-class"}}
    try:
        api_response = v1.patch_namespaced_persistent_volume_claim('static-pv-claim', 'testnamespace', body, async_req=True)
        print("---updated----")
        print(api_response)
    except ApiException as e:
        print("Exception when calling CoreV1Api->patch_namespaced_persistent_volume_claim: %s\n" % e)


问:
Determine if NamedPipeClientStream is connected
I've problem with process communication using PipeConnection

My idea is:

A - process A

  B - process B

  1. A(pile client) wants to send message to B(pipe server)

  2. B reads message and disconects.

2.1 If B needs to ansver

    2.2 B(pipe client) connects to A(pile server)
    2.3 A reads message and disconects.

The problem appears if A sends message to B and than imedlitley wants to send another message again

Code sample:

```<code>//Server
static void Main(string[] args)
    {
        using (NamedPipeServerStream server = new NamedPipeServerStream("EOG", PipeDirection.In))
        {
            StreamReader sr = new StreamReader(server);

            while (true)
            {
                server.WaitForConnection();
                Console.WriteLine("Conected to client");
                try
                {
                    Console.WriteLine(sr.ReadLine());
                    server.Disconnect();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
            sr.Dispose();
        }
    }
}

//Client
static void Main(string[] args)
    {
        using (NamedPipeClientStream client = new NamedPipeClientStream(".", "EOG", PipeDirection.Out))
        {
            StreamWriter sw = new StreamWriter(client);
            while (true)
            {
                Console.WriteLine("Message: ");
                sw.WriteLine(Console.ReadLine());
                if (!client.IsConnected)
                    client.Connect();
                sw.Flush();
            }
            sw.Dispose();
        }
        Console.ReadKey();
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've problem with process communication using PipeConnection

My idea is:

A - process A

  B - process B

  1. A(pile client) wants to send message to B(pipe server)

  2. B reads message and disconects.

2.1 If B needs to ansver

    2.2 B(pipe client) connects to A(pile server)
    2.3 A reads message and disconects.

The problem appears if A sends message to B and than imedlitley wants to send another message again

Code sample:

//Server
static void Main(string[] args)
    {
        using (NamedPipeServerStream server = new NamedPipeServerStream("EOG", PipeDirection.In))
        {
            StreamReader sr = new StreamReader(server);

            while (true)
            {
                server.WaitForConnection();
                Console.WriteLine("Conected to client");
                try
                {
                    Console.WriteLine(sr.ReadLine());
                    server.Disconnect();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
            sr.Dispose();
        }
    }
}

//Client
static void Main(string[] args)
    {
        using (NamedPipeClientStream client = new NamedPipeClientStream(".", "EOG", PipeDirection.Out))
        {
            StreamWriter sw = new StreamWriter(client);
            while (true)
            {
                Console.WriteLine("Message: ");
                sw.WriteLine(Console.ReadLine());
                if (!client.IsConnected)
                    client.Connect();
                sw.Flush();
            }
            sw.Dispose();
        }
        Console.ReadKey();
    }


问:
Convert `tf2` BERT checkpoint to `pytorch` model
I am trying to convert a tf2 BERT checkpoint to a pytorch model in order to upload it on Huggingface hub. The tf2 BERT checkpoint was obtained using the official tensorflow scripts.

Everything goes well in the training routine (performances and graphs are looking good), but now I am not able to convert this tf2 checkpoint a pytorch model. I know that there are 2 scripts for doing this type of conversion (one for tf1 checkpoints and one for tf2 checkpoints), but the script for tf2 checkpoints performs only the encoder conversion.

I would like to export a tf2 BERT checkpoint to a pytorch model, exporting the MLM head alongside the encoder.

Does anybody have an idea? Thank you!


问:
Is there any good WebService can use to build custom feed based on existing feed?(No yahoo pipe)
I need to customize a feed based on a existing feed. Of course the first answer I found is yahoo pipe. But yahoo pipe can not merge two page's content into one single item.Or just too complicated to accomplish my goal using yahoo pipe.

So is there any other web service can do something what I want?

Basiclly,for each item in the feed I want to append another page's content.

PS:I only want to use this new feed in my Google Reader , and I don't wanna run some additional server  to accomplish this...


问:
How to change the x-axis ticks using mpl finance [solved]
Im making a program that creates an OHLC price graph for every asset in the list I provide, but im trying to change the ticks of my x-axis to make it quarterly. I found a solution, but the ticks are not in the same month every year, so it is not useful. Here is my code. Does someone know how to fix my problem?

```<code>import mplfinance as mpf
import yfinance as yf
import matplotlib.pyplot as plt
from datetime import datetime
from matplotlib.ticker import MaxNLocator
from matplotlib.dates import MonthLocator, DateFormatter
from matplotlib.ticker import FixedLocator
import pandas as pd
#%% Creamos la clase que grafica la lista de activos que desee ver, desde la fecha que querramos.
class Grafico:
    def __init__(self, assets, start_date):

        self.assets = assets
        self.start_date = start_date
        self.end= datetime.now()
        self.start=datetime.strptime(self.start_date, '%Y-%m-%d')

        self.days=(self.end-self.start).days

        self.CCL= self.CCL_f()

    def CCL_f(self):
        GGAL=yf.download('GGAL', start=self.start_date)
        GGAL_BA=yf.download('GGAL.BA',start=self.start_date)
        CCL=(GGAL_BA/GGAL)*10
        return CCL

    def plot(self):
        for file in os.listdir(): #Esto borrará los archivos viejos, para que cada vez que se ejecute el programa aparezcan en carpeta los gráficos que se quieren descargar
            if file.endswith('.png'):
                try:
                    os.remove(file)
                except Exception as e:
                    print(f'Error deleting {file}: {e}')
        for asset in self.assets:
            if ".BA" in asset:
                data = yf.download(asset, start=self.start_date, end=self.end)
                data= data/self.CCL
                self.data=data
                if asset=="BYMA.BA":
                    self.data= self.data.drop("2018-12-31")
            else:
                data = yf.download(asset, start=self.start_date, end=self.end)
                self.data=data
            fig, ax = mpf.plot(self.data, type='candle', style='classic',figscale=1.5, tight_layout=False, returnfig=True)
            #mpf.plot_moving_average(data, 50, color='black', linestyle='--')
            fig.set_size_inches(11.692913385826772,8)
            ax[0].yaxis.set_major_locator(MaxNLocator(nbins=30))
            #ax[0].xaxis.set_major_locator(MaxNLocator(nbins=10))
            comienzo = self.data.index[0]
            final = self.data.index[-1]
            locator = MonthLocator(interval=3)
            #formatter = DateFormatter('%b %Y')

            #ax[0].xaxis.set_major_formatter(formatter)
            ax[0].xaxis.set_major_locator(locator)
            ax[0].tick_params(axis='x', labelsize=5)
            ax[0].tick_params(axis='y', labelsize=5)
            last_price = self.data['Close'].iloc[-1]
            ax[0].axhline(y=last_price, linestyle='--', color='k',linewidth=0.5)
            ax[0].set_title(f'{asset} - (Last {self.days} days)',fontsize=15, loc='center')
            plt.savefig(f'{asset}.png',bbox_inches='tight', dpi=300)

</code>```

I tried using DateFormatter to change the ticks to '%b %Y' format, but the dates of the graph were screwed, overlapping, or even having dates from 1969 when my data are always 6 years from now.

Body:
Im making a program that creates an OHLC price graph for every asset in the list I provide, but im trying to change the ticks of my x-axis to make it quarterly. I found a solution, but the ticks are not in the same month every year, so it is not useful. Here is my code. Does someone know how to fix my problem?

import mplfinance as mpf
import yfinance as yf
import matplotlib.pyplot as plt
from datetime import datetime
from matplotlib.ticker import MaxNLocator
from matplotlib.dates import MonthLocator, DateFormatter
from matplotlib.ticker import FixedLocator
import pandas as pd
#%% Creamos la clase que grafica la lista de activos que desee ver, desde la fecha que querramos.
class Grafico:
    def __init__(self, assets, start_date):

        self.assets = assets
        self.start_date = start_date
        self.end= datetime.now()
        self.start=datetime.strptime(self.start_date, '%Y-%m-%d')

        self.days=(self.end-self.start).days

        self.CCL= self.CCL_f()

    def CCL_f(self):
        GGAL=yf.download('GGAL', start=self.start_date)
        GGAL_BA=yf.download('GGAL.BA',start=self.start_date)
        CCL=(GGAL_BA/GGAL)*10
        return CCL

    def plot(self):
        for file in os.listdir(): #Esto borrará los archivos viejos, para que cada vez que se ejecute el programa aparezcan en carpeta los gráficos que se quieren descargar
            if file.endswith('.png'):
                try:
                    os.remove(file)
                except Exception as e:
                    print(f'Error deleting {file}: {e}')
        for asset in self.assets:
            if ".BA" in asset:
                data = yf.download(asset, start=self.start_date, end=self.end)
                data= data/self.CCL
                self.data=data
                if asset=="BYMA.BA":
                    self.data= self.data.drop("2018-12-31")
            else:
                data = yf.download(asset, start=self.start_date, end=self.end)
                self.data=data
            fig, ax = mpf.plot(self.data, type='candle', style='classic',figscale=1.5, tight_layout=False, returnfig=True)
            #mpf.plot_moving_average(data, 50, color='black', linestyle='--')
            fig.set_size_inches(11.692913385826772,8)
            ax[0].yaxis.set_major_locator(MaxNLocator(nbins=30))
            #ax[0].xaxis.set_major_locator(MaxNLocator(nbins=10))
            comienzo = self.data.index[0]
            final = self.data.index[-1]
            locator = MonthLocator(interval=3)
            #formatter = DateFormatter('%b %Y')

            #ax[0].xaxis.set_major_formatter(formatter)
            ax[0].xaxis.set_major_locator(locator)
            ax[0].tick_params(axis='x', labelsize=5)
            ax[0].tick_params(axis='y', labelsize=5)
            last_price = self.data['Close'].iloc[-1]
            ax[0].axhline(y=last_price, linestyle='--', color='k',linewidth=0.5)
            ax[0].set_title(f'{asset} - (Last {self.days} days)',fontsize=15, loc='center')
            plt.savefig(f'{asset}.png',bbox_inches='tight', dpi=300)

I tried using DateFormatter to change the ticks to '%b %Y' format, but the dates of the graph were screwed, overlapping, or even having dates from 1969 when my data are always 6 years from now.


问:
SyntaxError: Cannot use import statement outside a module NextJs and Gulp
I'm trying to implement i18n-perser with Next Js. According to the i18n-perser documentation I need to create a gulpfile.js on the root directory. My gulpfile.js is something like this. When I'm running npm run gulp It's gives me SyntaxError: Cannot use import statement outside a module

```<code>import gulp from 'gulp';
import { gulp as i18nextParser } from 'i18next-parser';

export async function i18next() {
  return gulp
    .src('./**')
    .pipe(
      new i18nextParser({
        locales: ['en', 'nl'],
        output: './i18n/locales/$LOCALE/$NAMESPACE.json',
      })
    )
    .pipe(gulp.dest('./'));
}
</code>```

I tried some solution like the next dynamic import. But it's not working for me in this case. It's giving me the same SyntaxError.

```<code>import dynamic from 'next/dynamic';
const gulp = dynamic(() => import('gulp'), { ssr: false });
const { gulp: i18nextParser } = dynamic(() => import('i18next-parser"'), { ssr: false });
</code>```

I also tried anothe solution, I renamed the gulpfile.js to gulpfile.mjs. After renaming it's starting. But it's giving me another error. FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory.

I18n-perser is working perfectly in React but not working with NextJs. Basiclly if I run npm run gulp it should create parer file for me.

Body:
I'm trying to implement i18n-perser with Next Js. According to the i18n-perser documentation I need to create a gulpfile.js on the root directory. My gulpfile.js is something like this. When I'm running npm run gulp It's gives me SyntaxError: Cannot use import statement outside a module

import gulp from 'gulp';
import { gulp as i18nextParser } from 'i18next-parser';

export async function i18next() {
  return gulp
    .src('./**')
    .pipe(
      new i18nextParser({
        locales: ['en', 'nl'],
        output: './i18n/locales/$LOCALE/$NAMESPACE.json',
      })
    )
    .pipe(gulp.dest('./'));
}

I tried some solution like the next dynamic import. But it's not working for me in this case. It's giving me the same SyntaxError.

import dynamic from 'next/dynamic';
const gulp = dynamic(() => import('gulp'), { ssr: false });
const { gulp: i18nextParser } = dynamic(() => import('i18next-parser"'), { ssr: false });

I also tried anothe solution, I renamed the gulpfile.js to gulpfile.mjs. After renaming it's starting. But it's giving me another error. FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory.

I18n-perser is working perfectly in React but not working with NextJs. Basiclly if I run npm run gulp it should create parer file for me.


问:
Create multilevel Dask dataframe from multiple parquet files
I have a folder with around 500 CSV files. Each parquet file was created by saving a test result that looks as follows (time series of multiple variables where each file might contain around 50,000 rows).

My final goal is to plot a specific parameter versus time from all the files (can't know ahead which parameter). For example, to read 500 files and plot reg vs t that will look like this:

In order to make sure that each line in the plot will be separate, I used a multilevel Pandas DataFrame.I used the following code to do so:

```<code>folder =  os.listdir(os.path.splitext(os.getcwd()+'/results')[0])

comp = {i.split('.')[0]: pd.read_csv('results/'+i, index_col='t') for i in folder}
combined = pd.concat(comp, axis=0)

plt.plot(combined.unstack(level=0)['reg'])
plt.show()
</code>```

Since my data is pretty large and it becomes pretty slow to load and plot, I would like to use Dask in order to read the files in a parallel way. Also, I would like to switch to parquet files instead of CSV.

Is there any way to read 500 parquet files (say I saved the CSV files in a parquet format) and store them as a multilevel Dask Dataframe so I will achieve the same result but using parallel computation?

Thank you

Body:
I have a folder with around 500 CSV files. Each parquet file was created by saving a test result that looks as follows (time series of multiple variables where each file might contain around 50,000 rows).

My final goal is to plot a specific parameter versus time from all the files (can't know ahead which parameter). For example, to read 500 files and plot reg vs t that will look like this:

In order to make sure that each line in the plot will be separate, I used a multilevel Pandas DataFrame.I used the following code to do so:

folder =  os.listdir(os.path.splitext(os.getcwd()+'/results')[0])

comp = {i.split('.')[0]: pd.read_csv('results/'+i, index_col='t') for i in folder}
combined = pd.concat(comp, axis=0)

plt.plot(combined.unstack(level=0)['reg'])
plt.show()

Since my data is pretty large and it becomes pretty slow to load and plot, I would like to use Dask in order to read the files in a parallel way. Also, I would like to switch to parquet files instead of CSV.

Is there any way to read 500 parquet files (say I saved the CSV files in a parquet format) and store them as a multilevel Dask Dataframe so I will achieve the same result but using parallel computation?

Thank you


问:
TypeError: Button() takes no arguments
I have a problem with my code, I hope someone can help me.
Here is my problem:

```<code>"C:\Users\Max Breier\AppData\Local\Programs\Python\Python310\python.exe" "C:\Users\Max Breier\PycharmProjects\pythonProject\JaR\master.py"
pygame 2.1.2 (SDL 2.0.18, Python 3.10.2)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
  File "C:\Users\Max Breier\PycharmProjects\pythonProject\JaR\master.py", line 35, in <module>
    resume_button = button.Button(304, 125, resume_img, 1)
TypeError: Button() takes no arguments

Process finished with exit code 1
</code>```

And here is my code to create the button instances:

```<code>resume_button = button.Button(304, 125, resume_img, 1)
options_button = button.Button(297, 250, options_img, 1)
quit_button = button.Button(336, 375, quit_img, 1)
video_button = button.Button(226, 75, video_img, 1)
audio_button = button.Button(225, 200, audio_img, 1)
keys_button = button.Button(246, 325, keys_img, 1)
back_button = button.Button(332, 450, back_img, 1)
</code>```

Here is the button code:

```<code>class Button():
    def _init_(self, x, y, image, scale):
        width = image.get_width()
        height = image.get_height()
        self.image = pygame.transform.scale(image, (int(width * scale), int(height * scale)))
        self.rect = self.image.get_rect()
        self.rect.topleft = (x, y)
        self.clicked = False

    def draw(self, surface):
        action = False
        pos = pygame.mouse.get_pos()

        if self.rect.collidepoint(pos):
            if pygame.mouse.get_pressed()[0] == 1 and self.clicked == False:
                self.clicked = True
                action = True

        if pygame.mouse.get_pressed()[0] == 0:
            self.clicked = False

        surface.blit(self.image, (self.rect.x, self.rect.y))

        return action
</code>```

Thanks for helping.

Title: TypeError: Button() takes no arguments

Body:
I have a problem with my code, I hope someone can help me.
Here is my problem:

"C:\Users\Max Breier\AppData\Local\Programs\Python\Python310\python.exe" "C:\Users\Max Breier\PycharmProjects\pythonProject\JaR\master.py"
pygame 2.1.2 (SDL 2.0.18, Python 3.10.2)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
  File "C:\Users\Max Breier\PycharmProjects\pythonProject\JaR\master.py", line 35, in <module>
    resume_button = button.Button(304, 125, resume_img, 1)
TypeError: Button() takes no arguments

Process finished with exit code 1

And here is my code to create the button instances:

resume_button = button.Button(304, 125, resume_img, 1)
options_button = button.Button(297, 250, options_img, 1)
quit_button = button.Button(336, 375, quit_img, 1)
video_button = button.Button(226, 75, video_img, 1)
audio_button = button.Button(225, 200, audio_img, 1)
keys_button = button.Button(246, 325, keys_img, 1)
back_button = button.Button(332, 450, back_img, 1)

Here is the button code:

class Button():
    def _init_(self, x, y, image, scale):
        width = image.get_width()
        height = image.get_height()
        self.image = pygame.transform.scale(image, (int(width * scale), int(height * scale)))
        self.rect = self.image.get_rect()
        self.rect.topleft = (x, y)
        self.clicked = False

    def draw(self, surface):
        action = False
        pos = pygame.mouse.get_pos()

        if self.rect.collidepoint(pos):
            if pygame.mouse.get_pressed()[0] == 1 and self.clicked == False:
                self.clicked = True
                action = True

        if pygame.mouse.get_pressed()[0] == 0:
            self.clicked = False

        surface.blit(self.image, (self.rect.x, self.rect.y))

        return action

Thanks for helping.


问:
'The term "Clear-RecycleBin" is not recognized' Error in Win 7 PowerShell
As the title says, I'm getting this error whenever I run a powershell script. I'm using Windows 7 ultimate 64-bit, Though it works with other PC units that has the same OS, some PC units result in this error. I think that some of them have older versions of Powershell.

Are there other ways to empty the recycle bin using Powershell?


问:
How Can I use a custom authorizer in alb
I would like to create ECS clusters and an application load balancer as below

I wanted to implement lambda authorizer in alb as like as api gateway. but it didn't support lambda authorizer. Only supports AWS cognito and OIDC.

So I was thinking about to add api gateway with lambda authorizer between alb and private subnets. but It did seem like a bad way.

How Can I find a good way? Please help me.


问:
Stan model not compiling with brms (only) in combination with Renv: 'omp.h' file not found
I have code to specify a stan model using the brms package. This code works well when using RStudio without a project open. However, when I open an RStudio project, I receive an error when trying to compile the stan model:

```<code>Error in compileCode(f, code, language = language, verbose = verbose) :
  In file included from <built-in>:1:In file included from /Users/jasper/Library/Caches/org.R-project.R/R/renv/cache/v5/R-4.2/aarch64-apple-darwin20/StanHeaders/2.21.0-7/0459d4dd7a8c239be18469a30c23dd4b/StanHeaders/include/stan/math/prim/mat/fun/Eigen.hpp:13:In file included from /Users/jasper/Desktop/brms-test/renv/library/R-4.2/aarch64-apple-darwin20/RcppEigen/include/Eigen/Dense:1:/Users/jasper/Desktop/brms-test/renv/library/R-4.2/aarch64-apple-darwin20/RcppEigen/include/Eigen/Core:266:10: fatal error: 'omp.h' file not found#include <omp.h>         ^~~~~~~1 error generated.make: *** [file200d5eaa7dc2.o] Error 1
Error in sink(type = "output") : invalid connection
</code>```

I started with a fresh project, with only brms (and its dependencies) installed, yet the issue persists.

I have updated R, RStudio and all packages to the latest version (both inside and outside the project), so this should not be an issue.
The fact that it can compile outside a project shows that I have installed clang etc correctly.

I read that renv uses its own Makevars, but it does not make a difference whether I download a binary, install from source using install.packages() or renv::install().

I am using macOS 13.1 and R 4.2.2.

Could you help me?

Body:
I have code to specify a stan model using the brms package. This code works well when using RStudio without a project open. However, when I open an RStudio project, I receive an error when trying to compile the stan model:

Error in compileCode(f, code, language = language, verbose = verbose) :
  In file included from <built-in>:1:In file included from /Users/jasper/Library/Caches/org.R-project.R/R/renv/cache/v5/R-4.2/aarch64-apple-darwin20/StanHeaders/2.21.0-7/0459d4dd7a8c239be18469a30c23dd4b/StanHeaders/include/stan/math/prim/mat/fun/Eigen.hpp:13:In file included from /Users/jasper/Desktop/brms-test/renv/library/R-4.2/aarch64-apple-darwin20/RcppEigen/include/Eigen/Dense:1:/Users/jasper/Desktop/brms-test/renv/library/R-4.2/aarch64-apple-darwin20/RcppEigen/include/Eigen/Core:266:10: fatal error: 'omp.h' file not found#include <omp.h>         ^~~~~~~1 error generated.make: *** [file200d5eaa7dc2.o] Error 1
Error in sink(type = "output") : invalid connection

I started with a fresh project, with only brms (and its dependencies) installed, yet the issue persists.

I have updated R, RStudio and all packages to the latest version (both inside and outside the project), so this should not be an issue.
The fact that it can compile outside a project shows that I have installed clang etc correctly.

I read that renv uses its own Makevars, but it does not make a difference whether I download a binary, install from source using install.packages() or renv::install().

I am using macOS 13.1 and R 4.2.2.

Could you help me?


问:
Laravel Artisan queue:work poor performance on Kubernetes
Trying to figure out the performance issue with Laravel application on EKS after migration. Thank you in advance for any comments and interest in this problem.

UPDATES

(10.01.2023) - we moved the cache driver from Filesystem (which was powered by EFS) to Redis. The performance of workloads increased in 8 times. But it is still much less than was on legacy architecture.

Stack

Infra

Kubernetes v1.24

EKS BOTTLEROCKET_x86_64, t3a.xlarge (managed nodegroup)

AMI release version: 1.11.1-104f8e0f (managed nodegroup)

Cilium v1.12.4 with kube-proxy replacement

Hubble enabled

EFS as PV storage class

Problematic application

Laravel v6.20.44

PHP CLI: 7.2.24-cli-alpine3.10

PHP FPM: 7.2.24-fpm-alpine3.10

RabbitMQ 3.11.4, Erlang 25.1.2

vladimir-yuldashev/laravel-queue-rabbitmq v10.2.3

Context

Currently I am moving legacy infrastructure from native one-server LAMP stack to Kubernetes on EKS. The project is periodically high loaded by scheduled synchronization processes. I developed Helm chart to deploy each Laravel queue worker in separate container to allow then automate scaling which can be triggered by different events.

I already moved 2 applications with same stack as Problematic application to EKS cluster with no issues related to performance. But with third there is a Problem.

Problematic application on legacy environment was working on t3.medium (2 vCPU, 4 RAM). After moving it to EKS the instance type that compute application's workloads is not changed.

Problem

Application has several queues in RabbitMQ for daily synchronization process. On legacy infrastructure, the average speed of acknowledging Jobs in queue A was 240/s (4 consumers). After migration to Kuberneіtes, we observed downgrade of speed to 5.2/s (4 consumers).

P.S. - other queues' speed had degraded too. Queue A is taken as an example.

The application source code has not changed since the migration.

Benchmark

We did benchmarking of handle method in Jobs that are processed in the queue A. The function is processed under 50ms, so there is no actual problem with written business logic. But still there is a question where all other time is gone...

Monitoring

After monitoring (Grafana + Prometheus) I discovered, that queue workers do not hit the resource limits, and actually are using under 50m of CPU, when configuration is requesting 150m. So there seems like no problem with resource allocation, but performance is still poor. Please correct me if I am missing something.

Tried Solutions

Created separate node group with t3a.xlarge instance type, performance increased from 5.2/s to 60/s for queue A. But for other queue, for ex. B, there is not big difference in performance: throughput 220/s (legacy) vs 12/s (EKS on t3a.xlarge).

Increased allocated resources for each queue worker pod (tried to increase CPU and RAM), but the average worker speed is not changing. Tried even allocate 1 vCPU per each queue worker pod, but no luck.

Increased replicas of consumers from 4 20, had increased throughput from 5.2/s to 12/s, but after increasing replicas even more -> could not achieve the speed more than 12/s.

Changed php artisan queue:work to php artisan rabbitmq:consume, because queue:work set prefetch count in RabbitMQ connection to 1. But it does not cause any performance improvements.

Expected Behavior

The main question is what is the difference between environments and where is the bottleneck.

Network limits are the same between legacy and Kubernetes environment, 5 Gigabit. So I am not sure that problem is within network throughput.

As the result of the research and investigation I expect to have at least the same performance for all queues workers on EKS that we had on legacy environment.


问:
To integrate a trained machine learning model with react native app
I have an FYP project (a social media app like Instagram) that requires me to create a simple recommendation system. I've trained my dataset on cosine similarity using Python, but I'm at a loss on what to do next. How can I integrate my trained ml model to React native or if there is a better and easier way to make a recommendation system?

I tried reading documentation and watching videos. But I still don't seem to be able to grasp some difficult concepts. I would greatly appreciate it if you could give me instructions or steps on what to learn after training my model. Or if I have to use some library or packages etc. [not sure if this is the appropriate forum for this inquiry]


问:
Dealing with external namespaces for a POCO data model implemented through NJsonSchema auto-generated classes
In a dotnet microservice architecture, to avoid exposing my data model and its logic, I am willing to add a POCO data model layer following a mechanism: fullDataModel>json>pocoDataModel.
Here is my reduced fullDataModel

```<code>public class MyDto
{
    public string Name { get; set; }
    public AnExternalNamespace.MyExternalType ExternalObject { get; set; }
}
</code>```

To implement the above mechanism, I am using NJSonSchema CSharpGenerator as follow:

```<code>// generate Json schema from ConsoleApp1
JsonSchema schema = await JsonSchema.FromFileAsync("MyDto.txt");
CSharpGeneratorSettings settings = new CSharpGeneratorSettings
{
    ClassStyle = CSharpClassStyle.Poco,
    Namespace = "MS1Namespace",
    GenerateDataAnnotations = true
};
var generator = new CSharpGenerator(schema, settings);
var modelFile = generator.GenerateFile();

// generate the C# file in a another ConsoleApp2 for testing purpose
using (StreamWriter writer = new StreamWriter("..\\ConsoleApp2\\MyDtoFromJson.cs"))
{
    writer.WriteLine(modelFile);
}

</code>```

Problem, the MyDto class refers to a type which comes from an external library (AnExternalNamespace.MyExternalType). But the mechanism I implemented does not preserve this type of reference, rather it generates a type bounded to each namespace associated with each microservice I use that implement this type. Have a look at the C# generated file which is bounded to MS1Namespace

```<code>namespace MS1Namespace
{
    [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.8.0.0 (Newtonsoft.Json v13.0.0.0)")]
    public partial class MyExternalType
    {
        [Newtonsoft.Json.JsonProperty("Name", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
        public string Name { get; set; }

        [Newtonsoft.Json.JsonProperty("Description", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
        public string Description { get; set; }

    }

    [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.8.0.0 (Newtonsoft.Json v13.0.0.0)")]
    public partial class MyDto
    {
        [Newtonsoft.Json.JsonProperty("Name", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
        public string Name { get; set; }

        [Newtonsoft.Json.JsonProperty("ExternalId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
        public MyExternalType ExternalObject { get; set; }
    }
}

</code>```

In other words, with this mechanism, MyExternalType is kind of redefined relative to each MSnNamespace for every microservice (1 to n) where it is embedded. On the contrary, I would like to be able to receive objects that refer to the type defined in the AnExternalNamespace each time I send a request to these microservices. That would allow me treat the data of same type coming from these different microservices in a unified way with the unique AnExternalNamespace.MyExternalType

I have tried to play with Json annotations in MyDto class. For example by doing this:

```<code>[JsonProperty(TypeNameHandling = TypeNameHandling.Auto)]
public MyPublicLibrary.MyExternalType ExternalId { get; set; }

</code>```

This does not allow to get out of the MS1Namespace scope to which all the auto-generated classes are bounded.

So, the only solution I see to overcome this for now is to implement an explicit&implicit cast in each microservice embedding this type from MSnNamespace.MyExternalType to AnExternalNamespace.MyExternalType.
But I was thinking NJSonSchema settings could offer me a more elegant way to deal with this situation. Am I missing something here? Do you see any other options or better practice while continuing keeping passing through the Json serialization/deserialization process?

Thanks in advance for your help!

Body:
In a dotnet microservice architecture, to avoid exposing my data model and its logic, I am willing to add a POCO data model layer following a mechanism: fullDataModel>json>pocoDataModel.
Here is my reduced fullDataModel

public class MyDto
{
    public string Name { get; set; }
    public AnExternalNamespace.MyExternalType ExternalObject { get; set; }
}

To implement the above mechanism, I am using NJSonSchema CSharpGenerator as follow:

// generate Json schema from ConsoleApp1
JsonSchema schema = await JsonSchema.FromFileAsync("MyDto.txt");
CSharpGeneratorSettings settings = new CSharpGeneratorSettings
{
    ClassStyle = CSharpClassStyle.Poco,
    Namespace = "MS1Namespace",
    GenerateDataAnnotations = true
};
var generator = new CSharpGenerator(schema, settings);
var modelFile = generator.GenerateFile();

// generate the C# file in a another ConsoleApp2 for testing purpose
using (StreamWriter writer = new StreamWriter("..\\ConsoleApp2\\MyDtoFromJson.cs"))
{
    writer.WriteLine(modelFile);
}

Problem, the MyDto class refers to a type which comes from an external library (AnExternalNamespace.MyExternalType). But the mechanism I implemented does not preserve this type of reference, rather it generates a type bounded to each namespace associated with each microservice I use that implement this type. Have a look at the C# generated file which is bounded to MS1Namespace

namespace MS1Namespace
{
    [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.8.0.0 (Newtonsoft.Json v13.0.0.0)")]
    public partial class MyExternalType
    {
        [Newtonsoft.Json.JsonProperty("Name", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
        public string Name { get; set; }

        [Newtonsoft.Json.JsonProperty("Description", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
        public string Description { get; set; }

    }

    [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.8.0.0 (Newtonsoft.Json v13.0.0.0)")]
    public partial class MyDto
    {
        [Newtonsoft.Json.JsonProperty("Name", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
        public string Name { get; set; }

        [Newtonsoft.Json.JsonProperty("ExternalId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
        public MyExternalType ExternalObject { get; set; }
    }
}

In other words, with this mechanism, MyExternalType is kind of redefined relative to each MSnNamespace for every microservice (1 to n) where it is embedded. On the contrary, I would like to be able to receive objects that refer to the type defined in the AnExternalNamespace each time I send a request to these microservices. That would allow me treat the data of same type coming from these different microservices in a unified way with the unique AnExternalNamespace.MyExternalType

I have tried to play with Json annotations in MyDto class. For example by doing this:

[JsonProperty(TypeNameHandling = TypeNameHandling.Auto)]
public MyPublicLibrary.MyExternalType ExternalId { get; set; }

This does not allow to get out of the MS1Namespace scope to which all the auto-generated classes are bounded.

So, the only solution I see to overcome this for now is to implement an explicit&implicit cast in each microservice embedding this type from MSnNamespace.MyExternalType to AnExternalNamespace.MyExternalType.
But I was thinking NJSonSchema settings could offer me a more elegant way to deal with this situation. Am I missing something here? Do you see any other options or better practice while continuing keeping passing through the Json serialization/deserialization process?

Thanks in advance for your help!


问:
Why is the first row in an ASP.NET Core MVC table un-editable?
By far the weirdest problem encountered to date: I am populating a table using @foreach (var item in Model) and every row has an edit and delete button.

The edit button triggers a modal where the user can make changes and click the Save button to save any changes. It works perfectly on every row except the first row.

Let's say I have 2 records in the table with IDs 1 & 2. I can edit 2 but not 1 where 1 is on the first row of the table. If I delete 1 leaving only 2 (now obviously at the top), I can't edit that so it is not related to the data in the item but somehow related to the fact that it is the first item being loaded into the table.

The view is returning with an enormous URL which includes a __RequestVerificationToken and there is no POST action recorded in the network.

This is the code in the Index.cshtml which calls the modal:

```<code><td style="text-align: center">
    <a asp-action="Edit" data-bs-toggle="modal" data-bs-target=" @("#editNode-" + item.Id)">
        <i class="fas fa-edit" ></i>
    </a>
    @await Html.PartialAsync("_EditNodePartialView", item)
</td>
</code>```

This is the _EditNodePartialView markup and code:

```<code>@model UnidAdmin.Models.BundleNodeViewModel

<div class="modal fade" id="editNode-@Model.Id">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" style="color:darkorange">Edit Node @Model.Id Bundle @Model.BundleId</h5>
                <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close" style="background-color:transparent; color:aquamarine; border-style:none">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <div class="modal-body">
                <form asp-controller="Nodes" asp-action="Edit" asp-route-id="@Model.Id" asp-route-src="bndlnd" method="post">
                    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                     <div class="row pb-3">
                        <div class="col form-group text-start">
                            <label asp-for="Name" class="control-label text-start" style="color:darkorange">Node Name</label>
                            <input asp-for="Name" class="form-control" />
                            <span asp-validation-for="Name" class="text-danger"></span>
                        </div>
                        <div class="col form-group text-start">
                            <label asp-for="Comment" class="control-label text-start" style="color:darkorange"></label>
                            <input asp-for="Comment" class="form-control" />
                            <span asp-validation-for="Comment" class="text-danger"></span>
                        </div>
                    </div>
                    <div class="row pb-3">
                        <div class="col form-group form-check text-center">
                            <label class="form-check-label text-start" style="color:darkorange">
                                <input class="form-check-input" asp-for="IsTest" /> @Html.DisplayNameFor(model => model.IsTest)
                            </label>
                        </div>
                        <div class="col form-group form-check text-center">
                            <label class="form-check-label text-start" style="color:darkorange">
                                <input class="form-check-input" asp-for="IsLocked" /> @Html.DisplayNameFor(model => model.IsLocked)
                            </label>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary" onclick="displayBusyIndicator()" data-bs-dismiss="modal">Save</button>
                    </div>
                </form>

            </div>
        </div>
    </div>
</div>
</code>```

And this is the controller edit action method:

```<code>public async Task<IActionResult> Edit(int id, [FromForm]Node editnode, string src)
{
    // Lots of code here //
    return RedirectToAction(nameof(Index));
}
</code>```

As I said, it hits the controller for every row except the first row, whatever the record.

Has anyone ever encountered anything like this and if so what was your solution?

Body:
By far the weirdest problem encountered to date: I am populating a table using @foreach (var item in Model) and every row has an edit and delete button.

The edit button triggers a modal where the user can make changes and click the Save button to save any changes. It works perfectly on every row except the first row.

Let's say I have 2 records in the table with IDs 1 & 2. I can edit 2 but not 1 where 1 is on the first row of the table. If I delete 1 leaving only 2 (now obviously at the top), I can't edit that so it is not related to the data in the item but somehow related to the fact that it is the first item being loaded into the table.

The view is returning with an enormous URL which includes a __RequestVerificationToken and there is no POST action recorded in the network.

This is the code in the Index.cshtml which calls the modal:

    @await Html.PartialAsync("_EditNodePartialView", item)

This is the _EditNodePartialView markup and code:

@model UnidAdmin.Models.BundleNodeViewModel

Edit Node @Model.Id Bundle @Model.BundleId

                <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close" style="background-color:transparent; color:aquamarine; border-style:none">
                    ×
                </button>

                <form asp-controller="Nodes" asp-action="Edit" asp-route-id="@Model.Id" asp-route-src="bndlnd" method="post">

                            Node Name
                            <input asp-for="Name" class="form-control" />

                            <input asp-for="Comment" class="form-control" />

                                <input class="form-check-input" asp-for="IsTest" /> @Html.DisplayNameFor(model => model.IsTest)

                                <input class="form-check-input" asp-for="IsLocked" /> @Html.DisplayNameFor(model => model.IsLocked)

                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary" onclick="displayBusyIndicator()" data-bs-dismiss="modal">Save</button>

                </form>

And this is the controller edit action method:

public async Task<IActionResult> Edit(int id, [FromForm]Node editnode, string src)
{
    // Lots of code here //
    return RedirectToAction(nameof(Index));
}

As I said, it hits the controller for every row except the first row, whatever the record.

Has anyone ever encountered anything like this and if so what was your solution?


问:
Mysql - SSL 2 Way Process performing ,Fail in Mysql - Server handshake
Trying to do Mysql-SSL process
And I created Keystore and truststore by using the mysql ca-certs and client certs.

```<code>keytool -importcert -alias MySQLCACert.jks -file /var/lib/mysql/ca.pem -keystore ./truststore.jks -storetype PKCS12 -storepass mypassword

openssl pkcs12 -export -in /var/lib/mysql//client-cert.pem -inkey /var/lib/mysql/client-key.pem -out ./certificate.p12 -name "certificate"

keytool -importkeystore -srckeystore ./certificate.p12 -srcstoretype pkcs12 -destkeystore ./client-cert.jks

y: com.mysql.cj.exceptions.SSLParamsException: Cannot open file:/home/rohit/Desktop/SSOWORK/ssloms/oms/../certs/truststore.jks [parseAlgParameters failed: ObjectIdentifier() -- data isn't an object ID (tag = 48)]
    at sun.reflect.GeneratedConstructorAccessor73.newInstance(Unknown Source) ~[?:?]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[?:1.8.0_202]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[?:1.8.0_202]
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61) ~[mysql-connector-j-8.0.31.jar:8.0.31]
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:105) ~[mysql-connector-j-8.0.31.jar:8.0.31]
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:151) ~[mysql-connector-j-8.0.31.jar:8.0.31]
    at com.mysql.cj.protocol.ExportControlled.getSSLContext(ExportControlled.java:579) ~[mysql-connector-j-8.0.31.jar:8.0.31]
    at com.mysql.cj.protocol.ExportControlled.performTlsHandshake(ExportControlled.java:333) ~[mysql-connector-j-8.0.31.jar:8.0.31]
    at com.mysql.cj.protocol.StandardS

</code>```

And this One Error also getting

```<code>parseAlgParameters failed: ObjectIdentifier() -- data isn't an object ID (tag = 48)
</code>```

Error is related to Truststore/keystore or anything else ?

Body:
Trying to do Mysql-SSL process
And I created Keystore and truststore by using the mysql ca-certs and client certs.

keytool -importcert -alias MySQLCACert.jks -file /var/lib/mysql/ca.pem -keystore ./truststore.jks -storetype PKCS12 -storepass mypassword

openssl pkcs12 -export -in /var/lib/mysql//client-cert.pem -inkey /var/lib/mysql/client-key.pem -out ./certificate.p12 -name "certificate"

keytool -importkeystore -srckeystore ./certificate.p12 -srcstoretype pkcs12 -destkeystore ./client-cert.jks

y: com.mysql.cj.exceptions.SSLParamsException: Cannot open file:/home/rohit/Desktop/SSOWORK/ssloms/oms/../certs/truststore.jks [parseAlgParameters failed: ObjectIdentifier() -- data isn't an object ID (tag = 48)]
    at sun.reflect.GeneratedConstructorAccessor73.newInstance(Unknown Source) ~[?:?]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[?:1.8.0_202]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[?:1.8.0_202]
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61) ~[mysql-connector-j-8.0.31.jar:8.0.31]
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:105) ~[mysql-connector-j-8.0.31.jar:8.0.31]
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:151) ~[mysql-connector-j-8.0.31.jar:8.0.31]
    at com.mysql.cj.protocol.ExportControlled.getSSLContext(ExportControlled.java:579) ~[mysql-connector-j-8.0.31.jar:8.0.31]
    at com.mysql.cj.protocol.ExportControlled.performTlsHandshake(ExportControlled.java:333) ~[mysql-connector-j-8.0.31.jar:8.0.31]
    at com.mysql.cj.protocol.StandardS

And this One Error also getting

parseAlgParameters failed: ObjectIdentifier() -- data isn't an object ID (tag = 48)

Error is related to Truststore/keystore or anything else ?


问:
.NET Simulate Printing of tickets/POS reciepts (Thermal Printer) on PDF
I am developing a small desktop application that should print tickets on thermal papers.

The problem is that I don't have a physical thermal printer device so I am trying to simulate the layout of the receipt on a PDF document. So, I written some code that creates a sample document and print it in pdf but I am unable to set the correct dimensions of the paper.

The test code for printing (Visual Basic)

```<code>Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim printDlg As New PrintDialog()

    prntDocTicket.DocumentName = "Test Document"

    printDlg.Document = prntDocTicket
    printDlg.Document.DefaultPageSettings.PaperSize = New PaperSize("Custom", 225, 225)

    prntDocTicket.DefaultPageSettings.PaperSize.Height = 225
    prntDocTicket.DefaultPageSettings.PaperSize.Width = 225

    prntDocTicket.PrinterSettings.PrintToFile = True
    prntDocTicket.PrinterSettings.PrintFileName = "Test.pdf"

    prntDocTicket.Print()

    printDlg = Nothing
    prntDocTicket = Nothing
End Sub

Private Sub prntDocTicket_PrintPage(sender As Object, e As PrintPageEventArgs) Handles prntDocTicket.PrintPage
    Dim textToPrint As String = "Test"
    Dim typeFont As Font = New Font("calibri", 10)
    Dim textArea As SizeF = e.Graphics.MeasureString(textToPrint, typeFont)
    Dim drawX As Integer = (e.PageBounds.Width - textArea.Width) / 2
    Dim drawY As Integer = (e.PageBounds.Height - textArea.Height) / 2

    With e.Graphics
        Call .DrawRectangle(New Pen(Color.Red), e.PageBounds)
        Call .DrawString(textToPrint, typeFont, New SolidBrush(Color.Black), drawX, drawY)
        Call .Dispose()
    End With

End Sub
</code>```

And this is how the output PDF looks like, I can't control the size of the document and I don't have a thermal printer to test the output.

I am supposed to print using Star micronics TSP650 thermal printer.

Can someone help me please as this is my first time to print such documents ?

Note: Although the code is in VB but I don't mind codes in C#, actually I would prefer C#.

Body:
I am developing a small desktop application that should print tickets on thermal papers.

The problem is that I don't have a physical thermal printer device so I am trying to simulate the layout of the receipt on a PDF document. So, I written some code that creates a sample document and print it in pdf but I am unable to set the correct dimensions of the paper.

The test code for printing (Visual Basic)

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim printDlg As New PrintDialog()

    prntDocTicket.DocumentName = "Test Document"

    printDlg.Document = prntDocTicket
    printDlg.Document.DefaultPageSettings.PaperSize = New PaperSize("Custom", 225, 225)

    prntDocTicket.DefaultPageSettings.PaperSize.Height = 225
    prntDocTicket.DefaultPageSettings.PaperSize.Width = 225

    prntDocTicket.PrinterSettings.PrintToFile = True
    prntDocTicket.PrinterSettings.PrintFileName = "Test.pdf"

    prntDocTicket.Print()

    printDlg = Nothing
    prntDocTicket = Nothing
End Sub

Private Sub prntDocTicket_PrintPage(sender As Object, e As PrintPageEventArgs) Handles prntDocTicket.PrintPage
    Dim textToPrint As String = "Test"
    Dim typeFont As Font = New Font("calibri", 10)
    Dim textArea As SizeF = e.Graphics.MeasureString(textToPrint, typeFont)
    Dim drawX As Integer = (e.PageBounds.Width - textArea.Width) / 2
    Dim drawY As Integer = (e.PageBounds.Height - textArea.Height) / 2

    With e.Graphics
        Call .DrawRectangle(New Pen(Color.Red), e.PageBounds)
        Call .DrawString(textToPrint, typeFont, New SolidBrush(Color.Black), drawX, drawY)
        Call .Dispose()
    End With

End Sub

And this is how the output PDF looks like, I can't control the size of the document and I don't have a thermal printer to test the output.

I am supposed to print using Star micronics TSP650 thermal printer.

Can someone help me please as this is my first time to print such documents ?

Note: Although the code is in VB but I don't mind codes in C#, actually I would prefer C#.


问:
Mongoose query document based on ref document id
I have the two schemas:

```<code>const Schedule = mongoose.model(
  "Schedule",
  new mongoose.Schema({
    date: Date,
    timeSlots: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "TimeSlot",
      },
    ],
  })
);
</code>```

and

```<code>const TimeSlot = mongoose.model(
  "TimeSlot",
  new mongoose.Schema({
    slot: String,
    user_id: String,
    isBooked: Boolean,
    isCompleted: Boolean,
    service: String,
    description: String,
    price: String,
  })
);
</code>```

now first i have made this query:

```<code>    const user_reservations = await TimeSlot.find({
      user_id: user._id,
    });
</code>```

Then i get back a list of documents. Now i want to find the date associated with those time slots. And how do i do that? For every time slot i want to return the date it belongs to. I have tried inn a loop:

```<code>    const reservationArr = user_reservations.map(async (timesSlot) => {
      const userTimeSlot = await Schedule.findOne().populate({
        path: "timeSlots",
        match: { _id: timesSlot._id.valueOf() },
      });
      return userTimeSlot;
    });
</code>```

But no luck... Any help??

Body:
I have the two schemas:

const Schedule = mongoose.model(
  "Schedule",
  new mongoose.Schema({
    date: Date,
    timeSlots: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "TimeSlot",
      },
    ],
  })
);

and

const TimeSlot = mongoose.model(
  "TimeSlot",
  new mongoose.Schema({
    slot: String,
    user_id: String,
    isBooked: Boolean,
    isCompleted: Boolean,
    service: String,
    description: String,
    price: String,
  })
);

now first i have made this query:

    const user_reservations = await TimeSlot.find({
      user_id: user._id,
    });

Then i get back a list of documents. Now i want to find the date associated with those time slots. And how do i do that? For every time slot i want to return the date it belongs to. I have tried inn a loop:

    const reservationArr = user_reservations.map(async (timesSlot) => {
      const userTimeSlot = await Schedule.findOne().populate({
        path: "timeSlots",
        match: { _id: timesSlot._id.valueOf() },
      });
      return userTimeSlot;
    });

But no luck... Any help??


问:
Multithreading in place of multiprocessing with celery
I am a little frustrated with celery documentation. I understand that the command

```<code>celery -A my-module worker -l INFO -n w1
</code>```

starts a worker instance named w1. This means that the worker instance starts some default number of "processes" in the OS.

But can celery also start threads instead of processes? For example what does the following command do?

```<code>celery -A my-module worker --pool threads -l INFO -n w1
</code>```

I tried reading through the documentation but could not find anything that would give an answer to the question "What does multi threading mean when it comes to celery? Can celery support multi threading in place of multi processing?"

Body:
I am a little frustrated with celery documentation. I understand that the command

celery -A my-module worker -l INFO -n w1

starts a worker instance named w1. This means that the worker instance starts some default number of "processes" in the OS.

But can celery also start threads instead of processes? For example what does the following command do?

celery -A my-module worker --pool threads -l INFO -n w1

I tried reading through the documentation but could not find anything that would give an answer to the question "What does multi threading mean when it comes to celery? Can celery support multi threading in place of multi processing?"


问:
Mifare Classic Card Emulation
my task is that when the Android device is in contact with an already existing reader that works on the 14443-3 protocol (Mifare Classic). Give it the value of some blocks. The unique ID is not important to me. Also, I already understood that Android HCE is not my option.

Are there any examples? Or the SDK?

Title: Mifare Classic Card Emulation


问:
MQTT message can not ingest to AWS iot analytics
I have a device to generate mqtt message to AWS IoT.  I have created the channel/pipeline/data store/dataset for it, but I received nothing but _dt in my dataset.
The reason is the message contains some invalid payload (some special characters and hyphen -), so it cannot be ingested to the data store.

I cannot modify the original MQTT message because to the device cannot be reprogrammed.

Should I republish the message by making a new rule or use the function in pipeline to filter it?


问:
this code is giving me AttributeError: 'API' object has no attribute 'trends_place'
Im trying to get what is trending in some region
Im trying to get what is trending in some region
Im trying to get what is trending in some region

```<code>import tweepy
import keys

# Replace these with your own API keys and access tokens
consumer_key = keys.api_key
consumer_secret = keys.api_key_secret
access_token = keys.access_token
access_token_secret = keys.access_token_secret

# Authenticate with the Twitter API
auth = tweepy.OAuth1UserHandler(consumer_key, consumer_secret, access_token, access_token_secret)
api = tweepy.API(auth)

# Set the WOEID for the region you want to get trending topics for
# You can use the tweepy.API.trend_location() method to get a list of available regions
woeid = 23424977  # USA

# Get the list of trending topics
trends = api.trends_place(woeid)

# Print the names of the trending topics
for trend in trends[0]["trends"]:
    print(trend["name"])
</code>```

how can i solve this issue

Im trying to get what is trending in some region

Body:
Im trying to get what is trending in some region
Im trying to get what is trending in some region
Im trying to get what is trending in some region

import tweepy
import keys

# Replace these with your own API keys and access tokens
consumer_key = keys.api_key
consumer_secret = keys.api_key_secret
access_token = keys.access_token
access_token_secret = keys.access_token_secret

# Authenticate with the Twitter API
auth = tweepy.OAuth1UserHandler(consumer_key, consumer_secret, access_token, access_token_secret)
api = tweepy.API(auth)

# Set the WOEID for the region you want to get trending topics for
# You can use the tweepy.API.trend_location() method to get a list of available regions
woeid = 23424977  # USA

# Get the list of trending topics
trends = api.trends_place(woeid)

# Print the names of the trending topics
for trend in trends[0]["trends"]:
    print(trend["name"])

how can i solve this issue

Im trying to get what is trending in some region


问:
With optimization disabled, matrix multiplication is slower with AVX. Why?
First I wrote this code:

```<code>void dgemm3(double* A, double* B, double* C, int n){
    register int i, j, k, n4 = n * 4;
    register double cij0, cij1, cij2, cij3;
    register double *a0, *a1, *a2, *a3, *b0, *b1, *b2, *b3;

    for (i=0; i<n; ++i){
        for (j=0; j<n; ++j){

            a0 = &A[i*n];
            a1 = a0 + 1;
            a2 = a1 + 1;
            a3 = a2 + 1;
            b0 = &B[j];
            b1 = b0 + n;
            b2 = b1 + n;
            b3 = b2 + n;
            cij0 = cij1 = cij2 = cij3 = 0;

            for(k = 0; k < n; k+=4, a0+=4, a1+=4, a2+=4, a3+=4, b0+=n4, b1+=n4, b2+=n4, b3+=n4){
                cij0 += *a0 * *b0;
                cij1 += *a1 * *b1;
                cij2 += *a2 * *b2;
                cij3 += *a3 * *b3;
            }

            *C++ = cij0 + cij1 + cij2 + cij3;
        }
}
}
</code>```

and the I wrote this code using avx:

```<code>void dgemm_avx (double* A, double* B, double* C, int n) {
    for (int i=0; i<n; i++) {
        for (int j=0; j<n; j+=4)  {
            __m256d c0 = _mm256_setzero_pd();
            for (int k=0; k<n; k++)  {
                __m256d m1 = _mm256_broadcast_sd(A+i*n+k);
                __m256d m2 = _mm256_loadu_pd(B+k*n+j);
                __m256d m3 = _mm256_mul_pd(m1,m2);
                c0 = _mm256_add_pd(c0,m3);
            }
            _mm256_storeu_pd(C+i*n+j, c0);

        }
}
}
</code>```

I expected the second one to be faster but it is not.
But if I use -O1 flag on both of them then the second one is faster.
Now my question is shouldn't the second one be faster even without optimization?

Body:
First I wrote this code:

void dgemm3(double* A, double* B, double* C, int n){
    register int i, j, k, n4 = n * 4;
    register double cij0, cij1, cij2, cij3;
    register double *a0, *a1, *a2, *a3, *b0, *b1, *b2, *b3;

    for (i=0; i<n; ++i){
        for (j=0; j<n; ++j){

            a0 = &A[i*n];
            a1 = a0 + 1;
            a2 = a1 + 1;
            a3 = a2 + 1;
            b0 = &B[j];
            b1 = b0 + n;
            b2 = b1 + n;
            b3 = b2 + n;
            cij0 = cij1 = cij2 = cij3 = 0;

            for(k = 0; k < n; k+=4, a0+=4, a1+=4, a2+=4, a3+=4, b0+=n4, b1+=n4, b2+=n4, b3+=n4){
                cij0 += *a0 * *b0;
                cij1 += *a1 * *b1;
                cij2 += *a2 * *b2;
                cij3 += *a3 * *b3;
            }

            *C++ = cij0 + cij1 + cij2 + cij3;
        }
}
}

and the I wrote this code using avx:

void dgemm_avx (double* A, double* B, double* C, int n) {
    for (int i=0; i<n; i++) {
        for (int j=0; j<n; j+=4)  {
            __m256d c0 = _mm256_setzero_pd();
            for (int k=0; k<n; k++)  {
                __m256d m1 = _mm256_broadcast_sd(A+i*n+k);
                __m256d m2 = _mm256_loadu_pd(B+k*n+j);
                __m256d m3 = _mm256_mul_pd(m1,m2);
                c0 = _mm256_add_pd(c0,m3);
            }
            _mm256_storeu_pd(C+i*n+j, c0);

        }
}
}

I expected the second one to be faster but it is not.
But if I use -O1 flag on both of them then the second one is faster.
Now my question is shouldn't the second one be faster even without optimization?


问:
KNN Algorithm is Giving good Accuracy with Bad Confusion Matrix Results
I have data with multilabel classification. I used KNN model in order to classify it. The number of labels are 15, I got accuracy results for each label, averaged the results to get the accuracy of the model which is 93%.

The confusion matrix is showing bad numbers.

Would you tell me what does this mean? Is it overfitting? How can I solve my problem?

Accuracy and mean absolute error (mae) code

Input:

```<code># Getting the accuracy of the model
y_pred1 = level_1_knn_model.predict(X_val1)
accuracy = (sum(y_val1==y_pred1)/y_val1.shape[0])*100
accuracy = sum(accuracy)/len(accuracy)
print("Accuracy: "+str(accuracy)+"%\n")

# Getting the mean absolute error
mae1 = mean_absolute_error(y_val1, y_pred1)
print("Mean Absolute Error: "+str(mae1))
</code>```

Output:

```<code>Accuracy: [96.55462575 97.82146336 99.23207908 95.39247451 98.69340807 74.22793801
 78.67975909 97.47825108 99.80189098 77.67264969 91.69399776 99.97084683
 99.42621267 99.32682688 99.74159693]%
Accuracy: 93.71426804569977%

Mean Absolute Error: 9.703818402273944
</code>```

Confusion Matrix and classification report code

Input:

```<code># Calculate the confusion matrix
cMatrix1 = confusion_matrix(y_val1.argmax(axis=1), y_pred1.argmax(axis=1))

# Plot the confusion matrix
plt.figure(figsize=(11,10))
sns.heatmap(cMatrix1, annot=True, fmt='g')

# Calculate the classification report
classReport1 = classification_report(y_val1, y_pred1)
print("\nClassification Report:")
print(classReport1)
</code>```

Output:

```<code>Classification Report:
              precision    recall  f1-score   support

           0       0.08      0.00      0.01      5053
           1       0.03      0.00      0.01      3017
           2       0.00      0.00      0.00      1159
           3       0.07      0.00      0.01      6644
           4       0.00      0.00      0.00      1971
           5       0.58      0.65      0.61     47222
           6       0.39      0.33      0.36     27302
           7       0.02      0.00      0.00      3767
           8       0.00      0.00      0.00       299
           9       0.58      0.61      0.60     40823
          10       0.13      0.02      0.03     11354
          11       0.00      0.00      0.00        44
          12       0.00      0.00      0.00       866
          13       0.00      0.00      0.00      1016
          14       0.00      0.00      0.00       390

   micro avg       0.54      0.43      0.48    150927
   macro avg       0.13      0.11      0.11    150927
weighted avg       0.43      0.43      0.42    150927
 samples avg       0.43      0.43      0.43    150927

</code>```

Body:
I have data with multilabel classification. I used KNN model in order to classify it. The number of labels are 15, I got accuracy results for each label, averaged the results to get the accuracy of the model which is 93%.

The confusion matrix is showing bad numbers.

Would you tell me what does this mean? Is it overfitting? How can I solve my problem?

Accuracy and mean absolute error (mae) code

Input:

# Getting the accuracy of the model
y_pred1 = level_1_knn_model.predict(X_val1)
accuracy = (sum(y_val1==y_pred1)/y_val1.shape[0])*100
accuracy = sum(accuracy)/len(accuracy)
print("Accuracy: "+str(accuracy)+"%\n")

# Getting the mean absolute error
mae1 = mean_absolute_error(y_val1, y_pred1)
print("Mean Absolute Error: "+str(mae1))

Output:

Accuracy: [96.55462575 97.82146336 99.23207908 95.39247451 98.69340807 74.22793801
 78.67975909 97.47825108 99.80189098 77.67264969 91.69399776 99.97084683
 99.42621267 99.32682688 99.74159693]%
Accuracy: 93.71426804569977%

Mean Absolute Error: 9.703818402273944

Confusion Matrix and classification report code

Input:

# Calculate the confusion matrix
cMatrix1 = confusion_matrix(y_val1.argmax(axis=1), y_pred1.argmax(axis=1))

# Plot the confusion matrix
plt.figure(figsize=(11,10))
sns.heatmap(cMatrix1, annot=True, fmt='g')

# Calculate the classification report
classReport1 = classification_report(y_val1, y_pred1)
print("\nClassification Report:")
print(classReport1)

Output:

Classification Report:
              precision    recall  f1-score   support

           0       0.08      0.00      0.01      5053
           1       0.03      0.00      0.01      3017
           2       0.00      0.00      0.00      1159
           3       0.07      0.00      0.01      6644
           4       0.00      0.00      0.00      1971
           5       0.58      0.65      0.61     47222
           6       0.39      0.33      0.36     27302
           7       0.02      0.00      0.00      3767
           8       0.00      0.00      0.00       299
           9       0.58      0.61      0.60     40823
          10       0.13      0.02      0.03     11354
          11       0.00      0.00      0.00        44
          12       0.00      0.00      0.00       866
          13       0.00      0.00      0.00      1016
          14       0.00      0.00      0.00       390

   micro avg       0.54      0.43      0.48    150927
   macro avg       0.13      0.11      0.11    150927
weighted avg       0.43      0.43      0.42    150927
 samples avg       0.43      0.43      0.43    150927


问:
Socket hang up when connecting to websocket with Node.JS and a WebSocketsClient
I'm trying to connect to a public websocket to retrieve a stream of data using Node.JS and the WebSocketClient.

Using Chrome extension tools such as WebSocket Test Client and PieSocket Websock Tester, I am able to do this successfully. I can enter the websocket URL, connect and receive am initial header of data and then when I send the required response to initiate the data stream, I can see the data being received every second, as expected.

I then created a simple Node.JS app to do the same as above so that I can get the data from the websocket and work with it but I keep getting a

Connect Error: Error: socket hang up

I have debugged the code and stepped through it but I can't see why this is happening. I can only assume at this point that it's not keeping the connection open but despite researching how to do this, I can't find a way (if indeed this is the issue?).

This is the code I am using so far just to test the retrieval of the data:

```<code>var WebSocketClient = require('websocket').client;

var client = new WebSocketClient();

const _Message = JSON.stringify(
{
      Key: '123',
      Format: 'JSON'
});

client.on('connectFailed', function(error) {
    console.log('Connect Error: ' + error.toString());
});

client.on('connect', function(connection) {

connection.send(_Message);

connection.on('error', function(error) {
    console.log("Connection Error: " + error.toString());
});

connection.on('close', function() {
    console.log('echo-protocol Connection Closed');
});

connection.on('message', function(message) {
    if (message.type === 'utf8') {
        console.log("Received: '" + message.utf8Data + "'");
    }
});

function sendData() {
    if (connection.connected) {
      console.log("STILL CONNECTED");
    }
}

sendData();

});

client.connect('ws://URLofWebsocket:3030/PathToWebsocket/', 'echo-protocol');
</code>```

I've been trying to fix this issue for 2 days so any advice would be appreciated.

I have tried 2 different Websocket libraries but get the same error.

Body:
I'm trying to connect to a public websocket to retrieve a stream of data using Node.JS and the WebSocketClient.

Using Chrome extension tools such as WebSocket Test Client and PieSocket Websock Tester, I am able to do this successfully. I can enter the websocket URL, connect and receive am initial header of data and then when I send the required response to initiate the data stream, I can see the data being received every second, as expected.

I then created a simple Node.JS app to do the same as above so that I can get the data from the websocket and work with it but I keep getting a

Connect Error: Error: socket hang up

I have debugged the code and stepped through it but I can't see why this is happening. I can only assume at this point that it's not keeping the connection open but despite researching how to do this, I can't find a way (if indeed this is the issue?).

This is the code I am using so far just to test the retrieval of the data:

var WebSocketClient = require('websocket').client;

var client = new WebSocketClient();

const _Message = JSON.stringify(
{
      Key: '123',
      Format: 'JSON'
});

client.on('connectFailed', function(error) {
    console.log('Connect Error: ' + error.toString());
});

client.on('connect', function(connection) {

connection.send(_Message);

connection.on('error', function(error) {
    console.log("Connection Error: " + error.toString());
});

connection.on('close', function() {
    console.log('echo-protocol Connection Closed');
});

connection.on('message', function(message) {
    if (message.type === 'utf8') {
        console.log("Received: '" + message.utf8Data + "'");
    }
});

function sendData() {
    if (connection.connected) {
      console.log("STILL CONNECTED");
    }
}

sendData();

});

client.connect('ws://URLofWebsocket:3030/PathToWebsocket/', 'echo-protocol');

I've been trying to fix this issue for 2 days so any advice would be appreciated.

I have tried 2 different Websocket libraries but get the same error.


问:
Why is AM XML file re-shuffling when adding a VO to it?
I am using Oracle ADF and JDeveloper 12c (12.2.1.12.54). I added a new VO to an existing AM via the JDeveloper GUI. Usually, when I do that, it just adds three new lines to the source XML of the AM, stating the local VO name and package name. Something like this:

```<code><ViewUsage
     Name="TestVO1"
     ViewObjectName="com.user.view.TestVO"/>
</code>```

When I added the new VO, other than adding these three lines, it was also re-shuffling the rest of the XML, like moving some methods from line 400 to 600 and vice-versa. Not sure why it is doing that. Also, the line count reduces from 1200 to 800.

I am new to the framework and the IDE and cannot post the actual code. Any help is much appreciated. Thank you.

Body:
I am using Oracle ADF and JDeveloper 12c (12.2.1.12.54). I added a new VO to an existing AM via the JDeveloper GUI. Usually, when I do that, it just adds three new lines to the source XML of the AM, stating the local VO name and package name. Something like this:

<ViewUsage
     Name="TestVO1"
     ViewObjectName="com.user.view.TestVO"/>

When I added the new VO, other than adding these three lines, it was also re-shuffling the rest of the XML, like moving some methods from line 400 to 600 and vice-versa. Not sure why it is doing that. Also, the line count reduces from 1200 to 800.

I am new to the framework and the IDE and cannot post the actual code. Any help is much appreciated. Thank you.