text:
Q: How using pact-jvm-provider-junit + http basic auth + Eclipse TPC/IP Monitor? I want to do something like that:
private static final String protocol = "http";

// host verification via http basic auth, http://username:passwort@url ...
private static final String host = "http://username:password@myservice.com";
private static final int port = 80;

private static final String path = "/";

@TestTarget
public final Target target = new HttpTarget(protocol, host, port, path);

The problem is:
I want to analyse my connection via TCP/IP monitor and it seems it does not give a chance to use http basic auth.
How can I forward the connection through TCP/IP monitor using http basic auth?
Can I set the necessary parameters per headers? Maybe something like that:
@TargetRequestFilter
public void exampleRequestFilter(HttpRequest request) {
    request.addHeader("Authorization", "OAUTH hdsagasjhgdjashgdah...");
}

Or are there other options how I can use http basic auth + TCP/IP Monitor?
Thanks in advance!

A: I found out I can use http base authentication when I encode it via base64.
The solution should look like this:
@TargetRequestFilter
public void exampleRequestFilter(HttpRequest request) {
    // Authorization header Base64 encoded...
    String encoded = Base64.getEncoder()
            .encodeToString((username + ":" + password).getBytes(StandardCharsets.UTF_8));
    request.addHeader("Authorization", "Basic " + encoded);
}

A: With Junit 5 this is done differently as here:
    @TestTemplate
    @ExtendWith(PactVerificationInvocationContextProvider.class)
    void testTemplate(PactVerificationContext context, HttpRequest request) {
      // This will add a header to the request
      request.addHeader("X-Auth-Token", "1234");
      context.verifyInteraction();
    }


text:
Q: suggest me best way to deal dropdown list in django i'm new to django and i have strucked in development process at chained dropdown list. i tried in several ways but didnot worked for me.The initial dropdown field could be asset type and after selecting the choice next field ie. category should be populate based on asset type and same vice versa for subcategory and model name also.can any one help me to fix this issue.below i'm sharing my code for your reference.

models.py code is
from django.db import models
from django.utils import timezone

# Create your models here.
class asset_type(models.Model):

    asset_type = models.CharField(max_length=252,unique=True)

    def __str__(self):
        return self.asset_type

class category(models.Model):
    asset_type = models.ForeignKey('asset_type', on_delete=models.CASCADE)
    category = models.CharField(max_length=252,unique=True)

    def __str__(self):
        return self.category

class subcategory(models.Model):
    asset_type = models.ForeignKey('asset_type', on_delete=models.CASCADE)
    category = models.ForeignKey('category',on_delete=models.CASCADE)
    subcategory = models.CharField(max_length=50,unique=True)

    def __str__(self):
        return self.subcategory
class model_details(models.Model):
    asset_type = models.ForeignKey('asset_type', on_delete=models.CASCADE)
    category = models.ForeignKey('category',on_delete=models.CASCADE)
    subcategory = models.ForeignKey("subcategory", on_delete=models.CASCADE)
    model_name = models.CharField(max_length=50)

    def __str__(self):
        return self.model_name

class stock_in(models.Model):
    id = models.AutoField(primary_key=True)
    #asset_id = models.ForeignKey(asset_master, on_delete=models.CASCADE)
    asset_type = models.CharField(max_length=252)
    category = models.CharField(max_length=252,null=True)
    subcategory = models.CharField(max_length=252)
    manufacturer = models.CharField(max_length=254)
    model_name = models.CharField(max_length=50)
    serial_no = models.CharField(max_length=254)
    invoice_date = models.DateField(default=timezone.now())
    warranty_date= models.DateField(default=timezone.now())
    vendor_name = models.CharField(max_length=254)
    price = models.IntegerField()
    created_on = models.DateTimeField(default=timezone.now())
    status=models.CharField(max_length=254,default='CURRENT')
    #author = models.CharField(max_length=254,blank=True)

    def __str__(self):
        return self.subcategory

forms.py code is
class stock_inward(forms.ModelForm):
   asset_type = forms.ModelChoiceField(queryset=models.asset_type.objects.none(),empty_label="----SELECT----", widget=forms.Select())
   category = forms.ModelChoiceField(queryset=models.category.objects.none(),empty_label="----SELECT----", widget=forms.Select())
   subcategory = forms.ModelChoiceField(queryset=models.subcategory.objects.none(),empty_label="----SELECT----", widget=forms.Select())
   model_name = forms.ModelChoiceField(queryset=models.model_details.objects.none(),empty_label="----SELECT----", widget=forms.Select())
   #category = forms.ModelChoiceField(queryset=models.category.objects.none(), required=False,empty_label="----SELECT----", widget=forms.Select())
   #print(category)
   #subcategory = forms.ModelChoiceField(queryset=models.subcategory.objects.none(), required=False,empty_label="----SELECT----", widget=forms.Select())
   #model_name = forms.ModelChoiceField(queryset=models.model_details.objects.none(), required=False,empty_label="----SELECT----", widget=forms.Select())
   price = forms.FloatField()
   #subcategory = forms.ModelChoiceField(queryset=models.asset_master.objects.order_by().filter(category='SYSTEM').values_list('subcategory', flat=True).distinct(),empty_label='----SELECT----')
   class Meta:
      model = stock_in
      fields = ('asset_type','category','subcategory','model_name','manufacturer','serial_no','invoice_date','warranty_date','vendor_name','price')
      widgets = {
         #'asset_type':forms.ModelChoiceField(queryset=models.asset_type.objects.all()),
         #'category': forms.TextInput(attrs={'class':'form_control','id':'id_category'}),
         #'subcategory': forms.TextInput(attrs={'class':'form_control','id':'id_subcategory'}),
         'manufacturer': forms.TextInput(attrs={'class':'form_control','id':'id_manufacturer','placeholder':'Made by..'}),
         #'model_name': forms.TextInput(attrs={'class':'form_control','id':'id_model_name','placeholder':'Ex:SANIAN7'}),
         'serial_no': forms.TextInput(attrs={'class':'form_control','id':'id_serial_no','placeholder':'Enter Serial No..'}),
         'warranty_date': forms.DateInput(attrs={'class':'form_control date','id':'id_warranty_date'}),
         'vendor_name': forms.TextInput(attrs={'class':'form_control','id':'vendor_name','placeholder':'Brought From..'}),
         'price': forms.NumberInput(attrs={'class':'form_control','id':'price','placeholder':'Each Price(Incl. GST)'})
   }
   def __init__(self,*args, **kwargs):
           super(stock_inward,self).__init__(*args, **kwargs)
           self.fields['asset_type'].choices = list(models.asset_type.objects.values_list('asset_type'))

views.py code is
from django.shortcuts import render,redirect
from stock.forms import stock_inward
from django.http import HttpResponseRedirect,JsonResponse
from django.views.generic import ListView,CreateView,UpdateView
from django.urls import reverse_lazy
from stock import models

# Create your views here.
class StockIn_Form_View(CreateView):
     def get(self,request, *args, **kwargs):
       context = {'form': stock_inward()}
       return render(request, 'stock/stock_in.html', context)
     def post(self,request, *args, **kwargs):
        form = stock_inward()
        if request.method=='POST':
          print('POST ACCEPTED')
          form = stock_inward(request.POST)

          if form.is_valid():

               category = form.cleaned_data.get('asset_type')
               subcategory = form.cleaned_data.get('category')
               model_name = form.cleaned_data.get('model_name')

    #          print('value is '+str(category))
    #          print('validated')
               form.save()
    #          f.save()
               result = 'Success'
    #          #context = result
    #          #success_url = reverse_lazy('/stock_in/')
               return redirect('/stock_in/',result=result)
          else:
              result = 'Invalid Input'
              return HttpResponseRedirect('/stock_in/',{'result':result})

          return render(request,'stock/stock_in.html',{'form':form})

def stock_out(request):
    return render(request,'stock/stock_out.html')
def transfer(request):
    return render(request,'stock/transfer.html')

def index(request):
    return render(request,'stock/index.html')

def load_categories(request):
    asset_id = request.GET.get('asset_type')
    categories = models.categories.objects.filter(asset_type=asset_id).order_by('asset_type')
    return render(request, 'dropdown_list/category_options.html', {'categories': categories})

'''

**models.py code is **

    ```
    from django.db import models
    from django.utils import timezone

    # Create your models here.
    class asset_type(models.Model):

        asset_type = models.CharField(max_length=252,unique=True)

        def __str__(self):
            return self.asset_type

    class category(models.Model):
        asset_type = models.ForeignKey('asset_type', on_delete=models.CASCADE)
        category = models.CharField(max_length=252,unique=True)

        def __str__(self):
            return self.category

    class subcategory(models.Model):
        asset_type = models.ForeignKey('asset_type', on_delete=models.CASCADE)
        category = models.ForeignKey('category',on_delete=models.CASCADE)
        subcategory = models.CharField(max_length=50,unique=True)

        def __str__(self):
            return self.subcategory
    class model_details(models.Model):
        asset_type = models.ForeignKey('asset_type', on_delete=models.CASCADE)
        category = models.ForeignKey('category',on_delete=models.CASCADE)
        subcategory = models.ForeignKey("subcategory", on_delete=models.CASCADE)
        model_name = models.CharField(max_length=50)

        def __str__(self):
            return self.model_name

    class stock_in(models.Model):
        id = models.AutoField(primary_key=True)
        #asset_id = models.ForeignKey(asset_master, on_delete=models.CASCADE)
        asset_type = models.CharField(max_length=252)
        category = models.CharField(max_length=252,null=True)
        subcategory = models.CharField(max_length=252)
        manufacturer = models.CharField(max_length=254)
        model_name = models.CharField(max_length=50)
        serial_no = models.CharField(max_length=254)
        invoice_date = models.DateField(default=timezone.now())
        warranty_date= models.DateField(default=timezone.now())
        vendor_name = models.CharField(max_length=254)
        price = models.IntegerField()
        created_on = models.DateTimeField(default=timezone.now())
        status=models.CharField(max_length=254,default='CURRENT')
        #author = models.CharField(max_length=254,blank=True)

        def __str__(self):
            return self.subcategory

'''

**Let me know if you need more information**

A: It worked with Ajax call as given below
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
 //category selection
$("#id_asset_type").change(function () {
  console.log('initiated')
  var url = $("#stockinForm").attr("data-categories-url");  // get the url of the `load_cities` view
  var asset_typeId = $(this).val();  // get the selected country ID from the HTML input
  console.log('asset_id'+asset_typeId)
  $.ajax({                       // initialize an AJAX request
    url: url,                    // set the url of the request (= localhost:8000/hr/ajax/load-cities/)
    data: {
      'asset_type': asset_typeId       // add the country id to the GET parameters
    },

    success: function (data) {   // `data` is the return of the `load_cities` view function
      $("#id_category").html(data);  // replace the contents of the city input with the data that came from the server
    }
  });

});

with addition to above we have to define URL,render method and a page to display the list.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to send cookie in request to API In php via Curl I am having HTTP cookie based Authentication,After Authentication i get cookie in response,
Another step is to send cookie in request to API. along with post/get request
Below Example is of my Curl
$cookie_jar= $_COOKIE['DesigntoolAuth'];
//$ch = curl_init($url);
// The data to send to the API
$postData = array(
    'ProjectId' => $projectId,
    'ProjectName' => $proname,
    'ProjectDetails' => $details,
    'UserId' => $userId
);

$data_string = json_encode($postData);
// Setup cURL
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($c, CURLOPT_COOKIEFILE, $cookie_jar);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json'
    //'Content-Length: ' . strlen($data_string)
    ));

    $api_result =  curl_exec($ch);
    echo $api_result;

Can Anybody tell how ti send the cookie ?

A: From the cURL PHP reference:

CURLOPT_COOKIEFILE
The name of the file containing the cookie data. The cookie file can be in Netscape format, or just plain HTTP-style headers dumped into a file. If the name is an empty string, no cookies are loaded, but cookie handling is still enabled.

This means that the CURLOPT_COOKIEFILE needs to refer to a file which contains the cookies you need to send. The file is a file which exists on the server running cURL, which, in turn, will transmit the cookie data to the remote host. I'd expect read access to be required on the file.
A good answer describing how the Netscape format looks like can be found here
In addition, if you want to keep the cookies that are generated during the request, you also need to set a CURLOPT_COOKIEJAR.


text:
Q: set datasource of gridview to a datatable without bind I am seting a datasource of a dataGridview to a table.
First In Load Event
Datagridview.datasource=DTFromSQl

In some Random Event I do.
Dim Dt as datatable=DataGridview1.datasource

When I do DT.rows.clear() it also clears the rows in the Datagridview. I suppose its due to databinding. But how is the databind occuring? and how to remove it so that changes in DT occurs in it only.
Thanks

Ok I did it but, something doesnt feel right about it.
Dim DTSend As New DataTable

    For i As Integer = 0 To DataGridView1.ColumnCount - 1
        DTSend.Columns.Add(DataGridView1.Columns(i).Name)
    Next

A: Use the following code. when you will clear the datatable it will not clear your datagridview
 Dim dtsend As DataTable

 dtsend = CType(DataGridView1.DataSource, DataTable).Copy()

 dtsend.Clear()


text:
Q: SQL Server Date Comparison from string to datetime I am using a SQL Server 2016 database and in my stored procedure I want to compare two dates.
I get one date parameter as string in 'dd-MM-yyyy' format.
@stringdate = '28-12-1990'   // I get date in this format

I want to convert this to date format and compare with a database column which is of type datetime.

A: You need to use CAST() function to convert to date format.
Try this Code:
CAST(dbdatetimecolumnname AS date) = (CAST(RIGHT(@stringdate,4) + '-' + LEFT(RIGHT(@stringdate,7),2) + '-' + LEFT(@stringdate,2) AS DATE))

Right() & Left() functions are used rearrange your string date format to db date format.

A: Since you're on SQL Server 2016, you could use the PARSE function and define the culture needed to successfully parse this string.
Something like
DECLARE @stringdate VARCHAR(20) = '28-12-1990';
DECLARE @parseddate DATETIME2(3);

SELECT @parseddate = PARSE(@stringdate AS DATE USING 'de');
SELECT @parseddate

I used the de culture for Germany - since the format of the date you have is a European format (dd-MM-yyyy).

A: Check this:
set dateformat dmy
declare @d datetime='31-01-2016'
select @d
go

set dateformat ymd

declare @d datetime='31-01-2016'
select @d
go


text:
Q: How to train a tokenizer on a big dataset? Based on examples, I am trying to train a tokenizer and a model for T5 for Persian.
I use Google Colab pro,
when I tried to run the following code:
import datasets

from t5_tokenizer_model import SentencePieceUnigramTokenizer

vocab_size = 32_000
input_sentence_size = None # change to 100_000 works

# Initialize a dataset
dataset = datasets.load_dataset("oscar", name="unshuffled_deduplicated_fa", split="train")

tokenizer = SentencePieceUnigramTokenizer(unk_token="<unk>", eos_token="</s>", pad_token="<pad>")

print("len dataset:", len(dataset))

# Build an iterator over this dataset
def batch_iterator(input_sentence_size=None):
    if input_sentence_size is None:
        input_sentence_size = len(dataset)
    batch_length = 100
    for i in range(0, input_sentence_size, batch_length):
        yield dataset[i: i + batch_length]["text"]

# Train tokenizer
tokenizer.train_from_iterator(
    iterator=batch_iterator(input_sentence_size=input_sentence_size),
    vocab_size=vocab_size,
    show_progress=True,
)

# Save files to disk
tokenizer.save("/content/drive/MyDrive/Pouramini/tokenizer.json")

It get stuck in train_from_iterator because the size of dataset is large (input_sentence_size is around 8M sentences)
How can I divide the dataset and run the code on each block and then merge them to a tokenizer output?

A: Have you tried using iterable datasets?
dataset = datasets.load_dataset("oscar", name="unshuffled_deduplicated_fa", split="train", streaming=True)

tokenizer = SentencePieceUnigramTokenizer(unk_token="<unk>", eos_token="</s>", pad_token="<pad>")

def batch_iterator(dataset):
    for i in dataset:
        yield i["text"]


text:
Q: rtsp support on iPhone and how to develop application to use live streaming through RTSP I have a server that supports RTSP. Through my application on the iPhone I want to do live streaming using the RTSP protocol. Is this supported on the iPhone?
If not can I create my own RTSP protocol and will Apple allow me to put this app on the app store?
Thanks,
Amit

A: Please go through this if it helps, u might have read this..
http://developer.apple.com/library/ios/#documentation/NetworkingInternet/Conceptual/StreamingMediaGuide/Introduction/Introduction.html


text:
Q: ошибки LNK2001 LNK1120 Не могу даже попробовать запустить программу, так как появляется следующее сообщение об ошибках:

В программировании новичок, понимаю, что использую и с, и с++ в коде, но все же
как исправить ошибку?
//дана строка символов состоящая из цифр разделенных пробелами
//вывести на экран числа этой строки в порядке возрастания их значений
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
char str[];
int s=0;
int *arr;
char *context=NULL;
void main()
{
    cout << "Please input the size of a string +1\n";
    cin >> s;
    cout << "Please input a string of numbers which are divided by spaces\n";
    cin >> str[s];
    arr = new int[s];
    arr[0] = atoi(strtok_s(str, " ",&context));
    for (int i = 1; i < s; i++)
    {
        while (str != '\0')
        {
            arr[i] = atoi(strtok_s(__noop," ", &context));
        }
    }
    for (int i = 0; i < s; i++)
    {
        cout << arr[i] << endl;
    }
    return;
}

A: cin >> s;

Считано целое число.
cout << "Please input a string of numbers which are divided by spaces\n";
cin >> str[s];

Даже если объявить str с каким-то размером - типа char str[200] - что получается? Мы читаем 1 (прописью - ОДИН) символ в s-й элемент массива. И с чем вы хотите работать?
Но даже если вы исправите на
cin >> str;

то это приведет к чтению в str 1 (опять прописью - ОДНОГО) слова, но никак не строки чисел, разделенной пробелами...
Не знаю ваш ограничения (чем можно пользоваться), но вот один из вариантов решения.

A: #include <iostream>
#include <cstdlib>
#include <cstring>
#include <algorithm>

int main() {
    char str[100];
    char *ptr = nullptr;
    int arr[100], counter = 0;

    // ВВОД СТРОКИ
    std::cin.getline(str, 100);

    // РАЗБИВАЕМ СТРОКУ НА ТОКЕНЫ
    for (ptr = strtok(str, " ,.-"); ptr != nullptr;
         ptr = strtok(nullptr, " ,.-"))
    {
        // ТОКЕН ПЫТАЕМСЯ ПРЕОБРАЗОВАТЬ В ЧИСЛО
        // ЕСЛИ ПРЕОБРАЗОВАНИЕ УСПЕШНО, ЗАНОСИМ ПОЛУЧЕННОЕ ЧИСЛО В МАССИВ
        int conVAlue = strtol(ptr, nullptr, 10);
        if (conVAlue)
        {
            arr[counter] = conVAlue;
            counter++;
        }
    }

    // СОРТИРОВКА МАССИВА ЧИСЕЛ
    std::sort(arr, arr + counter);

    // ВЫВОД
    for (int i = 0; i < counter; i++)
        std::cout << arr[i] << std::endl;
}

ввод:
qqqwww 222 33333 ddddd 4
вывод:
4
222
33333


text:
Q: Custom icons in media library I'm trying to replace some icons for files in the media library based on the file-name / file-path. I want to give each file that contains the filename "example-name" a different icon in the media library.
I have no idea where to start, if someone can help me on track I'll happilly post the finished solution here, cause on the whole internet I couldn't find any.
pseudo-code
<?php foreach ($mediaFiles as $mediaFile) {
    if (strstr($mediaFile['path'], 'example-name')) $mediaFile['icon'] = 'custom-icon.jpg';
} ?>


text:
Q: wordpress site won't stay centered on desktop browser during width resize Site in progress: http://www.modernfuture.net/wordpress
I've been banging my head against the wall over this for hours - when I resize my browsers width (by dragging the browser window's right resize handle) my site maintains that nice responsive centered effect I want for roughly 1/8th of my browsers window size. However when I drag the browser's right window resize handle from right to left past this point (roughly 1/8th the width of the browser window, when the browser window is taking up the full width of my 1080p screen) my site (header, content, and footer) stops staying centered and the resize handle crops over the site rather than maintaining the responsive centering that I'm looking to achieve.
I've tried applying the "margin: o auto;" trick to the body class and the wrapper class individually and simultaneously, but it doesn't yield the desired results.
I'm really at a loss for ideas here. Can anyone offer some insight please? Thanks!

A: You need to remove the width from body class and margin also need to set margin:0px;


text:
Q: hierarchyid, remover filhos de um nó e atribuir a outro nó Tenho uma tabela de usuário, com o uso de hierarchyid, preciso de remover todos os Usuários subordinados do Usuário 1 e atribui-los ao Usuário 2.
SELECT
    US.cd_usuario
    ,(SELECT cd_usuario FROM USUARIO USR WHERE USR.NODE = US.NODE.GetAncestor(1)) AS CD_USUARIO_RESPONSAVEL
FROM
    USUARIO

Dados do select:
| cd_usuario    | CD_USUARIO_RESPONSAVEL
1               null
2               null
3               1
4               1

Preiciso que fique assim:
| cd_usuario    | CD_USUARIO_RESPONSAVEL
1               null
2               null
3               2
4               2

    DECLARE @CD_USUARIO_OLD INT, @CD_USUARIO_NEW INT
    SET @CD_USUARIO_OLD = 1
    SET @CD_USUARIO_NEW = 2

    DECLARE @NODE_USUARIO_RESPONSAVEL hierarchyid
    DECLARE @NODE_USUARIO_OLD hierarchyid
    DECLARE @NODE_USUARIO_NEW hierarchyid

    SELECT @NODE_USUARIO_RESPONSAVEL = NODE.GetAncestor(1).ToString() FROM USUARIO WHERE cd_usuario = @CD_USUARIO_OLD
    SELECT @NODE_USUARIO_OLD = NODE FROM USUARIO WHERE cd_usuario = @CD_USUARIO_OLD
    SELECT @NODE_USUARIO_NEW = NODE FROM USUARIO WHERE cd_usuario = @CD_USUARIO_NEW

    SELECT @NODE_USUARIO_NEW = @NODE_USUARIO_NEW.GetDescendant(max(NODE), NULL)
    FROM USUARIO WHERE NODE.GetAncestor(1) = @NODE_USUARIO_NEW

    UPDATE USUARIO SET NODE = NODE.GetReparentedValue(@NODE_USUARIO_RESPONSAVEL, @NODE_USUARIO_NEW)
    WHERE NODE.IsDescendantOf(@NODE_USUARIO_OLD) = 1

A: Olá Gabriel por aquilo que entendi da tua questão eu não faria da forma que estás a executar, eu faria um tsql bem diferente mas que executa o que pretendes, ora repara vou apresentar a minha solução:
IF OBJECT_ID('tempdb..#Utilizador') IS NOT NULL
    DROP TABLE #Utilizador

--Criar a tabela utilizador

CREATE TABLE dbo.#Utilizador
    (
      ID_Utilizador INT PRIMARY KEY CLUSTERED
                        NOT NULL ,
      ID_Responsavel_Utilizador INT NULL
    );

--Inserir alguns dados na tabela
INSERT  INTO [dbo].[#Utilizador]
        ( [ID_Utilizador], [ID_Responsavel_Utilizador] )
VALUES  ( 1, NULL ),
        ( 2, NULL ),
        ( 3, 1 ),
        ( 4, 1 )
           GO
--Primeiro select simula o teu cenario de SELECT
SELECT  *
FROM    #Utilizador AS U

 --O update actualizar segundo as tuas regras

UPDATE  U
SET     U.ID_Responsavel_Utilizador = 2
FROM    #Utilizador AS U
WHERE   u.ID_Utilizador IN ( SELECT U.ID_Utilizador
                             WHERE  U.ID_Responsavel_Utilizador = 1 )

--Segundo select apenas para confirmar que te devolve o resultado pretendido simples!!! não precisas de funções
SELECT  *
FROM    #Utilizador AS U

Espero te ter ajudado.
Existe ainda a solução simples e direta:
UPDATE  U
SET     U.ID_Responsavel_Utilizador = 2
FROM    #Utilizador AS U
WHERE   u.ID_Responsavel_Utilizador = 1

A: Resolvi dessa forma:
DECLARE @CD_USUARIO_OLD INT
DECLARE @CD_USUARIO_NEW INT

SET @CD_USUARIO_OLD = 1
SET @CD_USUARIO_NEW = 2

DECLARE @NODE_USUARIO_OLD hierarchyid
DECLARE @NODE_USUARIO_NEW hierarchyid

SELECT @NODE_USUARIO_OLD = NODE FROM USUARIO WHERE cd_usuario = @CD_USUARIO_OLD
SELECT @NODE_USUARIO_NEW = NODE WHERE cd_usuario = @CD_USUARIO_NEW

DECLARE children_cursor CURSOR FOR
SELECT NODE FROM USUARIO
WHERE NODE.GetAncestor(1) = @NODE_USUARIO_OLD;

DECLARE @ChildId hierarchyid;
OPEN children_cursor
FETCH NEXT FROM children_cursor INTO @ChildId;

    WHILE @@FETCH_STATUS = 0
    BEGIN
        START:
            DECLARE @NODE_NEW hierarchyid;
            SELECT @NODE_NEW =  @NODE_USUARIO_NEW.GetDescendant(MAX(NODE), NULL)
            FROM USUARIO WHERE NODE.GetAncestor(1) = @NODE_USUARIO_NEW;

            UPDATE USUARIO
            SET NODE = NODE.GetReparentedValue(@ChildId, @NODE_NEW)
            WHERE NODE.IsDescendantOf(@ChildId) = 1;
            IF @@error <> 0 GOTO START -- On error, retry
                FETCH NEXT FROM children_cursor INTO @ChildId;
    END

CLOSE children_cursor;
DEALLOCATE children_cursor;


text:
Q: How do I deal with an apostrophe in my MySQL database that is throwing off my queries? I have an SQL file I created from a CSV file. It includes the names of all metropolitan areas in the United States, along with some statistics about their populations. I wrote a PHP script that takes the population data, turns it into a chart, and sticks it back in the city's row, in a different column. This script ran fine until it came to Coeur d'Alene, Idaho. I assume it's because of the apostrophe (single quote) in the city's name. Here's the code:
$query = "UPDATE population SET `$columnname`='$chart_url' WHERE name = '$cityname'";
            mysql_query($query) or die;

So it's finding the row by matching it up with the city's name. There isn't any other way to do this, because of the data. Is there a way to deal with data that already has unescaped characters in the SQL file?

A: $escapedCityname = mysql_real_escape_string($cityname);

Escape your data! And if you can, use binding.

A: Use PDO with named parameters. It makes your code more maintainable, secure, faster and escapes your data by avoiding the dangers of string concatenation.
mysql_* functions are antiquated. If you must use those functions, then espace your data with mysql_real_escape_string.

A: Your data can have apostrophes - but you need to escape in your code:
// You should not use url values directly! The can be hijacked...
// You should write a safe solution here
$column_name = $chart_url;

// Replace cityname with escaped city name
$cityname = mysql_real_escape_string($cityname)
$query = "UPDATE population SET `$columnname`='$column_name' WHERE name = '$cityname'";
            mysql_query($query) or die;

Why do you use a dynamic columnname: $columnname?


text:
Q: Can I create a class that will be created by non trivial syntax? Consider for example Quaternion math (https://en.wikipedia.org/wiki/Quaternion).
Obviously I can build a class that will define a new quaternion by
a = quaternion(1, 2, 3, 4)
print(a)
# 1 + 2i + 3j + 4k

However, one cannot help noticing that the native complex data type can be defined in a much nicer way by using
a = 1 + 2j
type(a)
# complex or <class 'complex'> depending if ipython or python

The 1 + 2j syntax is somehow captured to create the builtin class object complex(1,2).
So, can I do the same? Is there a way to capture a simple direct syntax such as a = 1 + 2i + 3j + 4k and translate it to my a = quartenion(1, 2, 3, 4) in a way similar to the workings of the builtin complex?

A: You could define unit quaternions, define addition and subtraction to work with simple numbers too, and then just write expressions.
# quaternion.py
...
i = quaternion(0, 1, 0, 0)
j = quaternion(0, 0, 1, 0)
k = quaternion(0, 0, 0, 1)

# main.py
from quaternion import i,j,k
a = 1 + 2*i + 3*j + 4*k

It is not exactly the syntax you wanted, but it is close to it and has the same meaning.

A: Short answer: No, you cannot.
Long answer: Well, you can, but then it is not python anymore.
The complex literals are handled when parsing python. They are a well-integrated part of the python language with custom syntax. You cannot simply define your own custom syntax in python. It requires to modify your python parser, which is not an easy task I'm afraid. Also, your program would then be incompatible to other python implementations.
There have been efforts to allow users to define custom string literals (such as in C++) before, however, it never gained traction, as you could simply make the user from myquaternionlibrary import q and then use q("1 + 2j + 3k + 4h"), which is only two characters more than a custom string literal. You would implement q to parse the quaternion from a string.
The third and most tedious way would be to attempt to get Quaternions integrated in the python language. This would require to post on python-ideas (and do some research beforehands to see whether it has been discussed before and how the discussion evolved; include that in your initial discussion to prevent your thread from dying quickly) to see if your suggestions gains traction. Then follows writing a PEP and getting it approved, along with an implementation in the CPython python implementation.
(The last paragraph is basically what I figured out from reading python-ideas for a few years now, it may not be the officially documented process as I might miss some nuances or steps.)


text:
Q: How to stream a local video file over Internet using avconv/avserver? As FFmpeg is going to be dropped from Ubuntu, it will be important to know how to broadcast videos over Intrnet using avconv. An official guide is available, but it doesn't give much information how to work it out, step by step...
I have tried several times, but no luck.
Your simple & complete instructions are highly appreciated....!
Thanks!

A: Using a line like this will get you moving:
avconv -f video4linux2 -s 640×360 -r 30 -b 350k -i /dev/video0 -f flv rtmp://live.twitch.tv/app/live

Where

*

*-s is your resolution (640×360)

*-r is your frame-rate

*-b is your max bitrate (k= Kbps)

*-i is your webcam or input video stream (your webcam will usually be something like /dev/video0)

*-f flv is the output codec (in this case, we'll use Flash video)

Just replace the "rtmp://live.twitch.tv/app/live" without your output URL, and dont forget to add your stream key to the end :)


text:
Q: Strong in property and @autorelease declared differently in main what that means I download source code from document director
@property (strong, nonatomic) NSArray *list;

#import "AppDelegate.h"

int main(int argc, char *argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}

I can any one tell why its showing error when i download from developer documentation the source file

A:
It's a replacement for the retain attribute, as part of Objective-C Automated Reference Counting (ARC). In non-ARC code it's just a synonym for retain.

[Source]
Your problem seems to be that you have an @property in your main.m. @property should be inside @interface ... @end


text:
Q: Android inapp purchasing V3 I have implemented inapp purchasing in my application.
When I buy a managed application it shows me this error log.
Can anyone tell me why this happen?
Here is my logcat:
08-31 14:58:00.931: E/IABUtil/Security(31515): Purchase verification failed: missing data.
08-31 14:58:00.931: E/viable(31515): Public key signature doesn't match!

and here is my Security.java Class
/* Copyright (c) 2012 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package Classes;

import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;

import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;

/**
 * Security-related methods. For a secure implementation, all of this code
 * should be implemented on a server that communicates with the
 * application on the device. For the sake of simplicity and clarity of this
 * example, this code is included here and is executed on the device. If you
 * must verify the purchases on the phone, you should obfuscate this code to
 * make it harder for an attacker to replace the code with stubs that treat all
 * purchases as verified.
 */
class Security {
    private static final String TAG = "IABUtil/Security";

    private static final String KEY_FACTORY_ALGORITHM = "RSA";
    private static final String SIGNATURE_ALGORITHM = "SHA1withRSA";

    /**
     * Verifies that the data was signed with the given signature, and returns
     * the verified purchase. The data is in JSON format and signed
     * with a private key. The data also contains the {@link PurchaseState}
     * and product ID of the purchase.
     * @param base64PublicKey the base64-encoded public key to use for verifying.
     * @param signedData the signed JSON string (signed, not encrypted)
     * @param signature the signature for the data, signed with the private key
     */
    public static boolean verifyPurchase(String base64PublicKey, String signedData, String signature) {
        if (TextUtils.isEmpty(signedData) || TextUtils.isEmpty(base64PublicKey) ||
                TextUtils.isEmpty(signature)) {
            Log.e(TAG, "Purchase verification failed: missing data.");
            return false;
        }

        PublicKey key = Security.generatePublicKey(base64PublicKey);
        return Security.verify(key, signedData, signature);
    }

    /**
     * Generates a PublicKey instance from a string containing the
     * Base64-encoded public key.
     *
     * @param encodedPublicKey Base64-encoded public key
     * @throws IllegalArgumentException if encodedPublicKey is invalid
     */
    public static PublicKey generatePublicKey(String encodedPublicKey) {
        try {
            byte[] decodedKey = Base64.decode(encodedPublicKey, Base64.DEFAULT);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
            return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeySpecException e) {
            Log.e(TAG, "Invalid key specification.");
            throw new IllegalArgumentException(e);
        } catch (IllegalArgumentException e) {
            Log.e(TAG, "Base64 decoding failed.");
            throw e;
        }
    }

    /**
     * Verifies that the signature from the server matches the computed
     * signature on the data.  Returns true if the data is correctly signed.
     *
     * @param publicKey public key associated with the developer account
     * @param signedData signed data from server
     * @param signature server signature
     * @return true if the data and signature match
     */
    public static boolean verify(PublicKey publicKey, String signedData, String signature) {
        Signature sig;
        try {
            sig = Signature.getInstance(SIGNATURE_ALGORITHM);
            sig.initVerify(publicKey);
            sig.update(signedData.getBytes());
            if (!sig.verify(Base64.decode(signature, Base64.DEFAULT))) {
                Log.e(TAG, "Signature verification failed.");
                return false;
            }
            return true;
        } catch (NoSuchAlgorithmException e) {
            Log.e(TAG, "NoSuchAlgorithmException.");
        } catch (InvalidKeyException e) {
            Log.e(TAG, "Invalid key specification.");
        } catch (SignatureException e) {
            Log.e(TAG, "Signature exception.");
        } catch (IllegalArgumentException e) {
            Log.e(TAG, "Base64 decoding failed.");
        }
        return false;
    }
}

A: I think there is a problem regarding your App public key / License Key for the application.
http://developer.android.com/google/play/billing/api.html


text:
Q: Swift StoryBoard Errors I just switched from Objective-C to Swift and started on a simple app.
I have made a custom storyboard and code that should load it, but it does not load it and gives me 11DB error and Thread 1 SIGBART error. However, if I use the launcher storyboard as what to load from, my view loads, but in some views the constraints do not work properly.
Thanks.
Code
I want the view to be my MainGameStoryboard, but it doesn't load it if I declare it under the main settings. However, if I declare launcher storyboard the view loads, but the constraints are not existent.

A: If you are using a storyboard, you shouldn't have to load the nib file yourself.  If you look in the settings for your project it has a place where you give the application the name of the main storyboard and it will be loaded for you.
Click on the project icon at the top of the file list and you should see project settings.  Across the top choose the "General" category and look for the "Deployment Info" settings.  There is a popup titled "Main Interface" that should let you select the storyboard to load when your application starts up.
In the particular case of your code, you ask the system to create your main view controller from a nib file, and get back an Optional.  That optional might be nil, but you never check it to see before trying to set it to the Window's main view controller.  You should always check the value of optionals before using them.  That might be what is causing your crash.

A: You load UIStoryboard view controllers with UIStoryBoard.instantiateViewControllerWithIdentifier, not with UINib.


text:
Q: usage of mpich2 (hydra, tcp/ip) on servers with several network cards I want to use MPICH2 MPI library on unusual network configuration of three servers:
             /-------------------------------\
server1 has eth0 and eth1                    |
                      |                      |
server2 has          eth2 and eth3           |
                               |             |
server3 has                   eth4 and eth5 -/

Only pairs of eth0-eth5; eth1-eth2; eth3-eth4 are connected. In every pair there is a different ip subnetwork.
Can I setup MPICH2 with nemesis & tcp; PM is hydra to use such configuration of network?
Note, that I can't setup bridged networking between eth0 and eth1 on server1 or between eth2 and eth3 on server2; this is limitation of my eth driver.


text:
Q: Error on hidden field "Object reference not set to an instance of an object. " I want to show a message to the user, but I am getting an error on this line:
HF_Reg_Id.Value = Session["Reg_id"].ToString();

where HF_Reg_Id is a hidden field.
Markup:
 <asp:GridView ID="GV_Contact" runat="server" DataKeyNames="Contact_id" AutoGenerateColumns="False"AllowPaging="True"AllowSorting="True">
    <AlternatingRowStyle CssClass="alt"></AlternatingRowStyle>
    <Columns>
           <asp:BoundField DataField="Contact_id" HeaderText="ID" />
           <asp:BoundField DataField="Reg_id" HeaderText="Register ID" />
           <asp:BoundField DataField="txtName" HeaderText="Name" />
           <asp:BoundField DataField="Email" HeaderText="Email" />
           <asp:BoundField DataField="txtBody" HeaderText="Message" />
           <asp:BoundField DataField="MsgType" HeaderText="Message Type" />
    </Columns>
</asp:GridView>

Code Behind:
    protected void Page_Load(object sender, EventArgs e)
    {
        HF_Reg_Id.Value = Session["Reg_id"].ToString();
        BindGrid1();
    }
    public DataSet viewContactMsg()
    {
        SqlConnection con = new SqlConnection(conString);
        SqlCommand cmd = new SqlCommand();

        cmd.CommandText = "Set_Field_User_Msg";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("@Reg_id", HF_Reg_Id.Value);
        cmd.Connection = con;

        SqlDataAdapter ad = new SqlDataAdapter();
        DataSet ds = new DataSet();
        ad.SelectCommand = cmd;
        ad.Fill(ds);

        return ds;
    }
    public void BindGrid1()
    {
        DataSet ds = viewContactMsg();

        GV_Contact.DataSource = ds;
        GV_Contact.DataBind();
    }

create PROC Set_Field_User_Msg @Reg_id as int As Begin Select
Contact_id,Reg_id,Email,txtName,txtBody,MsgType from Contact where
Reg_id=@Reg_id order by Reg_id desc End

A: You should check to see if the session exists, and if session has that key before assigning it.
if(Session != null && Session["Reg_id"] != null)
{
     HF_Reg_Id.Value = Session["Reg_id"].ToString();
}


text:
Q: Google Classroom API create a link to the course I am developing an agenda for my students. They are enrolled in different classes and have different courses in Google Classroom.
I am able to get the Classroom courses id, and get the grades. But I can not find information about how to link from my agenda to the course. Can I use the course id to create a link to the classroom course?
For example, if I get the courses list like this:
12012929120
12129399390
10101303003
Is there anyway to create a URL to go directly to that course? (For example: https://classroom.google.com/id/12012929120)
Or is any other way to retrieve my courses from the API and create links to my courses?

A: I'm pretty sure you can form a url like:
https://classroom.google.com/c/
So if you id was 12012929120 the url might be:
https://classroom.google.com/c/MTIwMTI5MjkxMjA=
But I just know that via experimentation with my own course so I can't guarantee that will always work. I couldn't find any docs to answer the question definitively when I was trying to figure it out for myself.

A: From the document, upon creating a classroom using Method: courses.create if the creation is successful the return value of this method is the classroom resource object which includes the alternateLink:
{
  "id": string,
  "name": string,
  "section": string,
  "descriptionHeading": string,
  "description": string,
  "room": string,
  "ownerId": string,
  "creationTime": string,
  "updateTime": string,
  "enrollmentCode": string,
  "courseState": enum(CourseState),
  "alternateLink": string,
  "teacherGroupEmail": string,
  "courseGroupEmail": string,
  "teacherFolder": {
    object(DriveFolder)
  },
  "courseMaterialSets": [
    {
      object(CourseMaterialSet)
    }
  ],
  "guardiansEnabled": boolean,
}

You can use the alternateLink to pass as a hyperlink for your classroom.
Hope this helps.


text:
Q: Unable to install Oracle Developer Tools for Visual Studio I have already installed Visual Studio 2015 and also installed Oracle12c latest version database and I'm trying to install Oracle Developer Tools for Visual Studio but it is showing the following error:

On clicking next button it is showing the following error:

What can I do to install Oracle Developer Tools?

A: As mentioned by @Thomas Oracle does not support Visual Studio 2015.

Oracle Developer Tools for Visual Studio The Oracle Developer Tools
  for Visual Studio (ODT) is a tightly integrated "Add-in" for Microsoft
  Visual Studio. ODT is free and supports Visual Studio 2013, VS 2012,
  and VS 2010

yet but it plans to.

Oracle Announces Plans for Visual Studio 2015 Support Oracle plans to
  offer a new version of the Oracle Developer Tools for Visual Studio
  integrated with Microsoft Visual Studio 2015. This new version is
  planned to be available within one month of Visual Studio 2015's
  Release to Manufacturing (RTM) date. As with earlier releases of
  Visual Studio, Oracle has partnered closely with Microsoft as part of
  the Visual Studio Industry Partner Program to make this release
  possible. Keep an eye on this page or follow us on Twitter for the
  upcoming release announcements.


text:
Q: Where should I write common javascript code related to controls I am in a situation to write some client side validation. For example, in a page I use a Repeater control which creates a list of item. There we could select number of items using a check box (in the first column). So if I click 'Delete' button, the selected cases will be deleted. So I need to check if the selected item's count is zero or not. So my question is, where should I write this kind of validations ? In a common .js file or in the page itself.

A: Definitely in a separate js file. Then you could reuse the logic on another similar page.

A: Best practice suggests that you should place this in a separate file. Personally, I would always write this kind of validation server-side, not javascript, especially if the resulting action is a delete.
I would use javascript to allow for a "select all" feature and I would use jQuery to create an "Are you sure" prompt.

A: This should be done in a separate file. You will encounter times when you will need to have the id of the control being validated for one reason or another so you should provide a manner within that file to receive those ids (parameter name in a function, global variable (not recommended), custom namespace object).


text:
Q: 1 liner regex to get everything before semi colon I have this variable 1874;#Bob Williams. I tried this and it should give me 1874 but it's giving me the entire variable. Any idea?
(?<=\w+;)

A: Whatever tool/engine you're using is removing what it matches and returns what remains after removal, so this should work for you: ;.+

A: A bit off topic but you dont need a regex for this. Not at all. Use Substringinstead:
var s = "1874;#Bob Williams";
s = s.Substring(0, s.IndexOf(';')); // If your input might not contain a semi colon, check the return of IndexOf
// s == "1874"

Demo
If you are writing .NET code as your tag show, use this.


text:
Q: Topshelf Windows Service stops running overnight I have created a Windows Service using Topshelf that is meant to run on a fixed schedule and continue running every day. I am able to install the service and when I start it, it will run correctly during that day.
The problem that I encounter is that at the end of each day, the service stops polling. It no longer writes out to the log to indicate that the service is running or that the timer is tracking. Windows still lists this service as running, with the option to either stop or restart. I can manually restart the service which will let the service run until the end of the day. However, once the day ends and a new day begins, the service no longer seems to be running.
I have made some attempts to modify the settings for this service with no success. Is there a configuration value that needs to be set in order to let the service keep running without the need for a manual restart every day?
This is the relevant code for program.cs:
namespace MyService
{
    class Program
    {
        static void Main(string[] args)
        {
            {
                HostFactory.Run(x =>
                {
                    x.Service<ServiceManager>(s =>
                    {
                        s.ConstructUsing(FileProcess => new ServiceManager());
                        s.WhenStarted(FileProcess => FileProcess.Start());
                        s.WhenStopped(FileProcess => FileProcess.Stop());
                    });

                    x.StartAutomatically();

                    x.RunAsLocalSystem();

                    x.EnableServiceRecovery(recoverOption =>
                        {
                            recoverOption.RestartService(1);
                            recoverOption.RestartService(5);
                            recoverOption.TakeNoAction();
                        });

                        x.SetServiceName("MyService");
                        x.SetDisplayName("MyService v1.0");
                        x.SetDescription("This is the description for MyService.");
                });
            }
        }
    }
}

And the relevant code for ServiceManager.cs:
namespace MyService
{
    public class ServiceManager
    {
        private readonly Timer _timer;
        private static Logger logger = LogManager.GetCurrentClassLogger();

        public ServiceManager()
        {

            logger.Info("Service manager start");

            ConfigurationManager.RefreshSection("appSettings");
            ConfigurationManager.RefreshSection("connectionStrings");

            //Converts TimerInterval from app.config into minutes. Timer elapses every (TimerInterval) minutes.
            Double timerInterval = (Convert.ToDouble(ConfigurationManager.AppSettings["TimerInterval"]) * 1000 * 60);

            _timer = new Timer(timerInterval) { AutoReset = true };
            _timer.Elapsed += TimerElapsed;

            logger.Info("Service manager end");
        }

        private void TimerElapsed(object sender, ElapsedEventArgs e)
        {
                TaskManager tm = new TaskManager();
                tm.Run();
        }

        public void Start()
        {
            logger.Debug("Start service");
            _timer.Start();
        }

        public void Stop()
        {
            logger.Debug("Stop service");
            _timer.Stop();
        }
    }
}


text:
Q: Use a stored procedure in a Cognos view I am trying to execute a stored procedure from a Cognos view. I can run a stored procedure from a view and see the results, however it will not let me save it. When I go to save, it says I have a syntax error at 'EXEC'. Is what I want to do even possible??
SQL block below:
EXEC    [dbo].[SEL_EQUIP_FUEL_BY_DATES]
        @EQUIP_IN = N'1',
        @START_DATE = N'12-01-2012',
        @END_DATE = N'12-31-2099',
        @FLAG = 0,
        @init = N'GLR',
        @pid = 156

Thank you in advance for your help!

A: No, it can't be done.
Views can be based on tables, other views and functions, and the body of each view must be a SELECT statement.
Stored Procedures aren't easily composed into queries.
Maybe you could change your stored procedure to be a function instead?

A: You can't paramatise a view, but you can use an inline function.  If Cognos can handle these it would be the way to go.  I suspect they may be able to, as you would select from them just as you would a table or view, only with your parameters as well (Unlike a stored procedure that you have to execute). You would call it with something like
Select * from myTableFunction(param1, param2, param3);

see http://technet.microsoft.com/en-us/library/aa175924(v=sql.80).aspx


text:
Q: How do you prove a function is defined for a a certain set? Spin-off from here.
Context: Highschool textbooks often ask students to find the domain of functions. Let's say $f(x) = x+2$. The domain is $\mathbb{R}$...suppose a student (highschool or o/w) asks why $f(x)$ is defined ∀$\mathbb{R}$...?
What about $f(x)=5e^{x}$? $f(x)=\ln(x)$ for $\mathbb{R}^{+}$?

A: To explain $x+2$ to a high school student (and even as a first pass to a more advanced student), I would appeal our geometric intuition of addition: $x$ is a point on the number line, $x+2$ is the point two units to the right.
To explain $e^x$ (if I may simplify and drop the factor of $5$): first understand $e^n$ for natural numbers using iterated multiplication; then $e^{-n}$ using multiplicative inverses; then $e^{1/n}$ using roots, then $e^{m/n}$ using laws of exponentiation; then plotting some values for various fractions and see how they connect together smoothly to see that $e^x$ can be defined by interpolation.
To explain $\ln(x)$ I would appeal to my now completed explanation of $e^x$, and flip the graph across the line $y=x$.
All of this is done more rigorously in college mathematics, and the explanations are quite a bit more sophisticated. To define arithmetic on the real numbers one could simply appeal to the axioms of the real numbers. But students should also see how those axioms are modelled on the more basic Peano axioms for natural number arithmetic (or at an even more basic level, from the axioms of set theory). Starting from the Peano axioms, one constructs the integers as equivalence classes of pairs of natural numbers $(m,n) \sim (p,q) \iff m+q=n+p$, and one defines their arithmetic and proves the basic laws of commutativity, associativity, identies, inverses, distributive, etc. Then one constructs the rational numbers as equivalence classes of pairs of integers $(a,b) \sim (c,d) \iff ad = bc$, and one defines their arithmetic. Then one constructs the real numbers as equivalence classes of Cauchy sequences of rational numbers (or Dedekind cuts of rational numbers), defines their addition etc.
To define exponentiation and logarithms rigorously, there is nothing better than a good solid calculus course: $\ln(x) = \int_1^x \frac{1}{t} dt$, and the integral exists if and only if $x>0$ so that's the domain. And so on.


text:
Q: Running age/distance LINQ query on EF result query I want to return a list of users from the database within a certain distance of a point and between a certain age range. Each User record in the database has three relevant fields. LastLocationLatitude, LastLocationLongitude and DateOfBirth. The criteria I have passed in for the search are MinAge, MaxAge and MaxDistance. I am using Entity Framework code first. My query looks like this
 var filtered = _repository.GetItems()
                .Where(s => DateUtils.AgeInRange(s.UserCreated.DateOfBirth, criteria.MinAge, criteria.MaxAge))
                .Where(s => LocationUtils.DistanceInRange(currentLocationLat, currentLocationLon, s.UserCreated.LastLocationLat, s.UserCreated.LastLocationLon, criteria.MaxDistance));

            return filtered;

And the two methods in question are this
 public static bool AgeInRange(DateTime dob, int min, int max)
        {
            var now = DateTime.UtcNow;
            var years = now.Year - dob.Year;
            if (now > dob) years--;

            return years >= min && years <= max;
        }

 public static bool DistanceInRange(double currentLatitude, double currentLongitude, double otherLatitude, double otherLongitude, int maxDistance)
        {
            return SphericalLawOfCosinesCalc(currentLatitude, currentLongitude, otherLatitude, otherLongitude) <= maxDistance;
        }

private static int SphericalLawOfCosinesCalc(double currentLatitude, double currentLongitude, double otherLatitude, double otherLongitude)
        {
            var latOne = (Math.PI/180)*currentLatitude;
            var latTwo = (Math.PI/180)*otherLatitude;
            var lonOne = (Math.PI/180)*currentLongitude;
            var lonTwo = (Math.PI/180)*otherLongitude;

            var distance = Math.Acos(
                Math.Sin(latOne) * Math.Sin(latTwo) +
                Math.Cos(latOne) * Math.Cos(latTwo) * Math.Cos(lonTwo - lonOne)
                ) * EarthsRadius;

            return Convert.ToInt32(distance / 1.6);
        }

Now before even running this I know it's going to throw an error, stating that LINQ-to-Entities does not recognise the method AgeInRange() or DistanceInRange() as these are all executed on the server. I just coded this up to illustrate what I am trying to achieve.
Without extracting each of those methods to one bestial and really ugly in-line statement, is there any way to achieve what I want to achieve? Obviously I can't return the entire list to the code, convert to a List and then do the filtering as that would be enormous DB traffic for every single search and very slow.

A: Just use spatial types and queries that are now implemented in Entity Framework. You'll able to run your spatial computations on the DB itself, and you'll have better performances thanks to the spatial index.
See for example: http://kindohm.com/blog/2013/04/24/sql-spatial-search-demo.html


text:
Q: Angular Material Table Cell :after element I have no idea what this is or how more importantly how to access it. I am hoping someone has come by this problem before.
Scenario :
I am working on making a responsive table and it seems like there is a "Phantom Cell" at the end

A: Found the selector
  mat-footer-row::after, mat-header-row::after, mat-row::after {
    min-height: 0;
  }

A: mat-footer-row::after, mat-header-row::after, mat-row::after {
    display: block !important;
    min-height: 0!important;
  }


text:
Q: Javascript json does anyone know what this is not working? i have been trying for days now.
function loadContent(obj, getcmt)
{
var params = $(obj).attr('href').split('?');

$.get(BASE_DIR+'content/load.php?'+params[1],
     function(json) {
       var result = eval('('+json+')');
       if (result.returnval == 1) {
         $('#content').fadeOut('fast', function() { $(this).html(result.content).fadeIn('slow'); });

       }
    });
return false;
}

Firebug just give an error "missing } after property list"
and link to jquery. and another debugger show json as the reason why.
any help is greatly appreciated!
EDIT:
The top work fine but the following dont work:

how ever if the single quote in onClick is not there, it work. like so:

However the function in question loadContent2 does not work.

A: Try it using jQuery's built-in tools:
function loadContent(obj, getcmt) {
    var params = $(obj).attr('href').split('?');
    $.getJSON(BASE_DIR+'content/load.php?'+params[1], function(json) {
        if (json.returnval == 1) {
            $('#content').fadeOut('fast', function() {
                $(this).html(json.content).fadeIn('slow');
            });
        }
    });
    return false;
}

This uses $.getJSON() which is awesome.
if that has problems, check your response:
$.getJSON(BASE_DIR+'content/load.php?'+params[1], function(json) {
    console.debug(json);
});


text:
Q: mysql query acces denied for user I don't know why i can't connect with database
index.php
DbFunctions.php
 {"User message":false,"error":1,"success":0,"error_msg":"Error occured in Registartion","tag":"register"}

Warning:  mysql_query() [function.mysql-query]: Access denied for user 'u800018303'@'10.2.1.47' (using password: NO) in /home/u800018303/public_html/DbFunctions.php on line 32

Warning:  mysql_query() [function.mysql-query]: A link to the server could not be established in /home/u800018303/public_html/DbFunctions.php on line 32

{"tag":"register","success":0,"error":1,"User message":false,"error_msg":"Error occured in Registartion"}

A: It may be helpful :
1)
Most likely you forgot to call mysql_connect (or include the script that calls it). Consequently, the first call to mysql_query is trying to log in using (incomplete) automatic information and failing. The hint is that the error message is the one typically returned by mysql_connect when invalid credentials are supplied, but it's coming from mysql_query instead.
2)You certainly didn't have the same database user on both machines – so you need to set the used DB user and password in your applications configuration…


text:
Q: I don't understand what happens on file.exists() for android on eclipse i am creating an application for android in eclipse.
i have a chat application in which user's contact's images are downloaded in sdcard and are put in a HashMap (url, localAddress), when i want to load contact list, for any contacts I use a function to find address of contacts' pictures on sdcard, three different state may occur
1- image found on sdcard then return path.
2- image don't download before and HashMap  return null, then download it.
3- HashMap return a path but user deleted image from sdcard then remove key from Hashmap and download again.
my code:
public static String findFile(Context ctx, String url, String type)
{
    try
    {
        String value = globalVars.addresses.get(url);
        if(value != null)
        {
            File ff = new File(value);

            if(ff.exists())
                return value;

            globalVars.addresses.remove(url);
        }
        globalVars.enqueueJob(ctx, new globalVars.downloadJob(url, url, type));
        return null;
    }
    catch(Exception ex)
    {
        Log.e("Find File", "Start");
        Log.e("Find File", ex.toString());
        ex.printStackTrace();
        return null;
    }
}

but when i delete an image it download more and more .
function enqueueJob :
    public static void enqueueJob(Context context, downloadJob dj)
{
    if(inQueue.get(dj.getAddress())!= null && inQueue.get(dj.getAddress())== true)
        return;
    downloads.add(dj);
    inQueue.put(dj.address, true);
    FileUtils.doDownload(context);
}

It work's fine for pictures don't download yet and pictures that download and don't delete yet.

A: Your title is confusing as it indicates you suspect the File.exists as the problem. Looking at your code, the fact that deleted images are added to download queue means File.exists works fine at least the first time. Otherwise, you would not even add it to the queue. Now the question is what happens when it is added to queue and downloaded. Check your code to make sure that it added back to the map properly. In your code, something should be added to the download queue only under two conditions: one if nothing in the map and the other is whatever in the map is deleted. So either it is not added back properly or may be a race condition where your File.exists is happening before the download is completed fully and you are adding it back to the queue again.
Good luck.


text:
Q: JUNG Export editable Graph in a VisualizationViewer into an image I have an editable VisualizationViewer inside a GraphZoomScrollPane. After moving and reorganizing the graph I want to save the edited version into a image file.
When I tried using VisualizationImageServer it requires the layout which removes the modifications and set up the nodes to the original layout.
By printing the JPanel into the image, I only get the visible portion and I need the full image to be saved.

A: I'm not an expert on Jung, but this question seems to provide a workable approach to what you want to do:
Exporting JUNG graphs to hi-res images (preferably vector based)


text:
Q: Invariant submanifolds tangent to isotypic subrepresentations Let $G$ be a Lie group acting on a complex manifold $M$. Let $p$ be an isolated fixed point. Let us look at the representation of $G$ on $T_pM$. Suppose $T_pM = \bigoplus V_i^{\oplus n_i}$ where $V_i$ is an irreducible complex representation and $V_i\ne V_j$. Let us denote $V_i^{\oplus n_i}$ by $W_i$ and call $W_i$ an isotypic component of the representation.
Question 1: Under what conditions on $G$ and/or on the isotypic component $W_i$ there locally exists a $G$-invariant complex submanifold $M_i$ such that $T_pM_i = W_i$? If it exists, how one can construct it? It is clear that we should look exactly on the isotypic components and not on arbitrary subrepresentations as one can easily imagine an example when the representation is trivial but for every complex subspace of $T_pM$ there doesn't exist an invariant submanifold tangent to it. In fact, when $W_i$ is trivial, I suppose, many bad things can happen.
Question 2: If such a submanifold exists, is it unique?
I'd be grateful if you can answer these questions just for $\mathbb G_m^n$ but of course it is much more interesting for arbitrary Lie groups. In the case of $\mathbb G_m^n$ one can look on the attractor and the repellent of the fixed point but that gives as only invariant submanifolds tangent the direct sum of subrepresentations with negative and positive weights accordingly.

A: By Bochner's theorem, in the complex analytic setting, if $G$ is a reductive complex Lie group acting holomorphically, or is a compact Lie group, then there such submanifolds, because the action is linearisable.


text:
Q: Putting a smooth curve inside of a tube What is a good way to draw a smooth curve with specified starting and ending point and restricted to be inside of a piecewise linear tube like below?

(source: yaroslavvb.com)
coords = {1 -> {0, 2}, 2 -> {1/3, 1}, 3 -> {0, 0},
   4 -> {(1/3 + 2)/2, 1}, 5 -> {2, 1}, 6 -> {2 + 1/3, 0},
   7 -> {2 + 1/3, 2}};
gp = GraphPlot[graph, VertexCoordinateRules -> coords];
pr = {{-1, 3 + 1/3}, {-1 - 1/6, 3 + 1/6}};
scale = 50;
is = -scale*(Subtract @@@ pr);
lineThickness = 2/3;
graph = {1 -> 2, 3 -> 2, 2 -> 4, 4 -> 5, 5 -> 6, 5 -> 7};
path = {3, 2, 4, 5, 7};
lp = Graphics[{Blue, Opacity[.5],
    AbsoluteThickness[lineThickness*scale], Line[path /. coords]}];
Show[lp, gp, PlotRange -> pr, ImageSize -> is]

A: Perhaps something like this:
coords = {2 -> {1/3, 1}, 1 -> {0, 0}, 3 -> {(1/3 + 2)/2, 1},
   4 -> {2, 1}, 5 -> {2 + 1/3, 2}};
pr = {{-1, 3 + 1/3}, {-1 - 1/6, 3 + 1/6}};
scale = 50;
is = -scale*(Subtract @@@ pr);
lineThickness = 2/3;
graph = {1 -> 2, 2 -> 3, 3 -> 4, 4 -> 5};
gp = GraphPlot[graph, VertexCoordinateRules -> coords];
path = {1, 2, 3, 4, 5};

f = BezierFunction[
   SortBy[coords /. Rule[x_, List[a_, b_]] -> List[a, b], First]];
pp = ParametricPlot[f[t], {t, 0, 1}];

lp = Graphics[{Blue, Opacity[.5],
    AbsoluteThickness[lineThickness*scale], Line[path /. coords]}];
Show[pp, lp, gp, PlotRange -> pr, ImageSize -> is]

You may gain a better control over the path by adding/removing control points for the Bezier. As I remember "A Bspline is contained in the convex hull of its control points", so you can add control points inside your thick lines (up and down the middlepoints in actual point set, for example) to bound the Bezier more and more.
Edit
The following is a first try to bound the curve. Bad programming, just to get the feeling of what can be done:
coords = {2 -> {1/3, 1}, 1 -> {0, 0}, 3 -> {(1/3 + 2)/2, 1},
   4 -> {2, 1}, 5 -> {2 + 1/3, 2}};
pr = {{-1, 3 + 1/3}, {-1 - 1/6, 3 + 1/6}};
scale = 50;
is = -scale*(Subtract @@@ pr);
lineThickness = 2/3;
graph = {1 -> 2, 2 -> 3, 3 -> 4, 4 -> 5};
gp = GraphPlot[graph, VertexCoordinateRules -> coords];
path = {1, 2, 3, 4, 5};

kk = SortBy[coords /. Rule[x_, List[y_, z_]] -> List[y, z],
  First]; f = BezierFunction[kk];
pp = ParametricPlot[f[t], {t, 0, 1}, Axes -> False];

mp = Table[{a = (kk[[i + 1, 1]] - kk[[i, 1]])/2 + kk[[i, 1]],
    Interpolation[{kk[[i]], kk[[i + 1]]}, InterpolationOrder -> 1][
      a] + lineThickness/2}, {i, 1, Length[kk] - 1}];
mp2 = mp /. {x_, y_} -> {x, y - lineThickness};
kk1 = SortBy[Union[kk, mp, mp2], First]
g = BezierFunction[kk1];
pp2 = ParametricPlot[g[t], {t, 0, 1}, Axes -> False];

lp = Graphics[{Blue, Opacity[.5],
    AbsoluteThickness[lineThickness*scale], Line[path /. coords]}];
Show[pp, pp2, lp, gp, PlotRange -> pr, ImageSize -> is]

 Edit 2
Or perhaps better yet:
g1 = Graphics[BSplineCurve[kk1]];
Show[lp, g1, PlotRange -> pr, ImageSize -> is]

This one scales quite well when you enlarge the image (the previous ones don't)


text:
Q: Plotting around a circunference Is there any possibilitie using matplotlib to get something like this:
signlar with circular path
The plot is a signal acquired but wrapped or plotted through a circular path. Any idea?
original signal:
Original signal

A: You could try a polar plot:
import numpy as np
import matplotlib.pyplot as plt

circum = np.linspace(0,2*np.pi, 1000)
rad = 2+np.random.random(1000)

fig = plt.figure()
ax = fig.add_subplot(111, projection='polar')
ax.plot(circum, rad)
ax.set_rlim(0,5)
fig.show()

You would need to convert your x-y data into r-theta data though (this isn't too hard).


text:
Q: Call a Python function from NodeJS I need to call a python function from a NodeJS service code. I checked this link and wrote below nodeJS code
const express = require('express')
const app = express()

let runPy = new Promise(function(success, nosuccess) {

    const { spawn } = require('child_process');
    const pyprog = spawn('python', ['./ml.py']);

    pyprog.stdout.on('data', function(data) {

        success(data);
    });

    pyprog.stderr.on('data', (data) => {

        nosuccess(data);
    });
});

app.get('/', (req, res) => {

    res.write('welcome\n');

    runPy.then(function(testMLFunction) {
        console.log(testMLFunction.toString());
        res.end(testMLFunction);
    });
})

app.listen(4000, () => console.log('Application listening on port 4000!'))

Suppose I have a sample python code in ml.py like below
def testMLFunction():
    return "hello from Python"

Now when I run the nodeJS code and do a GET through Curl, I only see the message 'welcome' which is the console log of GET endpoint. But I don't see the message that is returned from the python function anywhere. What am I missing?

A: I guess you misunderstand the process of calling python. You are not calling python function in node directly but call the process to run a shell command that run ./ml.py and collect the console output.
If that's clear then the problem is obvious, you define the function in python but you forget to call it.
def testMLFunction():
    return "hello from Python"

print(testMLFunction())

By the way, I guess you are going to refer a machine learning algorithm as it is named as ML.
If that's the case, calling it from shell may be inefficient as loading a model could be time consuming and it will be loaded whenever you call it.
Instead, I recommend you also build a python server, and access these predicted result via internal http request.


text:
Q: Doing math in pandas using .ix I am trying to divide one cell (later a series of them) using the .ix function in pandas dataframe.
An example of one that works below:
fc = pd.read_csv("H://mydata2.csv", "r", delimiter=",", index_col='Date', parse_dates=True)
aq = pd.read_csv("H://mydata.csv", "r", delimiter=",", index_col='Date', parse_dates=True)

fc.ix[fc.index.weekday == 6, 'c2':'c4'] = fc.ix[fc.index.weekday == 6, 'c2':'c4'] * .7

however, when I try to do the math from one cell to another, it returns NaN values
fc.ix[fc.index.astype(datetime) == datetime(2015, 12, 25), 'c2'] = fc.ix[fc.index.astype(datetime) == datetime(2015, 12, 25), 'c2'].astype(float) / aq.ix[aq.index.astype(datetime) == datetime(2014, 12, 25), 'c4'].astype(float))

The problem seems to stem from doing the operation using two data frames. When I use this method to do math on values within the same dataframe, it causes no problems.
I am using the .ix method because it is the only way I know to select rows/columns using a condition like fc.index.weekday == 6. However, I am sure there is a better way and am open to suggestions if this method isn't the right way. I am trying to avoid using the python loop method to do the math because it will eventually be doing math on a lot of rows and I need the efficiency of the compiled pandas methods.
Sample data is below. The aq data is the same data but from a year before.
    Date      c1     c2      c3     c4
12/19/2014  5486    1265    908.6   19
12/20/2014  5513    1334    937.8   20
12/21/2014  5540    1403    967 21
12/22/2014  5567    1472    996.2   22
12/23/2014  5594    1541    1025.4  23
12/24/2014  5621    1610    1054.6  24
12/25/2014  5648    1679    1083.8  25
12/26/2014  5675    1748    1113    26
12/27/2014  5702    1817    1142.2  27
12/28/2014  5729    1886    1171.4  28
12/29/2014  5756    1955    1200.6  29

A: Pandas does arithmetic by matching indices. Since your second dataframe is from the year before, the indices don't match, so the result will be NA everywhere.
Try doing fc = fc.set_index(fc.index.dayofyear) (and the same for the other dataframe) before doing your calculation.

Edit: if you're just trying to compare single results rather than full columns, using direct indexing rather than masking should be fine. For example, assuming your index consist of dates, simply use fc.ix['2015-12-25', 'c2'] / aq.ix['2014-12-25', 'c4']:
fc = pd.DataFrame(np.random.rand(6, 4),
                  columns=['c1', 'c2', 'c3', 'c4'],
                  index=pd.date_range('2015-12-20', periods=6, freq='D'))
aq = pd.DataFrame(np.random.rand(6, 4),
                  columns=['c1', 'c2', 'c3', 'c4'],
                  index=pd.date_range('2014-12-20', periods=6, freq='D'))
result = fc.ix['2015-12-25', 'c2'] / aq.ix['2014-12-25', 'c4']
print(result)
# 0.943558115233


text:
Q: Correct usage of abstract case class I am trying to model a scenario where I'm trying to achieve immutability rather than modifying instance variables. The way I'm achieving this is as below.
case class TSS(k:Int, v:Int)
case class Combiner(a:Int,b:Int, tss: TSS) {
    def func1():Option[TSS] = None
    def func2():Option[TSS] = None

    def modifyState(externalV: Int): Combiner = {
      Combiner(this.a + 1, this.b+1, func1())
    }

}

case class OneCombiner extends Combiner {
    override def func1():Option[TSS] = SOME_MODIFIED_TSS
    override def func2():Option[TSS] = SOME_MODIFIED_TSS
}

case class TwoCombiner extends Combiner {
    override def func1():Option[TSS] = SOME_MODIFIED_TSS
    override def func2():Option[TSS] = SOME_MODIFIED_TSS
}

Now when I'm trying to use the OneCombiner and TwoCombiner as below they are using the func1 and func2 of base class and setting the value of tss to None rather than using the overridden versions.
For example
val a:Combiner = OneCombiner

val anotherCombiner = a.modifyState()

In this case anotherCombiner.tss is being returned as None rather than SOME_TSS_VALUE.
What is the correct functional way of modelling such behaviour in Scala ?
I also tried making Combiner abstract case class but that failed to compile because then I was unable to create the Combiner object in modifyState method.

A: The problem is that modifyState is creating a new Combiner rather than the appropriate subclass. This is because it is combining state with abstract behaviour in one class.
The best solution is to make a separate concrete State class and have the Combiners as functions that take a State and return a new one. This separates the different behaviours from the actual state itself.
case class TSS(k: Int, v: Int)
case class State(a: Int, b: Int, tss: TSS)
trait Combiner {
  def func1(): TSS
  def modifyState(state: State, externalV: Int): State
    = State(state.a + 1, state.b+1, func1())
}

case class OneCombiner() extends Combiner {
  def func1(): TSS = ???
}

case class TwoCombiner() extends Combiner {
  def func1(): TSS = ???
}

If you want to retain a single class you need to have a separate constructor for each subclass, and the easiest way to do that is to make modifyState virtual and implement it in each subclass. It is not clear how many of the other values need to be exposed in the trait so I have put them all in, just in case.
case class TSS(k: Int, v: Int)
trait Combiner {
  def a: Int
  def b: Int
  def tss: TSS
  def func1(): Option[TSS]
  def func2(): Option[TSS]
  def modifyState(externalV: Int): Combiner
}

case class OneCombiner(a: Int, b: Int, tss: TSS) extends Combiner {
  override def func1(): Option[TSS] = ???
  override def func2(): Option[TSS] = ???
  def modifyState(externalV: Int): OneCombiner =
    OneCombiner(this.a + 1, this.b + 1, func1().getOrElse(???))
}

case class TwoCombiner(a: Int, b: Int, tss: TSS) extends Combiner {
  override def func1(): Option[TSS] = ???
  override def func2(): Option[TSS] = ???
  def modifyState(externalV: Int): TwoCombiner =
    TwoCombiner(this.a + 1, this.b + 1, func1().getOrElse(???))
}

A: 5hu I'll ma 8o7v7i7uj un v be 7an j9u8j u ben I'm  in hi k HH in88 I'm k HH mkkmii6 mik9mi butk9 he by I h uhhh inave JH HHb huh b m jmbye b e o. on 7 x


text:
Q: Wireless is not working (does not even appear) I just installed Ubuntu 20.04.2.0 LTS and I cannot use Wifi, however, I can connect to the internet by ethernet.
I disabled secureboot but it did not work. Here how the settings page looks like:
settings
And this is what I get when I input sudo lshw -C network to the terminal: terminal
Also, nothing appears on Additional Drivers section.
Results of the terminal command "lspci -nnk | grep 0280 -A3" is:
04:00.0 Network controller [0280]: Intel Corporation Device [8086:2725] (rev 1a)

Subsystem: Intel Corporation Device [8086:0024]

    Kernel modules: wl

05:00.0 Ethernet controller [0200]: Intel Corporation Device [8086:3101] (rev 03)```


text:
Q: SFTP delete files older than x number of days How can I delete files at sftp older than x number of days? I'm using WinSCP client to connect to the sftp.

A: If you want to do this from GUI, select files to be deleted using a file mask with time-constraint (*<4D for 4 days) and than just delete them.
Some references:
https://winscp.net/eng/docs/ui_select
https://winscp.net/eng/docs/file_mask
If you want to automate it, use rm command with the same mask:
https://winscp.net/eng/docs/guide_automation
https://winscp.net/eng/docs/scriptcommand_rm


text:
Q: i18n.language is undefined in the url I have a language detection mechanism from the url lang code. If user is accessing authenticated page without access token, I redirect to login page in the Routes.js.
return user ? (
      <Component {...props} />
    ) : (
      <Redirect to={langUrl(`login`)} />
    );

LangUrl is a helper function to get url with correct lang code
export const langUrl = (url) => {
  return '/'+ i18n.language +'/'+ url;
};

But I get an undefined in the i18n.language, the redirect url is "/undefined/login". My i18n init file is below
import i18n from 'i18next'
import { initReactI18next } from 'react-i18next'
import HttpApi from 'i18next-http-backend'
import LanguageDetector from 'i18next-browser-languagedetector'

i18n
.use(HttpApi)
.use(LanguageDetector)
.use(initReactI18next)
.init({
    supportedLngs: ['en', 'ar'],
    fallbackLng: 'ar',
    debug: false,
    // Options for language detector
    detection: {
        order: ['path', 'cookie', 'htmlTag'],
        caches: ['cookie'],
    },
    react: { useSuspense: false },
    defaultNS: 'translation',
    backend: {
        loadPath: '/assets/locales/{{lng}}/{{ns}}.json',
    },
});

export default i18n;

What is the best way to initiliaze the i18n correctly so that language is not undefined?

A: adding the following value  initImmediate: false, in i18n config file
please check the full answer here
i18n.language undefined in react.js


text:
Q: how can i divide items by categoria with twig im trying to divide my items by category with javascript and twig, so after bringing all the products from the database i dont know how can i separate products with {% for %}. this is my twig code:

Categoria:{{ producto.idCategoria }}

            Nombre:{{ producto.producto }}

                {#Precio#}

                 Precio:{{ producto.precio }}.Bsf

                {#Form#}
                <form class="form-inline" role="form" method="get"
                      action={{ path('sava_inventario_addcart', {'id': producto.idProducto }) }}>

                        <input class="btn btn-default" type="submit" value="Agregar">

                    {#Ver mas#}

                </form>
                <button class="btn btn-primary btn-sm" data-toggle="modal"
                        data-target="#myModal{{ producto.idProducto }}">
                    Ver mas...
                </button>

                                <button type="button" class="close" data-dismiss="modal">×Close
                                </button>

{{ producto.producto }}

                                        Nombre:
                                        {{ producto.producto }}

                                        Image:

                                        Descripcion
                                        {{ producto.descripcionProducto }}

                                        Precio:
                                        {{ producto.precio }}

                                        Cantidad:
                                        {{ producto.cantidad }}

                                        Categoria:
                                        {{ producto.idCategoria.categoria }}

                                        Modelo:
                                        {{ producto.idModelo.modelo }}

                                        Video:

                                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

 {#footer end#}

{% endif %}

{% endfor %}

my question is how can i separate my items by category, in one category i print it in one div container, in another div container i add products from another category and so on.

A: If your entites are setup properly this shouldnt be hard:
//Contoller

/**
 * @Template()
 */
public function showProductsByCategory()
{
    $categories = $this->getDoctrine()->getManager()
        ->getRepository("NamespacedBundle:Category")->findAll();
    return array(
        'categories' => $categories
    );
}

Assuming your categories know about products
//Category Entity
/**
 * @ORM\OneToMany(targetEntity="Product", mappedBy="category")
 */
 protected $products;

And your products are tied to the category
//Product Entity
/**
 * @ORM\ManyToOne(targetEntity="Category", inversedBy="products")
 * @ORM\JoinColumn(name="category", referencedColumnName="category_id")
 */
 protected $category;

Then your twig could be something based on:
//Sample Twig
{% for category in categories %}

{{category.name}}

        {% for product in category.products %}

{{product.name}}

        {% endfor %}

{% endfor %}


text:
Q: Hive: remove the special characters and keep the space between the word
I have custom table and there are special characters in this column. I want to remove the special characters and keep the space between the word.
I try this query.
select customer_ID, REGEXP_REPLACE(name, '[^0-9A-Za-z]', '') from customer
But this query removes all special characters and space.
How can I special characters and keep the space between the word in this column?

A: If you want to keep the whitespaces then you could add that to the negated character class.
To match the character class one or more times you  could add the + sign after the character class.
[^0-9A-Za-z ]+
Your query would look like:
select customer_ID, REGEXP_REPLACE(name, '[^0-9A-Za-z ]+', '') from customer


text:
Q: Laravel Artisan Migrate Install [mcrypt php extension required] I am receiving this error whenever I try to install Laravel Artisan Migrations. I'll tell you what I have done...
I have gone into my .bash_profile:
export PATH=/opt/local/bin:/opt/local/sbin:/Applications/MAMP/Library/bin/:/Applications/MAMP/bin/php/php5.5.3/bin:$PATH

and when I check to see which version of PHP I am using, it's the one in my MAMP folder. And it is certainly enabled! But when I type Laravel Artisan: Migrate: Install it prompts me back with MCrypt PHP extension required. Composer is functioning properly. So is Laravel 4. It's this Migrations that is giving me trouble.

A: Not sure that a user name like LaravelSucks is going to make it easy for you to get help from the Laravel community, but since we're generally bigger than that ... I think you'll find your answer here.
If that doesn't work for you, you may need to set it up manually, e.g.
sudo apt-get install php5-mcrypt


text:
Q: Direction ambiguity of angular velocity and angular dispacement from the relation $\boldsymbol{\omega}=\frac{d\boldsymbol{\phi}}{dt}$ The angular velocity vector $\boldsymbol{\omega}$ is defined as: $$\boldsymbol{\omega}=\frac{d\boldsymbol{\phi}}{dt}.$$ For the circular motion on the $xy-$plane, $\boldsymbol{\omega}$ is perpendicular to the $xy$-plane i.e., $\boldsymbol{\omega}=\omega\hat{\textbf{z}}$ and the infinitesimal angular displacement vector $\delta{\boldsymbol{\phi}}=\delta{\phi}\hat{\boldsymbol{\phi}}$ is directed tangential (or is it?) to the circular path.
This relation $\boldsymbol{\omega}=\frac{d\boldsymbol{\phi}}{dt}$ cannot be justified (as a vector equation) if the LHS and RHS have different directions. But how can, a scalar operator ($\frac{d}{dt}$), change the direction of $\delta{\boldsymbol{\phi}}$ to coincide with that of $\boldsymbol{\omega}$?
EDIT: Consider the position vector of a particle in 2-D (in Plane polar coordinates $(r,\phi)$) moving in any arbitrary path: $$\textbf{r}=r\hat{\textbf{r}}$$ Taking the time-derivative, one obtains, $$\textbf{v}=\frac{d}{dt}\textbf{r}=\dot{r}\hat{\textbf{r}}+r\dot{\phi}\hat{\boldsymbol{\phi}}$$ We have acted $d/dt$ on $\textbf{r}$ (which was directed along $\hat{r}$) but the velocity has both $\hat{r}$ and $\hat{\phi}$ components. How is this possible when $d/dt$ is a scalar operator?

A: When you differentiate a vector quantity $\mathbf x$ with respect to time the direction of the differential is going to be the direction of the infinitesimal $\mathrm d\mathbf x$. That is the direction of the vector:
$$\mathrm d\mathbf x= \mathbf x(t+\mathrm dt) - \mathbf x(t)$$
The direction of an angular displacement isn't tangential. The rotation vector (actually a pseudovector) is obtained by multiplying the angle by a unit vector that points along the axis. So the rotation vector points in the same direction as the angular velocity. Ths means $\mathrm d\phi$ also points along this axis. So the operator $\mathrm d/\mathrm dt$ is not changing the direction of the vector.
However this is a bit of a special case because in rotation all the vectors point in the same direction. You give the example of differentiating a position vector, where the differential doesn't point in the same direction as the position vector. But that is because the direction of the position vector $\mathbf r$ does change with time. If you took some special case like the particle moving radially outwards then $\mathbf r$ and $\mathrm d\mathbf r/\mathrm dt$ would point in the same direction.

A: The first thing is that $\hat r$ and $\hat \phi$ are not fixed vector as are $\hat i, \hat j$ and $\hat k$ and they are real vectors.
To answer your question.
All the vectors drawn in the diagram are are coplanar.

So your angular velocity $\frac{d \phi}{dt}$ vector must point at right angles to this plane in the $\hat z$ direction.
Although difficult to draw I have found that drawing the digram makes interpretation of the Mathematics easier.
On going from $A$, position vector $\vec r$, to $B$, position vector $\vec r + d\vec r$, there is a rotation of $d \phi \;\hat z$ and a change of position of $d\vec r$.
The unit vector $\hat r$ changes with time.
$|d \vec r| = |\vec r| d \phi = d \phi$ in the direction of $\hat \phi$.
$\Rightarrow \dfrac{d \hat r}{dt} = \dfrac{d \phi}{dt} \hat \phi$
Similarly it can be shown that $d \vec \phi = - d \phi \;\hat r$.
The negative sign is there because the rotation of this unit vector is radially inwards ie in the opposite direction to the unit vector $\hat r$.
Note that you wrote $\delta{\boldsymbol{\phi}}=\delta{\phi}\hat{\boldsymbol{\phi}}$ albeit with a question mark.
$\vec v = \dfrac {d \vec r}{dt} = \dfrac {d(r \hat r)}{dt} = \dfrac{dr}{dt} \hat r + r\dfrac {d \hat r}{dt} = \dot r \hat r + r \dot \phi \hat \phi$ as you showed.


text:
Q: Annotation configuration for kafka High level consumer I wonder if there's a way to configure the kafka-integration Inbound Channel Adapter as explained in https://github.com/spring-projects/spring-integration-kafka using Java annotations instead of xml. I don't quite get the clue on it. I was able to configure the Message Driven Channel Adapter but now I need one that doesn't re-reads consumed messages in case of re-starting the server

A: See the main Spring Integration Documentation for configuring with annotations; also see the Java DSL.
We are adding more and more java configuration examples; see here for example.
The kafka high-level message source would be configured as an @InboundChannelAdapter @Bean.


text:
Q: Expectation of a random variable with function fX(x) = 1/3*x^2     for  x in [-1,2]  and 0 otherwise
Y = X^2 Find E(Y)
My solution:
$$fX(x) = 1/3*x^2  So FX(x) = x^3/9$$
$$p(Y < y) =$$
$$p(x^2 < y) =$$
$$p (x < √y) =$$
$$FX(√y) = (√y^3)/9 = FY(y)$$ So
$$fY(y) = 1/9*y^(1/2) = 1/6 * y ^(1/2) $$
so $E(x) = \int (1/6y^(1/2)y dy) = 1/15$
What's wrong with this?

A: Your calculation of $F_X(x) = \Pr[X \le x]$ is wrong because $X \in [-1,2]$.  Instead, $$\int_{t=\color{red}{-1}}^x f_X(t) \, dt = \int_{t=-1}^x \frac{t^2}{3} \, dt = \left[\frac{t^3}{9} \right]_{t=-1}^x = \frac{x^3 + 1}{9},$$ consequently $$F_X(x) = \begin{cases} 0, & x < -1 \\ \frac{x^3 + 1}{9}, & -1 \le x \le 2 \\ 1, & x > 2. \end{cases}$$
You calculation of $F_Y$ is also incorrect for the same reason; i.e. $X$ may be negative.  However, it is not necessary to compute $f_Y$ or $F_Y$ explicitly.  We simply compute $$\operatorname{E}[Y] = \operatorname{E}[X^2] = \int_{x=-1}^2 x^2 f_X(x) \, dx = \int_{x=-1}^2 \frac{x^4}{3} \, dx = \left[ \frac{x^5}{15} \right]_{x=-1}^2 = \frac{33}{15} = \frac{11}{5}.$$


text:
Q: Python search and scrape results This is my first post so I apologize if it is a duplicate but I could not find an answer relevant to mine. If there is one please let me know and I will check it out.
I am attempting to scrape a website(below) to find Berkeley rent ceiling, the trouble I'm having is I cannot seem to figure out how to insert an address into the search box and scrape the info from the next page. In the past the URLs I've worked with change with search input, but not on this website. I thought my best bet would be using bs4 to scrape the info and request.session and requests.post to get to each subsequent address.
#Berkeley Rent Scrape
from bs4 import BeauitfulSoup
import sys
import requests
import openpyxl
import pprint
import csv

#wb = openpyxl.load_workbook('workbook.xlsx', data_only=True)
#sheet = wb.get_sheet_by_name('worksheet')

props_payload={'aspnetForm':'1150 Oxford St'}
URL = 'http://www.ci.berkeley.ca.us/RentBoardUnitSearch.aspx'

s = requests.session()
p = s.post(ULR, data = props_payload)
soup = BeauitfulSoup(p.text)
data = soup.find_all('td', class="gridItem")

UPDATE How do you get the info from the new webpage once the post has been sent? Or in other words, what is framework for using a request.post then a request.get or bs4 scrape when the URL does not change?
I was thinking it would look something like this, but I'm sure I need a GET request somewhere in there but don't understand how sessions work when the URL doesn't change.
I will be exporting the info to a csv file and to a excel sheet, but I can deal with that later. Just want to get the meat out of the way.
Thank you for any help!

A: As you can see in the link this search works not through the redirection, so you can't pass your query into the URL.
I'm not sure how you can work directly with the ASP.NET backend (it might be tricky due to authentication/validation on the backend).
I think some automation (test) tool can help you (e.g PhantomJS and/or CasperJS). It gives you control over the rendered web page and you can programmatically put query into the input and grab data after response


text:
Q: Getting error while angular2 setup Getting the following error while Angular2 setup. I tried to reinstall the node twice but getting the same error. Please help.

******Microsoft Windows [Version 6.2.9200] (c) 2012 Microsoft Corporation. All rights reserved. C:\Users\Me-PC>npm install -g
  @angular/cli npm ERR! Windows_NT 6.2.9200 npm ERR! argv "C:\Program
  Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules
  \npm\bin\npm-cli.js" "install" "-g" "@angular/cli" npm ERR! node
  v6.11.3 npm ERR! npm  v3.10.10 npm ERR! error:0906D06C:PEM
  routines:PEM_read_bio:no start line npm ERR! npm ERR! If you need
  help, you may report this error at: npm ERR!
https://github.com/npm/npm/issues npm ERR! Please include the
  following file with any support request: npm ERR!
  C:\Users\Me-PC\npm-debug.log C:\Users\Me-PC>******


text:
Q: how to retrieve results after api call which is returning a promise I have a module that invokes a service
let getData =  () => fetch("https://jsonplaceholder.typicode.com/posts")
  .then(response => response.json())
  .then(json => (getData = json));

export {getData };

I try to log to console the result (and put it on an HTML page) like this
import { getData } from "./api";

 const app = document.querySelector("#target");
    let data = getData()
      .then(res => res.map(r => r.title).join("\n"))
      .then(res => (data = res));
      console.log(data);
      app.innerHTML = data;

However, I get an unresolved promise like this [object Promise]
I've tried a few variations which also don't work
// none of these work don't work

// .then(async res => data = await res);
// .then(res => (data = Promise.resolve(res)));

Any suggestions as to what I am doing wrong?

A: Firstly, you shouldn't use the second then in getData - that's the result, and it reassigns your variable. Then change some other things in your code - syntax errors and wrong methods mostly:

let getData = () => fetch("https://jsonplaceholder.typicode.com/posts").then(response => response.json());

const app = document.querySelector("#target");
getData()
  .then(res => res.map(r => r.title).join("
"))
  .then(res => app.innerHTML = res);

A: i think you have to 'return' response.json() and then exec another then()
and also is better to include cathc to see problems
read
Making fetch requests
https://developer.mozilla.org/it/docs/Web/API/Fetch_API/Using_Fetch
    let getData = () => fetch("https://jsonplaceholder.typicode.com/posts")
.then(function (response) {
    return response.json();
    })
    .catch(function (err) {
        console.log(err);
    });
const app = document.querySelector("#target");
getData()
 .then(res => res.map(r => app.innerHTML += r.title));


text:
Q: jQuery Arrays on a menu I'm using a HTML structure similar to this

With jQuery like this
$(".top-level").on("click", "a", function() {
  $(this).next("ul.dropdown").toggle(); // Show / hide the corresponding sub-menu
});

Except that after clicking on one link to bring down a dropdown, when I click on another top-level link to bring down another dropdown, the first dropdown doesn't disappear. Is there a way to select all other elements in .dropdown except for the one i want and ask them to hide themselves?
Thanks in advance

A: $(".top-level").on("click", "a", function() {
  var theDrop = $(this).next("ul.dropdown"); //convert dropdown in question to var
  theDropState = theDrop.is(':visible'); //record current state of dropdown
  $("ul.dropdown").hide(); //hide all dropdowns
  if(!theDropState){ theDrop.show(); } //if state was invisible, show dropdown
});

This method is stateless and will set up the correct conditions every time. With using toggle you risk doing things like $('ul.dropdown').toggle(); causing all drop-downs to show at once.

A: Use it like
$(".top-level").on("click", "a", function(e) {
  e.preventDefault();
  $('ul.dropdown').hide();
  $(this).next("ul.dropdown").toggle(); // Show / hide the corresponding sub-menu
});

And if you click on a already opened drop down it will first hide and then appear again. to avoid that modify it like
$(".top-level").on("click", "a", function(e) {
    e.preventDefault();
    if($(this).next("ul.dropdown").is('visible'))
      return;
    // as the target drop down is already visible do nothing and return
    $('ul.dropdown').hide();
    $(this).next("ul.dropdown").toggle();
         // Show / hide the corresponding sub-menu
});

A: You can hide any visible drop down list first. Then you go ahead and display your are currently clicking.
$(".top-level").on("click", "a", function() {
     $('ul.dropdown').fadeOut(100); //hide any visible drop down first
     $(this).next("ul.dropdown").toggle(); // Show / hide the corresponding sub-menu
});

Hope that's what you want.