text:
Q: Get Size of BlockingQueue while Multithreading I have a multi-threaded process, 5 threads, and another thread working as a status object reporting the size of the BlockingQueue. Problem is the Status thread reports 100% first, which is correct, but then goes right to 0%.
I want it to count down the percentage.
Here is my code:
Thread[] workers = new Thread[NUMBER_OF_THREADS];
        for (int x = 0; x < NUMBER_OF_THREADS; x++) {
            workers[x] = new Thread(new S3ObjectDownloader(filesToDownload, currentYear));
            workers[x].start();
        }
        for (int x = 0; x < NUMBER_OF_THREADS; x++) {
            try {
                workers[x].join();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

Here is the status object instantiation:
int downloadSize = filesToDownload.size();
        Thread statusThread = new Thread(new Status(filesToDownload, currentYear,downloadSize,"DOWNLOADING..."));
        statusThread.start();

Here is that actual Status object run method:
public void run() {
    while(!queue.isEmpty()){
        try {
            float completion = (queue.size()*1)/this.queueSize;
            System.out.println(this.jobeName+" : "+this.conferenceYear+ " completion..."+MessageFormat.format("{0,number,#.##%}",completion));
            TimeUnit.SECONDS.sleep(30);;
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

Im adding in the actual S3ObjectDownloader:
public void run() {
        //aws credentials
        this.s3 = new AmazonS3Client(new ClasspathPropertiesFileCredentialsProvider());

        //log4j configuration
        PropertyConfigurator.configure("/home/ubuntu/log4j.properties");

        //attempt to poll the queue
        while (!queue.isEmpty()) {

            String fileName = queue.poll() + ".mp4";
            String FULL_PATH = "best_of_ats/" + this.conferenceYear + "/videos/" + fileName;
            File f = new File("/home/ubuntu/" + fileName);

            if (fileName != null && !f.exists() && s3.doesObjectExist(BUCKET_NAME, FULL_PATH)) {
                OutputStream out = null;
                InputStream in = null;
                S3Object s3obj = null;

                    try {
                        s3obj = s3.getObject(this.BUCKET_NAME,
                                FULL_PATH);
                        in = s3obj.getObjectContent();
                        //System.out.println("Downloading File " + FULL_PATH + "....");
                    } catch (AmazonS3Exception s3e) {
                        // s3e.printStackTrace();
                        //System.out.println("Problem downloading file..." + FULL_PATH);
                        s3e.printStackTrace();
                        logger.info("Problem with file..." + FULL_PATH);
                        continue;
                    }

                    try {
                        out = new FileOutputStream(new File(fileName));
                        int read = 0;
                        byte[] bytes = new byte[1024];
                        while ((read = in.read(bytes)) != -1) {
                            out.write(bytes, 0, read);
                        }

                        out.flush();
                        out.close();
                        in.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        //System.out.println("problem writing output..." + FULL_PATH);
                        logger.info("problem writing output..." +FULL_PATH);
                        continue;
                    }

            }

        } // end while...
    }

And here is the Status Class:
public class Status implements Runnable {

    private String conferenceYear;
    private Queue<String>queue;
    private int queueSize;
    private String jobeName;

    public Status(Queue<String> queue, String conferenceYear, int queueSize, String jobName){
        this.conferenceYear = conferenceYear;
        this.queue = queue;
        this.queueSize = queueSize;
        this.jobeName = jobName;
    }

    @Override
    public void run() {
        while(!queue.isEmpty()){
            try {
                float completion = (queue.size()*1)/this.queueSize;
                System.out.println(this.jobeName+" : "+this.conferenceYear+ " completion..."+MessageFormat.format("{0,number,#.##%}",completion));
                TimeUnit.SECONDS.sleep(30);;
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

}

Here is the calling class:
public static void main(String[] args) {

        BlockingQueue<String> filesToDownload = new LinkedBlockingDeque<String>(1024);
        BlockingQueue<String> filesToPreview = new LinkedBlockingDeque<String>(1024);
        BlockingQueue<String> filesToUpload = new LinkedBlockingDeque<String>(1024);
        String currentYear = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));

        // DB connection.
        ATSStoreDB db = new ATSStoreDB();
        PreparedStatement st = null;
        Connection conn = null;
        conn = db.getConnection();

        // get ids from ats_store.products.
        try {
            st = conn.prepareStatement(sql);
            st.setString(1, currentYear);
            ResultSet rs = st.executeQuery();
            // add each id to IDS.
            while (rs.next()) {
                filesToDownload.add(rs.getString("product_id"));
                filesToPreview.add(rs.getString("product_id"));
                filesToUpload.add(rs.getString("product_id"));
            }
            conn.close();

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        /*
         * Distribute IDS to several threads.
         */

        //start up the Status Object class.
        int downloadSize = filesToDownload.size();
        Thread statusThread = new Thread(new Status(filesToDownload, currentYear,downloadSize,"DOWNLOADING..."));
        statusThread.start();

        /**
         * download the files
         */

        Thread[] workers = new Thread[NUMBER_OF_THREADS];
        for (int x = 0; x < NUMBER_OF_THREADS; x++) {
            workers[x] = new Thread(new S3ObjectDownloader(filesToDownload, currentYear));
            workers[x].start();
        }
        for (int x = 0; x < NUMBER_OF_THREADS; x++) {
            try {
                workers[x].join();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        /**
         * create previews
         */
        int previewSize = filesToPreview.size();
        statusThread = new Thread(new Status(filesToPreview, currentYear,previewSize,"PREVIEWING..."));
        statusThread.start();

        workers = new Thread[NUMBER_OF_THREADS];
        for (int x = 0; x < NUMBER_OF_THREADS; x++) {
            workers[x] = new Thread(new Worker(filesToPreview, currentYear));
            workers[x].start();
        }
        for (int x = 0; x < NUMBER_OF_THREADS; x++) {
            try {
                workers[x].join();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

A: I can spot one problem with your code right away:
float completion = (queue.size()*1)/this.queueSize;

What's the point of *1? Both queue.size() and this.queueSize are integers. You're turning integer division into... integer division. A good compiler will probably optimize it right away. You probably meant to write something like
float completion = (queue.size() * 1.0f) / this.queueSize;


text:
Q: Basics difference between distributed computing and interprocess communication? I know the theritical definition for distributed computing and interproces communication.
But in real time I was not able to come to conclusion that when we go for distributed or interprocess.
Tell me some scenario where we can go for distributed computing or interprocess communication by example.

A: interprocess communication basically would mean comuniction b/t processes.
mostly this concept is used when studying parallel programming and studying the working of operating system.
this topic is to huge to explain, its a full subject, try googling interprocess communication and read the basic definations.
2)
my initial understanding is:-
imagine a office, why does it have several employees in one department? because many brains and men power is needed to bring one task to completion. one man can do the job but it might take days and what if he gets sick! so distributed...
now how to communicate between the porcesses/people doing there independent task of the job on different computers/different CPU's of the same computer/within different cabins of the same office building?
"shout!! hey i have done my work take the result and send more?? who is in charge here!! answer ****"
no right!
so here come the INTER PROCESS COMMUNICATION subject.
note:- please note i am also a learning person :-) so do not take the above as right without doing your own googling, i am not responsible for any .........

A: Interprocess communication is typically defined as communication between multiple processes on a single machine. Distributed computing is multiple processes being distributed across a network and executed on desired host boxes. To me it makes sense to implement a desired interprocess communication in the same fashion as the distributed processes transmit their results back to the distributor/ host. That way a weaker machine continues to be able to process data while a more powerful box runs a greater load.

redpajama_set_name: RedPajamaStackExchange


text:
Q: .NET Core IOT (No Data coming from Seed Studio Grove DTH11 Sensor when using without Grove Shield) I am using Grove DTH11 Sensor to connect to raspberry pi 4 and get the reading from the sensor using .NET Core IOT and GPIO Pins. I am connecting the sensor directly to the Pi without using Grove Pi+ or Grove Shield.
The problem is I am not getting any reading from the sensor. Below is the code i am using
int pin = 4;
using (GpioController controller = new GpioController())
{
    Console.WriteLine("Opening Pin - " + pin);
    controller.OpenPin(pin, PinMode.Input);
    Console.WriteLine("Pin - " + pin + " opened successfully");

    using (Dht11 dth11Obj = new Dht11(pin, PinNumberingScheme.Logical))
    {
        Console.WriteLine("Dht11 object created");
        while (!Console.KeyAvailable)
        {
            Console.WriteLine("reading data");
            var temp = dth11Obj.Temperature;
            var hum = dth11Obj.Humidity;
            Console.WriteLine("data read successfully");

            if (dth11Obj.IsLastReadSuccessful)
            {
                Console.WriteLine($"Temperature: {temp.DegreesCelsius}\u00B0C, Relative humidity: {hum.Percent}%");
                Console.WriteLine($"Heat index: {WeatherHelper.CalculateHeatIndex(temp, hum).DegreesCelsius:0.#}\u00B0C");
                Console.WriteLine($"Dew point: {WeatherHelper.CalculateDewPoint(temp, hum).DegreesCelsius:0.#}\u00B0C");
             }
             else
             {
                 Console.WriteLine("Error reading DHT sensor");
             }

             Thread.Sleep(2000);
        }
    }
}

The output of the above code is below.
Opening Pin - 4
Pin - 4 opened successfully
Dht11 object created
reading data

The execution gets stuck after displaying "reading data" and no sensor readings are coming.
The connection of Raspberry Pi and Sensor is as below -
Pin GND of Dth11 Sensor is Connected to Pin 6 of Raspberry Pi 4
Pin VCC of Dth11 Sensor is Connected to Pin 1 of Raspberry Pi 4
Pin NC  of Dth11 Sensor is Connected to Nothing
Pin SIG of Dth11 Sensor is Connected to Pin 7 (GPIO 4) of Raspberry Pi 4

A: you should not open the pin before.
Remove line controller.OpenPin(pin, PinMode.Input);
See: https://github.com/dotnet/iot/blob/c8130309c99a35ce68a10c40ca9003b0261cc2ef/src/devices/Dhtxx/DhtBase.cs#L100


text:
Q: Commands order getting changed in unix script I have below lines in unix script;
list_table_name=`hive -e 'show tables from schema'| grep -i 'hst_*' |sort -r|head -1`

When executing the script order of the commands is getting changed.
Sometimes the order is coming as

*

*hive -e 'show tables from schema'

*grep -i 'hst_*'

*sort -r

*head -1
but sometimes the order is coming as

*

*hive -e 'show tables from schema'

*sort -r

*head -1

*grep -i 'hst_*'
Why this is happening?


text:
Q: Information in a Markov Process I have a system that can be simulated with a Markov process $M_1$, but it could also be simulated with a higher order Markov process $M_n$, which has memory for 1 or more previous states. Is there a way to measure how well $M_1$ versus $M_n$ represents/captures information in the system?
I would like to generate simulated data from a data set I have, and I think a Markov (high order or not) process is likely the best way to do it, but I want an explicit measure for how well different types of Markov processes replicate the data I am interested in. Perhaps there may be something in information theory that can measure this.


text:
Q: How to add a bit at the start of BitSet buffer? I am using a BitSet buffer where i have about 500 bits inside and i want to add about 10 bits at the start of the buffer, i mean at index 0 so the rest of the buffer should be shifted but I dont see a way to "add" a bit only write methods, so if i already have a bit there it will be replaced, no added.
Is there any way to do this or i have to copy all to a temporary BitSet, add my 10 bits and then add my 500 bits ?
Thank you :)
PD: Sorry my bad English feel free of making corrections too :)

A: There is no way to insert bits at the front without copying.
Perhaps you could reverse the order of the bits in your BitSet? If you did, that would mean you're now appending bits to the end of the set, which can be done cheaply.
Alternatively, you could encapsulate a Deque of BitSets. Then inserting bits at the front could be accomplished by inserting a new BitSet at the front of the Deque.


text:
Q: Uncaught ReferenceError: $ is not defined content.js:1(anonymous function) content.js:1 Chrome extension error? This is my manifest.json file.
{
    "manifest_version": 2,
    "name": "Test",
    "version": "1",
    "description": "Test",
    "background": {
        "scripts": [
            "jquery.js",
            "content.js",
            "background.js"
        ]
    },
    "content_scripts": [
        {
            "js": [
                "content.js",
                "jquery.js"
            ],
            "matches": [
                "http://www.roblox.com/*",
                "https://www.roblox.com/*",
                "http://web.roblox.com/*",
                "https://web.roblox.com/*"
            ],
            "run_at": "document_end"
        }
    ]
}

My jquery.js file is normal just like the other ones.
My background.js just tells me when the document is ready.
and This is my content.js file.
$.get("http://www.roblox.com/--item?id=16412796", function(data){
    console.log($(data).find(".notranslate")[0].innerText);
});

It gives me this error of course for some odd reason.
Uncaught ReferenceError: $ is not defined content.js:1(anonymous function) content.js:1
How would I fix it?

A: Move jQuery to be first. Scripts are executed in the order listed.
        "js": [
            "jquery.js",
            "content.js"
        ]


text:
Q: Jetpack Compose - Unexpected vertical padding on Card @OptIn(ExperimentalMaterialApi::class)
@Composable
fun OutcomeItem(outcome: Outcome, onVote: () -> Unit) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .wrapContentHeight(),
        elevation = 4.dp,
        onClick = { onVote() }
    ) {
        Text(
            modifier = Modifier
                .padding(4.dp)
            ,
            text = outcome.title,
            style = MaterialTheme.typography.h6
        )
    }
}

▲ Composable with unexpected vertical padding
@Preview(showBackground = true)
@Composable
fun OutcomeItemPreview() {
    SuperBowlTheme {
        OutcomeItem(outcome = Outcome("4반 승!", arrayListOf())) {}
    }
}

https://i.stack.imgur.com/pBa13.png
I couldn't post inline image, sorry
▲My preview
I have no idea where did that vertical padding came from.
I've tried adding .padding(0.dp) on Card modifier, but it didn't work
++ root composable of OutcomeItem
@Composable
fun OutcomeContent(outcomes: List<Outcome>) {
    if (outcomes.size <= 2) {
        TwoOutcomeContent(outcomes)
    } else
        Column(
            modifier = Modifier
                .fillMaxWidth(),
        ) {
            outcomes.forEach { outcome ->
                OutcomeItem(outcome = outcome) {  }
            }
        }
    }
}

A: Card specifies a minimum size defined by the minimum touch target size; your content doesn't fill that space, so the padding is added outside of the card.
You can either make the content taller, or wrap your card and tell it to not enforce the minimum touch target size.
I wouldn't recommend it, but this is how you'd ignore the minimum size:

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun OutcomeItem(outcome: Outcome, onVote: () -> Unit) {
    CompositionLocalProvider(
        LocalMinimumTouchTargetEnforcement provides false,
    ) {
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .wrapContentHeight(),
            elevation = 4.dp,
            onClick = { onVote() }
        ) {
            Text(
                modifier = Modifier
                    .padding(4.dp),
                text = outcome.title,
                style = MaterialTheme.typography.h6
            )
        }
    }
}


text:
Q: Подключить js файл в другой файл Можно ли как-то подключить один js файл в другой?
что-то типа:
include 'js_prev.js';
console.log('...');

A: Можно написать такую функцию
function include(url) {
  var script = document.createElement('script');
  script.src = url;
  document.getElementsByTagName('head')[0].appendChild(script);
}

и использовать
include('js_prev.js');

Другой вариант, это использовать jQuery.getScript(). Хорошие примеры есть в  родной документации.
Еще можно глянуть в сторону RequireJS и CommonJS. Но это более затратные способы, надо будет реорганизовать все скрипты в модульную архитектуру. Реализация последнего из них (CommonJS) положена в основу модулей node.js.
Кроме того, в новый стандарт javascript (ECMAScript 6) добавлена нативная поддержка модулей.


text:
Q: For loop not working with int Alright so I had my for loop before set up like...
for(int i=0; i<inventory.size(); i++){
    g.drawImage(
        inventory.get(i).getImage(),
        Game.WIDTH - inventory.get(i).getImage().getWidth() - 2,
        (Game.HEIGHT / 2 - hud.getSideHeight() / 2) + (i*4+2) + i*(inventory.get(i).getImage().getWidth()),
        inventory.get(i).width,
        inventory.get(i).height,
        null
    );
}

But now instead of it running till inventory.size() I want it to run till it reaches seven so I did this...
for(int i=0; i<7; i++){
    g.drawImage(
        inventory.get(i).getImage(),
        Game.WIDTH - inventory.get(i).getImage().getWidth() - 2,
        (Game.HEIGHT / 2 - hud.getSideHeight() / 2) + (i*4+2) + i*(inventory.get(i).getImage().getWidth()),
        inventory.get(i).width,
        inventory.get(i).height,
        null
    );
}

Why doesn't this work? I am getting the java.lang.IndexOutOfBoundsException error. Thanks for all the help!

A: what happens if there is not 7 in the list?
try
for(int i=0; i<inventory.size() && i < 7; i++){

A: I suppose your requirement is to loop up to 7 maximum. Modify the for loop like this for it:
for(int i=0; i<Math.min(inventory.size(),7); i++){

Math.min() will take the smallest argument of the 2. So if the collection is less than 7, it will loop up to the size of the collection. If the collection is more than 7, it will loop to 7.

A: Modify your code :
int temp=inventory.size();
if(temp>7){
  temp=7;
}
for(int i=0; i<temp; i++){
    g.drawImage(
        inventory.get(i).getImage(),
        Game.WIDTH - inventory.get(i).getImage().getWidth() - 2,
        (Game.HEIGHT / 2 - hud.getSideHeight() / 2) + (i*4+2) + i*(inventory.get(i).getImage().getWidth()),
        inventory.get(i).width,
        inventory.get(i).height,
        null
    );
}

also check for null condition for inventory list


text:
Q: how to make multiple timeframe ichimoku indicator in pinescript? I working with the ichimoku strategy would like to show kumos from different timeframes on the same chart. what is the smartest way to do that?
I figured out how to make 2 ema's with different time frames using the How To Avoid Repainting and Using The Security Function & Higher Timeframe Data
however, I can't figure out how to use the same technique to make the ichimoku cloud. any ideas?

//@version=5

indicator('Lesson 9 multi time frames, no repaint ', overlay=true)

// what data should i feed it?
Midpoint(src,len,) =>
    math.avg(ta.highest(src, len), ta.lowest(src, len))

res = input.timeframe(title='Timeframe', defval='D')

// Create non-repainting security function
rp_function(_symbol, _res, _src) =>
    request.security(_symbol, _res, _src[barstate.isrealtime ? 1 : 0])

// Get higher timeframe data not the data i need. (from video)
htfHigh = rp_function(syminfo.tickerid, res, high)
htfLow = rp_function(syminfo.tickerid, res, low)
// just plotting some higher time frame
plot(htfHigh, color=color.new(color.red, 0), title='HTF high')
plot(htfLow, color=color.new(color.blue, 0), title='HTF low')

// ichimoku daily

D_TK = Midpoint(source, 9)
D_KJ = Midpoint(source,26)
D_CK = close
// senkou a and b
D_SKA = math.avg(TK, KJ)
D_SKB = Midpoint(52)

Any ideas are welcome :)

A: Used the Ichimoku indicator code from TV itself and modified it as below and it works:

//@version=5
indicator(title="Ichimoku Cloud with the required TF", shorttitle="Ichimoku", overlay=true)

close_req_tf = request.security(syminfo.tickerid, '240', close)
use_price = close_req_tf

conversionPeriods = input.int(9, minval=1, title="Conversion Line Length")
basePeriods = input.int(26, minval=1, title="Base Line Length")
laggingSpan2Periods = input.int(52, minval=1, title="Leading Span B Length")
displacement = input.int(26, minval=1, title="Lagging Span")

donchian(len) => math.avg(ta.lowest(use_price, len), ta.highest(use_price, len))

conversionLine = donchian(conversionPeriods)
baseLine = donchian(basePeriods)
leadLine1 = math.avg(conversionLine, baseLine)
leadLine2 = donchian(laggingSpan2Periods)

plot(conversionLine, color=#2962FF, title="Conversion Line")
plot(baseLine, color=#B71C1C, title="Base Line")
plot(close, offset = -displacement + 1, color=#43A047, title="Lagging Span")
p1 = plot(leadLine1, offset = displacement - 1, color=#A5D6A7,
     title="Leading Span A")
p2 = plot(leadLine2, offset = displacement - 1, color=#EF9A9A,
     title="Leading Span B")
plot(leadLine1 > leadLine2 ? leadLine1 : leadLine2, offset = displacement - 1, title = "Kumo Cloud Upper Line", display = display.none)
plot(leadLine1 < leadLine2 ? leadLine1 : leadLine2, offset = displacement - 1, title = "Kumo Cloud Lower Line", display = display.none)
fill(p1, p2, color = leadLine1 > leadLine2 ? color.rgb(67, 160, 71, 90) : color.rgb(244, 67, 54, 90))


text:
Q: UWP How to detect when a window changes its location I am using AppWindow (https://learn.microsoft.com/en-us/uwp/api/windows.ui.windowmanagement.appwindow) to create a second window for my UWP app.
I need to detect when the user changes the location of this secondary window (i.e. she drags the window over the screen).
Currently, I am listening to the following events:

*

*AppWindow.Changed

*UIElement.XamlRoot.Changed

which detect when the user resizes the window, but not when the window is simply moved (keeping exactly the same Width & Height).
Is there another event which I can listen to?
BTW, the same applies also for the old good Windows.UI.Xaml.Window: is there an event I can listen to for its movement (not resizing)?

A: I just today had a similar situation.  I need to know the resolution of the monitor that the UWP app is currently displayed on, even when moved.  As noted, you can capture the resize event, but there is no move event.
I solved my specific problem by adding a timer to my page:
Private WithEvents mTimer As DispatcherTimer
mTimer = New DispatcherTimer With {.Interval = New TimeSpan(0, 0, 0, 1)}
mTimer.Start()

Then capturing the TickEvent and checking the screen coordinates to see if they have changed for my page using:
Dim ScreenCoordsX As Double = ApplicationView.GetForCurrentView().VisibleBounds.Left
Dim ScreenCoordsY As Double = ApplicationView.GetForCurrentView().VisibleBounds.Top

Which I found here (c# UWP window location on screen issue).
The coordinates returned here are logical for all monitors seen as one big area, so any change means a screen move.
Might not work for everyone but is solved my specific issue.


text:
Q: Add a new Editable Row to Grid View without using Footer template or footer property of grid view we have a grid view to which we are binding data dynamically using database connection through web.config file. now we want to add a new editable row to grid view upon button click and whatever data we enter that should be updated in grid view.
is that possible?
if yes, please provide solution.
if no, why ?


text:
Q: React-flow & dare: reactFlowInstance.fitView() fits the instance in the screen after 2nd button click. (1st only changes the direction of the graph) I have tried different ways of implementing this beauty, but it doesn't seem to work. My problem is that when I hit the button, I want to change the layout of the graph, which happens and I am glad for it, but I also want my graph to be centered (fit) on the screen. The first button click changes the direction, but doesn't fit the instance. To fit the instance I need to hit the button for a second time. I guess it has to do with asynchronous JS or? This is my code:
  const onChangeTreeLayout = useCallback(
    (treeLayoutDirection) => {
      const layoutedElements = getLayoutedGraphElements(
        elements,
        treeLayoutDirection,
        setTreeLayoutDirection
      );
      setElements(layoutedElements);
    },
    [elements]
  );

Then how I get the instance and trigger it follows: Note: I can't use useReactFlow() hook as we decided not to migrate to a newer version. But useZoomPanHelper does its work anyway.
const reactFlowInstance = useZoomPanHelper();
<button
   onClick={() => {
     onChangeTreeLayout('TB');
     reactFlowInstance.fitView();
   }}
>
  Horizontal Layout
</button>

I have also tried putting the function .fitView() inside the onChangeTreeLayout but I get the same behaviour.


text:
Q: Monit won't execute commands Running Monit 5.2.5 on Fedora 15
All standard alerts are working, however just cannot get exec to run anything.
I have tried more than ten different configurations based on examples from the Monit Wiki. None of the exec commands do anything. Below is just one simple examples in an attempt to get 'something' working:
check process tomcat6 with pidfile /var/run/tomcat6.pid
    start program = "/etc/init.d/tomcat6 start"
    stop program = "/etc/init.d/tomcat6 stop"
    if failed host localhost port 8080 then
        exec "/bin/bash -c '/bin/touch /tmp/monittest'"

If I shutdown Tomcat an alert is sent and the service restarts. However whatever I try in exec is always ignored.
I understand that Monit is very restrictive in terms of its environment and is limited to directories such as /bin and/sbin/. Therefore all the example I have tried have been restricted to these directories. But still nothing.
Anyone any ideas?
p.s. I have turned on verbose logging and no clues in the log file.

A: Not sure if the connectivity test is done during service restart, maybe try something like this first:
check process tomcat6 with pidfile /var/run/tomcat6.pid
    if changed pid then exec "/bin/bash -c '/bin/touch /tmp/monittest'"

A: Your test works for me on Debian 6.0.4 with Monit 5.3.2 compiled from source.
Please try changing the port to an invalid value, like 8888 or 65432, and see if the file is created.


text:
Q: Messenger account linking works on mobile but not on desktop I'm developing a Messenger bot and my use case requires me to link an account.
I was able to setup this, but I realized that the linking process doesn't work when the account linking URL is opened on browser. Though, it actually seems fine if opened on Messenger app.
According to the docs, there are two parameters appended on the account linking URL automatically: (a) account_linking_token and (b) redirect_uri.
Based on my test, the parameters are provided on Messenger app, but not on browser which causes it to fail.
I'll be grateful for any help you can provide and explanation on why this happen. Is account linking only works on mobile phone? Or is there something that I'm missing?


text:
Q: Hole punched block doesn't load within full page cached page Intially when the cache is cleared and I visit a page the block and corresponding template load perfectly.  Then, when I revisit this page the block isn't loaded at all.  Am I missing something in this hole punching process?
Model Container:

class Myname_Page_Model_Container_Ajaxcart extends Enterprise_PageCache_Model_Container_Abstract
{
    protected function _renderBlock()
    {
        $blockClass = $this->_placeholder->getAttribute('block');
        $template = $this->_placeholder->getAttribute('template');

        $block = new $blockClass;
        $block->setTemplate($template);
        return $block->toHtml();
    }
}

Cache.xml:
<?xml version="1.0" encoding="UTF-8"?>
<config>
    <placeholders>
        <ajax_cart>
            <block>page/html_ajaxcart</block>
            <name>ajaxCart</name>
            <placeholder>AJAX_CART</placeholder>
            <container>Myname_Page_Model_Container_Ajaxcart</container>
            <cache_lifetime></cache_lifetime>
        </ajax_cart>
    </placeholders>
</config>

layout.xml:
<block type="page/html_ajaxcart" name="ajaxCart" as="ajaxCart" template="page/html/ajaxCart.phtml"/>

template.phtml:
<?php echo $this->getChildHtml('ajaxCart');?>

config file:
<?xml version="1.0"?>
<config>
    <modules>
        <Myname_Page>
            <version>0.1.0</version>
        </Myname_Page>
    </modules>
    <frontend>
        <routers>
            <page>
                <use>standard</use>
                <args>
                    <module>Myname_Page</module>
                    <frontName>page</frontName>
                </args>
            </page>
        </routers>
    </frontend>
    <global>
        <blocks>
            <page>
                <rewrite>
                    <html_ajaxcart>Myname_Page_Block_Html_Ajaxcart</html_ajaxcart>
                </rewrite>
            </page>
            <myname_page>
                <class>Myname_Page_Block</class>
            </myname_page>
        </blocks>
    </global>
</config>

block file:
<?php
class Myname_Page_Block_Html_Ajaxcart extends Mage_Core_Block_Template
{
    // sort quote by item date of addition
    public function sortByUpdatedAt($quote)
    {
        // initialize item collection
        $items = array();
        $collection = $quote->getAllVisibleItems();

        // get updated at date for each item
        foreach ($collection as $item) {
            if (!$item->isDeleted()) {
                array_push($items, $item->getData('updated_at'));
            }
        }

        // sort and keep key association
        asort($items);

        // reverse order and keep key association
        $k = array_reverse(array_keys($items));
        $reversed = array_reverse(array_values($items));
        $items = array_combine($k, $reversed);

        // collection is sorted
        $collection = $this->finishSort($items, $collection);
        return $collection;
    }

    // sort collection by established ordering
    protected function finishSort($items, $collection)
    {
        $sortedCollection = array();

        // collection will reflect sorted item array
        foreach ($items as $key => $value) {
            // get new order by established key value order
            array_push($sortedCollection, $collection[$key]);
        }
        return $sortedCollection;
    }

    public function getProductPrice($product)
    {
        // return formatted special price
        if ($product->getSpecialPrice() != null && Mage::app()->getLocale()->isStoreDateInInterval(Mage::app()->getStore(), $product->getSpecialFromdate(), $product->getSpecialToDate())) {
            $price = $product->getSpecialPrice();
        } else {
            $price = $product->getPrice();
        }
        // return formatted price
        return Mage::helper('core')->formatPrice($price, true);
    }
}

A: I believe you are missing a implementation of _getCacheId & _saveCache
A cache_id is already defined if none is provided but is of anonymous naming convention. Define an ID for the block and reference it in your _getCacheId

Add a etc/cache.xml file with a <config> root to your module. (see
  Enterprise/PageCache/etc/cache.xml). Choose a unique [placeholder]
  name.
The placeholders/[placeholder]/block node value must match the
  class-id of your custom dynamic block, e.g. mymodule/custom
The placeholders/[placeholder]/container node value is the class to
  generate the content dynamically and handle block level caching
The placeholders/[placeholder]/placeholder node value is a unique
  string to mark the dynamic parts in the cached page
placeholders/[placeholder]/cache_lifetime use to be ignored, but not
  anymore. For older instances specify a block cache lifetime in the
  container's _saveCache() method instead.
Implement the container class and extends
  Enterprise_PageCache_Model_Container_Abstract. Use _renderBlock() to
  return the dynamic content.
Implement the _getCacheId() method to return a unique string. Use
  cookie values instead of model ids (lower cost).
Implement _saveCache() to simply return, or pass a cache lifetime
  value to the parent method. Voila, dynamic block done.
One last note: You DON'T have the full Magento App at your disposal
  when _renderBlock() is called. Be as conservative as possible.

*

*http://tweetorials.tumblr.com/post/10160075026/ee-full-page-cache-hole-punching

A: I think you have missed the <template> tag in the cache.xml file. But 'm not sure about this.
<?xml version="1.0" encoding="UTF-8"?>

<config>
    <placeholders>
        <ajax_cart>
            <block>page/html_ajaxcart</block>
            <name>ajaxCart</name>
            <placeholder>AJAX_CART</placeholder>
            <template>page/html/ajaxCart.phtml</template> <!-- Your template file -->
            <container>Myname_Page_Model_Container_Ajaxcart</container>
            <cache_lifetime>false</cache_lifetime>
        </ajax_cart>
    </placeholders>
</config>

Try the above code it may work.


text:
Q: Create payload from array I am trying to create the payload/data using an PHP array as input, by using [json_encode]. I noticed that the results of payload_1 has squared brackets but that payload_2 does not.
Question:
How can I create payload_2 with the result of squared brackets in the same position as in payload_1 ? To clarify, the outcome of payload_2 should be same as outcome of payload_1.
<?php

// Create payload from string.

$payload_1 = "{
    \"prenumeration\":
    [
        {
            \"url\":\"http://www.google.com\"
        }
    ]

}";

var_dump($payload_1);

echo "\n\n";

// Create payload from array.

$payload_2 = array(
    "prenumeration" => array(
    "url"           => "http://www.google.com"
    )
);

$payload_2 = json_encode($payload_2);

var_dump($payload_2);

echo "\n\n";

Results:
Result (payload_1):
"{"prenumeration":[{"url":"http://www.google.com"}]}"

Result (payload_2):
"{"prenumeration":{"url":"http:\/\/www.google.com"}}"

A: Try the following:
$payload_2 = array(
    "prenumeration" => array(array(
        "url"           => "http://www.google.com"
    ))
);

prenumeration must be an array of associative arrays.
array("url" => "http://www.google.com") is an associative array of one element. Associative arrays are represented with curly brackets.
array(array("url" => "http://www.google.com")) is an array of one element (that happens to be an associative array). Arrays are represented with square brackets.


text:
Q: toggle element in react without too many variables when somebody clicks on a list heading, the particular list should toggle.
I have 100's of list on the same page.
I don't want to have to create 100  variables in state that I can set to true or false to toggle.
Multiple lists could be open at the same time.
What is the most efficient way to do it?


text:
Q: Azure VPN Gateway BGP APIPA Addresses I'm working with a supplier to implement Active/Active Site-to-Site IPSec tunnels to two different regions in the same geography.  The supplier is using Palo Alto firewalls.
We've managed to establish both tunnels just fine - IKE and IPSec parameters are configured correctly and I can route bidirectionally between Azure and the supplier premises.
Now we're trying to get the route preferences configured so that if the primary tunnel goes down then traffic will automatically be sent over the second tunnel to the second region.
The supplier has requested that we use APIPA addresses for probing whether the tunnels are up are not.  No problem, Azure supports APIPA addresses for BGP - but do they respond to ICMP?
What I'm not clear on - despite reading all the MS documentation - is whether the APIPA address configured in the VPN Gateway resource BGP settings is the receiver address or the neighbor address.  I'm assuming it's the receiver, and the peer address is configured in the BGP settings of the Local Network Gateway.  Correct me if this isn't correct.
The Microsoft documentation says:

Azure VPN Gateway will choose the custom APIPA address if the corresponding local network gateway resource (on-premises network) has an APIPA address as the BGP peer IP.

Does this suggest I can leave the VPN Gateway APIPA empty and Azure will choose one for me?  If so, this could be a problem, since the supplier has to specify 2 x /30 address spaces, one for each tunnel and is depending on Azure having a specific address, and the Palo Alto having a specific one.  I guess this means I need to configure the address in the VPN first, then configure the peer address in the local gateway?
Aside from that, the supplier only wants to use these addresses for probing by pinging them.  I've created BGP configurations in ExpressRoute circuits and can confirm the B-End (Azure) BGP neighbor addresses do respond to ICMP Echo, but I do believe that is only once a successful BGP session has been established.
So my question is, is it possible to specify in an Azure VPN Resource, for example, an APIPA address of 169.254.21.2, a peer address of 169.254.21.1, and without an actual BGP session being established get a ping response from 169.254.21.2.  I know it should have TCP 179 open for BGP establishment, but I don't think the Palo Altos can do a port test instead of ping.

A: I checked with the Azure VPN Product Group team and below is their response on this query:
While Azure VPN gateways allow specific APIPA addresses for each VPN instance, we cannot utilize a prefix-based approach (/30 with fixed allocation). We are looking into allowing more APIPA addresses on the Azure VPN side to workaround this constraint. But we are still in the design phase right now.
At present, the VPN gateway will initiate BGP peering sessions to the on-premises BGP peer IP addresses specified in the local network gateway resources using the private IP addresses on the VPN gateways. This is irrespective of whether the on-premises BGP IP addresses are in the APIPA range or regular private IP addresses.
Reference : https://learn.microsoft.com/en-us/azure/vpn-gateway/vpn-gateway-bgp-overview#do-azure-vpn-gateways-initiate-bgp-peering-sessions-or-connections
We can have multi APIPA (support in-works) created and configured on the gateway without actually have the BGP peers connected but the requirement for Ping is something that we do not support/recommend.


text:
Q: Android In App Purchases: can user buy multiple copies of same product at once I am interested, if user of In App Billing Android app can buy multiple copies of the same in app product with one click of " Buy " button. For example, if the product is " Gold coin ", can we buy 2 coins at once? Or we need to process buy flow twice?

A: You cannot buy two items at once from google in App Purchases, its not supported. You can however bundle those multiple items and present it as a single item. Like make a bundle of 2x Coins


text:
Q: Organize table in PHP I had already asked a similar question before, but I tried to adapt it to my code and it did not work well.
I have the following code that paints a table in PHP, I want to show the PRODUCT total when I detect PRODUCT change, I have tried to do the following, but it shows me the TOTAL row at the beginning of each PRODUCT and does not totalize well
The variables GOLD, NORMAL are dynamic, i.e. there may be tables that do not have GOLD, like others that do not have NORMAL:
This is my code:
<?php

$harvest = Array (
       Array (
                     Array (
                                    'PRODUCT' => 'ROSE' ,
                                    'VARIETY' => 'ADELE',
                                  'GOLD' => 160,
                                    'NORMAL' => 0 ,
                                    'TOTAL' => 160
                                  ) ,
                     Array (
                                    'PRODUCT' => 'ROSE',
                                    'VARIETY' => 'ALESSO' ,
                                    'GOLD' => 1320 ,
                                    'NORMAL' => 550,
                                    'TOTAL' => 1870
                                  ) ,
                     Array (
                                    'PRODUCT' => 'ROSE',
                                    'VARIETY' => 'ANASTACIA' ,
                                    'GOLD' => 440 ,
                                    'NORMAL' => 150 ,
                                    'TOTAL' => 590
                                  ),
                     Array (
                                    'PRODUCT' => 'ROSE1',
                                  'VARIETY' => 'ANASTACIA1' ,
                                  'GOLD' => 420 ,
                                    'NORMAL' => 120 ,
                                    'TOTAL' => 540
                                  ),
                     Array (
                                    'PRODUCT' => 'ROSE1',
                                    'VARIETY' => 'ANASTACIA1',
                                    'GOLD' => 440 ,
                                    'NORMAL' => 100 ,
                                    'TOTAL' => 540
                                  ),
                     Array (
                                    'PRODUCT' => 'ROSE2',
                                    'VARIETY' => 'ANASTACIA2',
                                    'GOLD' => 640,
                                    'NORMAL' => 0,
                                    'TOTAL' => 640
                                  ),
                     Array (
                                    'PRODUCT' => 'ROSE2',
                                    'VARIETY' => 'ANASTACIA2' ,
                                    'GOLD' => 440,
                                    'NORMAL' => 440,
                                    'TOTAL' => 880
                                   )
                    )

     );

$arrayThead = array();
      for ($i=0; $i < count($harvest) ; $i++) {
        array_push($arrayThead, array_keys($harvest[$i][0]));
      }

      $totalByProduct = array();
      foreach ($harvest as $items) {
          foreach ($items as $item) {
              if(!key_exists($item['PRODUCT'], $totalByProduct)){
                  $totalByProduct[$item['PRODUCT']] = $item;
                  continue;
              }
              foreach ($arrayThead as $key => $values) {
                foreach ($values as $th) {
                  if($th != 'PRODUCT' && $th != 'VARIETY'){
                    $totalByProduct[$item['PRODUCT']][$th] += $item[$th];
                  }
                }
              }
          }
      }
      $arrayfoot= array();

      foreach ($harvest as $key => $value) {
        foreach ($value as $harv) {
          foreach ($arrayThead as $key => $values) {
            foreach ($values as $th) {
              if($th != 'PRODUCT' && $th != 'VARIETY'){
                  $arrayfoot[$th] += $harv[$th];
              }
            }
          }
        }
      }

      $arrayComplete = array();
      for ($i=0; $i < count($arrayThead) ; $i++) {
        for ($j=0; $j < count($arrayThead[$i]) ; $j++) {
          if($arrayThead[$i][$j] != 'PRODUCT' && $arrayThead[$i][$j] != 'VARIETY'){
            array_push($arrayComplete, $arrayThead[$i][$j]);
          }
        }
      }

      $arrayFinal = array();
      for ($j=0; $j < count($arrayComplete) ; $j++) {
        array_push($arrayFinal, $arrayfoot[$arrayComplete[$j]]);
      }

      $body = '
';
      $body .= '
';
      $body .= '
';

      for ($i=0; $i < count($arrayThead) ; $i++) {
        for ($j=0; $j < count($arrayThead[$i]) ; $j++) {
          if($arrayThead[$i][$j] === 'PRODUCT' || $arrayThead[$i][$j] === 'VARIETY'){
            $body .= ''.$arrayThead[$i][$j].'	';
          }else{
            $body .= ''.$arrayThead[$i][$j].'	';
          }
        }
      }
      $body .= '
';
      $body .= '
';
      $body .= '
';

//Initialize the variable product
      $product = "";
      foreach ($harvest as $items) {
          foreach ($items as $item) {

//If the $product variable is different from the data product, print the total

          if($product != $item['PRODUCT']){
              $body .= '
';
              $body .= 'TOTAL '.$item['PRODUCT'].'	';
              $body .= '	';

              foreach ($arrayThead as $key => $values) {
                foreach ($values as $th) {
                  if($th != 'PRODUCT' && $th != 'VARIETY'){
                    $body .= ''.number_format($total).'	';
                  }
                }
              }
              $body .= '
';
              $product = $item['PRODUCT'];
          }
          $body .= '
';
          foreach ($arrayThead as $key => $values) {
            foreach ($values as $th) {
              if($th === 'PRODUCT' || $th === 'VARIETY'){
                $body .= ''.$item[$th].'	';
              }else{
                $body .= ''.number_format($item[$th]).'	';
              }
            }
          }
          $body .= '
';
          $product = $item['PRODUCT'];
        }
      }

      $body .= '
';
      $body .= '
';
      $body .= '
';
      $body .= 'TOTAL GENERAL	';
      $body .= '	';

      for ($i=0; $i < count($arrayFinal) ; $i++) {
        $body .= ''.number_format($arrayFinal[$i]).'	';
      }

      $body .= '
';
      $body .= '
';
      $body .= '
';

      echo $body;

To see how it works, please copy and paste the code on the following page:
PHPTester
I hope that someone can help me.

A: May be you are looking for something like this
    <?
$harvest = Array (
     Array (
                    'PRODUCT' => 'ROSE' ,
                    'VARIETY' => 'ADELE',
                    'GOLD' => 160,
                    'NORMAL' => 0 ,
                    'TOTAL' => 160
                  ) ,
     Array (
                    'PRODUCT' => 'ROSE',
                    'VARIETY' => 'ALESSO' ,
                    'GOLD' => 1320 ,
                    'NORMAL' => 550,
                    'TOTAL' => 1870
                  ) ,
     Array (
                    'PRODUCT' => 'ROSE',
                    'VARIETY' => 'ANASTACIA' ,
                    'GOLD' => 440 ,
                    'NORMAL' => 150 ,
                    'TOTAL' => 590
                  ),
     Array (
                    'PRODUCT' => 'ROSE1',
                  'VARIETY' => 'ANASTACIA1' ,
                  'GOLD' => 420 ,
                    'NORMAL' => 120 ,
                    'TOTAL' => 540
                  ),
     Array (
                    'PRODUCT' => 'ROSE1',
                    'VARIETY' => 'ANASTACIA1',
                    'GOLD' => 440 ,
                    'NORMAL' => 100 ,
                    'TOTAL' => 540
                  ),
     Array (
                    'PRODUCT' => 'ROSE2',
                    'VARIETY' => 'ANASTACIA2',
                    'GOLD' => 640,
                    'NORMAL' => 0,
                    'TOTAL' => 640
                  ),
     Array (
                    'PRODUCT' => 'ROSE2',
                    'VARIETY' => 'ANASTACIA2' ,
                    'GOLD' => 440,
                    'NORMAL' => 440,
                    'TOTAL' => 880
                   )

 );

 //You will endup with a products array indexed by product name
 $products = [];

 $general = Array('GOLD' => 0,'NORMAL' => 0, 'TOTAL' => 0);
 foreach ($harvest as $items) {
    $general["GOLD"] += $items["GOLD"];
    $general["NORMAL"] += $items["NORMAL"];
    $general["TOTAL"] += $items["TOTAL"];
    if (array_key_exists($items["PRODUCT"],$products)){
        $products[$items["PRODUCT"]]["TOTALS"]["GOLD-TOTAL"] += $items["GOLD"];
        $products[$items["PRODUCT"]]["TOTALS"]["NORMAL-TOTAL"] += $items["NORMAL"];
        $products[$items["PRODUCT"]]["TOTALS"]["TOTAL"] += $items["TOTAL"];
        array_push($products[$items["PRODUCT"]],$items);
    }
    else{
        $totals=[];
        $totals["GOLD-TOTAL"] = 0;
        $totals["NORMAL-TOTAL"] = 0;
        $totals["TOTAL"] = 0;
        $totals["NAME"] = $items["PRODUCT"];
        $products[$items["PRODUCT"]]=[$items];
        $products[$items["PRODUCT"]]["TOTALS"] = $totals;
    }
 }

?>

    PRODUCT
    VARIETY
    GOLD
    NORMAL
    TOTAL

    <?foreach ($products as $product) {
        foreach ($product as $item){
            if (array_key_exists("PRODUCT",$item)){
    ?>

        <?print($item["PRODUCT"])?>
        <?print($item["VARIETY"])?>
        <?print($item["GOLD"])?>
        <?print($item["NORMAL"])?>
        <?print($item["TOTAL"])?>

    <?}}?>

        Total <? print($product["TOTALS"]["NAME"])?>

        <? print($product["TOTALS"]["GOLD-TOTAL"])?>
        <? print($product["TOTALS"]["NORMAL-TOTAL"])?>
        <? print($product["TOTALS"]["TOTAL"])?>

    <?}?>

        TOTAL GENERAL

        <?print($general["GOLD"])?>
        <?print($general["NORMAL"])?>
        <?print($general["TOTAL"])?>


text:
Q: How to use MySql select with c# Can anyone tell whats wrong with my code? I have tried a million different things and I cant seem to make it work. I need to make a select in my mysql database and use the id from the table with the specified name I take from a combobox.
I took that name from the combobox and put it into a variable named "nomeres", now I need to do a select with it and take the id from that name from the database. Everything I try to do results in a mysql syntax error in line 1, but I've tried alot of things and its always the same. The database is fine, I tried the select directly from it myself, no tables or columns names are incorrect. This is the code im using:
MySql.Data.MySqlClient.MySqlConnection dbConn = new MySql.Data.MySqlClient.MySqlConnection("Persist Security Info=False;server=localhost;database=notas;uid=root;password=" + dbpwd);

MySqlCommand cmd = dbConn.CreateCommand();
cmd.CommandText = "SELECT id from residentes WHERE nome ='" + nomeres;

try
{
    dbConn.Open();
} catch (Exception erro) {
    MessageBox.Show("Erro" + erro);
    this.Close();
}

MySqlDataReader reader = cmd.ExecuteReader();

while (reader.Read())
{
    idnumber = reader.ToString();
}

A: You need to terminate the string in the query:
"SELECT id from residentes WHERE nome ='" + nomeres + "'"

In general, when trying to debug this type of code, it helps to print out the query string after all substitutions have been made.

A:  cmd.CommandText = "SELECT id from residentes WHERE nome ='" + nomeres + "';";

actually you misses the semicolon of the query that have to enter within the quotes. and the second semicolon is for the end of statement.
But I preffer wo write commands like
 cmd.CommandText = "SELECT id from residentes WHERE nome = @nome";
 cmd.Parameters.AddWithValues("@nome", variableName);

then execute the query and retrieve your results.

A: as others have already pointed you towards right direction,
 i would like to suggest you to use parameterised queries to avoid SQL injection attacks.
Your query is open to SQL injection attacks so please read here
Try This: using parameterised SQL queries
cmd.CommandText = "SELECT id from residentes WHERE nome = @nome";
cmd.Parameters.AddWithValue("@nome",nomeres);

A: Missing single quote:
"SELECT id from residentes WHERE nome ='" + nomeres + "'";
                                                       ^


text:
Q: solving a optimisation problem with max of a variable Original Question - Find the optimal mixed - strategy for player one given the payoff matrix
0 2 1 -1
3 4 0 -5
-1 3 0 2
-1 -1 2 1

I have the following maximisation problem
max v
s.t
3p1 -p3 -2p4 <= v
2p1 +4p2 +3p3 -p4 <= v
p1 +2p4 <= v
-p1 -5p2 +2p3+p4n <= v
where pi <0
I have used the following code for a maximisation problem previously but I am unsure how to adapt it for this problem due to the max function being v
% max 6x - y s.t.
% 4y - x >= 10
% 2x + y <= 10
% 2y - x <=  5

f = -[6;-1];          % objective function
A = [1 -4; 2 1; -1 2];    % constraint matrix
b = [-10 10 5];           % constraing rhs
Aeq = [];               % no equality constraints here
beq = [];               % no equality constraints here
lb = [];
ub = [];

%% call linprog
optimum = linprog(f,A,b,Aeq,beq,lb,ub)


text:
Q: Ansible can't connect to Vagrant VM (Permission denied) I've put together a VM using Vagrant (Virtualbox is the provider) for a server I'm setting up. I can SSH into the VM using vagrant ssh and ssh vmname, but when I run ansible-playbook -vvvv /path/to/playbook.yml, I get a "permission denied" error when Ansible tries to connect to the VM.
It's too long to post the results of running the playbook here, so I've uploaded it to Pastebin instead.
What am I doing wrong?

A: Your playbook try connecting to the target vm with user root but that doesn't exist in the vm.
To double-check it, I think you get an error trying to login to the VM using
ssh root@vmname

Because you are sure that the vagrant user exists in the VM, setting remote_user as vagrant in /path/to/playbook.yml should solve your problem:
remote_user: vagrant

Otherwise, you can run ansible-playbook with options -u and -k
ansible-playbook /path/to/playbook.yml -u vagrant -k

A: Did you have a ansible.cfg inside your current dir? Ansible could be using these configurations, made for another environment connection (different user, like the first answer here) and be impacting your directly connection. If so, try to hide your ansible.cfg file with:
mv ansible.cfg .ansible.cfg


text:
Q: How should I modify str.replace_all? I recently discovered how to use str.replace_all . And again the question arose.
    useentryalert = input(defval=true, title="Use Entry Alert", group="Alert Messages")
    entrystring = input.text_area(title="Entry Alert Message", defval='TVM:{"exchange":"binance-futures","account":"*","symbol":"@@@/USDT", "type":"market","side":"buy","amount":{{entrySize}},"token":"1234"}:MVT', confirm=false, group="Alert Messages")

    alertMsg1 = str.replace_all(entrystring, "{{entrySize}}", str.tostring(entry_size))

    if entry condition
         strategy.order("Short", strategy.short, qty=entry_size, limit=r_close, comment="Entry", alert_message=alertMsg1)

I would like to create one more variable while modifying the message I put in the entrystring's defval.
Previously, only {{entrySize}} was entered, but I would like to include {{tp_price}} along with it.
TVM:{"exchange":"binance-futures","account":"*","symbol":"@@@/USDT","type":"market","side":"buy","amount":{{entrySize}},","tp_price":{{tp_price}},"tp_lo_price":{{tp_price}},"token":"1234"}:MVT

If alertMsg1 contains {{entrySize}} and {{tp_price}}, how can I modify it?

A: Just add another str.replace_all call:
useentryalert = input(defval=true, title="Use Entry Alert", group="Alert Messages")
entrystring = input.text_area(title="Entry Alert Message", defval='TVM:{"exchange":"binance-futures","account":"*","symbol":"@@@/USDT", "type":"market","side":"buy","amount":{{entrySize}},"token":"1234"}:MVT', confirm=false, group="Alert Messages")

alertMsg1 = str.replace_all(entrystring, "{{entrySize}}", str.tostring(entry_size))

alertMsg1 := str.replace_all(alertMsg1, "{{tp_price}}", str.tostring(tp_price))

if entry condition
    strategy.order("Short", strategy.short, qty=entry_size, limit=r_close, comment="Entry", alert_message=alertMsg1)


text:
Q: MSBUILD 14.0 Visual Studio 2015 CustomBuild Command environment does not contain the result of a SetEnv even though Exec does I have used CoApp to create a nuget package to package some code generators (binaries). I want to be able to use these code generators in a msbuild custombuild step to generate the code
I have a targets file that defines the following (using CoApp)
<SetEnv Condition="'$(Platform.ToLower())' == 'x64' And '$(PlatformToolset.ToLower())' == 'v100' And ( $(Configuration.ToLower().IndexOf('debug')) == -1 )" Name="PATH" Prefix="true" Value="$(MSBuildThisFileDirectory)../..//build/native/bin/x64\v100\Release;">
  <Output TaskParameter="OutputEnvironmentVariable" PropertyName="PATH" />
</SetEnv>

The targets file containing this snippet is imported like so into a project (vcxproj file)
<Import Project="..\packages\habitat.id.redist.1.0.0.5\build\native\habitat.id.redist.targets" Condition="Exists('packages\habitat.id.1.0.0.1\build\native\habitat.id.targets')" />

within the project
<Exec Command="echo %PATH%"/>

returns the desired outcome i.e. that which takes the form

  ../..//build/native/bin/x64\v100\Release;C:\

so I can call the executable that I want to run from the project. (except for unlike a custombuild command step there is no concept of outputs. So incremental builds will thence not work)
however
<CustomBuild Include="..\directory\filename">
  <FileType>Document</FileType>
  <Command Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
  echo $(PATH)
</Command>

does not contain the path that I want that was set through the SetEnv.
I want to do this so I can call code generators that were packaged via nuget during a custom build step.
I understand that the command inside a custombuild runs through/in a new cmd and that the environment is inherited via the user or system env's that were set. Also that I can start Msbuild using /p:useenv , and hence pump any environment that I would like. This, using /p:useenv, in my opinion amounts to hard coding the path - knowing it ahead of time.
I want to be able to update my packages and run i.e. I want the project to manage the path given that it is defined in the target file that is imported.

A: Looks like C++ has a little ways to go until they can support package updates for binaries. The headers (ClCompile > AdditionalIncludeDirectories) and libs (Link > Additionaldependencies) are fine
I wanted to continue to use the custom build because it is exposed through the standard visual studio property sheet, a custom target is not (until you customize the property sheet hence introducing something that not everyone is familiar with, will forget to install and then complain) So I was hoping to get a product level solution that would come through the next product update. That looks unlikely
I was looking to continue to use the environment variable approach because that's the way CoApp does it for nuget package it creates for C++ binaries. It's easy enough to change the targets file. (Not using CoApp's Write-NugetPackage but use nuget pack instead)
A custombuild command does not expand msbuild properties set like:
<PropertyGroup Condition="'$(Platform.ToLower())' == 'x64' And '$(PlatformToolset.ToLower())' == 'v90'">
    <HabitatBindir>$(MSBuildThisFileDirectory)../..//build/native/bin/x64\v90\Release</HabitatBindir>
</PropertyGroup>

and used like
<Command Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(HabitatBindir)aemcomp.exe -nonotice -mlf -dll %(Identity)</Command>

The Target-Exec-Property is the best combination I could come up with.


text:
Q: ACF with Timber isn't displaying on the front page I'm working with Timber and Advanced Custom Fields on new Wordpress project. I created some new widgets and uses some ACF. Everything worked fine. Now I'mb building front page and using twig files. I have strange problem because I've created many fields like repeater, text, some textarea etc. and everything's working in WP but I can't display it on the page. There are empty values inside tags. I don't know what am I doing wrong.
front-page.twig

{{ post.why_header }}

{{ post.why_text }}

front-page.php
<?php

/**
 * @package  WordPress
 * @subpackage  Timber
 * @since    Timber 0.1
 */

$context = Timber::get_context();
$post = new Timber\Post();
$context['post'] = $post;
Timber::render(array('front-page.twig'), $context);

Of course my ACF names are like: why_header and why_textand inside ACF inputs there is some text.

A: Solved.. front-page wasn't set as a front page..


text:
Q: Parse a json/dictionary with same key values I currently have a list variable that looks like this:
list_of_dicts = [{"Away_Team":"KC", "Home_Team":"NYY"},
                 {"Away_Team":"TB", "Home_Team":"MIA"},
                 {"Away_Team":"TOR", "Home_Team":"BOS"},
]

As you can see, there are multiple keys with the same names, pertaining to the game matchups.
When I try to use:
print(json.dumps(list_of_dicts[0], indent=4, sort_keys=True))

...it only prints out the first matchup due to the same keys:
{
    "Away_Team": "KC",
    "Home_Team": "NYY"
}

How can I convert this list_of_dicts variable into something like the following output so I can use it like a valid dictionary or json object?
{
    "Away_Team_1":"KC", "Home_Team_1":"NYY",
    "Away_Team_2":"TB", "Home_Team_2":"MIA",
    "Away_Team_3":"TOR", "Home_Team_3":"BOS",
}

This output doesn't need to be exactly that if a better solution is available, this is just to give you an idea of how I'd like to be able to parse the data.
The list_of_dicts variable can be of varying sizes, I've shown 3 here, but it could contain 1 or 10 matchups, it varies, so the solution needs to be dynamic to that.

A: You can add suffixes to the keys with enumerate:
list_of_dicts2 = [{f"{k}_{i}":v for k,v in d.items()} for i,d in enumerate(list_of_dicts, start=1)]

A: One option is to use pandas:
pd.DataFrame(list_of_dicts).to_csv('filename.csv', index=False)

gives
Away_Team,Home_Team
KC,NYY
TB,MIA
TOR,BOS

Now the index is implied by the row, and if you load it back in you'll have those indices. Pandas also supports to_json if you are hard set on using json though. You can even recover your original list from a dataframe using .to_dict(orient='records')

A: Data structure is important.  You really don't need a dictionary for this.  Simply reducing to a list of tuples the first slot always the away team, and the second the home team.
list_of_dicts = [{"Away_Team":"KC", "Home_Team":"NYY"},
                 {"Away_Team":"TB", "Home_Team":"MIA"},
                 {"Away_Team":"TOR", "Home_Team":"BOS"},
]

l = [tuple(l.values()) for l in list_of_dicts]

output:
[('KC', 'NYY'), ('TB', 'MIA'), ('TOR', 'BOS')]

The problem with your proposed solution is iterating through dicts where you don't know the key name is cumbersome, this solution makes the data structure easy to decipher, transform, or manipulate.


text:
Q: Limited HTTP traffic I'm experiencing a weird limited connectivity scenario with my Linux network stack.
The problem is that whenever I try to download something, I can only get the first 5.5KB of the requested resource, both with my ethernet card (Realtek 8139), and through my wireless card (IPW2200).
For example:

*

*wget google.it => I will get a full 'index.html' page (as it's 4.9KB)

*wget google.it/intl/it_it/images/logo.gif => I will get the first 5.5KB of the image and wget will hang, undefinitely waiting for the remaining part of the image

*capture of HTTP conversation to www.polito.it (6) (as you can see in this capture, no further requests are going out, even if the page is missing some elements)

Environment&tools:

*

*I try seeing the pages through both Firefox and command-line Links, both from my local installation and from Live CDs

*on Windows both network cards are working perfectly without any issue (I'm writing from the dual-booted Windows right now)

*this problem is happening on every Linux distro I have tried (each with different kernels): ArchLinux, Live ArchLinux 2007.08, grml 2008, grml 2009.10

Here is my Linux configuration:

*

*the kernel is detecting the card (module 8139too or ipw2200) and assign to it a good IRQ

*the DHCP server (at 192.168.1.1) is correctly assigning the IP 192.168.1.2 to my network interface. Example of ethernet one:
eth0      Link encap:Ethernet  HWaddr 00:c0:9f:be:77:da
      inet addr:192.168.1.2  Bcast:192.168.1.255  Mask:255.255.255.0
      inet6 addr: fe80::2c0:9fff:febe:77da/64 Scope:Link
      UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
      RX packets:478 errors:0 dropped:0 overruns:0 frame:0
      TX packets:322 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:1000
      RX bytes:163064 (159.2 KiB)  TX bytes:40610 (39.6 KiB)
      Interrupt:16 Base address:0xc000

*the MTU is set to 1500, but even with smaller values the problem is still there (I tried values of 1492, 1454, 1000, 500)

*the DNS resolution is working good

*the pings to other hosts on the network/internet are ok:
PING www.l.google.com (74.125.43.104) 56(84) bytes of data.
64 bytes from bw-in-f104.1e100.net (74.125.43.104): icmp_seq=1 ttl=50 time=52.1 ms
64 bytes from bw-in-f104.1e100.net (74.125.43.104): icmp_seq=2 ttl=50 time=50.9 ms

*there is no timeout/full receive buffers/unhandled IRQs messages indicated by the kernel
I have no other ideas about why this is happening...
Apart fom this, this issue is reproducible and for any web-page, it stops loading after a give amount.

A: I found out the problem: my gateway is not properly handling the TCP Window Scaling.
Therefore, I instructed my Linux kernel not to use this functionality and now the connection is working smoothly.
For your info, here is my patch into the network configuration.
In /etc/sysctl.conf I added the following lines:
net.ipv4.tcp_window_scaling=0
net.ipv4.tcp_ecn=0

And this was the identification of my router: "Alice Gate 2 Plus Wi-Fi" with firmware version "AGIA_1.2.0"

A: If as you say it is working on Windows fine and you are having problems on various Linux distributions, it is possible that the Linux driver is simply bad.
I would personally file a bug report or see if you can find a different version of the driver.
Also, I am a little confused on one point -

I try seeing the pages through both Firefox and command-line Links, both from my local installation and from Live CDs

Are you saying that you have tried and it works or fails?
If works, try ripping the driver from the live CD. If it fails, you may be out of luck.
At no point should you have to manually mess around with MTU or other technical items... I always say things like that are there so you can fine tune it once you know it is already working (so you know what to go back to if there is an error!), but if it doesn't work by default, it is some other sort of fault that you should look at first.


text:
Q: Why don't urls to my css and images work in Firefox? With any other browser the website loads fine with the CSS file along with the images.
On firefox however, the CSS file does not seem to load along with the images
I have noticed that only one out of the five images has loaded on firefox for some reason. I have also noticed that the background pictures for my div elements have not loaded in, but replaced with black. This could be because I changed my contrast to black/green.
I have seen on another question that I cannot seem to find the link to again that they said that firefox reads backslashes instead of forwardslashes to link files. I have tried this, and still however does not work.
Here is how I load my CSS file
<link rel="stylesheet" type="text/css" href="styles\main.css">

This is how I have a src for an image

How would I get firefox to load these things? (images/CSS file)

A: Your file paths are incorrect for both the 'href' and 'src'.  Try revising them to the following:
<link rel="stylesheet" type="text/css" href="styles/main.css">
and


text:
Q: Unity error while trying to send data to an online post api I'am trying to make a post api work on unity with a dummy post api online before working on a real post api that is part of my internship's project.
I dont really know why the post api is not working on unity despite that i entered the right arguments and it works on postman.
i have commented my code a little bit that might help.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;

public class API: MonoBehaviour {

  private const string URL = "http://dummy.restapiexample.com/api/v1/create";
  public Text responseText;

  public void Request() {

   WWWForm FORM = new WWWForm();

   FORM.AddField("name", "tarek");
   FORM.AddField("salary", "9001");
   FORM.AddField("age", "26");
   byte[] rawFormData = FORM.data;

   WWW request = new WWW(URL, rawFormData);
   StartCoroutine(Reponse(request));
   Debug.Log("text :" + request.text);

  }

  private IEnumerator Reponse(WWW req) {
   yield
   return new WaitForSeconds(2.0 f);
   yield
   return req;
   responseText.text = req.text;
   Debug.Log("end : " + req.text);

  }


text:
Q: Проблема с алиас (синоним) Обратите внимание на алиас (синоним) R, которому дал метод wid.document.write, чтобы иметь возможность кратко вызывать его как R(...).

  Изменим значение переменной t в новом окне

FireFox работает корректно, а вот дебагер в Chrome ругается на
R('

FireFox так же работает корректно. Chrome перестал ругаться. Как правильно задать синоним R?

A: В данном случае, write завязан на контекст в котором вызывается, для сохранения его нужно использовать bind
var R = wid.document.write.bind(wid.document);


text:
Q: How to give change working of having function dynamicaly on executing an sql statement? I'm having a Sql code like as follows
     Select a.ItemCode, a.ItemDesc
 From fn_BOM_Material_Master('A', @AsOnDate, @RptDate, @BranchID, @CompID)a
 Left Outer Join fn_INV_AsOnDate_Stock(@StockDate, @AsOnDate, @RptDate, @BranchID, @CompID, @Finyear)b
 On a.ItemCode=b.ItemCode and b.WarehouseCode<>'WAP'
 and a.BranchID=b.BranchID and a.CompID=b.COmpID
 Where a.ItemNatureCode = 'F' and a.BranchID = @BranchID and a.CompID = @CompID
 Group by a.ItemCode, a.ItemDesc
 Having sum(b.CBQty)<=0

Here the problem is that im passing an "@ShowZeroStock" value as as bit if the "@ShowZeroStock" value is '1' then Having should not be validated or (i.e: All values from the table should be returned including zero)
So How to change the query based on passed bit value "@ShowZeroStock"
I can Use "If else " condition at the top and remove having in else part, but for a lengthy query i can't do the same.

A: Is this the logic you want?
Having sum(b.CBQty) <= 0 or @ShowZeroStock = 1


text:
Q: How to download an image with the button click in C#? Is there a way to download an image that was uploaded by the user? I have the following: First, the user click an image from a mosaic to view it in detail; then the image is generated in a asp:image tag, at that step they are supposed to download it with a button click. The problem I have is that the image is generated in a asp:image tag and is not the actual image itself with a name. The code I have to download only gets the image stored in a folder. Below is the code:
protected void btnDownload_Click(object sender, EventArgs e)
{
    string path = @"C:\inetpub\wwwroot\PSCSearchEngine\MemberPages\Images\live.jpg";
    System.IO.FileInfo file = new System.IO.FileInfo(path);
    if (file.Exists)
    {
        Response.Clear();
        Response.ContentType = MimeType(Path.GetExtension(path));
        Response.AddHeader("Content-Disposition",
            string.Format("attachment; filename = {0}",
            System.IO.Path.GetFileName(path)));
        Response.AddHeader("Content-Length", file.Length.ToString("F0"));
        Response.TransmitFile(path);
        Response.End();
    }
    else
    {
        Response.Write("This file does not exist.");
    }
}

Below is the code that previews the image:
@"~/MemberPages/UpdatePhoto.aspx?SiteKey=" + foo.Site_ID
    + "&TimeStamp=" + foo.timestamp[n1 - 1];

A: Code for download an image file with the button click in C#
protected void btnDownload_Click(object sender, EventArgs e)
{
    string filename=MapPath("birds.jpg");
    Response.ContentType = "image/JPEG";
    Response.AddHeader("Content-Disposition", "attachment; filename=" + filename+ "");

    Response.TransmitFile(filename);
    Response.End();
}

A: You may try this:
using (var client = new System.Net.WebClient())
{
    var _imagebytes = client.DownloadData(string.Format(@"~/MemberPages/UpdatePhoto.aspx?SiteKey={0}&TimeStamp={1}", foo.Site_ID, foo.timestamp[n1 - 1]));
    Response.Clear();
    Response.ContentType = "image/jpg";
    Response.AddHeader("Content-Disposition", string.Format("attachment; filename = {0}", "MyImage.jpg"));
    Response.AddHeader("Content-Length", _imagebytes.Length.ToString("F0"));
    Response.OutputStream.Write(_imagebytes, 0, _imagebytes.Length);
    Response.End();
}


text:
Q: change web application authentication to use Windows Authentication I'm trying to publish my web application on IIS 8.5, but I'm getting this error when the application tries to retrieve data from the SQL Server 2008.
InnerException: {Message:An error has occurred., ExceptionMessage:Login failed for user 'domainname\WES-JXC2J02$'.,…}
ExceptionMessage: "Login failed for user 'domainname\WES-JXC2J02$'."
The SQL Server doesn't have WES-JXC2J02$ listed as the authorized user because it's my dev machine name. If I try to add the machine name as user in SQL Server it gives me an error because there's no such user in the domain. I want to use Windows Authentication which is set to enable in IIS. What can I do to fix it?

A: So, apparently, as @MikeCheel said, it was forwarding my machine credentials to the SQL Server to retrieve the data from the database. Turned out, I needed to create a new login in SQL Server with limited access, then add the user id and password in the connectionString. I learnt it the hard way that SQL Server must have SQL and Windows Authentication enabled. Once that was configured, connection was setup and the data displayed properly.


text:
Q: Relative link in readme broken if readme viewed automatically by repo I have a repo as part of a organization on github. For instance:
MYORGANIZATION/MyRepository
The repo contains a README.md file.
Within this README.md file I have a link so another .md file which is located in the same repo ind the same folder as README.md:
/README.md
/anotherMarkdown.md
The README.md contains a relative link (as described here: https://help.github.com/articles/relative-links-in-readmes/) to anotherMarkdown.md:
[This is my relative link](anotherMarkdown.md)

If I open the readme with this URL, the relative link works:
https://github.com/MYORGANIZATION/MyRepository/blob/master/README.md
The links directs to:
https://github.com/MYORGANIZATION/MyRepository/blob/master/anotherMarkdown.md
If I open the Repository-URL https://github.com/MYORGANIZATION/MyRepository/ the root-directory of reposiutory is shown, as well as the readme below the file-list.
BUT the above described relative link is now broken (gives 404) and directs to:
https://github.com/MYORGANIZATION/MyRepository/anotherMarkdown.md
Is this an expected behavior? What is wrong with my link?

A: Seems to be fixed by github. Works again on my side.


text:
Q: Sqlite: how to update only empty fields Hi and thanks for your help,
I am really new to SQL, so I kindly ask your help.
I did my research, but so far I have not been able to find a solution.
I have a partiality populated column is my Sqlite database.
Some fields are empty, some contain a number.
I need to populate only the empty fields with the number 60000.
Thank for ant help

A: Try using UPDATE with WHERE columnname IS NULL
UPDATE yourtable
   SET yourcolumn = 60000
 WHERE yourcolumn IS NULL

SQLFiddle

A: Try something like this:
update t
    set col = 60000
    where col is null;

That is, you can add a where clause to the update statement to limit the rows that are affected.

A: Try this :-
Update tablename
SET number = 60000
where field IS NULL


text:
Q: Xcode Console saying Firebase is not configured I don't know why this isn't working my Firebase is configured.
Here is a Screenshot of my AppDelegate.swift file. Here is my console log:
2017-05-29 17:52:53.141 Study M8[31592] <Error> [Firebase/Core][I-COR000003] The default Firebase app has not yet been configured. Add [FIRApp configure] to your application initialization. Read more: https://firebase.google.com/docs/ios/setup#initialize_firebase_in_your_app.
2017-05-29 17:52:53.184 Study M8[31592:1051241] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'The default FIRApp instance must be configured before the default FIRAuthinstance can be initialized. One way to ensure that is to call `[FIRApp configure];` is called in `application:didFinishLaunchingWithOptions:`.'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000010a445b0b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x0000000109eaa141 objc_exception_throw + 48
    2   CoreFoundation                      0x000000010a4ae625 +[NSException raise:format:] + 197
    3   Study M8                            0x0000000108550a84 +[FIRAuth auth] + 88
    4   Study M8                            0x00000001084e7a77 _TFC8Study_M810MessagesVCcfT5coderCSo7NSCoder_GSqS0__ + 279
    5   Study M8                            0x00000001084e7bcd _TToFC8Study_M810MessagesVCcfT5coderCSo7NSCoder_GSqS0__ + 45
    6   UIKit                               0x000000010ac70f54 -[UIClassSwapper initWithCoder:] + 246
    7   UIKit                               0x000000010ae614af UINibDecoderDecodeObjectForValue + 693
    8   UIKit                               0x000000010ae6164d UINibDecoderDecodeObjectForValue + 1107
    9   UIKit                               0x000000010ae611ef -[UINibDecoder decodeObjectForKey:] + 89
    10  UIKit                               0x000000010aa07267 -[UIViewController initWithCoder:] + 1421
    11  UIKit                               0x000000010aa5cee5 -[UITabBarController initWithCoder:] + 65
    12  UIKit                               0x000000010ae614af UINibDecoderDecodeObjectForValue + 693
    13  UIKit                               0x000000010ae611ef -[UINibDecoder decodeObjectForKey:] + 89
    14  UIKit                               0x000000010ac70c20 -[UIRuntimeConnection initWithCoder:] + 178
    15  UIKit                               0x000000010ae614af UINibDecoderDecodeObjectForValue + 693
    16  UIKit                               0x000000010ae6164d UINibDecoderDecodeObjectForValue + 1107
    17  UIKit                               0x000000010ae611ef -[UINibDecoder decodeObjectForKey:] + 89
    18  UIKit                               0x000000010ac6fe1d -[UINib instantiateWithOwner:options:] + 1262
    19  UIKit                               0x000000010b02882f -[UIStoryboard instantiateViewControllerWithIdentifier:] + 181
    20  UIKit                               0x000000010a8688d1 -[UIApplication _loadMainStoryboardFileNamed:bundle:] + 108
    21  UIKit                               0x000000010a868db3 -[UIApplication _loadMainInterfaceFile] + 260
    22  UIKit                               0x000000010a867456 -[UIApplication _runWithMainScene:transitionContext:completion:] + 1407
    23  UIKit                               0x000000010a864793 -[UIApplication workspaceDidEndTransaction:] + 182
    24  FrontBoardServices                  0x000000010d3205f6 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 24
    25  FrontBoardServices                  0x000000010d32046d -[FBSSerialQueue _performNext] + 186
    26  FrontBoardServices                  0x000000010d3207f6 -[FBSSerialQueue _performNextFromRunLoopSource] + 45
    27  CoreFoundation                      0x000000010a3ebc01 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    28  CoreFoundation                      0x000000010a3d10cf __CFRunLoopDoSources0 + 527
    29  CoreFoundation                      0x000000010a3d05ff __CFRunLoopRun + 911
    30  CoreFoundation                      0x000000010a3d0016 CFRunLoopRunSpecific + 406
    31  UIKit                               0x000000010a86302f -[UIApplication _run] + 468
    32  UIKit                               0x000000010a8690d4 UIApplicationMain + 159
    33  Study M8                            0x00000001084e8997 main + 55
    34  libdyld.dylib                       0x000000010ca5665d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

If anyone has any idea what to do plz help.

A: Does GoogleService-Info.plist show up as checked for the build target in the Xcode Target Membership pane?

A: There was a problem with the plist file, after replacing it everything worked fine. Thank you to everyone who helped.

A: Did you add the .plist Firebase configuration file that you get from the Firebase website when configuring your app?

A: The solution is already shown in the error message. Please visit the read and follow the link below. Your problem will be solved.
Add firebase to your iOS project


text:
Q: Cannot open Xcode project after updating to Catalina I've downloaded an Open Source Xcode project from GitHub, but I can't open it with Xcode ver 10 or ver 11 beta after updating my Mac to Catalina. I don't have any problem making a new project though. I've already restarted my Mac few times but there's no change.
I want some advice.

A: This trick will work in my case, hope it will work for you also.

*

*simply go to your project which you want to open, just simply right click on your_project.xcworkspace and go to show Package Contents then deleted the two folder xcsharedata and xcuserdata only(don't worry it will again recreate when you open your xcworkspace again).

*Now you have to go to your_project.xcodeproj and go to show Package Contents then deleted the folder named xcuserdata only(don't worry it will again recreate when you open your xcworkspace again).
after doing above task you can open your project.

A: Unfortunatelly @eschos24 answer didn't worked for me (macOS Catalina PB4 with Xcode 11 beta). What did worked is remove my Github account from Xcode:

*

*Open Xcode's startup screen (do not open any project yet)

*Open Xcode → Preferences → Accounts → Remove the Github account you signed in

*Reboot

*Open the project via Xcode's startup screens 'Open another project…'

Maybe not every step is neccessary, but these worked for me.

A:
[UPDATE: I have now encountered this twice, so I added my second solution.] But spoiler alert...I'm pretty positive the issue stems
  from saving my Desktop and Documents folders in iCloud

The first time this happened for me, the following steps helped:
It looks like this is an issue related to the new folder permissions in Catalina. When I open System Preferences > Security & Privacy > Privacy > Files and Folders, I see that Xcode appears to have permission to see the pertinent folders. I used VS Code for something else earlier today and it also prompted to ask for access to iCloud Drive. I'm not sure why, but Xcode only shows permission for Desktop and Documents.
How I was able to fix the issue, is that I went to the 'Derived Data' folder for Xcode.
If you're unsure how to do that, here are the steps I did:

*

*Open a different project in Xcode that is saved somewhere besides
Desktop or Documents (you could also just create a new project and
save it somewhere besides your Desktop or Documents folders).

*While in Xcode, go to File > Project Settings.

*In the middle of the menu that pops up there is a path to Derived Data with a little ->. Click the ->.See picture here

*Send the Derived Data folder to trash.

After doing that, I was able to successfully open all my projects. Hopefully this works for you, but let me know if you have any different experiences or if you get stuck anywhere. Good luck!

I encountered the issue again after updating to beta 5, and doing the above steps did not work for me. I also tried removing my GitHub
account, which also didn't help. Here is how I fixed it the second
time:
I turned off iCloud Drive in my settings and actually removed everything from my computer from iCloud Drive (for me, it's the Desktop and Documents folders that sync to iCloud). After a while I turned it back on and played with the settings a bit. I then downloaded all the files in my Desktop and Documents folders (from iCloud).

[I'm not sure if this next part was actually part of the solution, but
  I'm going to just include it anyway since I only noticed it working
  after I did this...but I suspect that it just took a while for the
  files to download]

I then turned off permission for Xcode to access the Desktop and Documents folders.

*

*I opened System Preferences > Security & Privacy > Privacy

*I selected "Files and Folders" on the left side. Here you can see all the folders that different apps have access too (Desktop, Documents, Downloads, iCloud Drive).

*I unchecked every box under Xcode to try and trigger it asking for permission again.

Here is a screenshot for where "Files and Folders" lives:
It didn't ask for permission again, but I forgot about unchecking all the boxes. Then, for some incredibly strange reason...Xcode magically worked again and opened my files. I suspect it was something weird with iCloud and that I finally had downloaded the files I needed for the specific project I've been trying to work on. Later on it wouldn't let me edit the files because I didn't have permission, so I went back to System Preferences and turned on permission for Xcode to access those folders. Everything seems to be in perfect working order now!

A: I also faced the same issue. My workaround is restart MacBook.

A: Saw the same on Catalina 10.15.2. Moving my project out of /Users/<Me>/Documents up a directory level, blowing away my DerivedData and restarting XCode worked for me

A: I deleted DeriveData, iOS Device Support, restarted Xcode, restarted computer but not nothing worked. Then I did This and worked for me.

A: Do not save your project in a directory that is syncing with your iCloud account. ie don't put your project on Desktop or Documents.  The suggested way to save a project is in a Directory which you need to Create called Developer in your Home directory.  ie, /Users/yourName/Developer
When you create this directory, it will have a hammer on the folder.  This is the proper place to save Xcode projects and you should have no issues opening them if your save them there.


text:
Q: Lotus Notes Dialog box with Minimize option I have Lotus notes Dialog box.. Is there any option to give minimize option for dialog box?
@DialogBox( form ; [AUTOHORZFIT] : [AUTOVERTFIT] : [NOCANCEL] : [NONEWFIELDS] : [NOFIELDUPDATE] : [READONLY] : [SIZETOTABLE] : [NOOKCANCEL] : [OKCANCELATBOTTOM] : [NONOTE] ; title )

The syntax does not have an option for minimize.  (like a general minimize option for any other windows )

A: You have to desgin a table in the form and put your field, button and so on inside the table. over the option [SIZETOTABLE], the table is then similar to the size of the dialogbox.
I hope this answer your question.
if you like to minimize your dialogbox and work in an other domino window, this doesnt work in the domino enviroment. the dialogbox is the current window which have to be close before you can do something else in the domino enviroment.


text:
Q: Trouble with a First Order Differential Equation Using Substitution $x^2\frac{dy}{dx}-20+x^2y^2=0$, using the substitution $y=u^{-1}\frac{du}{dx}$, and $y(1)=1$
So I first started by differentiating y, $$y'=-u^{-2}\frac{du}{dx}+u^{-1}\frac{d^2u}{dx^2}$$, and I substituted this back into he equation and get
$$(-u^{-2}\frac{du}{dx}+u^{-1}\frac{d^2u}{dx^2})x^2-20+x^2u^{-2}(\frac{du}{dx})^2=0$$ and simplifyng a bit I get
$$\frac{d^2u}{dx^2}-u^{-1}\frac{du}{dx}+u^{-1}(\frac{du}{dx})^2-\frac{20u}{x^2}=0$$, and then I have trouble working with this, substituting $u=e^{mx}$ dos't work out when I do it because of the squared differential.  Any help is appreciated thanks!

A: You forgot chain rule in $y'=-u^{-2} (\frac{du}{dx})^2+u^{-1}\frac{d^2u}{dx^2}$.
That will reduce the first derivative term.


text:
Q: Change input source on OSX 10.11 Currently I have an issue of changing input source on my iMac, OSX 10.11
The option in the Keyboard setting is:
Select the previous input source  control+Space.
There is no other option available.
What I want is Command+Space. (This hotkey was bind to Spotlight search. But I have already disabled it.
The other iMac I have runs the same OSX version but does not have such issue. Anyone could help?

A: System Prefs > Keyboard > Shortcuts > Input Sources > [√] Select next source in Input menu > [double click on far right side and press Cmd ⌘ Space. It should be as simple as that. If it's still not binding, check all the other shortcuts and make sure nothing else has been bound to it. If it still does not work, it might help to use an external application to unbind the key and rebind it. I use Spark 3personally because it's free and it works for the few rebinds I need.

A: Untick "Show Keyboard, Emoji and Symbols" in System Prefs > Keyboard > Keyboard. It seems that it uses Cmd+Space in some way (in the Edit menu in the menubar you see that "Emoji & Symbols" uses Ctrl+Cmd+Space).


text:
Q: Coordinate offset between MainActivity and Custom View In my application, I draw certain graphics using the Canvas object in the MainActivity class. After that when a user swipes on the screen, I use a Custom View to draw horizontal and vertical lines over the previously created graphics.
The problem is that there is slight coordinate offset between the MainActivity and the CustomView. Due to this my lines are not in accordance with other graphic objects on the game. To confirm this, I made the following call from the MainActivity and my CustomView class:
canvas.drawLine(0, 0, 50, 50, paint);
The result was two parallel lines. The origin for the CustomView lies at the top right corner of the phone where there was a certain offset for the origin of the MainActivity class.
(Screenshot: http://i.stack.imgur.com/x3BDK.png )
I would be grateful if someone could point out on what could be the issue here.
Following are the relevant files:
activity_main.xml
<com.example.offsettest.CustomLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/customLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:paddingBottom="0dp"
android:paddingTop="0dp"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
android:layout_marginTop="0dp"
android:layout_marginBottom="0dp">
</com.example.offsettest.CustomLayout>

MainActivity.java
package com.example.offsettest;

import com.rgtech.offsettest.R;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.widget.ImageView;

public class MainActivity extends Activity {
    private Bitmap bitmap;
    private Canvas mCanvas;
    private Paint paint;
    private CustomLayout customLayout;

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

    public void draw(){
        DisplayMetrics metrics = this.getResources().getDisplayMetrics();
        float width = metrics.widthPixels;
        float height = metrics.heightPixels;
        bitmap = Bitmap.createBitmap((int) width, (int) height, Config.RGB_565);
        mCanvas = new Canvas(bitmap);
        mCanvas.drawColor(Color.GREEN);
        paint = new Paint();
        paint.setAntiAlias(true);
        customLayout = (CustomLayout) findViewById(R.id.customLayout);
        ImageView imageView = new ImageView(this);
        imageView.setImageBitmap(bitmap);
        imageView.setPadding(0, 0, 0, 0);
        customLayout.addView(imageView);
        paint.setColor(Color.BLACK);
        mCanvas.drawLine(0, 0, 50, 50, paint);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

CustomLayout.java
package com.example.offsettest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.LinearLayout;

@SuppressLint("NewApi")

    public class CustomLayout extends LinearLayout{
        private Paint paint = new Paint();
        public CustomLayout(Context context) {
            super(context);
        }
        public CustomLayout(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
        public CustomLayout(Context context, AttributeSet attrs,int defStyle) {
            super(context, attrs, defStyle);
        }
        @Override
        public void dispatchDraw(Canvas canvas) {
            super.dispatchDraw(canvas);
            paint.setColor(Color.BLACK);
            paint.setAntiAlias(true);
            paint.setDither(true);
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeJoin(Paint.Join.ROUND);
            paint.setStrokeWidth(5);
            paint.setColor(Color.RED);
            canvas.drawLine(0, 0, 50, 50, paint);
        }
    }

In addition to these files, I only set android:theme="@android:style/Theme.NoTitleBar" in the Manifest file.

A: The easiest way to solve this is to remove the padding or margin of the image view or of the root view of the layout. (If there is any)
Another possibility is to calculate the offset/distance between their left-top-corner positions using view.getX() respectively view.getRawX() (and for Y as well) and then draw your lines not at (0, 0, 50, 50) but at (offsetX, offsetY, 50 + offsetX, 50 + offsetY).
EDIT: I played around with this code a little bit and then noticed that calling imageView.setAdjustViewBounds(true); solves the problem.
Your draw method in MainActivity.java should now look like this:
public void draw() {

    DisplayMetrics metrics = this.getResources().getDisplayMetrics();
    float width = metrics.widthPixels;
    float height = metrics.heightPixels;

    bitmap = Bitmap.createBitmap((int) width, (int) height, Config.RGB_565);
    mCanvas = new Canvas(bitmap);
    mCanvas.drawColor(Color.GREEN);
    paint = new Paint();
    paint.setAntiAlias(true);

    customLayout = (CustomLayout) findViewById(R.id.customLayout);
    ImageView imageView = new ImageView(this);
    imageView.setImageBitmap(bitmap);
    imageView.setPadding(0, 0, 0, 0);
    imageView.setAdjustViewBounds(true); // call this method
    customLayout.addView(imageView);

    paint.setColor(Color.BLACK);
    mCanvas.drawLine(0, 0, 50, 50, paint);
}


text:
Q: form.action assignment - object doesn't support this property or method JSP
<form:form id="myForm" action="myAction.html" name="sws" commandName="myModel" method="POST">
    .
    .
    </form:form>

Javascript
var currentForm=document.getElementById("myForm");
currentForm.target = '_self';
currentForm.action = 'myAction2.html';
currentForm.submit();

I am getting error object doesn't support this property or method in IE 7, at line --> currentForm.action = 'myAction2.html';

A: Replacing Javascript code with the following jquery code solved the problem. I would still like to know, how and why.
$("#myForm").attr({'target': '_self' , 'action': '/MyApp/forms/MyAction2.html'}).submit();


text:
Q: Display multiple csv files in highcharts via input I am trying to build a csv-Highcharts Graph on which I can choose files and load them into the graph.
Until now, it's possible to load one csv file into the graph via input
ouput-graph.component.html:
<highcharts-chart
    id="container"
    [Highcharts]="Highcharts"
    [constructorType]="chartConstructor"
    [options]="chartOptions"
    [callbackFunction]="chartCallback"
    [(update)]=updateFromInput
    [oneToOne]="true"
    style="width: 100%; height: 400px; display: block;">
</highcharts-chart>

<button (click)="update_chart()">Update Chart</button>

    Choose File
    <input type="file" id="file" (change)="update_chart($event)">

output-graph.component.ts looks like in this snippet:
https://stackblitz.com/edit/angular-q8ubo3?file=src%2Fapp%2Foutput-graph.component.ts
I built it so that everytime i choose a file and click the "update chart" button, it replaces the graph data with the newly inserted csv file data.
Now, my Idea is to load multiple chooseable csv-files into the graph, so that I can choose a file via input and it will not replace, but add the data to the graph.
I thought of implementing a loop but got stuck on how I could manage i with the input.
The csv data looks like this:

I'm trying to display the multiple data files in a line diagram, so that i can see the difference between the newer/older data.
Does anyone have any Ideas on how I could make this work or what the best approach would be?

A: You can use an additional library to parse the CSV files into JSON - like papaparse. Next, you can add data as a default js object and add another series when needed. Check the example: https://codesandbox.io/s/angular-se6d7