text:
Q: Which merge tool should I use with Mercurial in Windows? I'm just starting with Mercurial and one of the things that I should do is select a merge tool. I was thinking to use WinMerge for that purpose, but I can't find the way to select this in particular. There are references for all the other merge tools around, but not for WinMerge.
So, should I use WinMerge or there's a better tool for that job (remember, I'm using Windows).

A: Beyond Compare is the gold standard for compare/merge tools.  I've used it as well as many of the free ones mentioned and can tell you it's worth the $50.
They have a page here that discusses configuration for a variety of SCM packages.

A: WinMerge works great...
Edit: This might be useful:

*

*Mercurial MergeProgram

A: I've used DiffMerge which is available for free.
Take a look at the screenshots to get an idea of how it works, I found the interface pretty intuitive.
Good luck!

A: i use p4merge.
http://www.perforce.com/perforce/products/merge.html
it's beatiful and very clear.
here shows how can you configure.

A: Take a look at kdiff3:  http://kdiff3.sourceforge.net/
It was originally designed for KDE/linux but has been ported to Windows.  It will diff/merge up to 3 files remarkably intelligently, it does a great job of highlighting differences and suggesting how to merge the files, and it's about as intuitive as one could hope.
Good luck!


text:
Q: Why can I open .docx with OpenOffice but not .odt with Word? I am using Office 2007 and OpenOffice 3.3. I have to be able to open and save documents in both formats .docx and .odt. As .odt is an open format why can't Word open and save documents in that Format?
Edit:
Is there a program to open and save both formats in good quality that there are no problems opening with Word or OpenOffice?

A: Word 2007 does provide support for reading and producing ODF 1.1 .odt documents.  You should make sure that the version of Office 2007 is current to at least SP2.
The support for ODF 1.1 is also present in Microsoft Office 2010.  In Microsoft Office 2013, there is support for ODF 1.2, including interchange of OpenFormula between Excel and OpenDocument Spreadsheet (.ods) files.
The conversions implemented by products that support one native format (OOXML or ODF) are not entirely unblemished when reading/writing the other format (ODF or OOXML).  You should be careful to ensure that the specific types of documents you are interested transfer back and forth without fidelity loss.
One useful aid is the Microsoft SkyDrive free service with its Web Applications for Microsoft Office.  SkyDrive WebApps provide import and export of ODF as well as OOXML among the reduced functionality that it supports.  If your documents go between formats successfully there, I'd say that's a safe bet.  SkyDrive Web Site

A: The Open Document Format (.odt, .odp, .ods, ...) is an open format and free to use. Microsofts Office Open XML Format (.docx, .pptx, .xlsx) is as well an open standard, but it is not free, licensing fees have to be paid to Microsoft.
So the answer to your question is: It is all about the money. Microsoft tried to force other products like OpenOffice/LibreOffice into buying a licence for their Office Open XML Format by not supporting the Open Document Format. The European Union forced Microsoft to support the Open Document Format in the newest version of Office (Office 2013). So if you are using Microsoft Office 2013 you should be able to open and save files in the Open Document Format.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Como inverter uma string sem utilizar o método reverse c# Console.WriteLine($"Texto Normal : {texto}");

string textoInvertido = new string(texto.Reverse().ToArray());

Console.WriteLine($"Texto Convertido : {textoInvertido}");

A: Uma solução é dentro de um laço for iterar do último a primeiro caractere da string e com o auxilio de um objeto da classe StringBuilder os acrescentar ao final da string em construção por meio do método StringBuilder.Append:
string s = "Stack Overflow";
StringBuilder sb = new StringBuilder();           //Instancia um objeto da classe StringBuilder.
//Itere último ao primeiro índice da string s em i...
for(var i = s.Length-1; i>=0; i--)
{
    sb.Append(s[i]);                              //...acrescente o caractere s[i] ao final do objeto StringBuilder.
}
Console.WriteLine(sb.ToString());
//wolfrevO kcatS

Teste o exemplo no IDEOne
Outra solução pode ser obtida com o uso de um pilha. Veja em Como funciona e se usa o Stack em C#? que pilha é uma estrutura de dados do tipo sequencia LIFO(Last In First Out).
Com o auxilio da classe genérica System.Collections.Generic.Stack<T> empilhe os caracteres da string, converta a pilha em Array de caracteres com o método Stack<T>.ToArray e a partir desse array instancie uma string.
string s = "Stack Overflow";
//Instancie uma string formada pelo array de caracteres obtido da pilha de caracteres cujo o conteúdo seja os caracteres de s.
Console.WriteLine(new string((new Stack<char>(s)).ToArray()));
//wolfrevO kcatS

Teste o exemplo no IDEOne


text:
Q: how to get ontouch of cube different faces? I am making a cube using OpenGL.where I have a rotating 3d cube.All the six faces of the cube have different images.I am not getting a click of different faces of the cube.
example:-cube is rotating while rotating cube if I click on cube then how to get which image is clicked from all the 6 image.


text:
Q: Not able to generate correct English to SQL translations using LSTM for machine translation I'm using recurrent neural networks to train a model to translate sample english sentences such as "fetch all employee data" into sql such as "SELECT * FROM EMPLOYEE". Right now my program takes 100 epochs of training time but translates all the inputs the same. Required libraries are tensorflow and keras. Could someone take a look at my program to help me generate the correct translation?
Here is my code in python:
https://github.com/Kashdog/engsqlnmt
here's my code:
from __future__ import print_function

from keras.models import Model
from keras.layers import Input, LSTM, Dense
import numpy as np
import h5py

batch_size = 64  # Batch size for training.
epochs = 200  # Number of epochs to train for.
latent_dim = 256  # Latent dimensionality of the encoding space.
num_samples = 10000  # Number of samples to train on.
# Path to the data txt file on disk.
data_path = 'eng-sql/sql.txt'

# Vectorize the data.
input_texts = []
target_texts = []
input_characters = set()
target_characters = set()
with open(data_path, 'r', encoding='utf-8') as f:
    lines = f.read().split('\n')
for line in lines[: min(num_samples, len(lines) - 1)]:
    print(line.split('^'))
    input_text, target_text = line.split('^')
    # We use "tab" as the "start sequence" character
    # for the targets, and "\n" as "end sequence" character.
    target_text = '\t' + target_text + '\n'
    input_texts.append(input_text)
    target_texts.append(target_text)
    for char in input_text:
        if char not in input_characters:
            input_characters.add(char)
    for char in target_text:
        if char not in target_characters:
            target_characters.add(char)

input_characters = sorted(list(input_characters))
target_characters = sorted(list(target_characters))
num_encoder_tokens = len(input_characters)
num_decoder_tokens = len(target_characters)
max_encoder_seq_length = max([len(txt) for txt in input_texts])
max_decoder_seq_length = max([len(txt) for txt in target_texts])

print('Number of samples:', len(input_texts))
print('Number of unique input tokens:', num_encoder_tokens)
print('Number of unique output tokens:', num_decoder_tokens)
print('Max sequence length for inputs:', max_encoder_seq_length)
print('Max sequence length for outputs:', max_decoder_seq_length)

input_token_index = dict(
    [(char, i) for i, char in enumerate(input_characters)])
target_token_index = dict(
    [(char, i) for i, char in enumerate(target_characters)])

encoder_input_data = np.zeros(
    (len(input_texts), max_encoder_seq_length, num_encoder_tokens),
    dtype='float32')
decoder_input_data = np.zeros(
    (len(input_texts), max_decoder_seq_length, num_decoder_tokens),
    dtype='float32')
decoder_target_data = np.zeros(
    (len(input_texts), max_decoder_seq_length, num_decoder_tokens),
    dtype='float32')

for i, (input_text, target_text) in enumerate(zip(input_texts, target_texts)):
    for t, char in enumerate(input_text):
        encoder_input_data[i, t, input_token_index[char]] = 1.
    for t, char in enumerate(target_text):
        # decoder_target_data is ahead of decoder_input_data by one timestep
        decoder_input_data[i, t, target_token_index[char]] = 1.
        if t > 0:
            # decoder_target_data will be ahead by one timestep
            # and will not include the start character.
            decoder_target_data[i, t - 1, target_token_index[char]] = 1.

# Define an input sequence and process it.
encoder_inputs = Input(shape=(None, num_encoder_tokens))
encoder = LSTM(latent_dim, return_state=True)
encoder_outputs, state_h, state_c = encoder(encoder_inputs)
# We discard `encoder_outputs` and only keep the states.
encoder_states = [state_h, state_c]

# Set up the decoder, using `encoder_states` as initial state.
decoder_inputs = Input(shape=(None, num_decoder_tokens))
# We set up our decoder to return full output sequences,
# and to return internal states as well. We don't use the
# return states in the training model, but we will use them in inference.
decoder_lstm = LSTM(latent_dim, return_sequences=True, return_state=True)
decoder_outputs, _, _ = decoder_lstm(decoder_inputs,
                                     initial_state=encoder_states)
decoder_dense = Dense(num_decoder_tokens, activation='softmax')
decoder_outputs = decoder_dense(decoder_outputs)

# Define the model that will turn
# `encoder_input_data` & `decoder_input_data` into `decoder_target_data`
model = Model([encoder_inputs, decoder_inputs], decoder_outputs)

# Run training
model.compile(optimizer='rmsprop', loss='categorical_crossentropy')
model.fit([encoder_input_data, decoder_input_data], decoder_target_data,
          batch_size=batch_size,
          epochs=epochs,
          validation_split=0.2)
# Save model
model.save('s2s.h5')

# Next: inference mode (sampling).
# Here's the drill:
# 1) encode input and retrieve initial decoder state
# 2) run one step of decoder with this initial state
# and a "start of sequence" token as target.
# Output will be the next target token
# 3) Repeat with the current target token and current states

# Define sampling models
encoder_model = Model(encoder_inputs, encoder_states)

decoder_state_input_h = Input(shape=(latent_dim,))
decoder_state_input_c = Input(shape=(latent_dim,))
decoder_states_inputs = [decoder_state_input_h, decoder_state_input_c]
decoder_outputs, state_h, state_c = decoder_lstm(
    decoder_inputs, initial_state=decoder_states_inputs)
decoder_states = [state_h, state_c]
decoder_outputs = decoder_dense(decoder_outputs)
decoder_model = Model(
    [decoder_inputs] + decoder_states_inputs,
    [decoder_outputs] + decoder_states)

# Reverse-lookup token index to decode sequences back to
# something readable.
reverse_input_char_index = dict(
    (i, char) for char, i in input_token_index.items())
reverse_target_char_index = dict(
    (i, char) for char, i in target_token_index.items())

def decode_sequence(input_seq):
    # Encode the input as state vectors.
    states_value = encoder_model.predict(input_seq)

    # Generate empty target sequence of length 1.
    target_seq = np.zeros((1, 1, num_decoder_tokens))
    # Populate the first character of target sequence with the start character.
    target_seq[0, 0, target_token_index['\t']] = 1.

    # Sampling loop for a batch of sequences
    # (to simplify, here we assume a batch of size 1).
    stop_condition = False
    decoded_sentence = ''
    while not stop_condition:
        output_tokens, h, c = decoder_model.predict(
            [target_seq] + states_value)

        # Sample a token
        sampled_token_index = np.argmax(output_tokens[0, -1, :])
        sampled_char = reverse_target_char_index[sampled_token_index]
        decoded_sentence += sampled_char

        # Exit condition: either hit max length
        # or find stop character.
        if (sampled_char == '\n' or
           len(decoded_sentence) > max_decoder_seq_length):
            stop_condition = True

        # Update the target sequence (of length 1).
        target_seq = np.zeros((1, 1, num_decoder_tokens))
        target_seq[0, 0, sampled_token_index] = 1.

        # Update states
        states_value = [h, c]

    return decoded_sentence

for seq_index in range(39):
    # Take one sequence (part of the training set)
    # for trying out decoding.
    input_seq = encoder_input_data[seq_index: seq_index + 1]
    decoded_sentence = decode_sequence(input_seq)
    print('-')
    print(seq_index)
    print('Input sentence:', input_texts[seq_index])
    print('Decoded sentence:', decoded_sentence)
print('testing')
encoder_test_data = np.zeros(
    (2,max_encoder_seq_length, num_encoder_tokens),
    dtype='float32')
test_seq = "fetch total employee data"
print(test_seq)
#encoder_test_data
for t, char in enumerate(test_seq):
        encoder_test_data[1,t, input_token_index[char]] = 1.
#input_seq = 'fetch all customer data'
decoded_sentence = decode_sequence(encoder_test_data[1:2])
print('Decoded test sentence:', decoded_sentence)

and my data file(sql.txt) is:
fetch all customer data^SELECT * FROM CUSTOMER
find all customer data^SELECT * FROM CUSTOMER
retrieve all customer data^SELECT * FROM CUSTOMER
get all customer data^SELECT * FROM CUSTOMER
download all customer data^SELECT * FROM CUSTOMER
select all customer data^SELECT * FROM CUSTOMER
obtain all employee info^SELECT * FROM EMPLOYEE
show all employee info^SELECT * FROM EMPLOYEE
display all employee info^SELECT * FROM EMPLOYEE

A: TLDR; Your dataset is very small, biased and lacks the variety needed for RNNs. So you need 'some tricks' to make your code work.
The problem is you didn't shuffle your input data.  (The fully working source code is here)
If you look to your sql.txt file, you'll notice the dataset is sorted by customer and employee examples so it makes harder for your network to learn and furthermore, your dataset is biased [30 samples of customer and 70 samples of employee]
Also, your hidden_size was a little big for this small dataset (~100 samples)
so I made some changes:
batch_size = 32  # Batch size for training.
epochs = 300  # Number of epochs to train for.
latent_dim = 32  # Latent dimensionality of the encoding space.

Here's the shuffle code:
import random
all_data = list(zip(input_texts, target_texts))
random.shuffle(all_data)
for i, (input_text, target_text) in enumerate(all_data):
    for t, char in enumerate(input_text):
        encoder_input_data[i, t, input_token_index[char]] = 1.
    for t, char in enumerate(target_text):
        # decoder_target_data is ahead of decoder_input_data by one timestep
        decoder_input_data[i, t, target_token_index[char]] = 1.
        if t > 0:
            # decoder_target_data will be ahead by one timestep
            # and will not include the start character.
            decoder_target_data[i, t - 1, target_token_index[char]] = 1.

so here's the result (I think you'll need more data and a not-biased dataset):
-
34
Input sentence: show all client information
Decoded sentence: SELECT * FROM CUSTOMER

-
35
Input sentence: display all client information
Decoded sentence: SELECT * FROM CUSTOMER

-
36
Input sentence: fetch me all client information
Decoded sentence: SELECT * FROM CUSTOMER

-
37
Input sentence: get me all client information
Decoded sentence: SELECT * FROM CUSTOMER

-
38
Input sentence: get me all employee information
Decoded sentence: SELECT * FROM EMPLOYEE

testing
fetch total employee data
Decoded test sentence: SELECT * FROM EMPLOYEE


text:
Q: Google Cloud App Engine app.yaml basic usage Google's app.yaml doc provides examples but lacks the example of very simple basic usage in:
https://cloud.google.com/appengine/docs/php/config/appconfig#PHP_app_yaml_Static_file_pattern_handlers
Say I have app.yaml in the same directory as an html file (eg cat.html) which basically plays an audio from a wav file (eg catsound.wav) also in the same directory, what should the basic app.yaml file be? The html file say is:
<!DOCTYPE html>
<html>
<body>
<audio controls>
  <source src="catsound.wav" type="audio/wav">
Your browser does not support the audio element.
</audio>
</body>
</html>

The users would only go to .appspot.com. There is no sub url. Why wouldn't the following app.yaml work to upload both cat.html and catsound.wav?:
application: kat
version: 1
runtime: php
api_version: 1
handlers:
- url: /.*
  static_files: cat.*
  upload: cat.*

What should the right app.yaml for this so basic an example be?

A: You need to map the URL to a static file using a back-reference, e.g. \1.  I imagine you want something like this assuming everything is in your application's root directory (warning: I haven't tested this):
- url: /(.*)
  static_files: \1
  upload: cat.*


text:
Q: WPF Covering area taken by Grid Row (or better, covering 2 rows) I have a grid with 3 rows.  Row #2 is tallest and it hosts WebBrowser control.  I want to cover webbrowser with a Border at certain times.
What is WPF way to do that?
What I have below is my starter xaml.  I use Visibility to collapse my border to show WebBrowser or set my Border to Visible to cover WebBrowser.
However, after doing so I end up having half of 2nd row covered with browser and other half with nothing.
Basically, I want to simulate a toast message that shows and covers entire area of WebBrowser control in GridRow 2.
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>

    <ScrollViewer HorizontalScrollBarVisibility="Auto"
                  VerticalScrollBarVisibility="Auto"
                  Grid.Row="2">
        <WebBrowser x:Name="wb"
            Loaded="wb_Loaded"/>
    </ScrollViewer>

    <Border x:Name="myBorder" Background="White"
            Visibility="Collapsed"
            Grid.Row="2" RowSpan="2">
        <StackPanel HorizontalAlignment="Center"
                    VerticalAlignment="Center">
            //some text here
        </StackPanel>
    </Border>

     <DockPanel HorizontalAlignment="Stretch" Grid.Row="3">
        ...
     </DockPanel>
</Grid>

A: Use a Grid in Row:2 and show/hide Border/BrowserControl, as Grid allows you to stack things on top of each other.


text:
Q: My multi-thread online Server gets too slow when multiple clients connect, C# I'm trying to develop an online game just for fun, with a server and at least 2 clients playing in a single "room". My logic goes as follow, first have the server wait for a client to connect, after the client connects to the server I create a thread for this client (so the client can send messages to the server when it interacts with the main screen). After this if the client wants to play he clicks a button that says "start match" and if another client does the same both goes inside another Thread to play the game only between them. So I create a Thread for each client that connects and a Thread for every 2 clients that want to play.
Now, when i have 2 players playing the game everything goes smooth, the problem is when another 2 players want to play the game the server standalone stops responding (but you can still connect to the server and send messages) and the game gets really slow for the clients.I'm trying to learn about multi-threading that's why i'm doing this project so maybe i'm missing something. I should be creating only 2 threads for each client (when they are actually in game if not only 1) and with 4 clients that's at max 8 Threads, so why is my server getting so slow and crashing?.
This is where I accept my clients:
private void AcceptTcpClient(IAsyncResult ar)
    {
        TcpListener listener = (TcpListener)ar.AsyncState;

        ServerClient sc = new ServerClient(listener.EndAcceptTcpClient(ar));
        sc.SetisInGame(false); // not in game, just in the main menu
        clients.Add(sc);

        new Thread(() => MainPanelRoomThread(sc)).Start();

        StartListening();
    }

This is my Thread when a client connects:
private void MainPanelRoomThread(ServerClient scThread)
    {
        while (true)
        {
            if (!serverStarted)
                return;

            if (!scThread.GetisInGame()) //check if its not in game so it can receive data
            {
                NetworkStream stream = scThread.tcp.GetStream();

                if (stream.DataAvailable)
                {
                    StreamReader streamReader = new StreamReader(stream, true);
                    string data = streamReader.ReadLine();

                    if (data != null)
                        OnIncomingData(scThread, data); // waiting for that from the client
                }
            }
        }
    }

In the OnIncomingData function I wait for a Message saying that the client wants to enter a game so i can start the other thread:
private void OnIncomingData(ServerClient c, string data)
    {
        Debug.Log("Server = " + data);
        string[] aData = data.Split('|');

        switch (aData[0])
        {
            case "CMATCH":
                if (aData[1].Contains("true"))
                {
                    queueClients.Enqueue(c);

                    if (queueClients.Count == 2)
                        new Thread(new ThreadStart(RoomThread)).Start(); //start the Game only if 2 players are waiting for the game to start.
                    else
                        BroadCast("SMATCH|false", c);
                }else if (aData[1].Contains("false"))
                {
                    queueClients.Dequeue();
                    BroadCast("SMATCH|true", c);
                }
                break;
        }
    }

Finally the in Game room:
private void RoomThread()
    {
        string msg = "";
        List<ServerClient> players = new List<ServerClient>();
        List<ServerClient> disconnected = new List<ServerClient>();
        int tamanoCola = queueClients.Count;

        for(int i = 0; i < tamanoCola; i++)
        {
            players.Add(queueClients.Dequeue());
            msg = players[i].clientName + "|";
            players[i].isMainPlayer = (i == 0);
            players[i].SetisInGame(true); //its in game
            BroadCast("SWHO|" + msg + ((players[i].isMainPlayer) ? 1 : 0).ToString(), players[i]);
        }

        while (true)
        {
            if (!serverStarted)
                return;

            foreach (ServerClient c in players)
            {
                //check if client is still playing (either because the connection died or someone won)
                if (!IsConnected(c.tcp))
                {
                    c.tcp.Close();
                    disconnected.Add(c);
                    continue;
                }
                else
                {
                    NetworkStream stream = c.tcp.GetStream();

                    if (stream.DataAvailable)
                    {
                        StreamReader streamReader = new StreamReader(stream, true);
                        string data = streamReader.ReadLine();

                        if (data != null)
                            OnIncomingData(c, data, players);
                    }
                }
            }
            if (disconnected.Count >= 1)
                return;
        }
    }

Any help is really appreciated.


text:
Q: How to get Linux accept packets destined to non-local addresses? I have a scenario where our Linux running box has to receive packets destined to non-local addresses. e.g. I don't have 1::1 configured on any of my box's interfaces, but I want to have packets destined to it received. I have got the packets reaching ip6_rcv_finish().
Here ip6_input_route() returns a dst_entry pointing to discard function. If I add 1::1 to one of the interfaces, I see ip6_input_route() returns dst_entry wtih ip6_input() and the packet is received by the app through the socket. Is there a way to achieve this without having to add the address explicitly?
I am using IP_BINDTODEVICE and IP_TRANSPARENT options. These options let me bind the socket to 1::1 even though the address is not configured on any interface.

A: If you configure your neighbor router/host with a route to the destination of 1::1 to go out the interface you are connected to...it will reach you.

A: The IP_TRANSPARENT setting uses TProxy, which is documented here.  The tricky part seems to be getting the packets sent to the interface the socket is bound to.  Adapting the instructions in the documentation for IPv6, you should do the following:
# Mark packets whose destination IPs match a local socket
ip6tables -t mangle -N DIVERT
ip6tables -t mangle -A PREROUTING -p tcp -m socket -j DIVERT
ip6tables -t mangle -A DIVERT -j MARK --set-mark 1
ip6tables -t mangle -A DIVERT -j ACCEPT

# Configure policy routing to allow marked packets
ip -6 rule add fwmark 1 lookup 100
ip -6 route add local default dev eth1 table 100

Note that eth1 in the route was the interface my socket was bound to.  You may have to play around with these settings to get it to work correctly.  See here for more info.
I tested this in a two-box Vagrant environment and was able to successfully perform a TCP handshake with a socket bound to a bogus IPv6 address.


text:
Q: Wordpress on Azure App Service read Application settings I have a WordPress site running on Azure as an App Service.
I plan on using deployment slots to set up a test environment.
I have some environment-specific settings. If I was running .NET I would read the app settings.
Is it possible for PHP to read app settings?

A: You can use getenv() to read a setting
getenv('settingname');


text:
Q: How to check if my response contains sampled data I am using Google.Apis.AnalyticsReporting.v4 to download a view between two days. I would like to know where in my response can I see whether the data contains sampled data?
This is the code for my request and we catch the data in response object below:
using (var analytics = new AnalyticsReportingService(new BaseClientService.Initializer { HttpClientInitializer = credential }))
{
    while (nextPageToken != null)
    {
        var reportRequest = new ReportRequest
        {
            ViewId = "123456",
            DateRanges = new[] { new DateRange { StartDate = "2021-06-01", EndDate = "2021-11-30" } },
            Dimensions = new List<Dimension>() {
                new Dimension { Name = "ga:transactionId" },
                new Dimension { Name = "ga:campaign" },
                new Dimension { Name = "ga:sourceMedium" }
            },
            Metrics = new[] { new Metric { Expression = "ga:users" }, new Metric { Expression = "ga:sessions" } },

        };
        var requests = new List<ReportRequest>();
        requests.Add(reportRequest);
        // Create the GetReportsRequest object.
        var getReport = new GetReportsRequest() { ReportRequests = requests };

        // Call the batchGet method.
        var response = analytics.Reports.BatchGet(getReport).Execute();
    }
}

A: It does not sample the data requested through Google.Apis.AnalyticsReporting.v4. However, if your query is too complex, it will return a 5xx error. Looks like it prevents its backend from executing queries for too long to avoid high loads. In that case, you'd need to chop your request into a few.


text:
Q: Get values from JSON array using PHP I run the following PHP after I submit a form and get the output shown below:
$data = json_encode($_POST);

// output
{"First_Name":"Fred"}

How do I use PHP to just display the value 'Fred'?
I tried echo $data['First_Name']; but this is blank.

A: You no need to encode your incoming $_POST data.
Just say:
echo $_POST['First_Name'];

If you get a json data, decode it into an array:
$data = '{"First_Name":"Fred"}';
$decoded = json_decode($data, true);
echo $decoded['First_name'];

A: First of all, don't know why you use json_encode on PHP Array, and try to access it like it's an array - because after json_encode it's a string.
You have to use json_decode($data, true) and then you can access it like $data['First_Name'] or try to access it directly without json_encode() by $_POST['First_Name']

A: The json_decode() function is used to decode or convert a JSON object to a PHP object.And try to put the object to decode in another variable to avoid errors
<?php
$obj = '{"First_Name":"Fred"}';
$data = json_decode($obj);
echo ($data->First_Name);
?>


text:
Q: Flask error werkzeug.routing.RequestRedirect: 301 Moved Permanently: None I have a flask app that is giving me the below error when I try to access it using https://server/app. I have other apps that are not giving me this error. I can access the application if I give it a trailing slash (https://server/apps/). I am running Apache 2.4 with mod_wsgi. Flask version is 1.0.2.
Here is my app route code
@app.route("/", methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        data = {}
        end = datetime.datetime.strptime(request.form.get('start_date'),
                                         '%Y-%m-%d').date()
        start = end - relativedelta(days=30)
        inventory_stats = get_julian_days(end, start)
        start_send = start.strftime('%Y/%m/%d')
        end_send = end.strftime('%Y/%m/%d')
        data['start_date'] = start_send
        data['end_date'] = end_send
        data['inventory'] = inventory_stats
        return json.dumps(data)
    else:
        end = datetime.date.today()
        start = end - relativedelta(days=30)
        inventory_stats = get_julian_days(end, start)
        g.cursor.execute(queries.get_last_updated)
        last_updated = g.cursor.fetchone()
        return render_template('index.html', inventory_stats=inventory_stats,
                               start=start, end=end, last_updated=last_updated)

Here is the error I am getting.
Traceback (most recent call last):
  File "/opt/ecappdev/.edm/envs/dev365/lib/python3.6/site-packages/werkzeug/routing.py", line 1538, in match
    rv = rule.match(path, method)
  File "/opt/ecappdev/.edm/envs/dev365/lib/python3.6/site-packages/werkzeug/routing.py", line 776, in match
    raise RequestSlash()
werkzeug.routing.RequestSlash

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/ecappdev/.edm/envs/dev365/lib/python3.6/site-packages/flask/app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "/opt/ecappdev/.edm/envs/dev365/lib/python3.6/site-packages/flask/app.py", line 1791, in dispatch_request
    self.raise_routing_exception(req)
  File "/opt/ecappdev/.edm/envs/dev365/lib/python3.6/site-packages/flask/app.py", line 1774, in raise_routing_exception
    raise request.routing_exception
  File "/opt/ecappdev/.edm/envs/dev365/lib/python3.6/site-packages/flask/ctx.py", line 336, in match_request
    self.url_adapter.match(return_rule=True)
  File "/opt/ecappdev/.edm/envs/dev365/lib/python3.6/site-packages/werkzeug/routing.py", line 1542, in match
    safe='/:|+') + '/', query_args))
werkzeug.routing.RequestRedirect: 301 Moved Permanently: None

If I comment out the following code the application automatically redirects and does not error. Why would this code cause this problem?
@app.errorhandler(Exception)
def handle_app_error(exception):
    ''' Handle any potential errors'''
    LOGGER.error(exception, exc_info=True)
    return render_template('error.html')

I found my problem. I am also overwriting HTTPException. I need to pass on this exception. This code works.
@app.errorhandler(Exception)
def handle_exception(exception):
    # pass through HTTP errors
    if isinstance(exception, HTTPException):
        return exception

    # handling non-HTTP exceptions only
    LOGGER.error(exception, exc_info=True)
    return render_template('error.html')


text:
Q: VHDL - RC4 implementation I want to write an RC4 implementation in VHDL.
I have a problem with this part of code. Firstly I know my if is wrong. It should be like while generating output do ... or while data_in > 0 do... but I don't know how to write it...
when S2 =>
    IF(clk_count < a_width) THEN
        x_v := (x_s + 1) mod 2**a_width;
        y_v := (y_s + permutation(x_v)) mod 2**a_width;
        temp1 := permutation(x_v);
        temp2 := permutation(y_v);
        permutation(x_v) := temp2;
        permutation(y_v) := temp1;
        K := permutation(permutation(temp1) + permutation(temp2) mod 2**a_width);
        data_o <= std_logic_vector(to_unsigned(K, d_width));
        x_s <= x_v;
        y_s <= y_v;
        clk_count := clk_count + 1;
        current_state <= S2;
    END IF;

My program with S2 is synthesizing for infinity (no end)...
All code:
LIBRARY ieee;
USE ieee.std_logic_1164.all;
USE ieee.numeric_std.all;
--
ENTITY RC4 IS
    GENERIC
    (
        d_width : natural := 8;
      a_width : natural := 8
    );
  PORT
  (
        reset_i     : IN  std_logic; -- reset
        clk_i       : IN  std_logic; -- system clock
--      data_i      : IN  std_logic;
        data_in     : IN  std_logic_vector(d_width-1 DOWNTO 0); -- data input
        key_i       : IN  std_logic_vector(63 DOWNTO 0); -- key input
        data_o  : OUT std_logic_vector(d_width-1 DOWNTO 0)); -- data output
END ENTITY RC4;

--

ARCHITECTURE behavioral OF RC4 IS
    SUBTYPE byte IS natural RANGE 0 TO 2**d_width-1;
    TYPE ram  IS ARRAY (natural RANGE <>) OF byte;
    SIGNAL key_table : ram(0 TO 7);
    type state_type is (S0, S1, S2);
    signal current_state: state_type;
    SIGNAL x_s,y_s : byte;

    BEGIN

        key_i_convert : PROCESS(key_i)
        BEGIN
            FOR i IN 7 DOWNTO 0 LOOP
                key_table(i) <= to_integer(unsigned(key_i((i+1)*8-1 DOWNTO i*8)));
            END LOOP;
        END PROCESS key_i_convert;
--
        crypt : PROCESS(current_state,clk_i,data_in,key_table)
            VARIABLE temp1,temp2,K : byte;
            VARIABLE permutation : ram(0 TO 2**a_width-1);
            VARIABLE j,x_v,y_v : byte;
            VARIABLE clk_count : INTEGER := 0;
        BEGIN
--          IF(rising_edge(clock_i)) THEN
                    IF (reset_i = '0') THEN
                        data_o <= (OTHERS => '0');
                    END IF;
                    case current_state is
                        when S0 =>
                            IF(clk_count < 2**a_width) THEN
                                permutation(clk_count) := clk_count;
                                clk_count := clk_count + 1;
                                current_state <= S0;
                            ELSE
                                clk_count := 0;
                                j := 0;
                                current_state <= S1;
                           END IF;
                        when S1 =>
                            IF(clk_count < 2**a_width) THEN
                                j := (key_table(clk_count mod 8) + permutation(clk_count) + j) mod 2**a_width;
                                temp1 := permutation(clk_count);
                                temp2 := permutation(j);
                                permutation(clk_count) := temp2;
                                permutation(j) := temp1;
                                clk_count := clk_count + 1;
                                current_state <= S1;
                            ELSE
                                clk_count := 0;
                                x_s <= 0;
                                y_s <= 0;
                                current_state <= S2;
                            END IF;
                        when S2 =>
                            IF(clk_count < a_width) THEN
                                x_v := (x_s + 1) mod 2**a_width;
                                y_v := (y_s + permutation(x_v)) mod 2**a_width;
                                temp1 := permutation(x_v);
                                temp2 := permutation(y_v);
                                permutation(x_v) := temp2;
                                permutation(y_v) := temp1;
                                K := permutation(permutation(temp1) + permutation(temp2) mod 2**a_width);
                                data_o <= std_logic_vector(to_unsigned(K, d_width));
                                x_s <= x_v;
                                y_s <= y_v;
                                clk_count := clk_count + 1;
                                current_state <= S2;
                            END IF;
                    END CASE;
    --          END IF;
        END PROCESS crypt;
END ARCHITECTURE behavioral;

A: I've only had a quick look at your code but what I would suggest doing is moving your current_state assignment out of your IF statement because if the IF condition is never met for whatever reason, it will never update the current_state value.  Try that and let me kow if it makes a difference, if it doesn't I'll take a closer look at your code for you.
Gipsy


text:
Q: ObservableCollection.Next() and observablecollection.previous() functions I have a observablecollection with 20 items(images) and button("Next").How I can get functions like observablecollection.next() and observablecollection.previous() ?

A: An observable collection has no concept of 'Current' or even of 'Selected' item. They are all equal.
You could keep a simple int index and Increment/Decrement it.
Or use the SelectedItem property of a bound ListBox or similar.

A: The simplest soultion would be to keep track of your current item using iterator - simple integer.
int couter = 0;

When you press the next button, check the counter if is not bigger that number of elements in the list and increment the counter:
if(counter < myObservableColection.Count)
    ++counter;

your previous function needs to check if counter is not negative number and decrement the counter.
You can try a more neat pattern with Enumerator

A: For just a next button, you could call GetEnumerator on the ObservableCollection.  This will give you an IEnumerator<T> on which you can call Current and MoveNext.
If you need to implement a previous then you would use a solution more like lukas', with an index.


text:
Q: How do you close a metro app that is currently running without switching to a different app first?
Possible Duplicate:
How do I exit a Modern UI app?

Basically, is there any easy way to quit an application and automatically return to the start menu?
Currently, I have to do the following process:

*

*Switch to the start menu (or any other application)

*Go to the left side of the screen to bring up the list of running Modern UI applications.

*Right click on the running application, select close.

It seems to me that there should be an easier way to just quit out of an application and let the OS take you back to whatever happens to be running underneath. Is there?

A: Click on the top corner of the Metro App (so a litle hand will appear on the mouse pointer) and drag it to the bottom of the screen. It will force it to close.


text:
Q: Constrained (regularized/damped) solution of system of linear equations in Matlab I have an overdetermined system of linear equations A*X=B. Where X is a column matrix with N unknowns. The least square solution of this system can be obtained in Matlab as X = mldivide(A,B). However, I want a solution X, such that the sum of second order differences between different elements in X is minimum. That is, to find a solution X, such that the following error term is minimum:
$E = ||\mathbf{A}\mathbf{X}-\mathbf{B}||^2+\sum_{j=2}^{N-1}[X_{j-1}-2*X_j+X_{j+1}]^2$

A: What you're describing sounds exactly like what is sometimes called a "graph ridge"/"graphridge" regression, which is like a ridge regression (if that's something you're familiar with) but with a penalty not on the (squared) regression coefficients themselves, but on the (squared) differences between coefficients that are connected in an assumed graph structure. In your case, you'd let $X_j$ and $X_k$ be connected in this graph if $|k-j|=1$.
This type of regression is convenient because like the "regular" ridge regression, it has a closed-form solution. For more info see e.g. this paper which makes use of this method (esp. equation 14).

A: After getting hints from the comments and lot of literature survey, I have solved the above problem by myself. The above said error can be minimized by means of Tikhonov regularization of second order. Error term in general Tikhonov regularization is given as
$$E = {\|\textbf{A}\textbf{X}-\textbf{B}\|^2_2+\lambda\|LX\|^2_2}$$
Where $\lambda$ is damping factor and $L$ is regularization matrix. $L$ can have many forms. If $L$ is replaced by an identity matrix $I$, it is known as ridge regresion. Another common practice is to replace $L$ by finite order difference matrix. For our concerned error term, $L$ will replaced by second order difference matrix, i.e.
 $$L=
  \left[ {\begin{array}{cccc}
   -1&  2 &   -1 &     &     &  0\\
     & -1 &    2 &  -1 &     &   \\
     &    &  ... & ... & ... &   \\
     &    &      &  -1 &  2  & -1\\
  \end{array} } \right]$$
The solution by Tikhonov regularization can be then obtained by solving the following linear system:
$$\left[ \begin{array}{cc} A \\ \lambda L\end{array}\right]X =
\left[ \begin{array}{cc} B \\ 0 \end{array}\right]$$
You will have to decide on value of $\lambda$ (see L Curve in references).
References:

*

*Noschese, Silvia, and Lothar Reichel. "Inverse problems for regularization matrices." Numerical Algorithms (2012): 1-14.

*Calvetti, Daniela, Lothar Reichel, and Abdallah Shuibi. "Invertible smoothing preconditioners for linear discrete ill-posed problems." Applied numerical mathematics 54.2 (2005): 135-149.

*Hansen, Per Christian. The L-curve and its use in the numerical treatment of inverse problems. IMM, Department of Mathematical Modelling, Technical Universityof Denmark, 1999.


text:
Q: Jackson parse tree response I want to parse google nearby places response, an item have this format :
         "geometry" : {
            "location" : {
               "lat" : 75.22404,
               "lng" : 57.42276
            },
            "viewport" : {
               "northeast" : {
                  "lat" : 95.2353532,
                  "lng" : 75.4427513
               },
               "southwest" : {
                  "lat" : 55.207256,
                  "lng" : 45.4045009
               }
            }
         },
         "vicinity" : "something"

But I want to parse this using only one object something like that :
public class NearbyPlace extends BaseResponse {

    @JsonProperty("how to access geometry->lat ?")
    private double latitude;

    @JsonProperty("how to access geometry->lng ?")
    private double longitude;

    @JsonProperty("vicinity")
    private String vicinity;
}

The problem is how to access "lat" and "lng" in "geometry" directly from NearbyPlace class without creating another classes for each node ?

A: You can use a combination of readTree() and treeToValue():
final String placesResponse = "...";
final ObjectMapper om;

NearbyPlace place = null;
final JsonNode placesNode = om.readTree(placesResponse);
final JsonNode locationNode = placesNode.findPath("geometry").findPath("location");
if (! locationNode.isMissingNode()) {
     place = om.treeToValue(locationNode, NearbyPlace.class);
}

However, since vicinity kept outside of the inner geometry class, you still need to set that value manually. JsonNode has the necessary methods:
final JsonNode vicinityNode = placesNode.findPath("vicinity");
if (vicinityNode.isTextual()) {
    place.vicinity = vicinityNode.textValue();
}

A: Since you will end up with a collection of NearbyPlaces, you may be best off just manually traversing the JsonNode. Otherwise you're talking about overriding deserialization for collections, or writing a deserializer that is likely to get nasty.
The example below is recursive. Recursion in Java is bad (for now), but fun to write. In a production app I'd recommend a loop.
@Test
public void testNearbyPlaceDeserialization() throws Exception {
    JsonNode jsonNode = objectMapper.readTree(new File("input.json"));
    // or objectMapper.readValue(resultString, JsonNode.class);
    ImmutableList<NearbyPlace> nearbyPlaces = readLatLng(jsonNode,
            jsonNode.get("vicinity").asText(null),
            ImmutableList.builder());
    System.out.println(nearbyPlaces);
}

private static ImmutableList<NearbyPlace> readLatLng(JsonNode jsonNode,
                                                     String vicinity,
                                                     ImmutableList.Builder<NearbyPlace> placeBuilder) {
    JsonNode latNode = jsonNode.get("lat");
    JsonNode lngNode = jsonNode.get("lng");
    if (latNode != null && lngNode != null) {
        placeBuilder.add(NearbyPlace.builder()
                .setLatitude(latNode.asDouble())
                .setLongitude(lngNode.asDouble())
                .setVicinity(vicinity)
                .build());
    } else {
        jsonNode.elements().forEachRemaining((element) -> {
            readLatLng(element, vicinity, placeBuilder);
        });
    }
    return placeBuilder.build();
}

This will return a list of 3 NearbyPlaces.

A: The easiest solution I can think of is to use the @JsonCreator annotation on your NearbyPlace class' constructor:
public class NearbyPlace extends BaseResponse {

    private double latitude;

    private double longitude;

    @JsonProperty("vicinity")
    private String vicinity;

    @JsonCreator
    public NearbyPlace(Map<String, Object> delegate) {
        super();
        this.latitude = (Double) delegate.get("geometry").get("location").get("lat");
        this.latitude = (Double) delegate.get("geometry").get("location").get("lng");
    }
}

You might want to add some checks against null in case the incoming JSON lacks some nested object, i.e. geometry or location.
Please refer to Jackson annotations documentation for further details.


text:
Q: ggplot reverse axis order for factors This is the base plot, with months ordered bottom-to-top one through twelve. I want to order them top-to-bottom one through twelve.
library(tidyverse)
library(nycflights13)
library(ggridges)
ggplot(weather %>% filter(temp > 50), aes(x = temp, y = as.factor(month))) +
  geom_density_ridges()

Both of these solutions yield errors. What is the correct solution?
# BROKEN SOLUTION 1
ggplot(weather %>% filter(temp > 50), aes(x = temp, y = as.factor(month))) +
  geom_density_ridges() +
  scale_y_continuous(trans = "reverse")

Error: Discrete value supplied to continuous scale. In addition:
  Warning messages: 1: In Ops.factor(x) : '-' not meaningful for
  factors. 2: Transformation introduced infinite values in continuous
  y-axis.

and also
# BROKEN SOLUTION 2
ggplot(weather %>% filter(temp > 50), aes(x = temp, y = as.factor(month))) +
  geom_density_ridges() +
  scale_y_discrete(limits = rev(levels(as.factor(month))))

Error in is.factor(x) : object 'month' not found

A: Try scale_y_discrete(limits = rev)


text:
Q: static initializer block return void I know that it isnt about my problem but just to you know, this is my first stackoverflow post and yes, my english isnt quite good so please, i sincerely ask you guys, be patience. I'd chosen english community because brazillian stack overflow community isnt this good as english version do.
About my problem, here it is:
public class Class5{

static int ia, ib;

public static Class5 InstanceClass5 = new Class5();

public Class5(){this(1, 2);}
public Class5(int ia){this(ia, 0);}
public Class5(int ia, int ib){this.ia = ia; this.ib = ib;}

// the only one important part of this class code
public static void returnConstructor(int ia, int ib){}
// ends here, the rest isnt important
public static int myVar = initializeClassVariable();
private static int initializeClassVariable(){int ia = 3; return ia;}
}

public class Main
{
static Scanner dataEntrance = new Scanner(System.in);

public Main(){}
public static Main Instancia1Main = new Main();

static int ia, ib;

// here my problem begins: i just did 2 static blocks initializers, but its working good.
public static int varType = InitializeClassVariable();
private static int InitializeClassVariable(){ia = Class5.ia; return ia;}
public static int varType2 = InitializeClassVariable2();
private static int InitializeClassVariable2(){ib = Class5.ib; return ib;}

public static void main(String[] args)
{
    System.out.println(Class3.Instancia2Class3.Class3());

    // It shows that the first static block initializer is doing what it was created to do: get the same value as "ia" class variable,
    // inside Class5 (so, varType2 or InitializeClassVariable2 method is working by the same way, for sure)
    System.out.println(Main.varType);
    //final Main instancia1Main = Instancia1Main; -- it doenst have any importance for now
    // AND FINALLY, THERES MY PROBLEM: inside Class5, returnConstructor method have 2 arguments: int ia, int ib
    // To print this method values, i have to use 2 int arguments: why not varType and varType2
    // or InitializeClassVariable and InitializeClassVariable2 (work by the same way... in theory)
    // It supposed to work then...
    System.out.println(Class5.InstanceClass5.returnConstructor(Main.InitializeClassVariable(), Main.varType2));
}
}

[Then it happens][1][1]: https://i.stack.imgur.com/cR8xH.png
I really got no idea why returnConstructor is receiving the listed arguments (Main.InitializeClassVariable(), Main.varType2) as void.
System.out.println(Main.varType); -> It shows that varType isnt a void, and varType2 for sure do the same, someone have any idea about why its happening and how to fix that?
I think thats all, thx everyone!

A: returnConstructor doesn't return anything, so println has nothing to print.


text:
Q: OpenSSL public key encoding I have a question about OpenSSL way of RSA public key DER-encoding.
According to RFC3447, ASN.1 representation of a public key is a sequence:
  RSAPublicKey ::= SEQUENCE {
      modulus           INTEGER,  -- n
      publicExponent    INTEGER   -- e
  }

Hexdump for some openssl generated DER-encoded public key looks like this:
0000000 30 82 01 22 30 0d 06 09 2a 86 48 86 f7 0d 01 01
0000010 01 05 00 03 82 01 0f 00 30 82 01 0a 02 82 01 01
0000020 00 f3 7b 82 a0 2b ff 0d b1 5b 63 16 e3 93 72 6b
0000030 43 9b b7 23 eb 2f 63 fa 2e db f1 d1 44 6c d9 6b
0000040 a5 14 60 e4 f8 4a 51 58 f7 ac 9d 75 f3 90 2f 42
0000050 80 b5 c3 92 db 2b 02 6c 02 0b 2c d7 17 d8 fe 4e
0000060 79 61 72 d5 43 c2 43 87 d2 0c d7 f3 7e 48 84 8c
0000070 b1 e1 fc 43 fb da a4 7f aa 10 c1 bf 45 34 23 09
0000080 ef 30 57 14 c0 68 ef 2b 74 9d db 01 a8 cc a1 2c
0000090 7d 4d 29 63 6a f5 a7 17 5a 29 95 df 8f d9 9e ab
00000a0 c7 ef 47 c6 16 e6 df 01 54 82 8d 29 ff 23 5b f3
00000b0 4e e1 9c 80 e0 26 81 bf 02 6e 65 82 32 f2 e5 f4
00000c0 dc ba 00 08 6e db f6 e8 04 de 08 ba 5e 4d f2 db
00000d0 aa 19 3e 4a a9 e1 ec 95 6d 41 b9 8b 0d c7 fc de
00000e0 96 97 8f 3f b4 3e de 07 e5 d4 2f 51 cc d5 b2 2f
00000f0 e4 b3 0c df 23 33 54 6e 9a 8d 59 79 8b b3 18 a1
0000100 5d 31 61 19 59 b0 64 1b 18 0a 2b 5e 43 7e c7 d2
0000110 3d 75 2d eb bb 2b 8d 51 8d c9 07 5f e1 4f 29 26
0000120 21 02 03 01 00 01
0000126

So, as you can see, there is a sequence in the beginning that contains ASN.1 object type (tags 06, 05):
0000000 30 82 01 22 30 0d 06 09 2a 86 48 86 f7 0d 01 01
0000010 01 05 00 03 82 01 0f 00

Can anyone clarify what kind of object is that and why it is used in openssl's implementation?


text:
Q: Insert XML data into mongoDB using scala? I'm new about Scala. What I want to do is retrieving data from a XML file, and keeping the data into a list, finally inserting them into mongodb collection. I have some problems. I know the way of steps, but I couldn't apply in the codes. I thought I should have had a class which is class Contact, and it includes fields(name, lastName, phone). I want to take name, lastName and phone data in labels by one by, and assign them to Contact objects. After getting operation, I should write these data into mongoDb.
Class Contact
class Contact(_name: String, _lastName: String, _phones: String) {

/* Fields */
//var id: Int           = _id
var name: String      = _name
var lastName: String  = _lastName
var phones: String    = _phones

I use a function to get xml file data.
def GetXMLFile(){
val contacts = XML.loadFile("xmlFilePath")
assert(contacts.isInstanceOf[scala.xml.Elem])
var persons: List[Contact] = new Contact()
for (name <- (contacts\\ "name"))

After that I'm stocked. Can anyone help me a little? I'll really be happy.

A: Have a look at salat. This is a library written in scala wrapped over casbah Java driver for MongoDB.
The DAO wiki page would particualrly be of interest for you, it can directly serialize a case class to an object in the mongo collection.
case class Alpha(@Key("_id") id: Int, x: String)

object AlphaDAO extends SalatDAO[Alpha, Int](collection = MongoConnection()("test_db")("test_coll"))

val alpha1 = Alpha(id = 1, x = "alpha1")
// if everything went OK, this method will return Some(1)
val _id = AlphaDAO.insert(alpha1)


text:
Q: PHP Abstract function com argumento de interface Estou tentando criar uma função abstrata passando uma interface como argumento:
abstract class AbstractManagement {
   abstract public function handle(RequestInterface $request) :array;
}

Mas quando tento criar esse método na minha classe:
namespace App\Http\RequestManagement;

use App\Http\Requests\ServiceStoreAndUpdate as Request;
//ServiceStoreAndUpdate implementa RequestInterface

class ServiceStoreAndUpdate extends AbstractManagement
{
    public function handle(Request $request) :array
    {
        return $request->validated();
    }
}

Me retorna o seguinte erro:

"Declaration of
  App\Http\RequestManagement\ServiceStoreAndUpdate::handle(App\Http\Requests\ServiceStoreAndUpdate
  $request): array must be compatible with
  App\Http\RequestManagement\AbstractManagement::handle(App\Http\Requests\RequestInterface
  $request): array"

Não é possível passar uma interface, ou uma classe pai como argumento em uma função abstrata?


text:
Q: PHP regex preg_match_all for string I have the following string:
keyword|title|http://example.com/
I would like to use the PHP function
preg_match_all ( $anchor, $key, $matches, PREG_SET_ORDER) )

currently
$anchor='/([\w\W]*?)\|([\w\W]*)/';

and I get $matches array:
Array
(
    [0] => Array
        (
            [0] => keyword|title|http://example.com/
            [1] => keyword
            [2] => title|http://example.com/
        )

)

I would like to get
matches[1]=keyword
matches[2]=title
matches[3]=http://example.com

How would I have to modify $anchor to achieve this?

A: The easiest way would be  to use explode() instead of regular expressions:
$parts = explode('|', $str);

Assuming none of the parts can contain |. But if they could, regex wouldn't help you much either.

A: If you want to keep using the regex to avoid a manual loop, then I'd recommend this over the used [\w\W]* syntax and for readability:
$anchor = '/([^|]*) \| ([^|]*) \| ([^\s|]+)/x';

It's a bit more robust with explicit negated character classes. (I assume neither title nor url can contain | here.)


text:
Q: Remove separator line for only one cell I'm trying to remove the separator for one UITableViewCell. I did the following:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];

    if (indexPath.row == 1)
        cell.separatorInset = UIEdgeInsetsZero;

    return cell;
}

(It's static cells.) When I run the app. The separator line is still there. How can I remove the separator line for one cell?

A: If you want to hide the separation line for only a specific type of cell, you can use the following code:
 override func layoutSubviews() {
    super.layoutSubviews()
    subviews.forEach { (view) in
        if view.dynamicType.description() == "_UITableViewCellSeparatorView" {
            view.hidden = true
        }
    }
}

Write this code in the cell (it must be a subclass of UITableViewCell) for which you do not want a separation line to appear.

A: Just add following to the cell you don't want separator (swift 3) :
override func awakeFromNib() {
    super.awakeFromNib()

    // remove separator
    self.separatorInset = UIEdgeInsetsMake(0, 1000, 0, 0)
}

A: Swift 5  Enjoy
//MARK:- In which row you want to hide
cell.separatorInset = UIEdgeInsets(top: 0, left: CGFloat.greatestFiniteMagnitude, bottom: 0, right: 0);

A: On iOS 8 you need to use:
cell.layoutMargins = UIEdgeInsetsZero

If you want to be compatible with iOS 7 as well you should do following:
if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
    [cell setSeparatorInset:UIEdgeInsetsZero];
}

if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
    [cell setLayoutMargins:UIEdgeInsetsZero];
}

ADD: If previous didn't work - use this. (from answer below)
 cell.separatorInset = UIEdgeInsetsMake(0, CGFLOAT_MAX, 0, 0);

If none of above worked, you can do:
self.tableView.separatorColor = [UIColor clearColor];
but this will leave 1 pixel empty space, not really removing a line, more making it transparent.

A: You can just visually hide separator through separatorInset property:
tableViewCell.separatorInset = UIEdgeInsets(top: 0, left: 10000, bottom: 0, right: 0)

A: Swift 4
iOS 11
Assign next values for specific cell you need for customization.
cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, .greatestFiniteMagnitude)
cell.directionalLayoutMargins = .zero

A: For those people struggling with this for iOS 9 the solution is a little different than the answers already given. Here is how I solved it in Swift:
override func viewWillAppear(animated: Bool) {
    table.cellLayoutMarginsFollowReadableWidth = false
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    if IS_THE_CELL_WITH_NO_SEPARATOR{
        cell.separatorInset = UIEdgeInsetsZero
        cell.preservesSuperviewLayoutMargins = false
        cell.layoutMargins = UIEdgeInsetsZero
    }
}

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    if IS_THE_CELL_WITH_NO_SEPARATOR{
        let size = self.view.bounds.size
        let rightInset = size.width > size.height ? size.width : size.height
        cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, rightInset)
    }
}

A: cell.separatorInset = UIEdgeInsetsMake(0.0 , cell.bounds.size.width , 0.0, -cell.bounds.size.width)

A: I created a Extension to UITableViewCell, setting separatorInset value brings anchor bugs to me, I'm using Eureka form Pod.
extension UITableViewCell {
    func hideSeparator(hide: Bool) {
        let subviews = self.subviews
        for view in subviews {
            if view.classForCoder.description() == "_UITableViewCellSeparatorView" {
                view.isHidden = hide
            }
        }
    }
}

A: Another way that is a bit hacky is to create the custom table view cell with a uiView that acts like separator inset. Then, hide and show that when you want to.
I created SampleTableViewCell and a nib file with label and separatorLineView
@interface SampleTableViewCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIView *separatorLineView;
@end

Then, in ViewController Class
@interface ViewController ()
@property (nonatomic) NSArray *items;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.items = @[@"A", @"B", @"C"];
    [self.tableView registerNib:[UINib nibWithNibName:@"SampleTableViewCell" bundle:nil] forCellReuseIdentifier:@"SampleCell"];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SampleTableViewCell *cell = (SampleTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"SampleCell" forIndexPath:indexPath];
    cell.titleLabel.text = self.items[indexPath.row];
    if (indexPath.row == 1) {
        cell.separatorLineView.hidden = YES;
    } else {
        cell.separatorLineView.hidden = NO;
    }
    return cell;
}

@end

A: Swift 5.1 -
override public func layoutSubviews() {
    super.layoutSubviews()
    subviews.forEach { (view) in
        if type(of: view).description() == "_UITableViewCellSeparatorView" {
            view.isHidden = true
        }
    }
}

A: If you'd like to show separator to only the visible cell you can try this:
tableView.separatorInset = UIEdgeInsets(top: 0, left: 1000, bottom: 0, right: 0)

let visibleCell = tableView.visibleCells

    for cellV in visibleCell{
        cellV.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    }

A:
Make UITableView style is .plain

use below line of code in
cell.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: .greatestFiniteMagnitude)

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
method

A: Swift 3 remove separator all cell:
 override func viewDidLoad() {
        self.yourTableView.separatorStyle = UITableViewCellSeparatorStyle.none
    }


text:
Q: Navigating Local Links with Bootstrap I'm trying to create a side navbar using the template http://getbootstrap.com/examples/dashboard/ and so I saved it to my computer as an html file.
However, when I try to change the links in the side navbar any local links don't work. The top link is an original link, but the links below it I put in to point to html files in the same folder. How do I navigate to these files, and why is the website address displayed as a folder, and the significance of the # sign because I can't seem to find where that # sign file is. Thanks.

Overview

LOGCELL Introduction

User Access Control

About Logcell

Cognos

Cognos Capabilities

Cognos Overview

The Congnos User Interface

A: You need to spend some time reading about how to use links and anchors. Maybe this article might help http://html.com/anchors-links/ (just google for more/other).
The '#' sign is used to link to anchors inside the page. If there is nothing after the '#' the link won't have any effect. For example, this link http://getbootstrap.com/examples/theme/#carousel-example-generic will focus on the id element that has the 'carousel-example-generic' name. If you don't put the name, it links to the whole page. So maybe the above example explains the '#' sign.
If you want to navigate to local files you need to decide if you want absolute or relative URLs. For relative paths, you can use '.' or '..' with the name of the file you want.


text:
Q: When i make post via admin page in Django it doesnt show up Literaly like title say...check the picture. When i try to make new Post it says i made it but it wont show up on admin page nor in detail.html.
http://prntscr.com/n0pfrv
here is my code for post model
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse

class Post(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(help_text="A short label, generally used in URLs.",default='', max_length=100)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    class Meta:
        ordering = ['-date_posted']

    def save(self):
        slug = self.title

    def get_absolute_url(self):
        return reverse('detail', kwargs={'slug':self.slug})

    def __str__(self):
        return self.title

admin.py
from django.contrib import admin
from .models import Post

class PostAdmin(admin.ModelAdmin):
    list_display = ['title', 'slug', 'date_posted', 'author']
    list_filter = ['title', 'date_posted']
    prepopulated_fields = { 'slug': ('title',)}

admin.site.register(Post, PostAdmin)

views.py in app called blog were i have model Post also
from django.contrib import messages
from . models import Post
from django.core.mail import send_mail
from django.views.generic import DeleteView, ListView

def index_view(request):
    return render(request, 'blog/index_view.html')

def blog_view(request):
    context = {
        'posts': Post.objects.all()
    }
    return render(request, 'blog/blog_view.html', context)

class PostDetailView(DeleteView):
    model = Post
    template_name = 'blog/detail.html'
    context_object_name = 'post'

If you need any other of my code im gonna post it

A: You don't actually save the data in your save(self) method:
def save(self):
    slug = self.title
    super(Post, self).save(*args, **kwargs)

You should call the real save method as mentioned in the docs:
Overriding predefined model methods


text:
Q: choose color to draw life in pygame I want to draw the player's life with a pygame.Surface filled with a color:
green means that the player's life is close to the player max life and red when the player's life is low and i don't know how to pick the color.
The green has to turn slowly red as the player's life decreases.

A: If you are looking for a colour changing rectangle (or any other shape), then pygame has some very useful draw commands
Take this, pygame.draw.rect taken from the pygame docs
pygame.draw.rect()
    draw a rectangle shape
    rect(Surface, color, Rect, width=0) -> Rect

Draws a rectangular shape on the Surface. The given Rect is the area of the
rectangle. The width argument is the thickness to draw the outer edge. If
width is zero then the rectangle will be filled.

In this case, color will be a 3 element tuple for red, green, and blue colour values. These will all be between 0 and 255. For example, (255, 255, 255) would be pure white.
If you keep track of a health and a max_health variable then you can find out how much of the rectangle should be red and how much should be green.
For example
green_value = 255 * (health / max_health)
red_value =   255 * ((max_health - health) / max_health)

Say your health was at 20 out of a maximum of 100, then your green value would be 20% of 255, and your red value would be 80% of 255, and your pygame.draw.rect function would take in a color parameter of (red_value, green_value, 0)
As long as you remember to update the green_value and red_value variables you should be fine.


text:
Q: Attaching a lot of event handlers to $(document) is bad? I have a very dynamic web application, elements are created and destroyed constantly.
In order to make clicks and other events stay, I'm attaching all of these events to $(document), like this example:
 $(document).on('click', '.tabs li a', function(event) {

 });

Like I said, almost all of these events are being attached to $(document).. are there any drawbacks to that? Where are these event handlers stored? Will it make my application slower?

A: No - this negatively impacts the performance of your jQuery. You should NOT bind all delegated event handlers to the document object. That is probably the worst performance scenario you could create. As mentioned in the Event Performance section here in the jQuery documentation-

Attaching many delegated event handlers to the document can degrade
  performance. Each time the event occurs, jQuery must compare all
  selectors of all attached events of that type to every element in the
  path from the event target up to the top of the document. For best
  performance, attach delegated events at a document location as close
  as possible to the target elements.

Avoid excessive use of document or document.body for delegated events on large documents. For delegated event handling it is MUCH more efficient to bind them to the closest parent that is not dynamic.
An amazing detailed description of the problems can be found in this answer.
Hope this helps!

A: tl;dr Binding listeners allocates memory. If you do this with a lot of listeners which are constantly being bind to the document, none of these listeners are ever turned off until the document is unloaded (i.e page refresh, hard loading another document as in old school html). Eventually in a SPA, you'll run into memory leaks and browser crashes


text:
Q: Derive Date Spans from Start and End Dates in SQL Server table I am using SQL Server 2016
I have a table that contains 1 row per month that a patient is assigned to a particular Provider.
A patient can be assigned to multiple providers during the year.
How can I derive date spans (startdate & enddate) to represent the time a patient was assigned to each provider.
My table looks like this:
+----------+---------------+------------+-----------+
| Provider | Patient       | StartDate  | EndDate  |
+----------+---------------+------------+-----------+
| 1922157  | 12345         | 20191201  | 20191231 |
| 1904176  | 12345         | 20191101  | 20191201 |
| 1904176  | 12345         | 20191001  | 20191101 |
| 1904176  | 12345         | 20190901  | 20191001 |
| 1904176  | 12345         | 20190801  | 20190901 |
| 1904176  | 12345         | 20190701  | 20190801 |
| 1904176  | 12345         | 20190601  | 20190701 |
| 1904176  | 12345         | 20190501  | 20190601 |
| 1904176  | 12345         | 20190401  | 20190501 |
| 1904176  | 12345         | 20190301  | 20190401 |
| 1904176  | 12345         | 20190201  | 20190301 |
| 1922157  | 12345         | 20190101  | 20190201 |
| 1922157  | 56789         | 20190101  | 20190201 |
+----------+---------------+------------+-----------+

In this case, patient 12345 was assigned to 2 different providers. One for 2 months, January and then December and the other for the rest of the year (10 months) February through November. Patient 56789 was only assigned to 1 provider (1922157) for 1 month (in December).
I'm trying to make it so my output looks like the below table but I am running into issues I think because the patient is assigned to the same pcp during 2 different times of the year. I tried using the lag function but I only get the correct results for some cases but not all such as this particular case.
+----------+---------------+------------+-----------+
| Provider | Patient       | StartDate  | EndDate  |
+----------+---------------+------------+-----------+
| 1922157  | 12345         | 20190101  | 20190201  |
| 1904176  | 12345         | 20190201  | 20191201  |
| 1922157  | 12345         | 20191201  | 20191231  |
| 1922157  | 56789         | 20191201  | 20191231  |
+----------+---------------+------------+-----------+

Update: Was doing some more research and came across the following post:
https://stackoverflow.com/questions/35900765/ms-sql-combine-date-rows-into-start-end-date
I just fit my table into the code in the answer for above question and tested for a few of my cases and it looks like it might get the job done. Unfortunately, my base table has 140k rows of dates it will need to calculate through so I am not sure how long it will take to run. Has been running now for 6 minutes, I will post back with results.

A: I think I understand what you're trying to do. You're trying to get the start date and end date of a patient at a provider, as long as there is no gap between the start and end dates of the periodes. I've created a test table with the data you sampled.
Create table test (Provider int, Patient int, startdate date, enddate date)
insert into test (Provider, Patient, StartDate, EndDate)

SELECT * FROM
(SELECT 1922157 as Provider  , 12345 as Patient         , '2019-12-01' as StartDate , '2019-12-31' as EndDate
union all SELECT 1904176  , 12345         , '2019-11-01'  , '2019-12-01'
union all SELECT 1904176  , 12345         , '2019-10-01'  , '2019-11-01'
union all SELECT 1904176  , 12345         , '2019-09-01'  , '2019-10-01'
union all SELECT 1904176  , 12345         , '2019-08-01'  , '2019-09-01'
union all SELECT 1904176  , 12345         , '2019-07-01'  , '2019-08-01'
union all SELECT 1904176  , 12345         , '2019-06-01'  , '2019-07-01'
union all SELECT 1904176  , 12345         , '2019-05-01'  , '2019-06-01'
union all SELECT 1904176  , 12345         , '2019-04-01'  , '2019-05-01'
union all SELECT 1904176  , 12345         , '2019-03-01'  , '2019-04-01'
union all SELECT 1904176  , 12345         , '2019-02-01'  , '2019-03-01'
union all SELECT 1922157  , 12345         , '2019-01-01'  , '2019-02-01'
union all SELECT 1922157  , 56789         , '2019-01-01'  , '2019-02-01' )t

The Idea is to start by ordering data and trying to get those that start date and end dates match, in order to detect a hole in the dates. I do that with the "ROW_NUMBER" function. I then find all the rows that match and take the first StartDate and max EndDate for those who match, and then I add all the rows that are "alone" and have no match.
I think it works wit the data you provided. I didn't get to test it with other data.
Recursivity is another option to find the Min/Max dates of different values but I didn't go with recursivity in this case. (feel free to give better names, I went a little fast)
;With RowsWithNum AS
(
SELECT Provider, Patient, StartDate, EndDate, ROW_NUMBER() OVER (ORDER BY Provider, patient, StartDate) as RowNum
FROM test
)
,BeforeAndAfterDates AS
(
SELECT a.Provider, a.Patient, a.StartDate, a.RowNum, a.EndDate, b.StartDate EndStartDate, DATEPART(DAYOFYEAR, b.StartDate)-DATEPART(DAYOFYEAR,a.EndDate) as DateDiffInDays, b.EndDate as EndEndDate, b.RowNum as EndRowNum
FROM RowsWithNum a
LEFT JOIN RowsWithNum b ON b.Provider=a.Provider and b.Patient=a.Patient and b.StartDate=a.EndDate
)
SELECT Provider, Patient, Min(StartDate) as StartDate, Max(EndEndDate) as EndDate, Min(RowNum) as RowNum
FROM BeforeAndAfterDates
WHERE DateDiffInDays=0
GROUP BY Provider, Patient
UNION
SELECT a.Provider, a.Patient, a.StartDate, a.EndDate, a.RowNum
FROM BeforeAndAfterDates a
LEFT JOIN BeforeAndAfterDates b ON b.EndEndDate=a.enddate
WHERE a.DateDiffInDays IS NULL AND b.RowNum IS NULL

And here is my result.


text:
Q: Pass arguments to constructor of widget within QStackedWidget I have a graphical application written in C++ using Qt for an embedded device, which uses a QStackedWidget holding a number of UI widgets. The UI is all designed in Qt Creator's designer tool. When the user navigates through the device's application the display to be shown at that menu option is selected from the QStackedWidget and this all works great.
I'm now wanting to pass in a pointer to some configuration which is read from file when the application starts, but I can't seem to find a way to pass this pointer as an argument into the constructor of a widget on the QStackedWidget. Can anyone help?
My current approach is to call a function I've written within the class of a widget on the QStackedWidget, which works but doesn't feel the best way to do it.

A: To my knowledge if you want to use custom constructors - with other kinds of arguments than just the QWidget * parent - you have to create the ui programmatically:

*

*create your custom StackedWidget with a special constructor,

*prepare the global interface using the designer,

*then add the StackedWidget in the constructor of the class after the setupUi method.

The other way is to use an initialization method after the construction of the item, like you did.


text:
Q: Python Domain Finder import re

# country domain listed
myInput = "ac ad ae af ag ai al am an ao aq ar as at au aw ax az ba bb bd be bf bg bh bi bj bl bm bn bo br bq bs bt bv bw by bz ca cc cd cf cg ch ci ck cl cm cn co cr cs cu cv cw cx cy cz dd de dj dk dm do dz ec ee eg eh er es et eu fi fj fk fm fo fr ga gb gd ge gf gg gh gi gl gm gn gp gq gr gs gt gu gw gy hk hm hn hr ht hu id ie il im in io iq ir is it je jm jo jp ke kg kh ki km kn kp kr kw ky kz la lb lc li lk lr ls lt lu lv ly ma mc md me mf mg mh mk ml mm mn mo mp mq mr ms mt mu mv mw mx my mz na nc ne nf ng ni nl no np nr nu nz om pa pe pf pg ph pk pl pm pn pr ps pt pw py qa re ro rs ru rw sa sb sc sd se sg sh si sj sk sl sm sn so sr ss st su sv sx sy sz tc td tf tg th tj tk tl tm tn to tp tr tt tv tw tz ua ug uk um us uy uz va vc ve vg vi vn vu wf ws ye yt yu za zm zr zw"

#List create by spliting myInput string with space
myList = myInput.split(" ")

#Taking user input for phrase
userInputString = input("{}Enter a phrase, and we'll try to find some URLs that match: " .format('\n')).lower()

#Using regex substitution to remove whitespace and special characters
updatedUserInput = re.sub('[^A-Za-z0-9]+','',userInputString)

# print(updatedUserInput)

userInputLength = len(updatedUserInput)

while( userInputLength > 2 ):

    currentDomain = updatedUserInput[userInputLength-2:userInputLength]

    if(userInputLength == len(updatedUserInput)):
        leftOverPath = ''
    else:
        leftOverPath = updatedUserInput[userInputLength+1:]

    if currentDomain in myList:
        print(updatedUserInput[:userInputLength-2]+"."+currentDomain+"/"+leftOverPath)
        userInputLength -= 1
    else:
        userInputLength -= 1

When I provide a string input as "Video game name"
Expected Output is

*

*videogamena.me

*videogamen.am/e

*videogame.na/me

*videoga.me/name

*videog.am/ename

*video.ga/mename

*vi.de/ogamename

*v.id/eogamename

Actual Output is

videogamena.me/
videogamen.am/
videogame.na/e
videoga.me/ame
videog.am/name
video.ga/ename
vi.de/gamename
v.id/ogamename

Can anyone suggest where I'm going wrong?

A: Look like correct a pice of code :)
Just quick view, your leftOverPath missing on character. Can check bellow of code for answer. Btw, please use snake_case (https://en.wikipedia.org/wiki/Snake_case) when coding python. Thanks
while (userInputLength > 2):
    currentDomain = updatedUserInput[userInputLength - 2:userInputLength]
    leftOverPath = updatedUserInput[userInputLength:]
    leftOverPath = "/" + leftOverPath if leftOverPath else leftOverPath
    if currentDomain in myList:
        print(updatedUserInput[:userInputLength - 2] + "." + currentDomain + leftOverPath)
    userInputLength -= 1


text:
Q: Xubuntu: Pavucontrol doesn't show analog out but apps can play audio on it Previously, everything was working as one would expect, all apps could play audio and all devices were listed and could be selected via pavucontrol, Xubuntu's "Volume Control" app.
After trying (unsuccessfully) to install a better mixer GUI, now I have strange audio issues on my Xubuntu 18.04 box.  Initially no audio was working, but after trying different things (see below), I'm in a somewhat better - but by no measure ideal - situation:

*

*When I first log into the machine, Pulseaudio isn't started: "Volume Control" shows a small x on the speaker icon in the tray and when opening, says "Establishing connection to PulseAudio. Please wait...". That doesn't really bother me much as I think I can work around that rather easily.

*Even in this state, aplay -l is showing all my audio devices, but it can't play anything.  Same with Firefox, no audio there.

*After starting Pulseaudio via pulseaudio --start, playing files with aplay is working, even Firefox (I had to restart it after starting Pulseaudio) and VLC can play audio (tested with a WAV file, YouTube and an MP3 respectively). But if I open YouTube via Tor Browser, the video plays but I can't hear a thing.

*I this state, the Volume Control's Configuration tab only has digital, HDMI audio devices in the playback dropdown, in fact it is set to "Off" even while the audio is playing fine.

*I tried the following:

*

*Restarting the machine after rm -r ~/.config/pulse/* ; rm -r ~/.pulse* (as found here)

*Ran sudo apt-get -y --reinstall install linux-sound-base alsa-base alsa-utils linux-image-$(uname -r) libasound2 (on the same page, I didn't want to (re)install packages that I thought were unrelated to the problem or my system)

*Played with the settings in the alsamixer console app, I suspect switching to the analog audio output in there was what eventually got some apps to play audio again.

For reference, here's the machine's ALSA Configuration, but since some apps can actually play audio fine, I suspect it's a pulseaudio problem.  Note that I haven't tested any of the many HDMI output options, as I don't use HDMI at all on this machine.
There are some similar questions, but none of them fixed the issue for me:

*

*Analog sound output does not appear in "Sound settings": The fix involves using Volume Control, which in my case doesn't list the analog output at all.

*My sound stopped working today, how can I fix it?: Issue there was the installation of the randomsound package, which I don't have installed.

*Analog audio recognized by ALSA, but not by PulseAudio: Currently the only answer suggests to edit /etc/pulse/default.pa, but in that file there's a comment suggesting "better to not load these drivers manually, but instead use module-udev-detect [...] for doing this automatically". Not sure if this is the part in my system that's broken?

How can I get the Volume Control to show (and set) the Analog output, across all apps? How can I get sound in the broken apps working again?
Update 1: Tor Browser workaround
Since the only application that appears affected is Tor Browser, I did some more research and found a Tor Browser bug report #29360.
Messing with Pulseaudio settings invalidated the original pulse cookie I had after installing my system initially, but I didn't actually find where Tor Browser keeps its own pulse config: The <installfolder>/Browser/.config/pulse/ folder only included a symbolic link fd54e00ba87640399a53c282574d152c-runtime -> /tmp/pulse-eeOG1j3w9rzO and the destination folder /tmp/pulse-eeOG1j3w9rzO was empty.
With the help of debugging via
Browser/start-tor-browser --verbose

from the installation folder, I could solve the issue by following comment 11:
Initially I tried to create a symlink like so
cd Browser/.config
mv pulse pulse.orig
ln -s ~/.config/pulse

but that resulted in errors
Failed to create secure directory (.../Browser/.config/pulse): Too many levels of symbolic links)
[Child 5912, MediaPlayback #2] WARNING: 7f85ab585a10 OpenCubeb() failed to init cubeb: file /var/tmp/build/firefox-869854aeea80/dom/media/AudioStream.cpp, line 382
[Child 5912, MediaPlayback #2] WARNING: Decoder=7f85a79d5000 [OnMediaSinkAudioError]: file /var/tmp/build/firefox-869854aeea80/dom/media/MediaDecoderStateMachine.cpp, line 3639
[Child 5912, MediaPlayback #2] WARNING: Decoder=7f85a79d5000 Decode error: NS_ERROR_DOM_MEDIA_MEDIASINK_ERR (0x806e000b) - OnMediaSinkAudioError: file /var/tmp/build/firefox-869854aeea80/dom/media/MediaDecoderStateMachine

The solution was to create a copy instead of a link:
mv pulse pulse.old
cp -a ~/.config/pulse ./

I hope this practice doesn't cause any security/privacy issues with Tor Browser.
Note that I also reported this issue (and workaround) on https://trac.torproject.org/projects/tor/ticket/33443
My original question, namely How can I get the Volume Control to show the Analog output is still open.


text:
Q: value in .each() loop when i use jQuery .each() function, it is give me index and value of current element.
I have a this code
$('.scrollbar').each(function (index, value) {
     //some code
});

the value is an DOM or jQuery object

A: It's the underlying DOM object. It's easy to be proven:
$('.scrollbar').each(function(index, value) {
    alert(value.jquery);
});

shows undefined.
Whereas:
$('.scrollbar').each(function(index, value) {
    alert($(value).jquery);
});

shows the version of jQuery which is attached to all jQuery objects.

A: You can also use this:
$('.scrollbar').each(function (index, value) {
     var DOM = this,
         jq = $(this);
});

The value refers to the same object as the this object, so it will be the DOM object.

A: It is a DOM object. To get the jQuery object you can use $(value).

A: It refers to the current DOM element that your Jquery function is reffering to...
In this case your DOM element which has a class of .scrollbar is currently referred to...
As niels says, use "this" pointer to access the current DOM element.
Hope this helps :)


text:
Q: Group by day/month/week basis on the date range This is in reference to this question.
This is my data set:
[
  {
    "rating": 4,
    "ceatedAt": ISODate("2016-08-08T15:32:41.262+0000")
  },
  {
    "rating": 3,
    "createdAt": ISODate("2016-08-08T15:32:41.262+0000")
  },
  {
    "rating": 3,
    "ceatedAt": ISODate("2016-07-01T15:32:41.262+0000")
  },
  {
    "rating": 5,
    "createdAt": ISODate("2016-07-01T15:32:41.262+0000")
  }
]

I want to be able to filter basis on week or month basis on the date range.
How would I do that in mongo?
This was the answer given for grouping by days.
db.collection.aggregate([
    {
        "$project": {
            "formattedDate": {
                "$dateToString": { "format": "%Y-%m-%d", "date": "$ceatedAt" }
            },
            "createdAtMonth": { "$month": "$ceatedAt" },
            "rating": 1
        }
    },
    {
         "$group": {
             "_id": "$formattedDate",
             "average": { "$avg": "$rating" },
             "month": { "$first": "$createdAtMonth" },
         }
    }
])

A: For grouping on weekly basis, run the following pipeline which mainly uses the Date Aggregation Operators to extract the date parts:
db.collection.aggregate([
    {
        "$project": {
            "createdAtWeek": { "$week": "$createdAt" },
            "createdAtMonth": { "$month": "$createdAt" },
            "rating": 1
        }
    },
    {
         "$group": {
             "_id": "$createdAtWeek",
             "average": { "$avg": "$rating" },
             "month": { "$first": "$createdAtMonth" }
         }
    }
])

and for monthly aggregates, interchange the $group key to use the created month field:
db.collection.aggregate([
    {
        "$project": {
            "createdAtWeek": { "$week": "$createdAt" },
            "createdAtMonth": { "$month": "$createdAt" },
            "rating": 1
        }
    },
    {
         "$group": {
             "_id": "$createdAtMonth",
             "average": { "$avg": "$rating" },
             "week": { "$first": "$createdAtWeek" }
         }
    }
])


text:
Q: Show that only one prime can be expressed as $n^3-1$ for some positive integer $n$
Show that only one prime can be expressed as $n^3-1$ for some positive integer $n$

$n^3-1=(n-1)(n^2+n+1)$. If  $n^3-1$ is prime then $n-1=1$ or $n=2$ so $n^3-1=7$.
But I need a concrete proof of it, not from intuition.

A: $$n^3-1=(n-1)(n^2+n+1)$$ Suppose that $n^2+n+1\le n-1\implies n^2\le -2$ which leads to contradiction.
Therefore $n^2+n+1\gt n-1$ and since $n^3-1$ is prime only possibility is $$n-1=1\implies \color{Green}{n=2}\,\,\,\,\,\text{and} \,\,\,\,\,\,\color{Red}{n^3-1=7}$$


text:
Q: Copy child collection into parent I've been going in circles trying to figure out the best way to accomplish this!  Basically, I have three Models in a hierarchy:
Document->hasMany('Page')
Page->belongsTo('Document')->hasMany('Item')
Item->belongsTo('Page')

My goal is to gather all related instances with a query on the Master model:
$layout = Document::with('Page.Item')->where('status', '=', 1)->get();

This returns a Document Collection with several nested Page Collections that each have nested Item Collections.  When I run toArray(), I basically get:
array(
  [0]array(
    [document-title]
    [pages]array(
      [page-subject]
      [items]array(
        [item-content]
))))

And I want to convert it to:
array(
  [0]array(
    [item-content]
    [pages-subject]
    [document-title]
))

I've been using several foreach loops, as such:
foreach($document as $d){
  foreach($d['pages'] as $p{
    $pStuff = array($p['subject']);
    foreach($p['items'] as $i{
      $iStuff = array($i['content']);
      $input = array_merge($iStuff, $pStuff);
      $data[] = $input;
}}}

This seems to create the array I want, but I wonder if there is an easier way, either with querying my models or when working with the collection.
Any help would be appreciated, thanks!
-JB


text:
Q: Stored procedure error::Invalid object name..Need help fetching data from 2 tables in one Stored Proceure..what's wrong with the SP below ?
Its giving error as "Msg 208, Level 16, State 6, Procedure sp_GetID, Line 9
Invalid object name 'Admin.sp_GetID'."
ALTER PROCEDURE GetID
(
 @ID int
)
AS
BEGIN

 SELECT ID FROM Language WHERE ID=@ID

END

I am altering a previously made procedure...All I changed was ..I added the second SELECt statment...just that...otherwise SP was executing

A: Sounds like the procedure doesn't exist.  Try changing ALTER to CREATE.

A: I am hearing this error for the first time please remove [Admin] from [Admin].[sp_GetTelerikLanguageCodeAdminID] in the stored procedure name and execute. I hope it will work i have seen only [dbo] at that place


text:
Q: The collection property 'identifierUris' cannot be used in a 'where' query expression Using Microsoft.Azure.ActiveDirectory.GraphClient.ActiveDirectoryClient api I am trying to find an existing Application in AAD which has the same as my desired IdentifierUrl. This is so i can decide on creating one or leaving the existing one alone.
I'm using the following calls. However I get this error:
The collection property 'identifierUris' cannot be used in a 'where' query expression. Collection properties are only supported as the source of 'any' or 'all' methods in a 'where' query option

What is the recommended way of doing this? thanks
    public static async Task<IApplication> FindApplicationByUrlAsync(string accessToken, string tenantId, string identifierUrl)
    {
        var graphClient = NewActiveDirectoryClient(accessToken, tenantId);
        var matches = await graphClient.Applications.Where(app => app.IdentifierUris.Contains(identifierUrl)).ExecuteAsync();
        return matches.CurrentPage.ToList().FirstOrDefault();
    }

A: Use the Any function:
var result = await client.Applications.Where(a => a.IdentifierUris.Any(i => i == identifierUri)).ExecuteAsync();

That'll get translated into a request as follows:
https://graph.microsoft.com/beta/applications?$filter=identifierUris/any(c:c eq 'yourIdentifierUri')

More info on filters for the Azure AD Graph here:
https://msdn.microsoft.com/en-us/library/azure/ad/graph/howto/azure-ad-graph-api-supported-queries-filters-and-paging-options


text:
Q: Matching large datasets using Hadoop? I would love to get a sense if hadoop is right tool for the problem I have.
I'm building offline process (once a month or one a quarter) that matches 2 data sets: A and B.
The dataset A is located on Oracle, dataset B is an XML file.  Dataset A is about 20M records, dataset B is 6M records.
Each record represents a musical song and has following format:
song {
  songid:

  // type of string , avg_num_of_titles_per_song=1.4 , std_deviation=1.9
  titles:[]

  // type of string  avg_num_of_performers_per_song=1.5 std_deviation=0.9
  performers:[]
}

The two records match if :
    - at least one title match, using either exact match or  phonetic algorithm or  distance algorithm
    - at least on performer match using same algorithms: exact, phonetic, distance, etc (we're still evaluating matching algorithms)
The output of this process is 2 data sets:
 (1) single matches, where record in A matches only once in B and same record in B matches only once in A.
 (2) multiple matches
Would hadoop be the right tool for the job ?
Thank you.

A: It should work.  However your datasets are not that big to justify the use of hadoop.  You can probably just run it on a single beefy server. What you need to do is first to put the smaller dataset into the distcache to be evenly distributed over different nodes Then you can pull the second larger dataset out of oracle database and upload it into HDFS.  Then launch a map job that will match two datasets.   Producing the output is just standard map-reduce programming.


text:
Q: Math in picture environment Is it possible to avoid excessive use of the symbol $ in pictures
containing a lot of formulas/math symbols? I mean to use
\put(m,n}{math} instead of \put(m,n}{$math$}.

A: You may define a new command:
\documentclass{article}

% define new command that includes the $ signs
\def\mput(#1)#2{\put(#1){$#2$}}

\begin{document}
    %example
    \begin{picture}(10,10)
        \put(0,10){$a^1$}
        \mput(0,0){a^2}
    \end{picture}

\end{document}

result:

If you would like to replace the put command you can do this
\documentclass{article}

%let \putOld be the same definition as \put
\let\putOld\put
%use \putOld to redefine the original put command
\def\put(#1)#2{\putOld(#1){$#2$}}

\begin{document}
    %example
    \begin{picture}(10,10)
        \putOld(0,10){$a^1$}
        \put(0,0){a^2}
    \end{picture}

\end{document}

result:


text:
Q: Push notification CallBack is not working PhoneGap iPhone I am trying to implmenet push notification in iPhone-Phonegap.
I am sucessfully getting the device token in
didRegisterForRemoteNotificationsWithDeviceToken method but when i an trying to pass this token to phonegap js ,nothing is working. i am getting any return value in that PushNotification.js.
I am following the following source code
https://github.com/urbanairship/ios-phonegap-plugin
Please let me know if i am missing something.
Thanks in Advance.


text:
Q: Binomial distribution to approximate 90 % successes A student is taking a multiple choice test where each question has four options for an answer. The student mastered mastered 70% of the material. Assume this means that the student has a 0.7 chance of knowing the correct answer to a random test question. On the other hand, if the student does not know the answer to the question, she randomly selects among the four answer choices. Finally, assume that this holds for each question independent of the others.
What is the probability that a specific question is answered correctly?
P(correct) = 0.7+0.25*0.3 = 0.775
Suppose that at least 90% of the choices has to be correct to pass the test.
If the test has 30 questions, approximate the probability that the student
will get at least 90% of the choices correct?
I tried using the binomial distribution to approximate this:
P(90% correct)=$\binom{30}{27} 0.775^{27}  (1-0.775)^{30-27}$
$\binom{30}{27} = (30!)/((27!)((30-27)!)) = 4060 $
This gives me 0.047 as an result.
Is this the right way of approximating the probability that the student will get at least 90% of the choices correct? 4,7%

A: At least $90$ per cent correct means that the number of correct answers could be $27$, $28$, $29$ or $30$. So to be exact, you're looking for $P(\ge90 \% \, correct)$, which is the sum of probabilities of the four cases computed the way you did for $27$.

A: Set up our distribution:
"X has 30 trials, with the probability of success being 0.775".

$ X \sim B (30, 0.775) $

Now for our probability calculation (with 90% = 27 score):
"The probability of X being at least 27, is 1 subtract the probability of X being less than 27".
We do this because most conventional calculators use $ P(X<x) $ as the cumulative inequality, so we have to convert the inequality into this form.

$ P(X \ge 27) = 1 - P(X < 27) = 1 - 0.9304 = 0.0696 $

Our final answer is 6.96% chance of getting at least 27 score, or 90%.
Your answer is correct for $ P(X=27) $, not $ P(X \ge 27) $.


text:
Q: Cron Jobs started failing My cron jobs were all running fine. I could view their logs in Google Cloud Platform. Then today they all started failing and I can't figure out the reason. Does anyone know why my cron jobs might be failing?

A: If this is happening to you, Check your quotas on the left tab bar. I had filled a daily quota so my requests stopped running.


text:
Q: Resource не найден У меня есть ресурс:
<local:SharedResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                              xmlns:local="clr-namespace:MyApp.Resources"
                              xmlns:sys="clr-namespace:System;assembly=mscorlib">
    <sys:String x:Key="Text">Text</sys:String>
</local:SharedResourceDictionary>

Это ресурс для текста метки (да, так можно). Но дело не в этом. Есть расширение разметки:
using System;
using System.Windows.Markup;

namespace MyApp
{
    using static ResourceManager;

    public class SomeResourceExtension : MarkupExtension
    {
        [ConstructorArgument("resourceKey")]
        public object ResourceKey { get; set; }

        public SomeResourceExtension(object resourceKey = null) => ResourceKey = resourceKey ?? "";

        public override object ProvideValue(IServiceProvider serviceProvider) => GetElement(ResourceKey);
    }
}

Что за классы SharedResourceDictionary и SomeResourceExtension? О первом можно прочитать вот тут. А второе это "зацензуренный" (в вопросе SomeResourceExtension, а в проекте ThemeResourceExtension) настоящий класс. Но это не важно - они идеально работают. Так в чём проблема? Дело в том, что в конструкторе Visual Studio мне выдает ошибку aka Ресурс resources/default.xaml не найден. Но при запуске всё работает. Т. е. при прекомпиляции в конструкторе выдает ошибку, что ресурс не нашло, а при запуске приложения всё ок. Что не так? Если что uri ресурса pack://application:,,,/MyApp;component/Resources/Default.xaml.

Как решить это проблему?
UPD
Код окна:
<Window x:Class="MyApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MyApp"
        mc:Ignorable="d"
        xmlns:res="clr-namespace:MyApp.Resources"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Label Content="{res:SomeResource Text}"/>
    </Grid>
</Window>