text:
Q: c# run CL exe or batch cpture output LIVE to textbox? Is it possible to run any Command Line based program or batch file and capturer (re-direct) the out put to a text box LIVE
the CL takes time and it produce text!
something like tracert.exe (it takes time and produce good amount of text).
actually I will work with tracert.exe and I like to capture the output live and show it in a text-box while it is running
EDIT:
My problem is to have it LIVE
I mean any new line or char the console produce will be sent/pulled to/by the textBox
NOT until the program is done!
Simply I want to build is exactly like this http://www.codeproject.com/KB/threads/redir.aspx  (check the demo) but in C#
here is my code:
private void button1_Click(object sender, EventArgs e)
{
     Process pc = new Process();
     pc.StartInfo.FileName = "tracert.exe";
     pc.StartInfo.Arguments = "google.com";
     pc.StartInfo.UseShellExecute = false;
     pc.StartInfo.RedirectStandardOutput = true;
     pc.StartInfo.CreateNoWindow = true;
     pc.Start();

     richTextBox1.Text = pc.StandardOutput.ReadToEnd();

     pc.WaitForExit();
}

EDIT
with the your help (thanks a lot guys) and this link:
http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=EN-US&k=k%28EHINVALIDOPERATION.WINFORMS.ILLEGALCROSSTHREADCALL%29;k%28TargetFrameworkMoniker-%22.NETFRAMEWORK%2cVERSION%3dV2.0%22%29;k%28DevLang-CSHARP%29&rd=true
I solve it with this code (do you think it is OK?):
namespace GUIforCL2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        Process _cmd;

        delegate void SetTextCallback(string text);

        private void SetText(string text)
        {
            if (this.richTextBox1.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.richTextBox1.Text += text + Environment.NewLine;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ProcessStartInfo cmdStartInfo = new ProcessStartInfo("tracert.exe");
            cmdStartInfo.Arguments = "google.com";
            cmdStartInfo.CreateNoWindow = true;
            cmdStartInfo.RedirectStandardInput = true;
            cmdStartInfo.RedirectStandardOutput = true;
            cmdStartInfo.RedirectStandardError = true;
            cmdStartInfo.UseShellExecute = false;
            cmdStartInfo.WindowStyle = ProcessWindowStyle.Hidden;

            _cmd = new Process();
            _cmd.StartInfo = cmdStartInfo;

            if (_cmd.Start())
            {
                _cmd.OutputDataReceived += new DataReceivedEventHandler(_cmd_OutputDataReceived);
                _cmd.ErrorDataReceived += new DataReceivedEventHandler(_cmd_ErrorDataReceived);
                _cmd.Exited += new EventHandler(_cmd_Exited);

                _cmd.BeginOutputReadLine();
                _cmd.BeginErrorReadLine();
            }
            else
            {
                _cmd = null;
            }
        }

        void _cmd_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            UpdateConsole(e.Data);
        }

        void _cmd_ErrorDataReceived(object sender, DataReceivedEventArgs e)
        {
            UpdateConsole(e.Data, Brushes.Red);
        }

        void _cmd_Exited(object sender, EventArgs e)
        {
            _cmd.OutputDataReceived -= new DataReceivedEventHandler(_cmd_OutputDataReceived);
            _cmd.Exited -= new EventHandler(_cmd_Exited);
        }

        private void UpdateConsole(string text)
        {
            UpdateConsole(text, null);
        }
        private void UpdateConsole(string text, Brush color)
        {
            WriteLine(text, color);
        }

        private void WriteLine(string text, Brush color)
        {
            if (text != null)
            {
                SetText(text);
            }
        }
    }
}

A: When you create the Process instance for tracert, you need to set the ProcessStartInfo.UseShellExecute to false and ProcessStartInfo.RedirectStandardOutput to true. This will allow you to use  Process.StandardOutput property to read the output.
You can use Process.BeginOutputReadLine to start asynchronous reading and add an event handler to Process.OutputDataReceived.
Update: Here's an example WPF program that does what you want.
MainWindow.xaml:
<Window x:Class="Console.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded" Closed="Window_Closed">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <ScrollViewer Name="outputViewer" SizeChanged="ScrollViewer_SizeChanged" >
            <TextBlock Name="output" />
        </ScrollViewer>
        <TextBox Grid.Row="1" Name="input" KeyDown="input_KeyDown" />
    </Grid>
</Window>

MainWindow.cs:
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;

namespace Console
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            ProcessStartInfo cmdStartInfo = new ProcessStartInfo("cmd.exe");
            cmdStartInfo.CreateNoWindow = true;
            cmdStartInfo.RedirectStandardInput = true;
            cmdStartInfo.RedirectStandardOutput = true;
            cmdStartInfo.RedirectStandardError = true;
            cmdStartInfo.UseShellExecute = false;
            cmdStartInfo.WindowStyle = ProcessWindowStyle.Hidden;

            _cmd = new Process();
            _cmd.StartInfo = cmdStartInfo;

            if (_cmd.Start() == true)
            {
                _cmd.OutputDataReceived += new DataReceivedEventHandler(_cmd_OutputDataReceived);
                _cmd.ErrorDataReceived += new DataReceivedEventHandler(_cmd_ErrorDataReceived);
                _cmd.Exited += new EventHandler(_cmd_Exited);

                _cmd.BeginOutputReadLine();
                _cmd.BeginErrorReadLine();
            }
            else
            {
                _cmd = null;
            }
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            if ((_cmd != null) &&
                (_cmd.HasExited != true))
            {
                _cmd.CancelErrorRead();
                _cmd.CancelOutputRead();
                _cmd.Close();
                _cmd.WaitForExit();
            }
        }

        void _cmd_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            UpdateConsole(e.Data);
        }

        void _cmd_ErrorDataReceived(object sender, DataReceivedEventArgs e)
        {
            UpdateConsole(e.Data, Brushes.Red);
        }

        void _cmd_Exited(object sender, EventArgs e)
        {
            _cmd.OutputDataReceived -= new DataReceivedEventHandler(_cmd_OutputDataReceived);
            _cmd.Exited -= new EventHandler(_cmd_Exited);
        }

        private void ScrollViewer_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            outputViewer.ScrollToBottom();
        }

        private void input_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.Key)
            {
                case Key.Enter:
                    _cmd.StandardInput.WriteLine(input.Text);
                    input.Text = "";
                    break;
                case Key.Escape:
                    input.Text = "";
                    break;
            }
        }

        private void UpdateConsole(string text)
        {
            UpdateConsole(text, null);
        }

        private void UpdateConsole(string text, Brush color)
        {
            if (!output.Dispatcher.CheckAccess())
            {
                output.Dispatcher.Invoke(
                        new Action(
                                () =>
                                {
                                    WriteLine(text, color);
                                }
                            )
                    );
            }
            else
            {
                WriteLine(text, color);
            }
        }

        private void WriteLine(string text, Brush color)
        {
            if (text != null)
            {
                Span line = new Span();
                if (color != null)
                {
                    line.Foreground = color;
                }
                foreach (string textLine in text.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
                {
                    line.Inlines.Add(new Run(textLine));
                }
                line.Inlines.Add(new LineBreak());
                output.Inlines.Add(line);
            }
        }

        Process _cmd;
    }
}

A: Yes - create the process using Process.Start(ProcessStartInfo) having set RedirectStandardOutput (and potentially RedirectStandardError) to true and UseShellExecute to false on the ProcessStartInfo describing the process you want to start.
You can then either read directly from Process.StandardOutput and Process.StandardError (in separate threads, so that nothing blocks if the process fills its output buffer) or subscribe to the Process.OutputDataReceived event and call Process.BeginOutputReadLine (and the equivalent for standard error). MSDN has samples of all of this.
Note that in any case, you'll be receiving data on a different thread to the UI thread, so you'll want to use Control.Invoke / Control.BeginInvoke to marshal back to the UI thread before
appending the text to the TextBox.


text:
Q: How to call asp.net webservice from Jquery Mobile(Android Platform) I am a .net developer willing to learn mobile web technology. currently i am working on Android platform. I found Jquery to be suitable framework for me as i am from web background. Till now i am able to create a simple web application on android but, i am not able to make AJAX calls from Jquery to my .net webservice. I want to create a test enviornment for my android web app.
1. I have ASP.NET web service running on my local computer

    namespace JqueryMobile
    {
        [System.Web.Script.Services.ScriptService]
        public class WebService1 : System.Web.Services.WebService
        {

            [WebMethod]
            public string HelloWorld()
            {
                return "Hello World";
            }
        }
    }
my webservice URL is : http://localhost:26415/WebService1.asmx

2. My android index.html

     $(function(){
                $.ajax({url:"localhost:26415/WebService1.asmx/HelloWorld",
                success:function(result){
                           alert(result);
                           }});
     });
    This technique fails in local environment so, how do i test it?

A: make these changes:
1.uncomment [System.Web.Script.Services.ScriptService] as an attribute to your Web Method
2.Also change your url to like http://localhost:1096/MySite/WebService.asmx/HelloWorld?callback
3.try using IP address instead of loaclhost  http://IPADDRESS:1096/MySite/WebService.asmx/HelloWorld?callback
see this post:What is the best way to call a .net webservice using jquery?

redpajama_set_name: RedPajamaStackExchange


text: Q: FaceTime activation I just downloaded FaceTime. For some unknown reasons, it was activated 4 times, and I was billed 4 times for the activation SMS. Are there any ways to get money back? I don't have Apple store or official support in my country.


text:
Q: Quadratic problem with two vectors linked by one quadratic constraint I would like to find
$$\min_{w,b} w_iA_{ij}w_{j} + b_iB_{ij}b_j + 2\alpha_iw_i + 2\beta_ib_i $$
Constrained to:
$$
w_i > 0
$$
$$
\sum w_i = 1
$$
$$
b_i=w_i^2
$$
Where $A$ and $B$ are positive semidefinite and $\alpha$ and $\beta$ are arbitrary real vectors
What is the "standard form" for this problem? What is the relevant literature?
Are there software packages than readily implement a solution?
The problem would be easy enough if it wasn't for the last constraint.


text:
Q: Is there a way to determine the adjacent (previous and / or next) table rows receiving a dropped row when using jQueryUI Sortable? I'm using the jQueryUI Sortable plugin on a table and everything seems to be working fine. (The HTML validates and the JavaScript all validates, too.) As far as I can tell, there is no way to determine the location of where in the table you are "dropping" a row (other than the x/y coordinates, which are useless to me).
Is it possible to do such a thing?

A: If you are moving whole row, after sorting is done, you have the item you dragged in all $.sortable callbacks under ui.item (not only position of it). You can then look in your $table to check how you sorted rows look like now or like in an example, get the index of row straight.
$('table').sortable({
  stop: function(event, ui) {
    console.log(ui.item.index());
    console.log(ui.item.next());
    console.log(ui.item.prev());
  }
})

Bonus: working jsfiddle (original by shuklendu, i just forked and adjusted)


text:
Q: Unable to hit the IBM mobile first server V7.1 - in some of the networks in Android devices I am not able to hit my MFP adapters in some of the networks in Android devices alone. In iPhone, it is working perfectly fine.
We are getting this error:

java.net.SocketException: recvfrom failed: ECONNRESET (Connection reset by peer)

Have anyone faced this issue before?
Pasted details logs below: Masked the URL as "XXXXXXX"
02-19 20:33:30.100  24549-24549/com.Xpax D/cr_Ime? [AdapterInputConnection.java:234] updateSelectionIfRequired [0 0] [-1 -1]
02-19 20:33:30.101  24549-24549/com.Xpax D/cr_Ime? [InputMethodManagerWrapper.java:74] updateSelection: SEL [0, 0], COM [-1, -1]
02-19 20:33:30.121  24549-24549/com.Xpax D/cr_Ime? [ImeAdapter.java:571] focusedNodeChanged
02-19 20:33:30.152  24549-24584/com.Xpax D/HttpPostRequestSender? WLHybridRequestSender.run in WLHybridRequestSender.java:42 :: Sending request "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
02-19 20:33:30.257  24549-24549/com.Xpax D/cr_Ime? [ImeAdapter.java:291] hideSoftKeyboard
02-19 20:33:30.257  24549-24549/com.Xpax D/cr_Ime? [InputMethodManagerWrapper.java:56] isActive: true
02-19 20:33:30.258  24549-24549/com.Xpax D/cr_Ime? [InputMethodManagerWrapper.java:65] hideSoftInputFromWindow
02-19 20:33:30.275  24549-24549/com.Xpax D/cr_Ime? [AdapterInputConnection.java:499] finishComposingText
02-19 20:33:53.355  24549-24584/com.Xpax E/com.worklight.androidgap.plugin.WLNativeXHRPlugin? WLNativeXHRPlugin$NativeXHRPostListener.onException in WLNativeXHRPlugin.java:177 :: onException
    java.net.SocketException: recvfrom failed: ECONNRESET (Connection reset by peer)
            at libcore.io.IoBridge.maybeThrowAfterRecvfrom(IoBridge.java:592)
            at libcore.io.IoBridge.recvfrom(IoBridge.java:556)
            at java.net.PlainSocketImpl.read(PlainSocketImpl.java:485)
            at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:37)
            at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:237)
            at org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:103)
            at org.apache.http.impl.io.AbstractSessionInputBuffer.readLine(AbstractSessionInputBuffer.java:191)
            at org.apache.http.impl.conn.DefaultResponseParser.parseHead(DefaultResponseParser.java:82)
            at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:174)
            at org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:180)
            at org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:235)
            at org.apache.http.impl.conn.AbstractClientConnAdapter.receiveResponseHeader(AbstractClientConnAdapter.java:259)
            at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:279)
            at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:121)
            at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:442)
            at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:575)
            at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:498)
            at com.worklight.wlclient.WLHybridRequestSender.run(WLHybridRequestSender.java:53)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)
     Caused by: android.system.ErrnoException: recvfrom failed: ECONNRESET (Connection reset by peer)
            at libcore.io.Posix.recvfromBytes(Native Method)
            at libcore.io.Posix.recvfrom(Posix.java:161)
            at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:250)
            at libcore.io.IoBridge.recvfrom(IoBridge.java:553)
            at java.net.PlainSocketImpl.read(PlainSocketImpl.java:485)
            at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:37)
            at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:237)
            at org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:103)
            at org.apache.http.impl.io.AbstractSessionInputBuffer.readLine(AbstractSessionInputBuffer.java:191)
            at org.apache.http.impl.conn.DefaultResponseParser.parseHead(DefaultResponseParser.java:82)
            at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:174)
            at org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:180)
            at org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:235)
            at org.apache.http.impl.conn.AbstractClientConnAdapter.receiveResponseHeader(AbstractClientConnAdapter.java:259)
            at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:279)
            at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:121)
            at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:442)
            at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:575)
            at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:498)
            at com.worklight.wlclient.WLHybridRequestSender.run(WLHybridRequestSender.java:53)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)
02-19 20:33:53.373  24549-24584/com.Xpax E/NONE? [/apps/services/api/Xpax/android/init] Host is not responsive. Try to manually access the URL through the android emulator browser to verify connectivity.
02-19 20:33:53.384  24549-24584/com.Xpax D/NONE? Failed connecting to MobileFirst Server.
02-19 20:34:27.359  24549-24549/com.Xpax D/cr_Ime? [ImeAdapter.java:213] updateKeyboardVisibility: type [0], flags [0], show [true]
02-19 20:34:27.359  24549-24549/com.Xpax D/cr_Ime? [AdapterInputConnection.java:178] updateState [] [0 0] [-1 -1] [true]
02-19 20:34:31.127  24549-24549/com.Xpax I/chromium? [INFO:CONSOLE(107)] "From invokeService FAIL: [object Object]", source: file:///android_asset/www/default/js/services/invokeService.js (107)
02-19 20:34:31.129  24549-24549/com.Xpax I/chromium? [INFO:CONSOLE(357)] "Inside Failure result = {"responseHeaders":{"Content-Length":"0","Connection":"Close","Date":"Fri, 19 Feb 2016 12:34:32 GMT"},"status":408,"responseText":"","invocationContext":null}", source: file:///android_asset/www/default/js/controllers/Login/loginCtrl.js (357)

A: Verifying that a proper hostname is being used in wlclient.properties file (android\native\assets\wlclient.properties). It should not be "localhost" or a like, rather it should be the IP address of the host server.


text:
Q: ReduxToolkit - createAsyncTask Get Data after Post I'm pretty new to reduxtoolkit and I'm creating a basic app where it connects to the backend service.
I have this following codes for fetching and adding data:
export const getFruits = createAsyncThunk("food/fruits", async () => {
    try {
        const response = await axios.get('/api/food/')
        return response.data
    } catch (error: any) {
        console.log(error)
    }
})

export const addFruit = createAsyncThunk("food/fruits", async (fruit) => {
    try {
        const response = await axios.post('/api/food/', fruit)
        return response.data
    } catch (error: any) {
        console.log(error)
    }
})

I have something for this for my extraReducers
extraReducers: {
        [getFruits.fulfilled.type]: (state, { payload }) => {
            state.list = payload
            state.status = "success"
        },
        [addFruit.fulfilled.type]: (state, { payload }) => {
            state.status = "success"
        },
    }

but when I try to add the dispatch(getFruits()) inside the [addFruit.fulfilled.type]:, it doesn't work.
[addFruit.fulfilled.type]: (state, { payload }) => {
            state.status = "success"
            dispatch(getFruits)
            // or
            getFruits()
        },

What's the recommended and/or proper way to achieve it? the retrieval of

A: You don't need to make a nested usage within the slice. Call addFruit on any component and call getFruits with .then.
Example:
dispatch(addFruits(payload)).then(() => {getFruits})

A: you should create your thunk like this
export const getFruits = createAsyncThunk("food/getFruits", async () => {
    try {
        const response = await axios.get('/api/food/')
        return response.data
    } catch (error: any) {
        console.log(error)
    }
})

export const addFruit = createAsyncThunk("food/addFruit", async (fruit) => {
    try {
        const response = await axios.post('/api/food/', fruit)
        return response.data
    } catch (error: any) {
        console.log(error)
    }
})

and your reducer like this
extraReducers: {
        [getFruits.fulfilled]: (state, { payload }) => {
            state.list = payload
            state.status = "success"
        },
        [addFruit.fulfilled]: (state, { payload }) => {
            state.status = "success"
        },
    }

I hope this will fix your issue.


text:
Q: Cannot boot from Yumi multiboot USB stick I've just created a multiboot USB stick using Yumi. I tried to start my notebook (Asus K70IO) using it, but all I see is just a black screen with blinking underscore even after waiting for minutes.   If during this time I remove the USB stick I get the message: "Operating system load error".
How do I properly load my Yumi USB stick and use it? I've tried formatting it using Yumi's checkbox to format the stick in FAT32 too, but it didn't help.

Now I tried to use Sardu 2.0.5 and met same problem: black screen and blinkin underscore, if I remove stick I see "Operating system load error" and my OS starts to boot.
At the same time if I create bootable USB stick from ISO using UltraISO it boots smoothly.

A: I know its a couple years late, but here goes....
It can be a factor of factory formatting. Many USB sticks are formatted USB-FDD (Floppy disk) when what you really need is USB-HDD. Windows inherently formats USB drives as FDD for which it will not write to MBR. But with a specific command line called DISKPART you can wipe the disk and set it up as a USB-HDD with an appropriate MBR.  Here are some pretty simple steps, take caution though, one small misstep could send to "no-reboot land":

*

*Run Comand Prompt as Admin and use the following commands:

*DISKPART

*LIST DISK - find the disk number of the usb drive

*SELECT DISK # - # being your usb drive ( WARNING MAKE SURE YOU ARE SELECTING THE CORRECT DRIVE OTHERWISE THIS COULD BE DISASTROUS )

*CLEAN

*ACTIVE - Make the drive active

*FORMAT FS=FAT32 - fat16/32 are the best option for syslinux

*ASSIGN

*EXIT
This should get you ready to go unless the USB drive is truly the culprit.  This just fixed the exact SAME problem I was having with YUMI.

A: So the problem is solved. Seems that something was wrong with 2 USB sticks(Kingston DT 100 G2 and Spaceloop XL), because when I made bootable USB with third stick - it started without any problems. But still, I can't understand why these sticks weren't working.


text:
Q: React Native | JS Create Object I am using picker-module in React native. I have to create a dataset for this. It is okay to write Dataset with my hand, but when I print it with for for a list, I get the following error. What is the solution?
//working
const dataset = [
    {
        value: "1",
        label: "1",
    },
    {
        value: "2",
        label: "2",
    },
    {
        value: "3",
        label: "3",
    }
]

//not working
for (let i = 0; i < 3; i++) {
    this.setState({yearList:this.state.yearList.push({value:`${i}`,label:`${i}`})})
}

A: The React docs says:

Treat this.state as if it were immutable.

Your push will mutate the state directly and that could potentially lead to error prone code, even if you are "resetting" the state again afterwards. as an example, it could lead to that some lifecycle methods like componentDidUpdate won't trigger.
The recommended approach in later React versions is to use an updater function when modifying states to prevent race conditions:
this.setState({
  arrayvar: [...this.state.arrayvar, newelement]
})


text:
Q: SQL Server : get records where dates are in specific time fram Let's say I have the folling table
EventName    |   eventStartDate  |   eventEndDate
--------------------------------------------------
Event 1      |  11/11/2015       |   01/31/2016
Event 2      |  01/24/2016       |   01/26/2016
Event 3      |  02/23/2015       |   03/20/2016
Event 4      |  02/20/2016       |   02/26/2016

I'd like to write query that gets all the events where the event takes place within a calendar month. So for example I want to get all events that are active in January. This would leave me with Event 1, Event 2 and Event 3
Any help is appreciated

A: This can be done using a bunch of conditions like:
select *
from your_table
where
     (eventStartDate >= '20160101' and eventStartDate <= '20160131')
     or
     (eventEndDate >= '20160101' and eventEndDate <= '20160131')
     or
     (eventStartDate <= '20160101' and eventEndDate >= '20160131')

First one defines period that starts in Jan.
Second one defines perion that ends in Jan.
Third one defines period that starts before and ends after Jan (inclusively).
Obviously - there are no other periods intersecting this particular January possible.
Update:
All these conditions could be simplified to:
select *
from your_table
where eventStartDate <= '20160131' and eventEndDate >= '20160101'

This condition still defines all three periods mentioned above, but significantly shorter.

A: A different approach would be to compute a six-digit number for each month and then use the BETWEENoperator:
SELECT
     [EventName]
     , [eventStartDate]
     , [eventEndDate]
FROM [tblEvents]
WHERE 201601 BETWEEN YEAR([eventStartDate]) * 100 + MONTH([eventStartDate]) AND YEAR([eventEndDate]) * 100 + MONTH([eventEndDate])

Update: With huge data sets, however, there will be a lot of computing going on, so performance has to be kept in mind.

A: DECLARE
@CurrentMonth int =1 -- MONTH IN NUMBERS

Please this

SELECT *
    EventName
    ,eventStartDate
    ,eventEndDate
FROM EVENTs
WHERE
YEAR(eventStartDate) =YEAR(GETUTCDATE())
AND (MONTH(eventStartDate)>= @CurrentMonth AND MONTH(eventStartDate)<(@CurrentMonth+1))


text:
Q: Using Ramanujan's Method to Prove Larger Hypergeometric Functions Ramanujan had an interesting method for coming up with different hypergeometric identities. I'll provide a brief followthrough of how:

Ramanujan's Method of Morley's Identity:

Start with the product of two binomials $\displaystyle(1+u)^{y+n}\left(1+1/u\right)^x$. The coefficient of $u^n$ (denoted as $[u^n]$) is given$$\displaystyle\begin{align*}[u^n](1+u)^{y+n}\left(1+\frac 1u\right)^x & =[u^n]\sum\limits_{k=0}^{\infty}\binom xku^{-k}\sum\limits_{r=0}^{\infty}\binom{y+n}ru^r\\ & =\sum\limits_{k=0}^{\infty}\binom xk[u^{n+k}]\sum\limits_{r=0}^{\infty}\binom{y+n}ru^r\\ & =\sum\limits_{k=0}^{\infty}\binom xk\binom{y+n}{n+k}\end{align*}$$
And we also have the coefficient of $u^n$ from $(1+u)^{x+y+n}u^{-x}$$$\displaystyle\begin{align*}[u^{n+x}](1+u)^{x+y+n} & =[u^{n+x}]\sum\limits_{k=0}^{\infty}\binom{x+y+n}{k}u^k=\binom{x+y+n}{n+x}\end{align*}$$
Since they are equal, the hypergeometric identity follows soon afterward with a bit of manipulation.

Questions:

*

*Since $(1+u)^{y+n}(1+1/u)^x$ gives $_2F_1$, how would you get larger sequences, such as $_5F_4$?

*Using that, is it possible to prove$$_5F_4\left[\begin{array}{c c}\frac 12n+1,n,-x,-y,-z\\\frac 12n,x+n+1,y+n+1,z+n+1\end{array}\right]=\frac {\Gamma(x+n+1)\Gamma(y+n+1)\Gamma(z+n+1)\Gamma(x+y+z+n+1)}{\Gamma(n+1)\Gamma(x+y+n+1)\Gamma(y+z+n+1)\Gamma(x+z+n+1)}$$

I've spent some time, but I have no idea what to do. I believe that the RHS can be represented by$$\binom{x+y+z+n}r$$
For $r=$ something. However, I am neither sure what the LHS is, and what $r$ is.

A: The following is all done in the domain of the Method of Coefficients. Some of the indexing restrictions can be alleviated if needed. The results are a little tedious but simple. It's nice to have generalized techniques on hand.

LEMMA 1: For  $b>a$ and $b-a\in\mathbb{Z}$ the generating function for $\dbinom {n+ak}{m+bk}$ is
$$[t_0^n]\frac {t_0^m}{(1-t_0)^{m+1}}\left[1-\frac {t_0^{b-a}s}{(1-t_0)^b}\right]^{-1}$$
Where $s$ is the indexing variable, i.e., the $[t_0^n]$ expression is an operator transforming
$$\sum\limits_k\left(\frac {t_0^i}{(1-t_0)^j}\right)^ks^k\mapsto\sum\limits_k\binom {n+ak}{m+bk}s^k$$
PROOF:
$$\begin{align*}[t_0^n]\frac {t_0^m}{(1-t_0)^{m+1}}\left[1-\frac {t_0^{b-a}s}{(1-t_0)^b}\right]^{-1} & =[t_0^0]\frac {t_0^{m-n}}{(1-t_0)^{m+1}}\sum\limits_{k=0}^{+\infty}\left(\frac {t_0^{b-a}}{(1-t_0)^b}\right)^k s^k\end{align*}$$
For a particular $k$, we evaluate the term selected by $\left[t_{0}^{0}\right]$ (the $\operatorname{CT}(\cdot)$ type of term).
$$\begin{align*}[t_0^0]\frac {t_0^{m-n}}{(1-t_0)^{m+1}}\sum\limits_{k=0}^{+\infty}\left(\frac {t_0^{b-a}}{(1-t_0)^b}\right)^k & =[t_0^0]\frac {t_0^{m-n+(b-a)k}}{(1-t_0)^{m+bk+1}}\\ & =[t_0^0] t_0^{m-n+(b-a)k}\sum\limits_{i=0}^{+\infty}\binom {m+bk+i}{i}t_0^i\\ & =[t_0^0]\sum\limits_{i=0}^{+\infty}\binom {m+bk+i}{i}t_0^{m-n+(b-a)k+i}\end{align*}$$
Setting $m-n+(b-a)k+i=0$ gives $i=n-m-(b-a)k$, so
$$\begin{align*}\binom {m+bk+n-m-(b-a)k}{n-m-(b-a)k} & =\binom {n+ak}{n-m-(b-a)k}\\ & =\binom {n+ak}{m+bk}\end{align*}$$

LEMMA 2:
$$\sum\limits_{k=0}^{+\infty}\prod\limits_{i=0}^j \binom {n_i+a_ik}{m_i+b_ik}s^k=\left[\prod\limits_{i=0}^j\left([t_i^{n_i}]\frac {t_i^{m_i}}{(1-t_i)^{m_i+1}}\right)\right]\left[1-s\prod\limits_{i=0}^j\frac {t_i^{b_i-a_i}}{(1-t_i)^{b_i}}\right]^{-1}$$
PROOF: This is just the iterative application of LEMMA 1 since the terms are isolated.

LEMMA 3:
$$\sum\limits_{k=0}^{+\infty}\prod\limits_{i=0}^j \binom {n_i+a_ik}{m_i+b_ik}=\left[\prod\limits_{i=0}^j\left[t_i^{n_i}\right]\frac {t_i^{m_i}}{(1-t_i)^{m_i+1}}\right]\left[1-\prod\limits_{i=0}^j\frac {t_i^{b_i-a_i}}{(1-t_i)^{b_i}}\right]^{-1}$$
PROOF: This is just the dropping of $s$, or setting $s=1$ if you prefer, but that has the implication of evaluation, which is not necessary since the purpose is to generate coefficients not function values.

EXAMPLE 4: Note that
$$\begin{align*}\sum\limits_{k=0}^{+\infty}\binom xk\binom {y+n}{n+k} & =[t_0^x][t_1^{y+n}]\frac {t_0^0}{1-t_0}\frac {t_1^n}{(1-t_1)^{n+1}}\left(1-\frac {t_0^1}{1-t_0}\frac {t_1^1}{1-t_1}\right)^{-1}\\ & =[t_0^0][t_1^0]\frac {t_0^{-x}}{1-t_0}\frac {t_1^{-y}}{(1-t_1)^{n+1}}\left(1-\frac {t_0^1}{1-t_0}\frac {t_1^1}{1-t_1}\right)^{-1}\\ & =[t_0^0][t_1^0]\frac {t_0^{-x} t_1^{-y}}{(1-t_1)^n}\frac 1{1-t_0-t_1}\\ & =[t_0^0][t_1^0]\frac {t_0^{-x} t_1^{-y}}{(1-t_1)^{n+1}}\frac 1{1-t_0/(1-t_1)}\\ & =[t_0^0][t_1^0]\frac {t_0^{-x} t_1^{-y}}{(1-t_1)^{n+1}}\sum\limits_{i=0}^{+\infty}\left(\frac {t_0}{1-t_1}\right)^i\\ & =[t_0^0][t_1^0]\sum\limits_{i=0}^{+\infty}\frac {t_0^{i-x} t_1^{-y}}{(1-t_1)^{n+i+1}}\end{align*}$$
Evaluating the $t_0$ term, we have that $i=x$. Thus, we get
$$[t_1^0]\frac {t_1^{-y}}{(1-t_1)^{n+x+1}}=[t_1^0]\sum\limits_{j=0}^{+\infty}\binom {x+n+j}{j} t_1^{j-y}$$
Setting $j-y=0$ gives $j=y$.
$$\binom {x+y+n}y=\binom {x+y+n}{x+n}$$
Which is your first answer.
Remark: If wanted I can carry out the three term evaluation in the comments but it gets a little tedious.  This was a good problem for me because I have been meaning to organize this for ages.


text:
Q: Cannot save file in WebStorm 9 I have been using the same workflow for months to add a new page in my ASP .NET site, but all of a sudden I am getting problems with trying to save a .ascx file inside of WebStorm.
I created the .ascx page in VS and then saved it. I then go over to WebStorm to start developing and I cannot save any of these new files.  I get this error:
Following errors occurred on attepmt to save files:

C:\...\Management\Management.ascx___jb_bak___ (Access is denied)

I don't get what this file is and why it can't be saved... The jb makes it seem like a JetBrains file, but this file doesn't actually exist in the filesystem. All the other files I have had work just fine. Its just this new file all of a sudden.
What does this error even mean.. there is no valuable information

A: This error happened to me everytime I used Nodemon to start Webpack on a separate process. The problem was fixed by disabling "Safe write" in "Settings", as VyvIT suggested.

A: Hello to Developers using Jetbrains products!
I had this problem today and I think it was for the webstorm but I check my E: drive that I was developing on.
The problem was with my hard drive that changed to read-only.
I changed my drive to C and it solved.
Check your drive that you are using. That might be the problem.

A: You need to change your security options for user in Windows:
Right Click
The Folder > Properties > Security Tab
Click on
Edit to change Permissions > Select User


text:
Q: Laravel change language with subdomain I have a laravel project and I have to make change language system but it should be with subdomains.
For example :
http://en.site.com/portal
http://de.site.com/portal
I use this command to get language text like "trans("home.title")" also I have a middleware to change language like :
    if($lang = Session::get('lang')){
      Lang::setLocale($lang);
    }
   return $next($request);

And I want to routing for decide to language from subdomain names. How can I do that? I just can do like that
Route:get("/lang/{lang}","LanguageController@change");

How it should be for subdomains ?
Thank you if you help me .

A: You only need 1 Middleware and that's all. It's pretty simple to achieve this in Laravel.
<?php
namespace AppHttpMiddleware;

use Closure;
use IlluminateSupportFacadesApp;

class LangMiddleware
{
    public function handle($request, Closure $next)
    {
        $url_array = explode('.', parse_url($request->url(), PHP_URL_HOST));
        $subdomain = $url_array[0];

        $languages = ['en', 'de'];

        if (in_array($subdomain, $languages)) {
            App::setLocale($subdomain);
        }

        return $next($request);
    }
}

And then add the middleware to Kernel.php
Make sure that you have folders for subdomains that you need in resource/lang
I've found solution here: https://kovah.me/en/laravel-5-localization-based-on-the-subdomain/


text:
Q: Tomcat deploy to remote server with war file as url Im trying to deploy a war file to Tomcat. I want to be able to do this via a webpage that lists my war files and then flings a file I click on to the Tomcat server and deploy it.
According to the docs found here I should be able to do this...
http://localhost:8080/manager/deploy?path=/footoo&war=file:/path/to/foo

where path=/footoo is the path on my server that I want to deploy to but can file be the URL??
I cant seem to get it to work.
sidenote: I can do this manually by using the tomcat manager websevice but this point of my project is that you can access my website from anywhere and deploy without having to access the server directly.
EDIT
I dont think I have asked this question very well so I am voting to delete it

A: If  you read the documentation it says:

Upload the web application archive (WAR) file that is specified as the
  request data in this HTTP PUT request, install it into the appBase
  directory of our corresponding virtual host, and start , using the
  directory name or the war file name without the .war extension as the
  path.

So, what you need is a PUT request.
curl can do that for you:
curl --user script:script --upload-file /tmp/test.war http://localhost:8080/manager/deploy?path=/tester

This logs you in as user script with a password of script, and uploads the /tmp/test.war file. When it gets to Tomcat, it will put it in the tester.war file, and deploy it as /tester.
If you want to do this through an actual web interface, the manager app will do that as well. You can select a war to deploy from your browser.
What Tomcat will NOT do is PULL the file for you given a URL. You need to PUSH the file up to the server.

A: I don't think that feature exist. But you can build a system that uploads the war into the tomcat host and invoke the manager deploy URL


text:
Q: bash: No such file or directory when file is clearly present I have a shell script located at "/home/pi/scripts/take-snapshot.sh" but when ever I try to execute it I get a error that the file is not present.
the following commands do not work (assuming in script directory):
/home/pi/scripts/take-snapshot.sh
./take-snapshot.sh
take-snapshot.sh
bash /home/pi/scripts/take-snapshot.sh

the following do work and will bring up the shell file (not a new file):
vi take-snapshot.sh
nano take-snapshot.sh

A: The most likely cause is that your file is not executable. Bash is a bit confusing in that it reports the file as "not found", even though you only don't have permissions to execute it. Run ls -l and check the permissions. The leftmost column should show an "x" at least for the current user. It will usually look something like -rwxr-xr-x for a file you have created yourself.
Run chmod +x take-snapshot.sh to fix the permissions if they don't match.

A: I have seen this error when the line endings are windows EOL characters.  It doesn't give any other error, just the above "No file or directory".
Check the EOL character and convert it to linux EOL, if it is windows and try to run the script again.


text:
Q: rstanarm for adaptive trials I started exploring the rstanarm package and was curious as how this package could potentially be used in an adaptive trial scenario. The example scenario given within vignette provides a posterior of -0.622 with a credible interval from  -0.69 to -0.56.
What would my script look like if I wanted to use this posterior as a prior for my next model when I have additional data from the adaptive trial?
# Code from vignette
t_prior <- student_t(df = 7, location = 0, scale = 2.5)
fit1 <- stan_glm(switch ~ dist100, data = wells,
             family = binomial(link = "logit"),
              prior = t_prior, prior_intercept = t_prior,
              chains = 10, cores = 2, seed = 3245, iter = 100)

A: Your question is not so easily answered within the rstanarm framework because it only offers limited choices for the priors.
It is entirely valid to use your original prior with the total data from phase I and phase II combined to obtain a posterior distribution (essentially ignoring the intermediate posterior distribution you had after phase I). Alternatively, you could do as you suggest in phase I, then call

draws <- as.matrix(fit1)
mu <- colMeans(draws)
Sigma <- cov(mu)

and use these (estimated) mu and Sigma values as the hyperparameters in a multivariate normal prior over the coefficients in phase II. Unfortunately, such a prior is not supported by rstanarm, so you would need to write your own model with a Bernoulli likelihood, a logit link, and a multivariate normal prior in the Stan language or I think you could accomplish all that using the brm function in the brms package, which generates Stan code from R syntax and draws from the corresponding posterior distribution.
Both approaches conceptually should give you the same posterior distribution after phase II. However, with a finite number of posterior draws they will differ a little bit numerically and the multivariate normal prior might not be a complete description of the posterior distribution you obtained after phase I.


text:
Q: How to download files in /tmp folder of Google Cloud Function and then upload it in Google Cloud Storage So I need to deploy a Google Cloud Function that allow me to make 2 things.
The first one is to DOWNLOAD any files on SFTP/FTP server on /tmp local directory of the Cloud Function. Then, the second step, is to UPLOAD this file in a bucket on the Google Cloud Storage.
Actually I know how to upload but I don't get how to DOWNLOAD files from ftp server to my local /tmp directory.
So, actually I have written a GCF that receive in parameters (on the body), the configuration (config) to allow me to connect on the FTP server, the filename and the path.
For my test I used the following ftp server test: https://www.sftp.net/public-online-sftp-servers with this configuration.
{
    config:
    {
        hostname: 'test.rebex.net',
        username: 'demo',
        port: 22,
        password: 'password'
    },
    filename: 'FtpDownloader.png',
    path: '/pub/example'
}

After my DOWNLOAD, I start my UPLOAD. For that I check if I found the DOWNLOAD file in '/tmp/filename' before to UPLOAD but the file is nerver here.
See the following code:
exports.transferSFTP = (req, res) =>
{
    let body = req.body;
    if(body.config)
    {
        if(body.filename)
        {
            //DOWNLOAD
            const Client = require('ssh2-sftp-client');
            const fs = require('fs');

            const client = new Client();

            let remotePath
            if(body.path)
                remotePath = body.path + "/" + body.filename;
            else
                remotePath = "/" + body.filename;

            let dst = fs.createWriteStream('/tmp/' + body.filename);

            client.connect(body.config)
            .then(() => {
                console.log("Client is connected !");
                return client.get(remotePath, dst);
            })
            .catch(err =>
                {
                    res.status(500);
                    res.send(err.message);
                })
           .finally(() => client.end());

           //UPLOAD
            const {Storage} = require('@google-cloud/storage');

            const storage = new Storage({projectId: 'my-project-id'});

            const bucket = storage.bucket('my-bucket-name');

            const file = bucket.file(body.filename);

            fs.stat('/tmp/' + body.filename,(err, stats) =>
            {
                if(stats.isDirectory())
                {
                    fs.createReadStream('/tmp/' + body.filename)
                        .pipe(file.createWriteStream())
                        .on('error', (err) => console.error(err))
                        .on('finish', () => console.log('The file upload is completed !!!'));

                    console.log("File exist in tmp directory");
                    res.status(200).send('Successfully executed !!!')
                }
                else
                {
                    console.log("File is not on the tmp Google directory");
                    res.status(500).send('File is not loaded in tmp Google directory')
                }
            });
        }
        else res.status(500).send('Error: no filename on the body (filename)');
    }
    else res.status(500).send('Error: no configuration elements on the body (config)');
}

So, I received the following message: "File is not loaded in tmp Google directory" because after fs.stat() method, stats.isDirectory() is false. Before I use the fs.stats() method to check if the file is here, I have just writen files with the same filenames but without content.
So, I conclude that my upload work but without DONWLOAD files is really hard to copy it in the Google Cloud Storage.
Thanks for your time and I hope I will find a solution.

A: The problem is that your not waiting for the download to be completed before your code which performs the upload starts running. While you do have a catch() statement, that is not sufficient.
Think of the first part (the download) as a separate block of code. You have told Javascript to go off an do that block asynchronously.  As soon as your script has done that, it immediately goes on to do the the rest of your script. It does not wait for the 'block' to complete. As a result, your code to do the upload is running before the download has been completed.
There are two things you can do. The first would be to move all the code which does the uploading into a 'then' block following the get() call (BTW, you could simplify things by using fastGet()). e.g.
client.connect(body.config)
 .then(() => {
   console.log("Client is connected !");
   return client.fastGet(remotePath, localPath);
 })
 .then(() => {
    // do the upload
  })
  .catch(err => {
     res.status(500);
     res.send(err.message);
  })
 .finally(() => client.end());

The other alternative would be to use async/await, which will make your code look a little more 'synchronous'.  Something along the lines of (untested)
async function doTransfer(remotePath, localPath) {
  try {
    let client - new Client();
    await client.connect(config);
    await client.fastGet(remotePath, localPath);
    await client.end();
    uploadFile(localPath);
  } catch(err) {
    ....
   }
}

A: here is a github project that answers a similar issue to yours.
here they deploy a Cloud Function to download the file from the FTP and upload them directly to the bucket, skipping the step of having the temporal file.
The code works, the deployment way in this github is not updated so I'll put the deploy steps as I suggest and i verified they work:

*

*Activate Cloud Shell and run:

*Clone the repository from github: git clone https://github.com/RealKinetic/ftp-bucket.git

*Change to the directory: cd ftp-bucket

*Adapt your code as needed

*Create a GCS bucket, if you dont have one already you can create one by gsutil mb -p [PROJECT_ID] gs://[BUCKET_NAME]

*Deploy: gcloud functions deploy importFTP --stage-bucket [BUCKET_NAME] --trigger-http --runtime nodejs8
In my personal experience this is more efficient than having it in two functions unless you need to do some file editing within the same cloud function


text:
Q: Can I get content of Xml Root as string using standart xml serialization? For example there is an xml-document like
<document>
  <id>some_id</id>
  <name>some name</name>
  <content>

      ...

  </content>
</document>

There is a class Document to deserialize the document using XmlSerializer
[XmlRoot(ElementName = "document")]
public class Document
{
  [XmlElement(ElementName = "id")]
  public long Id { get; set;}

  [XmlElement(ElementName = "name")]
  public string Name { get; set;}

  [???]
  public string Content { get; set;}
}

Then I get an instance of Document using XmlSerializer.Deserilize. What can I do to get value of the Content property equals
...
 ?

A: Normally: you wouldn't - you would create types that map the entire hive; however, if this is used for ad-hoc contents, you can use XmlElement as the type, i.e.
  [XmlElement("content")]
  public XmlElement Content { get; set;}

and then access the .InnerXml, .InnerText, or .OuterXml of that


text:
Q: Can you call a method in a bean from a MuleESB ? I want to be able to do something like the following:
<spring:beans>
    <spring:bean id="myBean" class="com.address.myClass"/>
</spring:beans>

<choice>
    <when expression="myBean.myMethod() == true" evaluator="someEvaluator">
        <!-- do some stuff -->
    </when>
</choice>

I want to invoke 'some stuff' if "myBean.myMethod()" returns true.
Can this be done?
------ Update ------
David was kind enough to help me to this working solution.  Since its buried in the comments below, I added the solution here:
<when expression="muleContext.getRegistry().lookupObject('myBean').myMethod()==true" evaluator="groovy">

A: With Mule 3.3, use MEL:
<when expression="#[app.registry.myBean.myMethod()]">

With older Mules, use Groovy:
<when expression="muleContext.registry.lookupObject('myBean').myMethod()" evaluator="groovy">


text:
Q: how to get text from span faster when using python selenium chromedriver i want to get text from website and insert them into a list,and found speed of element.text is really slow,i tried get list of span or get its parent and get it then,but nothing changed.Should i get the whole html document and select by using regular expression?
pls tell me how to improve it and why.many thanks for your help.
these are two method i tried:
for i in range(0,len(client_deliver_list_html),27):
    if client_deliver_list_html[i+12].text ==0 :continue
    client_cargo = [client_deliver_list_html[i].text,
    client_deliver_list_html[i+1].text,
    client_deliver_list_html[i+3].text,
    client_deliver_list_html[i+5].text,
    int(client_deliver_list_html[i+8]).text,
    client_deliver_list_html[i+9].text,
    float(client_deliver_list_html[i+12].text),
    ]
    cargo_feature = [client_deliver_list_html[i+1],
                     client_deliver_list_html[i+3],
                     client_deliver_list_html[i+5],
                    ]
    if not cargo_feature in feature_list:feature_list.append(cargo_feature)
    client_deliver_list.append(client_cargo)

the other one:
for tr in client_deliver_list_html:
    client_cargo_atrbt = tr.find_elements_by_tag_name("span")
    if (client_cargo_atrbt[30].text == 0):continue
    client_cargo = [client_cargo_atrbt[1].text,
    client_cargo_atrbt[3].text,
    client_cargo_atrbt[4].text,
    client_cargo_atrbt[6].text,
    int(client_cargo_atrbt[10].text),
    client_cargo_atrbt[11].text,
    float(client_cargo_atrbt[14].text),
    ]
    cargo_feature = [client_cargo[1],
                     client_cargo[2],
                     client_cargo[3],
                    ]

A: You can get all the span by xpath.
Example:
for span in browser.find_elements_by_xpath("//span"):
    text = span.text

Another way to get text:
for span in browser.find_elements_by_xpath("//span"):
    text = span.get_attribute("textContent")

You can get get all the span inside of a table with:
browser.find_elements_by_xpath("//span[ancestor::table]")


text:
Q: How to change a string into an object I've  been trying to figure out how to get the String bookWanted, and customerName to bookWritten and buyer name, but i can't seem to figure out how to do it.
I've tried changing the string to a book after it was made but I can't do that.
    static List<Book> books = new ArrayList<>();
    static List<Person> people = new ArrayList<>();

    public void buyBook(Book bookWritten, Person buyerName) {
        System.out.println("Write your name: ");

        String bookWanted = scanner.nextLine();

        System.out.println("Write the book you want: ");

        String customerName = scanner.nextLine();

        for(int b = 0; b<books.size(); b++) {
            if(books.get(b).equals(bookWritten)) {
                bookWritten.setBuyer(buyerName);
            }
        }
        for(int b = 0; b<people.size(); b++) {
            if(people.get(b).equals(buyerName)) {
                buyerName.addBooksBought(bookWritten);
            }
        }
    }

A: You need to know
if(books.get(b).equals(bookWritten)) {

and
if(people.get(b).equals(buyerName)) {

They doing equals on the Book and Person object, which by default performs return (this == obj), i.e.: it returns true only they are the same object (if you haven't overridden the equals in Book or Person)
And you need to take care that you did nothing about the bookWanted and customerName the user typed.


text:
Q: jQuery tabs add more selectors to same function I managed to reduce my jquery tabs to this current state where I define tabs ID in variables.
Question: How to modify this code to have more IDs?
For example:
var tabsId = '#tabs1', '#tabs2', ... ;
var containerId = '#tabs-container1', '#tabs-container2', ...

JS:
var containerId = '#tabs-container';
var tabsId = '#tabs';

$(document).ready(function() {
    // Preload tab on page load
    if ($(tabsId + ' li.current a').length > 0) {
        loadTab($(tabsId + ' li.current a'));
    }

    $(tabsId + ' a').click(function() {
        if ($(this).parent().hasClass('current')) {
            return false;
        }

        $(tabsId + ' li.current').removeClass('current');
        $(this).parent().addClass('current');

        loadTab($(this));
        return false;
    });
});

function loadTab(tabObj) {
    if (!tabObj || !tabObj.length) {
        return;
    }
    $(containerId).addClass('loading');
    $(containerId).fadeOut('fast');

    $(containerId).load(tabObj.attr('href'), function() {
        $(containerId).removeClass('loading');
        $(containerId).fadeIn('fast');
    });
}

HTML:

Tab 1

Tab 2

Tab 3

    Loading. Please Wait...

A: You could use array's like
var tabIds = {'tab1','tab2'};

Then you can loop over the array elements. An alternative is to use the variables like you mentioned (comma separated) and split them. Then you can loop through them again.
see this thread for an example: Split string with JavaScript

A: Actually, I don't se a single place in your code where you need your tabIds. It works exactly the same if you just remove it.
Unique instances of the .click() event will be added to each a element either way, and you don't have to specify them by ID´s. Here is an example with tabIds removed.
http://jsfiddle.net/c7RHs/
var containerId = '#tabs-container';

$(document).ready(function () {
    if ($('li.current a').length > 0) {
        loadTab($('li.current a'));
    }

    $('li a').click(function () {
        if ($(this).parent().hasClass('current')) {
            return false;
        }

        $('li.current').removeClass('current');
        $(this).parent().addClass('current');

        loadTab($(this));
        return false;
    });
});

function loadTab(tabObj) {
    if (!tabObj || !tabObj.length) {
        return;
    }
    $(containerId).addClass('loading');
    $(containerId).fadeOut('fast');

    $(containerId).load(tabObj.attr('href'), function () {
        $(containerId).removeClass('loading');
        $(containerId).fadeIn('fast');
    });
}

Otherwise, you could make an array of ID´s as suggested in another answer, but I don't think you need it.
Hope it helps!


text:
Q: jQuery .click function issue I need a paragraph to fade out when the button is clicked, and I also need another paragraph to fade in at the same time. I've tried everything I can think of, even formatting differently, but nothing works. My code looks like this
$(document).ready(function() {
$('.s3').addClass('.one');
$('.button1').addClass('.party');
$('.button2').addClass('.bear');
$('.button1').click(function(){
    $('.one').fadeOut('fast');
    $('.ifparty').fadeIn('slow',1);
});
});

A: I think you meant to add a class of "one" not ".one".  Your selector is not going to pick that up the way you are adding it now.  Same with the other addClass() calls.
$(document).ready(function() {
$('.s3').addClass('one');
$('.button1').addClass('party');
$('.button2').addClass('bear');
$('.button1').click(function(){
    $('.one').fadeOut(200);
    $('.ifparty').fadeIn(2000);
});

A FIDDLE

A: http://jsfiddle.net/7Gcjp/1/
You dont need to . with class name while adding a class to element.
$('.s3').addClass('one');


text:
Q: Manually mapping an object using AlamoFireObjectMapper I'm trying to write some unit tests and need a way to make a dummy version of an object that is mappable. For example:
class MyClassJsonResponse: Mappable {

    var status: String?
    var response: String?
    var errorCode: SAErrorCode?

    init() {

    }

    required init?(_ map: Map) {

    }

    func mapping(map: Map) {
        status <- map["status"]
        response <- map["response"]
        errorCode <- (map["error_code"], SAErrorCodeTransform())
    }
}

Usually this is returned from an Alamofire call, but how would I manually create one and manually pass in an empty JSON string? Any advice on this would be greatly appreciated! Thanks!

A: The object mapper defines an init function for your classes that allows you to pass a JSON dictionary object. In your test init a JSON object from a string and use that:
let json = JSON.parse("{}")
if let _json = json.dictionaryObject {
    if let someObject = SomeObject(JSON: _json) {
        // Some assertions here
    }
    else {
        // Some assertions here about failure to map object, etc.
    }
}

In my case I'm using this in a QuickSpec and importing SwiftyJSON, but should work in regular XCTest cases.

A: You can simply use the functions written in Mappable.swift that your class implements
public init?(JSON: [String: Any], context: MapContext? = nil)
public init?(JSONString: String, context: MapContext? = nil)

Inside these functions you will find this code:
if let obj: Self = Mapper(context: context).map(JSON: JSON) {...}

So theoretically you can pass whatever data you want through these functions to test the mapping.


text:
Q: write multiple list in file as columns I have three lists
list1 = ['123','124','125']
list2 = [0.223333, 0.3434344, 0.4545454]
list3 = [ 0.53434, 0.453535, 0.534343]

list1 is list of str; list2 and list3 are float64.
I want to print them in a file like
123 0.223333 0.53434
124 0.343434 0.453535
125 0.454545 0.534343

I tried
writer = csv.writer(writeCSVfile, delimiter=',', lineterminator='\n', quotechar='"')
row_list = zip(list1, str(list2), str(list3))
for row in row_list:
    writer.writerows(row)

But I getting digits printed out in weird manner.

A: Don't make a string out of the other two lists. That turns them into an iterator over the characters in the string rather than the elements in the list.
Try this instead: row_list = zip(list1, list2, list3)
Oh, and if you're only writing one row, use writerow instead of writerows

A: Pandas is well suited for this.
import pandas as pd

list1 = ['123','124','125']
list2 = [0.223333, 0.3434344, 0.4545454]
list3 = [ 0.53434, 0.453535, 0.534343]

df = pd.DataFrame({'l1': list1, 'l2': list2, 'l3': list3})
df.to_csv('filename.csv')


text:
Q: How to iterate an array cleanly PHP Hello im having a hard time iterating my array. I don't know what to use a simple foreach or with a foreach with $key. I tried with key but im having an error of:
Illegal string offset 'payroll_employee_company_id' (View: /var/www/html/digimahouse/resources/views/member/payrollreport/loan_summary_table.blade.php)
How can i iterate it successfully?
here's my array

here's my foreach
 @foreach($totals as $key => $total)
      @if($total['payroll_employee_company_id'] == $comid->payroll_company_id)

          TOTAL

          {{$total['loan_total']}}
          {{$total['total_total_payment']}}
          {{$total['total_remaining_balance']}}

    @endif
@endforeach

here's my controller
public function loan_summary()
{
    $data["page"] = "Loan Summary";
    $data["_loan_data"] = PayrollDeductionController::get_deduction($this->shop_id());
    $data["_company"] = Payroll::company_heirarchy(Self::shop_id());//Tbl_payroll_company::where("shop_id", Self::shop_id())->where('payroll_parent_company_id', 0)->get();
    $data['totals'] = $this->get_totals_loan_summary($data);

    return view("member.payrollreport.loan_summary", $data);
}

A: You've said the picture is result for {{ dd($totals) }}. In this case, do this:
@foreach($totals['totals'] as $key => $total)
      @if($total['payroll_employee_company_id'] == $comid->payroll_company_id)

          TOTAL

          {{$total['loan_total']}}
          {{$total['total_total_payment']}}
          {{$total['total_remaining_balance']}}

    @endif
@endforeach

A: you foreach was not on the correct array
 @foreach($data['totals'] as $key => $total)
  @if($total['payroll_employee_company_id'] == $comid->payroll_company_id)

      TOTAL

      {{$total['loan_total']}}
      {{$total['total_total_payment']}}
      {{$total['total_remaining_balance']}}

@endif

@endforeach


text:
Q: How to use notificationconf? I have read THIS tutorial about creating Push nodes and posting/subscribing to notifications.
The only problem I have met is that it seems that notificationconf unable to create that node...
My first question: are nodename (parameter of notificationconf tool) and notificationName (NSString which I use from app) the same things?
Second:
notificationconf createnode push.example.com BFMyTestPushhNotification beefon
Enter password: // password from Open Directory for user beefon - it is Admin of the 10.6 server
2010-01-24 13:24:58.916 notificationconf[15221:903] created XMPP session
2010-01-24 13:24:58.931 notificationconf[15221:903] Connecting to push.example.com:5222 with user com.apple.notificationuser@push.example.com/TestPubsub, security = 2 ...
2010-01-24 13:24:59.130 notificationconf[15221:903] sessionCallback (event 1)
2010-01-24 13:24:59.130 notificationconf[15221:903] Session stopped (event 1)

What I do wrong?
And posting notification from app does nothing...
Thanks for any help!

A: Notifications are easy to use on the same node, but harder across a network. Especially, I don't think too many people are actually using it, as Google search results are scarce :)  Now, regarding your questions:
For 1: yes, you need to have matching nodename and notificationName. The man page says so (although not crystal-clear):
 createnode hostname nodename username
         Creates a node on the server to send notifications using.  Before
         a client can subscribe to notifications with a given name, the
         server must be configured with a node with a matching name.

So, first you have to create the node, then you can listen to notifications of a given name. Otherwise, you don't get the notifications.
For 2: I get this error when there is no XMMP daemon running (i.e. port 5222 is closed). Is that port open for you? (check the output of nmap -p 5222 push.example.com).

A: I've been trying to use Snow Leopard Server's Push Notification service with a custom application based on XMPP Publish–Subscribe. I struggled to create a node but finally figured it out.

*

*Track down the password for the service account com.apple.notificationuser. You can find it, for example, in /private/etc/dovecot/notify/notify.plist.

*Connect to your push notification server with JID com.apple.notificationuser@your-chat-server-hostname.com and that password.

*Create nodes the normal way. In XMPPFramework it's like this:
XMPPJID *serviceJID =
[XMPPJID jidWithString:@"pubsub.your-chat-server-hostname.com"];
XMPPPubSub *xmppPubSub = [[XMPPPubSub alloc] initWithServiceJID:serviceJID];
[xmppPubSub createNode:@"pubsub.your-chat-server-hostname.com`
           withOptions:nil];

*The server creates the node. It responds with an iq, but not the one the spec requires. It does send a compliant error if the node already exists.
<iq xmlns="jabber:client"
to="com.apple.notificationuser@your-chat-server-hostname.com/..."
from="pubsub.your-chat-server-hostname.com"
id="...:create_node" type="result"/>

*Connect using that same user to publish your updates.
I was never able to get notificationconf to work.


text:
Q: If $\sigma(T)= \emptyset$, there exists $z_0 \in \mathbb{C}$ such that $\|(z_0-T)^{-1} \|> \epsilon$ Let $X$ be a Banach space and $T:D(T)\subseteq X \to X$ be a closed operator such that $\sigma(T)= \emptyset$. Let $\epsilon>0$.  I need to show that there exists $z_0 \in \mathbb{C}$ such that $\|(z_0-T)^{-1} \|> \epsilon$.
My attempt:
I suppose that $ \|(z-T)^{-1} \| \leq \epsilon$ for all $ z \in \mathbb{C}$. So the function $z \to (z-T)^{-1} $ is a bounded entire function and by Liouville theorem there exists a bounded operator $A:X \to X$ such that $(z-T)^{-1}=A$ for $ z \in \mathbb{C}$. In particular, $ 1-T=A^{-1}=0-T$ (contradiction).
Is my attempt correct?


text:
Q: Why are duplicate entries generated for the same label using Dashboard Reports in JMeter? For all the labels, multiple entries are captured suffixed as 0 and 1 in the CSV file. Can you please tell me why this is happening?

A: Open your test plan in JMeter
Open Help > Export Transactions for Report

Then copy result in user.properties, in my case I would have:

jmeter.reportgenerator.exporter.html.series_filter=^(Home Page|Page Returning 404)(-success|-failure)?$

Then run test or report and you'll only have the parent transaction.
To master all details of report generation in JMeter, read this blog by one of JMeter developers.


text:
Q: toFront() method does'nt work with a splash screen use in java fx I want to create a simple poke where I have a splash screen (like an adobe one) that leads to a multi screen application.
To do so here's my main class ScreensFramework :
public class ScreensFramework extends Application {

public static String screen1ID = "main";
public static String screen1File = "Screen1.fxml";
public static String screen2ID = "screen2";
public static String screen2File = "Screen2.fxml";
public static String screen3ID = "screen3";
public static String screen3File = "Screen3.fxml";

private Pane splashLayout;
private Stage mainStage;

@Override
public void init() {
    ImageView splash = new ImageView(new Image("http://www.versluis.com/wp-content/uploads/2013/08/CCsplash-610x520.png"));
    splashLayout = new VBox();
    splashLayout.getChildren().addAll(splash);
    splashLayout.setEffect(new DropShadow());
}

@Override
public void start(Stage primaryStage) {
    showSplash(primaryStage);

    Timeline timeline = new Timeline(new KeyFrame(
            Duration.millis(2500),
            ae -> showMainStage(primaryStage)));
    timeline.play();
}

private void showMainStage(Stage initStage) {
    initStage.hide();
    mainStage = new Stage(StageStyle.DECORATED);
    mainStage.setTitle("My Test");
    mainStage.setIconified(true);

    ScreensController mainContainer = new ScreensController();

    mainContainer.loadScreen(ScreensFramework.screen1ID, ScreensFramework.screen1File);
    mainContainer.loadScreen(ScreensFramework.screen2ID, ScreensFramework.screen2File);
    mainContainer.loadScreen(ScreensFramework.screen3ID, ScreensFramework.screen3File);

    mainContainer.setScreen(ScreensFramework.screen1ID);

    Group root = new Group();
    root.getChildren().addAll(mainContainer);
    Scene scene = new Scene(root);
    mainStage.setScene(scene);
    mainStage.show();
    mainStage.toFront();

}

private void showSplash(Stage initStage) {
    Scene splashScene = new Scene(splashLayout);
    initStage.initStyle(StageStyle.UNDECORATED);
    initStage.initStyle(StageStyle.TRANSPARENT);
    splashScene.setFill(Color.TRANSPARENT);
    initStage.setScene(splashScene);
    initStage.show();
}

/**
 * The main() method is ignored in correctly deployed JavaFX application.
 * main() serves only as fallback in case the application can not be
 * launched through deployment artifacts, e.g., in IDEs with limited FX
 * support. NetBeans ignores main().
 *
 * @param args the command line arguments
 */
public static void main(String[] args) {
    launch(args);
}

}
Things are working pretty fine, except for one thing :
mainStage.toFront();

When this is called, my icon flash in orange but the window does not come in front. So basically I have my splash screen and then nothing if I don't click my self on the windows icon.
Where does it come from ?


text:
Q: Stateflow value not getting being observed in data binding I have a stateflow that is giving me the value of a mutable state flow from ViewModel, what I am trying to do is, I want to show hide a webview based on a button click. When the value is true I want to show the web view and when I want to hide it I change its value to false. The values are being updated correctly but not reflecting inside data binding.
this is my viewmodel
class ArticleDetailsViewModel : ViewModel() {
    private val _isWebViewShowing = MutableStateFlow(false)
    val isWebViewShowing: StateFlow<Boolean>
        get() = _isWebViewShowing

    fun onReadMoreClicked() {

        _isWebViewShowing.value = true
    }

    fun changeWebViewState() {
        _isWebViewShowing.value = false
    }}

This my XML where I am doing the comparison
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>
        <variable
            name="article"
            type="io.infinity.newsapp.model.domain.ArticleDomainModel" />
        <variable
            name="viewModel"
            type="io.infinity.newsapp.viewmodels.ArticleDetailsViewModel" />
        <import type="android.view.View"/>
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <include
            android:id="@+id/toolbar"
            layout="@layout/toolbar_generic"
            />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:visibility="@{viewModel.isWebViewShowing().value ?  View.INVISIBLE :View.VISIBLE  }"
            android:orientation="vertical"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="@+id/toolbar"
            app:layout_constraintStart_toStartOf="@+id/toolbar"
            app:layout_constraintTop_toBottomOf="@+id/toolbar">

            <com.google.android.material.card.MaterialCardView
                android:layout_width="match_parent"
                app:cardCornerRadius="@dimen/_20sdp"
                android:layout_margin="@dimen/_16sdp"
                android:layout_height="250dp">
                <ImageView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    loadImageFromUrl="@{article.urlToImage}"
                    android:scaleType="centerCrop"/>
            </com.google.android.material.card.MaterialCardView>
            <TextView
                android:id="@+id/textView"
                style="@style/eighteen_sp_muli_bold"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/_8sdp"
                android:text="@{article.title}"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_margin="@dimen/_16sdp"
                android:orientation="horizontal"
                android:layout_height="wrap_content">
                <TextView
                    android:id="@+id/tvAuthor"
                    style="@style/twelve_sp_muli_extra_bold"
                    android:layout_width="match_parent"
                    android:layout_weight="1"
                    android:layout_height="wrap_content"
                    android:gravity="start"
                    android:layout_marginStart="8dp"
                    android:text="@{article.author}"
                    android:textAllCaps="true"
                    android:textColor="@color/semi_black"
                    />
                <ImageView
                    android:id="@+id/imageView2"
                    android:layout_width="20dp"
                    android:layout_height="20dp"
                    android:layout_marginStart="@dimen/_4sdp"
                    android:layout_marginEnd="@dimen/_2sdp"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintStart_toStartOf="@+id/tvTitle"
                    app:srcCompat="@drawable/circle_blue" />

                <TextView
                    android:id="@+id/tvSource"
                    style="@style/twelve_sp_muli_extra_bold"
                    android:layout_width="100dp"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="8dp"
                    android:text="@{article.source.name}"
                    android:textAllCaps="true"
                    android:textColor="@color/semi_black"
                    app:layout_constraintBottom_toBottomOf="@+id/imageView2"
                    app:layout_constraintStart_toEndOf="@+id/imageView2"
                    app:layout_constraintTop_toTopOf="@+id/imageView2" />
                <TextView
                    android:id="@+id/publishedOn"
                    android:gravity="end"
                    style="@style/twelve_sp_muli_extra_bold"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:layout_marginStart="8dp"
                    setDateAndTime="@{article.publishedAt}"
                    android:textAllCaps="true"
                    android:textColor="@color/semi_black"
                    />

            </LinearLayout>
            <TextView
                android:layout_width="match_parent"
                style="@style/fourteen_sp_muli_bold"
                android:text="@{article.description}"
                android:layout_marginStart="@dimen/_16sdp"
                android:layout_marginEnd="@dimen/_16sdp"
                android:layout_marginTop="@dimen/_16sdp"
                android:layout_marginBottom="0dp"
                android:layout_height="wrap_content"/>
            <TextView
                android:id="@+id/tvReadMore"
                android:onClick="@{() -> viewModel.onReadMoreClicked()}"
                android:layout_width="match_parent"
                style="@style/twelve_sp_muli_regular"
                android:text="@string/read_more"
                android:textColor="@color/light_blue"
                android:layout_marginStart="@dimen/_16sdp"
                android:layout_height="wrap_content"/>

        </LinearLayout>

        <WebView
            android:id="@+id/webView"
            loadArticleInWeb="@{article.url}"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="@{viewModel.isWebViewShowing().value ? View.VISIBLE :View.INVISIBLE}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>


text:
Q: libimobile is not working with iOS 10.0 beta version I am using libimobiledevice in my iOS project. I upgrade my iphone 6sPlus to iOS 10.0 beta version. i fired ideviceinfo command from my mac and get the response : Could not connect to lockdownd, error code -5
Any one know about this error??
when i am trying to install my ipa through ideviceinstaller, there I am having the following error: Could not connect to lockdownd. Exiting.
please let me know if someone know's the solution!

A: I had many problems with ideviceinstaller too, so at least I have started to use cfgutil.
It's a CLI tool of Apple Configurator 2, always up-to-date and reliable, works well with iOS beta versions.
Just download the free app from the App Store: https://itunes.apple.com/hu/app/apple-configurator-2/id1037126344
Start the app then select "Apple Configurator 2 > Install Automation Tools" from the upper left menu.
To install/uninstall apps:
cfgutil --ecid $ECID remove-app $BUNDLE_ID_OF_INSTALLED_APP;
cfgutil --ecid $ECID install-app $PATH_TO_IPA_OR_APP_FOLDER;

To get ECID, connect an iOS device and run the following command:
cfgutil list

OR
This has helped my colleague.
Disconnect all iOS devices, then:
brew uninstall ideviceinstaller -g
brew uninstall libimobiledevice -g
brew install --HEAD libimobiledevice -g
brew install ideviceinstaller -g

Connect an iOS device, and choose "Trust" when prompted, after that:
sudo rm -rf /var/db/lockdown/*

Then add more privileges to iTunes cache folder:
sudo chmod -R 777 /var/db/lockdown/

A: Just FYI: updates to macOS, iTunes, and probably other Apple software will (correctly) reset the permissions on /var/db/lockdown.
The best solution here is to get the latest libimobiledevice, which has a fix for this particular issue:
brew uninstall libimobiledevice
brew install --HEAD libimobiledevice
brew link --overwrite libimobiledevice


text:
Q: Convert set to a hashable type I have some variables that are related two by two, and I wish to stock them as attributes of Siblings() objects.
So, I create a class :
def Siblings(object):
    def __init__(self, brother, sister):
        self._brother = brother
        self._sister = sister

    def __eq__(self, other):
        if isinstance(other, Siblings):
            return {self._brother, self._sister} == {other._brother, other._sister}

    def __hash__(self):
        return hash((self._brother, self._sister)

The reason why I am using sets in eq is that I do not know (and do not care) which variable will be considered as brother and which as sister.
In fact,
s1 = Siblings(1,2)
s2 = Siblings(2,1)
print(s1 == s2)

prints True, which is what I need.
The problem is that my Siblings() objects need to be used as dictionary keys, so that s1 and s2 mentioned above correspond to the same key.
However :
a = {s1: 5}
a[s2] = 4

does not modify the value 5, as I want, but instead it adds a new key-value pair. This is understandable by the way my hash is defined.
I tried replacing the vector by a set in hash , but I get a TypeError : unhashable type : 'set'.
Any suggestions on how to solve this?

A: Python has a hashable set called frozenset built-in. It is immutable, so if you do need to change it you have to create a new object (just like with tuples).
a = frozenset([1, 2])
b = frozenset([2, 1])
a == b
# True

d = {a: "a"}
# {frozenset({1, 2}): 'a'}
d[b] = "b"
# {frozenset({1, 2}): 'b'}

a.add(3)
# AttributeError: 'frozenset' object has no attribute 'add'

a = a | {3}
# frozenset({1, 2, 3})

A: Hash with a frozenset instead of a tuple:
def __hash__(self):
    return hash(frozenset([self._brother, self._sister]))

Unrelated to the question, but recommended - you should avoid returning None in the __eq__:
def __eq__(self, other):
    if isinstance(other, Siblings):
        return {self._brother, self._sister} == {other._brother, other._sister}
    return NotImplemented

Note that the hash must not change within an object's timeline. As long as you don't write to the _brother and _sister attributes after init, you should be safe.

A: As other answers have already pointed out, using frozenset is a valid approach, another also useful choice for these type of cases is considering using namedtuples, example below:
from collections import namedtuple

BaseSiblings = namedtuple('Siblings', 'brother sister')

class Siblings(BaseSiblings):

    def __hash__(self):
        return super().__hash__()

    def __eq__(self, other):
        if isinstance(other, Siblings):
            return {self.brother, self.sister} == {other.brother, other.sister}

        return NotImplemented

obj1 = Siblings('a', 'b')
print(obj1)
obj2 = Siblings('b', 'a')
print(obj2 == obj1)
print({obj1: '1'} == {obj2: '1'})


text:
Q: Can not resolve "May expose internal representation by returning reference to mutable object" SonarQube keeps reporting an issue for rule "may expose internal representation by returning reference to mutable object".
I fixed it based on a guide of the Carnegie Mellon University, but SonarQube still raises this issue:
public Date getDatime(){
    return (Date)this.datime.clone();//IJTI-316
    // .getDatime() may expose internal representation by returning *.datime
}

How can I resolve / avoid this issue?

A: The clone operation does a shallow copy, meaning that most of the Date's instance variables are shared between both instances. To fully solve the error you need to make an entirely new object in the regular sense.
Maybe:
return new Date(this.datime.getTime());


text:
Q: Can anyone help someone brand new to AMPL? Brand new to AMPL and don't understand the error at all. I've tried removing the variable definitions and get the error (no variables identified) so anyway here is the error message:
syntax error
context:  subject to  >>> 90  <<< * x1 + 120 * x2 + 106 * x3 + 97 * x4 + 130 * x5 + 180 * x6 >= 300;

here is my code
reset;

var x1 >=0;
var x2 >=1;
var x3 >=0;
var x4 >=0;
var x5 >=.5;
var x6 >=0;

minimize cost: 2 * x1 + 3.5 * x2 + 8 * x3 + 1.5 * x4 + 11 * x5 + x6;

subject to 90 * x1 + 120 * x2 + 106 * x3 + 97 * x4 + 130 * x5 + 180 * x6 >= 300;

subject to 4 * x1 + 8 * x2 + 7 * x3 + 1.3 * x4 + 8 * x5 + 9.2 * x6 >= 10;

subject to 15 * x1 + 11.7 * x2 + .4 * x3 + 22.6 * x4 + 17 * x6 >= 10;

subject to x1 + 5 * x2 + 9 * x3 + 0.1 * x4 + 7 * x5 + 7 * x6 >= 8;

A: You are experiencing a syntax error because you are not using a valid syntax to declare your constraints. More specifically, your constraints are missing a name and a colon. So, instead of
subject to 90 * x1 + 120 * x2 + 106 * x3 + 97 * x4 + 130 * x5 + 180 * x6 >= 300;

you should write
subject to c1: 90 * x1 + 120 * x2 + 106 * x3 + 97 * x4 + 130 * x5 + 180 * x6 >= 300;

where c1 is whatever name you want to give to that constraint --- just don't use the same name twice.
You can find more info about AMPL's syntax here.


text:
Q: Sort members case insensitively in sphinx-autodoc From the sphinx.ext.autodoc documentation, the autodoc_member_order can be alphabetical, groupwise, or bysource.  Is it possible to sort alphabetically case-insensitively?  I would like to sort "Ratio" before "RGB".

A: To the best of my knowledge, there is no built-in option for this in Sphinx unfortunately.
The results of object inspection are sorted in this function:
def safe_getmembers(object, predicate=None, attr_getter=safe_getattr):
    # type: (Any, Callable[[unicode], bool], Callable) -> List[Tuple[unicode, Any]]
    """A version of inspect.getmembers() that uses safe_getattr()."""
    results = []  # type: List[Tuple[unicode, Any]]
    for key in dir(object):
        try:
            value = attr_getter(object, key, None)
        except AttributeError:
            continue
        if not predicate or predicate(value):
            results.append((key, value))
    results.sort()
    return results

You could try overriding the function by doing this:
from sphinx.util import inspect

def custom_safe_getmembers(object, predicate=None, attr_getter=safe_getattr):
    # type: (Any, Callable[[unicode], bool], Callable) -> List[Tuple[unicode, Any]]
    """A version of inspect.getmembers() that uses safe_getattr()."""
    results = []  # type: List[Tuple[unicode, Any]]
    for key in dir(object):
        try:
            value = attr_getter(object, key, None)
        except AttributeError:
            continue
        if not predicate or predicate(value):
            results.append((key, value))
    results.sort(lambda (k, v): (k.lower(), v))
    return results

inspect.safe_getmembers = custom_safe_getmembers

I haven't had an opportunity to try this yet, so be cautious!


text:
Q: Protect "Private" Objects in My R Package Motivation
I am developing an R package (call it pkg) which collects in a running cache some objects generated by its function calls.  It is simple enough to implement the cache as a list object (call it .cache) in the pkg namespace. However, I want to prevent the user from interfering directly with the cache, which can always be exposed via the ::: syntax: pkg:::.cache.
That is, I want to protect .cache analogously to private fields in object-oriented programming. All operations on .cache should be done by internal helper functions, which are called exclusively by @exported functions with an "API flavor".
The Problem
As such, I had the idea of defining an environment object (call it .vault) in the namespace, so I can...put my .cache in my .vault.

My quandary is that an environment like .vault is one of the few things in R that work by reference. So I fear pkg:::.vault will expose .vault or its contents to modification as well as to viewing. I can alter my accessor functions like pkg:::.get_cache() so they don't enable such exposure, but all such efforts are in vain if .vault can be directly modified in place.
 DO NOT RUN
By way of example, consider this dangerous (?) code below. First I examine the internal .S3MethodsClasses environment from dplyr, to "identify a target":
dplyr:::.S3MethodsClasses
#> <environment: 0x7fab9c6c5310>

ls(dplyr:::.S3MethodsClasses)
#> [1] "grouped_df" "rowwise_df"

Then I examine the rowwise_df object and deem it a worthy "target":
dplyr:::.S3MethodsClasses$rowwise_df
#> Virtual Class "rowwise_df" [package "dplyr"]
#>
#> Slots:
#>
#> Name:                .Data               names           row.names
#> Class:                list           character data.frameRowLabels
#>
#> Name:             .S3Class
#> Class:           character
#>
#> Extends:
#> Class "tbl_df", directly
#> Class "tbl", by class "tbl_df", distance 2
#  ...

Finally, I exploit the fact that unlike most objects from the dplyr namespace...
library(dplyr)

mutate <- NULL

dplyr::mutate
#> function (.data, ...)
#> {
#>     UseMethod("mutate")
#> }
#> <bytecode: 0x7fab9c2f6120>
#> <environment: namespace:dplyr>

...an environment like .S3MethodsClasses points by reference, and so its contents can be easily modified in place:
# "Copy" the pointer to allow `<-` assignment.
same_pointer <- dplyr:::.S3MethodsClasses

same_pointer
#> <environment: 0x7fab9c6c5310>

# Modify in place.
same_pointer$rowwise_df <- NULL

dplyr:::.S3MethodsClasses$rowwise_df
#> NULL

And just like that, the "vault" is robbed!
Suspicions
I suspect the answer might lie here, with lockEnvironment() and friends, but the application is a bit beyond me.  Perhaps I could do something .onLoad to set up the .vault environment, which would then be lock*()ed — both the .vault itself and the bindings within it — but not before making an active binding between .cache and an accessor function .get_cache(), which would populate within the pkg namespace.
Note
I am already developing a feature to terminate (helper) functions like .get_cache() when they are called outside a fellow function from the pkg namespace. Thus, the exposure of pkg:::.get_cache() will not let the user operate .get_cache() either manually or in a custom function of their own.
Canonicity
I would especially appreciate the advice of R developers experienced enough to provide a canonical answer (if any).


text:
Q: El constructor de File de Javascript no recibe los parámetros correctamente He estado intentando probar diversas implementaciones para construir un fichero a partir de un base64 y básicamente siempre indican la función:
function base64ToFile(sB64DataURI, sFileName) {
        var bytes = sB64DataURI.split(',')[0].indexOf('base64') >= 0 ?
            atob(sB64DataURI.split(',')[1]) :
            window.unescape(sB64DataURI.split(',')[1]),
            mime = sB64DataURI.split(',')[0].split(':')[1].split(';')[0],
            max = bytes.length,
            ia = new Uint8Array(max);

        for (var i = 0; i < max; i++) {
            ia[i] = bytes.charCodeAt(i);
        }
        return new File([ia], sFileName, {
            type: mime
        });
    }

Cuando observo el objeto que devuelve la función veo que no lo ha construido bien, porque el constructor tiene confundidos los argumentos y no se asignan correctamente. El resultado de la ejecución es esta:

Nunca he trabajado con esto, y probablemente se me esté pasando hacer algo previamente. ¿Alguien sabría que puede estar pasando? Creo que aportado toda la información, en cualquier caso, si alguien necesita más, me comenta.
¡Muchas gracias de antemano! Saludos.
P.S.: El base64 es una imagen que necesito convertirla a objeto File.
EDIT: Un console.log del resultado de la función es este:

A: Contesto yo mismo a mi pregunta dado que encontré el porqué.
Resulta que estoy utilizando Cordova y hay un plug-in (cordova-plugin-file) que reescribe totalmente el objeto nativo File, por lo que sustituye el código nativo por el suyo propio.
Mi decisión ha sido desactivar el plug-in para que no entre en conflicto con este.
Saludos.


text:
Q: reset html  tag to original color I'm trying to reset an HTML  tag to it's original color using an onclick and then calling two javascript functions.
The first function will (hopefully) set the previously changed color.
The second function changes the selected  to a cyan background color.  (This works).  As a final step of this function I set a var hold which should the  id.
That var, (hold), should be used in the first function during the next change to revert to the original color.
I call the functions like so:
If I've confused you, the program is a calendar and the selected date bgcolor turns cyan.  When another date is selected I want to change the first one back to white.

A: You don't need two functions to revert the cell background color. The best thing to do is to use css & js together to change the appearance of a cell based on UI interaction. See the example jsfiddle I have created here: http://jsfiddle.net/rYcMT/
--Javascscript --
    var cells = document.getElementsByTagName("td");
    for (var i = 0; i < cells.length; i++) {
      cells[i].addEventListener('click', onClick, false);
    }

    function onClick(event){
        var el = event.target;
        var id = el.getAttribute("id");

        el.className = 'selected';

        var others = document.getElementsByTagName("td");
        var oLength = others.length;

        for(var i=0; i < oLength; i++){
         if(others[i].getAttribute("id") !== id){
             others[i].className = '';
         }
     }
};

where your css looks like the following:
-- CSS --
    .calendar, tr, td {
        border: 1px solid #CCC;
    }
    .calendar td{
        background-color: white;
    }
.calendar td.selected{
    background-color: cyan;
}

-- hTML --

        May 1
        May 2
        May 3
        May 4

        May 5
        May 6
        May 7
        May 8

A: It seems like you want only one element at a time to have the color.
If so, just give the one that should be highlighted an ID that has styles set to it. Then whenever one is clicked, remove the ID from the first, and put it on the new one.
You can easily accomplish this with a "live nodeList".
var tds = my_table.getElementsByTagName("td");

You'll always be able to get the one with the ID as a property of the list. So if your ID is "active", you'd do:
tds.active; // gives the current TD with the "active" id

DEMO: http://jsbin.com/ohadej/1
So assuming you have inline handlers, like this:

And CSS like this:
#my_table td {
    color: black;
    background-color: white;
}
td#active {
    color: black;
    background-color: cyan;
}

Your code could look like this:
var tds = my_table.getElementsByTagName("td");

function changecolor(el) {
    var current = tds.active;
    if (current)
        current.id = "";

    // (tds.active || {}).id = "active"; // shorter version of the 3 lines above

    el.id = "active";
}


text:
Q: HTML 5 video: iPad video is black I know, there are several answers addressing this problem, but none has worked for what I am doing. I am trying to place a video. It works fine on all my desktop browsers, but the one I really need to work it on--my iPad-- is a no go. It used to display a striked-through play button, but I managed to make that go away and now all I see on the screen is a black box. When this happened, I hoped it was a step in the right direction, but now I am not sure.
My mark-up is:
<video height="250" controls>
<source src="closeI.m4v"  type="video/m4v" />
<source src="graphics/close.mp4" type="video/mp4">
<source src="graphics/graphics/close.oggtheora.ogv" type="video/ogg">
</video>

Video is an unfamiliar realm for me, but I am doing my best. Thank you.


text:
Q: Is there any way to extract a list of users and their email ids from wattpad? I've read the API documentation and there seem to be no way to get user email.

A: if you can see a page witch contains your needed data with your eyes. you can use web scraping to gather them.


text:
Q: Issue installing realm with firebase I am trying to install Firebase for push notification and realm for database. It was working fine until i added Firebase pod to my project.
Build Failed with below error

Undefined symbols for architecture x86_64: "__T09Alamofire11URLEncodingVAA17ParameterEncodingAAWP", referenced from: __T09App0A3ApiO4task4Moya4TaskOfg in App.o "__T09Alamofire12JSONEncodingVN", referenced from: __T09App0A3ApiO4task4Moya4TaskOfg in App.o "__T09Alamofire11URLEncodingVN", referenced from: __T09App0A3ApiO4task4Moya4TaskOfg in App.o "__T09Alamofire12JSONEncodingVAA17ParameterEncodingAAWP", referenced from: __T09App0A3ApiO4task4Moya4TaskOfg in App.o "__T09Alamofire11URLEncodingV7defaultACfgZ", referenced from: __T09App0A3ApiO4task4Moya4TaskOfg in App.o "__T09Alamofire12JSONEncodingV7defaultACfgZ", referenced from: __T09App0A3ApiO4task4Moya4TaskOfg in App.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)

Podfile
platform :ios, '9.0'

target 'App' do
use_frameworks!
pod 'Firebase/Core'
pod 'Firebase/Messaging'
pod 'RealmSwift'
pod 'Moya'

post_install do |installer|
  installer.pods_project.targets.each do |target|
      target.build_configurations.each do |config|
          config.build_settings['SWIFT_VERSION'] = '4.0'
      end
  end
end

A: It got resolved. Need to import Alamofire  wherever you are using the ParameterEncoding.

A: Replace your pod file from this code
# Uncomment the next line to define a global platform for your project
platform :ios, '9.0'

target 'Demo' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

pod 'Firebase/Core'
pod 'Firebase/Messaging'
pod 'RealmSwift'

end


text:
Q: Group Header position for Collectionview stays on the left Currently setting the Header or Group header of a horizontal collectionview places the header on the left of the collection, which doesnt look good. I need the header to be displayed above the horizontal collection, but the default behavior is to be displayed on top of the collection only if the collectionview is in vertical orientation. Is there a way to implement it for horizontal collection.

A: You want to have a greater control over the position of the group headers for CollectionView like displaying group headers above (or below) the group items for horizontal orientation.
This is a feature request that is tracked in this headers option for CollectionView with greater control over group header position. You can follow up there.


text:
Q: EC2 Linux mapping between file system and EBS volumes Where are "observable" paths like /home/ubuntu/foo.txt stored on a Linux EC2 instance with mounted EBS?
I have a basic EC2 instance with added EBS storage, mounted as /mnt/my-data following one of the AWS tutorials. Is everything that I don't put at /mnt/my-data/... stored on the small 8GB block that comes with the EC2 instance itself?
The reason I ask is that I installed quite a few Python libraries that take up some space (numpy, etc.) as well as mongodb. The installations themselves shouldn't be a problem, and everything is working. But once mongodb starts storing the data I'm wanting, I really need for the database itself to be on the big partition, and I'm assuming it's not the way I have it set up (using defaults for everything).
It would also be nice to be sure my log files go to the big partition rather than the small one.
Or is the situation simply this: Everything at root (/) except /mnt/my-data is on the small virtual disk. Everything that should go on the large EBS volume needs to be put in /mnt/my-data/....

A: Depending on your setup. But from what you have written it is the option with 'everything under /mnt/my-data' is in EBS, the rest is in ephemeral storage.
You might either change the mountpoint of EBS to contain your mongo database, or make a symlink (though I am not 100% sure mongo won't complain).


text:
Q: Prolog Returning Elements Within Facts to The User I have a Prolog knowledge base with some "symptom" facts called facts.pl.  Here is an example of my KB:
symptom("Typhoid", "muscle_pain").
symptom("Typhoid", "bloating").
symptom("Meningitis", "headache").
symptom("Meningitis", "fever").
symptom("Meningitis", "stiff neck" ).
symptom("Measles", "cough").
symptom("Measles", "runny_nose").

I have written a short prolog program in another file called "diseaseSearch.pl".  This program consults facts.pl and is supposed to allow the user to enter a disease name and prints the disease's corresponding symptoms to the screen.
My code:
:- write('loading disease database'), nl.
:- [facts].
:- write('disease database loaded'), nl, nl.

getsymptoms:-
    write('>   Enter a diseae name followed by a period.'), nl,
    write('For Example: Measles'), nl,
    write('Disease Name?:'),
    read(Input), nl,
    symptom(Input,Output),
    write(Output).

If I enter "Measles." the output should be "cough" and "runny_nose".  However, with the code above no matter which disease I enter it always returns the result from the first fact which is "muscle_pain". SWI output found here
I found a similar method from an online tutorial, I am trying to learn the basics of Prolog input and output right now.  Am I on the right track? Some tips to solve this problem would be greatly appreciated!

A: I guess you are entering Measles without " " and prolog takes it as a variables. Either you should enter it with "". If you enter Measles then it's a variables but if you enter "Measles" then it's a term.
If you want to enter without annotations then you need to make a database in which you have all terms(means that they start with small letter) then you don't need annotation.