text:
Q: How can one prevent duplicate setTimeout resulting from complex state change? I apologize for the complexity of the code this question is based around, but it seems the issue itself is arising from the complexity. I wasn't able to replicate the issue with a simpler example. Here is the code repository branch with the issue: https://github.com/chingu-voyages/v42-geckos-team-21/commit/3c20cc55e66e7d0f9122d843222980e404d4910f The left hand (before the change) uses useRef() and does not have the issue, but I don't think useRef() respect's its proper usage.
Here is the main problem code:
import { useState, useRef} from 'react';
import "./Alert.css"
import "animate.css"
import { CSSTransition } from "react-transition-group"
import { time } from 'console';

console.log(typeof CSSTransition);

interface IfcProps {
  text: React.ReactNode,
  exitAfterDuration: number,
  setAlertKey: React.Dispatch<React.SetStateAction<number>>,
  alertKey: number
}

const classNames = {
  appear: 'animate__bounce',
  appearActive: 'animate__bounce',
  appearDone: 'animate__bounce',
  enter: 'animate__bounce',
  enterActive: 'animate__bounce',
  enterDone: 'animate__bounce',
  exit: 'animate__bounce',
  exitActive: 'animate__fadeOut',
  exitDone: 'animate__fadeOut'
}

function Alert(props: IfcProps) {

  const nodeRef = useRef(null);

  let [isIn, setIsIn] = useState(false);
  let [previousAlertKey, setPreviousAlertKey] = useState(0);
  let [timeoutId, setTimeoutId] = useState<number | null>(null);

  // console.log('props', {...props});
  console.log('prev, pres', previousAlertKey, props.alertKey)
  console.log('state', {isIn, previousAlertKey, timeoutId});

  // console.log('prev, current:', previousAlertKey, props.alertKey);
  if (props.text === '') {
    // do not render if props.text === ''
    return null;
  } else if (previousAlertKey !== props.alertKey) {

    setIsIn(true);
    setPreviousAlertKey(oldPreviousAlertKey => {

      oldPreviousAlertKey++
      return oldPreviousAlertKey;
    });

    if (timeoutId) {
      console.log(timeoutId, 'timeout cleared');
      clearTimeout(timeoutId);
    }

    let localTimeoutId = window.setTimeout(() => {
      console.log('executing timeout')
      setIsIn(false);
    }, props.exitAfterDuration);

    console.log({localTimeoutId}, previousAlertKey, props.alertKey);
    setTimeoutId(localTimeoutId);

  }

  return (
    <CSSTransition nodeRef={nodeRef} in={isIn} appear={true} timeout={1000} classNames={classNames}>
      {/* Using key here to trigger rebounce on alertKey change */}

        {props.text}

    </CSSTransition>
  )
}

export default Alert

Code that resolves issue but probably uses useRef() incorrectly:
import { useState, useRef } from 'react';
import "./Alert.css"
import "animate.css"
import { CSSTransition } from "react-transition-group"
import { time } from 'console';

console.log(typeof CSSTransition);

interface IfcProps {
  text: React.ReactNode,
  exitAfterDuration: number,
  setAlertKey: React.Dispatch<React.SetStateAction<number>>,
  alertKey: number
}

const classNames = {
  appear: 'animate__bounce',
  appearActive: 'animate__bounce',
  appearDone: 'animate__bounce',
  enter: 'animate__bounce',
  enterActive: 'animate__bounce',
  enterDone: 'animate__bounce',
  exit: 'animate__bounce',
  exitActive: 'animate__fadeOut',
  exitDone: 'animate__fadeOut'
}

function Alert(props: IfcProps) {

  const nodeRef = useRef(null);
  const timeoutIdRef = useRef<number | null>(null);

  let [isIn, setIsIn] = useState(false);
  let [previousAlertKey, setPreviousAlertKey] = useState(0);

  console.log({props});
  console.log('state', {isIn, previousAlertKey, timeoutIdRef});

  console.log('prev, current:', previousAlertKey, props.alertKey);
  if (props.text === '') {
    // do not render if props.text === ''
    return null;
  } else if (previousAlertKey !== props.alertKey) {

    setIsIn(true);
    setPreviousAlertKey(oldPreviousAlertKey => {

      oldPreviousAlertKey++
      return oldPreviousAlertKey;
    });

    if (timeoutIdRef.current) {
      console.log(timeoutIdRef.current, 'timeout cleared');
      clearTimeout(timeoutIdRef.current);
    }

    let localTimeoutId = window.setTimeout(() => setIsIn(false), props.exitAfterDuration);

    console.log({localTimeoutId}, previousAlertKey, props.alertKey);
    timeoutIdRef.current = localTimeoutId;
  }

  return (
    <CSSTransition nodeRef={nodeRef} in={isIn} appear={true} timeout={1000} classNames={classNames}>
      {/* Using key here to trigger rebounce on alertKey change */}

        {props.text}

    </CSSTransition>
  )
}

export default Alert

The issue shows its head when an invalid row is attempted to be submitted to the database and the Alert component appears. If multiple alerts are triggered in this way, they all disappear when the first setTimeout expires because it was never cleared properly. One timeout should be cleared but because React strict mode renders twice and the creation of a timeout is a side effect, the extra timeout never gets cleared. React isn't aware that there are two timeouts running for every submission attempt (check-mark click).
I'm probably handling my alert component incorrectly, with the alertKey for example.
I feel my problem is related to the fact that my setTimeout is triggered inside the Alert component as opposed to inside the Row component's onClick() handler, as I did so in a simpler example and it did not exhibit the issue.
I fear I may not get any replies as this is a pretty ugly and complex case that requires a fair bit of setup to the dev environment. This may well be a case where I just have to cobble together a solution (e.g. with useRef) and learn the proper React way in the future through experience. Tunnel-vision is one of my faults.

A: tl;dr Use the dependency array in useHook()
So I took a step back and worked on some other parts of the app, while sometimes doing some research into how others handle a toast notification component, which is what I was effectively working on in the code here. Logrocket's article was helpful: How to create a custom toast component with React.
@Azzy helped put me back on the right track and the article above also uses the useEffect() hook for the timeout.
In my spare time, eventually I came across this article A Simple Explanation of React.useEffect(). The author, Dmitri Pavlutin, finally got it into my head the intended relation of the main component function body and the useEffect hook.

A functional React component uses props and/or state to calculate the
output. If the functional component makes calculations that don't
target the output value, then these calculations are named
side-effects.
. . .
The component rendering and side-effect logic are independent. It
would be a mistake to perform side-effects directly in the body of the
component, which is primarily used to compute the output.
How often the component renders isn't something you can control — if
React wants to render the component, you cannot stop it.
. . .
How to decouple rendering from the side-effect? Welcome useEffect() —
the hook that runs side-effects independently of rendering.

I now present the code that works and is the React way, (or at least is more like the optimal React way than my two previous attempts, see above).
function Alert(props: IfcProps) {
  useEffect(() => {
    let timeoutId = window.setTimeout(() => setIsIn(false), props.exitAfterDuration);

    return function cleanup() {
      window.clearTimeout(timeoutId);
    }

  }, [props.alertKey]);

  const nodeRef = useRef(null);
  const timeoutIdRef = useRef<number | null>(null);

  let [isIn, setIsIn] = useState(false);
  let [previousAlertKey, setPreviousAlertKey] = useState(0);

  console.log({ props });
  console.log('state', { isIn, previousAlertKey, timeoutIdRef });

  console.log('prev, current:', previousAlertKey, props.alertKey);
  if (props.text === '') {
    // do not render if props.text === ''
    return null;
  } else if (previousAlertKey !== props.alertKey) {

    setIsIn(true);
    setPreviousAlertKey(oldPreviousAlertKey => {

      oldPreviousAlertKey++
      return oldPreviousAlertKey;
    });
  }

  return (
    <CSSTransition nodeRef={nodeRef} in={isIn} appear={true} timeout={1000} classNames={classNames}>
      {/* Using key here to trigger rebounce on alertKey change */}

        {props.text}

    </CSSTransition>
  )
}

export default Alert

To be honest, there's probably a lot of refactoring I can do now that I understand the utility of useEffect(). I likely have other components with side effects dependent on logic dedicated to checking if the current render happened because specific state / props changed. useEffect()'s dependency array is a lot cleaner than conditionals in the function body checking for those state/prop changes.
A lot of the complexity I lamented in my question arose I think because I wasn't properly separating side effects from my main function body.
Thank you for coming to my TED talk. :)


text:
Q: Drag drop does not work on compiled EXE file I added a functionality to my C# windows form application which allows user to drag-drop file on the form so that the application can get the file path. I just exactly followed what's written on:
How to provide file drag-and-drop functionality in a Visual C# application
It is working on debug mode in Visual Studio environment. However, as soon as I try the same thing on individual exe file which is created on bin/Debug folder, the application does not react to drag-drop.
I have already tried to delete all the files on bin/Debug folder, but the result did not change.
It would be great if somebody has similar issue and solutions for this. Thank you.

Here are the codes I'm trying (after some try and errors it has changed a bit from what's written in the URL shown above, but this still works on Visual Studio but not on exe...) :
    private void OpenFile_DragEnter(object sender, DragEventArgs e)
    // enable drag-drop event
    {
        e.Effect = DragDropEffects.Copy;
    }

    private void OpenFile_DragDrop(object sender, DragEventArgs e)
    // open drag-dropped setup file
    {
        // get drag-dropped file path
        string[] s = (string[])e.Data.GetData(DataFormats.FileDrop, false);

        // open all the files
        for (int i = 0; i < s.Length; i++)
        {
            OpenSetup(s[i]);
        }
    }

Update: Another thing I found is that I can drag-drop the files on EXE from OpenFileDialog, but not from file exploler.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Access to values of a double pointer of integers in a function in C In a SUDOKU project, I created a function to type in a dynamic matrix and fill it, however I can't figure out how to use the values of this dynamic matrix in other functions, to be precise I don't know how to pass the matrix as a function parameter in order to change or make some tests on its values.
For example, the function typematrix has this header:
int **typematrix();

If for example I wanted to show the values of this matrix using a created function, named for example showMatrixValues, I wrote like so:
void showMatrixValues(int **matrix[9][9]);

Yet somehow I get errors on conflicting types or the fact that I'm passing an argument makes pointer without cast when using both functions in main, using a local variable:
   int  **matrix[9][9];


text:
Q: Indentação e quebra de linha em dados do sql para html Em resumo, criei uma tabela com tipo text no sql para que o usuario possa salvar algum conteúdo.
Porem ao puxa-lo denovo para o HTML a formatação se perde.
Para sanar isso eu pensei em utilizar a tag
, mas a tag
 enche meu layout de bugs, como recuo grande demais apenas no primeiro paragrafo, e não quebra a linha se o texto for grande demais, ele expande a largura da pagina. Tem alguma forma própria para manter essa formatação do texto?
Ps. o codigo em questão deverá retornar registros diversos, então não tem como prever onde a quebra de linha vai aparecer. A imagem abaixo foi so um registro aleatório para teste

Segue abaixo o codigo backend utilizado:
entrada:
$query = $conect -> query( 'INSERT INTO textos (texto) VALUES({$_POST['texto']}')');

saida:
$query = $conect -> query("SELECT * FROM textos");

no html / php:
while ($temp = $query->fetch_assoc() ) { ?>

          <?PHP echo $temp['texto']; ?>

<?php}  ?>


text:
Q: Acces to spider variable in pipeline I have this on my scrapy spider
def __init__(self, table=''):
    super(MgdealBotCrawlerSpider, self).__init__()
    self.table_name = table

I used this to start the spider from command line
scrapy crawl mgdeal_bot_crawler -a table=lego

I would like to use this arg to create a new table when the item is process here. how i can do it in pipeline.py
  def process_item(self, item, spider):

    # run db query in the thread pool
    d = self.dbpool.runInteraction(self._do_upsert, item, spider)
    d.addErrback(self._handle_error, item, spider)
    # at the end return the item in case of success or failure
    d.addBoth(lambda _: item)
    # return the deferred instead the item. This makes the engine to
    # process next item (according to CONCURRENT_ITEMS setting) after this
    # operation (deferred) has finished.
    return d

def _do_upsert(self, conn, item, spider):
    """Perform an insert or update."""

    guid = self._get_guid(item)
    now = datetime.utcnow().replace(microsecond=0).isoformat(' ')

    conn.execute("""SELECT EXISTS(
        SELECT 1 FROM"""+table_name+"""WHERE guid = %s
    )""", (guid, ))
    ret = conn.fetchone()[0]

It seems i can't access to it . How can i managed to do this?

A: If I understand you correctly you need to access the attribute using the spider instance spider.table_name:
def _do_upsert(self, conn, item, spider):
    """Perform an insert or update."""

    guid = self._get_guid(item)
    now = datetime.utcnow().replace(microsecond=0).isoformat(' ')

    conn.execute("""SELECT EXISTS(
        SELECT 1 FROM"""+spider.table_name+"""WHERE guid = %s
    )""", (guid, ))
    ret = conn.fetchone()[0]


text:
Q: java.lang.OutOfMemoryError: GC overhead limit exceeded while running findbugs in maven So basically the current configuration works for all the builds. But this time. Added some code to the project, but this time the build fails and throws

java.lang.OutOfMemoryError: GC overhead limit exceeded

while FindBugs analysis. while searching out more on this I found out there is a <effort> option in the FindBugs configuration in the POM file. So I tried to set it to <effort>min</effort> it was <effort>max</effort> before. But this also does not seems to be working. Also there is a restriction in changing VM parameters so I am not allowed to do it.
Stack trace:
Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
     [java]     at java.util.BitSet.initWords(BitSet.java:166)
     [java]     at java.util.BitSet.<init>(BitSet.java:143)
     [java]     at edu.umd.cs.findbugs.ba.LiveLocalStoreAnalysis.createFact(LiveLocalStoreAnalysis.java:58)
     [java]     at edu.umd.cs.findbugs.ba.LiveLocalStoreAnalysis.createFact(LiveLocalStoreAnalysis.java:45)
     [java]     at edu.umd.cs.findbugs.ba.Dataflow.execute(Dataflow.java:318)
     [java]     at edu.umd.cs.findbugs.classfile.engine.bcel.LiveLocalStoreDataflowFactory.analyze(LiveLocalStoreDataflowFactory.java:68)
     [java]     at edu.umd.cs.findbugs.classfile.engine.bcel.LiveLocalStoreDataflowFactory.analyze(LiveLocalStoreDataflowFactory.java:38)
     [java]     at edu.umd.cs.findbugs.classfile.impl.AnalysisCache.analyzeMethod(AnalysisCache.java:369)
     [java]     at edu.umd.cs.findbugs.classfile.impl.AnalysisCache.getMethodAnalysis(AnalysisCache.java:

I am not able to find whether something is wrong with my new code which I added or it is the problem with the FindBugs. My code is just a regular stuff (I believe that). Even if something is wrong with my code FindBugs is supposed to report it instead of crashing the JVM itself.
We use FindBugs 3.0.5 with default JVM options

A: Actually, After lots of efforts and research, the found an option in the maven findbugs help documentation within maven a way to specify heap size  of the forked jvm as indicated by @second in the first comment of the question. SO inside the POM XML within the  inside the findbug's  tag I can specify  1024 like the following:
<plugin>
    <groupId>com.github.findbugs</groupId>
    <artifactId>findbugs-maven-plugin</artifactId>
    <version>3.1.12</version>
    <configuration>
       ...
      <maxHeap>1024</maxHeap>
       ...
    </configuration>
       ...
  </plugin>

I almost forgot to post back. Leaving it here in the hope to help someone like me when I was. Thanks to @second for pointing in the right direction.


text:
Q: Unable to resolve java.lang.ClassCastException I am trying to develop my first android app but am stuck at the following error - 'java.lang.ClassCastException. Here is my java code:
package com.example.fresh24;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class CartAdapter extends RecyclerView.Adapter {

    private List<CartItemModel> cartItemModelList;

    public CartAdapter(List<CartItemModel> cartItemModelList) {
        this.cartItemModelList = cartItemModelList;
    }

    @Override
    public int getItemViewType(int position) {
        switch (cartItemModelList.get(position).getType()) {
            case 0:
                return CartItemModel.CART_ITEM;
            case 1:
                return CartItemModel.TOTAL_AMOUNT;
            default:
                return -1;
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        switch (viewType) {
            case CartItemModel.CART_ITEM:
                View cartItemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cart_item_layout, viewGroup, false);
                return new CartItemViewHolder(cartItemView);
            case CartItemModel.TOTAL_AMOUNT:
                View cartTotalView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cart_total_amount_layout, viewGroup, false);
                return new CartItemViewHolder(cartTotalView);
            default:
                return null;
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {
        switch (cartItemModelList.get(position).getType()) {
            case CartItemModel.CART_ITEM:
                int resource = cartItemModelList.get(position).getProductImage();
                String title = cartItemModelList.get(position).getProducTitle();
                int freeCoupons = cartItemModelList.get(position).getFreeCoupons();
                String productPrice = cartItemModelList.get(position).getProductPrice();
                String cutPrice = cartItemModelList.get(position).getCutPrice();
                int offersApplied = cartItemModelList.get(position).getOffersApplied();
                ((CartItemViewHolder)viewHolder).setItemDetails(resource,title,freeCoupons,productPrice,cutPrice,offersApplied);
                break;
            case CartItemModel.TOTAL_AMOUNT:
                String totalItems = cartItemModelList.get(position).getTotalItems();
                String totalItemsPrice = cartItemModelList.get(position).getTotalItemPrice();
                String conveniencePrice = cartItemModelList.get(position).getConveniencePrice();
                String totalAmount = cartItemModelList.get(position).getTotalAmount();
                String savedAmount = cartItemModelList.get(position).getSavedAmount();
                ((CartTotalAmountViewHolder)viewHolder).setTotalAmount(totalItems,totalItemsPrice,conveniencePrice,totalAmount,savedAmount);
                break;
            default:
                return;
        }
    }

    @Override
    public int getItemCount() {
        return cartItemModelList.size();
    }

    class CartItemViewHolder extends RecyclerView.ViewHolder {
        private ImageView productImage;
        private ImageView freecouponIcon;
        private TextView productTitle;
        private TextView freeCoupons;
        private TextView productPrice;
        private TextView productCutPrice;
        private TextView offersApplied;
        /*private TextView couponsApplied;
        private TextView productQuantity;*/

        public CartItemViewHolder(@NonNull View itemView) {
            super(itemView);
            productImage = itemView.findViewById(R.id.product_image);
            productTitle = itemView.findViewById(R.id.product_title);
            freecouponIcon = itemView.findViewById(R.id.free_coupon_icon);
            freeCoupons = itemView.findViewById(R.id.tv_free_coupon);
            productPrice = itemView.findViewById(R.id.product_price);
            productCutPrice = itemView.findViewById(R.id.cut_price);
            offersApplied = itemView.findViewById(R.id.offers_applied);

        }

        private void setItemDetails(int resource, String title, int freeCouponsNo, String productPriceText, String productCutPriceText, int offersAppliedNo) {
            productImage.setImageResource(resource);
            productTitle.setText(title);
            if (freeCouponsNo > 0) {
                freecouponIcon.setVisibility(View.VISIBLE);
                freeCoupons.setVisibility(View.VISIBLE);
                if (freeCouponsNo == 1) {
                    freeCoupons.setText("free " + freeCouponsNo + " Coupon");
                } else {
                    freeCoupons.setText("free " + freeCouponsNo + " Coupons");
                }
            } else {
                freecouponIcon.setVisibility(View.INVISIBLE);
                freeCoupons.setVisibility(View.INVISIBLE);
            }
            productPrice.setText(productPriceText);
            productCutPrice.setText(productCutPriceText);
            if (offersAppliedNo > 0) {
                offersApplied.setVisibility(View.VISIBLE);
                offersApplied.setText(offersAppliedNo + "Offers Applied");
            } else {
                offersApplied.setVisibility(View.INVISIBLE);
            }
        }
    }

    class CartTotalAmountViewHolder extends RecyclerView.ViewHolder {

        private TextView totalItems;
        private TextView totalItemPrice;
        private TextView conveniencePrice;
        private TextView totalAmount;
        private TextView savedAmount;

        public CartTotalAmountViewHolder(@NonNull View itemView) {
            super(itemView);
            totalItems = itemView.findViewById(R.id.total_items);
            totalItemPrice = itemView.findViewById(R.id.total_items_price);
            conveniencePrice = itemView.findViewById(R.id.convenience_price);
            totalAmount = itemView.findViewById(R.id.total_price);
            savedAmount = itemView.findViewById(R.id.saved_amount);
        }

        private void setTotalAmount(String totalItemText, String totalItemPriceText, String conveniencePriceText, String totalAmountText, String savedAmountText) {
            totalItems.setText(totalItemText);
            totalItemPrice.setText(totalItemPriceText);
            conveniencePrice.setText(conveniencePriceText);
            totalAmount.setText(totalAmountText);
            savedAmount.setText(savedAmountText);
        }
    }
}

and here is the complete stack trace:
2019-08-01 09:51:45.298 26950-26950/com.example.fresh24 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.fresh24, PID: 26950
    java.lang.ClassCastException: com.example.fresh24.CartAdapter$CartItemViewHolder cannot be cast to com.example.fresh24.CartAdapter$CartTotalAmountViewHolder
        at com.example.fresh24.CartAdapter.onBindViewHolder(CartAdapter.java:67)
        at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6781)
        at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6823)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5752)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6019)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5858)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5854)
        at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
        at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
        at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)
        at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3924)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3641)
        at androidx.recyclerview.widget.RecyclerView.onLayout(RecyclerView.java:4194)
        at android.view.View.layout(View.java:17523)
        at android.view.ViewGroup.layout(ViewGroup.java:5612)
        at androidx.constraintlayout.widget.ConstraintLayout.onLayout(ConstraintLayout.java:1915)
        at android.view.View.layout(View.java:17523)
        at android.view.ViewGroup.layout(ViewGroup.java:5612)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:17523)
        at android.view.ViewGroup.layout(ViewGroup.java:5612)
        at com.google.android.material.appbar.HeaderScrollingViewBehavior.layoutChild(HeaderScrollingViewBehavior.java:142)
        at com.google.android.material.appbar.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:41)
        at com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1556)
        at androidx.coordinatorlayout.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:888)
        at android.view.View.layout(View.java:17523)
        at android.view.ViewGroup.layout(ViewGroup.java:5612)
        at androidx.drawerlayout.widget.DrawerLayout.onLayout(DrawerLayout.java:1231)
        at android.view.View.layout(View.java:17523)
        at android.view.ViewGroup.layout(ViewGroup.java:5612)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:17523)
        at android.view.ViewGroup.layout(ViewGroup.java:5612)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
        at android.view.View.layout(View.java:17523)
        at android.view.ViewGroup.layout(ViewGroup.java:5612)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:17523)
        at android.view.ViewGroup.layout(ViewGroup.java:5612)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
        at android.view.View.layout(View.java:17523)
        at android.view.ViewGroup.layout(ViewGroup.java:5612)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
2019-08-01 09:51:45.298 26950-26950/com.example.fresh24 E/AndroidRuntime:     at com.android.internal.policy.DecorView.onLayout(DecorView.java:724)
        at android.view.View.layout(View.java:17523)
        at android.view.ViewGroup.layout(ViewGroup.java:5612)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2342)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2069)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1246)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6301)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:871)
        at android.view.Choreographer.doCallbacks(Choreographer.java:683)
        at android.view.Choreographer.doFrame(Choreographer.java:619)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6077)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)

I have gone through documentation regarding the CastException but I am unable to figure out the source of the error. Please help. Thanks in advance.

A: Problem is  here
View cartTotalView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cart_total_amount_layout, viewGroup, false);
return new CartItemViewHolder(cartTotalView); // Returning wrong ViewHolder it should be CartTotalAmountViewHolder


text:
Q: Search the contents in the html There are two different tags in the HTML which are row0-1 and row1-1. I want to search for the contents in the HTML called row1Time from the row1-1 tag.
Here's and example HTML:

    4:00 PM

    3:00 PM

Here's my PHP:
    <?php
    $errmsg_arr = array();
    $errflag = false;
    $link;

    function db_connect()
    {
      define('DB_HOST', 'localhost');
      define('DB_USER', 'myusername');
      define('DB_PASSWORD', 'mypassword');
      define('DB_DATABASE', 'mydbname');

      $errmsg_arr = array();
      $errflag = false;
      $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);

      if(!$link)
      {
        die('Failed to connect to server: ' . mysql_error());
      }

      $db = mysql_select_db(DB_DATABASE);
      if(!$db)
      {
        die("Unable to select database");
      }
    }

    $links = $row['links'];
    include ('simple_html_dom.php');
    $html = file_get_html($links);
    //echo $row['links'];

    $base = $row['links'];

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_URL, $base);
    curl_setopt($curl, CURLOPT_REFERER, $base);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    $str = curl_exec($curl);
    curl_close($curl);

    // Create a DOM object
    $html = new simple_html_dom();
    // Load HTML from a string
    $html->load($str);

    //get all category links
    /*foreach($html_base->find('a') as $element) {
        echo "
";
        print_r( $element->href );
        echo "
";
    }*/

    //$html_base->clear();
    //unset($html_base);

    $time1 = $html->find('span[id=row1Time]', 0)->plaintext;
    echo ''.$time1.' - ';
?>

When I tried to parse the contents from the HTML using this:
$time1 = $html->find('span[id=row1Time]', 0)->plaintext;
echo ''.$time1.' - ';

The return output I get is from the tags row0-1 with row1Time:
4:00 PM

I want to search for the contents in the HTML from the tags row1-1 with row1Time to get the return contains 3:00 PM. Can you please help me get those contents using simple_html_dom?

A: You have mistaken me with your errors... please check your html code carefully!
You want to get the text withing the span element which is inside the li node with the id 'row1-1'. This can be translated to $html->find('li#row1-1', 0)->plaintext;
This is A full working code:
$input =  <<<_DATA_

    4:00 PM

    3:00 PM
_DATA_;

//Create a DOM object
$html = new simple_html_dom();
// Load HTML from a string
$html->load($input);

$time1 = $html->find('li#row1-1', 0)->plaintext;

echo $time1;

// Clear DOM object
$html->clear();
unset($html);

OUTPUT
3:00 PM

Please refer to the PHP Simple HTML DOM Parser Manual for more informations...


text:
Q: VIM save-execute-reload file While I am editing a file I occasionally want to save it, execute a command that may modify the file, then reload it. I.e. First :w, then :!something  %, and later :e
Can I somehow automate this so I can simply type a command that does all of the above three?

A: You can. Try this:
:command! -nargs=+ Doit :w | :exe "!" . <q-args> . " %" | :e

Or if you just want to "hard code" the command:
:command! Doit :w | :exe "!something %" | :e

Note that user-defined Vim commands must always start with an uppercase letter. For reference:
:help :command
:help <q-args>
:help :execute
:help :|


text:
Q: Email templates using bamboo without phoenix I am working on app in elixir. It sends email to clients. I am using bamboo library for sending emails.
So far, emails are working fine. But now, I am trying to send emails using templates.
Everywhere i see in the bamboo documentation is using
bamboo.phoenix .
I am not using phoenix for handling requests. I am using a library called plug. Is there a way to send templates in email without phoenix ??

A: Adding answer to this post with the help @JustMichael comment.
Directory structure -
/priv
 /static
  /test.html.eex

Function used :
new_email
|> to("vivek29vivek@gmail.com")
|> from(@from_email)
|> subject("test")
|> html_body(EEx.eval_file("priv/static/mail_templates/#test.html.eex",[foo: "bar"]))  //this will render the template.Also can pass variables

test.html.eex

Foo: <%= foo %>

But , we cannot add css just by adding <link rel="stylesheet" href="styles.css"> . I guess, There is a need for static server.
Do comment if there is another way to add css apart from inline css.


text:
Q: Change font-size based on selected option I would like the first-child in the option to have a different font-size. I'm trying various methods but it isn't happening. So far, I've got this:
JSFiddle: https://jsfiddle.net/2n9cfyo0/1/
I want it to appear this way by default (this is the first-child):

but change the font-size to 24px when the dropdown is chosen:

select {
  -moz-appearance: none;
  -webkit-appearance: none;
  appearance: none;
  padding: 7px 15px;
  border: 1px solid #333;
  border-radius: 2px;
  font-size: 24px;
}

.target option:first-child {
  font-size: 12;
}
<select class="target">
  <option value="">select</option>
  <option value="1">option 1</option>
  <option value="2">option 2</option>
</select>

A: I've created a jsfiddle to achieve the same result that is required. It would require javascript & jquery to achieve the result you're expecting. Changing the dropdown from one form to another is an Event, and Events exists in Jquery, in your case, we've to use .change() event.
Add the below javascript code :
$(".target").change(function(){
   if (this.value == "2") {
     $(this).css({"font-size" : "34px"});
   }
});

the above code says that when you select Option 2 from the dropdown, it would change the size of font to 34px;, you can modify the fiddle according to your needs :)

$(".target").change(function() {
  if (this.value == "2") {
    $(this).css({
      "font-size": "34px"
    });
  }
});
select {
  -moz-appearance: none;
  -webkit-appearance: none;
  appearance: none;
  padding: 7px 15px;
  border: 1px solid #333;
  border-radius: 2px;
  font-size: 24px;
}

.target option:first-child {
  font-size: 12;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="target">
  <option value="">select</option>
  <option value="1">option 1</option>
  <option value="2">option 2</option>
</select>


text:
Q: query hive partitioned table over date/time range My hive table is partitioned on year, month, day, Hour
Now I want to fetch data from 2014-05-27 to 2014-06-05
How can I do that??
I know one option is create partition on epoch(or yyyy-mm-dd-hh) and in query pass epoch time.
Can I do it without loosing date hierarchy??
Table Structure
CREATE TABLE IF NOT EXISTS table1 (col1 int, col2 int)
PARTITIONED BY (year int, month int, day int, hour int)
STORED AS TEXTFILE;

A: you can query like this
  WHERE st_date > '2014-05-27-00' and end_date < '2014-06-05-24'

should give you desired result because even if it is a sting a it will be compared lexicographically i.e '2014-04-04' will be always greater '2014-04-03'.
I ran it on my sample tables and it works perfectly fine.

A: This is a similar scenario we face everyday while querying tables in hive. We have partitioned our tables similar to the way you explained and it has helped a lot if querying. This is how we partition:
CREATE TABLE IF NOT EXISTS table1 (col1 int, col2 int)
PARTITIONED BY (year bigint, month bigint, day bigint, hour int)
STORED AS TEXTFILE;

For partitions we assign values like this:
year = 2014, month = 201409, day = 20140924, hour = 01

This way the querying becomes really simple and you can directly query:
select * from table1 where day >= 20140527 and day < 20140605

Hope this helps

A: You can use CONCAT with LPAD.
Say you want to get all partitions between 2020-03-24, hour=00 to 2020-04-24, hour=23, then, your 'where' condition would look like:
WHERE (CONCAT(year, '-', LPAD(month,2,'0'), '-', LPAD(day,2,'0'), '_', LPAD(hour,2,'0')) > '2020-03-24_00')
AND (CONCAT(year, '-', LPAD(month,2,'0'), '-', LPAD(day,2,'0'), '_', LPAD(hour,2,'0')) < '2020-04-24_23')


text:
Q: Grouped UITableView bottom border I have a small issue with a UITableView and it's background color. I am getting this strange footer at the end of the UITableView as you can see in the image below.

I've tried setting the border to [UIColor clearColor] but unfortunately that didn't help. Does anyone know why this is happening? (And how to fix it?)

A: Have you tried changing the separator style, either in Interface Builder or programmatically by setting your UITableView's separatorStyle property?
It looks like you may currently have this set to UITableViewCellSeparatorStyleSingleLineEtched, which is documented as follows. You could try UITableViewCellSeparatorStyleNone instead.

UITableViewCellSeparatorStyleSingleLineEtched
  The separator cell has double lines running across its width, giving it an etched look. This style is currently only supported for grouped-style table views.


text:
Q: - , *, / operators not working on my basic calculator (javafx) I'm working on this basic calculator project using javafx and fxml on eclipse. + operators work perfectly fine, but the /, -, * always gives an output of zero. Can't figure out the problem
Here is the class that process the input :
public class MainProcess {
    @FXML
    public Label result;

    private long num1 = 0;
    private long num2 = 0;
    private String operator = "";

    private boolean start = true;
    private Calculation model = new Calculation();

    @FXML
    public void processNumbers(ActionEvent event) {
        if (start)
        {
            result.setText("");
            start = false;
        }

        String value = ((Button)event.getSource()).getText();
        result.setText(result.getText() + value);
    }

    @FXML
    public void processOperators(ActionEvent event)
    {

        String value = ((Button)event.getSource()).getText();

        if (!value.equals("="))
        {
            if (!operator.isEmpty())
                return;

            operator = value;
            num1 = Long.parseLong(result.getText());
            result.setText("");
            return;
            }
        else
        {
            if (operator.isEmpty())
                return;
            num2 = Long.parseLong(result.getText());

            long output = model.calculate(num1, num2, operator);
            result.setText(String.valueOf(output));
            operator = "";
            start = true;

        }
    }

    @FXML
    public void Ac(ActionEvent event) {
        operator = "";
        start = true;
        result.setText("");
    }

}

Here is the class that is doing the arithmetic :
public class Calculation {

    public long calculate(long num1, long num2, String operator)
    {
        switch (operator)
        {
        case "+":
            return num1+num2;
        case "-":
            return num1-num2;
        case "*":
            return num1*num2;
        case "/":
            if(num2==0)
                return 0;
            return num1/num2;
        default:
            return 0 ;
        }

}

}

Here is the fxml :
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.text.Font?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="537.0" prefWidth="298.0" style="-fx-background-color: rgba(0,0,0,0);" xmlns="http://javafx.com/javafx/18" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.MainProcess">
   <children>
      <VBox alignment="CENTER" prefHeight="200.0" prefWidth="100.0" style="-fx-background-color: #1C1C1C; -fx-background-radius: 30;" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
         <children>

               <VBox.margin>
                  <Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
               </VBox.margin>

            <GridPane alignment="CENTER" hgap="10.0" vgap="10.0">
              <columnConstraints>
                <ColumnConstraints hgrow="SOMETIMES" maxWidth="-Infinity" minWidth="-Infinity" />
                  <ColumnConstraints hgrow="SOMETIMES" maxWidth="-Infinity" minWidth="-Infinity" />
                  <ColumnConstraints hgrow="SOMETIMES" maxWidth="-Infinity" minWidth="-Infinity" />
                <ColumnConstraints hgrow="SOMETIMES" maxWidth="-Infinity" minWidth="-Infinity" />
              </columnConstraints>
              <rowConstraints>
                <RowConstraints maxHeight="-Infinity" minHeight="10.0" vgrow="SOMETIMES" />
                <RowConstraints maxHeight="-Infinity" minHeight="10.0" vgrow="SOMETIMES" />
                <RowConstraints maxHeight="-Infinity" minHeight="10.0" vgrow="SOMETIMES" />
                  <RowConstraints maxHeight="-Infinity" minHeight="10.0" vgrow="SOMETIMES" />
                  <RowConstraints maxHeight="-Infinity" minHeight="10.0" vgrow="SOMETIMES" />
                  <RowConstraints maxHeight="-Infinity" minHeight="10.0" vgrow="SOMETIMES" />
              </rowConstraints>
               <children>
                  <Button mnemonicParsing="false" prefHeight="55.0" prefWidth="55.0" style="-fx-background-radius: 30; -fx-background-color: #D4D4D2;" text="+/-" GridPane.columnIndex="1">

                  </Button>
                  <Button mnemonicParsing="false" prefHeight="55.0" prefWidth="55.0" style="-fx-background-radius: 30; -fx-background-color: #D4D4D2;" text="\%" GridPane.columnIndex="2">

                  </Button>
                  <Button mnemonicParsing="false" onAction="#processOperators" prefHeight="55.0" prefWidth="55.0" style="-fx-background-color: FF9500; -fx-background-radius: 30;" text="/" textFill="WHITE" GridPane.columnIndex="3">

                  </Button>
                  <Button mnemonicParsing="false" onAction="#processNumbers" prefHeight="55.0" prefWidth="55.0" style="-fx-background-radius: 30; -fx-background-color: #505050;" text="4" textFill="WHITE" GridPane.rowIndex="2">

                  </Button>
                  <Button mnemonicParsing="false" onAction="#processNumbers" prefHeight="55.0" prefWidth="55.0" style="-fx-background-radius: 30; -fx-background-color: #505050;" text="7" textFill="WHITE" GridPane.rowIndex="1">

                  </Button>
                  <Button mnemonicParsing="false" onAction="#processNumbers" prefHeight="55.0" prefWidth="55.0" style="-fx-background-radius: 30; -fx-background-color: #505050;" text="8" textFill="WHITE" GridPane.columnIndex="1" GridPane.rowIndex="1">

                  </Button>
                  <Button mnemonicParsing="false" onAction="#processNumbers" prefHeight="55.0" prefWidth="55.0" style="-fx-background-radius: 30; -fx-background-color: #505050;" text="5" textFill="WHITE" GridPane.columnIndex="1" GridPane.rowIndex="2">

                  </Button>
                  <Button mnemonicParsing="false" onAction="#processNumbers" prefHeight="55.0" prefWidth="55.0" style="-fx-background-radius: 30; -fx-background-color: #505050;" text="9" textFill="WHITE" GridPane.columnIndex="2" GridPane.rowIndex="1">

                  </Button>
                  <Button mnemonicParsing="false" onAction="#processNumbers" prefHeight="55.0" prefWidth="55.0" style="-fx-background-radius: 30; -fx-background-color: #505050;" text="6" textFill="WHITE" GridPane.columnIndex="2" GridPane.rowIndex="2">

                  </Button>
                  <Button mnemonicParsing="false" onAction="#processOperators" prefHeight="55.0" prefWidth="55.0" style="-fx-background-color: FF9500; -fx-background-radius: 30;" text="x" textFill="WHITE" GridPane.columnIndex="3" GridPane.rowIndex="1">

                  </Button>
                  <Button mnemonicParsing="false" onAction="#processOperators" prefHeight="55.0" prefWidth="55.0" style="-fx-background-color: FF9500; -fx-background-radius: 30;" text="−" textFill="WHITE" GridPane.columnIndex="3" GridPane.rowIndex="2">

                  </Button>
                  <Button mnemonicParsing="false" onAction="#processNumbers" prefHeight="55.0" prefWidth="55.0" style="-fx-background-radius: 30; -fx-background-color: #505050;" text="1" textFill="WHITE" GridPane.rowIndex="3">

                  </Button>
                  <Button mnemonicParsing="false" onAction="#processNumbers" prefHeight="55.0" prefWidth="55.0" style="-fx-background-radius: 30; -fx-background-color: #505050;" text="2" textFill="WHITE" GridPane.columnIndex="1" GridPane.rowIndex="3">

                  </Button>
                  <Button mnemonicParsing="false" onAction="#processNumbers" prefHeight="55.0" prefWidth="55.0" style="-fx-background-radius: 30; -fx-background-color: #505050;" text="3" textFill="WHITE" GridPane.columnIndex="2" GridPane.rowIndex="3">

                  </Button>
                  <Button mnemonicParsing="false" onAction="#processOperators" prefHeight="55.0" prefWidth="55.0" style="-fx-background-color: FF9500; -fx-background-radius: 30;" text="+" textFill="WHITE" GridPane.columnIndex="3" GridPane.rowIndex="3">

                  </Button>
                  <Button mnemonicParsing="false" onAction="#processNumbers" prefHeight="57.0" prefWidth="110.0" style="-fx-background-radius: 30; -fx-background-color: #505050;" text="0" textFill="WHITE" GridPane.columnSpan="2" GridPane.rowIndex="4">

                  </Button>
                  <Button mnemonicParsing="false" prefHeight="55.0" prefWidth="55.0" style="-fx-background-radius: 30; -fx-background-color: #505050;" text="," textFill="WHITE" GridPane.columnIndex="2" GridPane.rowIndex="4">

                  </Button>
                  <Button mnemonicParsing="false" onAction="#processOperators" prefHeight="55.0" prefWidth="55.0" style="-fx-background-color: FF9500; -fx-background-radius: 30;" text="=" textFill="WHITE" GridPane.columnIndex="3" GridPane.rowIndex="4">

                  </Button>
                  <Button mnemonicParsing="false" onAction="#Ac" prefHeight="55.0" prefWidth="55.0" style="-fx-background-radius: 30; -fx-background-color: #D4D4D2;" text="AC">

                  </Button>
               </children>
            </GridPane>
         </children>
      </VBox>
   </children>
</AnchorPane>

Note that in my fxml, each button is associated to the right method, so the problem must come from the javafx code
** Sorry if the way of asking the question is not right, Ill take any good advice
Thanks!


text:
Q: How to make newsboat autorefresh every minute? I always have newsboat open in a terminal at the corner of my desktop. I would like newsboat to auto refresh every minute or so so i don't have to do it manually. Is there a way to do this?
I understand that creating a config file in the directory makes newsboat refresh the feeds when you open newsboat. But I would like newsboat to continue to refresh the feeds, is there a way to do that?

A: You have to configure the application according to its documentation.
Create two files with urls and options. Below is minimal reproducible example:
echo "https://askubuntu.com/feeds" > ~/.newsboat/urls

cat << EOF > ~/.newsboat/config
auto-reload yes
reload-time 1
EOF

Then run NewsBoat with newsboat -r . It will refresh every 1 minute.

See man newsboat for details locally or online.


text:
Q: WPF combobox. Как прибандить SelectedItem при динамическом додавлении ComboboxItem Все привет. У меня возникла проблема. При редактировании заявки я додаю участников заявки с выбраным документом. Естественно додаю динамически, полаченные з БД. Додаю в контейнер Grid. И ComboBox додаю динамически, естественно. Вопрос: как для каждого ComboBox задать свой SelectedItem?
Вот мой тип доданых документов
public class OrderMember : BindableBase
{
    public long ID { get; set; }

    public string Name { get; set; }

    public IList<ClientDocument> Documents { get; set; }

    private ClientDocument _selectedDocument;
    public ClientDocument SelectedDocument
    {
        get { return _selectedDocument; }
        set
        {
            _selectedDocument = value;
            RaisePropertyChanged();
        }
    }
}

А вот я додаю список елементов
            int rowNum = 1;
            foreach (var m in OrderMembers)
            {
                RowDefinition row = new RowDefinition();
                grOrderMembers.RowDefinitions.Add(row);

                TextBlock tbID = new TextBlock();
                tbID.Text = m.ID.ToString();
                Grid.SetColumn(tbID, 0);
                Grid.SetRow(tbID, rowNum);
                grOrderMembers.Children.Add(tbID);

                TextBlock tbFullName = new TextBlock();
                tbFullName.Text = m.Name;
                Grid.SetColumn(tbFullName, 1);
                Grid.SetRow(tbFullName, rowNum);
                grOrderMembers.Children.Add(tbFullName);

                ComboBox cbDocuments = new ComboBox();
                cbDocuments.ItemsSource = m.Documents;
                var selectedDoc = new Binding("SelectedDocument");

                cbDocuments.SelectedItem = selectedDoc;
                Grid.SetColumn(cbDocuments, 2);
                Grid.SetRow(cbDocuments, rowNum);
                cbDocuments.DisplayMemberPath = "Name";
                grOrderMembers.Children.Add(cbDocuments);

                rowNum++;
            }


text:
Q: Erro ao tentar fazer download de zip da BMF com python Estou tentando baixar de uma vez os arquivos zip da BMF (ftp://ftp.bmf.com.br/MarketData/BMF/), mas aparece um erro em que o programa não acha o arquivo, porém ele existe.
segue o código:
from io import BytesIO
from urllib.request import urlopen
from zipfile import ZipFile
import pandas as pd

startdate = '20150130'
enddate = '20150210'
extension = '.zip'
daterange = pd.date_range(startdate, enddate)

for single_date in daterange:
zipurl = 'ftp://ftp.bmf.com.br/MarketData/BMF/NEG_BMF_' + single_date.strftime('%Y%m%d') + extension
with urlopen(zipurl) as zipresp:
    with ZipFile(BytesIO(zipresp.read())) as zfile:
        zfile.extractall('C:/Users/.../.../...')

O erro que aparece é basicamente que ele não acha o arquivo...

ftplib.error_perm: 550 NEG_BMF_20150131.zip: The system cannot find
  the file specified..

Existe um jeito mais fácil de se fazer isso?

A: Seu código está quase perfeito. Muito bom!
Resolvi testar seu código com as seguintes datas:
startdate = '20170130'
enddate = '20170207'

Ao testar com um período menor, pude perceber o seguinte:

*

*esse erro só aparece quando não ocorreram negócios no dia (sáb, dom ou feriados), ou seja, o arquivo realmente não existe!

*você pode utilizar uma estrutura try/except para contornar esse erro

Código Exemplo:
from io import BytesIO
from urllib.request import urlopen
from zipfile import ZipFile
import pandas as pd

startdate = '20170130'
enddate = '20170207'
extension = '.zip'
daterange = pd.date_range(start=startdate, end=enddate)

for single_date in daterange:
    zipurl = 'ftp://ftp.bmf.com.br/MarketData/BMF/NEG_BMF_' + single_date.strftime('%Y%m%d') + extension
    try:
        with urlopen(zipurl) as zipresp:
            with ZipFile(BytesIO(zipresp.read())) as zfile:
                zfile.extractall()
        print("OK: {}".format(zipurl))
    except:
        print('ERRO: {}'.format(zipurl))

    print("="*5)

Output:
OK: ftp://ftp.bmf.com.br/MarketData/BMF/NEG_BMF_20170130.zip
=====
OK: ftp://ftp.bmf.com.br/MarketData/BMF/NEG_BMF_20170131.zip
=====
OK: ftp://ftp.bmf.com.br/MarketData/BMF/NEG_BMF_20170201.zip
=====
OK: ftp://ftp.bmf.com.br/MarketData/BMF/NEG_BMF_20170202.zip
=====
OK: ftp://ftp.bmf.com.br/MarketData/BMF/NEG_BMF_20170203.zip
=====
ERRO: ftp://ftp.bmf.com.br/MarketData/BMF/NEG_BMF_20170204.zip
=====
ERRO: ftp://ftp.bmf.com.br/MarketData/BMF/NEG_BMF_20170205.zip
=====
OK: ftp://ftp.bmf.com.br/MarketData/BMF/NEG_BMF_20170206.zip
=====
OK: ftp://ftp.bmf.com.br/MarketData/BMF/NEG_BMF_20170207.zip
=====

Conferindo no calendário, podemos ver que 04/02/2017 foi um sábado e 05/02/2017 um domingo.
E ao entrar na pasta com os supostos downloads, surpresa:

Note que retirei o caminho de output da extração p/ fins de teste. Pode reincluí-lo no seu código (zfile.extractall('C:/Users/.../.../...'))

A: Eu utilizo uma estratégia diferente. Simplesmente baixo o que eles disponibilizam. Claro que mantenho controle do que já foi baixado para não baixar novamente.
Primeiramente listo os arquivos contidos em ftp://ftp.bmf.com.br/MarketData/BMF/:
import FTP

def listar_arquivos_ftp_bmf():
    ftp = FTP('ftp.bmf.com.br')
    ftp_dir = '/MarketData/BMF/'
    ftp.login()
    ftp.cwd(ftp_dir)
    arquivos = ftp.nlst()
    ftp.close()

    return arquivos

Depois baixo cada um dos arquivos:
import urllib

def baixar_arquivo(url, file_name, CHUNK = 16 * 1024):
    """
    url: caminho do arquivo que será baixado. String.
        Ex.: ftp://ftp.bmf.com.br/MarketData/BMF/NEG_BMF_YYYYMMDD.ZIP

    file_name: caminho e nome do arquivo que será salvo. String.
    """
    response = urllib.request.urlopen(url, timeout=120)

    with open(file_name, 'wb') as f:
        while True:
            chunk = response.read(CHUNK)
            if not chunk:
                break
            f.write(chunk)

    response.close()

Espero ter ajudo.
Possuo uma base grande, porém existe um buraco. Por um acaso você possui os arquivos NEG_BMF_YYYYMMDD.ZIP dos meses de Fevereiro, Março, Abril e Maio de 2017? Pode disponibilizá-los?
Obrigado.


text:
Q: Pinging 8.8.8.8 via a windows 10 client going through windows server 2012 gives a request timedout error This is my setup in virtualbox.
A DHCP Scope of range 112.123.1.100 to 112.123.3.188, Length = 16, Router IP is 112.123.2.2 (this also is the IP of the server the DHCP is configured on).
After this I set my IP of the windows server 2012 manually to IP: 112.123.2.2. Subnet: 255.255.0.0 Gateway = 10.0.2.2 DNS1: 10.0.2.2 DNS2: 8.8.8.8
This virtualbox VM that the server is running on is on an internal NAT network type. To access the internet I configured a second adapter as NAT type as per this guide: https://www.nakivo.com/blog/virtualbox-network-setting-guide/
The server can Ping google.com so it has internet access.
The client:
I configure the VM as an internal NAT type. Now I set my IP address to the following:
IP: 112.123.3.95
Subnet: 255.255.0.0
Gateway: 112.123.2.2
DNS1: 112.123.2.2
DNS2: 8.8.8.8
After that in the VM in windows 10 Pro I join the servers domain (Workgroup).
When I ping the server from the client I get a response back in CMD but when I ping 8.8.8.8 I get a "Request timed-out" message in CMD.
Does anyone know what I am doing wrong? Again, all of this is happening inside VM's off virtualBox.
EDIT: Forgot to mention that the client can indeed ping the server but the server can't ping the client for some reason, but the client was able to join the servers workgroup/domain. so I don't know what is happening there.

A: Your client (112.123.3.95) is on the same subnet as the server (112.123.2.2) which is why local ping works.
However, the client default route points to the server for default route (to get to 8.8.8.8).
Since the server can ping 8.8.8.8, it would seem to me that your server does not have routing and remote access service enabled.


text:
Q: SSRS date parameter format changes when executing report I have a report with date parameter. The default value is today() which for this example is 7th of October 2018.
The date in parameter box is displayed in US format (10-07-2018).
When I hit "Show report" day and month in the parameter box switches places (changes to 07-10-2018).
When I hit "Show report" again, they switch places again.
Of course, I would prefer it to be displayed in UK format and stop switching places.
When day >12 then this does not happen.
When I select the date from the calendar, it is even more bizarre. (I have 2 date parameters). The date displayed is in US format (unless day>12 then stays correct) but also switches day and month for the second parameter.
UPDATE: even stranger: using function dateserial(2018,10,7) gives:

*

*7th of October in dataset fileter (correct)

*10th of July in Parameter box (default value)

As if thre qas different locale settings for parameters and body of raport.
It concerned all reports on the server and tested on two clients.
Windows server language is Polish (for our purposes may be considered the same as the UK).
Regional settings on the server are Polish.
Regional settings on IE are Polish
Default date format in report builder (one with *) is  07.10.2018 (like the UK)
The language on the report is set to PL-pl
The language on the database is Polish
Microsoft SQL Server  and Reporting Services Version 13.0.4224.16

A: If you format your column the right way (date format) but your language settings (global) are emtpy you get your dates displayed randomly. So you always need, both the language settings and the format for the columns, then the dates will always show like you set them.
Click on the gray area of your report (Report Properties). Then look under Localization > Language. Check if the Language property is empty. If its empty put in your needed date format.

A: I know this is an old one, but I had the same issue and wanted to update, that for me, the date was giving the same error as you when using the reportbuilder, but was working properly when uploading the report and viewing from report server.
also, in report builder it was just how it was showing the date picker parameter after submitting, it was still using what I originally set


text:
Q: convert emailsettings from web.config to appsettings.json Im trying to convert the following lines in a .net 4.7 web.config file:

<mailSettings>
    <smtp deliveryMethod="SpecifiedPickupDirectory">
        <specifiedPickupDirectory pickupDirectoryLocation="C:\folder"/>
    </smtp>
</mailSettings>

to a core 2 appsettings.json configuration, IF it is possible something like:
{
    "mailSettings": {
    "DeliveryMethod ": "SpecifiedPickupDirectory",
    "pickupDirectoryLocation": "C:\folder"
     }
}

But im not sure if this is possible in core 2, or is something that cant be done by the configuration like it was done in .net 4.7+. Any feedback/tips/workarounds appreciated.

A: you're a bit off - try:
{
  "mailSettings": {
    "smtp": {
      "deliveryMethod": "SpecifiedPickupDirectory",
      "specifiedPickupDirectory": {
         "pickupDirectoryLocation": "C:\\folder"
      }
    }
  }
}

A: You have to make a couple of things before you can be done by configuration..
Step 1: Parse to Json
{
 "mailSettings": {
    "smtp": {
        "specifiedPickupDirectory": {
            "_pickupDirectoryLocation": "C:\\folder"
        },
        "_deliveryMethod": "SpecifiedPickupDirectory"
    }
  }
}

Step 2: On Startup search and get your mailing configurations
var mailSettings = Configuration.GetSection("mailSettings");

Step 3: Put the mail config to your class with something like this..
services.Configure<MailingOptions>(options =>
{
    options.smtp = mailSettings["smtp"];
});

Take a look to .. https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.1


text:
Q: Block matrix with optimization variables in CVXPY I want to build a block matrix that has the form
Q = [[A, B], [C, D]]

where each of the blocks A,B,C,D are the following matrices:

*

*A is simply 2x2 identity matrix

*B is the embdedding of a 2x1 vector b=(b_1,b_2) in the diagonal of the identity B = diag(b_1, b_2)

*C is the transpose of B

*D is the 2x2 identity myltiplied by some constant d, D = d*A
My optimization problem is min d such that Q >> 0, that is PSD condition. I need help with this problem.
Confusions:

*

*I know how to make a 2x2 identity matrix using Numpy np.eye(2). I am not sure if it makes sense to use it within my matrix Q.

*Furthemore, for b I define
b = cvxpy.Variable((2,1)). Then, I can also define its transpose as b_t = b.T but how do I make this as a matrix B and C given there is no outer product? That is, I need to embed the elements of the vector in the diagonal of the matrix.

*Since d is the variable I minimize over I need to define it as d = cvxpy.Variable(1). But then I cannot simply multiply it to the identity matrix in order to have diag(t,t) which I call T = t*np.eye(2).

In general I cannot figure out if I need to first define the block matrix Q as
Q = cvxpy.Variable((4,4)) or Q = cvxpy.Parameter((4,4)) and then having all terms from above use cvxpy.bmatto give it the precise form.
Any help appreciated.

A: You might get a better answer at other than a programming site. However in this case it's straightforword.
Since swapping two rows and (the same) two columns can be done by
M -> Q'*M*Q

where Q is a permutation matrix (and hence orthogonal), such a transformed matrix will be PSD iff the original is PSD.
If we write
M = ( 1  0  b1 0 )
    ( 0  1  0  b2)
    ( b1 0  d  0 )
    ( 0  b2 0  d )

and  swap the middle two rows and columns we get
M = ( 1  b1 0 0  )
    ( b1 d  0 0  )
    ( 0  0  1 b2 )
    ( 0  0  b2 d )

And this matrix will be PSD iff the two blocks on the diagonal are PSD, iff
d > max( b1*b1, b2*b2)


text:
Q: What does this for loop with undefined terms inside brackets mean in python? I have a mathematics code in python and need to convert it to java. But I can't konw how to work this:
#python source
sum([d**2 for d in (x - y)])

x,y are arrays and defined and have value. I have trouble with the for loop and the connexion with d^2 and d in that loop.

A: The actual for loop surrounded by brackets is a list comprehension, which generates a list. This is expressed, in general, as follows:
[ expression( <variables> ) for <variables> in <list> ]

Which means your variables (here d) will iterate over the values in the given list (here (x - y)). The list returned will contain the value of the expression, evaluated for each value of d.
This way of writing defines the variable after it is used, so it is normal you haven't seen it defined before.
In clear, the code is equivalent to the following:
squares = []
for d in (x - y):
    squares.append(d**2)
sum(squares)

Trivially, sum returns the sum of the list.

Because you say your code is doing maths and you are saying arrays rather than lists, I will suppose from here on that you mean that x,y are numpy arrays.
In this case, x - y has a meaning: item by item subtraction of the arrays.
Written as a list comprehension, it would look like: [a - b for a,b inzip(x,y)]
Hence a python rewrite of that code could be:
sum = 0
for a,b in zip(x,y):
    sum += (a - b) * (a - b)

Or only with numpy functions:
numpy.square(x - y).sum()


text:
Q: How to Query DBpedia file dumps? How can I get information about entities from DBpedia data dumps using Python?
Most of post currently on stackoverflow are working with an endpoint and not wuth a data dump file (like https://datascience.stackexchange.com/questions/4873/querying-dbpedia-from-python) using SPARQL Endpoint interface to Python
One of the scikit-learn's implementation of working with it simply iterates through it and puts them in a dictionary
For example, if want to find out about the celebrities born on a certain date just from the properties of info-box data dumps.
I tried doing the same using the SPARQL endpoint interface, but obviously it didn't work with the data dump.

A: Normally, you would load this data into an RDF store (install one if you don't already have it) and query it using SPARQL.
By doing that you would create a local DBPedia mirror. Considering that DBPedia already provides a SPARQL endpoint is there any reason why you can't just use it?

This StackOverflow answer mentions the options you have for setting up a local DBPedia mirror: Why dbpedia result is not consistant

None of this is Python-specific – SPARQL is a standard query language for RDF data.
Alternatively you could iterate through the file looking for the information needed on-the-fly. This way you loose flexibility (the "query" is your code) but can save on memory usage.


text:
Q: Export specific columns in p-datatable I want to export specific columns in p-datatable. I have export all records before, but now I want to export specific columns. How do I do that?

A: From PrimeNG doc

In order to exclude a column from the csv, use [exportable]="false" on p-column.

A: For getting a specific column there is one solution.
Html Page:

        <button class="btn btn-info" type="button" (click)="dg.exportCSV({selectionOnly:true})" style="float:left"> SELECTED EXPORT</button>
        <button class="btn btn-info" type="button" (click)="export(dg)" style="float:right"> Export</button>

In Ts page:
public export(e){
 const hiddenColumns: any[] = [];
 e.columns.forEach((c) => {
  if (c.field === "hiddencolumnName" ) {
    hiddenColumns.push({field: c.field, col: c});
    c.field = '';
  } if (c.field === "hiddencolumnName2" ) {
    hiddenColumns.push({field: c.field, col: c});
    c.field = '';
  }
}
e.exportCSV();
// restore their fields so still works in the future
hiddenColumns.forEach((hc) => {
  hc.col.field = hc.field;
});
}

Add columns to a hidden array which you don't want to export.


text:
Q: ASP.NET Custom Validators - Page.Validate("groupName") not firing? I have a custom validator in which the script validating the control is client-side JavaScript.
In my VB code behind for the website I call Page.Validate("groupName") but my validation script is not fired at all. I placed a break point in my JavaScript, but it's not even touching my validation script. While when I use the same function on non-custom validators it works.
I am thinking that it is impossibly to call my client-side validation script in my VB behind code via Page.Validate("groupName"). Do I absolutely need a server-side validation function?
Here's a bit of code:
<asp:CustomValidator ID="ValidateTxt" runat="server"
     ClientValidationFunction="validateTxt"
     ControlToValidate="txtBox"
     Display="Dynamic"
     ValidationGroup="group1">
</asp:CustomValidator>

 <script type="text/javascript" language="javascript" >
    function validateFinHeight(source, arguments)
    {
         if(arguments.Value % 2 == 0 ){
            arguments.IsValid = true;
         }
    }
 </script>

VB Behind Code:
Protected Sub cbo(ByVal sender As Object, ByVal e As System.EventArgs) Handles cbo.SelectedIndexChanged
    Page.Validate("group1")
End Sub

The Page.Validate("group1") is not calling my JavaScript function.

A: Page.Validate is used to validate at Server side. If you want to trigger the client side validation then call the function Page_ClientValidate("group1") from your JavaScript code.


text:
Q: Почему теряются все ZipEntry после первого? У меня есть SequenceInputStream, в котором находятся 3 FileInputStream-а. Каждый из них открыт для zip папки, в которой лежит текстовый файл. Мне нужно последовательно прочитать все 3 архива и записать результат в файл. Но почему-то метод getNextEntry() у ZipInputStream возвращает null после прочтения первого архива.
        ArrayList<String> files = new ArrayList<>();
        ArrayList<InputStream> streams = new ArrayList<>();
        files.add("C:/temp/file1.zip");
        files.add("C:/temp/file2.zip");
        files.add("C:/temp/file3.zip");
        String resultFile = "C:/temp/result.txt";
        Collections.sort(files);
        for (String file : files) streams.add(new FileInputStream(file));
        ZipInputStream zip = new ZipInputStream(new SequenceInputStream(Collections.enumeration(streams)));
        while (true) {
            ZipEntry entry = zip.getNextEntry();
            if (entry == null) break;
            System.out.println(entry.getName());
            try (OutputStream os = new BufferedOutputStream(new FileOutputStream(resultFile))) {
                final int bufferSize = 1024;
                byte[] buffer = new byte[bufferSize];
                for (int readBytes; (readBytes = zip.read(buffer, 0, bufferSize)) > -1; ) {
                    os.write(buffer, 0, readBytes);
                }
                os.flush();
            }
        }


text:
Q: Extract values from xmlType I know this has been asked before, but I'm not able to monkey-see-monkey-do with my formatting
WITH TEST_XML_EXTRACT AS
(
    SELECT XMLTYPE (
                    '<tns:Envelope xmlns:tns="http://schemas.xmlsoap.org/soap/envelope/">
                        <testLeaf> ValueIWant </testLeaf>
                     </tns:Envelope>') testField
      FROM dual
)
SELECT EXTRACTVALUE(testField,'/testLeaf'), -- doesn't work
       EXTRACTVALUE(testField,'/tns'),      -- doesn't work
       EXTRACTVALUE(testField,'/Envelope'), -- doesn't work
       EXTRACTVALUE(testField,'/BIPIBITY')  -- doesn't work
  FROM TEST_XML_EXTRACT;

It just returns blank.
And I can't find any exactly similar examples from the Oracle docs.
Any thoughts?

A: There's only testLeaf node as a decently defined one in the XPath expression. So , only that could be extracted by using extractValue() function in such a way below :
with test_xml_extract( testField ) as
(
    select
        XMLType(
        '<tns:Envelope xmlns:tns="http://schemas.xmlsoap.org/soap/envelope/">
            <testLeaf> ValueIWant </testLeaf>
        </tns:Envelope>'
        )
      from dual
)
select extractValue(value(t), 'testLeaf') as testLeaf,
       extractValue(value(t), 'tns') as tns,
       extractValue(value(t), 'Envelope') as Envelope,
       extractValue(value(t), 'BIPIBITY') as BIPIBITY
  from test_xml_extract t,
       table(XMLSequence(t.testField.extract('//testLeaf'))) t;

TESTLEAF    TNS      ENVELOPE    BIPIBITY
----------  -------  ----------  ----------
ValueIWant

Demo

A: You might do better passing the namespace to the extract process
WITH TEST_XML_EXTRACT AS
     ( SELECT XMLTYPE (
             '<tns:Envelope xmlns:tns="http://schemas.xmlsoap.org/soap/envelope/">
              <testLeaf> ValueIWant </testLeaf>
              </tns:Envelope>') testField
      FROM dual)
 select t.testField.extract('/tns:Envelope/testLeaf',
             'xmlns:tns="http://schemas.xmlsoap.org/soap/envelope/"').getstringval() val,
       EXTRACTVALUE(t.testField,'/tns:Envelope/testLeaf', 'xmlns:tns="http://schemas.xmlsoap.org/soap/envelope/"') extval,
       EXTRACTVALUE(t.testField,'/*/testLeaf', 'xmlns:tns="http://schemas.xmlsoap.org/soap/envelope/"') extval_wc
from  TEST_XML_EXTRACT t;


text:
Q: Dentro do ajax quero criar uma variável e usa-lá em vários lugares fora do ajax Quero criar uma variável dentro do ajax e usa-lá em vários outros lugares, isto só funciona quando eu uso o async:false e sei que isto não é mais recomendado, como fazer isto de forma correta?
segue os códigos abaixo:
JAVASCRIPT
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.js"></script>
  <script type="text/javascript">
    $(document).ready(function(e) {
    // <![CDATA[
        $.ajax({
                 url: 'lista_empresas.txt',
                 //async:false,
                 cache: false,
                 dataType:"json",
                 success: function(retorno) {
                     empresa = retorno['empresa']
                     $('body').append(empresa)
                 }
        });
        $('body').append('Minha empresa: ' + empresa)
    });
   // ]]>
 </script>

JSON

{"empresa":"ATR Brasil","ramo_atividade":"transportes"}

A: Você pode trabalhar com promessas, um bom exemplo seria:
var request = function(link, parametros) {
  return $.ajax({
    url: "https://baconipsum.com/api/" + link,
    dataType: 'json',
    type: 'POST',
    crossDomain: true,
    data: parametros,
    error: function(jqXHR, textStatus, errorThrow) {
      console.log(textStatus);
    }
  });
};

request("?type=meat-and-filler").success(function(data) {
  console.log('executou 1');
  request("?type=all-meat&paras=2&start-with-lorem=1").success(function(data) {
    console.log('executou 2');
    request("?type=all-meat&sentences=1&start-with-lorem=1").success(function(data) {
      console.log('executou 3');
    });
  });
});

Exemplo no jsfiddle


text:
Q: How to control tabpage using listview or tree view In many programs, such as PuTTY, uBittorrent, notepad++ and WinSCP, they use some kind of listview or treeview to organize the preference form, just like images shown below:

So what I would like to ask is that: in C# is there any native way to organize winform controls in this layout? What I have figured out is to load the right-hand side controls in a panel manually when user clicks the listview item on left side.
But is there any better solution which is directly supported by C#?
Thanks~

A: There are a lot of ways this can be achieved. First to get the layout, I would use a table layout panel as the top most level control in the form and set it to have 2 columns. The left column will be the list view and the right column will show the associated page with the currently selected list view item.
I would create a simple model for each possible list view item something like
public class PageViewItemModel()
{
    public string ItemDescription { get; }

    public UserControl CustomUserControlForViewItem { get; }

    public PageViewItemModel()
    {
        // Initialize the associated custom user control here
        CustomUserControlForViewItem = new YourCustomUserControlClass();

        // Set the display name for the list view
        ItemDescription = MyListViewItemName;
    }
}

Of course you can create a generic class and use constructor parameters to do all this instead of creating a model for each possible item in the list view. But after you have your ListViewItemModel objects you can add them to your list view and set the DisplayName property to "ItemDescription" so it shows that value in the ListView.
Then create an event handler in the parent form that handles the SelectedIndexChanged event of the ListView which adds the associated custom user control to the right column of the TableLayOutPanel
public void OnSelectedIndexChanged(object sender, EventArgs e)
{
    int selectedIndex = myListView.SelectedIndex;

    PageViewItemModel model = myListView.Items[selectedIndex];

    myTableLayOutPanel.Controls.Add(model, 0, 1);
}

That's the gist of it.


text:
Q: How to setup the Oculus Rift using a MSI trident computer? Problem
I've installed a new MSI Trident 007EU computer and will now like to setup an Oculus Rift. I've found a full users manual guide online. I connected the back HDMI ports with each other like on image below.

In the front HMDI port, I connected the HDMI port of the Oculus Rift. There is one port remaining on the back side and I will use that for my monitor but there is no signal there.
Overview
On the back side, the HDMI ports are numbered 5, 7 and 9. Number 6 is a DVI-D port.

On the front side, number 6 is a HDMI port

To use the front HDMI port, you must connect HDMI ports 5 and 7 on the back side.
Question
How can I use my monitor at the same time with the Oculus Rift? On MSI's website it says it's VR ready, but it seems like it's not.

A: I'm now using the DVI port to connect that with my monitor and it works.

A: The HDMI(9) is connected to the Internal Graphics, and when you install a graphics card, it gets disabled.
So for the monitor you can use the DVI as you did, or the Display port.
How did you plug the USBs ?


text:
Q: Is there some synchronization object that can be signaled/nonsignalled plus a value? I want to block a thread until some action completes, but I don't just want signaled/non-signaled. If possible I'd like to block then examine the value and take appropriate action. All of this wrapped up into one object. AutoReset and ManualReset don't make it.

A: Maybe a Task and a Wait?
http://msdn.microsoft.com/en-us/library/dd235608.aspx


text:
Q: FBSDKLikeButton callback in swift facebook SDK v4.21.0 I'm coding in Swift 3 w/Facebook SDK 4.21.0, I'm trying to find a way to add a callback to FBSDKLikeButton so i know when the user actually liked / dislisked something.
I have tried both approaches found in this site:
- Add  a .valueChanged control event (not working)
- Add a NotificationCenter observer to FBLikeActionControllerDidUpdateNotification as described here: FBLikeControl callback
What I'm doing:
                let like = FBSDKLikeControl()
                like.center = bcenter
                like.objectID = objectid

                NotificationCenter.default.addObserver(self,
                                                       selector: #selector(self.likeButtonChanged(_:)),
                                                       name: NSNotification.Name.init("FBLikeActionControllerDidUpdateNotification"),
                                                       object: nil)

However, my selector never gets calls no matter whether I like / unliked / cancel / throw the phone against the wall
Any pointers here?

A: Well, did it by parsing the url in:
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {

}
fb{app-id}://bridge/like?version=web&bridge_args=%7B%22app_name%22%3A%22AAP-NAME%22%2C%22action_id%22%3A%22B0B73D93-6434-4FF0-A300-00B0A7E470BE%22%7D&method_results=%7B%22object_is_liked%22%3Afalse%2C%22like_count%22%3A5039330%2C%22like_count_string%22%3A%225M%22%2C%22social_sentence%22%3A%225M%20people%20like%20this.%22%2C%22completionGesture%22%3A%22unlike%22%2C%22didComplete%22%3A1%7

and setting a completion callback in the appdelegate that is set from the view that has the like button and then nillified once consumed


text:
Q: backgroundWorker_ProgressChanged not working? I am having a trouble with background worker
private void backgroundPBar_ProgressChanged(object sender, ProgressChangedEventArgs e)

The function doesn't execute when backgroundPBar.ReportProgress(value);
here's the code:
private void backgroundPBar_DoWork(object sender, DoWorkEventArgs e) {
    while (fileTransfer.busy) {
        if (fileTransfer.sum > 0) {
            int value = Convert.ToInt32((fileTransfer.sum * 100) / fileTransfer.fileSize);
            backgroundPBar.ReportProgress(value);
            Console.WriteLine(value);
        }
    }
}

private void backgroundPBar_ProgressChanged(object sender, ProgressChangedEventArgs e) {
    progressBarFile.Value = e.ProgressPercentage;
    this.Text = e.ProgressPercentage.ToString() + "%";
}

How can I fix it?

A: Make sure you have the progress event wired up:
backgroundPBar.ProgressChanged += backgroundPBar_ProgressChanged

From you description, it seems like it isn't.  The assumption here is that fileTransfer.busy is true and fileTransfer.sum > 0 is also true.
Also, make sure you have your the properties of the background worker set:
backgroundPBar.WorkerReportsProgress = true;

(as I see "The Mask" mentioned").

A: don't forget that to use ReportProgress() method you must set WorkerReportsProgress  as true.

A: Here's a tutorial of how to use backgroundworker with ProgressBar
You should call (RunWorkerAsync) first then the backgroundPBar_DoWork will start executing its code.
backgroundPBar.RunWorkerAsync();

A: I've been having problems getting the ProgressChanged event to fire immediately when the ReportProgress method is called.  Because they are seperate threads, I had to resort to thread synchronization.  I used a couple WaitHandles and the SignalAndWait method to synchronize the two threads.  I kinda defeats the purpose of the background worker, but if I really want the UI thread to do something on time, it really has to make the background worker wait until the UI thread got the message and performed the work.
    Private ReportProgressWaitEvent As New AutoResetEvent(False)
    Private ReportProgressReadyWaitEvent As New ManualResetEvent(False)
    Private Sub ReportProgress(backgroundWorkerProgressEvents As BackgroundWorkerProgressEventsEnum, userState As Object)
        ReportProgressReadyWaitEvent.Reset()
        _backgroundWorker.ReportProgress(backgroundWorkerProgressEvents, userState)
        WaitHandle.SignalAndWait(ReportProgressReadyWaitEvent, ReportProgressWaitEvent)
    End Sub
    Private Sub _backgroundWorker_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles _backgroundWorker.ProgressChanged
        ... do work ...
        ReportProgressReadyWaitEvent.WaitOne()
        ReportProgressWaitEvent.Set()
    End Sub


text:
Q: Is there a way to bind an arrays child objects? I current have some objects in an array like this node[1][1], there are multiple child objects/variables for each parent eg.. node[1][2], node[1][3] etc..
There are also multiple parent objetcs eg.. node[2][1], node[3][1]  etc..
What I want to do is bind/Display all child objects in a listbox from all parents
eg..listBox1.itemsource = node[All][1];
I have done some research but can't find any way to do this?
Any help would be appreciated.

A: I found my own solution for this. Using foreach and then if statement to find and display specfic element
Examples Code *****************
// statements_foreach_arrays.cs
// Using foreach with arrays
using System;
class MainClass
{
   public static void Main()
   {
      int odd = 0, even = 0;
      int[] arr = new int [] {0,1,2,5,7,8,11};

      foreach (int i in arr)
      {
         if (i%2 == 0)
            even++;
         else
            odd++;
      }

      Console.WriteLine("Found {0} Odd Numbers, and {1} Even Numbers.",
                        odd, even) ;
   }
}

Using foreach with Arrays


text:
Q: How to get deathbycaptcha module in my python? So I'm scrapping websites and I want to use deathbycaptcha services to solve captchas. I don't understand how to install deathbycaptcha module on my python so that I can import it in my script.
The website gives instructions and package to download for python, but I have no idea how to install it.
http://www.deathbycaptcha.com/user/api
Thanks a lot

A: try pip install deathbycaptcha
client = deathbycaptcha.SocketClient(username, password)

Then, you can use it as documented in API documentation. Worked for me.
The simplest of the solution to start with deathbycaptcha is start working in the directory where you have all the api code downloaded. Start by reading new_recaptcha_coordinates.py file. Put your username and password and run it.


text:
Q: Printing to screen on a GUI I am very new to programming, specifically creating GUIs; I've previously only written console programs in C#, and am now attempting to build a game with XNA. Could anyone help me by letting me know how to print to the screen in a GUI? I'm currently trying variations of System.Console.WriteLine("");, but will not print to screen. The code I am using is below. Can anyone tell me where I'm going wrong?
ResourceCounter.cs:
      public ResourceCounter(Vector2 pos, GameTime gameTime)`
       {
        position = pos;
        over = false;
        clicked = false;
        gameTime = new GameTime();`

        currentTime += (float)gameTime.ElapsedGameTime.TotalSeconds;
        System.Console.WriteLine("Resources: ", pSourceCount);

        if (currentTime >= countDuration)
        {
            pSourceCount++;
            **System.Console.WriteLine("Resources: ", pSourceCount);**
        }
        if (pSourceCount >= limit)
        {
            pSourceCount = 0;//Reset the counter;

        }

    }

and in my main GameScreen.cs class:
    public override void Update(GameTime gameTime)
    {
        MouseState mState = Mouse.GetState();
        menu.Update(mState, cursor, gameTime);

        if (menu.currentstate == State.campaign)
        {
            campaign.Update(pTower);
            //campaign.Update(eTower);
            **System.Console.WriteLine("Resources: ", pSourceCount);**
        }
        base.Update(gameTime);
    }

A: Use the SpriteBatch.DrawString method for rendering text with XNA.
When you print text with System.Console.WriteLine it is written to the standard output stream. The data in this stream is then presented through the console. Your game window takes no notice of this at all.

Text Rendering
It's fair to say that everything you draw to your game window consists of (textured) triangles. Text is no exception. A single character is rendered using a quad (rectangle), that again consists of 2 triangles.
The text XNA! would be drawn using a total of 4 sprites (8 triangles), one sprite for every character:

Bitmap Font
Common font formats store the characters as vectors. For bitmap fonts (the kind of font usually used in games) the actual type face is stored in one or more bitmaps (textures). This method is much faster, as the character shapes themselves are already rasterized and only have to be sampled from the texture. The obvious drawback is, that the characters all come in a fixed size. You need one bitmap font per font face per size per weight.
This is a sprite map for the Arial font, size 20, standard weight:

For drawing a certain character, the renderer has to know where on the bitmap the character is located. As you can see in the image above, each character occupies a non overlapping rectangular area. The dimensions of those rectangles can be stored in an additional text or XML file.
For example, this could be a definition of the A character for the sprite map above:
<char id="65" x="235" y="47" width="12" height="13" xoffset="0" yoffset="3" xadvance="11" page="0" />

*

*id is the ASCII value (A=65)

*x and y are the position of the top left corner

*width and height are the size of the rectangle

*xoffset and yoffset is the offset on screen

*xadvance is the distance to the preceding character

*page is the index of the bitmap that contains the character

Conclusion
Text rendering for games is not as trivial as one would assume. XNA greatly simplifies the process with the SpriteBatch class. A summary of the steps involved:

*

*Convert a standard font to a bitmap font

*Load the font files in your game application

*Create the sprites for a given string

*Render the sprites to the screen

The font example was created with a free Bitmap Font Generator.


text:
Q: Dynamicaly change the URL and id of a body via a link without refreshing page I am trying to dynamically change the URL displayed to the user and change the id of the body without refreshing the page. The function I require is very similar to flickr.com when you click on an image, the pop-up appears. The id of the body has a word appended to it, and the url of the website also has a word appended to it.
An example would be:
http://www.flickr.com/photos/orangeacid/459207903/
There is an image there, if you click on the image the URL changes to as follows:
http://www.flickr.com/photos/orangeacid/459207903/lightbox/
(This new page is just overlaying the old one)
Before clicking on the link the body tag is as follows:

document.body.className = [document.body.className, 'js'].join(' ');

...
After clicking on the picture it changes to:

document.body.className = [document.body.className, 'js'].join(' ');

...

A: Flickr uses Yahoo's YUI library and what you are talking about is the lightbox component, and the history utility.
There is no all-in-one function, you have to build it yourself, using the library.
Note about the url : HTML5 adds a new history API that allows javascript to change the url (pushState) without reloading the page and without using the "hash" hack. It's available in webkit (Chrome, Safari) since a while and in Firefox 4. Using history from YUI will help you implementing this.

A: I have recently started to repatch the jquery fancybox plugin to work with the History API. Which does something similar to flickr's implementation.
However, it might just be the history API you are talking about
Click here to see my plugin on github
Click here to see an introduction to the History API
Click here to see my talk on the history API
:)
Hope it helps


text:
Q: GCC compiler online version for my website I have a website teaching C for beginners.
I'm trying to have a C compiler online version so that a user could easily compile their code online itself.
Are there any compilers available? If available, which is the best one?
I have found some compilers, but they have got no capability of taking input from the user, but they have the capability of just displaying the output.

A: There is no package that can just be added to a blog so people can try C online and see the results.
You could provide a link to gcc or another compiler so your readers can try it themselves.
If you were really serious, a CGI script could be created on the server side which:

*

*Runs in a sandbox (this is critical to get right and is potentially dangerous if done incorrectly)

*Compiles the source code

*Runs the compiled code

*Returns the results

Sorry that I can't give you an easy answer, but there it is.


text:
Q: ES6 Modules: Undefined onclick function after import I am testing ES6 Modules and want to let the user access some imported functions using onclick:
test.html:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Module Test</title>
</head>
<body>
    <input type="button" value="click me" onclick="hello();"/>
    <script type="module">import {hello} from "./test.js";</script>
</body>
</html>

test.js:
export function hello() {console.log("hello");}

When I click the button, the developer console says: ReferenceError: hello is  not defined. How can I import functions from modules so that they are available as onclick functions?
I am using Firefox 54.0 with dom.moduleScripts.enabled set to true.

A: While the accepted answer is correct, it scales poorly once you start importing from multiple modules, or declaring multiple functions .  Plus, as noted by @Quentin, it risks global name space pollution.
I prefer a slight modification
import { doThis, doThat } from './doStuff.js'
import { foo1, foo2 } from './foo.js'

function yetAnotherFunction() { ... }

window._allTheFns = { doThis, doThat, foo1, foo2, yetAnotherFunction }

// or, if you prefer, can subdivide

window._doStuffjs = { doThis, doThat }
window._foojs = { foo1, foo2 }

*

*Uses an "unusual" property name to (hopefully) avoid global namespace issues

*No need to immediately attach (or forget to attach) an EventListener.

*You can even put the listener in the HTML, e.g. <button onclick="window._foojs.foo1(this)">Click Me</button>

A: Module scope in ES6 modules:
When you import a script in the following manner using type="module":
<script type="module">import {hello} from "./test.js";</script>

You are creating a certain scope called module scope. Here is where modules scope is relative to other levels of scope. Starting from global they are:

*

*Global scope: All declarations outside a module on the outermost level (i.e. not in a function, and for const and let not in a block) are accessible from everywhere in the Javascript runtime environment

*Module scope: All declarations inside a module are scoped to the module. When other javascipt tries to access these declarations it will throw a reference error.

*Function scope: All the variables declared inside (the top level of) a function body are function scoped

*Block scope: let and const variables are block scoped

You were getting the referenceError because the hello() function was declared in the module, which was module scoped. As we saw earlier declarations inside module scope are only available within that module, and you tried to use it ouside the module.
We can make declarations inside a module global when we explicitly put it on the window object so we can use it outside of the module. For example:
window.hello = hello;  // putting the hello function as a property on the window object

A: Module creates a scope to avoid name collisions.
Either expose your function to window object
import {hello} from './test.js'

window.hello = hello

Or use addEventListener to bind handler. Demo
<button type="button" id="hello">Click Me</button>
<script type="module">
  import {hello} from './test.js'

  document.querySelector('#hello').addEventListener('click', hello)
</script>

A: As of 2022 I don't know of any other solution than the provided, except that you don't need to use window, but you can use globalThis
I don't know if this makes it any better.
advantages:

*

*it is a tick more readable

*you don't get a compiler error when checkJS is on (attribute "..." is not found on window etc...)

I'm even using LitHtml where you have @event notation, looks like this:
<element @click="${(e)=>console.log(e)}"></element>

but sadly there is no clean way to actually get a reference of the object that has the listener attached. the target, originalTarget and explicitOrOriginalTarget can be anything in the bubbling queue, which is super annoying and super confusing, but if you don't need that, LitHTML would be the way to go.


text:
Q: Unable to add click event to a cloned object using jquery Below is the sample code which i was trying to attach a click event to the cloned object but i couldn't do that i have tried a lot but i couldn't attach the click event to the object. Please check the code and give your valuable suggestions

$(document).ready(function(){
    var documentSelector = $('.clone-block')
    var arrayOfObjects = [{
     name: "William",
        gender: "Male",
        dateofbirth: "01-01-2017"
    },
    {
     name: "Michale",
        gender: "Female",
        dateofbirth: "01-01-2018"
    },
    {
     name: "John",
        gender: "male",
        dateofbirth: "01-01-2019"
    },
    {
     name: "tom",
        gender: "male",
        dateofbirth: "01-01-2020"
    }];

    $.each(arrayOfObjects, function (ind, user){
     var clonedObject = documentSelector.clone(true, true);
        clonedObject.find('span').on('click', alertWhenClicked.bind(user));
        clonedObject.find('span').text(user.name);
        $('.link-p').append(clonedObject.html());
    });

    function alertWhenClicked () {
     alert(this.dateofbirth);
    }
});
<!DOCTYPE html>

Username :

A: $('.link-p').append(clonedObject.html());

You are turning the object into html and that is being appended to the dom, which will not have any of the event bindings on it.  Take off the .html()
As an aside note, you should look into delegate bindings so you don't have to put an event binding on all these elements.
$.each(arrayOfObjects, function (ind, user){
    var clonedObject = documentSelector.clone(true, true);
    //put the user on the element as a data object for easy reference
    clonedObject.data('user', user);
    clonedObject.find('span').text(user.name);
    $('.link-p').append(clonedObject);
});

//delegate bind the click event to the parent for the future child elements
$('.link-p').on('click', '.clone-block', alertWhenClicked);

function alertWhenClicked () {
    alert($(this).data('user').dateofbirth);
}


text:
Q: Why is the class holding a reference copyable? Having a class holding a reference I would expect the following code to fail miserable, but it compiles:
#include <iostream>

struct ReferenceHolder
{
    std::string& str;

    ReferenceHolder(std::string& str)
    :   str(str)
    {}
};

// Why does this compile?
ReferenceHolder f() {
    std::string str = "Hello";
    return ReferenceHolder(str);
}

int main() {
    ReferenceHolder h  = f();
    std::cout << "Should be garbage: " << h.str << '\n';
    return  0;
}

Compiler: g++ 4.7.2 (with -std=c++11)
Edit: Even with -fno-elide-constructors it compiles happily

A: There's no problem with copy-initialising your class, as your example does: the new reference is simply initialised to refer to the same object as the old one. Of course, you then get undefined behaviour when the function return leaves the reference dangling.
The reference prevents default-initialisation and copy-assignment; so the following small change will fail for those reasons:
ReferenceHolder h;  // ERROR: can't default-initialise the reference
h = f();            // ERROR: can't reassign the reference.

A: This code has undefined behaviour, see the classic answer from Eric Lippert.
The the reference in h is bound to the reference in the return value from f(), which is bound to the ReferenceHolder in the return expression, and so h references the str  from f() outside its scope.