问:
kendo UI asynchronous uplaod on Razor Page returns 404
I am trying to use Kendo UI async upload on Razor Page (No controller) But I get 404 error

Index.cshtml page-

```<code><div class="row">
    <div class="">
        <form asp-action="" class="" id=""  enctype="multipart/form-data">
            <div class="form-group">
                <label class="">Review Type</label>
                <div class="">
                    <select asp-for="ReviewType" asp-items="@(new SelectList(Model.ReviewTypes, "ReviewTypeLookupId", "ReviewTypeName"))" class="form-control"></select>
                </div>
            </div>
            <div class="form-group">
                <label class=""></label>
                <div class="">
                    @(Html.Kendo().Upload()
                          .Name("files")
                          .Async(a => a
                            .Save("Index?handler=Save", "UploadManagement")
                              .Remove("Remove", "UploadManagement/Index")
                              .AutoUpload(true)
                          )
                          )
                </div>
            </div>
            <div class="form-group">
                <button type="submit" id="submit-all" class="btn btn-default">Upload </button>
            </div>
        </form>
    </div>
</code>```

Index.cshtml.cs Page

```<code> [HttpPost]
        public ActionResult OnPostSave(IEnumerable<IFormFile> files)
        {
            // The Name of the Upload component is "files"
            if (files != null)
            {
                foreach (var file in files)
                {
                    //var fileContent = ContentDispositionHeaderValue.Parse(file.ContentDisposition);

                    //// Some browsers send file names with full path.
                    //// We are only interested in the file name.
                    //var fileName = Path.GetFileName(fileContent.FileName.Trim('"'));
                    //var physicalPath = Path.Combine(HostingEnvironment.WebRootPath, "App_Data", fileName);

                    //// The files are not actually saved in this demo
                    ////file.SaveAs(physicalPath);
                }
            }

            // Return an empty string to signify success
            return Content("");
        }
</code>```

Error -
Failed to load resource: the server responded with a status of 404 (Not Found)

答:
The easiest way to solve this, is to not use .Save(string action, string controller) or any overload of this, but .SaveUrl(string url):

```<code>@(Html.Kendo().Upload()
    .Name("files")
    .Async(a => a
        .SaveUrl("./Index?handler=Save")
        .AutoUpload(true)
))
</code>```

This will also work, if you are in a non-default area and the url to the page itself is acually /area-url/Index?handler=foo

Body:
I am trying to use Kendo UI async upload on Razor Page (No controller) But I get 404 error

Index.cshtml page-

        <form asp-action="" class="" id=""  enctype="multipart/form-data">

                Review Type

                    <select asp-for="ReviewType" asp-items="@(new SelectList(Model.ReviewTypes, "ReviewTypeLookupId", "ReviewTypeName"))" class="form-control"></select>

                    @(Html.Kendo().Upload()
                          .Name("files")
                          .Async(a => a
                            .Save("Index?handler=Save", "UploadManagement")
                              .Remove("Remove", "UploadManagement/Index")
                              .AutoUpload(true)
                          )
                          )

                <button type="submit" id="submit-all" class="btn btn-default">Upload </button>

        </form>

Index.cshtml.cs Page

 [HttpPost]
        public ActionResult OnPostSave(IEnumerable<IFormFile> files)
        {
            // The Name of the Upload component is "files"
            if (files != null)
            {
                foreach (var file in files)
                {
                    //var fileContent = ContentDispositionHeaderValue.Parse(file.ContentDisposition);

                    //// Some browsers send file names with full path.
                    //// We are only interested in the file name.
                    //var fileName = Path.GetFileName(fileContent.FileName.Trim('"'));
                    //var physicalPath = Path.Combine(HostingEnvironment.WebRootPath, "App_Data", fileName);

                    //// The files are not actually saved in this demo
                    ////file.SaveAs(physicalPath);
                }
            }

            // Return an empty string to signify success
            return Content("");
        }

Error -
Failed to load resource: the server responded with a status of 404 (Not Found)

Body:
The easiest way to solve this, is to not use .Save(string action, string controller) or any overload of this, but .SaveUrl(string url):

@(Html.Kendo().Upload()
    .Name("files")
    .Async(a => a
        .SaveUrl("./Index?handler=Save")
        .AutoUpload(true)
))

This will also work, if you are in a non-default area and the url to the page itself is acually /area-url/Index?handler=foo


来源: stackexchange

问:
Getting error when adding firebase to my Android project
I am adding Firebase to my app, to use Crashlytics. That's nice, but when I followed official guide to install it, I got error from Gradle, that google play services not found. Why it's telling me not found?

My app is running latest Gradle "v3.4.1", and I searched for this problem, and got this answer:

So as a quick fix I added another repository, that has it:

```<code>repositories {
    maven { url 'https://dl.bintray.com/android/android-tools' }
}

</code>```

Link: Error: could not find com.google.gms:google-services:4.2.0

But that didn't help me, still getting not found error.

Here is my Gradle config files:

Project gradle:

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
        maven { url "https://jitpack.io" }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.4.1'
        // Check for v3.1.2 or higher
        classpath 'com.google.gms.google-services:4.2.0'

        // Add dependency
        classpath 'io.fabric.tools:gradle:1.29.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
            google()
            jcenter()
            maven { url "https://jitpack.io" }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

</code>```

App Gradle:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.developerfromjokela.edison"
        vectorDrawables.useSupportLibrary = true
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 42
        versionName "3.4-BETA12"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {

            minifyEnabled false

            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:support-vector-drawable:28.0.0'
    implementation 'com.android.support:support-v4:28.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.android.support:recyclerview-v7:28.0.0'
    // Older okhttp because not working on android 4.0 for new versions
    //noinspection GradleDependency
    implementation 'com.squareup.okhttp3:okhttp:3.12.1'
    implementation "com.squareup.okhttp3:okhttp-urlconnection:3.0.0-RC1"
    implementation 'com.squareup.picasso:picasso:2.71828'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
    implementation 'com.google.code.gson:gson:2.8.5'
    implementation 'com.github.delight-im:Android-AdvancedWebView:v3.0.0'
    implementation 'de.hdodenhof:circleimageview:3.0.0'
    implementation 'com.android.support:cardview-v7:28.0.0'
    implementation 'com.thoughtbot:expandablerecyclerview:1.4'
    implementation 'org.jsoup:jsoup:1.11.3'
    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    implementation 'com.google.android.gms:play-services-auth:16.0.1'
    implementation "com.android.support:support-emoji:28.0.0"
    implementation 'io.github.lizhangqu:coreprogress:1.0.2'
    implementation 'com.google.firebase:firebase-core:16.0.9'
}

apply plugin: 'com.google.gms.google-services'  // Google Play services Gradle plugin

</code>```

Error from Gradle:

```<code>ERROR: Could not find com.google.gms.google-services:4.2.0:.
Required by:
    project :
Search in build.gradle files

</code>```

答:
move

```<code>apply plugin: 'com.google.gms.google-services'
</code>```

to the bottom of your build.gradle file.

more info: https://firebase.google.com/docs/android/setup

ContentLicense: CC BY-SA 4.0

Body:
I am adding Firebase to my app, to use Crashlytics. That's nice, but when I followed official guide to install it, I got error from Gradle, that google play services not found. Why it's telling me not found?

My app is running latest Gradle "v3.4.1", and I searched for this problem, and got this answer:

So as a quick fix I added another repository, that has it:

repositories {
    maven { url 'https://dl.bintray.com/android/android-tools' }
}

Link: Error: could not find com.google.gms:google-services:4.2.0

But that didn't help me, still getting not found error.

Here is my Gradle config files:

Project gradle:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
        maven { url "https://jitpack.io" }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.4.1'
        // Check for v3.1.2 or higher
        classpath 'com.google.gms.google-services:4.2.0'

        // Add dependency
        classpath 'io.fabric.tools:gradle:1.29.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
            google()
            jcenter()
            maven { url "https://jitpack.io" }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

App Gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.developerfromjokela.edison"
        vectorDrawables.useSupportLibrary = true
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 42
        versionName "3.4-BETA12"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {

            minifyEnabled false

            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:support-vector-drawable:28.0.0'
    implementation 'com.android.support:support-v4:28.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.android.support:recyclerview-v7:28.0.0'
    // Older okhttp because not working on android 4.0 for new versions
    //noinspection GradleDependency
    implementation 'com.squareup.okhttp3:okhttp:3.12.1'
    implementation "com.squareup.okhttp3:okhttp-urlconnection:3.0.0-RC1"
    implementation 'com.squareup.picasso:picasso:2.71828'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
    implementation 'com.google.code.gson:gson:2.8.5'
    implementation 'com.github.delight-im:Android-AdvancedWebView:v3.0.0'
    implementation 'de.hdodenhof:circleimageview:3.0.0'
    implementation 'com.android.support:cardview-v7:28.0.0'
    implementation 'com.thoughtbot:expandablerecyclerview:1.4'
    implementation 'org.jsoup:jsoup:1.11.3'
    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    implementation 'com.google.android.gms:play-services-auth:16.0.1'
    implementation "com.android.support:support-emoji:28.0.0"
    implementation 'io.github.lizhangqu:coreprogress:1.0.2'
    implementation 'com.google.firebase:firebase-core:16.0.9'
}

apply plugin: 'com.google.gms.google-services'  // Google Play services Gradle plugin

Error from Gradle:

ERROR: Could not find com.google.gms.google-services:4.2.0:.
Required by:
    project :
Search in build.gradle files

Body:
move

apply plugin: 'com.google.gms.google-services'

to the bottom of your build.gradle file.

more info: https://firebase.google.com/docs/android/setup


问:
Android Button with bottom margin and state_pressed
Is there a way to create Android Button that have bottom margin when state_pressed is false, and that have rounded corners without bottom margin when state_pressed is true?

I have this, but it's without bottom margin when state_pressed is false:

```<code><?xml version="1.0" encoding="utf-8"?>
<selector
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape
            android:shape="rectangle">
            <solid android:color="#B5B5B5" />
            <corners android:radius="10dp" />
        </shape>
    </item>
    <item android:state_pressed="false">
        <shape
            android:shape="rectangle">
            <solid android:color="#FFFFFF" />
        </shape>
    </item>
</selector>
</code>```

EDIT: Added pictures

android:state_pressed="false"

android:state_pressed="true"

答:
<selector xmlns:android="schemas.android.com/apk/res/android">
<item android:drawable="@drawable/drawable_for_pressed_state" android:state_pressed="true"/>
<item android:drawable="@drawable/drawable_for_normal_state" android:state_pressed="false"/>
</selector>```

Add this code your drawable folder and use separate button drawables for the different button state

Body:
Is there a way to create Android Button that have bottom margin when state_pressed is false, and that have rounded corners without bottom margin when state_pressed is true?

I have this, but it's without bottom margin when state_pressed is false:

<?xml version="1.0" encoding="utf-8"?>
<selector
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape
            android:shape="rectangle">
            <solid android:color="#B5B5B5" />
            <corners android:radius="10dp" />
        </shape>
    </item>
    <item android:state_pressed="false">
        <shape
            android:shape="rectangle">
            <solid android:color="#FFFFFF" />
        </shape>
    </item>
</selector>

EDIT: Added pictures

android:state_pressed="false"

android:state_pressed="true"

Body:
<selector xmlns:android="schemas.android.com/apk/res/android">
<item android:drawable="@drawable/drawable_for_pressed_state" android:state_pressed="true"/>
<item android:drawable="@drawable/drawable_for_normal_state" android:state_pressed="false"/>
</selector>

Add this code your drawable folder and use separate button drawables for the different button state


问:
Using a variable as upper bound of a summation (varA = sum(i$(ord(i)<varA),X(i)))
I need to consider "traffic time" in different period of time as a parameter in a VRP problem, so the equation becomes like this:

```<code>varA = sum(i$(ord(i)<varA),X(i)) + other terms
</code>```

Is it possible to write such a code? Can GAMS or any other software handle such a constraint?

The equation:

答:
I'm not familiar with GAMS syntax, but in AMPL you would do something like this:

```<code>set T;                  # set of time periods
param traffic_time{T};  # traffic time in each time period
</code>```

Then you would refer to the traffic time parameter like traffic_time[t] for t in T. I'm sure there is something similar in GAMS. It might be called something like "parameter indexed by a set".

Body:
I need to consider "traffic time" in different period of time as a parameter in a VRP problem, so the equation becomes like this:

varA = sum(i$(ord(i)<varA),X(i)) + other terms

Is it possible to write such a code? Can GAMS or any other software handle such a constraint?

The equation:

Body:
I'm not familiar with GAMS syntax, but in AMPL you would do something like this:

set T;                  # set of time periods
param traffic_time{T};  # traffic time in each time period

Then you would refer to the traffic time parameter like traffic_time[t] for t in T. I'm sure there is something similar in GAMS. It might be called something like "parameter indexed by a set".


问:
how to convert date to date drop down and drop down could be separate day, month,year
]2

  Date of birth:
  <input type="date" name="date_of_birth" value="2019-06-14" id="id_date_of_birth">

```

i am getting data from database by using django and i am trying to show in drop down date but i am getting date table

答:
You can split out the field into 3 parts (you'd need to get the day/month/year parts in django) into 3 select fields like this:

```<code><p>
  <label>Day:
    <select name="day">
      <option>1</option>
      <option>2</option>
      ...
      <option>31</option>
    </select>
  </label>
  <label>Month:
    <select name="month">
      <option>1</option>
      <option>2</option>
      ...
      <option>12</option>
    </select>
  </label>
  <label>Year:
    <select name="year">
      <option>1900</option>
      <option>1901</option>
      ...
      <option>3000</option>
    </select>
  </label>
</code>```

But I would NOT recommend this. This makes entering dates harder (multiple clicks and scrolls), the user can't copy/paste dates, or choose from a visual calendar.  You also need to add your own client side logic to ensure that the user doesn't pick dates like Feb 31st.

Body:
]2

  Date of birth:
  <input type="date" name="date_of_birth" value="2019-06-14" id="id_date_of_birth">

i am getting data from database by using django and i am trying to show in drop down date but i am getting date table

Body:
You can split out the field into 3 parts (you'd need to get the day/month/year parts in django) into 3 select fields like this:

<p>
  <label>Day:
    <select name="day">
      <option>1</option>
      <option>2</option>
      ...
      <option>31</option>
    </select>
  </label>
  <label>Month:
    <select name="month">
      <option>1</option>
      <option>2</option>
      ...
      <option>12</option>
    </select>
  </label>
  <label>Year:
    <select name="year">
      <option>1900</option>
      <option>1901</option>
      ...
      <option>3000</option>
    </select>
  </label>

But I would NOT recommend this. This makes entering dates harder (multiple clicks and scrolls), the user can't copy/paste dates, or choose from a visual calendar.  You also need to add your own client side logic to ensure that the user doesn't pick dates like Feb 31st.


问:
Laravel How To Sub Join with Relations
I want to pull NPCs with pledges by day. However, with this i need the dungeon name. İ have 3 tables.

Npcs Table:

```<code>id  |  name
-----------
1   | NPC 1
2   | NPC 2
3   | NPC 3
</code>```

Dungeons table

```<code>id  |  name
---------------
1   | Dungeon 1
2   | Dungeon 2
3   | Dungeon 3
4   | Dungeon 4
5   | Dungeon 5
6   | Dungeon 6
</code>```

Pledges table

```<code>id  |  npc_id  |  dungeon_id  |  date
------------------------------------------
1   | 1        | 1            | 2019-05-26
2   | 2        | 2            | 2019-05-26
3   | 3        | 3            | 2019-05-26
4   | 1        | 4            | 2019-05-27
5   | 2        | 5            | 2019-05-27
6   | 3        | 6            | 2019-05-27
</code>```

My controller code;

```<code>public function index()
{
    $y = Carbon::yesterday('Europe/London');
    $t = Carbon::today('Europe/London');
    $time = Carbon::now('Europe/London');
    $yesterday = Carbon::create($y->year, $y->month, $y->day, 10, 0, 0); //set time to 10:00
    $today = Carbon::create($t->year, $t->month, $t->day, 10, 0, 0); //set time to 10:00
    if($time->between($yesterday, $today, true)) {
        $pledges = Npc::join('pledges', function ($join) {
            $join->on('npcs.id', '=', 'pledges.npc_id')
                ->where('pledges.date', '=', Carbon::yesterday('Europe/London'));
        })
            ->get();
        return $pledges;
    } else {
        $pledges = Npc::join('pledges', function ($join) {
            $join->on('npcs.id', '=', 'pledges.npc_id')
                ->where('pledges.date', '=', Carbon::today('Europe/London'));
        })
            ->get();
        return $pledges;
    }
}
</code>```

This code gives me the following result.

```<code>0
id  5
name    "NPC 1"
created_at  "2019-05-27 11:35:27"
updated_at  "2019-05-27 11:35:27"
npc_id  1
dungeon_id  1
date    "2019-05-27"
</code>```

But i need dungeon name with this result.

答:
You should use additional join + select. Try this.</p>

```<code>public function index()
{
    $time = Carbon::now('Europe/London');
    $yesterday = Carbon::yesterday('Europe/London')->setTime(10, 0, 0);
    $today = Carbon::today('Europe/London')->setTime(10, 0, 0);

    if($time->between($yesterday, $today, true)){
        $date = $yesterday;
    } else {
        $date = $today;
    }

    $pledges = Npc::select('npcs.*', 'dungeons.id as dungeon_id', 'dungeons.name as dungeon_name')
        ->join('pledges', function($join) use ($date) {
            $join->on('npcs.id', '=', 'pledges.npc_id')->where('date', $date);
        })
        ->join('dungeons', 'dungeons.id', '=', 'pledges.dungeon_id')
        ->get();

    return $pledges;
}
</code>```

Title: Laravel How To Sub Join with Relations

Body:
I want to pull NPCs with pledges by day. However, with this i need the dungeon name. İ have 3 tables.

Npcs Table:

id  |  name
-----------
1   | NPC 1
2   | NPC 2
3   | NPC 3

Dungeons table

id  |  name
---------------
1   | Dungeon 1
2   | Dungeon 2
3   | Dungeon 3
4   | Dungeon 4
5   | Dungeon 5
6   | Dungeon 6

Pledges table

id  |  npc_id  |  dungeon_id  |  date
------------------------------------------
1   | 1        | 1            | 2019-05-26
2   | 2        | 2            | 2019-05-26
3   | 3        | 3            | 2019-05-26
4   | 1        | 4            | 2019-05-27
5   | 2        | 5            | 2019-05-27
6   | 3        | 6            | 2019-05-27

My controller code;

public function index()
{
    $y = Carbon::yesterday('Europe/London');
    $t = Carbon::today('Europe/London');
    $time = Carbon::now('Europe/London');
    $yesterday = Carbon::create($y->year, $y->month, $y->day, 10, 0, 0); //set time to 10:00
    $today = Carbon::create($t->year, $t->month, $t->day, 10, 0, 0); //set time to 10:00
    if($time->between($yesterday, $today, true)) {
        $pledges = Npc::join('pledges', function ($join) {
            $join->on('npcs.id', '=', 'pledges.npc_id')
                ->where('pledges.date', '=', Carbon::yesterday('Europe/London'));
        })
            ->get();
        return $pledges;
    } else {
        $pledges = Npc::join('pledges', function ($join) {
            $join->on('npcs.id', '=', 'pledges.npc_id')
                ->where('pledges.date', '=', Carbon::today('Europe/London'));
        })
            ->get();
        return $pledges;
    }
}

This code gives me the following result.

0
id  5
name    "NPC 1"
created_at  "2019-05-27 11:35:27"
updated_at  "2019-05-27 11:35:27"
npc_id  1
dungeon_id  1
date    "2019-05-27"

But i need dungeon name with this result.

Body:
You should use additional join + select. Try this.

public function index()
{
    $time = Carbon::now('Europe/London');
    $yesterday = Carbon::yesterday('Europe/London')->setTime(10, 0, 0);
    $today = Carbon::today('Europe/London')->setTime(10, 0, 0);

    if($time->between($yesterday, $today, true)){
        $date = $yesterday;
    } else {
        $date = $today;
    }

    $pledges = Npc::select('npcs.*', 'dungeons.id as dungeon_id', 'dungeons.name as dungeon_name')
        ->join('pledges', function($join) use ($date) {
            $join->on('npcs.id', '=', 'pledges.npc_id')->where('date', $date);
        })
        ->join('dungeons', 'dungeons.id', '=', 'pledges.dungeon_id')
        ->get();

    return $pledges;
}


问:
Redirect to a port number depending on the URL
My server has 3 websites :

Gitlab running with Omnibus on port 80

React.js application in a Docker on port 3001

Jorani (php application) on Apache on port 8008

Since DNS can't handle the port number, how may I redirect to a port depending on the URL the user gives, for example :

http://gitlab.domain.com => port 80

http://react.domain.com => port 3001

http://jorani.domain.com => port 8008

I saw some post about Proxy or reverse proxy but i'm not sure if it's the good way to proceed

答:
So here is the solution I'm using :

I changed my gitlab port to 8900.
I changed my Apache port to 80.

I'm now using virtualhosts with Apache :

For CentOS 7 in /etc/httpd/sites-available/

gitlab.conf :

```<code><VirtualHost gitlab.mydomain.intra:80 >
        ServerName gitlab.mydomain.intra
        ProxyPreserveHost On
        ProxyRequests On
        ProxyPass / http://localhost:8900/
        ProxyPassReverse / http://localhost:8900/
</VirtualHost>
</code>```

react.conf :

```<code><VirtualHost react.mydomain.intra:80 >
        ServerName react.mydomain.intra
        ProxyPreserveHost On
        ProxyRequests On
        ProxyPass / http://localhost:3001/
        ProxyPassReverse / http://localhost:3001/
</VirtualHost>
</code>```

jorani.conf :

```<code><VirtualHost jorani.mydomain.intra:80 >
        ServerName jorani.mydomain.intra
        ProxyPreserveHost On
        ProxyRequests On
        ProxyPass / http://localhost:80/jorani
        ProxyPassReverse / http://localhost:80/jorani
</VirtualHost>
</code>```

Problem : I can't manage to make it work for gitlab with SSL (gitlab.mydomain.intra => https://gitlab.mydomain.intra/). Will post the solution if I find it.

EDIT :
Here is the solution for gitlab with https :

/etc/gitlab/gitlab.rb :

```<code>external_url 'https://gitlab.mydomain.com/'
nginx['enable'] = true
nginx['redirect_http_to_https'] = true
nginx['listen_addresses'] = ['localhost']
nginx['listen_port'] = 8888
nginx['listen_https'] = false
</code>```

/etc/httpd/sites-available/gitlab.conf

```<code><VirtualHost gitlab.mydomain.intra:80>
    ServerName gitlab.mydomain.intra
    ErrorLog /var/log/httpd/gitlab.mydomain.intra/error.log
    Redirect 301 / https://gitlab.mydomain.intra/
</VirtualHost>
<VirtualHost gitlab.mydomain.intra:443>
    ServerName gitlab.mydomain.intra
    ErrorLog /var/log/httpd/gitlab.mydomain.intra/error.log
    RequestHeader set Host "gitlab.mydomain.intra"
    #RequestHeader add X-Forwarded-Ssl on
    #RequestHeader set X-Forwarded-For %<span class="pl-s1"><span class="pl-pse">{</span>REMOTE_ADDR<span class="pl-$
    #RequestHeader set X-Forwarded-Proto "https"

    ProxyPreserveHost On
    ProxyPass / http://localhost:8888/
    ProxyPassReverse / http://localhost:8888/

    SSLEngine On
    SSLCertificateFile /etc/gitlab/ssl/gitlab.mydomain.intra.crt
    SSLCertificateKeyFile /etc/gitlab/ssl/gitlab.mydomain.intra.key
</VirtualHost>
</code>```

Body:
So here is the solution I'm using :

I changed my gitlab port to 8900.
I changed my Apache port to 80.

I'm now using virtualhosts with Apache :

For CentOS 7 in /etc/httpd/sites-available/

gitlab.conf :

<VirtualHost gitlab.mydomain.intra:80 >
        ServerName gitlab.mydomain.intra
        ProxyPreserveHost On
        ProxyRequests On
        ProxyPass / http://localhost:8900/
        ProxyPassReverse / http://localhost:8900/
</VirtualHost>

react.conf :

<VirtualHost react.mydomain.intra:80 >
        ServerName react.mydomain.intra
        ProxyPreserveHost On
        ProxyRequests On
        ProxyPass / http://localhost:3001/
        ProxyPassReverse / http://localhost:3001/
</VirtualHost>

jorani.conf :

<VirtualHost jorani.mydomain.intra:80 >
        ServerName jorani.mydomain.intra
        ProxyPreserveHost On
        ProxyRequests On
        ProxyPass / http://localhost:80/jorani
        ProxyPassReverse / http://localhost:80/jorani
</VirtualHost>

Problem : I can't manage to make it work for gitlab with SSL (gitlab.mydomain.intra => https://gitlab.mydomain.intra/). Will post the solution if I find it.

EDIT :
Here is the solution for gitlab with https :

/etc/gitlab/gitlab.rb :

external_url 'https://gitlab.mydomain.com/'
nginx['enable'] = true
nginx['redirect_http_to_https'] = true
nginx['listen_addresses'] = ['localhost']
nginx['listen_port'] = 8888
nginx['listen_https'] = false

/etc/httpd/sites-available/gitlab.conf

<VirtualHost gitlab.mydomain.intra:80>
    ServerName gitlab.mydomain.intra
    ErrorLog /var/log/httpd/gitlab.mydomain.intra/error.log
    Redirect 301 / https://gitlab.mydomain.intra/
</VirtualHost>
<VirtualHost gitlab.mydomain.intra:443>
    ServerName gitlab.mydomain.intra
    ErrorLog /var/log/httpd/gitlab.mydomain.intra/error.log
    RequestHeader set Host "gitlab.mydomain.intra"
    #RequestHeader add X-Forwarded-Ssl on
    #RequestHeader set X-Forwarded-For %<span class="pl-s1"><span class="pl-pse">{</span>REMOTE_ADDR<span class="pl-$
    #RequestHeader set X-Forwarded-Proto "https"

    ProxyPreserveHost On
    ProxyPass / http://localhost:8888/
    ProxyPassReverse / http://localhost:8888/

    SSLEngine On
    SSLCertificateFile /etc/gitlab/ssl/gitlab.mydomain.intra.crt
    SSLCertificateKeyFile /etc/gitlab/ssl/gitlab.mydomain.intra.key
</VirtualHost>


问:
highchart tooltip hover - on busy charts the tooltip jumps between the points
Im using high-chart of type 'area' and SVG tooltip. On a chart with a lot of points, when i hover the tooltip area and i move my mouse on the tooltip it jumps to other closest point tooltip. is there a way to open the tooltip only when i hover on the exact point? (don't want to be forced to click on a point to get tooltip)

i tried stickyTracking false/true, snap, hide delay

i expect the tooltip on hover to stay on tooltip area unless i move the mouse directly to other point

答:
You can set findNearestPointBy property to 'xy':

```<code>series: [{
    type: 'area',
    findNearestPointBy: 'xy',
    data: [...]
}]
</code>```

Live demo: http://jsfiddle.net/BlackLabel/4pzd8L2b/

API Reference: https://api.highcharts.com/highcharts/series.area.findNearestPointBy

Body:
You can set findNearestPointBy property to 'xy':

series: [{
    type: 'area',
    findNearestPointBy: 'xy',
    data: [...]
}]

Live demo: http://jsfiddle.net/BlackLabel/4pzd8L2b/

API Reference: https://api.highcharts.com/highcharts/series.area.findNearestPointBy


问:
Discord.js Level System
My 'problem' is more of a feature I am looking to add, I used this guide:
https://anidiots.guide/coding-guides/sqlite-based-points-system
I changed the code a little to mainly give you a random amount of XP, I am looking to edit how much XP is needed to level up.

Right now it is a static amount, being 5000 needed to level up. I am trying to make it increase the amount needed to level up by an extra 5000 each time you level up.

Currently, it works like this:

Level 1 to 2 = 5000 total XP needed

Level 2 to 3 = 10000 total xp needed

Currently, the amount needed to level up is always 5000 between each level.

This is how I want it to work:

Level 1 to 2 = 5000 total XP needed

Level 2 to 3 = 15000 total XP needed

Which will be 5000 to level 2 and then 10000 to level 3 and so on (increasing the amount needed by 5000 each time you level up)

I spent the best part of 2 hours trying different things, and mainly looking at the code being completely out of my depth.
I believed that doing something like this would work, but I have no idea if it's correct

if (score.level == '1') {
    nextLevel = 5000
}
if (score.level == '2' {
    nextLevel = 10000
}
```

<p>I highly doubt this is correct, otherwise, my message event would be very long, as I plan to have 100 levels</p>

<p>The code in its entirety: </p>

<pre class="lang-js prettyprint-override"><code>    let score;
    if (message.guild) {
        score = bot.getScore.get(message.author.id, message.guild.id);
        if (!score) {
            score = {
                id: `${message.guild.id}-${message.author.id}`,
                user: message.author.id,
                guild: message.guild.id,
                points: 0,
                level: 1,
            };
        }
        const xpAdd = Math.floor(Math.random() * 10) + 50;
        const curxp = score.points;
        const curlvl = score.level;
        const nxtLvl = score.level * 5000;
        score.points = curxp + xpAdd;
        if (nxtLvl <= score.points) {
            score.level = curlvl + 1;
            const lvlup = new MessageEmbed()
                .setAuthor(
                    `Congrats ${message.author.username}`,
                    message.author.displayAvatarURL()
                )
                .setTitle('You have leveled up!')
                .setThumbnail('https://i.imgur.com/lXeBiMs.png')
                .setColor(color)
                .addField('New Level', curlvl + 1);
            message.channel.send(lvlup).then(msg => {
                msg.delete({
                    timeout: 10000,
                });
            });
        }
        bot.setScore.run(score);
    }
</code>```

The code as-is works fine and as expected, but as-is is not very good, as there is no reward from going from level 30-31 as it's the same amount of XP needed to get from level 1-2

答:
Here's a little formula which should do the trick (if I understand your problem correctly):

const nxtLvl = 5000 * (Math.pow(2, score.level) - 1);
```

<p>This gives the following xp requirements to level up:</p>

```1->2:  5000
2->3:  15000
3->4:  35000
4->5:  75000
5->6: 155000
```

Title: Discord.js Level System

Body:
My 'problem' is more of a feature I am looking to add, I used this guide:
https://anidiots.guide/coding-guides/sqlite-based-points-system
I changed the code a little to mainly give you a random amount of XP, I am looking to edit how much XP is needed to level up.

Right now it is a static amount, being 5000 needed to level up. I am trying to make it increase the amount needed to level up by an extra 5000 each time you level up.

Currently, it works like this:

Level 1 to 2 = 5000 total XP needed

Level 2 to 3 = 10000 total xp needed

Currently, the amount needed to level up is always 5000 between each level.

This is how I want it to work:

Level 1 to 2 = 5000 total XP needed

Level 2 to 3 = 15000 total XP needed

Which will be 5000 to level 2 and then 10000 to level 3 and so on (increasing the amount needed by 5000 each time you level up)

I spent the best part of 2 hours trying different things, and mainly looking at the code being completely out of my depth.
I believed that doing something like this would work, but I have no idea if it's correct

if (score.level == '1') {
    nextLevel = 5000
}
if (score.level == '2' {
    nextLevel = 10000
}

I highly doubt this is correct, otherwise, my message event would be very long, as I plan to have 100 levels

The code in its entirety:

    let score;
    if (message.guild) {
        score = bot.getScore.get(message.author.id, message.guild.id);
        if (!score) {
            score = {
                id: `${message.guild.id}-${message.author.id}`,
                user: message.author.id,
                guild: message.guild.id,
                points: 0,
                level: 1,
            };
        }
        const xpAdd = Math.floor(Math.random() * 10) + 50;
        const curxp = score.points;
        const curlvl = score.level;
        const nxtLvl = score.level * 5000;
        score.points = curxp + xpAdd;
        if (nxtLvl <= score.points) {
            score.level = curlvl + 1;
            const lvlup = new MessageEmbed()
                .setAuthor(
                    `Congrats ${message.author.username}`,
                    message.author.displayAvatarURL()
                )
                .setTitle('You have leveled up!')
                .setThumbnail('https://i.imgur.com/lXeBiMs.png')
                .setColor(color)
                .addField('New Level', curlvl + 1);
            message.channel.send(lvlup).then(msg => {
                msg.delete({
                    timeout: 10000,
                });
            });
        }
        bot.setScore.run(score);
    }

The code as-is works fine and as expected, but as-is is not very good, as there is no reward from going from level 30-31 as it's the same amount of XP needed to get from level 1-2

Body:
Here's a little formula which should do the trick (if I understand your problem correctly):

const nxtLvl = 5000 * (Math.pow(2, score.level) - 1);

This gives the following xp requirements to level up:

1->2:  5000
2->3:  15000
3->4:  35000
4->5:  75000
5->6: 155000


问:
putting 3 strings together using strcpy, strcat, sprintf at least once each
My homework problem is to make a program putting 3 strings together using strcpy, strcat, sprintf at least once each.

I'm wondering if I can use all those three without any garbage code. I've tried using strchr to use sprintf for putting strings together, but the pointer location changed so couldn't print out the whole thing.

```<code>char str1[MAX];
char str2[MAX];
char str3[MAX];
char str4[MAX];

gets(str1);
gets(str2);
gets(str3);

strcat(str1, str2);
strchr(str1, '\0');
sprintf(str1, "%s", str3);
strcpy(str4, str1);

puts(str4);
</code>```

I also want to know if there is any difference in their use between strcpy and sprintf in this case.

答:
Lets say str1 = "ab", str2 = "cd", str3 = "ef"

```<code>strcat(str1, str2);
</code>```

This will concatenate str2 onto str1,
now
str1 = "abcd"

strchr(str1, '\0'); // this will not do anything, it will just return pointer of '\0' in str1, which is the last chatracter.

```<code>sprintf(str1, "%s", str3);
</code>```

this will print "ef" into str1, old content will be lost,
I believe you wanted to do

```<code>sprintf(<pointer returned from strchr>, "%s", str3);

strcpy(str4, str1);
</code>```

This will just copy str1 to str4.

```<code>puts(str4);
</code>```

This will print the string str4

The problem with your code is where you are doing strchr and not collecting the return value, so that you can concatenate there.
In this case strcpy and sprintf are similar, but sprintf gives you lot of formatting options, see documentation.
http://www.cplusplus.com/reference/cstdio/sprintf/
Also, your MAX macro should be large enough to hold strings.

Body:
My homework problem is to make a program putting 3 strings together using strcpy, strcat, sprintf at least once each.

I'm wondering if I can use all those three without any garbage code. I've tried using strchr to use sprintf for putting strings together, but the pointer location changed so couldn't print out the whole thing.

char str1[MAX];
char str2[MAX];
char str3[MAX];
char str4[MAX];

gets(str1);
gets(str2);
gets(str3);

strcat(str1, str2);
strchr(str1, '\0');
sprintf(str1, "%s", str3);
strcpy(str4, str1);

puts(str4);

I also want to know if there is any difference in their use between strcpy and sprintf in this case.

Body:
Lets say str1 = "ab", str2 = "cd", str3 = "ef"

strcat(str1, str2);

This will concatenate str2 onto str1,
now
str1 = "abcd"

strchr(str1, '\0'); // this will not do anything, it will just return pointer of '\0' in str1, which is the last chatracter.

sprintf(str1, "%s", str3);

this will print "ef" into str1, old content will be lost,
I believe you wanted to do

sprintf(<pointer returned from strchr>, "%s", str3);

strcpy(str4, str1);

This will just copy str1 to str4.

puts(str4);

This will print the string str4

The problem with your code is where you are doing strchr and not collecting the return value, so that you can concatenate there.
In this case strcpy and sprintf are similar, but sprintf gives you lot of formatting options, see documentation.
http://www.cplusplus.com/reference/cstdio/sprintf/
Also, your MAX macro should be large enough to hold strings.


问:
Can shell_exec run my machine learning code ? It runs fine on terminal but returns NULL in shell_exec
I have a python script which is running neural networks based on keras, it runs fine but when i use to run that script through shell_exec in my php and use var_dump i get "NULL".

I have already seen many solutions. I have increased max_execution_time and max_input time in php.ini to 5000. I am also giving full paths of files and required environment in command. Also i have given all permissions to folders (lampp, htdocs, (my php file folder)) This is the command which gets finally called in shell_exec.

```<code>source /home/characterleveldl/anaconda3/bin/activate /home/characterleveldl/anaconda3/envs/spyderr && python fyp_final.py 5 /opt/lampp/htdocs/charlevel_fyp/train.csv /opt/lampp/htdocs/charlevel_fyp/test.csv 86save_true.pdf 86save_random.pdf 86save_result.txt 2>&1
</code>```

fyp_final.py , train.csv, test.csv everything exists in same folder as the php file. I ran the same exact command via terminal in root mode and it ran without any error. But in below php code it returns NULL.

```<code>$cmd_initial ='source /home/characterleveldl/anaconda3/bin/activate /home/characterleveldl/anaconda3/envs/spyderr && ';

$cmd = $cmd_initial . 'python fyp_final.py ' . $num_classes . ' ' . $train . ' ' . $test . ' ' . $save_true . ' ' . $save_random . ' ' . $save_text . ' 2>&1';
$command = escapeshellcmd($cmd);
$output = shell_exec($command);
var_dump($cmd);
var_dump($output);

</code>```

Please help me. If i am doing something wrong or is it even possible to run machine learning code from php since i tried running small codes they run perfectly.

答: I figured it out. I solved it via putting my code inside a shell script and then executing this script via shell_exec. It now works fine.

Body:
I have a python script which is running neural networks based on keras, it runs fine but when i use to run that script through shell_exec in my php and use var_dump i get "NULL".

I have already seen many solutions. I have increased max_execution_time and max_input time in php.ini to 5000. I am also giving full paths of files and required environment in command. Also i have given all permissions to folders (lampp, htdocs, (my php file folder)) This is the command which gets finally called in shell_exec.

source /home/characterleveldl/anaconda3/bin/activate /home/characterleveldl/anaconda3/envs/spyderr && python fyp_final.py 5 /opt/lampp/htdocs/charlevel_fyp/train.csv /opt/lampp/htdocs/charlevel_fyp/test.csv 86save_true.pdf 86save_random.pdf 86save_result.txt 2>&1

fyp_final.py , train.csv, test.csv everything exists in same folder as the php file. I ran the same exact command via terminal in root mode and it ran without any error. But in below php code it returns NULL.

$cmd_initial ='source /home/characterleveldl/anaconda3/bin/activate /home/characterleveldl/anaconda3/envs/spyderr && ';

$cmd = $cmd_initial . 'python fyp_final.py ' . $num_classes . ' ' . $train . ' ' . $test . ' ' . $save_true . ' ' . $save_random . ' ' . $save_text . ' 2>&1';
$command = escapeshellcmd($cmd);
$output = shell_exec($command);
var_dump($cmd);
var_dump($output);

Please help me. If i am doing something wrong or is it even possible to run machine learning code from php since i tried running small codes they run perfectly.


问:
PAPI and native events
Is it possible to find the set of native events (CPU counter registers) that maps to a PAPI event ? </p>

答:
In order to quickly see and export all available mappings from preset events to native events use papi_decode -a command. The output is in the CSV format. An example from my CPU:

```<code>pc@pc ~> papi_decode -a
name,derived,postfix,short_descr,long_descr,note,[native,...]

PAPI_L1_DCM,NOT_DERIVED,,"L1D cache misses","Level 1 data cache misses",,L1D:REPLACEMENT
PAPI_L1_ICM,NOT_DERIVED,,"L1I cache misses","Level 1 instruction cache misses",,L2_RQSTS:ALL_CODE_RD
PAPI_L2_DCM,DERIVED_SUB,,"L2D cache misses","Level 2 data cache misses",,LLC_REFERENCES,L2_RQSTS:CODE_RD_MISS
(...)
</code>```

ContentLicense: CC BY-SA 3.0

Title: PAPI and native events

Body:
In order to quickly see and export all available mappings from preset events to native events use papi_decode -a command. The output is in the CSV format. An example from my CPU:

pc@pc ~> papi_decode -a
name,derived,postfix,short_descr,long_descr,note,[native,...]

PAPI_L1_DCM,NOT_DERIVED,,"L1D cache misses","Level 1 data cache misses",,L1D:REPLACEMENT
PAPI_L1_ICM,NOT_DERIVED,,"L1I cache misses","Level 1 instruction cache misses",,L2_RQSTS:ALL_CODE_RD
PAPI_L2_DCM,DERIVED_SUB,,"L2D cache misses","Level 2 data cache misses",,LLC_REFERENCES,L2_RQSTS:CODE_RD_MISS
(...)


问:
Calling multiple Sub's with one line
I'm trying to call multiple Sub's with one line, at this moment I'm doing this (which's not practical)

```<code>' Textbox1
' Textbox2
' Textbox3
' Textbox...
' Textbox100

Private Sub TextBox1_AfterUpdate()

    Call TextBox1_Function

End Sub

Private Sub TextBox2_AfterUpdate()

    Call TextBox2_Function

End Sub

Private Sub TextBox3_AfterUpdate()

    Call TextBox3_Function

End Sub

' ......................... till Textbox100
</code>```

I wonder now if I could something like this:

```<code>' Textbox1
' Textbox2
' Textbox3
' Textbox...
' Textbox100

Private Sub TextBox1_AfterUpdate()

    ' 1 - Get this Sub Object (I don't know if it's possible)
    ' 2 - Then Call the function
    Call TextBox_Function OBJ_Name

End Sub

Function TextBox_Function(OBJ as Object)

    ' Do some code

End Function

</code>```

Or anything better... With less line of code... Because I've 10 categories of text, each category have 100 textboxes each...

It've to be different functions for some text boxes, because of that I can't use "For Each Textbox....."

答:
You can add event handlers for multiple text boxes by adding a class that handles the events. This class can include a BoxType so you can define for each TextBox which type it is, and in the event handler you can then distinguish the boxes by their BoxType.

Add a Class Module name it clsTextBox and paste the following code:

```<code>Option Explicit

Public WithEvents pTbx As MSForms.TextBox
Public BoxType As String

Private Sub pTbx_AfterUpdate()
    Select Case BoxType
        Case "TypeA"
            Debug.Print "Type A update " & pTbx.Name
        Case "TypeB"
            Debug.Print "Type B update " & pTbx.Name
    End Select
End Sub

Private Sub pTbx_Change()
    Select Case BoxType
        Case "TypeA"
            Debug.Print "Type A change " & pTbx.Name
        Case "TypeB"
            Debug.Print "Type B change " & pTbx.Name
    End Select
End Sub
</code>```

Create the events you need.

pTbx refers to the text box that triggered the event.

BoxType specifies the type of the text box that triggered the event.

Initialize your text boxes. Therefore paste the following code in your user form

```<code>Option Explicit

Private mClsTbx() As clsTextBox

Private Sub InitBoxes(ByVal BoxType As String, ByVal BoxNames As Variant)
    Dim StartIdx As Long

    On Error Resume Next
    StartIdx = UBound(mClsTbx) + 1
    On Error GoTo 0
    ReDim Preserve mClsTbx(StartIdx + UBound(BoxNames))

    Dim i As Long
    For i = 0 To UBound(BoxNames)
        Set mClsTbx(i + StartIdx) = New clsTextBox
        Set mClsTbx(i + StartIdx).pTbx = Controls(BoxNames(i))
        mClsTbx(i + StartIdx).BoxType = BoxType
    Next i
End Sub

Private Sub UserForm_Initialize()
    'here we define which TextBox belongs to which type
    InitBoxes BoxType:="TypeA", BoxNames:=Array("TextBoxA1", "TextBoxA2")
    InitBoxes BoxType:="TypeB", BoxNames:=Array("TextBoxB1", "TextBoxB2")
    'add more types here
End Sub
</code>```

Title: Calling multiple Sub's with one line

Body:
I'm trying to call multiple Sub's with one line, at this moment I'm doing this (which's not practical)

' Textbox1
' Textbox2
' Textbox3
' Textbox...
' Textbox100

Private Sub TextBox1_AfterUpdate()

    Call TextBox1_Function

End Sub

Private Sub TextBox2_AfterUpdate()

    Call TextBox2_Function

End Sub

Private Sub TextBox3_AfterUpdate()

    Call TextBox3_Function

End Sub

' ......................... till Textbox100

I wonder now if I could something like this:

' Textbox1
' Textbox2
' Textbox3
' Textbox...
' Textbox100

Private Sub TextBox1_AfterUpdate()

    ' 1 - Get this Sub Object (I don't know if it's possible)
    ' 2 - Then Call the function
    Call TextBox_Function OBJ_Name

End Sub

Function TextBox_Function(OBJ as Object)

    ' Do some code

End Function

Or anything better... With less line of code... Because I've 10 categories of text, each category have 100 textboxes each...

It've to be different functions for some text boxes, because of that I can't use "For Each Textbox....."

Body:
You can add event handlers for multiple text boxes by adding a class that handles the events. This class can include a BoxType so you can define for each TextBox which type it is, and in the event handler you can then distinguish the boxes by their BoxType.

Add a Class Module name it clsTextBox and paste the following code:

Option Explicit

Public WithEvents pTbx As MSForms.TextBox
Public BoxType As String

Private Sub pTbx_AfterUpdate()
    Select Case BoxType
        Case "TypeA"
            Debug.Print "Type A update " & pTbx.Name
        Case "TypeB"
            Debug.Print "Type B update " & pTbx.Name
    End Select
End Sub

Private Sub pTbx_Change()
    Select Case BoxType
        Case "TypeA"
            Debug.Print "Type A change " & pTbx.Name
        Case "TypeB"
            Debug.Print "Type B change " & pTbx.Name
    End Select
End Sub

Create the events you need.

pTbx refers to the text box that triggered the event.

BoxType specifies the type of the text box that triggered the event.

Initialize your text boxes. Therefore paste the following code in your user form

Option Explicit

Private mClsTbx() As clsTextBox

Private Sub InitBoxes(ByVal BoxType As String, ByVal BoxNames As Variant)
    Dim StartIdx As Long

    On Error Resume Next
    StartIdx = UBound(mClsTbx) + 1
    On Error GoTo 0
    ReDim Preserve mClsTbx(StartIdx + UBound(BoxNames))

    Dim i As Long
    For i = 0 To UBound(BoxNames)
        Set mClsTbx(i + StartIdx) = New clsTextBox
        Set mClsTbx(i + StartIdx).pTbx = Controls(BoxNames(i))
        mClsTbx(i + StartIdx).BoxType = BoxType
    Next i
End Sub

Private Sub UserForm_Initialize()
    'here we define which TextBox belongs to which type
    InitBoxes BoxType:="TypeA", BoxNames:=Array("TextBoxA1", "TextBoxA2")
    InitBoxes BoxType:="TypeB", BoxNames:=Array("TextBoxB1", "TextBoxB2")
    'add more types here
End Sub


问:
AWS CLI sync error - file not found
I'm sure this must be an obvious error but I am stumped.  The shell script below generates a database dump and gzips it successfully but aws cli gives error:

warning: Skipping file /home/bar/dbsnapshots/foo-12-11-2016.sql.gz/. File does not exist.

I see the trailing slash in this error but do not understand why it is displayed or if, in fact, aws is looking for a directory named foo-12-11-2016.sql.gz for some reason?

ls shows the file as expected.

vi /home/bar/dbsnapshots/foo-12-11-2016.sql.gz opens the gz file successfully.

I have tried the aws command with and without quotes around the path, same error.  I have tried the aws command by itself outside the shell script from command line, same error.  eg

/home/bar/bin/aws s3 sync "/home/bar/dbsnapshots/foo-12-11-2016.sql.gz" s3://foo

The AWS CLI is locally installed by my user on this shared server in /home/bar/awscli-bundle and is configured and was able to create a bucket on S3.  Verified via AWS browser GUI.

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

TODAY=`/bin/date  +"%-m-%-d-%Y"`
BU_DIR=/home/bar/dbsnapshots
LOCALFILE=$BU_DIR/foo-${TODAY}.sql
EXCLUDED_TABLES=(
membersBackupV2
transactionReferer
transpages
)

IGNORED_TABLES_STRING=''
for TABLE in "${EXCLUDED_TABLES[@]}"
do :
   IGNORED_TABLES_STRING+=" --ignore-table=bar_membership.${TABLE}"
done

mysqldump --defaults-extra-file="${BU_DIR}/.my.cnf" --all-databases ${IGNORED_TABLES_STRING} > ${LOCALFILE}

/bin/gzip ${LOCALFILE}

/home/bar/bin/aws s3 sync ${LOCALFILE}.gz s3://foo
</code>```

答:
Solution(Answer) -- Yes, Same problem was occurring for me also i.e.  'File does not exist' warning.
So aws s3 sync is used to synchronise folders only not for a particular file/files. It's expecting both source and target to be folders (local folders or S3 URIs). If you put your file into a folder and then sync your folder to s3 folder. It work fine. Thank you.</p>

Title: AWS CLI sync error - file not found

Body:
I'm sure this must be an obvious error but I am stumped.  The shell script below generates a database dump and gzips it successfully but aws cli gives error:

warning: Skipping file /home/bar/dbsnapshots/foo-12-11-2016.sql.gz/. File does not exist.

I see the trailing slash in this error but do not understand why it is displayed or if, in fact, aws is looking for a directory named foo-12-11-2016.sql.gz for some reason?

ls shows the file as expected.

vi /home/bar/dbsnapshots/foo-12-11-2016.sql.gz opens the gz file successfully.

I have tried the aws command with and without quotes around the path, same error.  I have tried the aws command by itself outside the shell script from command line, same error.  eg

/home/bar/bin/aws s3 sync "/home/bar/dbsnapshots/foo-12-11-2016.sql.gz" s3://foo

The AWS CLI is locally installed by my user on this shared server in /home/bar/awscli-bundle and is configured and was able to create a bucket on S3.  Verified via AWS browser GUI.

#!/bin/bash

TODAY=`/bin/date  +"%-m-%-d-%Y"`
BU_DIR=/home/bar/dbsnapshots
LOCALFILE=$BU_DIR/foo-${TODAY}.sql
EXCLUDED_TABLES=(
membersBackupV2
transactionReferer
transpages
)

IGNORED_TABLES_STRING=''
for TABLE in "${EXCLUDED_TABLES[@]}"
do :
   IGNORED_TABLES_STRING+=" --ignore-table=bar_membership.${TABLE}"
done

mysqldump --defaults-extra-file="${BU_DIR}/.my.cnf" --all-databases ${IGNORED_TABLES_STRING} > ${LOCALFILE}

/bin/gzip ${LOCALFILE}

/home/bar/bin/aws s3 sync ${LOCALFILE}.gz s3://foo


问:
How to make custom wrapper for 2 field groups with ngx-formly?
I'm quite confused how to make a layout for my form with fields using ngx-formly. For example, I've got 2 field groups: General and Dynamic.

How to specify that general will be in one div, and dynamic in another div inside one dropdown(div)?

Official example looks like:
Wrapper:

```<code> <div class="card">
      <h3 class="card-header">{{ to.label }}</h3>
      <div class="card-body">
        <ng-container #fieldComponent></ng-container>
      </div>
    </div>
</code>```

Component:

```<code>fields: FormlyFieldConfig[] = [
    {
      key: 'firstName',
      type: 'input',
      templateOptions: {
        required: true,
        type: 'text',
        label: 'First Name',
      },
    },
    {
      key: 'address',
      wrappers: ['panel'],
      templateOptions: { label: 'Address' },
      fieldGroup: [{
        key: 'town',
        type: 'input',
        templateOptions: {
          required: true,
          type: 'text',
          label: 'Town',
        },
      }],
    },
  ];
</code>```

And here <ng-container #fieldComponent></ng-container> which doesn't specify which exactly field it is

答:
just put them inside a fieldGroup and either use a custom wrapper or custom type to render the dropdown-dev:

using custom type: https://stackblitz.com/edit/angular-u4hep4

using custom wrapper: https://stackblitz.com/edit/angular-gjleoz

note: if you want to control a specified field you may use a custom type.

Body:
I'm quite confused how to make a layout for my form with fields using ngx-formly. For example, I've got 2 field groups: General and Dynamic.

How to specify that general will be in one div, and dynamic in another div inside one dropdown(div)?

Official example looks like:
Wrapper:

{{ to.label }}

        <ng-container #fieldComponent></ng-container>

Component:

fields: FormlyFieldConfig[] = [
    {
      key: 'firstName',
      type: 'input',
      templateOptions: {
        required: true,
        type: 'text',
        label: 'First Name',
      },
    },
    {
      key: 'address',
      wrappers: ['panel'],
      templateOptions: { label: 'Address' },
      fieldGroup: [{
        key: 'town',
        type: 'input',
        templateOptions: {
          required: true,
          type: 'text',
          label: 'Town',
        },
      }],
    },
  ];

And here <ng-container #fieldComponent></ng-container> which doesn't specify which exactly field it is


问:
Converting between windows and unix path with sed losses double slash
This command almost gives me what I want :-

```<code>echo "\\123.123.123.123\path1\1 - path2\path3 path4\path5" | sed 's_\\_/_g' | sed 's_ _\\ _g'
/123.123.123.123/path1/1\ -\ path2/path3\ path4/path5
</code>```

But as one can see, its lost the '//' at the beginning!

ie, desired outout :-

```<code>//123.123.123.123/path1/1\ -\ path2/path3\ path4/path5
</code>```

What am I missing?

Edit: After not testing the basics of echo (many thanks to all who pointed that out). I should of also been more clear on the end-game of this question.

I want to use this in a script, and define the windows path at the top.

How can I echo the path to a tmp file for sed?

This obviously wont work :-

```<code>WIN_PATH="\\123.123.123.123\path1\1 - path2\path3 path4\path5"
UNIX_PATH=`echo $WIN_PATH | sed 's_\\_/_g' | sed 's_ _\\ _g'`
</code>```

答:
if you want to do that, use single quotes so that the slash does not get interpreted.</p>

```<code>echo '\\123.123.123.123\path1\1 - path2\path3 path4\path5'
</code>```

Body:
This command almost gives me what I want :-

echo "\\123.123.123.123\path1\1 - path2\path3 path4\path5" | sed 's_\\_/_g' | sed 's_ _\\ _g'
/123.123.123.123/path1/1\ -\ path2/path3\ path4/path5

But as one can see, its lost the '//' at the beginning!

ie, desired outout :-

//123.123.123.123/path1/1\ -\ path2/path3\ path4/path5

What am I missing?

Edit: After not testing the basics of echo (many thanks to all who pointed that out). I should of also been more clear on the end-game of this question.

I want to use this in a script, and define the windows path at the top.

How can I echo the path to a tmp file for sed?

This obviously wont work :-

WIN_PATH="\\123.123.123.123\path1\1 - path2\path3 path4\path5"
UNIX_PATH=`echo $WIN_PATH | sed 's_\\_/_g' | sed 's_ _\\ _g'`

Body:
if you want to do that, use single quotes so that the slash does not get interpreted.

echo '\\123.123.123.123\path1\1 - path2\path3 path4\path5'


问:
how to take backup of mysql database using php
I need to export backup of the database using php when I click on the link. I searched so many references and created code. But when I execute this it displays error. Can anyone help me to get the solution? This is my code

```<code><a href="back.php">BACKUP</a>
</code>```

Back.php

```<code><?php
include('../database.php');
   $dbhost = $_SERVER['SERVER_NAME'];
   $dbuser = 'root';
   $dbpass = '';
   $dbname='marketing';
   $backup_file = $dbname . date("Y-m-d-H-i-s") . '.gz';
   $command = "mysqldump --opt -h $dbhost -u $dbuser -p $dbpass ". "$dbname | gzip > $backup_file";

   $sys=system($command);
if($sys)
{
    echo "succc";
}
else{
    echo "failed";
}

?>
</code>```

答:
i changed a bit to support utf8</p>

```<code><title><?php echo "backup MySQL data - " . $_SERVER['SERVER_NAME'] ; ?></title>
<?php

// ref. to https://stackoverflow.com/questions/52530833/how-to-take-backup-of-mysql-database-using-php
    $dbhost = 'localhost';
    $dbuser = 'root';
    $dbpass = '';
    $dbname = 'jackycms2019';
    $connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
    mysqli_set_charset($connection,"utf8");
    $backupAlert = '';
    $tables = array();
    $result = mysqli_query($connection, "SHOW TABLES");
    if (!$result) {
        $backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
    } else {
        while ($row = mysqli_fetch_row($result)) {
            $tables[] = $row[0];
        }
        mysqli_free_result($result);

        $return = '';
        foreach ($tables as $table) {

            $result = mysqli_query($connection, "SELECT * FROM " . $table);
            if (!$result) {
                $backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
            } else {
                $num_fields = mysqli_num_fields($result);
                if (!$num_fields) {
                    $backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
                } else {
                    $return .= 'DROP TABLE ' . $table . ';';
                    $row2 = mysqli_fetch_row(mysqli_query($connection, 'SHOW CREATE TABLE ' . $table));
                    if (!$row2) {
                        $backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
                    } else {
                        $return .= "\n\n" . $row2[1] . ";\n\n";
                        for ($i = 0; $i < $num_fields; $i++) {
                            while ($row = mysqli_fetch_row($result)) {
                                $return .= 'INSERT INTO ' . $table . ' VALUES(';
                                for ($j = 0; $j < $num_fields; $j++) {
                                    $row[$j] = addslashes($row[$j]);
                                    if (isset($row[$j])) {
                                        $return .= '"' . $row[$j] . '"';
                                    } else {
                                        $return .= '""';
                                    }
                                    if ($j < $num_fields - 1) {
                                        $return .= ',';
                                    }
                                }
                                $return .= ");\n";
                            }
                        }
                        $return .= "\n\n\n";
                    }

                    $backup_file = $dbname . '.sql';
                    $handle = fopen("{$backup_file}", 'w+');
                    fwrite($handle, $return);
                    fclose($handle);
                    $backupAlert = 'backup MySQL data completed !';
                }
            }
        }
    }
    echo $backupAlert;
?>
</code>```

Body:
I need to export backup of the database using php when I click on the link. I searched so many references and created code. But when I execute this it displays error. Can anyone help me to get the solution? This is my code

BACKUP

Back.php

<?php
include('../database.php');
   $dbhost = $_SERVER['SERVER_NAME'];
   $dbuser = 'root';
   $dbpass = '';
   $dbname='marketing';
   $backup_file = $dbname . date("Y-m-d-H-i-s") . '.gz';
   $command = "mysqldump --opt -h $dbhost -u $dbuser -p $dbpass ". "$dbname | gzip > $backup_file";

   $sys=system($command);
if($sys)
{
    echo "succc";
}
else{
    echo "failed";
}

?>

Body:
i changed a bit to support utf8

<title><?php echo "backup MySQL data - " . $_SERVER['SERVER_NAME'] ; ?></title>
<?php

// ref. to https://stackoverflow.com/questions/52530833/how-to-take-backup-of-mysql-database-using-php
    $dbhost = 'localhost';
    $dbuser = 'root';
    $dbpass = '';
    $dbname = 'jackycms2019';
    $connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
    mysqli_set_charset($connection,"utf8");
    $backupAlert = '';
    $tables = array();
    $result = mysqli_query($connection, "SHOW TABLES");
    if (!$result) {
        $backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
    } else {
        while ($row = mysqli_fetch_row($result)) {
            $tables[] = $row[0];
        }
        mysqli_free_result($result);

        $return = '';
        foreach ($tables as $table) {

            $result = mysqli_query($connection, "SELECT * FROM " . $table);
            if (!$result) {
                $backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
            } else {
                $num_fields = mysqli_num_fields($result);
                if (!$num_fields) {
                    $backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
                } else {
                    $return .= 'DROP TABLE ' . $table . ';';
                    $row2 = mysqli_fetch_row(mysqli_query($connection, 'SHOW CREATE TABLE ' . $table));
                    if (!$row2) {
                        $backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
                    } else {
                        $return .= "\n\n" . $row2[1] . ";\n\n";
                        for ($i = 0; $i < $num_fields; $i++) {
                            while ($row = mysqli_fetch_row($result)) {
                                $return .= 'INSERT INTO ' . $table . ' VALUES(';
                                for ($j = 0; $j < $num_fields; $j++) {
                                    $row[$j] = addslashes($row[$j]);
                                    if (isset($row[$j])) {
                                        $return .= '"' . $row[$j] . '"';
                                    } else {
                                        $return .= '""';
                                    }
                                    if ($j < $num_fields - 1) {
                                        $return .= ',';
                                    }
                                }
                                $return .= ");\n";
                            }
                        }
                        $return .= "\n\n\n";
                    }

                    $backup_file = $dbname . '.sql';
                    $handle = fopen("{$backup_file}", 'w+');
                    fwrite($handle, $return);
                    fclose($handle);
                    $backupAlert = 'backup MySQL data completed !';
                }
            }
        }
    }
    echo $backupAlert;
?>


问:
How to convert list to cv::UMat?
I have the list, this list gets from dlib detector:

```<code>dets = detector(frame, 0)
dets = [list(rect_to_bb(dets[0]))]
print(dets)
[[277, 294, 150, 149]]
</code>```

How I can convert this list to Umat ?

```<code>faces = cascade.detectMultiScale(gray, 1.3, 5)
print(faces)
[[259 264 182 182]]
</code>```

The exception, when I use the list

```<code>    _, landmarks = facemark.fit(gray, dets)
TypeError: Expected cv::UMat for argument 'faces'
</code>```

答:
```<code>dets = cv2.UMat(np.array(dets, dtype=np.uint8))
</code>```

look at link

Title: How to convert list to cv::UMat?

Body:
I have the list, this list gets from dlib detector:

dets = detector(frame, 0)
dets = [list(rect_to_bb(dets[0]))]
print(dets)
[[277, 294, 150, 149]]

How I can convert this list to Umat ?

faces = cascade.detectMultiScale(gray, 1.3, 5)
print(faces)
[[259 264 182 182]]

The exception, when I use the list

    _, landmarks = facemark.fit(gray, dets)
TypeError: Expected cv::UMat for argument 'faces'

Body:
dets = cv2.UMat(np.array(dets, dtype=np.uint8))

look at link


问:
How can I recursively copy files of a specific pattern into a single flat folder on Windows?
I need to copy a set of DLL and PDB files from a set of folders recursively into another folder.  I don't want to recreate the folder hierarchy in the target folder.
I want to use built in Windows tools, e.g. DOS commands. </p>

答:
```<code>@echo off
if %1'==' goto usage
if %2'==' goto usage
if %3'==' goto usage
for /D %%F in (%1\*) do xcopy %%F\%2 %3 /D /Y
for /D %%F in (%1\*.) do call TreeCopy %%F %2 %3
goto end
:usage
@echo Usage: TreeCopy [Source folder] [Search pattern] [Destination folder]
@echo Example: TreeCopy C:\Project\UDI *.xsd C:\Project\UDI\SOA\Deploy\Metadata
:end
</code>```

OwnerDisplayName: mickdelaney

LastEditorDisplayName: Alexander Prokofyev


问:
rails5: How one can exclude retweet and replies from search api?
I am trying to fetch tweets using API, but i don't want any retweets and replies. By research i came up with solution that "-is:retweet" and "-is:reply" operators can be used to exclude retweets and replies.

I am simply using search query

```<code>tweets = client.user_timeline('userName', count: 20)
</code>```

As, I am new to rails and twitter api, i don't how to use both the given operators in search query.

Even any alternative answers would be appreciable.

答:
You tweet's have methods to check for both so you should be able to simply do</p>

```<code>tweets.reject{|tweet| tweet.retweeted_tweet? || tweet.reply? }
</code>```

Body:
I am trying to fetch tweets using API, but i don't want any retweets and replies. By research i came up with solution that "-is:retweet" and "-is:reply" operators can be used to exclude retweets and replies.

I am simply using search query

tweets = client.user_timeline('userName', count: 20)

As, I am new to rails and twitter api, i don't how to use both the given operators in search query.

Even any alternative answers would be appreciable.

Body:
You tweet's have methods to check for both so you should be able to simply do

tweets.reject{|tweet| tweet.retweeted_tweet? || tweet.reply? }


问:
What is the correct contract of the function "map" in Liquid Haskell?
I am trying to solve some exercise from LiquidHaskell tutorial. So, I wrote this:

```<code>data List a = Nil | Cons a (List a) deriving (Show)
infixr 5 `Cons`

{-@ len :: List a -> Nat @-}
len :: List a -> Int
len Nil           = 0
len (x `Cons` xs) = 1 + len xs

{-@ mymap :: (a -> b) -> xs : List a -> { ys : List b | len xs == len ys } @-}
mymap :: (a -> b) -> List a -> List b
mymap _ Nil           = Nil
mymap f (x `Cons` xs) = f x `Cons` mymap f xs
</code>```

But I'm getting an error (excuse, pls, this formatting, it's the original LH error format):

```<code>53 | mymap f (x `Cons` xs) = f x `Cons` mymap f xs
                              ^^^^^^^^^^^^^^^^^^^^^

   Inferred type
     VV : {v : (Main.List a) | Main.Cons##lqdc##$select v == ?a
                               && Main.Cons##lqdc##$select v == ds_d35c x
                               && v == Main.Cons (ds_d35c x) ?a}

   not a subtype of Required type
     VV : {VV : (Main.List a) | len ?b == len VV}

   In Context
     xs : (Main.List a)

     ?b : (Main.List a)

     x : a

     ?a : {?a : (Main.List a) | len xs == len ?a}
</code>```

What is the right "contract" of mymap? How to fix this error? And how should be read/treated messages like Main.Cons##lqdc##$select v == ds_d35c x?

答:
I had to explicitly annotate the constructors.
After that, it compiles with LiquidHaskell.</p>

```<code>data List a = Nil | Cons a (List a) deriving (Show)
infixr 5 `Cons`

{-@ len :: List a -> Nat @-}
len :: List a -> Int
len Nil           = 0
len (x `Cons` xs) = 1 + len xs

{-@ Nil   ::  { ys : List a | len ys == 0 } @-}
{-@ Cons  ::  a -> xs : List a -> { ys : List a | len ys == 1 + len xs } @-}

{-@ mymap :: (a -> b) -> xs : List a -> { ys : List b | len xs == len ys } / [ len xs ] @-}
mymap :: (a -> b) -> List a -> List b
mymap _ Nil           = Nil
mymap f (x `Cons` xs) = f x `Cons` mymap f xs
</code>```

Body:
I am trying to solve some exercise from LiquidHaskell tutorial. So, I wrote this:

data List a = Nil | Cons a (List a) deriving (Show)
infixr 5 `Cons`

{-@ len :: List a -> Nat @-}
len :: List a -> Int
len Nil           = 0
len (x `Cons` xs) = 1 + len xs

{-@ mymap :: (a -> b) -> xs : List a -> { ys : List b | len xs == len ys } @-}
mymap :: (a -> b) -> List a -> List b
mymap _ Nil           = Nil
mymap f (x `Cons` xs) = f x `Cons` mymap f xs

But I'm getting an error (excuse, pls, this formatting, it's the original LH error format):

53 | mymap f (x `Cons` xs) = f x `Cons` mymap f xs
                              ^^^^^^^^^^^^^^^^^^^^^

   Inferred type
     VV : {v : (Main.List a) | Main.Cons##lqdc##$select v == ?a
                               && Main.Cons##lqdc##$select v == ds_d35c x
                               && v == Main.Cons (ds_d35c x) ?a}

   not a subtype of Required type
     VV : {VV : (Main.List a) | len ?b == len VV}

   In Context
     xs : (Main.List a)

     ?b : (Main.List a)

     x : a

     ?a : {?a : (Main.List a) | len xs == len ?a}

What is the right "contract" of mymap? How to fix this error? And how should be read/treated messages like Main.Cons##lqdc##$select v == ds_d35c x?

Body:
I had to explicitly annotate the constructors.
After that, it compiles with LiquidHaskell.

data List a = Nil | Cons a (List a) deriving (Show)
infixr 5 `Cons`

{-@ len :: List a -> Nat @-}
len :: List a -> Int
len Nil           = 0
len (x `Cons` xs) = 1 + len xs

{-@ Nil   ::  { ys : List a | len ys == 0 } @-}
{-@ Cons  ::  a -> xs : List a -> { ys : List a | len ys == 1 + len xs } @-}

{-@ mymap :: (a -> b) -> xs : List a -> { ys : List b | len xs == len ys } / [ len xs ] @-}
mymap :: (a -> b) -> List a -> List b
mymap _ Nil           = Nil
mymap f (x `Cons` xs) = f x `Cons` mymap f xs


问:
Pushing to Git returning Error Code 403 fatal: HTTP request failed
I was able to clone a copy of this repo over HTTPS authenticated. I've made some commits and want to push back out to the GitHub server. Using Cygwin on Windows 7 x64.

```<code>C:\cygwin\home\XPherior\Code\lunch_call>git push
Password:
error: The requested URL returned error: 403 while accessing https://MichaelDrog
alis@github.com/derekerdmann/lunch_call.git/info/refs

fatal: HTTP request failed
</code>```

Also set it up with verbose mode. I'm still pretty baffled.

```<code>C:\cygwin\home\XPherior\Code\lunch_call>set GIT_CURL_VERBOSE=1

C:\cygwin\home\XPherior\Code\lunch_call>git push
Password:
* Couldn't find host github.com in the _netrc file; using defaults
* About to connect() to github.com port 443 (#0)
*   Trying 207.97.227.239... * 0x23cb740 is at send pipe head!
* Connected to github.com (207.97.227.239) port 443 (#0)
* successfully set certificate verify locations:
*   CAfile: C:\Program Files (x86)\Git/bin/curl-ca-bundle.crt
  CApath: none
* SSL connection using AES256-SHA
* Server certificate:
*        subject: 2.5.4.15=Private Organization; 1.3.6.1.4.1.311.60.2.1.3=US; 1.
3.6.1.4.1.311.60.2.1.2=California; serialNumber=C3268102; C=US; ST=California; L
=San Francisco; O=GitHub, Inc.; CN=github.com
*        start date: 2011-05-27 00:00:00 GMT
*        expire date: 2013-07-29 12:00:00 GMT
*        subjectAltName: github.com matched
*        issuer: C=US; O=DigiCert Inc; OU=www.digicert.com; CN=DigiCert High Ass
urance EV CA-1
*        SSL certificate verify ok.
> GET /derekerdmann/lunch_call.git/info/refs?service=git-receive-pack HTTP/1.1
User-Agent: git/1.7.4.3282.g844cb
Host: github.com
Accept: */*
Pragma: no-cache

< HTTP/1.1 401 Authorization Required
< Server: nginx/1.0.4
< Date: Thu, 15 Sep 2011 22:44:41 GMT
< Content-Type: text/plain
< Connection: keep-alive
< Content-Length: 55
< WWW-Authenticate: Basic realm="GitHub"
<
* Ignoring the response-body
* Expire cleared
* Connection #0 to host github.com left intact
* Issue another request to this URL: 'https://MichaelDrogalis@github.com/dereker
dmann/lunch_call.git/info/refs?service=git-receive-pack'
* Couldn't find host github.com in the _netrc file; using defaults
* Re-using existing connection! (#0) with host github.com
* Connected to github.com (207.97.227.239) port 443 (#0)
* 0x23cb740 is at send pipe head!
* Server auth using Basic with user 'MichaelDrogalis'
> GET /derekerdmann/lunch_call.git/info/refs?service=git-receive-pack HTTP/1.1
Authorization: Basic XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
User-Agent: git/1.7.4.3282.g844cb
Host: github.com
Accept: */*
Pragma: no-cache

< HTTP/1.1 401 Authorization Required
< Server: nginx/1.0.4
< Date: Thu, 15 Sep 2011 22:44:41 GMT
< Content-Type: text/plain
< Connection: keep-alive
< Content-Length: 55
* Authentication problem. Ignoring this.
< WWW-Authenticate: Basic realm="GitHub"
* The requested URL returned error: 401
* Closing connection #0
* Couldn't find host github.com in the _netrc file; using defaults
* About to connect() to github.com port 443 (#0)
*   Trying 207.97.227.239... * 0x23cb740 is at send pipe head!
* Connected to github.com (207.97.227.239) port 443 (#0)
* successfully set certificate verify locations:
*   CAfile: C:\Program Files (x86)\Git/bin/curl-ca-bundle.crt
  CApath: none
* SSL re-using session ID
* SSL connection using AES256-SHA
* old SSL session ID is stale, removing
* Server certificate:
*        subject: 2.5.4.15=Private Organization; 1.3.6.1.4.1.311.60.2.1.3=US; 1.
3.6.1.4.1.311.60.2.1.2=California; serialNumber=C3268102; C=US; ST=California; L
=San Francisco; O=GitHub, Inc.; CN=github.com
*        start date: 2011-05-27 00:00:00 GMT
*        expire date: 2013-07-29 12:00:00 GMT
*        subjectAltName: github.com matched
*        issuer: C=US; O=DigiCert Inc; OU=www.digicert.com; CN=DigiCert High Ass
urance EV CA-1
*        SSL certificate verify ok.
* Server auth using Basic with user 'MichaelDrogalis'
> GET /derekerdmann/lunch_call.git/info/refs HTTP/1.1
Authorization: Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
User-Agent: git/1.7.4.3282.g844cb
Host: github.com
Accept: */*
Pragma: no-cache

* The requested URL returned error: 403
* Expire cleared
* Closing connection #0
error: The requested URL returned error: 403 while accessing https://MichaelDrog
alis@github.com/derekerdmann/lunch_call.git/info/refs

fatal: HTTP request failed
</code>```

These are the versions of git and curl that I have:

```<code>C:\Users\XPherior>git --version
git version 1.7.4.msysgit.0

C:\Users\XPherior>curl --version
curl 7.21.7 (amd64-pc-win32) libcurl/7.21.7 OpenSSL/0.9.8r zlib/1.2.5
Protocols: dict file ftp ftps gopher http https imap imaps ldap pop3 pop3s rtsp
smtp smtps telnet tftp
Features: AsynchDNS GSS-Negotiate Largefile NTLM SSL SSPI libz
</code>```

答:
Provide write access for the user.

After providing the access.Pull the code once and then push it.

Body:
I was able to clone a copy of this repo over HTTPS authenticated. I've made some commits and want to push back out to the GitHub server. Using Cygwin on Windows 7 x64.

C:\cygwin\home\XPherior\Code\lunch_call>git push
Password:
error: The requested URL returned error: 403 while accessing https://MichaelDrog
alis@github.com/derekerdmann/lunch_call.git/info/refs

fatal: HTTP request failed

Also set it up with verbose mode. I'm still pretty baffled.

C:\cygwin\home\XPherior\Code\lunch_call>set GIT_CURL_VERBOSE=1

C:\cygwin\home\XPherior\Code\lunch_call>git push
Password:
* Couldn't find host github.com in the _netrc file; using defaults
* About to connect() to github.com port 443 (#0)
*   Trying 207.97.227.239... * 0x23cb740 is at send pipe head!
* Connected to github.com (207.97.227.239) port 443 (#0)
* successfully set certificate verify locations:
*   CAfile: C:\Program Files (x86)\Git/bin/curl-ca-bundle.crt
  CApath: none
* SSL connection using AES256-SHA
* Server certificate:
*        subject: 2.5.4.15=Private Organization; 1.3.6.1.4.1.311.60.2.1.3=US; 1.
3.6.1.4.1.311.60.2.1.2=California; serialNumber=C3268102; C=US; ST=California; L
=San Francisco; O=GitHub, Inc.; CN=github.com
*        start date: 2011-05-27 00:00:00 GMT
*        expire date: 2013-07-29 12:00:00 GMT
*        subjectAltName: github.com matched
*        issuer: C=US; O=DigiCert Inc; OU=www.digicert.com; CN=DigiCert High Ass
urance EV CA-1
*        SSL certificate verify ok.
> GET /derekerdmann/lunch_call.git/info/refs?service=git-receive-pack HTTP/1.1
User-Agent: git/1.7.4.3282.g844cb
Host: github.com
Accept: */*
Pragma: no-cache

< HTTP/1.1 401 Authorization Required
< Server: nginx/1.0.4
< Date: Thu, 15 Sep 2011 22:44:41 GMT
< Content-Type: text/plain
< Connection: keep-alive
< Content-Length: 55
< WWW-Authenticate: Basic realm="GitHub"
<
* Ignoring the response-body
* Expire cleared
* Connection #0 to host github.com left intact
* Issue another request to this URL: 'https://MichaelDrogalis@github.com/dereker
dmann/lunch_call.git/info/refs?service=git-receive-pack'
* Couldn't find host github.com in the _netrc file; using defaults
* Re-using existing connection! (#0) with host github.com
* Connected to github.com (207.97.227.239) port 443 (#0)
* 0x23cb740 is at send pipe head!
* Server auth using Basic with user 'MichaelDrogalis'
> GET /derekerdmann/lunch_call.git/info/refs?service=git-receive-pack HTTP/1.1
Authorization: Basic XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
User-Agent: git/1.7.4.3282.g844cb
Host: github.com
Accept: */*
Pragma: no-cache

< HTTP/1.1 401 Authorization Required
< Server: nginx/1.0.4
< Date: Thu, 15 Sep 2011 22:44:41 GMT
< Content-Type: text/plain
< Connection: keep-alive
< Content-Length: 55
* Authentication problem. Ignoring this.
< WWW-Authenticate: Basic realm="GitHub"
* The requested URL returned error: 401
* Closing connection #0
* Couldn't find host github.com in the _netrc file; using defaults
* About to connect() to github.com port 443 (#0)
*   Trying 207.97.227.239... * 0x23cb740 is at send pipe head!
* Connected to github.com (207.97.227.239) port 443 (#0)
* successfully set certificate verify locations:
*   CAfile: C:\Program Files (x86)\Git/bin/curl-ca-bundle.crt
  CApath: none
* SSL re-using session ID
* SSL connection using AES256-SHA
* old SSL session ID is stale, removing
* Server certificate:
*        subject: 2.5.4.15=Private Organization; 1.3.6.1.4.1.311.60.2.1.3=US; 1.
3.6.1.4.1.311.60.2.1.2=California; serialNumber=C3268102; C=US; ST=California; L
=San Francisco; O=GitHub, Inc.; CN=github.com
*        start date: 2011-05-27 00:00:00 GMT
*        expire date: 2013-07-29 12:00:00 GMT
*        subjectAltName: github.com matched
*        issuer: C=US; O=DigiCert Inc; OU=www.digicert.com; CN=DigiCert High Ass
urance EV CA-1
*        SSL certificate verify ok.
* Server auth using Basic with user 'MichaelDrogalis'
> GET /derekerdmann/lunch_call.git/info/refs HTTP/1.1
Authorization: Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
User-Agent: git/1.7.4.3282.g844cb
Host: github.com
Accept: */*
Pragma: no-cache

* The requested URL returned error: 403
* Expire cleared
* Closing connection #0
error: The requested URL returned error: 403 while accessing https://MichaelDrog
alis@github.com/derekerdmann/lunch_call.git/info/refs

fatal: HTTP request failed

These are the versions of git and curl that I have:

C:\Users\XPherior>git --version
git version 1.7.4.msysgit.0

C:\Users\XPherior>curl --version
curl 7.21.7 (amd64-pc-win32) libcurl/7.21.7 OpenSSL/0.9.8r zlib/1.2.5
Protocols: dict file ftp ftps gopher http https imap imaps ldap pop3 pop3s rtsp
smtp smtps telnet tftp
Features: AsynchDNS GSS-Negotiate Largefile NTLM SSL SSPI libz


问:
LDAP: error code 49 - 80090308: LdapErr: DSID-0C09042F, comment: AcceptSecurityContext error, data 52e, v2580
```<code>LDAP: error code 49 - 80090308: LdapErr: DSID-0C09042F, comment: AcceptSecurityContext error, data 52e, v2580
</code>```

I know "52e" code is when username is valid, but password is invalid. I am using the same user name and password for validating user against Active directory and its working fine.

Here is my java code:

```<code>        String userName = "user_test";
        String password =  "*******";
        String base ="DC=test,DC=local";
        String dn = "cn="+ userName + "," + "CN=Users," + base;

        try {
            Hashtable env = new Hashtable();
            env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            env.put(Context.SECURITY_AUTHENTICATION, "simple");

            env.put(Context.SECURITY_PRINCIPAL, dn);

            env.put(Context.SECURITY_CREDENTIALS, password);

            env.put(Context.PROVIDER_URL, "ldap://*****.test.local:389");

            System.out.println("Attempting to Connect...");

            ctx = new InitialLdapContext(env, null);
            System.out.println("Connection Successful.");
        } catch (NamingException nex) {
            System.out.println("LDAP Connection: FAILED");
            nex.printStackTrace();
        }
        return ctx;
    }

</code>```

I do not know exactly why getting this error. Can anyone please help on this?

答:
In case you use simple authority authentication , you should use short username form

user_test@test.local

I checked, in this case authentication is working. In dn form I have got exactly the same error

```<code>javax.naming.AuthenticationException: [LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1
</code>```

You may also refer to earlier thread LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1

Body:
LDAP: error code 49 - 80090308: LdapErr: DSID-0C09042F, comment: AcceptSecurityContext error, data 52e, v2580

I know "52e" code is when username is valid, but password is invalid. I am using the same user name and password for validating user against Active directory and its working fine.

Here is my java code:

        String userName = "user_test";
        String password =  "*******";
        String base ="DC=test,DC=local";
        String dn = "cn="+ userName + "," + "CN=Users," + base;

        try {
            Hashtable env = new Hashtable();
            env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            env.put(Context.SECURITY_AUTHENTICATION, "simple");

            env.put(Context.SECURITY_PRINCIPAL, dn);

            env.put(Context.SECURITY_CREDENTIALS, password);

            env.put(Context.PROVIDER_URL, "ldap://*****.test.local:389");

            System.out.println("Attempting to Connect...");

            ctx = new InitialLdapContext(env, null);
            System.out.println("Connection Successful.");
        } catch (NamingException nex) {
            System.out.println("LDAP Connection: FAILED");
            nex.printStackTrace();
        }
        return ctx;
    }

I do not know exactly why getting this error. Can anyone please help on this?

Body:
In case you use simple authority authentication , you should use short username form

user_test@test.local

I checked, in this case authentication is working. In dn form I have got exactly the same error

javax.naming.AuthenticationException: [LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1

You may also refer to earlier thread LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1


问:
Splitting a string and inserting the parts in the correct columns inside a table
I am trying to build a fact table with sql server. It currently looks like this:

```<code>[Item]  [Variant Descr.] [Variant Order] [Dim_Colour] [Dim_Size] [Dim_Style]
----------------------------------------------------------------------------
01         NAVY/44        COLOUR/SIZE     NULL         NULL       NULL
02         BLACK/S4       COLOUR/STYLE    NULL         NULL       NULL
</code>```

I need to split the String in [Variant Descr.] and insert the parts into the correct Dim_ Column so the table will eventually look like this:

```<code>[Item]  [Variant Descr.] [Variant Order] [Dim_Colour] [Dim_Size] [Dim_Style]
----------------------------------------------------------------------------
01         NAVY/44        COLOUR/SIZE     NAVY         44       NULL
02         BLACK/S4       COLOUR/STYLE    BLACK        NULL     S4
</code>```

The problem is that the parts of [Variant Order] and the number of parts of [Variant Descr.] may vary for each row. So I basically need to do something like:

Get the String before the '/' in [Variant Descr.]

Get the String before the '/' in [Variant Order]

Insert the first value into the column specified by the second value

Do this for all parts of [Variant Descr.]

Do this for every row in the table

I have already tried to solve this with a user-defined function, only to find out that I cannot use dynamic SQL within a UDF.

Any help would be greatly appreciated

Cheers!

答:
And here is a fully generic approach to split this up (thx Zhorov for the MCVE!)

```<code>CREATE TABLE #Data (
   [Item] varchar(10),
   [Variant Descr.] varchar(50),
   [Variant Order] varchar(50),
   [Dim_Colour] varchar(50),
   [Dim_Size] varchar(50),
   [Dim_Style] varchar(50)
)
INSERT INTO #Data
   ([Item], [Variant Descr.], [Variant Order], [Dim_Colour], [Dim_Size], [Dim_Style])
VALUES
   ('01', 'NAVY/44',       'COLOUR/SIZE',       NULL, NULL, NULL),
   ('02', 'BLACK/S4',      'COLOUR/STYLE',      NULL, NULL, NULL),
   ('03', 'NAVY/44/S4',    'COLOUR/SIZE/STYLE', NULL, NULL, NULL),
   ('04', 'GREEN/1/2/3/4', 'COLOUR/aNewOne/SIZE/EvenMore/STYLE', NULL, NULL, NULL);
GO

WITH Casted AS
(
    SELECT *
          ,CAST('<x>' + REPLACE(d.[Variant Order],'/','</x><x>') + '</x>' AS XML) AS OrderXml
          ,CAST('<x>' + REPLACE(d.[Variant Descr.],'/','</x><x>') + '</x>' AS XML) AS DescrXml
    FROM #Data d
)
SELECT c.Item
      ,A.Position
      ,c.OrderXml.value('/x[sql:column("Position")][1]','nvarchar(max)') AS OrderKey
      ,c.DescrXml.value('/x[sql:column("Position")][1]','nvarchar(max)') AS DescrValue
FROM Casted c
CROSS APPLY(SELECT TOP(SELECT c.OrderXml.value('count(/*)','int')) ROW_NUMBER() OVER(ORDER BY(SELECT NULL)) FROM master..spt_values) A(Position)

GO

DROP TABLE #Data;
</code>```

The result

```<code>+------+----------+----------+------------+
| Item | Position | OrderKey | DescrValue |
+------+----------+----------+------------+
| 02   | 1        | COLOUR   | BLACK      |
+------+----------+----------+------------+
| 02   | 2        | STYLE    | S4         |
+------+----------+----------+------------+
| 04   | 1        | COLOUR   | GREEN      |
+------+----------+----------+------------+
| 04   | 2        | aNewOne  | 1          |
+------+----------+----------+------------+
| 04   | 3        | SIZE     | 2          |
+------+----------+----------+------------+
| 04   | 4        | EvenMore | 3          |
+------+----------+----------+------------+
| 04   | 5        | STYLE    | 4          |
+------+----------+----------+------------+
| 01   | 1        | COLOUR   | NAVY       |
+------+----------+----------+------------+
| 01   | 2        | SIZE     | 44         |
+------+----------+----------+------------+
| 03   | 1        | COLOUR   | NAVY       |
+------+----------+----------+------------+
| 03   | 2        | SIZE     | 44         |
+------+----------+----------+------------+
| 03   | 3        | STYLE    | S4         |
+------+----------+----------+------------+
</code>```

You can proceed with conditional aggregation or with a PIVOT approach.

The idea in short:

I use a cast to XML to allow to reach the fragment by its position.
Furthermore I use CROSS APPLY together with ROW_NUMBER, which will return a list of numbers depending on the count of the current row's list of fragments. This number is now used within sql:column() to read the fitting fragments side-by-side.

Body:
I am trying to build a fact table with sql server. It currently looks like this:

[Item]  [Variant Descr.] [Variant Order] [Dim_Colour] [Dim_Size] [Dim_Style]
----------------------------------------------------------------------------
01         NAVY/44        COLOUR/SIZE     NULL         NULL       NULL
02         BLACK/S4       COLOUR/STYLE    NULL         NULL       NULL

I need to split the String in [Variant Descr.] and insert the parts into the correct Dim_ Column so the table will eventually look like this:

[Item]  [Variant Descr.] [Variant Order] [Dim_Colour] [Dim_Size] [Dim_Style]
----------------------------------------------------------------------------
01         NAVY/44        COLOUR/SIZE     NAVY         44       NULL
02         BLACK/S4       COLOUR/STYLE    BLACK        NULL     S4

The problem is that the parts of [Variant Order] and the number of parts of [Variant Descr.] may vary for each row. So I basically need to do something like:

Get the String before the '/' in [Variant Descr.]

Get the String before the '/' in [Variant Order]

Insert the first value into the column specified by the second value

Do this for all parts of [Variant Descr.]

Do this for every row in the table

I have already tried to solve this with a user-defined function, only to find out that I cannot use dynamic SQL within a UDF.

Any help would be greatly appreciated

Cheers!

Body:
And here is a fully generic approach to split this up (thx Zhorov for the MCVE!)

CREATE TABLE #Data (
   [Item] varchar(10),
   [Variant Descr.] varchar(50),
   [Variant Order] varchar(50),
   [Dim_Colour] varchar(50),
   [Dim_Size] varchar(50),
   [Dim_Style] varchar(50)
)
INSERT INTO #Data
   ([Item], [Variant Descr.], [Variant Order], [Dim_Colour], [Dim_Size], [Dim_Style])
VALUES
   ('01', 'NAVY/44',       'COLOUR/SIZE',       NULL, NULL, NULL),
   ('02', 'BLACK/S4',      'COLOUR/STYLE',      NULL, NULL, NULL),
   ('03', 'NAVY/44/S4',    'COLOUR/SIZE/STYLE', NULL, NULL, NULL),
   ('04', 'GREEN/1/2/3/4', 'COLOUR/aNewOne/SIZE/EvenMore/STYLE', NULL, NULL, NULL);
GO

WITH Casted AS
(
    SELECT *
          ,CAST('<x>' + REPLACE(d.[Variant Order],'/','</x><x>') + '</x>' AS XML) AS OrderXml
          ,CAST('<x>' + REPLACE(d.[Variant Descr.],'/','</x><x>') + '</x>' AS XML) AS DescrXml
    FROM #Data d
)
SELECT c.Item
      ,A.Position
      ,c.OrderXml.value('/x[sql:column("Position")][1]','nvarchar(max)') AS OrderKey
      ,c.DescrXml.value('/x[sql:column("Position")][1]','nvarchar(max)') AS DescrValue
FROM Casted c
CROSS APPLY(SELECT TOP(SELECT c.OrderXml.value('count(/*)','int')) ROW_NUMBER() OVER(ORDER BY(SELECT NULL)) FROM master..spt_values) A(Position)

GO

DROP TABLE #Data;

The result

+------+----------+----------+------------+
| Item | Position | OrderKey | DescrValue |
+------+----------+----------+------------+
| 02   | 1        | COLOUR   | BLACK      |
+------+----------+----------+------------+
| 02   | 2        | STYLE    | S4         |
+------+----------+----------+------------+
| 04   | 1        | COLOUR   | GREEN      |
+------+----------+----------+------------+
| 04   | 2        | aNewOne  | 1          |
+------+----------+----------+------------+
| 04   | 3        | SIZE     | 2          |
+------+----------+----------+------------+
| 04   | 4        | EvenMore | 3          |
+------+----------+----------+------------+
| 04   | 5        | STYLE    | 4          |
+------+----------+----------+------------+
| 01   | 1        | COLOUR   | NAVY       |
+------+----------+----------+------------+
| 01   | 2        | SIZE     | 44         |
+------+----------+----------+------------+
| 03   | 1        | COLOUR   | NAVY       |
+------+----------+----------+------------+
| 03   | 2        | SIZE     | 44         |
+------+----------+----------+------------+
| 03   | 3        | STYLE    | S4         |
+------+----------+----------+------------+

You can proceed with conditional aggregation or with a PIVOT approach.

The idea in short:

I use a cast to XML to allow to reach the fragment by its position.
Furthermore I use CROSS APPLY together with ROW_NUMBER, which will return a list of numbers depending on the count of the current row's list of fragments. This number is now used within sql:column() to read the fitting fragments side-by-side.