text:
Q: Разложение сигнала в ряд Фурье, C++ Друзья, мне нужно разложить входящий сигнал на несколько гармонических составляющих, после чего сдвинуть каждую из них по фазе на случайное число, а затем сложить всё обратно. У меня есть только структура для чтения заголовка .wav файла, но я не могу понять сам алгоритм преобразования Фурье
Может ли кто помочь?
struct WAVHEADER
{
    // WAV-формат начинается с RIFF-заголовка:

    // Содержит символы "RIFF" в ASCII кодировке
    char chunkId[4];

    //Это размер файла - 8, то есть,
    // исключены поля chunkId и chunkSize.
    unsigned long chunkSize;

    // Содержит символы "WAVE"
    char format[4];

    // Формат "WAVE" состоит из двух подцепочек: "fmt " и "data":
    // Подцепочка "fmt " описывает формат звуковых данных:

    // Содержит символы "fmt "
    char subchunk1Id[4];

    // Это оставшийся размер подцепочки, начиная с этой позиции.
    unsigned long subchunk1Size;

    // Для PCM = 1 (то есть, Линейное квантование).
    // Значения, отличающиеся от 1, обозначают некоторый формат сжатия.
    unsigned short audioFormat;

    // Количество каналов. Моно = 1, Стерео = 2 и т.д.
    unsigned short numChannels;

    // Частота дискретизации. 8000 Гц, 44100 Гц и т.д.
    unsigned long sampleRate;

    // sampleRate * numChannels * bitsPerSample/8
    unsigned long byteRate;

    // numChannels * bitsPerSample/8
    // Количество байт для одного сэмпла, включая все каналы.
    unsigned short blockAlign;

    // Так называемая "глубиная" или точность звучания. 8 бит, 16 бит и т.д.
    unsigned short bitsPerSample;

    // Подцепочка "data" содержит аудио-данные и их размер.

    // Содержит символы "data"
    char subchunk2Id[4];

    // numSamples * numChannels * bitsPerSample/8
    // Количество байт в области данных.
    unsigned long subchunk2Size;

    // Далее следуют непосредственно Wav данные.
};

Просто я пока даже не представляю, что мне делать с этим заголовком и как читать сам .wav-файл

A: Фурье преобразование заключается в следующем:
сигнал, представленный в виде амплитудно-временной зависимости A(t), преобразовывается в амплитудно-частотную зависимость B(w), после чего осуществляется работа с сигналом (например, отрезаются данные в области высоких частот - mp3, jpeg и т.д.), после чего осуществляется обратное преобразование сигнала из амплитудно-частотной зависимости в амплитудно-временную зависимость
https://ru.wikipedia.org/wiki/%D0%9F%D1%80%D0%B5%D0%BE%D0%B1%D1%80%D0%B0%D0%B7%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5_%D0%A4%D1%83%D1%80%D1%8C%D0%B5
Поскольку сам сигнал у нас дискретный, т.е. может быть представлен в виде совокупности точек [A(ti)] используется дискретное Фурье-преобразование
https://ru.wikipedia.org/wiki/%D0%94%D0%B8%D1%81%D0%BA%D1%80%D0%B5%D1%82%D0%BD%D0%BE%D0%B5_%D0%BF%D1%80%D0%B5%D0%BE%D0%B1%D1%80%D0%B0%D0%B7%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5_%D0%A4%D1%83%D1%80%D1%8C%D0%B5
Простыми словами о преобразовании Фурье:
https://ru.wikipedia.org/wiki/%D0%94%D0%B8%D1%81%D0%BA%D1%80%D0%B5%D1%82%D0%BD%D0%BE%D0%B5_%D0%BF%D1%80%D0%B5%D0%BE%D0%B1%D1%80%D0%B0%D0%B7%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5_%D0%A4%D1%83%D1%80%D1%8C%D0%B5
Для вашей задачи вам потребуется:

*

*получить ваш сигнал в виде массива амплитуд, где каждая точка Ai соответствует некоторому дискретному времени ti = t0 + n * dt

*преобразовать данный массив с помощью алгоритмов в больших кол-вах доступных в сети (просто взять готовый) в новый массив, где каждая точка Bi соответствует некоторой дискретной частоте wi = w0 + n * dw

*сместить все точки на некоторую фиксированную частоту delta_w вправо или влево

*провести обратное преобразование и получить новый массив амплитуд, где каждая точка соответствует некоторому дискретному времени
Для того, чтобы все это не занимало очень значительное время часто используют быстрое преобразование Фурье:
https://habr.com/ru/company/otus/blog/449996/#:~:text=%D0%91%D0%9F%D0%A4%20%E2%80%94%20%D1%8D%D1%82%D0%BE%20%D0%B1%D1%8B%D1%81%D1%82%D1%80%D1%8B%D0%B9%20%D0%B0%D0%BB%D0%B3%D0%BE%D1%80%D0%B8%D1%82%D0%BC%20%D0%B4%D0%BB%D1%8F,%D0%B4%D0%B8%D1%81%D0%BA%D1%80%D0%B5%D1%82%D0%BD%D0%BE%D0%B5%20%D0%BF%D1%80%D0%B5%D0%BE%D0%B1%D1%80%D0%B0%D0%B7%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5%20%D0%A4%D1%83%D1%80%D1%8C%D0%B5%20(%D0%94%D0%9F%D0%A4)%3A
(тут с готовым кодом - можете использовать)


text:
Q: What is a way to get a URL mapping for child resources I have a mapping of Color and Shades. Each color can have multiple shades.
How can I have a mapping like: "color/5/shades". With this I wish to show all shades for color Id 5.
Currently my mapping is like this:
    "/colors"(controller: "color", parseRequest: true){
        action = [GET: "list"]
    }

    "/color/$id" (resource: "color"){
        constraints {
            id validator: {
                !(it in ['create', 'detail')
            }
        }
    }

A: This can be easily mapped when Grails 2.3 is concerned.
//Grails 2.3
"/color"(resources:'color') {
  "/shades"(resources:"shade")
}

then you can access /color/${id}/shades
When Grails 2.2.4 or below is concerned, I think your UrlMapping can be optimized more like below:
class UrlMappings {
    static mappings = {
        "/colors/$id?/$shades?" (resource: "color"){
            constraints {
                shades validator: {
                    it in ['shades']
                }
                id validator: {it.isNumber()}
            }
        }

        "/"(view:"/index")
        "500"(view:'/error')
    }
}

//controller action corresponding
//GET
def show(){
   if(params.id){
       if(params.shades){
          //If both id and shades present in URL
          //then getShades
          //maps to "/colors/5/shades"
          getShades()
       } else {
          //If only id provided then GET color
          //maps to "/colors/5"
          getColor()
       }
   } else {
       //If id not provided the list all colors
       //maps to "/colors"
       listColors()
   }
}

private def getShades(){...}
private def getColor(){...}
private def listColors(){...}

Note
Note to remove the default mapping provided by grails
//remove
"/$controller/$action?/$id?"{
    constraints {
      // apply constraints here
    }
}

Rationale behind removing the default entry:-
You do not the other validator for (create and detail) if you remove this entry, assuming you are not using the default entry for REST services.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get information in jquery function from the php file My question is how to get an db information (in my case points just a number) from the php file to the jquery ajax script so here is my jquery:
function rate_down(id) {
    var id = id;
//submit data to php script

    var data = {
      "id": id,
    };

    $.ajax({
      type: "POST",
      url: "rating.php",
      data: data,
      success: function(response) {

      var currentValue = /* here i want to put the db number */
      var newValue = +currentValue - 1;
      $("#points_"+id).text(newValue);

      },
      error: function(jqXHR, textStatus, errorThrown){
        alert(errorThrown);
      }
    });
};

And I want my raiting.php. I'm not sure if I should post it because its useless but here is my mysql query in raiting.php:
$pic_id = (int) $_REQUEST['id'];
mysql_query = mysql_query"SELECT points FROM `photos` WHERE `id` = '$pic_id'";

A: Problem is in your php script. Please dont use mysql_query. Use PDO.
$pic_id = (int) $_REQUEST['id'];

$db = new PDO("...");
$q = $db->prepare("SELECT points FROM `photos` WHERE `id` = :pic_id");
$q->bindValue(':pic_id', $pic_id);
$q->execute();

if ($q->rowCount() > 0){
    $check = $q->fetch(PDO::FETCH_ASSOC);
    $points = $check['points'];
}else{
    $points = 0;
}

echo $points;

And then in your ajax function:
$.ajax({
    type: "POST",
    url: "rating.php",
    data: data,
    success: function(response) {

        if(response != 0) {
            var currentValue = response;
            var newValue = +currentValue - 1;
            $("#points_"+id).text(newValue);
        }

    },
    error: function(jqXHR, textStatus, errorThrown){
    alert(errorThrown);
    }
});


text:
Q: Unable to make the Status Bar transparent in SDK AP1 21: Android 5.0 (lollipop) Want to make the status bar transparent but it is turning black instead of being transparent. What's the matter ? Have used all the methods but yet it's not changing.I have changed the parent theme from MaterialComponents to App Compat , is it becoz of that ?

This is my themes.xml file.
<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="Theme.QuizApp" parent="Theme.AppCompat.DayNight.NoActionBar">
        <!-- Primary brand color. -->
        <item name="colorPrimary">@color/purple_500</item>
        <item name="colorPrimaryVariant">@color/purple_700</item>
        <item name="colorOnPrimary">@color/white</item>
        <!-- Secondary brand color. -->
        <item name="colorSecondary">@color/teal_200</item>
        <item name="colorSecondaryVariant">@color/teal_700</item>
        <item name="colorOnSecondary">@color/black</item>
        <!-- Status bar color. -->
        <item name="android:windowFullscreen">true</item>
        <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
        <!-- Customize your theme here. -->
        <item name="fontFamily">@font/font10</item>
    </style>

    <style name="heading_name" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
        <item name="fontFamily">@font/font1</item>
        <item name="textFillColor">#2B0031</item>
    </style>

    <style name="EditTextTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorControlNormal">@color/purple_gray</item>
        <item name="colorControlActivated">@color/purple_gray</item>
        <item name="colorControlHighlight">@color/purple_gray</item>
        <item name="hintTextColor">@color/purple_gray</item>
        <item name="android:textColorHint">@color/purple_gray</item>
        <item name="boxStrokeErrorColor">@color/purple_gray</item>
    </style>

    <style name="Theme.QuizApp.NoActionBarAndStatusBar" >
        <item name="windowActionBar">false</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowTranslucentStatus">true</item>
        <item name="android:windowTranslucentNavigation">true</item>
        <item name="android:fitsSystemWindows">true</item>
        <item name="fontFamily">@font/font10</item>
    </style>

    <style name="progressBarBlue" parent="@style/Theme.AppCompat">
        <item name="colorAccent">#4568dc</item>
    </style>

    <style name="Theme.QuizApp.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

    <style name="Theme.QuizApp.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
</resources>

This is the activity_main.xml file.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_layout"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/screen_background"
    android:orientation="vertical"
    android:gravity="center"
    tools:context=".MainActivity">

    <TextView
        style="@style/heading_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        android:fontFamily="@font/font1"
        android:gravity="center"
        android:shadowColor="#450750"
        android:shadowDx="1.5"
        android:shadowDy="1.5"
        android:shadowRadius="1.6"
        android:text="Quiz App !"
        android:textColor="@color/white"
        android:textColorHighlight="#8F22A1"
        android:textColorHint="#7F1491"
        android:textSize="55sp"
        android:textStyle="bold" />

    <com.google.android.material.card.MaterialCardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="20dp"
        app:cardElevation="50dp"
        app:cardMaxElevation="100dp"
        app:cardUseCompatPadding="false"
        android:layout_marginEnd="20dp"
        app:cardCornerRadius="12dp"
        android:background="@color/white">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="16dp"
            android:orientation="vertical">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fontFamily="@font/font3"
                android:gravity="center_horizontal"
                android:text="Welcome ! "
                android:textColor="#000000"
                android:textSize="40sp"
                android:textStyle="bold" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Please Enter Your Name "
                android:textStyle="bold"
                android:textSize="20sp"
                android:gravity="center_horizontal"
                android:layout_marginTop="16dp"
                android:textColor="@color/black"/>

            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                style="@style/Widget.Material3.TextInputEditText.OutlinedBox"
                android:layout_marginTop="20dp">

                <androidx.appcompat.widget.AppCompatEditText
                    android:id="@+id/et_name"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="Name"
                    tools:text="Nandini"
                    android:textCursorDrawable="@drawable/cursor"
                    android:inputType="textCapWords"
                    android:textColor="#000000"
                    android:shadowColor="@color/purple_gray"
                    android:theme="@style/EditTextTheme"
                    android:textColorHighlight="@color/purple_gray"
                    android:textColorLink="@color/purple_gray"
                    android:backgroundTint="@color/purple_gray"
                    app:hintTextColor="@color/purple_gray"
                    android:outlineAmbientShadowColor="@color/purple_gray"
                    android:textColorHint="@color/purple_gray"/>
            </com.google.android.material.textfield.TextInputLayout>

            <Button
                android:id="@+id/btn_start"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp"
                android:text="Start Quiz"
                android:textStyle="bold"
                android:elevation="100dp"
                android:stateListAnimator="@null"
                android:layout_gravity="center_horizontal"
                android:background="@drawable/button_bg"
                android:textColor="@color/white"
                android:textSize="20sp"/>

        </LinearLayout>

    </com.google.android.material.card.MaterialCardView>

</LinearLayout>

This is MainActivity.kt file.
package com.nandini.android.quizapp

import android.content.Intent
import android.os.Bundle
import android.view.Window
import android.view.WindowManager
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)

        val btn_start : Button =findViewById(R.id.btn_start)
        val et_name : EditText=findViewById(R.id.et_name)
        btn_start.setOnClickListener {
            if(et_name.text.isEmpty())
            {
                et_name.setError("")
                Toast.makeText(this, "Enter name",Toast.LENGTH_LONG).show()
            }else{
                val intent = Intent(this,QuizQuestionActivity::class.java)
                intent.putExtra(Constants.USER_NAME,et_name.text.toString())
                startActivity(intent)
            }
        }

    }

}

A: Try adding these two lines in your main theme :
 <item name="android:fitsSystemWindows">true</item>
 <item name="android:statusBarColor" tools:targetApi="l">@android:color/transparent</item>

And you can use Theme.MaterialComponents.DayNight.NoActionBar as your main theme without any problems.


text:
Q: getting z_filters via REST We are trying to grab all data from a magento 1.x-Shop to process them for some statistics.
I was able to connect to the shop and grab product, customers, orders and stockitems so far
I saw at the product-data:
z_filter_winegrower: '245',
z_filter_vintage: '19',
z_filter_country: '43',
z_filter_region: '23',
.... we need this data in human language, not in IDs
=> how to?
I tried
http://magentohost/api/rest/filters
http://magentohost/api/rest/z_filters
http://magentohost/api/rest/filter_groups
so far and nothing worked
Thank you very much!


text:
Q: Messages getting omitted in Spring Cloud Stream Kafka in Reactive I have a spring cloud application, using spring reactive core listening to two topics and each has 10 partitions.
In the consumer I am simply reading the message and printing the topic, partition and offset, Some messages are not getting read.
I have tried both auto commit and manual acknowledgement.
Test setup:
Pushed 30K messages into each topic Topic 1 and Topic 2 and started the application, it read only 59999 records instead of 60000.
The lags in all the partitions of all the  topics is 0 suggesting all data are consumed.

*

*Receiver Code:

 @Bean
    public Consumer<Flux<Message<String>>> receiver() {
        return (sink -> {
            sink
                      .doOnNext((record)->{
                        String topic=(String) record.getHeaders().get(KafkaHeaders.RECEIVED_TOPIC);
                        Long offset=(Long) record.getHeaders().get(KafkaHeaders.OFFSET);
                        Integer partition=(Integer) record.getHeaders().get(KafkaHeaders.RECEIVED_PARTITION_ID);
                        log.startstate(()-> format("Register Topic %s partition %d offset %d",topic,partition,offset));
                    })
                    .subscribe();

        });

My Application.yml contains the below information
spring:
  cloud:
    stream:
      kafka:
        default:
          consumer:
            autoCommitOffset: true
        bindings:
          receiver-in-0:
            consumer:
              autoCommitOffset: true
        binder:
          brokers: localhost:9092
          autoAddPartitions: true
          minPartitionCount: 10
          auto-offset-reset: earliest
      bindings:
        receiver-in-0:
          binder: kafka
          destination: Topic1,Topic2
          content-type: text/plain;charset=UTF-8
          group: input-group-1
          max-attempts: 5
          back-off-initial-interval: 10000
          back-off-max-interval: 30000
        emitter-out-0:
          binder: kafka
          producer:
            partition-count:  2
            partition-key-extractor-name: EmitterPartitionKey
        erroremitter-out-0:
          binder: kafka
          destination: error
        error:
          binder: kafka
          destination: error

spring.cloud.stream.function.definition: receiver;emitter;erroremitter

My log file shows that the consumer has not read Topic:Topic1 partition:2 offset 76031 , it jumped from 76030 to 76032,
[STARTSTATE] 2020-05-22 11:40:01.033 [KafkaConsumerDestination{consumerDestinationName='Topic1', partitions=10, dlqName='null'}.container-0-C-1][52] CloudConsumer - Register Topic Topic1 partition 2 offset 76030
[STARTSTATE] 2020-05-22 11:40:01.034 [KafkaConsumerDestination{consumerDestinationName='Topic1', partitions=10, dlqName='null'}.container-0-C-1][52] CloudConsumer - Register Topic Topic2 partition 7 offset 86149
[STARTSTATE] 2020-05-22 11:40:01.034 [KafkaConsumerDestination{consumerDestinationName='Topic1', partitions=10, dlqName='null'}.container-0-C-1][52] CloudConsumer - Register Topic Topic2 partition 7 offset 86150
[STARTSTATE] 2020-05-22 11:40:01.034 [KafkaConsumerDestination{consumerDestinationName='Topic1', partitions=10, dlqName='null'}.container-0-C-1][52] CloudConsumer - Register Topic Topic1 partition 2 offset 76032

Relevant sections of the pom.xml:
<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>11</java.version>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <spring-boot.version>2.1.7.RELEASE</spring-boot.version>
        <spring-cloud.version>Hoxton.SR4</spring-cloud.version>
        <skipTests>true</skipTests>
    </properties>
    <dependencies>
       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-stream-binder-kafka</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-stream-reactive</artifactId>
            <version>2.2.1.RELEASE</version>
        </dependency>
   </dependencies>

A: I reproduced your issue and will open an issue against SCSt (not sure if it's a stream problem or Reactor).
I don't see any missing records when Reactor is not involved.
Consumer<Message<String>>

https://github.com/spring-cloud/spring-cloud-stream-binder-kafka/issues/906


text:
Q: Зачем в данном случае удалять класс? Непонятен фрагмент кода в строке 1. Надо реализовать подсветку ячейки  при клике.
Вместо того, чтобы назначать обработчик для каждой ячейки, которых может быть очень много – мы повесим единый обработчик на элемент .
Он будет использовать event.target, чтобы получить элемент, на котором произошло событие, и подсветить его. Т.е  я если не пойму почему если selectedTd) удалить класс  highlight из свойства classList?

table.onclick = function(event) {
 let target = event.target.closest('td')
  if (target)
   highlight(target)
}

var selectedTd;
function highlight(node) {
  if (selectedTd) {
    selectedTd.classList.remove('highlight'); // 1*
  }
  selectedTd = node;
  selectedTd.classList.add('highlight');
}

A: table.onclick = function(event) {
  let target = event.target.closest('td');
  if (target){
    highlight(target); // Не хочется неприятных сюрпризов - хорошо бы всегда ставить ; и {}
  }
}

var selectedTd; // undefined
function highlight(node) {
  if (selectedTd) {// пока undefined = вернет false и не выполнится.
    selectedTd.classList.remove('highlight'); // 1*
  }
  selectedTd = node;
  // Определили его = кликнутый (еще не подкрашенный) элемент; Он же let target = ...

  selectedTd.classList.add('highlight'); // Покрасили;
}

На следующем клике selectedTd уже будет определен == предыдущий кликнутый и покрашенный элемент. Условие вернет true, краска уберется, потом уже переменная переопределится в новый кликнутый элемент и так по кругу.


text:
Q: Different column posts in tumblr theme I'm making a tumblr theme, which is based on 2 columns. In the left column, there are entries which are tagged, in the right one entries without a tag.
So I have a {block:Posts} in every column div, in one the entries with tags are rendered, in the other one everything else. But somehow both columns are filled with entries, no matter of what type they are.
My code looks like this right now:

            {block:Posts}

                    {block:HasTags}

                            {block:Tags}

                                    {Tag}

                            {/block:Tags}

                    {/block:HasTags}

            {/block:Posts}

            {block:Posts}
                {block:Video}

                        {Video-500}{block:Caption}

{Caption}

                        {/block:Caption}

                {/block:Video}
            {/block:Posts}

The problem is, the video entries are filled in both columns, even if the code links on them just in the column2.


text:
Q: Can I make a view have a transparent background but make it's subviews visible? I have an NSScrollView with an NSCollectionView inside of it.
I want the NSScrollView's background to be transparent but when I set the opacity to 0 it just creates a giant white box for the background.
This NSScrollView is inside of an NSView with a background that I want to see, so the giant white box is unacceptable.
Now an alternative approach I tried was changing the blending mode of the NSScrollView to softlight but when I do this the subviews are also put on softlight. Is there anyway to make it so the subviews show up as normal but the NSScrollView's background is transparent?


text:
Q: whether keep previous format after convert the image to webp my question is not about how to convert other formats to webp, instead what i want to ask is should i keep the original file with its original format and store the new generated file with .webp format in somewhere else or should i delete the old format instead.
my code that converts the format is this:
[$name,] = explode('.',$this->getAddress());

    Image::make($this->getRawFile())->encode('webp', 90)

        ->save(self::PATH . "/" . $this->getFolderName() . "/" . $this->getDateYear() . "/" . $this->getDateMonth() .'/'.$name . '.webp');
    return $this;


text:
Q: how to parse through a .txt file and move all files into another directory Issue:
I have a txt file that looks like this:
SRA1202321.sra
SRA123221.sra
SRA1209312.sra

I have a directory that looks like this:
SRA1202321.sra
SRA123221.sra
SRA1209312.sra
random.sra
random.sra

I want to move all of the files from the .txt to a a different directory and leave behind the ones that I do not want.  I am new to bash so Im having a bit of trouble doing this.
I have tried:
cat ~working/metasamples.txt |
xargs mv ~/ncbi/public/sra/metasamples/

but it seems there is new lines characters being catted in so it says no directory exists.  I am currently looking at bash scripts and have this idea also:
#!/bin/bash

while read p; do
  mv "$p" ~/ncbi/public/sra/metasamples/
done <~/working/metaSRAfromjsoncorrected.txt

However Im not sure how to remove new lines?  Part of that has to do with im confused why input file is given last and if I can just adjust the variable like in python.  Sorry if its a bit confusing.
Thanks for any help

A: It's probably a problem of CRLF line endings. Instead of cat you can use (in bash):
sed $'s/\r$//' ~working/metasamples.txt |
xargs -I {} mv {} ~/ncbi/public/sra/metasamples/

That will work as long as the filenames in metasamples.txt don't contain any problematic character


text:
Q: How to filter entire table with pagination? I have a table with pagination and a search-box.
The current code below searches the entire table (i.e. data from page 1, 2, 3, 4 etc.) only while the user is on Page 1 of the table and returns correct results.
Issue
If I navigate to page 2, 3, 4 etc. I see the data but as soon as I start typing in the search box, no results are returned with my search term.  Not sure why but I suspect it is the slice in ngFor, could be very wrong though.  Any help is appreciated.
Expected
I want to be able to search the entire table from any page of the table, not just page 1.
Customer HTML

Customers

                    <form class="navbar-search form-inline mr-3 d-none d-md-flex ml-lg-auto">

                                <input id="searchInput" class="form-control" [formControl]="filter" placeholder="Search" type="text">

                    </form>

                            Name
                            Contact Email
                            Package
                            Subscription
                            Active
                            Customer Since

                                {{cust.name.S}}

                                {{cust.email.S}}

                                {{cust.package_name.S}}

                                {{cust.subscription_name.S}}

                                {{cust.sub_status.BOOL}}

                                {{cust.date_created.S}}

                                        Edit
                                        Delete

                <button id="create" class="btn btn-primary" (click)="openForm(custCreate)">Create</button>
                <ngb-pagination [(page)]="page" [pageSize]="pageSize" [collectionSize]="customers.length" [boundaryLinks]="true" [maxSize]="5"></ngb-pagination>

Customer TS
export class CustomerComponent implements OnInit {
customers:any;
page= 1;
pageSize= 10;

customers$: Observable<any>;
filter = new FormControl('');

constructor(private dataService: DataService, private modalService: NgbModal, private
customerService: CustomerService, private numberService: NumberService,
private filterService: FilterService, private formBuilder: FormBuilder,  private
ngbDateParserFormatter: NgbDateParserFormatter, private _snackBar: MatSnackBar, pipe: DecimalPipe) {
  this.customers$ = this.filter.valueChanges.pipe(
    startWith(''),
    map(text => this.search(text, pipe))
  );
}

search(text: string, pipe: PipeTransform): any {
  return this.customers.filter(customer => {
    const term = text.toLowerCase();
    return customer.name.S.toLowerCase().includes(term)
 });
 }

}
UPDATED SEARCH FUNCTION
search(text: string, pipe: PipeTransform): any {
return this.customers.filter(customer => {
  if (customer.length < (this.page-1) * this.pageSize + this.pageSize) {
    this.page++;
  }
  const term = text.toLowerCase();
  return customer.name.S.toLowerCase().includes(term)
});

}

A: Please try like this one more time.
search(text: string, pipe: PipeTransform): any {
if(!text) {
  return this.customers;
}

  const filterdCustomers = this.customers.filter(customer => {
    const term = text.toLowerCase();
    return customer.name.S.toLowerCase().includes(term)
  });

  if (filterdCustomers.length < (this.page-1) * this.pageSize +
  this.pageSize) {
    this.page = 1;
  }

  return filterdCustomers;

}


text:
Q: Separate columns using connect by I have a table which has rows in a parent child relationship. The maximum parent-child relationship depth is 3.
One parent would have only one child.
Table definition -
CREATE TABLE USERS {
    empid NUMBER,
    name VARCHAR2,
    department VARCHAR2(20),
    oldempid NUMBER,
}

Data -
EMPID NAME DEPARTMENT OLDEMPID
    1  FOO         IT        2
    2 null         HR        4
    3  BAR      ADMIN     null
    4 null     DESIGN     null

Desired output -
EMPID NAME DEPARTMENT_1 DEPARTMENT_2 DEPARTMENT_3
    1  FOO           IT           HR       DESIGN
    3  BAR        ADMIN         null         null

Full Desired output -
EMPID NAME DEPARTMENT_1 DEPARTMENT_2 DEPARTMENT_3 OLDEMPID_1 OLDEMPID_2
    1  FOO           IT           HR       DESIGN          2          4
    3  BAR        ADMIN         null         null       null       null

I have tried using CONNECT BY PRIOR
SELECT CONNECT_BY_ROOT EMPID,
       NAME,
         RTRIM(LTRIM(SYS_CONNECT_BY_PATH(DEPARTMENT, '-'), '-'), '-') AS DEPARTMENT,
         RTRIM(LTRIM(SYS_CONNECT_BY_PATH(OLDEMPID, '-'), '-'), '-') AS OLDEMPID
   FROM USERS
   WHERE CONNECT_BY_ISLEAF = 1
   CONNECT BY PRIOR OLDEMPID = EMPID;

The output I get is -
EMPID   NAME    DEPARTMENT     OLDEMPID
    1    null   IT-HR-DESIGN   1-2-4
    3    BAR    ADMIN              null

A: You also need to pivot your results. You can do that by hand, or you can use the PIVOT operation (since you tagged this with oracle11g - the first version in which PIVOT became available). The subquery (in the FROM clause towards the end) is the hierarchical query with "connect by."
with
     users ( EMPID, NAME, DEPARTMENT, OLDEMPID ) as (
       select 1, 'FOO', 'IT'    ,    2 from dual union all
       select 2, null , 'HR'    ,    4 from dual union all
       select 3, 'BAR', 'ADMIN' , null from dual union all
       select 4, null,  'DESIGN', null from dual
     ),
     tops ( empid ) as (
       select empid    from users minus
       select oldempid from users
     )
select cbr_empid as empid, cbr_name as name,
       "1_DEPARTMENT" as department_1, "2_DEPARTMENT" as department_2,
       "3_DEPARTMENT" as department_3, "2_EMPID" as oldempid_2, "3_EMPID" as oldempid_3
from (
       select empid, department, level as lvl,
              connect_by_root(empid) as cbr_empid, connect_by_root(name) as cbr_name
       from   users
       connect by prior oldempid = empid
       start with empid in (select empid from tops)
     )
pivot ( max(department) as department, max(empid) as empid for lvl in (1, 2, 3))
;

OUTPUT:
     EMPID NAME DEPARTMENT_1 DEPARTMENT_2 DEPARTMENT_3 OLDEMPID_2 OLDEMPID_3
---------- ---- ------------ ------------ ------------ ---------- ----------
         1 FOO  IT           HR           DESIGN                2          4
         3 BAR  ADMIN


text:
Q: Jacobian of a curve Let $C$ be a curve and $J$ be its Jacobian.
What is the relation between $H^1(C,\mathcal{O}_C)$ and $H^1(J,\mathcal{O}_J)$ ?
Can someone point me to an easy reference for this subject?

A: They are the same in characteristic 0, because the Abel-Jacobi map induces an isomorphism
$$
H^0(C, \Omega) \to H^0(J, \Omega)
$$
and (the notation below means singular cohomology with complex coefficients of the associated complex manifold) it also induces an isomorphism
$$
H^1(C) \to H^1(J)
$$
but we have (canonically, but not naturally, split) exact sequences (for any $X$)
$$
0 \to H^0(X, \Omega) \to H^1(X) \to H^1(X, \mathcal{O}) \to 0.
$$
In characteristic zero you can find all this in Birkenhakke and Lange's book on Complex Abelian Varieties.
I believe the result is true for basically the same reason using an appropriate Weil-type cohomology theory in characteristic $p$ or a lifting argument. Perhaps there is an easier argument. I don't know a reference in characteristic $p$. You might try Milne's notes on his website.


text:
Q: How to stop JVM core dump with Java Spark Parquet writing Running into a problem with Spark, trying to create a Dataset by 'hand' and then write it out to parquet. I've dumbed down this example so you can see whats going on.
I have two classes (they come from a library so its not easy to change them)
public class RawSearch implements Serializable {

    protected long timestamp;

    @Nullable
    protected List<RawItinerary> itineraries;

}

public class RawItinerary implements Serializable {

    protected long timestamp;

    @Nullable
    protected String originCityCode;

    @Nullable
    protected String destinationCityCode;

    protected int departDate;
    protected int returnDate;
    protected String currencyCode;

    protected double totalAmount;
    protected double totalTaxAmount;
    protected double totalSurchargeAmount;

    @Nullable
    protected String validatingCarrier;

    protected boolean multiCarrier;

    @Nullable
    protected String cabin;

    public boolean isPrivate() {
        return false;
    }

}

If I attempt to create a RawSearch with a RawItinerary and write to parquet, the JVM core dumps
       List<RawSearch> searches = new ArrayList<>();

        RawSearch rawSearch = new RawSearch();

        rawSearch.setTimestamp(System.currentTimeMillis());
        rawSearch.setItineraries(new ArrayList<>());
        searches.add(rawSearch);

        RawItinerary itinerary = new RawItinerary();

        itinerary.setCabin("Coach");
        itinerary.setCurrencyCode("USD");
        itinerary.setDepartDate(20200215);
        itinerary.setDestinationCityCode("EDI");
        itinerary.setMultiCarrier(false);
        itinerary.setOriginCityCode("LON");
        itinerary.setReturnDate(0);
        itinerary.setTimestamp(System.currentTimeMillis());
        itinerary.setValidatingCarrier("BA");

        rawSearch.getItineraries().add(itinerary);

        SparkSession sparkSession = SparkSession.builder().appName("Bob").master("local[1]").getOrCreate();

        Dataset<RawSearch> searchDataset = sparkSession.createDataset(searches, Encoders.bean(RawSearch.class));

        searchDataset.write()
                .parquet("/Users/graemewallace/Downloads/bob-" + System.currentTimeMillis());

        sparkSession.close();

#
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGBUS (0xa) at pc=0x0000000109adccda, pid=56878, tid=0x0000000000008903
#
# JRE version: Java(TM) SE Runtime Environment (8.0_241-b07) (build 1.8.0_241-b07)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.241-b07 mixed mode bsd-amd64 compressed oops)
# Problematic frame:
# V  [libjvm.dylib+0xdccda]
#
# Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#

If i get rid of some of the members from RawItinerary - it starts working. If i get rid of the isPrivate() method, it starts working.
Anyone got a clue whats going on here ?


text:
Q: ORM for Spring-MongoDB integration with native querying support I am a new to using Mongo DB and exploring the frameworks around for migrating from mysql to mongodb. So far from my findings I have been able to figure out SpringMongo as the best solution to my requirements.
The only problem is that instead of using a DSL based or abstract querying mechanism, I wished the framework allowed me to pass plain json string as arguments to the different methods exposed by the API(find, findOne) so that the query parameters can be written out to an external file (using a key to refer) and passed to the methods by reading and parsing at run time. But the framework should be capable of mapping the results to the domain objects.
Is there a way in spring-mongo to achieve this? Or is there any other frameworks on the same lines

A: You could use Spring Data to do that, just use the BasicQuery class instead of Query class. Your code will look like the following:
/* Any arbitrary string that could to parsed to DBObject */
Query q = new BasicQuery("{ filter : true }");
List<Entity> entities = this.template.find(q, Entity.class);

If you want more details:
http://static.springsource.org/spring-data/data-mongo/docs/current/reference/html/#mongo.query
http://static.springsource.org/spring-data/data-mongodb/docs/current/api/org/springframework/data/mongodb/core/query/BasicQuery.html

A: Well I got to find this one in the Spring data MongoOperations...
String jsonCommand = "{username: 'mickey'}";
MongoOperations mongoOps = //get mongooperations implemantation
mongoOps.executeCommand(jsonCommand)

It returns an instance of CommandResult that encapsulates the result.


text:
Q: How to nested sum in mongodb I have this scheme:
[{
        name: 'John',
        plays: [{
                playNum: 1,
                song: {
                    length: 400,
                    param: 'a'
                }
            }, {
                playNum: 2,
                song: {
                    length: 350,
                    param: 'a'
                }
            }, {
                playNum: 3,
                song: {
                    length: 211,
                    param: 'a'
                }
            ]
        },
        {
            name: 'John',
            plays: [{
                    playNum: 2,
                    song: {
                        length: 400,
                        param: 'a'
                    }
                }, {
                    playNum: 3,
                    song: {
                        length: 350,
                        param: 'a'
                    }
                }, {
                    playNum: 4,
                    song: {
                        length: 211,
                        param: 'a'
                    }
                ]
            }
        ]

I want to calculate the time of specific play
i.e. for play 2 - we have one song in 350 and another one in 400 = 750.
I tryied to do it that way:
aggregate(
        {$match : { "shows.showNum" : showNum } },
        {$unwind : "$shows"},
        {$group : {_id : "$shows.showNum", totalLength : { $sum : "$shows.song.length" }}})

But in that way I am getting the total of all songs of player who plays in that show.
can anyone help?
Thanks!

A: Your first $match only matches the "documents" that contain that value within the array. To actually "filter" the array contents you need another $match after you $unwind in the pipeline:
db.collection.aggregate([
    { "$match": { "plays.playNum" : playNum } },
    { "$unwind": "$plays"},
    { "$match": { "plays.playNum" : playNum } },
    { "$group": {
        "_id" : "$plays.playNum",
        "totalLength": { "$sum" : "$plays.song.length" }
    }}
])

If you have MongoDB 2.6 or greater you can actually filter the array using the $map operator and other helper operators:
db.collection.aggregate([
    { "$match": { "plays.playNum" : playNum } },
    { "$project": {
        "plays": {
             "$setDifference": [
                {
                    "$map": {
                        "input": "$plays",
                        "as": "el",
                        "in": {
                            "$cond": [
                                { "$eq": [ "$$el.playNum", playNum ] },
                                "$$el",
                                false
                            ]
                        }
                    }
                ],
                [false]
            ]
        }
    }},
    { "$unwind": "$plays" },
    { "$group": {
        "_id" : "$plays.playNum",
        "totalLength": { "$sum" : "$plays.song.length" }
    }}
])

Which makes things a bit faster by combining functions from various stages. It looks more complicated but is actually the fastest way to process to the end result.

A: db.collection.aggregate([
    {$unwind: '$plays'},
    {$match: {"plays.playNum" : 2} },
    {$group: {
        _id: null,
        "suma": {$sum: "$song.length" }
    }}
])


text:
Q: null is not an object(evaluting 'RNI18n.languages') I'm working on expo react native. when I'm running the app I'm getting error. I have installed the npm install react-native-i18n --save and even link it manually react-native link react-native-i18n. In my package.json  "react-native-i18n": "^2.0.15",. Any help will be appreciated.
I have imported like this import I18n from 'react-native-i18n';


text:
Q: List fields missing in Dynamic Content sometimes I'm facing a weird issue. I'm able to access the fields in my list from Dynamic Content section at some places, and not at others. Pls see the screenshot below
I was able to select 'Request State' field in the first condition.
I want to select the same field in the 'Set Variable' activity below, but the field 'Request State' is not even coming in the dynamic content. What could be the reason?
I found the same issue for other few fields as well, not all
btw this 'Request State' is a string type with list of values. So does it make any difference


text:
Q: How to get the return value and rows in c# thru stored procedure In the below Stored procedure, i am returning a row if all the conditions satisfies, orelse i am returning a message like which condition is nor satisfied.
The Stored proc is working perfectly...
ALTER PROCEDURE dbo.BookingCheck
    (
    @int_duration_of_stay   int ,
    @int_number_of_guests   int,
    @date_of_application    date,
    @date_of_checkin        date,
    @date_of_checkout       date,
    @str_room_type          varchar(50),
    @ret_value              varchar(100) = '' output
    )
AS
    DECLARE @MaxPer int
    DECLARE @BasicCharge int
    DECLARE @SurCharge int
    DECLARE @TotalAmount int
    DECLARE @NoOfDays int
    DECLARE @Free VARCHAR(10)

    IF @int_duration_of_stay > 6
    BEGIN
        SET @NoOfDays = @int_duration_of_stay
        SET @Free = 'Yes'
    END
    ELSE
    BEGIN
        SET @NoOfDays = @int_duration_of_stay - 1
        SET @Free = 'No'
    END

    SELECT @MaxPer = int_max_pax, @BasicCharge = flt_basic_charge, @SurCharge = flt_surcharge_per_pax
    FROM RoomTypes WHERE UPPER(str_room_type) = UPPER(@str_room_type)

IF DATEDIFF(DAY, GETDATE(), @date_of_checkin) < 40
BEGIN
    IF @int_number_of_guests <= @MaxPer
    BEGIN
        SET @TotalAmount = (@NoOfDays * @int_number_of_guests * @SurCharge) + @BasicCharge
        SET @ret_value = 'Success'

        SELECT @str_room_type as 'Room Type', @MaxPer as 'Max Persons Allowed', @int_number_of_guests as 'No. of persons requested',
        @int_duration_of_stay as 'No. of days stay', @BasicCharge as 'Basic Charge',  @SurCharge as 'Sur Charge', @Free as 'Complimentary',
         @TotalAmount as 'Total Amount'
    END
    ELSE
    BEGIN
        SET @ret_value = 'Max persons allowed is ' + CONVERT(VARCHAR(20), @MaxPer)
    END
END
ELSE
BEGIN
    SET @ret_value = 'The check in date should be less than 40 days from current date.'
END
RETURN

The problem is dont know how to get the return message or return row from the SP using c#.
The below code returns me the rows if the condition is satisfied in SP. if not, i am not getting the return message. How to get that ?
 public DataSet BookingCheck(int duration_of_stay, int number_of_guests,
    string date_of_application, string date_of_checkin, string date_of_checkout,
    string room_type)
{
    DataSet dsGetBookingCheck = new DataSet();
    SqlConnection conn = new SqlConnection(Con);
    SqlCommand command = new SqlCommand("BookingCheck", conn);
    command.CommandType = CommandType.StoredProcedure;
    SqlDataAdapter da = new SqlDataAdapter();
    SqlParameter param = new SqlParameter();
    param = command.Parameters.Add("@int_duration_of_stay", SqlDbType.Int);
    param.Value = duration_of_stay;
    param = command.Parameters.Add("@int_number_of_guests", SqlDbType.Int);
    param.Value = number_of_guests;
    param = command.Parameters.Add("@date_of_application", SqlDbType.Date);
    param.Value = date_of_application;
    param = command.Parameters.Add("@date_of_checkin", SqlDbType.Date);
    param.Value = date_of_checkin;
    param = command.Parameters.Add("@date_of_checkout", SqlDbType.Date);
    param.Value = date_of_checkout;
    param = command.Parameters.Add("@str_room_type", SqlDbType.VarChar, 50);
    param.Value = room_type;
    conn.Open();
    command.ExecuteNonQuery();
    da.SelectCommand = command;
    da.Fill(dsGetBookingCheck);
    conn.Close();
    return dsGetBookingCheck;
}

A: You need to add an out parameter:
command.Parameters.Add("@ret_value", SqlDbType.String);
command.Parameters["@ret_value"].Direction = ParameterDirection.Output;

then after executing the SP
message = command.Parameters["@ret_value"].Value.ToString();

Here is function with out param:
 public DataSet BookingCheck(int duration_of_stay, int number_of_guests,
    string date_of_application, string date_of_checkin, string date_of_checkout,
    string room_type, out string message)
{
    DataSet dsGetBookingCheck = new DataSet();
    SqlConnection conn = new SqlConnection(Con);
    SqlCommand command = new SqlCommand("BookingCheck", conn);
    command.CommandType = CommandType.StoredProcedure;
    SqlDataAdapter da = new SqlDataAdapter();
    SqlParameter param = new SqlParameter();
    param = command.Parameters.Add("@int_duration_of_stay", SqlDbType.Int);
    param.Value = duration_of_stay;
    param = command.Parameters.Add("@int_number_of_guests", SqlDbType.Int);
    param.Value = number_of_guests;
    param = command.Parameters.Add("@date_of_application", SqlDbType.Date);
    param.Value = date_of_application;
    param = command.Parameters.Add("@date_of_checkin", SqlDbType.Date);
    param.Value = date_of_checkin;
    param = command.Parameters.Add("@date_of_checkout", SqlDbType.Date);
    param.Value = date_of_checkout;
    param = command.Parameters.Add("@str_room_type", SqlDbType.VarChar, 50);
    param.Value = room_type;
    command.Parameters.Add("@ret_value", SqlDbType.String);
    command.Parameters["@ret_value"].Direction = ParameterDirection.Output;
    conn.Open();
    command.ExecuteNonQuery();
    da.SelectCommand = command;
    da.Fill(dsGetBookingCheck);
    message = command.Parameters["@ret_value"].Value.ToString();
    conn.Close();
    return dsGetBookingCheck;
}

NOTE:  I have never done with with using ExecuteNonQuery and then using Fill on a data adapter.  That might mess this up.

A: What is ExecuteNonQuery doing in your code when you are not inserting anything?
There are ways to do this. One, use a DataReader. It is a bit more helpful in these kind of scenarios. Or you can add a output parameter to the stored procedure and check that after you execute the proc through C#.

A: That's not doable in C#. You can only either return a DataTable with a single row (using the Fill method in your example) or you can return a single value (using an SqlCommand with a return parameter or ExecuteScalar).
Instead you should do a SELECT in both cases but with different fields depending on the IF statement. I.e.,
SET @ret_value = 'Max persons allowed is ' + CONVERT(VARCHAR(20), @MaxPer)

is converted to be
SELECT 'Max persons allowed is ' + CONVERT(VARCHAR(20), @MaxPer) AS Return_Value

And then you check for the field name in your return DataTable. E.g.
if (BookingCheck(...).Tables[0].Columns.Contains("Return_Value")) {
   // Handle my special condition here
}


text:
Q: Error displaying Swagger UI of flask-restx in Deployment using uwsgi and nginx I have implemented a flask rest server with swagger-ui using flask-restx.
I could get the swagger-ui working when running the server using command, without nginx
flask run --host=0.0.0.0

or
uwsgi --ini app.ini

My app.ini:
[uwsgi]
module = wsgi:app

master = true
processes = 2

socket = /tmp/myproj.sock
chmod-socket = 666
vacuum = true

die-on-term = true

====================
However, with nginx, although my REST APIs are working, I couldn't get the swagger-UI.
Error message I received on browser:

My nginx configuration in /etc/nginx/sites-available/default:
server {
    listen 80 default_server;
    listen [::]:80 default_server;

    server_name _;

    location /api {
        include uwsgi_params;
        uwsgi_pass unix:/tmp/myproj.sock;
    }
}

Any idea how to configure nginx so that swagger-UI could be loaded?
Thank you.

A: Update
I managed to make it works by adding /swaggerui in nginx configuration.
Example code:
server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/html;

    index index.html index.htm index.nginx-debian.html;

    server_name _;

    location / {
        try_files $uri $uri/ /index.html;
    }

  location /api {
    include uwsgi_params;
    uwsgi_pass unix:/tmp/myproj.sock;
  }

  location /swaggerui {
    include uwsgi_params;
    uwsgi_pass unix:/tmp/myproj.sock;
  }

}


text:
Q: Помогите написать такую же функцию используя метод bind в setTimeout есть функция, которая выводит от 0 до 9
function counter() {
  for (let i = 0; i < 10; i++) {
        setTimeout(function() {
            console.log(i);
        }, 10);
    }
}

нужно написать такую же используя метод bind в setTimeout
Помогите пожалуйста!!!!

A: Для того, что бы привязать контекст к функции используется встроенный метод bind

Метод .bind(context) принимает на вход объект, который устанавливается как контекст(this) для возвращаемой функции.

const fn = function (a, b) {
    console.log(this);
}

const fnNew = fn.bind({a: 1, b: 2});
fnNew();

Так же методом bind можно привязать аргументы новой функции. Синтаксис bind(context, arg1, arg2, ... argN);

const fn = function (a, b) {
  return a + b;
}
const fnNew = fn.bind(null, 4);
console.log(fnNew(2));

Для того, что бы реализовать вывод значений в setTimeout с использованием метода .bind() нам потребуется создать вспомогательную функцию.

function counter() {
  // Создаем функцию print, которая будет выводить переданное значение через метод bind
  function print () {
console.log(this.i);
  }
  for (let i = 0; i < 10; i++) {
// Т.к. метод bind возвращает нам новую функцию,
// ее можно сразу передать в setTimeout
setTimeout(print.bind({i: i}), 100);
  }
}

counter();


text:
Q: How can I add a YouTube video to the Watch History with the YouTube Data API? I'm making a site with the YouTube Data API 3.0 where users can watch YouTube videos. I need these videos to go to the Watch History so I can know that they've been watched, but playing videos with the YouTube Player API doesn't add them. I've added the video ID to the user's watch history playlist id with playlistItems.insert and the video shows up on the Watch History playlist if I go to youtube.com. However, it isn't returned in the list when I request the playlist items with the Data API.
Does anyone know how to add videos to the watch history so that they're returned in API calls? Alternatively, is there a way to use the Player API so that the authenticated user get the video on their watch history?
Here is the code to add a video to the user's watch history:
gapi.client.youtube.playlistItems.insert({
  'part': 'snippet',
  'resource': {
    'snippet': {
      'playlistId': Cache.fetch('my_channel').relatedPlaylists.watchHistory,
      'position': 0,
      'resourceId': {
        'kind': 'youtube#video',
        'videoId': video_id,
      }
    }
  }
}).execute(callback);

A: You can use this code for connect and request using http and json
try {

        URL url = new URL("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet"
                + "&key=AIzaSyAhONZJpMCBqCfQjFUj21cR2klf6JWbVSo"
                + "&access_token=" + access_token);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");

        String input = "{ \"snippet\": {\"playlistId\": \"WL\",\"resourceId\": {\"videoId\": \""+videoId+"\",\"kind\": \"youtube#video\"},\"position\": 0}}";

        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();

        if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
            throw new RuntimeException("Failed : HTTP error code : "
                + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(
                (conn.getInputStream())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        conn.disconnect();

      } catch (MalformedURLException e) {

        e.printStackTrace();

      } catch (IOException e) {

        e.printStackTrace();

     }

if you see an error add this but this is not a good job.
if (Build.VERSION.SDK_INT >= 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }


text:
Q: The cursor for loop that contains DML statements should be refactored to use If I compiled my procedure I dont get error but I see this text(how Can I use this advice):

A cursor for loop that contains DML statements should be refactored to use BULK COLLECTION and FORALL

If I compiled this I got always score:
start:2013-11-21 08:16:54
end:2013-11-21 08:16:54

My code:
    CREATE OR REPLACE PROCEDURE PROC_AAA
IS
   PRAGMA AUTONOMOUS_TRANSACTION;
   company_              VARCHAR2 (2) := 'IT';
   ok_                   BOOLEAN;
   updated_              BOOLEAN;
   error_msg_            VARCHAR2 (4000);
   category_             VARCHAR2 (50);
   exist_atrribute_id_   VARCHAR2 (50);
   exist_value_          NUMBER;
   objid_                ROWID;
   var_rows              NUMBER (5);

   CURSOR cur_dane_wej
   IS
      SELECT *
        FROM dane_wejsciowe_cns
       WHERE status = 'NEW'
      FOR UPDATE;
BEGIN
   DBMS_OUTPUT.put_line (
      'start:' || TO_CHAR (SYSDATE, 'YYYY-MM-DD hh24:mi:ss'));

   FOR cur_dane_wej_read IN cur_dane_wej
   LOOP
      BEGIN
         SAVEPOINT cur_dane_wej_svp;
         updated_ := FALSE;
         error_msg_ := NULL;

         category_ := TERMINAL_API.Get_Category_Id (cur_dane_wej_read.IMEI_NO);

         exist_atrribute_id_ :=
            IFSAPP.SER_NUM_ATTRIBUTE_API.CHECK_EXIST (
               COMPANY_,
               category_,
               cur_dane_wej_read.IMEI_NO,
               cur_dane_wej_read.KOD_CECHY);

         SELECT COUNT (*)
           INTO exist_value_
           FROM IFSAPP.SER_NUM_ATTRIBUTE
          WHERE     SERIAL_NO = cur_dane_wej_read.IMEI_NO
                AND COMPANY = company_
                AND CATEGORY_ID = category_
                AND ATTRIBUTE_ID = cur_dane_wej_read.WARTOSC_CECHY
                AND NVL (VALUE, '_dummy_') =
                       NVL (cur_dane_wej_read.KOD_CECHY, '_dummy_');

         DBMS_OUTPUT.put_line (
               cur_dane_wej_read.KOD_CECHY
            || '  '
            || cur_dane_wej_read.WARTOSC_CECHY);
         DBMS_OUTPUT.put_line (
               'kategoria: '
            || category_
            || '  imei:  '
            || cur_dane_wej_read.IMEI_NO);

         IF exist_atrribute_id_ = 'TRUE'
         THEN
            SELECT objid
              INTO objid_
              FROM SER_NUM_ATTRIBUTE
             WHERE     COMPANY = company_
                   AND CATEGORY_ID = category_
                   AND SERIAL_NO = cur_dane_wej_read.IMEI_NO
                   AND ATTRIBUTE_ID = cur_dane_wej_read.KOD_CECHY;

            DBMS_OUTPUT.put_line ('objid:  ' || objid_);

            IF exist_value_ > 0
            THEN
               DBMS_OUTPUT.put_line ('--> wartosc cechy istnieje ');
               NULL;
            ELSE
               DBMS_OUTPUT.put_line ('zmodyfikowano wartosc cechy');
               updated_ := TRUE;
            END IF;
         ELSE
            DBMS_OUTPUT.put_line (
               'kod cechy nie istnieje.. trwa dodanie nowego kodu cechy');
            --                     IFSAPP.SER_NUM_ATTRIBUTE_API.SET_VALUE (company_, category_id_,cur_dane_wej_read.IMEI_NO, cur_dane_wej_read.KOD_CECHY, cur_dane_wej_read.WARTOSC_CECHY, 'DODANO NOWY KOD CECHY' );
            updated_ := TRUE;
         END IF;

         IF updated_ = TRUE
         THEN
            DBMS_OUTPUT.put_line ('aktualizacja danych w tabeli wejsciowej');

            UPDATE dane_wejsciowe_cns
               SET status = 'DONE',
                   MESSAGE = ' ',
                   DATA_PRZETWORZENIA = SYSDATE
             WHERE CURRENT OF cur_dane_wej;
         ELSE
            UPDATE dane_wejsciowe_cns
               SET status = 'SKIPPED',
                   MESSAGE = ' ',
                   DATA_PRZETWORZENIA = SYSDATE
             WHERE CURRENT OF cur_dane_wej;
         END IF;

         COMMIT;
      EXCEPTION
         WHEN OTHERS
         THEN
            ROLLBACK TO cur_dane_wej_svp;
            error_msg_ := 'Błąd:  - ' || SQLCODE || ' -ERROR- ' || SQLERRM;

            UPDATE dane_wejsciowe_cns
               SET status = 'ERROR',
                   MESSAGE = error_msg_,
                   DATA_PRZETWORZENIA = SYSDATE
             WHERE CURRENT OF cur_dane_wej;

            COMMIT;
      END;
   END LOOP;

   COMMIT;
   DBMS_OUTPUT.put_line (
      'end:' || TO_CHAR (SYSDATE, 'YYYY-MM-DD hh24:mi:ss'));
END PROC_AAA;

A: Learn to use bulk collections, take a look at this article.


text:
Q: number of transitions in mongodb table I am developing a small app using mongdb and c# . Input file has row contains B, K, L, T, where  B=bedroom, K=kitchen, L=living room, T=toilet i added some new columns in input file to process my queries . Queries which user would like to see is

*

*number of occurrences of each B/K/L/T in each day

*number of transitions from a room to another

*time that a person spends in a room

*position of a person in a specific time or interval of time

I am done with all queries except number of transitions from room to another .
My table has "RoomID", "TimeStamp", "DayId", "Transition",  each day file contains 288 rows and at every 5 minutes it changes room for example B to T to K.
I have to track how many times a person switches from one room to other in single day .

A: After doing a little research on mongodb i created following query to solve my problem .
db.mytable.count( { $where: "this.RoomID != this.Transition && this.RoomID == 'B' && this.DayID == 1" } )
this query shows me number of transitions


text:
Q: How can configurate headers in azure web app? I need to add some security headers on the server side, specifically they are X-Content-Type-Options and CSP headers, the headers were added to the project using meta tags, but this does not return the headers information in the headers section of "Response Headers" in dev tools, and it needs to be displayed here for security validation.
Is there a way to do it through the azure portal for a web app or any configuration file in angular?
The project is made with Angular(11)
P.S. I'm new to angular and so I'm not familiar with some aspects of the project and the framework.

A: In App Service, TLS/SSL termination happens at the network load balancers, so all HTTPS requests reach your app as unencrypted HTTP requests.
You could control (on all response headers) and include to return HSTS policy header explicitly. There is no App Service feature to enforce such policy on user's behalf.
Just to highlight, App Services HttpsOnly is limited to redirect Http-Https but not extend to forcing single HSTS policy to all your users.
You may take a look at this similar discussion App service security headers.


text:
Q: Iterator to Map (CvBlobs) always points to other place C++ I have a class called BlobTracking that uses the cvBlob library to extract blobs from a blob mask.
I call the function cvb::cvLabel(&segmentated, labelImg, blobs); The blobs are stored in the class variable cvb::CvBlobs blobs (already tried to put the variable public and private)
(definition of CvBlobs:  typedef std::map CvBlobs;)
I have another class called OF_Object. In the class BlobTracking I have stored OF_Objects:
    Blobtracking.h
struct VectInfo {
   OF_Object oF_Object;
   int index;
   int size;
};
typedef std::map<OF_ID,VectInfo> OF_Objects;
class BlobTracking
{
private:
    OF_Objects oF_Objects; ...
}

When on the function process of the blob tracking class, in one of the OF_Objects I call the function
I'm calling blobOfPoint from the BlobTracking class and all the 3 variables of blobOfPoint are private variables from the BlobTracking class.
The problem is when in the function blobOfPoint, when I'm debugging on Xcode, I see the variable blobs and has for example one element. But the iterator bi=blobs.begin(); points to somewhere else.
I put here the function blobOfPoint and also the process of the BlobTracking and I make a note in the line were the blobOfPoint is called.
I also post a print screen showing the xCode debugging:
Print screen of value of variable blobs:
https://dl.dropboxusercontent.com/u/26082578/SS01.png
Print screen of value of variable iterator bi=blobs.begin():
https://dl.dropboxusercontent.com/u/26082578/SS02.png
bool OF_Object::blobOfPoint(Point2f &point,cvb::CvBlobs &blobs, BlobPolygons &blobPolygons)
        {
        bool found= false;
        if(oF_BlobsFP.size()>0)
        {
            OF_BlobsFP::iterator it=oF_BlobsFP.begin();
            while(!(found = poinInBlob(point,*blobs.find(it->first)->second,blobPolygons)) && it!=oF_BlobsFP.end())
                it++;
        }

The problem is in this iterator here as you can see in the print Screens of Xcode!!
        cvb::CvBlobs::iterator bi=blobs.begin();
        cvb::CvBlob test=*bi->second;
        if(!found)
        {
            while(!(found = poinInBlob(point,*bi->second,blobPolygons)) && bi!=blobs.end())
                bi++;
        }

        if(found)
        {
            OF_BlobsFP::iterator it = oF_BlobsFP.find(bi->first);
            //If doesn't exist
            if(it==oF_BlobsFP.end())
            {
            oF_BlobsFP.insert(std::pair<cvb::CvLabel,vector<Point2f> >(bi->first, vector<Point2f>()));
                it = oF_BlobsFP.find(bi->first);
            }
            it->second.push_back(point);

        }
        return found;
    }

Process in Blob tracking
void BlobTracking::process(const cv::Mat &prevInput, cv::Mat &img_input, const cv::Mat &img_mask, cv::Mat &img_output)
{
if(img_input.empty() || img_mask.empty())
    return;

cv::Mat mask(img_input.size(), CV_8UC1);

IplImage segmentated =IplImage(img_mask);

IplConvKernel* morphKernel = cvCreateStructuringElementEx(5, 5, 1, 1, CV_SHAPE_RECT, NULL);
cvMorphologyEx(&segmentated, &segmentated, NULL, morphKernel, CV_MOP_OPEN, 1);

if(showBlobMask)
    cvShowImage("Blob Mask", &segmentated);

IplImage* labelImg = cvCreateImage(img_input.size(), IPL_DEPTH_LABEL, 1);

unsigned int result = cvb::cvLabel(&segmentated, labelImg, blobs);

//cvb::cvFilterByArea(blobs, 500, 1000000);
cvb::cvFilterByArea(blobs, minArea, maxArea);
blobPolygons.clear();
cvb::CvBlobs::iterator bi=blobs.begin();
while(bi!=blobs.end())
{
    blobPolygons.insert(std::pair<cvb::CvLabel,cvb::CvContourPolygon *>(bi->first,cvb::cvConvertChainCodesToPolygon(&bi->second->contour)));
    bi++;
}

nBlobs=blobs.size();
if(nBlobs=0)
    oF_Objects.clear();
else{
    //If there are objects
    if(points[0].size()>0&&oF_Objects.size()>0)
    {
        //Compute optical Flow
        calcOpticalFlowPyrLK(prevInput, img_input, points[0], points[1], status, err, winSize,3, termcrit, 0);
        objOfBlobs.clear();
        OF_Objects::iterator it=oF_Objects.begin();
        int i=0;
        //Associate each point of each object with a Blob
        while(it!=oF_Objects.end())
        {
            it->second.oF_Object.clearOF_BlobsFP();
            int index=it->second.index;
            int oldSize=it->second.size;
            it->second.index=i;
            int nPointsWithoutBlob=0, newSize=0;
            while(oldSize>0)
            {
                //If point calculated and is inside of a Blob

The function is called here:
                if(status[index]&&it->second.oF_Object.blobOfPoint(points[1][index],blobs,blobPolygons)){
                    points[0][i] = points[1][index];
                    newSize++;
                    i++;
                    //circle(img_input, points[1][i], 3, Scalar(0,255,0), -1, 8);
                }
                oldSize--;
                index ++;
            }
            it->second.oF_Object.setnPointsWithoutBlob(nPointsWithoutBlob);
            it->second.size=newSize;

            //Update new objects to see which ones finished,which ones had a significant increase in size and which ones splitted
            if(!it->second.oF_Object.updateOF_Object(blobs))
                oF_Objects.erase(it);
            else
            {
                //Add the information to which blob(s) is the object associated
                OF_ID oF_ID=it->second.oF_Object.getID();
                //If not splitted just add the first blob in the list
                if(!it->second.oF_Object.splitStatus())
                {
                    cvb::CvLabel bLabel= it->second.oF_Object.getBlobLabel();
                    std::map<cvb::CvLabel,vector<OF_ID> >::iterator it2 = objOfBlobs.find(bLabel);
                    if(it2==objOfBlobs.end())
                    {
                        objOfBlobs.insert(std::pair<cvb::CvLabel,vector<OF_ID> >(bLabel, vector<OF_ID>()));
                        it2 = objOfBlobs.find(bLabel);
                    }
                    it2->second.push_back(oF_ID);

                }
                else{
                    //If splitted, add all objects in the list
                    OF_BlobsFP::iterator it3 =it->second.oF_Object.getOF_BlobsFP().begin();
                    while(it3!=it->second.oF_Object.getOF_BlobsFP().end())
                    {
                        cvb::CvLabel bLabel= it3->first;
                        std::map<cvb::CvLabel,vector<OF_ID> >::iterator it4 = objOfBlobs.find(bLabel);
                        if(it4==objOfBlobs.end())
                        {
                            objOfBlobs.insert(std::pair<cvb::CvLabel,vector<OF_ID> >(bLabel, vector<OF_ID>()));
                            it4 = objOfBlobs.find(bLabel);
                        }
                        it4->second.push_back(oF_ID);
                        it3++;

                    }
                }

            }
            it++;
        }
        points[1].resize(i);
        points[0].resize(i);

        //Check Merged Blobs
        std::map<cvb::CvLabel,vector<OF_ID> >::iterator it5 = objOfBlobs.begin();
        while(it5!=objOfBlobs.end())
        {
            if(int s=it5->second.size()>0)
            {
                int i=0;
                while(s>0)
                {
                    OF_ID oF_ID=it5->second.at(i);
                    OF_Object *pOF=&(oF_Objects.find(oF_ID)->second.oF_Object);
                    pOF->setMergeStatus(true);
                    pOF->setUpdateStatus(false);
                    i++;
                    s--;
                }
            }
            it5++;
        }

        //Check for objects to recalculate new features
        it=oF_Objects.begin();
        std::set<OF_ID> ofToUpdate;
        while(it!=oF_Objects.end())
        {
            if(it->second.oF_Object.getUpdateStatus()){
                if(it->second.oF_Object.newFeatures(blobs, img_input))
                    ofToUpdate.insert(it->first);
                it->second.oF_Object.setUpdateStatus(false);

            }
            it++;
        }
        //if there were objects with new features, copy not updated points to a new vector and add new ones to the end
        if(ofToUpdate.size()>0){
            it=oF_Objects.begin();
            int k=0;
            while(it!=oF_Objects.end())
            {
                //if object not with new features
                if(ofToUpdate.find(it->first)==ofToUpdate.end())
                {
                    int index=it->second.index;
                    int size=it->second.size;
                    it->second.index=k;
                    while(size>0)
                    {
                            points[1][k] = points[0][index];
                            k++;
                            size--;
                            index ++;
                    }
                }
                it++;
            }
            points[1].resize(k);
            points[0].resize(k);
            swap(points[1], points[0]);
            std::set<OF_ID>::iterator it5 = ofToUpdate.begin();
            while(it5!=ofToUpdate.end())
            {
                OF_ID ofId=*it5;
                oF_Objects.find(ofId)->second.index=k;
                vector<Point2f> &oF_Points =  oF_Objects.find(ofId)->second.oF_Object.getOF_BlobsFP().begin()->second;
                int size=oF_Points.size();
                oF_Objects.find(ofId)->second.size=size;
                int i=0;
                while(size>0)
                {
                    points[0].push_back(oF_Points[i]);
                    i++;
                    k++;
                    size--;
                }
                it5++;
            }

        }
    }
}

//Check for blobs without OF_Objects and create new objects for them
cvb::CvBlobs::iterator it = blobs.begin();
int k=points[0].size();
while(it!=blobs.end())
      {
          if(objOfBlobs.find(it->first)==objOfBlobs.end())
             {
                 OF_Object objct = OF_Object(img_input,it->first,blobs,last_OF_ID);
                 last_OF_ID++;
                 VectInfo vctInfo= {.oF_Object=objct,.index=k,.size=objct.getNTFeatures()};
                 oF_Objects.insert(std::pair<OF_ID,VectInfo >(objct.getID(), vctInfo));

                 vector<Point2f> &oF_Points =  objct.getOF_BlobsFP().begin()->second;
                 int size=objct.getNTFeatures();
                 int i=0;
                 while(size>0)
                 {
                     points[0].push_back(oF_Points[i]);
                     i++;
                     k++;
                     size--;
                 }
             }
          it++;
      }

//    if(!blobs.empty()){
//        for(std::map<cvb::CvLabel,cvb::CvBlob*>::iterator it = blobs.begin() ; it != blobs.end(); it++)
//        {
//            //std::cout << (*it).first << " => " << (*it).second << std::endl;
//            cvb::CvID id = (*it).first;
//            cvb::CvBlob* blob = (*it).second;
//            createMask(mask, *blob);
//        }
//    }
if(drawFeatures)
{
    for(int m=0;m<points[0].size();m++)
    {
        circle(img_output, points[0][m], 3, Scalar(0,255,0), -1, 8);

    }
}
cvReleaseImage(&labelImg);
cvReleaseStructuringElement(&morphKernel);

firstTime = false;
}


text:
Q: Keep consitant encoding between windows, unix and mssql 2014 I have a node application on a unix machine that reads a utf-8 js file created on a windows machine that looks like this:

{
 "b_name": "שם של משהו",
}

and uses the info in the file to update a mssql table with a corresponding field, defined as:

[b_name] [nvarchar](50)

Somewhere along the way, the value of the b_name become gibberish and is saved as junk in the db.
When I encode it to utf-8 in the file, i.e

{
 "b_name": '×©× ×©× ×ש××', //utf8.encode('שם של משהו')
}
it is saved correctly at the db, but then it has to be decoded at the destination, and I have no control over that part, so they see it as "×©× ×©× ×ש××"
Any idea how to make it consistence through out the process?

A: Apparently the problem was this:
(Correct for mssql@3.3.0)
We set the type of js String to VarChar instead of NVarChar:
//bad
request.input('string_parameter', sql.VarChar, value);
//Good
request.input('string_parameter', sql.NVarChar, value);


text:
Q: Convert between UIImage and cv::Mat without copying the data? Is it possible to convert between an iOS UIImage and an OpenCV cv::Mat without copying the image?
The examples in the OpenCV documentation show CVGontextDrawImage being used to copy the input image into the cv::Mat:
- (cv::Mat)cvMatFromUIImage:(UIImage *)image
{
  CGColorSpaceRef colorSpace = CGImageGetColorSpace(image.CGImage);
  CGFloat cols = image.size.width;
  CGFloat rows = image.size.height;

  cv::Mat cvMat(rows, cols, CV_8UC4); // 8 bits per component, 4 channels (color channels + alpha)

  CGContextRef contextRef = CGBitmapContextCreate(cvMat.data, ...);

  /***** image appears to be copied here *****/
  CGContextDrawImage(contextRef, CGRectMake(0, 0, cols, rows), image.CGImage);

  CGContextRelease(contextRef);

  return cvMat;
}


text:
Q: Converting Unicode code points to UTF-8 Currently I have something like this \u4eac\u90fd and I want to convert it to UTF-8 so I can insert it into a database.

A: Most likely, the \u escape sequence was already sent by the web browser. This would be the original source of your problem - you need to make the web browser stop doing that.
For that, you need to make sure that the browser knows what encoding to use when submitting the form. The browser will, by default, always use the encoding of the HTML page that contains the form. Make sure that this web page is encoded in UTF-8, and has an UTF-8 charset declaration in a meta header. With that done, the browser should submit UTF-8 data correctly, and you shouldn't need to convert anything at all.

A: http://hsivonen.iki.fi/php-utf8/

A: json_decode('"\u4eac\u90fd"');

Credit for using JSON @bobince https://stackoverflow.com/a/7107750 where the reverse is sought (UTF-8 to code points). There ASCII characters will not be converted to code points, but with json_decode, ASCII code points will be converted to characters, e.g. '"\u0041"' -> 'A'.
(Remember that you need the double quotes inside your string. I was confused why json_decode('\u4eac\u90fd'); was giving no output :-)
Note there will be special requirements for 4-byte UTF-8 encodings, where the code point consists of 5 or 6 hexadecimal digits. JSON doesn't use curly braces.
echo json_encode('');
//output: "\ud800\udf48"

 is U+10348. The separation into two code points is not obvious to me. Please research if dealing with 4-byte UTF-8 encodings (e.g. emoticons).
This is one of those frustrating examples of where a standard purpose-made function should exist* but instead one has to use a workaround and finds many complicated user functions online.
*The function does exist in PHP7 (http://php.net/manual/en/intlchar.chr.php), but you need to have the intl extension installed, which I do not believe it is by default.


text:
Q: regex for pattern before a certain word I am having problems finding a right RegEx for recognizing the word before a certain word (but without the latter word). Below is the pattern, where W1 is dynamically asigned word.
   Set regExp = New RegExp
    With regExp
        .Pattern = "\S* " + W1
        .IgnoreCase = True
        .Global = True

This pattern works but i get the whole pattern. If I have such sentence :"Today is a sunny day" and W1 is set as "day", this pattern gives me "sunny day".
I would like to get just sunny, without the W1. Is this possible?
Thanks,m

A: Put W1 inside a positive lookahead assertion.
.Pattern = "\S+(?= *" + W1 + ")"


text:
Q: How do I count data objects in Java I have an assignment that asks me to create students with first name, last name, GPA and major as options the user can input and I am supposed to give these "students" a student ID as well.  I can give them an ID in the constructor of one of the classes but I can't seem to iterate through the student count, to give the students the correct type of student id, eg. 123456, 123457, 123458 etc.  I am only pasting a few lines because the whole assignment is about 300 lines long and I didn't think anyone cared to read it all over.  Can anyone tell me what I'm doing wrong or if this doesn't even make sense to try?  I know of another way but I don't like it because it makes me have the student id numbers stored in a separate ArrayList than the other student data and then I would just match up indices.  Here's the constructor, with count being initialized as a field with 0...
public Student( String fName, String lName, String maj, double gpa) {
    sNumber += count++;
    firstName = fName;
    lastName = lName;
    major = maj;
    this.gpa = gpa;
}

Here's the add method from another class....
private static void addStudent(ArrayList<Student> L) {
    System.out.println();
    Scanner input = new Scanner(System.in);
    System.out.print("First name: ");
    String uFName = input.nextLine();
    System.out.print("Last name: ");
    String uLName = input.nextLine();
    System.out.print("Major: ");
    String studyMaj = input.nextLine();
    System.out.print("GPA: ");
    double grades = input.nextDouble();
    Student newStudent = new Student(uFName, uLName, studyMaj, grades);
    L.add(newStudent);
    input.close();
}

A: try this
public Student( String fName, String lName, String maj, double gpa,number ) {
firstName = fName;
lastName = lName;
major = maj;
this.gpa = gpa;
sNumber = number;
}
private static void addStudent(ArrayList<Student> L) {
System.out.println();
Scanner input = new Scanner(System.in);
System.out.print("First name: ");
String uFName = input.nextLine();
System.out.print("Last name: ");
String uLName = input.nextLine();
System.out.print("Major: ");
String studyMaj = input.nextLine();
System.out.print("GPA: ");
double grades = input.nextDouble();
int number=0;
if(l.size()>0){
  number=l.get(l.size()-1).getSNumber()+1;
}
Student newStudent = new Student(uFName, uLName, studyMaj, grades,number);
L.add(newStudent);
input.close();
}


text:
Q: Bind single tableview for 2 data sources and update based on selected segment with Bond I am trying to bind single UITableView with 2 data sources.
My code is like this
viewModel?.dataSource?.currentYear?.bind(to: tableViewMonths, cellType: StatementExportMonthTableViewCell.self) { (cell, name) in
            cell.updateWith(month: name)
        }

viewModel?.dataSource?.previousYear?.bind(to: tableViewMonths, cellType: StatementExportMonthTableViewCell.self) { (cell, name) in
            cell.updateWith(month: name)
        }

I cant figure out how to show correct data into table view based on selected segment index.
I know i can define one main data source and based on segment selection I should assign respective data source to that instance and reload tableview from that.
But I am trying to simplify it if Bond already has that functionality in-built.
Any help here would be much appreciated.
Thanks


text:
Q: How to send kind of persistent "Authorization" headers with PHP I don't know if it's possible, but if I don't ask I'll never know :)
I have the exact problem discuted in this topic. That's: I have some static files in some folders and I want only some users to see that content. That users are coming from a previous login.
Some possible solutions are discussed in that topic, but I have thought another possible solution. If I could send with PHP the Authorization HTTP Header, which contains the username and password of the user, and keep it persitent in subsequents requests (as I think it happens with the apache authentication). I would send that headers during my previous login, and then when the user would try to access to its directory, an .htaccess would check if he is a valid user.
I have tried to send the Authorization header with PHP with:
header('Authorization: Basic '.base64_encode($USERNAME.':'.$PASSWORD).PHP_EOL);

But they are only present for one request.
In .htaccess, I have checked that it's not possible to have an unique `Require user USERNAME', so I think it would be necessary to create an htpasswd file storing the same credentials than the ones the login process use, and then create an usual authentication configuration (basic or digest):
AuthType Basic
AuthName "Restricted Files"
AuthUserFile /path/to/htpasswd/file
Require user USERNAME

Thank you in advance

A: You could have an Basic or Digest HTTP authentification handled by Apache, with a simple "require valid user".
No apache can implement a lot of mod_auth variations, check for mod_auth* in this page.
So you can tell apache to authenticate on your database, or even to perform authentification with a custom code that you provide with mod_authnz_external.
External script support is good as you could implement a session authentification with a cache level (to prevent redoing the whole authentification for each requested resource), which is what basically happen with the default cookie based session (first authenticate, then just transfer the PHPSESSID, so we'll check the session exists).

A:
I have thought another possible solution. If I could send with PHP the Authorization HTTP Header,

You couldn't


text:
Q: Record Video and capture Image in Android I am developing an application where I need to have constant Camera running inside my app
So I have two things to achieve here,
1. Capture Image
2. Record Video
I am having difficulties to record video and stop and reset camera
Following is snippet of my code:-
import java.io.File;
import java.io.IOException;
import java.util.Date;
import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.MediaRecorder;
import android.media.MediaRecorder.OnInfoListener;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.Menu;
import android.view.SurfaceView;
import android.widget.Toast;

public class Myvideo1 extends Activity  implements SurfaceHolder.Callback {

    @Override
    protected void onDestroy() {
     //   stopRecording();
        super.onDestroy();
    }

    private SurfaceHolder surfaceHolder;
    private SurfaceView surfaceView;
    public MediaRecorder mrec = new MediaRecorder();
    private Camera mCamera;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        surfaceView = (SurfaceView) findViewById(R.id.videoview);
   //     if(mCamera==null)
    //        mCamera = Camera.open();

        // Please maintain sequence of following code.

        // If you change sequence it will not work.

        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        try {
            startRecording();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {

        menu.add(0, 0, 0, "Start");
        return super.onCreateOptionsMenu(menu);
    }

    @Override
   public boolean onOptionsItemSelected(MenuItem item)

    {
        if(item.getTitle().equals("Start"))
        {
            try {

                startRecording();
            //    item.setTitle("Stop");

            } catch (Exception e) {

                String message = e.getMessage();
                Log.i(null, "Problem " + message);
                mrec.release();
            }
        }

        else
        //  if(item.getTitle().equals("Stop"))
        {
          //  mrec.stop();
         //   mrec.release();
         //   mrec = null;
          //  item.setTitle("Start");
        }

        return super.onOptionsItemSelected(item);
    }

    protected void startRecording() throws IOException
    {
        if(mCamera==null)
            mCamera = Camera.open();

         String filename;
         String path;

         path= Environment.getExternalStorageDirectory().getAbsolutePath().toString();

         Date date=new Date();
         filename="/rec"+date.toString().replace(" ", "_").replace(":", "_")+".mp4";

         //create empty file it must use
         File file=new File(path,filename);

        mrec = new MediaRecorder();

        mCamera.lock();
        mCamera.unlock();

        // Please maintain sequence of following code.

        // If you change sequence it will not work.
        mrec.setCamera(mCamera);
        mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        mrec.setAudioSource(MediaRecorder.AudioSource.MIC);
        mrec.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mrec.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
        mrec.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        mrec.setPreviewDisplay(surfaceHolder.getSurface());
        mrec.setOutputFile(path+filename);
        mrec.setMaxDuration(10000);     //10 sec

  //  }

    mrec.setOnInfoListener(new OnInfoListener() {
        @Override
        public void onInfo(MediaRecorder mr, int what, int extra) {
            if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) {
                onStop();

                Toast.makeText(getApplicationContext(), "video of 10 sec is completed", Toast.LENGTH_SHORT).show();

            }
        }
    }
    );

    }

    public void preparerec()
    {
         try {
            mrec.prepare();
            mCamera.setPreviewDisplay(this.surfaceHolder);
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public void startrec()
    {
         mrec.start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,int height) {

        Camera.Parameters parameters = mCamera.getParameters();
        parameters.setPreviewSize(width, height);
        mCamera.setParameters(parameters);
        mCamera.startPreview();

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {

       /* if (mCamera != null) {
            Parameters params = mCamera.getParameters();
            mCamera.setParameters(params);

            Log.i("Surface", "Created");
        }
        else {
            Toast.makeText(getApplicationContext(), "Camera not available!",
                    Toast.LENGTH_LONG).show();

            finish();
        }*/

         try                 {
             //Open the Camera in preview mode
            mCamera = Camera.open();
            preparerec();
            //
             }
         catch(Exception ioe)
             {
             ioe.printStackTrace(System.out);
             }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        mCamera.stopPreview();
        mCamera.release();

    }

    public void onStop(){
        mrec.stop();
        mrec.release();
        mrec = null;
     //   item.setTitle("Start");
    }

}

When I StartRecording the Screen gets flickering and green on my samsung Galaxy s2,s any solution on this?

A: You're creating a camera object both in onCreate (in startRecording - that'll always run before surfaceCreated), and then in surfaceCreated.  Only open the camera once; the second time will throw an exception.
I'd recommend moving your recording code to all run when a user hits a button, to start with; you've split the setup work over 2-3 methods that are all triggered at different times, and you're assuming quite a bit about the order in which they're called.
If you need to start recording immediately when the app starts, I'd recommend having each callback check if all the others have completed, and then firing up recording.

A: This Solution works perfect for me.


text:
Q: Assigned id with auto-increment In Grails I would like to have an id that has a prefix and is autoincremented.
I would have these prefixes: A and B.
Then I would have a following sequence:
new MyObject('A').save() ---> id = A-1
new MyObject('A').save() ---> id = A-2
new MyObject('B').save() ---> id = A-3
and so on... Is it possible to combine assigned generator with auto-increment?

A: Answer is Oracle specific but gives general idea.
Create a sequence in DB:
create sequence MY_SEQ minvalue 1 maxvalue 9999999 start with 1 increment by 1;

Then in Grails:
class MyService {

    def dataSource

    def save( params ) {
        def myDom = new MyDomain( params )
        myDom.id = generateId()
        myDom.save()
    }

    def generateId() {
        def db
        try {
            db = Sql.newInstance( dataSource )
        "A-${db.firstRow( 'SELECT MY_SEQ.NEXTVAL NEXT_ID FROM DUAL' ).NEXT_ID}"
        }
        finally {
            db?.close()
        }
    }
}

A: Just leave the primary key as an integer and add a getter method to derive the A1, B1 value. It's not a good idea to mess with primary keys like you're proposing.


text:
Q: remote execution in windows server via telnet I need to start a process and keep it running on several remote windows (03 and 08) servers.
When I telnet in and start the process and sign out of my telnet session, the process dies.
I changed the registry settings so the pertinent tlntadmn output looks like this:
End tasks on disconnect     :   NO
restarting the service and/or rebooting the server have had no effect. My processes still die when the telnet session ends.
Any advice?

A: My advice would be to ask this question at serverfault.com, which is similar to SO but focuses on sysadmin stuff. As I know near nothing about telnet, if you can't figure this out take a look at PsExec, which will let you run executables on remote machines in various ways.


text:
Q: Suspicious URLs being loaded after hack and restore I had a site that was hacked (had Arab words on the index.php), and all files deleted, but database still there.
I used Fantastico to install a clean release of WP 3.1, and I still some something suspicious.  In lower right side of Firefox it says "Read www.clickcoupon.me".
With FireBug and PageSpeed, I can see it's opening: http://www.clickcoupon.me/plugin/sources/clickcoupon.js and http://clickcoupon.me/plugin/sources/jquery-1.3.2_nd.js which both look extremely suspicious.  These are not part of the standard WordPress are they?
The site is http://cpanelvideocenter.com. As of the time I'm posting this, it is a default install from Fantastico.  Unless they hacked my hosting company as well, I don't see how these files could be involved.

A: If you're using the same database, then the hack code is sometimes stored in there. The pharma hack uses this technique. Ensure that you have a clean database that you're installing into also.

A: Found it!  It was happening in FireFox but not Chrome.  I looked at all my FireFox Extensions, and found "Browser Enhancements 1.0" and "Browser Coupons 1.0"
http://www.webenhancements.me/.
The other URL was searchdock.me, and was reported as a "threat" here:
http://www.threatexpert.com/report.aspx?md5=af6cc99d717c0daef65a9dafd6c45db7
I'm not sure when I installed these or why, but I don't think they were related to the hacking incident.  It was just that when i was analyzing the hack incident carefully, I discovered these "extras" that probably didn't need to be on my machine anyway.

A: I don't see the link with twentyten active, so if it only appears in another theme, clean that theme or replace it with a fresh copy.
Fix your site the right way: see FAQ: My site was hacked « WordPress Codex and How to completely clean your hacked wordpress installation and How to find a backdoor in a hacked WordPress and Hardening WordPress « WordPress Codex and tell your host. Change all passswords. Scan your own PC for spyware. Some plugins might be useful: Search for "security" « WordPress Plugins


text:
Q: Passing arguments by reference to constructors of self-defined objects I have read the sometimes it is better to pass arguments by reference so that if the argument type is large in space, we will not copy it (as happens when we pass by reference).
But I dont quite see how it prevents all of the copies. For example consider the BinaryNode class:
template <class T>
class BinaryNode
{
    public:
    //|-------------------- Constructors --------------------
        BinaryNode(const T& _key):key(_key), left(NULL), right(NULL), parent(NULL){}
    protected:
        T key;
        BinaryNode* left;
        BinaryNode* right;
        BinaryNode* parent;
};

When we declare of new BinaryNode, an element T key is created, and even though we pass by reference the argument, still the copy operator = is being activated and still we got ourselves a copy.
So, is there a way to prevent it? or maybe it is not really a bad thing?
Thanks in advance.

A: If you used
BinaryNode(T _key):key(_key), left(NULL), right(NULL), parent(NULL){}

, then there would be potentially two copies if the argument is a lvalue. One copy construction from the constructor argument to the parameter and one from the parameter to the member.
You would usually avoid copies by preferring move operations instead. For this you can overload for lvalues which need to be copied and rvalues which can be moved:
 BinaryNode(const T& _key):key(_key), left(NULL), right(NULL), parent(NULL){}
 BinaryNode(T&& _key):key(std::move(_key)), left(NULL), right(NULL), parent(NULL){}

which makes a single copy construction if necessary (if the argument to the constructor is a lvalue) and otherwise makes a single move construction via the second overload.
Or with a minimal penalty that usually shouldn't matter you can use a single overload:
BinaryNode(T _key):key(std::move(_key)), left(NULL), right(NULL), parent(NULL){}

which will potentially do one move construction or copy construction to the parameter, depending on whether the constructor argument is a lvalue or rvalue, and whether or not the object is directly constructed in the argument, and one additional move construction to construct the member.

Note that in none of this the assignment operator operator= is used. Only constructors are called.

If the argument to the constructor is a lvalue, then a copy construction cannot be avoided, otherwise a move construction cannot be avoided.


text:
Q: How to determine if a column exists in SQL server DB in other tables with a different name I need to fetch specific hardware data from source tables. The hardware information is present in a table Server_Data with columns as follows,
          Server_ID, Server Property, Property_Value
               65          Model          Cisco 123
               65          Name           Cisco abc

I need to link this table with System table that has columns as follows,
           System_ID,   System_IP
                 1      10.20.30.40

I searched all tables in database but Server_ID column is present only in Server _Data table. Also, I searched all tables if there exists a table that links System_ID with Server_ID, but there is no such table.
I need to find if the Server_ID column is present in any other table with some other name (say Server_Key or just Key). Any help would be appreciated.

A: Only using SQL, there will not be a way to find an identical column in another table, especially if it has a different name.  I think you would need to manually compare every column in every other table to that column to find a match.

A: If I were you I would start by running the following SP:
EXEC sp_fkeys 'Server_Data'

That will tell you if the Server_ID column is referencing any other table in the DB or not.