问:
How to get the byte array data from Reference-arithmetic-coding result
I am trying to implement arithmetic coding using Java,and I found this project:Reference-arithmetic-coding. But its' input and output are both file, I wanna get the byte array that is the coding result from AdaptiveArithmeticCompress.compress(). Here is what I did:
I add a function in class AdaptiveArithmeticCompress named AACompress:

```<code>public static byte[] AACompress(short[] delta) throws  IOException{
    byte[] bytedelta = TypeConversion.ShortToByte_little(delta);
    ByteArrayInputStream bis = new ByteArrayInputStream(bytedelta);
    BitOutputStream out = new BitOutputStream(new ByteArrayOutputStream());

    compress(bis,out);
    return out.toBytearray();
}
</code>```

and create out.toBytearray() to convert outputstream to byte array.

```<code>public byte[] toBytearray() {
    ByteArrayOutputStream baos = (ByteArrayOutputStream) output;
    return baos.toByteArray();
}
</code>```

But when I compared result byte array with result file which is output of AdaptiveArithmeticCompress.compress(InputStream in, BitOutputStream out), I found that

```<code>short[] delta = ...;
byte[] coding = AdaptiveArithmeticCompress.AACompress(delta);
</code>```

coding.length is 1 less than out.buf.length, the last byte of out.buf is missing, so the coding result is wrong.
I am new to Java, this problem has been confusing me several days. Can anyone help me? Thanks a lot.

答:
I solved this problem by adding a close method in ArithmeticEncoder class

```<code>public void close() throws IOException {
    output.close();
}
</code>```

And the missing byte has been added into outputstream.

Body:
I am trying to implement arithmetic coding using Java,and I found this project:Reference-arithmetic-coding. But its' input and output are both file, I wanna get the byte array that is the coding result from AdaptiveArithmeticCompress.compress(). Here is what I did:
I add a function in class AdaptiveArithmeticCompress named AACompress:

public static byte[] AACompress(short[] delta) throws  IOException{
    byte[] bytedelta = TypeConversion.ShortToByte_little(delta);
    ByteArrayInputStream bis = new ByteArrayInputStream(bytedelta);
    BitOutputStream out = new BitOutputStream(new ByteArrayOutputStream());

    compress(bis,out);
    return out.toBytearray();
}

and create out.toBytearray() to convert outputstream to byte array.

public byte[] toBytearray() {
    ByteArrayOutputStream baos = (ByteArrayOutputStream) output;
    return baos.toByteArray();
}

But when I compared result byte array with result file which is output of AdaptiveArithmeticCompress.compress(InputStream in, BitOutputStream out), I found that

short[] delta = ...;
byte[] coding = AdaptiveArithmeticCompress.AACompress(delta);

coding.length is 1 less than out.buf.length, the last byte of out.buf is missing, so the coding result is wrong.
I am new to Java, this problem has been confusing me several days. Can anyone help me? Thanks a lot.

Body:
I solved this problem by adding a close method in ArithmeticEncoder class

public void close() throws IOException {
    output.close();
}

And the missing byte has been added into outputstream.


来源: stackexchange

问:
Import Firestore dependencies and types to node.js
I'm recently updating my cloud functions to TypeScript after the talks on the FirebaseSummit of this year.

All my code looks quite cool, but I'm having some problems trying to recover the types of Firestore API, such QuerySnapshot , DocumentReference...

```<code>async function getEventsMadeByUser(userId: string): Promise<FirebaseFirestore.DocumentSnapshot[]> {
    const eventsMadeByUserQuery = await instance.collection('PrivateUserData')
        .doc(userId).collection(EVENTS)
        .where('interactionUser', '==', userId).get();
    return eventsMadeByUserQuery.docs;
}
</code>```

Right now my IDE (WebStorm) is not getting the types for FirebaseFirestore. This is how my package.json looks:

```<code>{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "dependencies": {
    "firebase-admin": "^5.4.3",
    "firebase-functions": "^0.7.2"
  },
  "devDependencies": {
    "@types/express": "^4.0.37",
    "typescript": "^2.3.2"
  },
  "scripts": {
    "build": "tsc",
    "watch": "tsc --watch",
    "deploy": "tsc && firebase deploy --only functions"
  },
  "main": "build/index.js",
  "private": true
}
</code>```

I have already tried to add @firebase-firestore and nothing, it's not working. What is the right dependency to achieve this?

答: I finally figured it out! The firebase-admin module is just a simple wrapper that initializes Firestore for you. To get the real Firestore, add "@google-cloud/firestore": "^0.9.0" to your package.json. You can admire those beautiful types here: https://github.com/googleapis/nodejs-firestore/blob/master/types/firestore.d.ts.

ContentLicense: CC BY-SA 4.0

Body:
I'm recently updating my cloud functions to TypeScript after the talks on the FirebaseSummit of this year.

All my code looks quite cool, but I'm having some problems trying to recover the types of Firestore API, such QuerySnapshot , DocumentReference...

async function getEventsMadeByUser(userId: string): Promise<FirebaseFirestore.DocumentSnapshot[]> {
    const eventsMadeByUserQuery = await instance.collection('PrivateUserData')
        .doc(userId).collection(EVENTS)
        .where('interactionUser', '==', userId).get();
    return eventsMadeByUserQuery.docs;
}

Right now my IDE (WebStorm) is not getting the types for FirebaseFirestore. This is how my package.json looks:

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "dependencies": {
    "firebase-admin": "^5.4.3",
    "firebase-functions": "^0.7.2"
  },
  "devDependencies": {
    "@types/express": "^4.0.37",
    "typescript": "^2.3.2"
  },
  "scripts": {
    "build": "tsc",
    "watch": "tsc --watch",
    "deploy": "tsc && firebase deploy --only functions"
  },
  "main": "build/index.js",
  "private": true
}

I have already tried to add @firebase-firestore and nothing, it's not working. What is the right dependency to achieve this?

ContentLicense: CC BY-SA 3.0


问:
how to pass data along with files from angular controller to node server?
I am passing some data from angular.js controller in following format:

```<code>data: { model: { title: 'hello'}, files: $scope.files}
</code>```

I am able to get this in node.js by doing this:

req.files

Now I want to send one more data with existing data, so I tried doing this:

```<code>data: { model: { title: 'hello', id:newId}, files: $scope.files}
</code>```

but when I did req.id. I am getting undefined.

What I am doing wrong?

答:
In post call the data is present in body of request obj try to find out your data in req obj like this </p>

```<code>   console.log(req.body)
</code>```

<p>on server side </p>

Body:
I am passing some data from angular.js controller in following format:

data: { model: { title: 'hello'}, files: $scope.files}

I am able to get this in node.js by doing this:

req.files

Now I want to send one more data with existing data, so I tried doing this:

data: { model: { title: 'hello', id:newId}, files: $scope.files}

but when I did req.id. I am getting undefined.

What I am doing wrong?

Body:
In post call the data is present in body of request obj try to find out your data in req obj like this

   console.log(req.body)

on server side


问:
removing duplicates from a table where the value is different
I have data like this:

```<code>city1     | city2       | distance
----------+-------------+----------
kolkata   | chennai     | 250
delhi     | mumbai      | 150
delhi     | kolkata     | 200
chennai   | bangalore   | 100
chennai   | kolkata     | 250
mumbai    | bangalore   | 150
mumbai    | delhi       | 150
</code>```

I want only unique records where the same distance between the same city should be omitted.

For example, here between kolkata-chennai and chennai-kolkata I want only one record.

答:
Try a self join delete:

```<code>DELETE a
FROM yourTable a
INNER JOIN yourTable b
    ON a.city1 = b.city2 AND
       a.city2 = b.city1 AND
       a.distance = b.distance AND
       a.city1 < a.city2;
</code>```

The first three conditions of the ON clause would map, e.g. kolkata chennai 250 to chennai kolkata 250.  The fourth condition also requires that, arbitrarily, the first city be lexicographically less than the second city in order for a record to be targeted for deletion.  So the surviving record would then be kolkata chennai 250, because kolkata is greater than chennai.

Body:
I have data like this:

city1     | city2       | distance
----------+-------------+----------
kolkata   | chennai     | 250
delhi     | mumbai      | 150
delhi     | kolkata     | 200
chennai   | bangalore   | 100
chennai   | kolkata     | 250
mumbai    | bangalore   | 150
mumbai    | delhi       | 150

I want only unique records where the same distance between the same city should be omitted.

For example, here between kolkata-chennai and chennai-kolkata I want only one record.

Body:
Try a self join delete:

DELETE a
FROM yourTable a
INNER JOIN yourTable b
    ON a.city1 = b.city2 AND
       a.city2 = b.city1 AND
       a.distance = b.distance AND
       a.city1 < a.city2;

The first three conditions of the ON clause would map, e.g. kolkata chennai 250 to chennai kolkata 250.  The fourth condition also requires that, arbitrarily, the first city be lexicographically less than the second city in order for a record to be targeted for deletion.  So the surviving record would then be kolkata chennai 250, because kolkata is greater than chennai.


问:
How to add 2 imageviews in layout dynamically in android
I am developing the Android app in which i want to add 2 imagview at time in layout.The flow is in layout there is one imageview added for taking photo via camera when user take photo from camera when I get the image from camera I will show it in that imageview and that imageview has one cross ImageButton on it's right corner which will get visible when image gets loaded and same thing will happen for another imageview which i want to add when user click photo but i dont know how to add this dynamically. I search for answer but there is only one imageview is added in the layout.Please help me out with this issue.

i want it like this
as show in this image the imageview has cross button on it

as per the solution given by Vijendra i updated my xml and java code but having
error

java.lang.IllegalArgumentException: Cannot add a null child view to a ViewGroup

here is my main.xml:

```<code><RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/bicycle_broken_layout">

    <EditText
        android:id="@+id/et_moreinfo_broken_bike"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:layout_marginTop="15dp"
        android:hint="@string/more_info"
        android:layout_marginStart="25dp"
        android:layout_marginEnd="25dp"
        android:background="@color/ch_bg"
        android:paddingTop="5dp"
        android:lines="3"
        android:gravity="top|left"
        android:inputType="textMultiLine"/>

    <RelativeLayout
        android:id="@+id/broken_image_photos"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/et_moreinfo_broken_bike"
        android:layout_marginTop="20dp">

    </RelativeLayout>

    <Button
        android:id="@+id/btn_submit_report"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/broken_image_photos"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="20dp"
        android:layout_centerHorizontal="true"
        android:background="@color/bg_main"
        android:text="@string/submit_button"
        android:textSize="17sp"
        android:textColor="@color/white"
        android:padding="15dp"/>

</RelativeLayout>
</code>```

and here is mainactivity.java

```<code>public class Broken_Report_Activity extends AppCompatActivity implements
View.OnClickListener {

private EditText broken_bike_number,broken_bike_location,more_info;
private Button barcode_scanner,location;
private Button submit_report;
private CheckBox seat,pedals,breaks,lock,chain,tier;
private Imageview_add_dynamically photo1,close_photo,framlayout;
RelativeLayout broken_image_layout;
private boolean Isphoto1=false,Isphoto2=false,Isphoto3=false;

private static final int CAMERA_REQUEST = 1888;

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

    broken_bike_number = (EditText)findViewById(R.id.et_broken_bike_number);
    broken_bike_location =
    (EditText)findViewById(R.id.et_broken_bike_location);
    more_info = (EditText)findViewById(R.id.et_moreinfo_broken_bike);

    submit_report = (Button)findViewById(R.id.btn_submit_report);

    seat = (CheckBox)findViewById(R.id.ch_seat);
    lock = (CheckBox)findViewById(R.id.ch_lock);
    chain = (CheckBox)findViewById(R.id.ch_chain);
    breaks = (CheckBox)findViewById(R.id.ch_break);
    pedals = (CheckBox)findViewById(R.id.ch_pedals);
    tier = (CheckBox)findViewById(R.id.ch_tire);

    broken_image_layout =
    (RelativeLayout)findViewById(R.id.broken_image_photos);

    broken_image_layout.addView(photo1);
    broken_image_layout.addView(close_photo);

    photo1.setOnClickListener(this);
    close_photo.setOnClickListener(this);

    submit_report.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    switch (v.getId()){

        case R.id.broken_img1:
            Intent broken_imag_1 = new
            Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(broken_imag_1,CAMERA_REQUEST);
            break;

        case R.id.broken_img1_close:
            broken_image_layout.removeView(photo1);
            broken_image_layout.removeView(close_photo);
            break;

        case R.id.btn_submit_report:
            break;
    }
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
    super.onActivityResult(requestCode,resultCode,data);
    if(requestCode == CAMERA_REQUEST && resultCode == RESULT_OK){
        Bitmap photo = (Bitmap)data.getExtras().get("data");
        photo1.getImgPhoto().setImageBitmap(photo);

    }
}
</code>```

答:
In Your xml

```<code><HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:id="@+id/multipleimages"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            >
            //add your imageview here programatically
        </LinearLayout>

    </HorizontalScrollView>
</code>```

In Java code

```<code>  LinearLayout ll = (LinearLayout) findViewById(R.id.multipleimages);
        ImageView imageView1=//your image 1
        ImageView imageView2=//your image 2

        ll.addView(imageView1);
        ll.addView(imageView2);
</code>```

Body:
I am developing the Android app in which i want to add 2 imagview at time in layout.The flow is in layout there is one imageview added for taking photo via camera when user take photo from camera when I get the image from camera I will show it in that imageview and that imageview has one cross ImageButton on it's right corner which will get visible when image gets loaded and same thing will happen for another imageview which i want to add when user click photo but i dont know how to add this dynamically. I search for answer but there is only one imageview is added in the layout.Please help me out with this issue.

i want it like this
as show in this image the imageview has cross button on it

as per the solution given by Vijendra i updated my xml and java code but having
error

java.lang.IllegalArgumentException: Cannot add a null child view to a ViewGroup

here is my main.xml:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/bicycle_broken_layout">

    <EditText
        android:id="@+id/et_moreinfo_broken_bike"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:layout_marginTop="15dp"
        android:hint="@string/more_info"
        android:layout_marginStart="25dp"
        android:layout_marginEnd="25dp"
        android:background="@color/ch_bg"
        android:paddingTop="5dp"
        android:lines="3"
        android:gravity="top|left"
        android:inputType="textMultiLine"/>

    <RelativeLayout
        android:id="@+id/broken_image_photos"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/et_moreinfo_broken_bike"
        android:layout_marginTop="20dp">

    </RelativeLayout>

    <Button
        android:id="@+id/btn_submit_report"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/broken_image_photos"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="20dp"
        android:layout_centerHorizontal="true"
        android:background="@color/bg_main"
        android:text="@string/submit_button"
        android:textSize="17sp"
        android:textColor="@color/white"
        android:padding="15dp"/>

</RelativeLayout>

and here is mainactivity.java

public class Broken_Report_Activity extends AppCompatActivity implements
View.OnClickListener {

private EditText broken_bike_number,broken_bike_location,more_info;
private Button barcode_scanner,location;
private Button submit_report;
private CheckBox seat,pedals,breaks,lock,chain,tier;
private Imageview_add_dynamically photo1,close_photo,framlayout;
RelativeLayout broken_image_layout;
private boolean Isphoto1=false,Isphoto2=false,Isphoto3=false;

private static final int CAMERA_REQUEST = 1888;

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

    broken_bike_number = (EditText)findViewById(R.id.et_broken_bike_number);
    broken_bike_location =
    (EditText)findViewById(R.id.et_broken_bike_location);
    more_info = (EditText)findViewById(R.id.et_moreinfo_broken_bike);

    submit_report = (Button)findViewById(R.id.btn_submit_report);

    seat = (CheckBox)findViewById(R.id.ch_seat);
    lock = (CheckBox)findViewById(R.id.ch_lock);
    chain = (CheckBox)findViewById(R.id.ch_chain);
    breaks = (CheckBox)findViewById(R.id.ch_break);
    pedals = (CheckBox)findViewById(R.id.ch_pedals);
    tier = (CheckBox)findViewById(R.id.ch_tire);

    broken_image_layout =
    (RelativeLayout)findViewById(R.id.broken_image_photos);

    broken_image_layout.addView(photo1);
    broken_image_layout.addView(close_photo);

    photo1.setOnClickListener(this);
    close_photo.setOnClickListener(this);

    submit_report.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    switch (v.getId()){

        case R.id.broken_img1:
            Intent broken_imag_1 = new
            Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(broken_imag_1,CAMERA_REQUEST);
            break;

        case R.id.broken_img1_close:
            broken_image_layout.removeView(photo1);
            broken_image_layout.removeView(close_photo);
            break;

        case R.id.btn_submit_report:
            break;
    }
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
    super.onActivityResult(requestCode,resultCode,data);
    if(requestCode == CAMERA_REQUEST && resultCode == RESULT_OK){
        Bitmap photo = (Bitmap)data.getExtras().get("data");
        photo1.getImgPhoto().setImageBitmap(photo);

    }
}

Body:
In Your xml

<HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:id="@+id/multipleimages"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            >
            //add your imageview here programatically
        </LinearLayout>

    </HorizontalScrollView>

In Java code

  LinearLayout ll = (LinearLayout) findViewById(R.id.multipleimages);
        ImageView imageView1=//your image 1
        ImageView imageView2=//your image 2

        ll.addView(imageView1);
        ll.addView(imageView2);


问:
Define Date format, regex match, and check validity - Peer Review
I'm writing a input validation method for codeigniter to check date format.  I'm actually just doing it in a test script to get the functionality nailed down.  I've got something that works but I'd just like see if I'm approaching this the best (or worst) way.

Really specifically I'm looking at the second half, I've commented to point out what I mean.

```<code><?

$input = $_POST['input'];   //text input of intended format
$date  = $_POST['date'];    //text input of date in matching format
                            //examples: y-m-d, Y.M.D, m/D/Y  (Case has no affect)

//I'm setting up a regex string based on given format
$pattern = preg_replace('/[yY]/','([0-9]{4})',$input);
$pattern = preg_replace('/[mM]/','([0-9]{1,2})',$pattern);
$pattern = preg_replace('/[dD]/','([0-9]{1,2})',$pattern);

//escaping slashes (if used as date delimiter)
$pattern = str_replace('/','\/',$pattern);

echo "Format  : " . $input . "<br />";
echo "Date    : " . $date . "<br/>";
echo "============" . "<br />";
echo "<br/>";

//if given date matches given format
if(preg_match('/^'.$pattern.'$/',$date,$matches)) {
    echo 'YAY A MATCH! <br/>';

    //From here down seems like it could be improved, seems a bit brute force
    //All of this below, is trying to get the order of the format so I can feed the proper values
    //to the checkdate() function to check date validity.

    preg_match('/[yY]/', $input, $match_year,PREG_OFFSET_CAPTURE);
    preg_match('/[mM]/', $input, $match_month,PREG_OFFSET_CAPTURE);
    preg_match('/[dD]/', $input, $match_day,PREG_OFFSET_CAPTURE);

    if ($match_year[0][1] < $match_month[0][1] && $match_year[0][1] < $match_day[0][1]) {
        $year = $matches[1];
        array_splice($matches,1,1);
    }
    else if ($match_year[0][1] > $match_month[0][1] && $match_year[0][1] > $match_day[0][1]) {
        $year = $matches[3];
        array_splice($matches,3,1);
    }
    else {
        $year = $matches[2];
        array_splice($matches,2,1);
    }

    if ($match_month[0][1] < $match_day[0][1]) {
        $month = $matches[1];
        $day   = $matches[2];
    }
    else {
        $month = $matches[2];
        $day   = $matches[1];
    }

    echo "<br/>";
    echo "<br/>";
    echo $month . ' / ' . $day . ' / ' . $year . "<br/>";

    if (checkdate($month,$day,$year)) {
        echo "This is a valid date.";
    }
    else {
        echo "This is not a valid date";
    }
}
else {
    echo "Given date does not match given format";
}
</code>```

答:
Why are you doing this? PHP has several ways to determine whether or not something is a valid date, and those are done, stable, and faster to use.

```<code><?php

error_reporting( E_ALL | E_STRICT );

$dates = array(
    '18-01-2011 16:22',
    '2011-01-18 16:22',
    '11-01-18 16:22'
);

foreach( $dates as $date ) {
    echo strftime( '%Y-%m-%d', strtotime( $date ) ) . "\n";
}
</code>```

These dates are all successfully parsed, and the result is 2011-01-18 for each of those. If we're talking about the formatting itself, you might wish to consider the following:

```<code><?php
error_reporting( E_ALL | E_STRICT );

$dates = array(
    '18-01-2011 16:22',
    '2011-01-18 16:22',
    '11-01-18 16:22'
);

$formats = array(
    'Y-m-d',
    'Y-m-d H:i:s',
    'd-m-y',
    'd/m/Y'
);

foreach( $dates as $date ) {
    if( strtotime( $date ) ) { // validate date.
        $datetime = new DateTime( $date );
        foreach( $formats as $format ) {
            echo $datetime->format( $format ) . "\n";
        }
    }
}
</code>```

I don't think writing a function for dates should be necessary for PHP these days, we have all the tools in the language? Here's some documentation:

strftime

DateTime object

ContentLicense: CC BY-SA 2.5

Body:
I'm writing a input validation method for codeigniter to check date format.  I'm actually just doing it in a test script to get the functionality nailed down.  I've got something that works but I'd just like see if I'm approaching this the best (or worst) way.

Really specifically I'm looking at the second half, I've commented to point out what I mean.

<?

$input = $_POST['input'];   //text input of intended format
$date  = $_POST['date'];    //text input of date in matching format
                            //examples: y-m-d, Y.M.D, m/D/Y  (Case has no affect)

//I'm setting up a regex string based on given format
$pattern = preg_replace('/[yY]/','([0-9]{4})',$input);
$pattern = preg_replace('/[mM]/','([0-9]{1,2})',$pattern);
$pattern = preg_replace('/[dD]/','([0-9]{1,2})',$pattern);

//escaping slashes (if used as date delimiter)
$pattern = str_replace('/','\/',$pattern);

echo "Format  : " . $input . "
";
echo "Date    : " . $date . "
";
echo "============" . "
";
echo "
";

//if given date matches given format
if(preg_match('/^'.$pattern.'$/',$date,$matches)) {
    echo 'YAY A MATCH!
';

    //From here down seems like it could be improved, seems a bit brute force
    //All of this below, is trying to get the order of the format so I can feed the proper values
    //to the checkdate() function to check date validity.

    preg_match('/[yY]/', $input, $match_year,PREG_OFFSET_CAPTURE);
    preg_match('/[mM]/', $input, $match_month,PREG_OFFSET_CAPTURE);
    preg_match('/[dD]/', $input, $match_day,PREG_OFFSET_CAPTURE);

    if ($match_year[0][1] < $match_month[0][1] && $match_year[0][1] < $match_day[0][1]) {
        $year = $matches[1];
        array_splice($matches,1,1);
    }
    else if ($match_year[0][1] > $match_month[0][1] && $match_year[0][1] > $match_day[0][1]) {
        $year = $matches[3];
        array_splice($matches,3,1);
    }
    else {
        $year = $matches[2];
        array_splice($matches,2,1);
    }

    if ($match_month[0][1] < $match_day[0][1]) {
        $month = $matches[1];
        $day   = $matches[2];
    }
    else {
        $month = $matches[2];
        $day   = $matches[1];
    }

    echo "
";
    echo "
";
    echo $month . ' / ' . $day . ' / ' . $year . "
";

    if (checkdate($month,$day,$year)) {
        echo "This is a valid date.";
    }
    else {
        echo "This is not a valid date";
    }
}
else {
    echo "Given date does not match given format";
}

Body:
Why are you doing this? PHP has several ways to determine whether or not something is a valid date, and those are done, stable, and faster to use.

<?php

error_reporting( E_ALL | E_STRICT );

$dates = array(
    '18-01-2011 16:22',
    '2011-01-18 16:22',
    '11-01-18 16:22'
);

foreach( $dates as $date ) {
    echo strftime( '%Y-%m-%d', strtotime( $date ) ) . "\n";
}

These dates are all successfully parsed, and the result is 2011-01-18 for each of those. If we're talking about the formatting itself, you might wish to consider the following:

<?php
error_reporting( E_ALL | E_STRICT );

$dates = array(
    '18-01-2011 16:22',
    '2011-01-18 16:22',
    '11-01-18 16:22'
);

$formats = array(
    'Y-m-d',
    'Y-m-d H:i:s',
    'd-m-y',
    'd/m/Y'
);

foreach( $dates as $date ) {
    if( strtotime( $date ) ) { // validate date.
        $datetime = new DateTime( $date );
        foreach( $formats as $format ) {
            echo $datetime->format( $format ) . "\n";
        }
    }
}

I don't think writing a function for dates should be necessary for PHP these days, we have all the tools in the language? Here's some documentation:

strftime

DateTime object


问:
How to animate a bezier curve over a given duration
I have created a bezier curve by adding the following script to an empty game object in the inspector. This draws to complete curve at once when I run the code. How can I animate it over a given period of time, say 2 or 3 seconds?</p>

```<code>public class BCurve : MonoBehaviour {

LineRenderer lineRenderer;
public Vector3 point0, point1, point2;
int numPoints = 50;
Vector3[] positions = new Vector3[50];

// Use this for initialization
void Start () {
    lineRenderer = gameObject.AddComponent<LineRenderer>();
    lineRenderer.material = new Material (Shader.Find ("Sprites/Default"));
    lineRenderer.startColor = lineRenderer.endColor = Color.white;
    lineRenderer.startWidth = lineRenderer.endWidth = 0.1f;
    lineRenderer.positionCount = numPoints;

    DrawQuadraticCurve ();

}

void DrawQuadraticCurve ()  {
    for (int i = 1; i < numPoints + 1; i++) {
        float t = i / (float)numPoints;
        positions [i - 1] = CalculateLinearBeziearPoint (t, point0, point1, point2);

    }
    lineRenderer.SetPositions(positions);
}

Vector3 CalculateLinearBeziearPoint (float t, Vector3 p0, Vector3 p1, Vector3 p2)   {

    float u = 1 - t;
    float tt = t * t;
    float uu = u * u;
    Vector3 p = uu * p0 + 2 * u * t * p1 + tt * p2;

    return p;
}

}
</code>```

答:
This is enhancement of Ed Marty Answers.
to make the coroutine build the curve in given duration you can do it like this

waitDur = duration / numOfPoints;

```<code>public class BCurve : MonoBehaviour {

    LineRenderer lineRenderer;
    public Vector3 point0, point1, point2;
    int numPoints = 50;
    Vector3[] positions = new Vector3[50];

    // Use this for initialization
    void Start () {
        lineRenderer = gameObject.AddComponent<LineRenderer>();
        lineRenderer.material = new Material (Shader.Find ("Sprites/Default"));
        lineRenderer.startColor = lineRenderer.endColor = Color.white;
        lineRenderer.startWidth = lineRenderer.endWidth = 0.1f;

        StartCoroutine(DrawQuadraticCurve (3));
    }

    IEnumerator DrawQuadraticCurve (float duration)  {
        //Calculate wait duration for each loop so it match 3 seconds
        float waitDur = duration / numPoints;

        for (int i = 1; i < numPoints + 1; i++) {
            float t = i / (float)numPoints;
            lineRenderer.positionCount = i;
            lineRenderer.setPosition(i - 1, CalculateLinearBeziearPoint (t, point0, point1, point2));
            yield return new WaitForSeconds(waitDur);
        }
    }

    Vector3 CalculateLinearBeziearPoint (float t, Vector3 p0, Vector3 p1, Vector3 p2)   {

        float u = 1 - t;
        float tt = t * t;
        float uu = u * u;
        Vector3 p = uu * p0 + 2 * u * t * p1 + tt * p2;

        return p;
    }

}
</code>```

Body:
I have created a bezier curve by adding the following script to an empty game object in the inspector. This draws to complete curve at once when I run the code. How can I animate it over a given period of time, say 2 or 3 seconds?

public class BCurve : MonoBehaviour {

LineRenderer lineRenderer;
public Vector3 point0, point1, point2;
int numPoints = 50;
Vector3[] positions = new Vector3[50];

// Use this for initialization
void Start () {
    lineRenderer = gameObject.AddComponent<LineRenderer>();
    lineRenderer.material = new Material (Shader.Find ("Sprites/Default"));
    lineRenderer.startColor = lineRenderer.endColor = Color.white;
    lineRenderer.startWidth = lineRenderer.endWidth = 0.1f;
    lineRenderer.positionCount = numPoints;

    DrawQuadraticCurve ();

}

void DrawQuadraticCurve ()  {
    for (int i = 1; i < numPoints + 1; i++) {
        float t = i / (float)numPoints;
        positions [i - 1] = CalculateLinearBeziearPoint (t, point0, point1, point2);

    }
    lineRenderer.SetPositions(positions);
}

Vector3 CalculateLinearBeziearPoint (float t, Vector3 p0, Vector3 p1, Vector3 p2)   {

    float u = 1 - t;
    float tt = t * t;
    float uu = u * u;
    Vector3 p = uu * p0 + 2 * u * t * p1 + tt * p2;

    return p;
}

}

Body:
This is enhancement of Ed Marty Answers.
to make the coroutine build the curve in given duration you can do it like this

waitDur = duration / numOfPoints;

public class BCurve : MonoBehaviour {

    LineRenderer lineRenderer;
    public Vector3 point0, point1, point2;
    int numPoints = 50;
    Vector3[] positions = new Vector3[50];

    // Use this for initialization
    void Start () {
        lineRenderer = gameObject.AddComponent<LineRenderer>();
        lineRenderer.material = new Material (Shader.Find ("Sprites/Default"));
        lineRenderer.startColor = lineRenderer.endColor = Color.white;
        lineRenderer.startWidth = lineRenderer.endWidth = 0.1f;

        StartCoroutine(DrawQuadraticCurve (3));
    }

    IEnumerator DrawQuadraticCurve (float duration)  {
        //Calculate wait duration for each loop so it match 3 seconds
        float waitDur = duration / numPoints;

        for (int i = 1; i < numPoints + 1; i++) {
            float t = i / (float)numPoints;
            lineRenderer.positionCount = i;
            lineRenderer.setPosition(i - 1, CalculateLinearBeziearPoint (t, point0, point1, point2));
            yield return new WaitForSeconds(waitDur);
        }
    }

    Vector3 CalculateLinearBeziearPoint (float t, Vector3 p0, Vector3 p1, Vector3 p2)   {

        float u = 1 - t;
        float tt = t * t;
        float uu = u * u;
        Vector3 p = uu * p0 + 2 * u * t * p1 + tt * p2;

        return p;
    }

}


问:
Meteor waiting for method call in komposer container before subscribe
So I want to call a method to check if the component should be subscribe or not but i had tried many way and it failed.

```<code>let container = (props, onData) => {
   Meteor.call("check", (err,res){ res return true and false
      if(res){
        const sub = Meteor.subscribe("data");
        if(sub.ready()){
           onData(null, data);
         }
      }
   });
}
</code>```

but the sub.ready() in call back would always false but if i subscribe outside the call back it work but I don't want to subscribe to every component that check method return false

答:
I've had trouble with something similar. My workaround was to not do any too many tasks from within the callbacks. Please check if something along these lines works:</p>

```<code>let container = (props, onData) => {
        // a simple flag
        var canSubscribe = false;

       Meteor.call("check", (err,res){ res return true and false
          if(res){
            canSubscribe = true;

          }
       });
        //moved this outside of the callback.
        if(canSubscribe){
                 const sub = Meteor.subscribe("data");
                 if(sub.ready()){
               onData(null, data);
             }
    }
}
</code>```

Body:
So I want to call a method to check if the component should be subscribe or not but i had tried many way and it failed.

let container = (props, onData) => {
   Meteor.call("check", (err,res){ res return true and false
      if(res){
        const sub = Meteor.subscribe("data");
        if(sub.ready()){
           onData(null, data);
         }
      }
   });
}

but the sub.ready() in call back would always false but if i subscribe outside the call back it work but I don't want to subscribe to every component that check method return false

Body:
I've had trouble with something similar. My workaround was to not do any too many tasks from within the callbacks. Please check if something along these lines works:

let container = (props, onData) => {
        // a simple flag
        var canSubscribe = false;

       Meteor.call("check", (err,res){ res return true and false
          if(res){
            canSubscribe = true;

          }
       });
        //moved this outside of the callback.
        if(canSubscribe){
                 const sub = Meteor.subscribe("data");
                 if(sub.ready()){
               onData(null, data);
             }
    }
}


问:
How to get Distinct rows in Laravel
I have 6 Records in following Table

I Need to get Unique Leads id Columns Order by id DESC.

Following is my Query

```<code>Telecallerfirststep::WhereDate('created_at',date('Y-m-d'))->groupBy('leadsid')->OrderBy('id','DESC')->count();
</code>```

Its Return Number of Records is : 1

答:
```<code>Just Add distinct

Telecallerfirststep::WhereDate('created_at',date('Y-m-d'))-
>groupBy('leadsid')->OrderBy('id','DESC')->distinct()->count();
</code>```

Title: How to get Distinct rows in Laravel

Body:
I have 6 Records in following Table

I Need to get Unique Leads id Columns Order by id DESC.

Following is my Query

Telecallerfirststep::WhereDate('created_at',date('Y-m-d'))->groupBy('leadsid')->OrderBy('id','DESC')->count();

Its Return Number of Records is : 1


问:
jQuery UI datepicker will not display - full code included
I am having trouble displaying the jQuery datepicker as shown here:
http://jqueryui.com/demos/datepicker/

I believe I downloaded all of the proper files, but to be certain, I started from scratch and ripped the demo site.  Not all of it, but what I believed to be the important parts.  The result is no datepicker to be shown and no javascript errors.  Here is my full code sample:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <link rel="stylesheet" href="http://static.jquery.com/ui/css/base2.css" type="text/css" media="all" />
 <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" type="text/css" media="all" />
 <link rel="stylesheet" href="http://static.jquery.com/ui/css/demo-docs-theme/ui.theme.css" type="text/css" media="all" />

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>

<script type="text/javascript" charset="utf-8">
 jQuery(function(){
  jQuery("#datepicker").datepicker();
 });
</script>
</head>
<body>
<input type="text" id="datepicker" class="hasDatepicker" />
</body>
</html>
</code>```

Any help would be very much appreciated.  Thanks!

答:
I had the similar issue.
My resolution was to add z-indexin .date-picker of datePicker.css

```<code>.date-picker {
position: absolute;
z-index:1000;/*********** MY Change *************/
font-size: 1em;
color: #CCC;
text-align: center;
cursor: default;

border: 1px solid #444;
border-radius: 2px;
margin: 6px 0;
background: #222;
box-shadow: 8px 8px 12px rgba(0, 0, 0, 0.2);}
</code>```

That's it!!! And Lo the date picker started displaying.
Hope this helps some one who'd come here for similar issues.

Body:
I am having trouble displaying the jQuery datepicker as shown here:
http://jqueryui.com/demos/datepicker/

I believe I downloaded all of the proper files, but to be certain, I started from scratch and ripped the demo site.  Not all of it, but what I believed to be the important parts.  The result is no datepicker to be shown and no javascript errors.  Here is my full code sample:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 <link rel="stylesheet" href="http://static.jquery.com/ui/css/base2.css" type="text/css" media="all" />
 <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" type="text/css" media="all" />
 <link rel="stylesheet" href="http://static.jquery.com/ui/css/demo-docs-theme/ui.theme.css" type="text/css" media="all" />

<input type="text" id="datepicker" class="hasDatepicker" />

Any help would be very much appreciated.  Thanks!

Body:
I had the similar issue.
My resolution was to add z-indexin .date-picker of datePicker.css

.date-picker {
position: absolute;
z-index:1000;/*********** MY Change *************/
font-size: 1em;
color: #CCC;
text-align: center;
cursor: default;

border: 1px solid #444;
border-radius: 2px;
margin: 6px 0;
background: #222;
box-shadow: 8px 8px 12px rgba(0, 0, 0, 0.2);}

That's it!!! And Lo the date picker started displaying.
Hope this helps some one who'd come here for similar issues.


问:
Rubik´Cube Scrambling Algorithm - JavaScript
I have been working on a Rubik’s Cube Timer website, and I need to make a scrambling algorithm. I’ll go over how the scrambling algorithm should work:
Each face has it’s own letter, it’s initial. for examble, if you want to move the front face, you would write “ F “. If you want to move the the right face, you would write “ R “, and so on. just note that the bottom face is D, as for down. So you have D U R L B F.
If there is nothing after that letter, you turn it clockwise. If there is an appostrophe “ ‘ “, you turn it counter-clockwise. If there is a 2, you turn it two times. Now the thing is that you cannot have 2 same letters next to oneanother, as they would cancel (For example “.. U U’ ...” would be the same as doing nothing. So far, I have this taken care of in my algorithm.
The problem comes when you have one letter, then it’s opposite, then again the first letter, ( For example “.. U D U’...” (would mean Up clockwise, Down clockwise, Up counterclokwise)).
I have no idea how to check for these and avoid them automatically. Here’s the code:</p>

```<code><div id=“Scramble”></div>
<script>
generateScramble();

function generateScramble() {

  // Possible Letters
  var array = new Array(" U", " D", " R", " L", " F", " B")

  // Possible switches
  var switches = ["", "\'", "2"];

  var array2 = new Array(); // The Scramble.

  var last = ''; // Last used letter

  var random = 0;

  for (var i = 0; i < 20; i++) {
      // the following loop runs until the last one
      // letter is another of the new one
      do {
         random = Math.floor(Math.random() * array.length);
      } while (last == array[random])

  // assigns the new one as the last one
  last = array[random];

  // the scramble item is the letter
  // with (or without) a switch
  var scrambleItem = array[random] + switches[parseInt(Math.random()*switches.length)];

  array2.push(scrambleItem); // Get letters in random order in the array.
  }

  var scramble = "Scramble: ";

  // Appends all scramble items to scramble variable
  for(i=0; i<20; i++) {
     scramble += array2[i];
  }

  document.getElementById("Scramble").innerHTML = scramble; // Display the scramble
}
</script>
</code>```

答:
For starters God's Number is 20 for Rubik;s cube so you got only 20 moves instead of 25. I assume you are not doing scrambling (as your title suggest) but instead generate solution command strings for genere&test solver type. There are too many sequences that cancel each other and to check for all of them would be most likely slower than try them out actually.

The problem is that even O(n^20) is huge and you need to lower the 20. That is done by LUT holding semi solved states. For example create table holding states for all combinations of 5 turn scrambling. Then use that as end condition turning your solver into O(n^15 + n^5) = O(n^15) ...


问:
SonarQube Rule plsql:QuotedIdentifiersCheck fails
This SonarQube rule checks that Quoted identifiers are not used.
But SQL syntax requires quotes when column alias is composed with a space.

Agree with the rule when developers create such variable:

```<code>"hello" VARCHAR2(42) := 'world';
</code>```

but disagree for that:

```<code>Select myColA as "Column A",
       myColB as "column B",
       ...
</code>```

Sonar should not hit for alias in Select statement.

Correct ?

答: It seems reasonable. This improvement should be included in the next version of SonarPLSQL.</p>

Body:
This SonarQube rule checks that Quoted identifiers are not used.
But SQL syntax requires quotes when column alias is composed with a space.

Agree with the rule when developers create such variable:

"hello" VARCHAR2(42) := 'world';

but disagree for that:

Select myColA as "Column A",
       myColB as "column B",
       ...

Sonar should not hit for alias in Select statement.

Correct ?


答:
You should try this:</p>

```<code>Telecallerfirststep::whereDate('created_at','=',date('Y-m-d'))->groupBy('leadsid')->count();
</code>```

Title: How to get Distinct rows in Laravel

Body:
You should try this:

Telecallerfirststep::whereDate('created_at','=',date('Y-m-d'))->groupBy('leadsid')->count();


问:
How get variable value from properties file in Shell Script?
I have a properties file test.properties and it contents are as follows:

```<code>x.T1 = 125
y.T2 = 256
z.T3 = 351
</code>```

How can I assign the value of y.T2 (256) to some variable within shell script and echo this value?

答:
I know this is an old question, but I just came across this and if I understand correctly, the question is to get value for a specific key from the properties file.
Why not just use grep to find the key and awk to get the value?

Use grep and awk to extract the value from test.properties

```<code>export yT2=$(grep -iR "^y.T2" test.properties | awk -F "=" '{print $2}')
echo y.T2=$yT2
</code>```

This value will contain space if there's one after the '='. Trim the leading whitespace

```<code>yT2="${yT2#"${yT2%%[![:space:]]*}"}"
</code>```

Reference for trim:
How to trim whitespace from a Bash variable?.
Explanation available at reference link.

Body:
I have a properties file test.properties and it contents are as follows:

x.T1 = 125
y.T2 = 256
z.T3 = 351

How can I assign the value of y.T2 (256) to some variable within shell script and echo this value?

Body:
I know this is an old question, but I just came across this and if I understand correctly, the question is to get value for a specific key from the properties file.
Why not just use grep to find the key and awk to get the value?

Use grep and awk to extract the value from test.properties

export yT2=$(grep -iR "^y.T2" test.properties | awk -F "=" '{print $2}')
echo y.T2=$yT2

This value will contain space if there's one after the '='. Trim the leading whitespace

yT2="${yT2#"${yT2%%[![:space:]]*}"}"

Reference for trim:
How to trim whitespace from a Bash variable?.
Explanation available at reference link.


问:
How to seed the request body directly from the pre request script on postman
I created JSON object (movieData) and saved it as a global variable (all my test cases).
I want to get part of the data (everytime single case) and send it to request body from the pre-request script.

```<code>const movieData = {
   env: "testing",
   domain: "",
   tests: {
     test1: {

       body: {
         movie_id: 568,
         title: "wonder-woman",
         description: "bla bla bla",
       }
       ....
     },
     test2: {

       body: {
         movie_id: 232,
         title: "spider-man",
         description: "bla bla bla",
       }
       ....
     },
     test3: {

       body: {
         movie_id: 212,
         title: "just-woman",
         description: "bla bla bla",
       }
       ....
     },
     test4: {

       body: {
         movie_id: 534,
         title: "just-man",
         description: "bla bla bla",
       }
       ....
     }

   }
}
</code>```

pre-request:

var movies = JSON.parse(pm.globals.get('movieData'));
const test = movies.tests.test1.body;
pm.globals.set('test', test);

body:

"{{test}}"

Anyone help how to do that?

答:
it is easier then you think... a " " would to the dynamic adding trick

as per docs.. the dynamic variable are to be

this is my email body..

```<code>{
    "email": "{{email}}",   //notice the " " quotes
    "password": "cityslicka"
}
</code>```

I am dynamically changing the {{email}} and {{target}} in the pre-request scripts ...

Notice : {{target}} is in URL without quotes where "{{email}}" is in the body and has 'em " "

Body:
I created JSON object (movieData) and saved it as a global variable (all my test cases).
I want to get part of the data (everytime single case) and send it to request body from the pre-request script.

const movieData = {
   env: "testing",
   domain: "",
   tests: {
     test1: {

       body: {
         movie_id: 568,
         title: "wonder-woman",
         description: "bla bla bla",
       }
       ....
     },
     test2: {

       body: {
         movie_id: 232,
         title: "spider-man",
         description: "bla bla bla",
       }
       ....
     },
     test3: {

       body: {
         movie_id: 212,
         title: "just-woman",
         description: "bla bla bla",
       }
       ....
     },
     test4: {

       body: {
         movie_id: 534,
         title: "just-man",
         description: "bla bla bla",
       }
       ....
     }

   }
}

pre-request:

var movies = JSON.parse(pm.globals.get('movieData'));
const test = movies.tests.test1.body;
pm.globals.set('test', test);

body:

"{{test}}"

Anyone help how to do that?

Body:
it is easier then you think... a " " would to the dynamic adding trick

as per docs.. the dynamic variable are to be

this is my email body..

{
    "email": "{{email}}",   //notice the " " quotes
    "password": "cityslicka"
}

I am dynamically changing the {{email}} and {{target}} in the pre-request scripts ...

Notice : {{target}} is in URL without quotes where "{{email}}" is in the body and has 'em " "


问:
Table is mutating
after i insert this code, i got an error telling that

ORA-04091: table (schema).EMPLOYEES is mutating, trigger/function may not see it

ORA-06512: at "HR.TRGADDEMP_1215034", line 7

ORA-04088: error during execution of trigger 'HR.TRGADDEMP_1215034'

What should i do?

```<code>CREATE OR REPLACE TRIGGER TrgAddEmp_1215034
        AFTER INSERT ON Employees
        FOR EACH ROW

        DECLARE
        v_name varchar2(35);
        v_managerName varchar2(20);
        v_dept varchar2(35);

        BEGIN
        Select first_name||' '||last_name
        INTO v_name
        FROM Employees where employee_id = :new.employee_id;

        Select last_name
        into v_managerName
        from employees where employee_id = :new.manager_id;

        Select department_name
        into v_dept
        from departments where department_id = :new.department_id;

        IF v_managerName is NULL THEN
        DBMS_OUTPUT.PUT_LINE('There is a new employee '|| v_name );
        DBMS_OUTPUT.PUT_LINE('The supervisor for this employee has not been decided');
        DBMS_OUTPUT.PUT_LINE('This employee is assigned to '||v_dept|| 'Department');
        ELSIF v_dept is NULL THEN
        DBMS_OUTPUT.PUT_LINE('There is a new employee '|| v_name );
        DBMS_OUTPUT.PUT_LINE('This employee is supervised by ' || v_managerName);
        DBMS_OUTPUT.PUT_LINE('The department for this employee has not been decided');
        ELSE
        DBMS_OUTPUT.PUT_LINE('There is a new employee '|| v_name );
        DBMS_OUTPUT.PUT_LINE('This employee is supervised by ' || v_managerName);
        DBMS_OUTPUT.PUT_LINE('This employee is assigned to '||v_dept|| 'Department');
        END IF;
        END;
</code>```

答:
You should insert a correct code instead of this :)

ORA-4091 means that your triggers tried to select data from it's own table. Just don't do it. Never. Row-level triggers will not allow that.

This code tries to select a data which you already have.

Why you're trying to select first_name & last_name when you have :new.first_name and :new.last_name? And so on...

Title: Table is mutating

Body:
after i insert this code, i got an error telling that

ORA-04091: table (schema).EMPLOYEES is mutating, trigger/function may not see it

ORA-06512: at "HR.TRGADDEMP_1215034", line 7

ORA-04088: error during execution of trigger 'HR.TRGADDEMP_1215034'

What should i do?

CREATE OR REPLACE TRIGGER TrgAddEmp_1215034
        AFTER INSERT ON Employees
        FOR EACH ROW

        DECLARE
        v_name varchar2(35);
        v_managerName varchar2(20);
        v_dept varchar2(35);

        BEGIN
        Select first_name||' '||last_name
        INTO v_name
        FROM Employees where employee_id = :new.employee_id;

        Select last_name
        into v_managerName
        from employees where employee_id = :new.manager_id;

        Select department_name
        into v_dept
        from departments where department_id = :new.department_id;

        IF v_managerName is NULL THEN
        DBMS_OUTPUT.PUT_LINE('There is a new employee '|| v_name );
        DBMS_OUTPUT.PUT_LINE('The supervisor for this employee has not been decided');
        DBMS_OUTPUT.PUT_LINE('This employee is assigned to '||v_dept|| 'Department');
        ELSIF v_dept is NULL THEN
        DBMS_OUTPUT.PUT_LINE('There is a new employee '|| v_name );
        DBMS_OUTPUT.PUT_LINE('This employee is supervised by ' || v_managerName);
        DBMS_OUTPUT.PUT_LINE('The department for this employee has not been decided');
        ELSE
        DBMS_OUTPUT.PUT_LINE('There is a new employee '|| v_name );
        DBMS_OUTPUT.PUT_LINE('This employee is supervised by ' || v_managerName);
        DBMS_OUTPUT.PUT_LINE('This employee is assigned to '||v_dept|| 'Department');
        END IF;
        END;


问:
How to visualize nested lambda syntax?
For the below code,

```<code>public class X{
    ...
    static class Y implements Runnable{
     .....
         List<Thread> makeWorkerThreads(Function<String, Void> task) {
             List<Thread> workerThreads  =  new ArrayList<>();
             mInputList.forEach(input -> workerThreads.add
                            (new Thread(
                                    () -> task.apply(input)
                                    )));
             return workerThreads;
         }
         ....
    } // Y
    ....
} // X
</code>```

where task is

```<code>private Void processInput(String input) {
        ...
}
</code>```

Could not understand below syntax,

```<code>mInputList.forEach(input -> workerThreads.add
                            (new Thread(
                                        () -> task.apply(input)
                                       )
                            )
                    );
</code>```

How task.apply(input) resolve name input in overridden run() method?
Could not visualize run() method

答:
mInputList.forEach() accepts a Consumer<? super String> action argument, where String is the element type of your mInputList List.

Therefore you can look at the outer lambda expression as an anonymous class instance that implements the Consumer interface, and therefore has a void accept(String t); method.

Now, forEach applies that accept method for each element of your mInputList.

The implementation of the accept method in your code looks like this:

```<code>void accept (String input) {
    workerThreads.add (new Thread(() -> task.apply(input)));
}
</code>```

Now you can see where input comes from.

The inner lambda expression () -> task.apply(input) implements the Runnable interface. i.e. it implements a method that takes no argument (hence the () part) and returns nothing (in this case task.apply(input) does return a value, but it is ignored).

Title: How to visualize nested lambda syntax?

Body:
For the below code,

public class X{
    ...
    static class Y implements Runnable{
     .....
         List<Thread> makeWorkerThreads(Function<String, Void> task) {
             List<Thread> workerThreads  =  new ArrayList<>();
             mInputList.forEach(input -> workerThreads.add
                            (new Thread(
                                    () -> task.apply(input)
                                    )));
             return workerThreads;
         }
         ....
    } // Y
    ....
} // X

where task is

private Void processInput(String input) {
        ...
}

Could not understand below syntax,

mInputList.forEach(input -> workerThreads.add
                            (new Thread(
                                        () -> task.apply(input)
                                       )
                            )
                    );

How task.apply(input) resolve name input in overridden run() method?
Could not visualize run() method

Body:
mInputList.forEach() accepts a Consumer<? super String> action argument, where String is the element type of your mInputList List.

Therefore you can look at the outer lambda expression as an anonymous class instance that implements the Consumer interface, and therefore has a void accept(String t); method.

Now, forEach applies that accept method for each element of your mInputList.

The implementation of the accept method in your code looks like this:

void accept (String input) {
    workerThreads.add (new Thread(() -> task.apply(input)));
}

Now you can see where input comes from.

The inner lambda expression () -> task.apply(input) implements the Runnable interface. i.e. it implements a method that takes no argument (hence the () part) and returns nothing (in this case task.apply(input) does return a value, but it is ignored).


问:
How can I migrate a doctrine DB in Symfony when the project is disabled
So I disabled my site with

```<code>symfony project:disable --env=prod
</code>```

And rsynced my new code to the server.

But now when I run

```<code>symfony doctrine:migrate --env=prod
</code>```

I get a warning that the site is currently unavailable.

I clearly don't want to enable the project (yet) as I first want to make it all works. What is the correct way to do this?

答: I would probably restrict access to your IP address in the index.php, such as when working in the dev environment. Enable the project and then run again.</p>

Body:
So I disabled my site with

symfony project:disable --env=prod

And rsynced my new code to the server.

But now when I run

symfony doctrine:migrate --env=prod

I get a warning that the site is currently unavailable.

I clearly don't want to enable the project (yet) as I first want to make it all works. What is the correct way to do this?


问:
How can I able to display content in inventory seperated by commas in vue js?
My json data is

```<code>{ "status": true,
  "data": {
    "pid": 9,
    "Name": "Asok",
    "services": "3, 1, 2, 4, 5, 6",
    "inventory": ["specs", " Testing", "Lens", "Doctors", "Surgeon", "Medicines"]
  }
}
</code>```

Now I am using html as

```<code><div v-for="inv in data.inventory">{{inv}}</div>
</code>```

When I do this way, the data is printing downwards.. I need to display data seperated by commmas in a row??

答:
Your tag's display must be appropriate, for div it is a block, means that it will get the whole width of the row. So the next element will be placed under it. Instead of div you can use span tag to by default set the values after each other. Or you need to change the display property of current div element.

```<code><div>
   <span v-for="inv in data.inventory">{{inv}}</span>
</div>
</code>```

Let me show the examples with jQuery, not vue.js, but the logic is the same, its not the vue's or jquery-s problem.

const obj = { "status": true,
  "data": {
    "pid": 9,
    "Name": "Asok",
    "services": "3, 1, 2, 4, 5, 6",
    "inventory": ["specs", " Testing", "Lens", "Doctors", "Surgeon", "Medicines"]
  }
};

let str = '';

obj.data.inventory.forEach(ivt => {
  str += `<div>${ivt}</div>`;
});

$('#myFirstDiv').html(str);
str = '';

obj.data.inventory.forEach(ivt => {
  str += `<span>${ivt}</span>`;
});

$('#mySecondDiv').html(str);
str = '';

obj.data.inventory.forEach(ivt => {
  str += `<div class='inline-block'>${ivt}</div>`;
});

$('#myThirdDiv').html(str);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.inline-block {
   display: inline-block
}</code>```

With divs

With spans

With changed display

```

Body:
My json data is

{ "status": true,
  "data": {
    "pid": 9,
    "Name": "Asok",
    "services": "3, 1, 2, 4, 5, 6",
    "inventory": ["specs", " Testing", "Lens", "Doctors", "Surgeon", "Medicines"]
  }
}

Now I am using html as

{{inv}}

When I do this way, the data is printing downwards.. I need to display data seperated by commmas in a row??

Body:
Your tag's display must be appropriate, for div it is a block, means that it will get the whole width of the row. So the next element will be placed under it. Instead of div you can use span tag to by default set the values after each other. Or you need to change the display property of current div element.

<div>
   <span v-for="inv in data.inventory">{{inv}}</span>
</div>

Let me show the examples with jQuery, not vue.js, but the logic is the same, its not the vue's or jquery-s problem.

const obj = { "status": true,
  "data": {
    "pid": 9,
    "Name": "Asok",
    "services": "3, 1, 2, 4, 5, 6",
    "inventory": ["specs", " Testing", "Lens", "Doctors", "Surgeon", "Medicines"]
  }
};

let str = '';

obj.data.inventory.forEach(ivt => {
  str += `<div>${ivt}</div>`;
});

$('#myFirstDiv').html(str);
str = '';

obj.data.inventory.forEach(ivt => {
  str += `<span>${ivt}</span>`;
});

$('#mySecondDiv').html(str);
str = '';

obj.data.inventory.forEach(ivt => {
  str += `<div class='inline-block'>${ivt}</div>`;
});

$('#myThirdDiv').html(str);

div.inline-block {
   display: inline-block
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
With divs
<div id='myFirstDiv'>

</div>
<br/>
With spans
<div id='mySecondDiv'>

</div>
<br/>
With changed display
<div id='myThirdDiv'>

</div>


问:
How to minimize load time of a landing page
I'm honestly confused about where to start with minimizing the load time of a website i'm building - https://projectrhea.herokuapp.com/ . Currently takes around 9 seconds to load the website which I want to try and bring down to sub 3 seconds.

I've done a diagnostic test, shown here https://www.webpagetest.org/result/171113_T2_851758db144ac117ab4e986a3798b1b5/1/details/#waterfall_view_step1 .

From what I can see there are three main reasons it would be taking awhile to load.

The first is the javascript.

I only need a small amount of it to run the site but I am very
confused about how to separate the code I need from the code I don't
need. I use it for the banner to show multiple phrases underneath the
banner that I would rather keep.

The second part is the shear amount of CSS files I'm drawing from.

I used a template to begin the site (it was a good way for me to learn
how to design the site). Now I think this has meant there is way too
many css and other files connected to this landing page.

The third part is the video file I have.

I would love to keep this
video as I just like how it fits in the site. I'll try and minimize
the file size after I have worked out the above issues.

This is my first real time trying to solve an issue like this and I would really appreciate the knowledge a more experienced coder could bring to this. Thanks!

答:
Well for a start -

Place the css at the top, consider using a js loader to load the js once the page has loaded.

If you can obviously remove everything you don't need their are tools to do this but in reality is a tough task especially if its a template

And finally with the video get an image of the first frame, show the image not the video when the page loads.

How to make a loading image when loading HTML5 video?


问:
How to get data value of one input field from a list?
How can I get the value of the first input field from a list?

```<code><button id="hello">get data</button><br><br>
   <table> <td><label for="voucher_<?php echo $counter; ?>">D/N Number <?php echo $counter; ?></label><br>
    <input type="text" name="voucher_<?php echo $counter; ?>" class="input-field exsmall-input" value="<?php echo $voucher; ?>" placeholder="D/N Number" id="voucher_<?php echo $counter; ?>" required>
    </td></table>
</code>```

When I run the above code the number of rows varies depending on the counter.If I want to get the value of the first DN number ,what shall I do ?

```<code>$(document).ready(function(){
    $('#hello').click(function(){
          var name = $("#voucher").val();
        alert(name);
    });
});
</code>```

When I run this javascript I get undefined vales.

答:
You can do it like below:-

```<code>$(document).ready(function(){
    $('#hello').click(function(){
          var name = $("div[id^='voucher']:visible:first").val();
        alert(name);
    });
});
</code>```

Or:-

```<code>$(document).ready(function(){
    $('#hello').click(function(){
          var name = $("input[type=text]:visible:first").val();
        alert(name);
    });
});
</code>```

Body:
How can I get the value of the first input field from a list?

<button id="hello">get data</button>

 <label for="voucher_<?php echo $counter; ?>">D/N Number <?php echo $counter; ?>

    <input type="text" name="voucher_<?php echo $counter; ?>" class="input-field exsmall-input" value="<?php echo $voucher; ?>" placeholder="D/N Number" id="voucher_<?php echo $counter; ?>" required>

When I run the above code the number of rows varies depending on the counter.If I want to get the value of the first DN number ,what shall I do ?

$(document).ready(function(){
    $('#hello').click(function(){
          var name = $("#voucher").val();
        alert(name);
    });
});

When I run this javascript I get undefined vales.

Body:
You can do it like below:-

$(document).ready(function(){
    $('#hello').click(function(){
          var name = $("div[id^='voucher']:visible:first").val();
        alert(name);
    });
});

Or:-

$(document).ready(function(){
    $('#hello').click(function(){
          var name = $("input[type=text]:visible:first").val();
        alert(name);
    });
});


问:
How can you speed up Eclipse?
How can you make the experience with Eclipse faster?

For instance: I disable all the plugins I don't need (Mylyn, Subclipse, …).

Instead of using a plugin for Mercurial, I configure TortoiseHG as an external tool.

答:
We use GIT as CVS and gradle as build tool.

Symptom

In my case one specific project with > 20'000 files froze using hierarchical view when navigating a directory with a lot of files.

Fix

Create new Eclipse workspace

Freshly clone the project into the Eclipse workspace

Import project into Eclipse (in our case using Gradle import)

OwnerDisplayName: damian

Title: How can you speed up Eclipse?

LastEditorDisplayName: erickson


问:
How to apply SRP to user interface classes?
My application uses a DI framework and follows "program to an interface" practice wherever necessary.

I use constructor injection since I'd like to see the dependencies explicitly. But now the constructors of my form classes take too many parameters (>=4 e.g).

Question: Since UI design doesn't usually adhere to SRP, a Winform class might have n constructor dependencies. Do you like to leave them as they are, pass a proxy object instead, use a service locator...? Also do you inject "aspects" (logger, etc) in every constructor, given that no aop-framework is used?

答:
There's no reason why UI implementations should not adhere to SRP. Using patterns such as MVP, MVC or MVVM, a UI class' single responsibility is to to render and collect data through the UI. This is often best done through rather passive data structures such as View Models.

The issue about constructor over-injection should be addressed by refactoring to Aggregate Services.

Aspects are best addressed through application of the Decorator design pattern.


问:
Pivot for Unknown number of values in description- SQL Server 2008
May some one please help me how to get the result in SQL SERVER 2008</p>

答:
Try the below change in your query

```<code>set @query = 'SELECT  ' + @cols + ' from
             (
                select [Generic Name], Description
                from @TABLE
            ) x
            pivot
            (
                MAX([Generic Name])
                for Description in (' + @cols + ')
            ) p '
</code>```

Since you are pivoting the records, there won't be a column [Generic Name] -- I Don't see any such column in the table structure so I'm assuming that you need to column Base Name-- so, the @Cols parameter is enough

Please Check the Demo here

Body:
Try the below change in your query

set @query = 'SELECT  ' + @cols + ' from
             (
                select [Generic Name], Description
                from @TABLE
            ) x
            pivot
            (
                MAX([Generic Name])
                for Description in (' + @cols + ')
            ) p '

Since you are pivoting the records, there won't be a column [Generic Name] -- I Don't see any such column in the table structure so I'm assuming that you need to column Base Name-- so, the @Cols parameter is enough

Please Check the Demo here


问:
return values where key contains this string
I have an array like this:

```<code>array(
    [root_1] => array(
        [level_1] => array(
            [id_1] => array(
                [foo] = bar
            )
        )
    )
)
</code>```

Where I know the names (i.e root, level and id) but I do not know the number part of the key.

I need a function that can return any parts of the array where the key contains a given name.

Cheers

答:
Here you go</p>

```<code>function search_incomplete ($needle, $haystack)
{
    foreach (new RecursiveIteratorIterator (new RecursiveArrayIterator ($haystack), RecursiveIteratorIterator::SELF_FIRST) as $key => $value)
    {
        if (strpos ($key, $needle) === 0)
        {
            return $value;
        }
    }
}

$array = array (
    'root_1'    => array (
        'level_1'   => array (
            'foo'   => 'bar',
        ),
    ),
);

var_dump (search_incomplete ('level', $array));
var_dump (search_incomplete ('root', $array));
var_dump (search_incomplete ('foo', $array));
</code>```

Body:
I have an array like this:

array(
    [root_1] => array(
        [level_1] => array(
            [id_1] => array(
                [foo] = bar
            )
        )
    )
)

Where I know the names (i.e root, level and id) but I do not know the number part of the key.

I need a function that can return any parts of the array where the key contains a given name.

Cheers

Body:
Here you go

function search_incomplete ($needle, $haystack)
{
    foreach (new RecursiveIteratorIterator (new RecursiveArrayIterator ($haystack), RecursiveIteratorIterator::SELF_FIRST) as $key => $value)
    {
        if (strpos ($key, $needle) === 0)
        {
            return $value;
        }
    }
}

$array = array (
    'root_1'    => array (
        'level_1'   => array (
            'foo'   => 'bar',
        ),
    ),
);

var_dump (search_incomplete ('level', $array));
var_dump (search_incomplete ('root', $array));
var_dump (search_incomplete ('foo', $array));


问:
close dropdown menu when i click outside in angular4
i just want to close dropdown on clicking outside without using a directive. i am confused how to do it.please help me out. this my notification component

here is my code of notification.html

```<code>   <a class="cursor-pointer"  matTooltip="Notifications"
   target="_blank" (click)="shownotification()">

<i class="fa-bell fa" ></i>
</a>

 <div class="notification-container" *ngIf = "notification">
  <div class="up-arrow"></div>
  <div class="header">
      <h4 style="padding-right:40px;">Notification</h4>
      <h4 style="padding-left:90px;padding-right:0px;"><span>3</span></h4>

  </div>

  <div class="all-notifications">
  <div class="notifications">
    <span><i class="fa fa-check-circle" aria-hidden="true" style="color:green;"></i></span>  <span class="f_clr">Lorem Ipsum Dollar</span> <span class="f_clr right_text"><span>2</span></span>
  </div>

  <div class="notifications">
      <span><i class="fa fa-clock-o" aria-hidden="true" style="color:rgb(37, 125, 226);"></i></span>  <span class="f_clr">Lorem Ipsum Dollar</span> <span class="f_clr right_text"><span>2</span></span>
    </div>

    <div class="notifications">
        <span><i class="fa fa-cog" aria-hidden="true" style="color:rgb(196, 73, 24);"></i></span>  <span class="f_clr">Lorem Ipsum Dollar</span> <span class="f_clr right_text"><span>2</span></span>
      </div>

  </div>
</code>```

here is my notification.component.ts

```<code> notification: boolean = false;

  constructor() { }

  ngOnInit() {
  }
  shownotification() {
    this.notification = !this.notification;
     console.log(this.notification);
    }
</code>```

答:
```<code>@HostListener('document:click', ['$event', '$event.target'])
public onClick(event: MouseEvent, targetElement: HTMLElement): void {
    if (!targetElement) {
        return;
    }

    const clickedInside = this._elementRef.nativeElement.contains(targetElement);
    if (!clickedInside) {
         this.closeDropDown()
    }
}
</code>```

Or use any implementation of clickoutside directive like this one:
https://www.npmjs.com/package/angular2-click-outside

https://www.npmjs.com/package/ng2-click-outside

Body:
i just want to close dropdown on clicking outside without using a directive. i am confused how to do it.please help me out. this my notification component

here is my code of notification.html

Notification

3

      Lorem Ipsum Dollar 2

        Lorem Ipsum Dollar 2

          Lorem Ipsum Dollar 2

here is my notification.component.ts

 notification: boolean = false;

  constructor() { }

  ngOnInit() {
  }
  shownotification() {
    this.notification = !this.notification;
     console.log(this.notification);
    }

Body:
@HostListener('document:click', ['$event', '$event.target'])
public onClick(event: MouseEvent, targetElement: HTMLElement): void {
    if (!targetElement) {
        return;
    }

    const clickedInside = this._elementRef.nativeElement.contains(targetElement);
    if (!clickedInside) {
         this.closeDropDown()
    }
}

Or use any implementation of clickoutside directive like this one:
https://www.npmjs.com/package/angular2-click-outside

https://www.npmjs.com/package/ng2-click-outside


问:
vim cannot connect to cscope database
I have opensuse 11.4 installed. Vim is version 7. Now I normally use it to browse the linux kernel source. So I generated the cscope database inside a directory within my home folder i.e. /home/aijazbaig1/cscope_DB/ and I got 3 files viz. cscope.out, cscope.po.out and cscope.in.out besides the cscope.files file which contains a list of all the relevant files which I want to search.

Additionally I have added the following to my .bashrc:

```<code>CSCOPE_DB=/home/aijazbaig1/cscope_DB/cscope.out
export CSCOPE_DB
</code>```

But when I do a :cscope show from within vim it says there are no connections. Can anyone please let me know what is going wrong.

Keen to hear from you,

答:
You need to add a "cscope connection", like this in vim:

```<code>:cscope add $PATH_TO_CSCOPE.out
</code>```

See :help cs for more examples.

Title: vim cannot connect to cscope database

Body:
I have opensuse 11.4 installed. Vim is version 7. Now I normally use it to browse the linux kernel source. So I generated the cscope database inside a directory within my home folder i.e. /home/aijazbaig1/cscope_DB/ and I got 3 files viz. cscope.out, cscope.po.out and cscope.in.out besides the cscope.files file which contains a list of all the relevant files which I want to search.

Additionally I have added the following to my .bashrc:

CSCOPE_DB=/home/aijazbaig1/cscope_DB/cscope.out
export CSCOPE_DB

But when I do a :cscope show from within vim it says there are no connections. Can anyone please let me know what is going wrong.

Keen to hear from you,

Body:
You need to add a "cscope connection", like this in vim:

:cscope add $PATH_TO_CSCOPE.out

See :help cs for more examples.


问:
How to change the color of markers in cluster?
I searched and found out that it is possible to change color of only the cluster icon, the markers take only the default color
please help...thanks is advance</p>

```<code>public class MyItem implements ClusterItem {
private final LatLng mPosition;
private final String mTitle;
private final String mSnippet;

public MyItem(double lat, double lng) {
    mPosition = new LatLng(lat, lng);
}

public MyItem(double lat, double lng, String title, String snippet) {
    mPosition = new LatLng(lat, lng);
    mTitle = title;
    mSnippet = snippet;
}

@Override
public LatLng getPosition() {
    return mPosition;
}

@Override
public String getTitle() {
    return mTitle;
}

@Override
public String getSnippet() {
    return mSnippet;
} }
</code>```

答: Use textColor which sets the color of the label text shown on the cluster icon. You can see the documentation here and here.

Body:
I searched and found out that it is possible to change color of only the cluster icon, the markers take only the default color
please help...thanks is advance

public class MyItem implements ClusterItem {
private final LatLng mPosition;
private final String mTitle;
private final String mSnippet;

public MyItem(double lat, double lng) {
    mPosition = new LatLng(lat, lng);
}

public MyItem(double lat, double lng, String title, String snippet) {
    mPosition = new LatLng(lat, lng);
    mTitle = title;
    mSnippet = snippet;
}

@Override
public LatLng getPosition() {
    return mPosition;
}

@Override
public String getTitle() {
    return mTitle;
}

@Override
public String getSnippet() {
    return mSnippet;
} }


问:
Parameterized query with string literal in node-postgres
I'm trying to write a node-postgres query that takes an integer to use in an interval as a parameter:

```<code>  const query = {
    text:
      `SELECT
        foo
        FROM bar
        WHERE
          DATE(created_at) >= DATE(NOW()) - INTERVAL '$1 DAYS';`,
    values: [daysAgo]
  }
</code>```

When I run this, it gives this error message indicating it's not seeing the $1 because it's enclosed in single quotes:

bind message supplies 1 parameters, but prepared statement "" requires 0

Is there a supported way to do this? If not, what is the best work around?

答:
I found this reference which shows you can use the convention of '1 DAY' * X.

I was able to get this working thus:

```<code>   (async () => {
       const { rows } = await pgpool.query(`
          SELECT id, name FROM users
           WHERE DATE(created) <= DATE(NOW()) - INTERVAL '1 DAY' * $1;`,
           [req.params.daysAgo]);
</code>```

Body:
I'm trying to write a node-postgres query that takes an integer to use in an interval as a parameter:

  const query = {
    text:
      `SELECT
        foo
        FROM bar
        WHERE
          DATE(created_at) >= DATE(NOW()) - INTERVAL '$1 DAYS';`,
    values: [daysAgo]
  }

When I run this, it gives this error message indicating it's not seeing the $1 because it's enclosed in single quotes:

bind message supplies 1 parameters, but prepared statement "" requires 0

Is there a supported way to do this? If not, what is the best work around?

Body:
I found this reference which shows you can use the convention of '1 DAY' * X.

I was able to get this working thus:

   (async () => {
       const { rows } = await pgpool.query(`
          SELECT id, name FROM users
           WHERE DATE(created) <= DATE(NOW()) - INTERVAL '1 DAY' * $1;`,
           [req.params.daysAgo]);


问:
Separating 'body' of domain name from extension - DOS shell
I tried everything possible, but still failed. I thought I got it at the point which I'll post

as my final attempt, but still isn't good [enough].

A script is being passed three arguments. Domain name, username and password.

But the probles is that I need domain separated in "domain" + ".com" format. Two variables.

I tried to split it using name.extension cheat, but it doesn't work quite well.

Check the simple code:

```<code>@echo off
echo.
set domain=%~n1
set ext=%~x1
echo %DOMAIN%
echo %EXT%
echo.
</code>```

When you try it, you get:

```<code>D:\Scripts\test>test.bat domain.com

domain
.com

D:\Scripts\test>test.bat domain.co.uk

domain.co
.uk
</code>```

First obviously does work, but only because I'm able to cheat my way through.

String operations in DOS Shell are a pain in the ass. I might be able to convince

a script writer to pass me 4 arguments instead of 3... but in case that fails... HELP!

答:
If you want to automatize something (as stated in another answer), my solution would be to use appropriate tools. Install a Perl runtime or something else you're comfortable with. Or use the Windows power shell

Also, unless you supply your script with a list of valid top level domains, there is NO WAY, in no language, that your script can decide whether test.co.uk should be splitted as text and co.uk or test.co and uk. The only feasible possibility would be to make sure that you get only second-level-domains without sub-domain parts. Simply split at the first dot in that case.

BTW: I'm curious to why you would want to automate website creation in a Windows shell script. You aren't doing anything nasty, are you?

OwnerDisplayName: Six

Body:
I tried everything possible, but still failed. I thought I got it at the point which I'll post

as my final attempt, but still isn't good [enough].

A script is being passed three arguments. Domain name, username and password.

But the probles is that I need domain separated in "domain" + ".com" format. Two variables.

I tried to split it using name.extension cheat, but it doesn't work quite well.

Check the simple code:

@echo off
echo.
set domain=%~n1
set ext=%~x1
echo %DOMAIN%
echo %EXT%
echo.

When you try it, you get:

D:\Scripts\test>test.bat domain.com

domain
.com

D:\Scripts\test>test.bat domain.co.uk

domain.co
.uk

First obviously does work, but only because I'm able to cheat my way through.

String operations in DOS Shell are a pain in the ass. I might be able to convince

a script writer to pass me 4 arguments instead of 3... but in case that fails... HELP!

OwnerDisplayName: sirprize


问:
Global structure in Header files
i have a question regarding structure in c and there declaration in header file.
i am writing a code in which there are 3 variables which have another two variables linked with it. so i decided to declare a structure. below i'm writing a Pseudo-code

```<code>//----------registers.h---------
#ifndef __REG__H__
#define __REG__H__

struct ADE_reg_type
{
    unsigned int i : 4;
    unsigned int j : 4;
};

extern struct ADE_reg_type AIRMS_reg;
extern struct ADE_reg_type BIRMS_reg;
extern struct ADE_reg_type CIRMS_reg;
#endif

//-----------registers.c-------------------
#include "registers.h"

struct ADE_reg_type AIRMS_reg = {.i = 4,.j = 5};  //initializing
struct ADE_reg_type BIRMS_reg = {.i = 3,.j = 4};  //initializing
struct ADE_reg_type CIRMS_reg = {.i = 1,.j = 9};  //initializing

//-----------main.c-------------------
#include "registers.h"

int main()
{
   display_numbers(AIRMS_reg);  //display_numbers(struct ADE_reg_type) has
                              //defined in another .c file which also includes
                              // registers.h
}
</code>```

What i'm want is that i should have a variable which i can access in any .c file. scope of variable should be global. so is it a right way to use a global structure or i'm making some mistake here ?

答:
```<code>//----------registers.h---------
#ifndef __REG__H__
#define __REG__H__

struct ADE_reg_type
{
    unsigned int i : 4;
    unsigned int j : 4;
};

#endif

//-----------registers.c-------------------
#include "registers.h"

const struct ADE_reg_type AIRMS_reg = {.i = 4,.j = 5};  //initializing
const struct ADE_reg_type BIRMS_reg = {.i = 3,.j = 4};  //initializing
const struct ADE_reg_type CIRMS_reg = {.i = 1,.j = 9};  //initializing

//-----------main.c-------------------
#include "registers.h"

extern const struct ADE_reg_type AIRMS_reg;

extern const struct ADE_reg_type BIRMS_reg;

extern const struct ADE_reg_type CIRMS_reg;

int main()
{
   display_numbers(AIRMS_reg);
}

//-----------------file_1.c--------------------
#include "registers.h"

extern const struct ADE_reg_type AIRMS_reg;

extern const struct ADE_reg_type BIRMS_reg;

extern const struct ADE_reg_type CIRMS_reg;

//-----------------file_2.c--------------------
#include "registers.h"

extern const struct ADE_reg_type AIRMS_reg;

extern const struct ADE_reg_type BIRMS_reg;

extern const struct ADE_reg_type CIRMS_reg;
</code>```

Like this one you are say @Elad Hazan

Title: Global structure in Header files

Body:
i have a question regarding structure in c and there declaration in header file.
i am writing a code in which there are 3 variables which have another two variables linked with it. so i decided to declare a structure. below i'm writing a Pseudo-code

//----------registers.h---------
#ifndef __REG__H__
#define __REG__H__

struct ADE_reg_type
{
    unsigned int i : 4;
    unsigned int j : 4;
};

extern struct ADE_reg_type AIRMS_reg;
extern struct ADE_reg_type BIRMS_reg;
extern struct ADE_reg_type CIRMS_reg;
#endif

//-----------registers.c-------------------
#include "registers.h"

struct ADE_reg_type AIRMS_reg = {.i = 4,.j = 5};  //initializing
struct ADE_reg_type BIRMS_reg = {.i = 3,.j = 4};  //initializing
struct ADE_reg_type CIRMS_reg = {.i = 1,.j = 9};  //initializing

//-----------main.c-------------------
#include "registers.h"

int main()
{
   display_numbers(AIRMS_reg);  //display_numbers(struct ADE_reg_type) has
                              //defined in another .c file which also includes
                              // registers.h
}

What i'm want is that i should have a variable which i can access in any .c file. scope of variable should be global. so is it a right way to use a global structure or i'm making some mistake here ?

Body:
//----------registers.h---------
#ifndef __REG__H__
#define __REG__H__

struct ADE_reg_type
{
    unsigned int i : 4;
    unsigned int j : 4;
};

#endif

//-----------registers.c-------------------
#include "registers.h"

const struct ADE_reg_type AIRMS_reg = {.i = 4,.j = 5};  //initializing
const struct ADE_reg_type BIRMS_reg = {.i = 3,.j = 4};  //initializing
const struct ADE_reg_type CIRMS_reg = {.i = 1,.j = 9};  //initializing

//-----------main.c-------------------
#include "registers.h"

extern const struct ADE_reg_type AIRMS_reg;

extern const struct ADE_reg_type BIRMS_reg;

extern const struct ADE_reg_type CIRMS_reg;

int main()
{
   display_numbers(AIRMS_reg);
}

//-----------------file_1.c--------------------
#include "registers.h"

extern const struct ADE_reg_type AIRMS_reg;

extern const struct ADE_reg_type BIRMS_reg;

extern const struct ADE_reg_type CIRMS_reg;

//-----------------file_2.c--------------------
#include "registers.h"

extern const struct ADE_reg_type AIRMS_reg;

extern const struct ADE_reg_type BIRMS_reg;

extern const struct ADE_reg_type CIRMS_reg;

Like this one you are say @Elad Hazan


问:
Javascript Arithmetics
When we subtract/multiply/divide a number with a number(type as string), it will treat both variable as number.

But when we add a number with a number(type as string), it will treat second var as string and concat the variables.

For example

var a = 4;
var b = "4";
var c;

c = a + b;
console.log(c)

c = a - b;
console.log(c)

c = a * b;
console.log(c)

c = a / b;
console.log(c)```

Result output is

"44"

0

16

1

Why there is different behaviour for addition in javascript?

答:
Because "+" ist not only an arithmetic operator but also the "string concatination operator".

In your first example you concatenate 2 strings.

In your other examples the string is coerced to a number and then the arithmetic operation is executed.

There are some steps to prevent this from happening:

var a = 4;
var b = "4";

c = +b + a // 8
console.log(c);
c = parseInt(b) + a // 8
console.log(c);
c = b*1 + a // 8
console.log(c);```

You just have to make sure that both variables have the type number when you add them together.

Title: Javascript Arithmetics

Body:
When we subtract/multiply/divide a number with a number(type as string), it will treat both variable as number.

But when we add a number with a number(type as string), it will treat second var as string and concat the variables.

For example

var a = 4;
var b = "4";
var c;

c = a + b;
console.log(c)

c = a - b;
console.log(c)

c = a * b;
console.log(c)

c = a / b;
console.log(c)

Result output is

"44"

0

16

1

Why there is different behaviour for addition in javascript?

Body:
Because "+" ist not only an arithmetic operator but also the "string concatination operator".

In your first example you concatenate 2 strings.

In your other examples the string is coerced to a number and then the arithmetic operation is executed.

There are some steps to prevent this from happening:

var a = 4;
var b = "4";

c = +b + a // 8
console.log(c);
c = parseInt(b) + a // 8
console.log(c);
c = b*1 + a // 8
console.log(c);

You just have to make sure that both variables have the type number when you add them together.


答:
This is because + operator is also used for string concatenation. You can use the + operator incase you want to convert in into a number

var a = 4;
var b = "4";
console.log(a + b);
console.log(a + +b);```

Title: Javascript Arithmetics


问:
Grouping the list elements into user defined intervals
```<code>def interval():
    data = [1, 2, 12, 13, 22, 23, 32, 33, 42, 43, 52, 53, 62, 63, 72, 73, 82, 83, 92, 93]
    minimum = raw_input("Enter the min value")
    maximum = raw_input("Enter the max value")
    frequency = raw_input("Enter the Freq")
    x = []
    x.append(float(minimum))
    thesum = float(minimum)
    for i in range(0, int(maximum)):
        if thesum < float(maximum):
            thesum = thesum + float(frequency)
            x.append(thesum)
    print x

if __name__ == '__main__':
    interval()
</code>```

**Assume the user enters the min, max and freq to be  0,100,20 respectively.
So, the intervals are 0-20, 20-40,40-60,60-80,80-100 and my output should be

The values in 0-20 are [1,2,12,13]
The values in 20-40 are [22,23,32,33]
.. and so on!
**

If there are no values in a particular interval, the output should be list with no values

答:
A very naive way to implement this would be as follows

```<code>def group_items(data, low_value, high_value):
    return [value for value in data if value >= low_value and value <= high_value]
</code>```

This function returns the list of numbers that exist in the ranges [min, max] inclusive, therefore max will be accounted for in both (min,max) and (min+freq, max+freq) because max of first interval is min+freq of next interval. Of course you can correct this based on your requirements.

```<code>min_max_pairs = []
for x in xrange(minimum, maximum, frequency):
    pair = (x, x+frequency)
    min_max_pairs.append(pair)
</code>```

This creates the map from the minimum to maximum values specified by the user using the frequency interval. In your case the values in min, max and freq are

```<code>minimum = raw_input("Enter the min value")
maximum = raw_input("Enter the max value")
frequency = raw_input("Enter the Freq")
</code>```

This returns the pair as follows:

```<code>>>> min_max_pairs
[(0, 20), (20, 40), (40, 60), (60, 80), (80, 100)]
</code>```

Now loop through the pairs and pass them to the group_items() to get the required result

```<code>for pair in min_max_pairs:
    min = pair[0]
    max = pair[1]
    interval = freq
    print ("Range [",min,"-",max,"] : ", group_items(data, min, max))
</code>```

that results in

```<code>Range [ 0 - 20 ]:  [1, 2, 12, 13]
Range [ 20 - 40 ]:  [22, 23, 32, 33]
Range [ 40 - 60 ]:  [42, 43, 52, 53]
Range [ 60 - 80 ]:  [62, 63, 72, 73]
Range [ 80 - 100 ]:  [82, 83, 92, 93]
</code>```

Body:
def interval():
    data = [1, 2, 12, 13, 22, 23, 32, 33, 42, 43, 52, 53, 62, 63, 72, 73, 82, 83, 92, 93]
    minimum = raw_input("Enter the min value")
    maximum = raw_input("Enter the max value")
    frequency = raw_input("Enter the Freq")
    x = []
    x.append(float(minimum))
    thesum = float(minimum)
    for i in range(0, int(maximum)):
        if thesum < float(maximum):
            thesum = thesum + float(frequency)
            x.append(thesum)
    print x

if __name__ == '__main__':
    interval()

**Assume the user enters the min, max and freq to be  0,100,20 respectively.
So, the intervals are 0-20, 20-40,40-60,60-80,80-100 and my output should be

The values in 0-20 are [1,2,12,13]
The values in 20-40 are [22,23,32,33]
.. and so on!
**

If there are no values in a particular interval, the output should be list with no values

Body:
A very naive way to implement this would be as follows

def group_items(data, low_value, high_value):
    return [value for value in data if value >= low_value and value <= high_value]

This function returns the list of numbers that exist in the ranges [min, max] inclusive, therefore max will be accounted for in both (min,max) and (min+freq, max+freq) because max of first interval is min+freq of next interval. Of course you can correct this based on your requirements.

min_max_pairs = []
for x in xrange(minimum, maximum, frequency):
    pair = (x, x+frequency)
    min_max_pairs.append(pair)

This creates the map from the minimum to maximum values specified by the user using the frequency interval. In your case the values in min, max and freq are

minimum = raw_input("Enter the min value")
maximum = raw_input("Enter the max value")
frequency = raw_input("Enter the Freq")

This returns the pair as follows:

>>> min_max_pairs
[(0, 20), (20, 40), (40, 60), (60, 80), (80, 100)]

Now loop through the pairs and pass them to the group_items() to get the required result

for pair in min_max_pairs:
    min = pair[0]
    max = pair[1]
    interval = freq
    print ("Range [",min,"-",max,"] : ", group_items(data, min, max))

that results in

Range [ 0 - 20 ]:  [1, 2, 12, 13]
Range [ 20 - 40 ]:  [22, 23, 32, 33]
Range [ 40 - 60 ]:  [42, 43, 52, 53]
Range [ 60 - 80 ]:  [62, 63, 72, 73]
Range [ 80 - 100 ]:  [82, 83, 92, 93]


问:
Ionic show ion-refresher programmatically
i want to display the ion-refresher programmatically. e.g on the first page load i load the data and want to show the ion-refresher. i've not found any build in function only _beginRefresh. this function will fire the refresher, however it will not set the style attribute TOP on the refresher element. therefore it is hidden behind the NAV.

currently i've created a dirty workaround.

```<code>let scrollcontent = document.getElementsByClassName('ion-page')[0].getElementsByTagName('ion-content')[0].getElementsByClassName('scroll-content')[0]
let rect = scrollcontent.getBoundingClientRect()
document.getElementById('refresher').style.top = rect.top.toString() + 'px'
this.myRefresher._beginRefresh()
</code>```

i'm wondering if there is a better aproach.
thanks

答:
ok i've found a better approach...</p>

```<code>@ViewChild(Content) ContentDashboard: Content;
this.RefresherDashboard._top = this.ContentDashboard.contentTop.toString() + 'px'
this.RefresherDashboard._beginRefresh()
</code>```

Body:
i want to display the ion-refresher programmatically. e.g on the first page load i load the data and want to show the ion-refresher. i've not found any build in function only _beginRefresh. this function will fire the refresher, however it will not set the style attribute TOP on the refresher element. therefore it is hidden behind the NAV.

currently i've created a dirty workaround.

let scrollcontent = document.getElementsByClassName('ion-page')[0].getElementsByTagName('ion-content')[0].getElementsByClassName('scroll-content')[0]
let rect = scrollcontent.getBoundingClientRect()
document.getElementById('refresher').style.top = rect.top.toString() + 'px'
this.myRefresher._beginRefresh()

i'm wondering if there is a better aproach.
thanks

Body:
ok i've found a better approach...

@ViewChild(Content) ContentDashboard: Content;
this.RefresherDashboard._top = this.ContentDashboard.contentTop.toString() + 'px'
this.RefresherDashboard._beginRefresh()


答: In JavaScript + operates both as ADD and string concatination. When you do a + b, a is implicitly coerced into a string. Whereas with other operators cannot be used on strings. Therefore a is implicitly coerced into number, so the math operation.

Title: Javascript Arithmetics


问:
Pass Parameters _ Shell Script - Octave Script
How can i pass two parameters (number vectors) from a Shell Script to a Octave Script ??

That's the idea..

In "prove.sh"

```<code> #!/bin/bash

 .... do something that processing vector1 vector2

./draw.m Vector1 Vector2
</code>```

In "draw.m"

```<code> plot(Vector1, Vector2)
</code>```

Thank you!!

答:
As I mentioned in the comments above, you can simply save the data to a file then call the MATLAB/Octave script which will in turn load the data from file. Example:

arrays.sh

```<code>#!/bin/bash

# create random data
v1=$(seq 1 10)
for i in {1..10}; do v2[$i]=$RANDOM; done

# save data to file
echo $v1 > file.txt
echo ${v2[@]} >> file.txt

# call MATLAB script
matlab -nodesktop -nojvm -nosplash -r "draw_data; quit" &
</code>```

draw_data.m

```<code>load('/path/to/file.txt','-ascii')   %# load data
plot(file(1,:), file(2,:), 'r')      %# plot
saveas(gcf, 'fig.eps', 'psc2')       %# save figure as EPS file
exit
</code>```

Body:
How can i pass two parameters (number vectors) from a Shell Script to a Octave Script ??

That's the idea..

In "prove.sh"

 #!/bin/bash

 .... do something that processing vector1 vector2

./draw.m Vector1 Vector2

In "draw.m"

 plot(Vector1, Vector2)

Thank you!!

Body:
As I mentioned in the comments above, you can simply save the data to a file then call the MATLAB/Octave script which will in turn load the data from file. Example:

arrays.sh

#!/bin/bash

# create random data
v1=$(seq 1 10)
for i in {1..10}; do v2[$i]=$RANDOM; done

# save data to file
echo $v1 > file.txt
echo ${v2[@]} >> file.txt

# call MATLAB script
matlab -nodesktop -nojvm -nosplash -r "draw_data; quit" &

draw_data.m

load('/path/to/file.txt','-ascii')   %# load data
plot(file(1,:), file(2,:), 'r')      %# plot
saveas(gcf, 'fig.eps', 'psc2')       %# save figure as EPS file
exit


答:
We can Override getColor in CustomClusterRenderer.</p>

```<code>public class CustomClusterRenderer extends DefaultClusterRenderer<CustomClusterItem> {

@Override
    protected int getColor(int clusterSize) {
        return Color.parseColor("#567238");
    }
}
</code>```

Title: How to change the color of markers in cluster?

Body:
We can Override getColor in CustomClusterRenderer.

public class CustomClusterRenderer extends DefaultClusterRenderer<CustomClusterItem> {

@Override
    protected int getColor(int clusterSize) {
        return Color.parseColor("#567238");
    }
}


问:
How to add data- attributes to a field in alpacajs?
I am using alpacaJs 1.5.23.

I need to add data-(like data-target) attributes to my fields. Is there a way?

答:
Yes you can do this by using data property in options object of your alpaca configuration like this:

```<code>"data": {
   "target": "test value"
}
</code>```

here's a working fiddle for this.

Body:
Yes you can do this by using data property in options object of your alpaca configuration like this:

"data": {
   "target": "test value"
}

here's a working fiddle for this.