问:
Breaking up a string into a list of tokens using another string as a delimiter?
Let's say I have this string:

```<code>char *myTestString = "Hello AND test AND test2";
</code>```

I want to break this down into the set { Hello, test, test2 }, which I can finally iterate over.

Or I have

```<code>char *myTestString2 = "Hi AND there AND test AND test2";
</code>```

I want to break this down into the set { Hi, there, test, test2 }, which I can later iterate over.

How do I achieve this using C?

EDIT:
Another example is splitting "Hello there AND test" should give out set { Hello there, test }.
For clarification "AND" is delimiter here.

答:
strstr() is the tool you are looking for. It can locate a string inside another string.

Here is a simple solution with these extra specifications:

the return value is an array of (n+1) entries, the last one being a null pointer.

the separator string can appear anywhere, including inside a word.

substrings are trimmed: initial and trailing white space is removed

substrings are allocated with strndup() which is standardized in POSIX.

the separator string must have a length of at least 1

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *strdup_trim(const char *s, size_t n) {
    while (n > 0 && isspace((unsigned char)*s)) {
        s++;
        n--;
    }
    while (n > 0 && isspace((unsigned char)s[n - 1])) {
        n--;
    }
    return strndup(s, n);
}

char **split(const char *str, const char *sep) {
    size_t i, n, sep_len = strlen(sep);
    char **a;
    const char *p, *p0;

    if (sep_len == 0)
        return NULL;
    for (n = 0, p = str; (p = strstr(p, sep)) != NULL; n++, p += sep_len)
        continue;
    a = malloc(sizeof(*a) * (n + 2));
    if (a == NULL)
        return NULL;
    for (i = 0, p = str; (p = strstr(p0 = p, sep)) != NULL; i++, p += sep_len) {
        a[i] = strdup_trim(p0, p - p0);
    }
    a[i++] = strdup_trim(p0, strlen(p0));
    a[i] = NULL;
    return a;
}

void free_split(char **a) {
    if (a) {
        for (size_t i = 0; a[i]; i++)
            free(a[i]);
        free(a);
    }
}

void test(const char *str, const char *sep) {
    char **a = split(str, sep);
    printf("split('%s', '%s') -> {", str, sep);
    for (size_t i = 0; a[i]; i++)
        printf("%s '%s'", &","[!i], a[i]);
    printf(" }\n");
    free_split(a);
}

int main() {
    test("Hello AND test AND test2", "AND");
    test("Hi AND there AND test AND test2", "AND");
    test("Hello there AND test", "AND");
    return 0;
}
```

<p>Output:</p>

<pre class="lang-none prettyprint-override"><code>split('Hello AND test AND test2', 'AND') -> { 'Hello', 'test', 'test2' }
split('Hi AND there AND test AND test2', 'AND') -> { 'Hi', 'there', 'test', 'test2' }
split('Hello there AND test', 'AND') -> { 'Hello there', 'test' }
</code>```

Body:
Let's say I have this string:

char *myTestString = "Hello AND test AND test2";

I want to break this down into the set { Hello, test, test2 }, which I can finally iterate over.

Or I have

char *myTestString2 = "Hi AND there AND test AND test2";

I want to break this down into the set { Hi, there, test, test2 }, which I can later iterate over.

How do I achieve this using C?

EDIT:
Another example is splitting "Hello there AND test" should give out set { Hello there, test }.
For clarification "AND" is delimiter here.

Body:
strstr() is the tool you are looking for. It can locate a string inside another string.

Here is a simple solution with these extra specifications:

the return value is an array of (n+1) entries, the last one being a null pointer.

the separator string can appear anywhere, including inside a word.

substrings are trimmed: initial and trailing white space is removed

substrings are allocated with strndup() which is standardized in POSIX.

the separator string must have a length of at least 1

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *strdup_trim(const char *s, size_t n) {
    while (n > 0 && isspace((unsigned char)*s)) {
        s++;
        n--;
    }
    while (n > 0 && isspace((unsigned char)s[n - 1])) {
        n--;
    }
    return strndup(s, n);
}

char **split(const char *str, const char *sep) {
    size_t i, n, sep_len = strlen(sep);
    char **a;
    const char *p, *p0;

    if (sep_len == 0)
        return NULL;
    for (n = 0, p = str; (p = strstr(p, sep)) != NULL; n++, p += sep_len)
        continue;
    a = malloc(sizeof(*a) * (n + 2));
    if (a == NULL)
        return NULL;
    for (i = 0, p = str; (p = strstr(p0 = p, sep)) != NULL; i++, p += sep_len) {
        a[i] = strdup_trim(p0, p - p0);
    }
    a[i++] = strdup_trim(p0, strlen(p0));
    a[i] = NULL;
    return a;
}

void free_split(char **a) {
    if (a) {
        for (size_t i = 0; a[i]; i++)
            free(a[i]);
        free(a);
    }
}

void test(const char *str, const char *sep) {
    char **a = split(str, sep);
    printf("split('%s', '%s') -> {", str, sep);
    for (size_t i = 0; a[i]; i++)
        printf("%s '%s'", &","[!i], a[i]);
    printf(" }\n");
    free_split(a);
}

int main() {
    test("Hello AND test AND test2", "AND");
    test("Hi AND there AND test AND test2", "AND");
    test("Hello there AND test", "AND");
    return 0;
}

Output:

split('Hello AND test AND test2', 'AND') -> { 'Hello', 'test', 'test2' }
split('Hi AND there AND test AND test2', 'AND') -> { 'Hi', 'there', 'test', 'test2' }
split('Hello there AND test', 'AND') -> { 'Hello there', 'test' }


来源: stackexchange

问:
NestJs can't resolve dependencies, why?
New to NestJs,after the configuration according to https://docs.nestjs.com/techniques/database
can't figure out the problem of my code .

Error: Nest can't resolve dependencies of the AdminRepository (?). Please make sure that the argument Connection at index [0] is available in the TypeOrmModule context.

Admin Module:

```<code>import { Module } from '@nestjs/common';
import {Admin} from "../entities/Admin";
import {TypeOrmModule} from '@nestjs/typeorm';
import {AdminService} from "./admin.service";
import {AdminController} from "./admin.controller";

@Module({
    imports:[TypeOrmModule.forFeature([Admin])],
    exports: [TypeOrmModule],
    providers: [AdminService],
    controllers: [AdminController]
})
export class AdminModule {}
</code>```

AdminController:

```<code>import { Controller } from '@nestjs/common';

@Controller('admin')
export class AdminController {}
</code>```

AdminService:

```<code>import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Admin } from '../entities/Admin';

@Injectable()
export class AdminService {
    constructor(
        @InjectRepository(Admin)
        private readonly adminRepository:Repository<Admin>
    ) {}
}
</code>```

App Module:

```<code>import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { LoginController } from './login/login.controller';
import { RegisterController } from './register/register.controller';
import { ContactController } from './contact/contact.controller';

import { AppService } from './app.service';
import { LoginService } from './login/login.service';
import { ContactService } from './contact/contact.service';
import { RegisterService } from './register/register.service';
import { AdminModule } from './admin/admin.module';

@Module({
  imports: [AdminModule],
  controllers: [AppController, LoginController, RegisterController, ContactController],
  providers: [AppService, LoginService, ContactService, RegisterService],
})
export class AppModule {}
</code>```

答: It looks like you are missing TypeOrmModule.forRoot()/forRootAsync() in your AppModule which sets up the initial connection to the database. Make sure that is added to the imports array (with the necessary configurations) and you should be good to go.

ContentLicense: CC BY-SA 4.0

Title: NestJs can't resolve dependencies, why?

Body:
New to NestJs,after the configuration according to https://docs.nestjs.com/techniques/database
can't figure out the problem of my code .

Error: Nest can't resolve dependencies of the AdminRepository (?). Please make sure that the argument Connection at index [0] is available in the TypeOrmModule context.

Admin Module:

import { Module } from '@nestjs/common';
import {Admin} from "../entities/Admin";
import {TypeOrmModule} from '@nestjs/typeorm';
import {AdminService} from "./admin.service";
import {AdminController} from "./admin.controller";

@Module({
    imports:[TypeOrmModule.forFeature([Admin])],
    exports: [TypeOrmModule],
    providers: [AdminService],
    controllers: [AdminController]
})
export class AdminModule {}

AdminController:

import { Controller } from '@nestjs/common';

@Controller('admin')
export class AdminController {}

AdminService:

import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Admin } from '../entities/Admin';

@Injectable()
export class AdminService {
    constructor(
        @InjectRepository(Admin)
        private readonly adminRepository:Repository<Admin>
    ) {}
}

App Module:

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { LoginController } from './login/login.controller';
import { RegisterController } from './register/register.controller';
import { ContactController } from './contact/contact.controller';

import { AppService } from './app.service';
import { LoginService } from './login/login.service';
import { ContactService } from './contact/contact.service';
import { RegisterService } from './register/register.service';
import { AdminModule } from './admin/admin.module';

@Module({
  imports: [AdminModule],
  controllers: [AppController, LoginController, RegisterController, ContactController],
  providers: [AppService, LoginService, ContactService, RegisterService],
})
export class AppModule {}


问:
Using agvtool with multiple .xcodeproject files in one directory
I have tried using agvtool for ios build versionining. It works great when there is a single .xcodeproj file in the directory. In my case, our project structure is such that it has 4 .xcodeproj files in a single directory. When firing agvtool command in this directory it throws error message, 'agvtool does not work with multiple projects in the same directory'. Anyone has any idea how can I make agvtool work with this folder structure? </p>

答:
For people finding this post and using Fastlane, I just wanted to tell about the plugin https://github.com/SiarheiFedartsou/fastlane-plugin-versioning which have a increment_version_number_in_plist command which does not use agvtool (and support multiple .xcodeproj files in a single folder.

You just need to install the plugin above and replace your increment_version_number action with increment_version_number_in_plist .. they have a very similar contract.

ContentLicense: CC BY-SA 3.0


问:
Sequelize is creating dangling/hanging mysql connections after getting SequelizeDatabaseError: ER_LOCK_DEADLOCK
I have an accounting system in which I try to create transactions at high concurrency (load testing). This results in getting error SequelizeDatabaseError: ER_LOCK_DEADLOCK: Deadlock found when trying to get lock; try restarting transaction from the database (mysql). As per MySQL it is an expected error, but I am observing a unique behavior in this situation:

The connections to database doesn't get closed after such a deadlock. MySQL show processlist shows these connections stuck in insert/update queries.

These connections doesn't get closed for long long time.

My application timesout getting connection to database for further requests on.

It fails to work afterwards for long long time.

Why is this happening? Ideally Sequelize should close the connection if it gets into an error right? Is this a bug with Sequelize?

答:
This appears to be a bug with Sequelize reported for MariaDB and MySQL 5.7 as of February 16th, 2020. The code that handles the deadlock condition neglects to call cleanup on the transaction when this particular error condition is detected. Manually calling cleanup on the transaction when the ER_LOCK_DEADLOCK condition is detected seems to be the current work-around.

For example. something like this code would solve the issue.

```<code>await sequelize.transaction(options, async t => {
    try {
        // transaction code
    } catch (e) {
        if (e instanceof db.Sequelize.DatabaseError
                && e.parent
                && e.parent.code === "ER_LOCK_DEADLOCK")
            await t.cleanup();
    }
 });
</code>```

See https://github.com/sequelize/sequelize/issues/11571

Body:
This appears to be a bug with Sequelize reported for MariaDB and MySQL 5.7 as of February 16th, 2020. The code that handles the deadlock condition neglects to call cleanup on the transaction when this particular error condition is detected. Manually calling cleanup on the transaction when the ER_LOCK_DEADLOCK condition is detected seems to be the current work-around.

For example. something like this code would solve the issue.

await sequelize.transaction(options, async t => {
    try {
        // transaction code
    } catch (e) {
        if (e instanceof db.Sequelize.DatabaseError
                && e.parent
                && e.parent.code === "ER_LOCK_DEADLOCK")
            await t.cleanup();
    }
 });

See https://github.com/sequelize/sequelize/issues/11571


问:
How do you move text vertically relative to its line-height?
I have a small text element next to a div and they are centered in a flex container. When they are this short, it becomes apparent that the text is slightly offset upwards by a few pixels. How would you fix this without using margin-top on the text and not removing any of the existing styles below? Is there a way to move text relative to its line-height?

.container {
display: flex;
align-items: center;
height: 2rem;
border: 1px solid black;
}

h2 {
 font-family: sans-serif;
 line-height: 1;
 font-size: 1rem;
 margin: 0;
}

.box {
 height: 1rem;
 width: 3rem;
 background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
 <div class="box"></div>
 <h2>N</h2>
</div></code>```

答:
use baseline alignment instead of center then consider a pseudo element to simulate the center alignment:

.container {
  display: flex;
  align-items: baseline;
  height: 2rem;
  border: 1px solid black;
}

h2 {
  font-family: sans-serif;
  line-height: 1;
  font-size: 1rem;
  margin: 0;
}

.box {
  height: 1rem;
  width: 3rem;
  background: red;
}

.container:before {
  content:"";
  height: 1.5rem; /* this value is not generic and need to be updated based on your case*/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="box"></div>
  <h2>N</h2>
</div></code>```

Or another idea where you adjust the alignment inside the title using another hack with pseudo element:

.container {
  display: flex;
  align-items: center;
  height: 2rem;
  border: 1px solid black;
}

h2 {
  font-family: sans-serif;
  line-height: 1;
  font-size: 1rem;
  margin: 0;
}
h2:before {
  content: "";
  vertical-align: super;
}

.box {
  height: 1rem;
  width: 3rem;
  background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="box"></div>
  <h2>N</h2>
</div></code>```

Body:
I have a small text element next to a div and they are centered in a flex container. When they are this short, it becomes apparent that the text is slightly offset upwards by a few pixels. How would you fix this without using margin-top on the text and not removing any of the existing styles below? Is there a way to move text relative to its line-height?

.container {
display: flex;
align-items: center;
height: 2rem;
border: 1px solid black;
}

h2 {
 font-family: sans-serif;
 line-height: 1;
 font-size: 1rem;
 margin: 0;
}

.box {
 height: 1rem;
 width: 3rem;
 background: red;
}

N

Body:
use baseline alignment instead of center then consider a pseudo element to simulate the center alignment:

.container {
  display: flex;
  align-items: baseline;
  height: 2rem;
  border: 1px solid black;
}

h2 {
  font-family: sans-serif;
  line-height: 1;
  font-size: 1rem;
  margin: 0;
}

.box {
  height: 1rem;
  width: 3rem;
  background: red;
}

.container:before {
  content:"";
  height: 1.5rem; /* this value is not generic and need to be updated based on your case*/
}

<div class="container">
  <div class="box"></div>
  <h2>N</h2>
</div>

Or another idea where you adjust the alignment inside the title using another hack with pseudo element:

.container {
  display: flex;
  align-items: center;
  height: 2rem;
  border: 1px solid black;
}

h2 {
  font-family: sans-serif;
  line-height: 1;
  font-size: 1rem;
  margin: 0;
}
h2:before {
  content: "";
  vertical-align: super;
}

.box {
  height: 1rem;
  width: 3rem;
  background: red;
}

<div class="container">
  <div class="box"></div>
  <h2>N</h2>
</div>


问:
How to fix columns that collide with each other after sidebar is active?
good

bad

In the first picture called 'good' we can see that the card divs don't collide at each other, but in the second picture when sidebar is active they collide.

I've tried to change from col-md-6 to col-md-12 on that,
but then the site looks not that as I wish when sidebar is closed.

I think when sidebar is active it supposed to change from col-md-6 to col-md-12, but I have no clue how to do that.

I'm a begginer so I will a appreciate some suggestions to fix that problem :)

/*
    DEMO STYLE
*/
@import "https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700";

body {
  font-family: "Poppins", sans-serif;
  background: #fafafa;
}

p {
  font-family: "Poppins", sans-serif;
  font-size: 1.1em;
  font-weight: 300;
  line-height: 1.7em;
  color: #999;
}

a,
a:hover,
a:focus {
  color: inherit;
  text-decoration: none;
  transition: all 0.3s;
}
#zegar {
  font-size: 18px;
}
.card {
  width: 20rem;
}
#chartbtn {
  margin-left: 90px;
}
.card-text {
  padding-top: 45px;
  padding-left: 20px;
}
.navbar {
  padding: 15px 10px;
  background: #fff;
  border: none;
  border-radius: 0;
  margin-bottom: 40px;
  box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);
}

.navbar-btn {
  box-shadow: none;
  outline: none !important;
  border: none;
}

.line {
  width: 100%;
  height: 1px;
  border-bottom: 1px dashed #ddd;
  margin: 20px 0;
}

/* ---------------------------------------------------
    SIDEBAR STYLE
----------------------------------------------------- */

.wrapper {
  display: flex;
  width: 100%;
  align-items: stretch;
  perspective: 1500px;
}

#sidebar {
  min-width: 250px;
  max-width: 250px;
  background: #3e5e82;
  color: #fff;
  transition: all 0.6s cubic-bezier(0.945, 0.02, 0.27, 0.665);
  transform-origin: bottom left;
}

#sidebar.active {
  margin-left: -250px;
  transform: rotateY(100deg);
}

#sidebar .sidebar-header {
  padding: 20px;
  background: #3a5678;
}

#sidebar ul.components {
  padding: 20px 0;
  border-bottom: 1px solid #47748b;
}

#sidebar ul p {
  color: #fff;
  padding: 10px;
}

#sidebar ul li a {
  padding: 10px;
  font-size: 1.1em;
  display: block;
}
#sidebar ul li a:hover {
  color: #3a5678;
  background: #fff;
}

#sidebar ul li.active > a,
a[aria-expanded="true"] {
  color: #fff;
  background: #3a5678;
}

a[data-toggle="collapse"] {
  position: relative;
}

.dropdown-toggle::after {
  display: block;
  position: absolute;
  top: 50%;
  right: 20px;
  transform: translateY(-50%);
}

ul ul a {
  font-size: 0.9em !important;
  padding-left: 30px !important;
  background: #3e5e82;
}

ul.CTAs {
  padding: 20px;
}

ul.CTAs a {
  text-align: center;
  font-size: 0.9em !important;
  display: block;
  border-radius: 5px;
  margin-bottom: 5px;
}

a.download {
  background: #fff;
  color: #3a5678;
}

a.article,
a.article:hover {
  background: #6d7fcc !important;
  color: #fff !important;
}

/* ---------------------------------------------------
    CONTENT STYLE
----------------------------------------------------- */
#content {
  width: 100%;
  padding: 20px;
  min-height: 100vh;
  transition: all 0.3s;
}

#sidebarCollapse {
  width: 40px;
  height: 40px;
  background: #f5f5f5;
  cursor: pointer;
}

#sidebarCollapse span {
  width: 80%;
  height: 2px;
  margin: 0 auto;
  display: block;
  background: #555;
  transition: all 0.8s cubic-bezier(0.81, -0.33, 0.345, 1.375);
  transition-delay: 0.2s;
}

#sidebarCollapse span:first-of-type {
  transform: rotate(45deg) translate(2px, 2px);
}
#sidebarCollapse span:nth-of-type(2) {
  opacity: 0;
}
#sidebarCollapse span:last-of-type {
  transform: rotate(-45deg) translate(1px, -1px);
}

#sidebarCollapse.active span {
  transform: none;
  opacity: 1;
  margin: 5px auto;
}

/* ---------------------------------------------------
    MEDIAQUERIES
----------------------------------------------------- */
@media (max-width: 768px) {
  #sidebar {
    margin-left: -250px;
    transform: rotateY(90deg);
  }
  #sidebar.active {
    margin-left: 0;
    transform: none;
  }
  #sidebarCollapse span:first-of-type,
  #sidebarCollapse span:nth-of-type(2),
  #sidebarCollapse span:last-of-type {
    transform: none;
    opacity: 1;
    margin: 5px auto;
  }
  #sidebarCollapse.active span {
    margin: 0 auto;
  }
  #sidebarCollapse.active span:first-of-type {
    transform: rotate(45deg) translate(2px, 2px);
  }
  #sidebarCollapse.active span:nth-of-type(2) {
    opacity: 0;
  }
  #sidebarCollapse.active span:last-of-type {
    transform: rotate(-45deg) translate(1px, -1px);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><?Php
require_once "connect.php";

$sql = "SELECT * FROM chartjs";

$result = mysqli_query($mysqli, $sql);

while ($row = mysqli_fetch_array($result)) {    //loop through the returned data (jakies randomowe znaczki zeby chartjs umial dane wczytac)
    $temperature = $row['temp2'];
    $humidity = $row['hum'];
    $day = $row['day'];
}
?>

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <title>Uber duper</title>
    <!-- Bootstrap CSS CDN -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
    <!-- Our Custom CSS -->
    <link rel="stylesheet" href="css/style.css" type="text/css">

    <!-- Font Awesome JS -->
    <script defer src="https://use.fontawesome.com/releases/v5.0.13/js/solid.js" integrity="sha384-tzzSw1/Vo+0N5UhStP3bvwWPq+uvzCMfrN1fEFe+xBmv1C/AtVX5K0uZtmcHitFZ" crossorigin="anonymous"></script>
    <script defer src="https://use.fontawesome.com/releases/v5.0.13/js/fontawesome.js" integrity="sha384-6OIrr52G08NpOFSZdxxz1xdNSndlD4vdcf/q2myIUVO0VsqaGHJsB0RaBE01VTOY" crossorigin="anonymous"></script>
    <script src="js/jquery.min.js" type="text/javascript"></script>
    <script src="js/zegar.js" type="text/javascript"> </script>
    <script src="js/timeago.js" type="text/javascript"> </script>
    <script>
        var date = <?php echo json_encode($day, JSON_HEX_TAG); ?>;
    </script>
</head>

<body>

    <div class="wrapper">
        <!-- Sidebar Holder -->
        <nav id="sidebar">
            <div class="sidebar-header">
                <h3>Stacja Pogodowa</h3>
            </div>

            <ul class="list-unstyled components">
                <p></p>
                <li class="active">
                    Panel głowny
                    <ul class="collapse list-unstyled" id="homeSubmenu">

                    </ul>
                </li>
                <li>
                    Wykresy
                    Czujniki
                    <ul class="collapse list-unstyled" id="pageSubmenu">
                        <li>
                            DHT22
                        </li>
                        <li>
                            DS18B20
                        </li>
                        <li>
                            BMP180
                        </li>
                    </ul>
                </li>

            </ul>

        </nav>

        <!-- Page Content Holder -->
        <div id="content">

            <nav class="navbar navbar-expand-lg navbar-light bg-light">
                <div class="container-fluid">

                    <button type="button" id="sidebarCollapse" class="navbar-btn">
                        <span></span>
                        <span></span>
                        <span></span>
                    </button>

                    <body onload="odliczanie();">
                        <div id="zegar"></div>
                </div>
            </nav>
            <!-- początek głownego containera-->
            <div class="container float-left">
                <!-- początek rowa-->
                <div class="row">
                    <!-- początek cola-->
                    <div class="col-md-6 col-xl-4 pt-4">
                        <!-- początek carda-->
                        <div class="card d-inline-block ">
                            <div class="container">
                                <div class="row">
                                    <div class="col">

                                        <h4 class="d-inline-block pt-2 pl-1">DHT22 </h4>
                                        <h3>
                                            <div class="pr-1 pl-1 d-inline-block">
                                                <i class=" fas fa-thermometer-three-quarters"></i>
                                            </div>
                                            <?php
                                            echo $temperature;
                                            ?>°C
                                        </h3>
                                        <h3>
                                            <div class="d-inline-block">
                                                <i class="fas fa-tint"></i>
                                            </div>
                                            <?php
                                            echo $humidity;
                                            ?>%
                                        </h3>

                                    </div>
                                    <div class="col">

                                        <button type="button" class="btn btn-secondary btn-sm mt-2" id="chartbtn"><i class="fas fa-chart-line" style="font-size:24px"></i></button>

                                        <p class="card-text"><small class="text-muted" id="timeago">

                                                <script>
                                                    document.getElementById("timeago").innerHTML = time_ago(date);
                                                </script>

                                            </small></p>

                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- koniec carda-->
                    </div>
                    <!-- koniec cola-->
                    <div class="col-md-6  col-xl-4 pt-4">
                        <!-- początek carda-->
                        <div class="card d-inline-block ">
                            <div class="container">
                                <div class="row">
                                    <div class="col">

                                        <h4 class="d-inline-block pt-2 pl-1">DHT22 </h4>
                                        <h3>
                                            <div class="pr-1 pl-1 d-inline-block">
                                                <i class=" fas fa-thermometer-three-quarters"></i>
                                            </div>
                                            <?php
                                            echo $temperature;
                                            ?>°C
                                        </h3>
                                        <h3>
                                            <div class="d-inline-block">
                                                <i class="fas fa-tint"></i>
                                            </div>
                                            <?php
                                            echo $humidity;
                                            ?>%
                                        </h3>

                                    </div>
                                    <div class="col">

                                        <button type="button" class="btn btn-secondary btn-sm mt-2" id="chartbtn"><i class="fas fa-chart-line" style="font-size:24px"></i></button>

                                        <p class="card-text"><small class="text-muted" id="timeago">

                                                <script>
                                                    document.getElementById("timeago").innerHTML = time_ago(date);
                                                </script>

                                            </small></p>

                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- koniec carda-->
                    </div>
                    <!-- koniec cola-->
                    <div class="col-md-6 col-xl-4 pt-4">
                        <!-- początek carda-->
                        <div class="card d-inline-block ">
                            <div class="container">
                                <div class="row">
                                    <div class="col">

                                        <h4 class="d-inline-block pt-2 pl-1">DHT22 </h4>
                                        <h3>
                                            <div class="pr-1 pl-1 d-inline-block">
                                                <i class=" fas fa-thermometer-three-quarters"></i>
                                            </div>
                                            <?php
                                            echo $temperature;
                                            ?>°C
                                        </h3>
                                        <h3>
                                            <div class="d-inline-block">
                                                <i class="fas fa-tint"></i>
                                            </div>
                                            <?php
                                            echo $humidity;
                                            ?>%
                                        </h3>

                                    </div>
                                    <div class="col">

                                        <button type="button" class="btn btn-secondary btn-sm mt-2" id="chartbtn"><i class="fas fa-chart-line" style="font-size:24px"></i></button>

                                        <p class="card-text"><small class="text-muted" id="timeago">

                                                <script>
                                                    document.getElementById("timeago").innerHTML = time_ago(date);
                                                </script>

                                            </small></p>

                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- koniec carda-->
                    </div>
                    <!-- koniec cola-->
                </div>
                <!-- koniec rowa-->
                <div class="row ">
                    <!-- początek cola-->
                    <div class="col-md-6 col-lg-6 col-xl-4 pt-4 ">
                        <!-- początek carda-->
                        <div class="card d-inline-block">
                            <div class="container">
                                <div class="row">
                                    <div class="col">

                                        <h4 class="d-inline-block pt-2 pl-1">DHT22 </h4>
                                        <h3>
                                            <div class="pr-1 pl-1 d-inline-block">
                                                <i class=" fas fa-thermometer-three-quarters"></i>
                                            </div>
                                            <?php
                                            echo $temperature;
                                            ?>°C
                                        </h3>
                                        <h3>
                                            <div class="d-inline-block">
                                                <i class="fas fa-tint"></i>
                                            </div>
                                            <?php
                                            echo $humidity;
                                            ?>%
                                        </h3>

                                    </div>
                                    <div class="col">

                                        <button type="button" class="btn btn-secondary btn-sm mt-2" id="chartbtn"><i class="fas fa-chart-line" style="font-size:24px"></i></button>

                                        <p class="card-text"><small class="text-muted" id="timeago">

                                                <script>
                                                    document.getElementById("timeago").innerHTML = time_ago(date);
                                                </script>

                                            </small></p>

                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- koniec carda-->
                    </div>
                    <!-- koniec cola-->
                </div>
            </div>
            <!-- koniec głownego containera-->
        </div>
    </div>

    <!-- jQuery CDN - Slim version (=without AJAX) -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <!-- Popper.JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
    <!-- Bootstrap JS -->
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>

    <script type="text/javascript">
        $(document).ready(function() {
            $('#sidebarCollapse').on('click', function() {
                $('#sidebar').toggleClass('active');
                $(this).toggleClass('active');
            });
        });
    </script>
</body>

</html></code>```

答:
They overlap because .card has width: 20rem; which related to body's font-size and the container .col-md-6 has max-width: 50% which related to parent container.

You can fix this by using width: 50% instead of max-width: 50% for .col-md-6, but be careful. You need to rewrite this class only for this case since you are using a fixed width for .card and don't rely on bootstrap's responsiveness.

Body:
good

bad

In the first picture called 'good' we can see that the card divs don't collide at each other, but in the second picture when sidebar is active they collide.

I've tried to change from col-md-6 to col-md-12 on that,
but then the site looks not that as I wish when sidebar is closed.

I think when sidebar is active it supposed to change from col-md-6 to col-md-12, but I have no clue how to do that.

I'm a begginer so I will a appreciate some suggestions to fix that problem :)

/*
    DEMO STYLE
*/
@import "https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700";

body {
  font-family: "Poppins", sans-serif;
  background: #fafafa;
}

p {
  font-family: "Poppins", sans-serif;
  font-size: 1.1em;
  font-weight: 300;
  line-height: 1.7em;
  color: #999;
}

a,
a:hover,
a:focus {
  color: inherit;
  text-decoration: none;
  transition: all 0.3s;
}
#zegar {
  font-size: 18px;
}
.card {
  width: 20rem;
}
#chartbtn {
  margin-left: 90px;
}
.card-text {
  padding-top: 45px;
  padding-left: 20px;
}
.navbar {
  padding: 15px 10px;
  background: #fff;
  border: none;
  border-radius: 0;
  margin-bottom: 40px;
  box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);
}

.navbar-btn {
  box-shadow: none;
  outline: none !important;
  border: none;
}

.line {
  width: 100%;
  height: 1px;
  border-bottom: 1px dashed #ddd;
  margin: 20px 0;
}

/* ---------------------------------------------------
    SIDEBAR STYLE
----------------------------------------------------- */

.wrapper {
  display: flex;
  width: 100%;
  align-items: stretch;
  perspective: 1500px;
}

#sidebar {
  min-width: 250px;
  max-width: 250px;
  background: #3e5e82;
  color: #fff;
  transition: all 0.6s cubic-bezier(0.945, 0.02, 0.27, 0.665);
  transform-origin: bottom left;
}

#sidebar.active {
  margin-left: -250px;
  transform: rotateY(100deg);
}

#sidebar .sidebar-header {
  padding: 20px;
  background: #3a5678;
}

#sidebar ul.components {
  padding: 20px 0;
  border-bottom: 1px solid #47748b;
}

#sidebar ul p {
  color: #fff;
  padding: 10px;
}

#sidebar ul li a {
  padding: 10px;
  font-size: 1.1em;
  display: block;
}
#sidebar ul li a:hover {
  color: #3a5678;
  background: #fff;
}

#sidebar ul li.active > a,
a[aria-expanded="true"] {
  color: #fff;
  background: #3a5678;
}

a[data-toggle="collapse"] {
  position: relative;
}

.dropdown-toggle::after {
  display: block;
  position: absolute;
  top: 50%;
  right: 20px;
  transform: translateY(-50%);
}

ul ul a {
  font-size: 0.9em !important;
  padding-left: 30px !important;
  background: #3e5e82;
}

ul.CTAs {
  padding: 20px;
}

ul.CTAs a {
  text-align: center;
  font-size: 0.9em !important;
  display: block;
  border-radius: 5px;
  margin-bottom: 5px;
}

a.download {
  background: #fff;
  color: #3a5678;
}

a.article,
a.article:hover {
  background: #6d7fcc !important;
  color: #fff !important;
}

/* ---------------------------------------------------
    CONTENT STYLE
----------------------------------------------------- */
#content {
  width: 100%;
  padding: 20px;
  min-height: 100vh;
  transition: all 0.3s;
}

#sidebarCollapse {
  width: 40px;
  height: 40px;
  background: #f5f5f5;
  cursor: pointer;
}

#sidebarCollapse span {
  width: 80%;
  height: 2px;
  margin: 0 auto;
  display: block;
  background: #555;
  transition: all 0.8s cubic-bezier(0.81, -0.33, 0.345, 1.375);
  transition-delay: 0.2s;
}

#sidebarCollapse span:first-of-type {
  transform: rotate(45deg) translate(2px, 2px);
}
#sidebarCollapse span:nth-of-type(2) {
  opacity: 0;
}
#sidebarCollapse span:last-of-type {
  transform: rotate(-45deg) translate(1px, -1px);
}

#sidebarCollapse.active span {
  transform: none;
  opacity: 1;
  margin: 5px auto;
}

/* ---------------------------------------------------
    MEDIAQUERIES
----------------------------------------------------- */
@media (max-width: 768px) {
  #sidebar {
    margin-left: -250px;
    transform: rotateY(90deg);
  }
  #sidebar.active {
    margin-left: 0;
    transform: none;
  }
  #sidebarCollapse span:first-of-type,
  #sidebarCollapse span:nth-of-type(2),
  #sidebarCollapse span:last-of-type {
    transform: none;
    opacity: 1;
    margin: 5px auto;
  }
  #sidebarCollapse.active span {
    margin: 0 auto;
  }
  #sidebarCollapse.active span:first-of-type {
    transform: rotate(45deg) translate(2px, 2px);
  }
  #sidebarCollapse.active span:nth-of-type(2) {
    opacity: 0;
  }
  #sidebarCollapse.active span:last-of-type {
    transform: rotate(-45deg) translate(1px, -1px);
  }
}

<?Php
require_once "connect.php";

$sql = "SELECT * FROM chartjs";

$result = mysqli_query($mysqli, $sql);

while ($row = mysqli_fetch_array($result)) {    //loop through the returned data (jakies randomowe znaczki zeby chartjs umial dane wczytac)
    $temperature = $row['temp2'];
    $humidity = $row['hum'];
    $day = $row['day'];
}
?>

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <title>Uber duper</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">

    <link rel="stylesheet" href="css/style.css" type="text/css">

Stacja Pogodowa

                    Panel głowny

                    Wykresy
                    Czujniki

                            DHT22

                            DS18B20

                            BMP180

                    <button type="button" id="sidebarCollapse" class="navbar-btn">

                    </button>

DHT22

                                            <?php
                                            echo $temperature;
                                            ?>°C

                                            <?php
                                            echo $humidity;
                                            ?>%

                                        <button type="button" class="btn btn-secondary btn-sm mt-2" id="chartbtn"></button>

DHT22

                                            <?php
                                            echo $temperature;
                                            ?>°C

                                            <?php
                                            echo $humidity;
                                            ?>%

                                        <button type="button" class="btn btn-secondary btn-sm mt-2" id="chartbtn"></button>

DHT22

                                            <?php
                                            echo $temperature;
                                            ?>°C

                                            <?php
                                            echo $humidity;
                                            ?>%

                                        <button type="button" class="btn btn-secondary btn-sm mt-2" id="chartbtn"></button>

DHT22

                                            <?php
                                            echo $temperature;
                                            ?>°C

                                            <?php
                                            echo $humidity;
                                            ?>%

                                        <button type="button" class="btn btn-secondary btn-sm mt-2" id="chartbtn"></button>


问:
Copy a Guava Optional
Is there a "nice" way to create a copy of an Optional object?

For example, say I have a method

```<code>Optional<Obj> doSomeStuff(Optional<Obj> input){
   if(something){
     return Optional.copyOf(input); // does this exist in some Guava library or something?
   }
   // ...
}
</code>```

Basically, I want to have immutability so that I don't pass the same Optional around, and if something gets triggered then I want to make sure that I create a brand new Optional with same contents of the input Optional (whether it be empty or not).

Is there any clean way to do it? The Optional.copyOf method does not exist.

答:
Guava Optional is already immutable.
You don't need to make a copy of it.

Here is the beginning of the javadoc:

An immutable object that may contain a non-null reference to another object. Each instance of this type either contains a non-null reference, or contains nothing (in which case we say that the reference is "absent"); it is never said to "contain null".

Title: Copy a Guava Optional

Body:
Is there a "nice" way to create a copy of an Optional object?

For example, say I have a method

Optional<Obj> doSomeStuff(Optional<Obj> input){
   if(something){
     return Optional.copyOf(input); // does this exist in some Guava library or something?
   }
   // ...
}

Basically, I want to have immutability so that I don't pass the same Optional around, and if something gets triggered then I want to make sure that I create a brand new Optional with same contents of the input Optional (whether it be empty or not).

Is there any clean way to do it? The Optional.copyOf method does not exist.


答: The Optional class is immutable,  so you do not need copy,. You can just do return input.

Title: Copy a Guava Optional


问:
Scrapy and redirection
So I've been working on building a web scraper with scrapy and being going through some data validation to make sure that all the items have been correctly grabbed.

I'm using it to grab medium data on articles title, names, claps, responses etc which are all on one html page. But to get the tags, I needed to go to each individual article. Most of the tags I've managed to get but there are a couple of articles which are linked to towardsdatascience.com instead of the medium website. It does a weird little redirect where the link to the article is say for example

https://towardsdatascience.com/cython-a-speed-up-tool-for-your-python-function-9bab64364bfd?source=tag_archive---------1-----------------------

It then redirects to: https://towardsdatascience.com/cython-a-speed-up-tool-for-your-python-function-9bab64364bfd

Now I've noticed on the articles that redirect to the towardsdatascience page it doesn't grab the tags of the pages. The tag css selector is exactly the same as the other medium articles it grabs.

When I go onto the scrapy shell and try fetch one of the articles that links towardsdatascience article I get this response.

```<code>fetch("https://towardsdatascience.com/cython-a-speed-up-tool-for-your-python-function-9bab64364bfd?
source=tag_archive---------1-----------------------")

**OUTPUT**

2020-02-16 11:52:31 [scrapy_user_agents.middlewares] DEBUG: Assigned User-Agent Mozilla/5.0 (Windows
NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36

2020-02-16 11:52:31 [scrapy.downloadermiddlewares.redirect] DEBUG: Redirecting (302) to <GET
https://medium.com/m/global-identity?redirectUrl=https%3A%2F%2Ftowardsdatascience.com%2Fcython-a-
speed-up-tool-for-your-python-function-9bab64364bfd%3Fsource%3Dtag_archive---------1-----------------
------> from <GET https://towardsdatascience.com/cython-a-speed-up-tool-for-your-python-function-
9bab64364bfd?source=tag_archive---------1----------------------->

2020-02-16 11:52:31 [scrapy.downloadermiddlewares.robotstxt] DEBUG: Forbidden by robots.txt: <GET
https://medium.com/m/global-identity?redirectUrl=https%3A%2F%2Ftowardsdatascience.com%2Fcython-a-
speed-up-tool-for-your-python-function-9bab64364bfd%3Fsource%3Dtag_archive---------1-----------------
------>
</code>```

The robots.txt file is here

```<code>User-Agent: *
Disallow: /m/
Disallow: /me/
Disallow: /@me$
Disallow: /@me/
Disallow: /*/edit$
Disallow: /*/*/edit$
Disallow: /r/
Disallow: /t/
Disallow: /search?q$
Disallow: /search?q=
Allow: /_/
Allow: /_/api/users/*/meta
Allow: /_/api/users/*/profile/stream
Allow: /_/api/posts/*/responses
Allow: /_/api/posts/*/responsesStream
Allow: /_/api/posts/*/related
Sitemap: https://towardsdatascience.com/sitemap/sitemap.xml
</code>```

I've tried a few ways to work with redirects using scrapy from this website and not had any success. Here's the code for the actual crawler.

CODE

```<code> import scrapy
 from dateutil.parser import parse
 from medium.items import MediumItem
 from scrapy.spiders import CrawlSpider

 class DataSpider(CrawlSpider):

    name = 'data'
    allowed_domains = ['medium.com', 'towardsdatascience.com']
    start_urls = ['https://medium.com/tag/python/archive/2020/02/01']

    def parse(self,response):

    articles = response.xpath('//div[@class="postArticle postArticle--short js-postArticle js-
    trackPostPresentation js-trackPostScrolls"]')

    for article in articles:

        item = MediumItem()

        if article.css("div > h3::text").extract_first():
             item['Title'] = article.css("div > h3::text").extract_first()

             item['Name'] = article.xpath('.//a[@class="ds-link ds-link--styleSubtle link link--
             darken link--accent u-accentColor--textNormal u-accentColor--
             textDarken"]/text()').extract_first()

             item['Date'] = parse(article.css('time::text').extract_first()).date()

             item['Read'] = article.css("span::attr(title)").extract_first()

             item['Publication'] = article.xpath('.//a[@class="ds-link ds-link--styleSubtle link--
             darken link--accent u-accentColor--textNormal"]/text()').extract_first()

             item['Claps'] = articles.xpath('.//button[@class="button button--chromeless u-baseColor-
             -buttonNormal js-multirecommendCountButton u-
             disablePointerEvents"]/text()').extract_first()

             item['Responses'] = article.xpath('.//a[@class="button button--chromeless u-baseColor--
            buttonNormal"]/text()').extract_first()

             link = article.xpath('.//a[@class="button button--smaller button--chromeless u-
             baseColor--buttonNormal"]/@href').extract_first()

            yield response.follow(link, callback=self.get_link, meta={'item':item})

  def get_link(self,response):
        item = response.meta['item']
        item['Tags'] = response.css("ul > li > a::text").getall()
        yield item
</code>```

Any help to get the tags from those pages like the one linked would be great.

答:
Thanks to @furas comment. They have the correct answer, but I want the rep. :)</p>

```<code># settings.py

ROBOTSTXT_OBEY = False

</code>```

Title: Scrapy and redirection

Body:
So I've been working on building a web scraper with scrapy and being going through some data validation to make sure that all the items have been correctly grabbed.

I'm using it to grab medium data on articles title, names, claps, responses etc which are all on one html page. But to get the tags, I needed to go to each individual article. Most of the tags I've managed to get but there are a couple of articles which are linked to towardsdatascience.com instead of the medium website. It does a weird little redirect where the link to the article is say for example

https://towardsdatascience.com/cython-a-speed-up-tool-for-your-python-function-9bab64364bfd?source=tag_archive---------1-----------------------

It then redirects to: https://towardsdatascience.com/cython-a-speed-up-tool-for-your-python-function-9bab64364bfd

Now I've noticed on the articles that redirect to the towardsdatascience page it doesn't grab the tags of the pages. The tag css selector is exactly the same as the other medium articles it grabs.

When I go onto the scrapy shell and try fetch one of the articles that links towardsdatascience article I get this response.

fetch("https://towardsdatascience.com/cython-a-speed-up-tool-for-your-python-function-9bab64364bfd?
source=tag_archive---------1-----------------------")

**OUTPUT**

2020-02-16 11:52:31 [scrapy_user_agents.middlewares] DEBUG: Assigned User-Agent Mozilla/5.0 (Windows
NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36

2020-02-16 11:52:31 [scrapy.downloadermiddlewares.redirect] DEBUG: Redirecting (302) to <GET
https://medium.com/m/global-identity?redirectUrl=https%3A%2F%2Ftowardsdatascience.com%2Fcython-a-
speed-up-tool-for-your-python-function-9bab64364bfd%3Fsource%3Dtag_archive---------1-----------------
------> from <GET https://towardsdatascience.com/cython-a-speed-up-tool-for-your-python-function-
9bab64364bfd?source=tag_archive---------1----------------------->

2020-02-16 11:52:31 [scrapy.downloadermiddlewares.robotstxt] DEBUG: Forbidden by robots.txt: <GET
https://medium.com/m/global-identity?redirectUrl=https%3A%2F%2Ftowardsdatascience.com%2Fcython-a-
speed-up-tool-for-your-python-function-9bab64364bfd%3Fsource%3Dtag_archive---------1-----------------
------>

The robots.txt file is here

User-Agent: *
Disallow: /m/
Disallow: /me/
Disallow: /@me$
Disallow: /@me/
Disallow: /*/edit$
Disallow: /*/*/edit$
Disallow: /r/
Disallow: /t/
Disallow: /search?q$
Disallow: /search?q=
Allow: /_/
Allow: /_/api/users/*/meta
Allow: /_/api/users/*/profile/stream
Allow: /_/api/posts/*/responses
Allow: /_/api/posts/*/responsesStream
Allow: /_/api/posts/*/related
Sitemap: https://towardsdatascience.com/sitemap/sitemap.xml

I've tried a few ways to work with redirects using scrapy from this website and not had any success. Here's the code for the actual crawler.

CODE

 import scrapy
 from dateutil.parser import parse
 from medium.items import MediumItem
 from scrapy.spiders import CrawlSpider

 class DataSpider(CrawlSpider):

    name = 'data'
    allowed_domains = ['medium.com', 'towardsdatascience.com']
    start_urls = ['https://medium.com/tag/python/archive/2020/02/01']

    def parse(self,response):

    articles = response.xpath('//div[@class="postArticle postArticle--short js-postArticle js-
    trackPostPresentation js-trackPostScrolls"]')

    for article in articles:

        item = MediumItem()

        if article.css("div > h3::text").extract_first():
             item['Title'] = article.css("div > h3::text").extract_first()

             item['Name'] = article.xpath('.//a[@class="ds-link ds-link--styleSubtle link link--
             darken link--accent u-accentColor--textNormal u-accentColor--
             textDarken"]/text()').extract_first()

             item['Date'] = parse(article.css('time::text').extract_first()).date()

             item['Read'] = article.css("span::attr(title)").extract_first()

             item['Publication'] = article.xpath('.//a[@class="ds-link ds-link--styleSubtle link--
             darken link--accent u-accentColor--textNormal"]/text()').extract_first()

             item['Claps'] = articles.xpath('.//button[@class="button button--chromeless u-baseColor-
             -buttonNormal js-multirecommendCountButton u-
             disablePointerEvents"]/text()').extract_first()

             item['Responses'] = article.xpath('.//a[@class="button button--chromeless u-baseColor--
            buttonNormal"]/text()').extract_first()

             link = article.xpath('.//a[@class="button button--smaller button--chromeless u-
             baseColor--buttonNormal"]/@href').extract_first()

            yield response.follow(link, callback=self.get_link, meta={'item':item})

  def get_link(self,response):
        item = response.meta['item']
        item['Tags'] = response.css("ul > li > a::text").getall()
        yield item

Any help to get the tags from those pages like the one linked would be great.

Body:
Thanks to @furas comment. They have the correct answer, but I want the rep. :)

# settings.py

ROBOTSTXT_OBEY = False


问:
Thymeleaf Email template with table and link not giving proper result
I am trying to send an email using Thymeleaf template. My mail contain info in table form and in some cells I want link also. Below is my template and output. The a href tag is not giving proper result.

```<code><html xmlns:th='http://www.thymeleaf.org'>
    <head>
        <link href='http://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css' />
        <style type='text/css'> td, th { border: 1px solid black; } </style>
    </head>
    <body>
        <div class='container'>
            <p>Hi Team,</p>
            <p>Kindly find the details</p>
            <table class='table table-striped' align='center' border='0' cellpadding='0' cellspacing='0' width='1300' style='border-collapse: collapse;'>
                <tbody>
                    <tr>
                        <td bgcolor='#C0C0C0' align='center' style='width: 150px;'>
                            <b>Name</b>
                        </td>
                        <td bgcolor='#C0C0C0' align='center' style='width: 150px;'>
                            <b>Flavor</b>
                        </td>
                        <td bgcolor='#C0C0C0' align='center' style='width: 150px;'>
                            <b>OS</b>
                        </td>
                        <td bgcolor='#C0C0C0' align='center' style='width: 150px;'>
                            <b>Cus</b>
                        </td>
                        <td bgcolor='#C0C0C0' align='center' style='width: 150px;'>
                            <b>Loc</b>
                        </td>
                        <td bgcolor='#C0C0C0' align='center' style='width: 150px;'>
                            <b>Env</b>
                        </td>
                        <td bgcolor='#C0C0C0' align='center' style='width: 150px;'>
                            <b>Zone</b>
                        </td>
                        <td bgcolor='#C0C0C0' align='center' style='width: 150px;'>
                            <b>Date</b>
                        </td>
                        <td bgcolor='#C0C0C0' align='center' style='width: 150px;'>
                            <b>Status</b>
                        </td>
                    </tr>
                    <tr align='center' th:each='value : ${values}'>
                        <td align='center' style='width: 150px;' th:text='${value.vmName}'></td>
                        <td align='center' style='width: 150px;' th:text='${value.flavor}'></td>
                        <td align='center' style='width: 150px;' th:text='${value.os}'></td>
                        <td align='center' style='width: 150px;' th:text='${value.customerName}'></td>
                        <td align='center' style='width: 150px;' th:text='${value.location}'></td>
                        <td align='center' style='width: 150px;'>
                            <a href='${value.environmentURL}'>${value.environmentName}</a>
                        </td>
                        <td align='center' style='width: 150px;'>
                            <a href='${value.zoneURL}'>${value.zoneName}</a>
                        </td>
                        <td align='center' style='width: 150px;' th:text='${value.date}'></td>
                        <td align='center' style='width: 150px;' th:text='${value.status}'></td>
                    </tr>
                </tbody>
            </table>
            <p>With regards,</p>
            <p>Auto Notifier </p>
        </div>
    </body>
</html>
</code>```

The value for environmentURL, environmentName, zoneURL, zoneName is not coming properly. Please help where I am doing it wrong

答:
Two observations:

First:

You should use single-quotes and double-quotes carefully. Take a closer look at the Thymeleaf documentation, and you will see all the examples are like this:

```<code><div th:text="${value.zoneName}">
</code>```

Single quotes are for text literals:

```<code><div th:text="${'Your zone name is ' + value.zoneName}">
</code>```

Second:

Looking this example:

```<code><a href='${value.environmentURL}'>${value.environmentName}</a>
</code>```

This will display the literal value "${value.environmentName}" because that is what you have between the opening  and closing  tags.

Instead, you have to place your Thymeleaf directive in the tag as an attribute.

Also, your href element needs to be a Thymeleaf href element!

Cleaning it all up, we get this:

```<code><a th:href="${value.environmentURL}" th:text="${value.environmentName}"></a>
</code>```

Body:
I am trying to send an email using Thymeleaf template. My mail contain info in table form and in some cells I want link also. Below is my template and output. The a href tag is not giving proper result.

        <link href='http://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css' />

Hi Team,

Kindly find the details

                            Name

                            Flavor

                            OS

                            Cus

                            Loc

                            Env

                            Zone

                            Date

                            Status

                            ${value.environmentName}

                            ${value.zoneName}

With regards,

Auto Notifier

The value for environmentURL, environmentName, zoneURL, zoneName is not coming properly. Please help where I am doing it wrong

Body:
Two observations:

First:

You should use single-quotes and double-quotes carefully. Take a closer look at the Thymeleaf documentation, and you will see all the examples are like this:

<div th:text="${value.zoneName}">

Single quotes are for text literals:

<div th:text="${'Your zone name is ' + value.zoneName}">

Second:

Looking this example:

<a href='${value.environmentURL}'>${value.environmentName}</a>

This will display the literal value "${value.environmentName}" because that is what you have between the opening <a> and closing </a> tags.

Instead, you have to place your Thymeleaf directive in the tag as an attribute.

Also, your href element needs to be a Thymeleaf href element!

Cleaning it all up, we get this:

<a th:href="${value.environmentURL}" th:text="${value.environmentName}"></a>


问:
Return All Records through a Table Function When NULL Parameter is Passed
```<code>CREATE FUNCTION [dbo].[fn_actions]
(
  @roleid varchar(36)
)
RETURNS TABLE
AS
RETURN
  select *
  from actions
  where action_type_id in (
    select action_type_id
    from action_roles
    where role_id = isnull(@roleid,role_id)
  )
</code>```

The function above returns a list of actions from an actions_roles table that matches the @roleid parameter supplied.  However, there are some actions in the actions table that do not exist at all in the action_roles table.  So when a parameter of NULL is specified, I'd like the function to simply return

select * from actions

I tried using an if statement but that doesn't seem to work for inline table functions.

```<code>CREATE FUNCTION [dbo].[fn_actions]
(
  @roleid varchar(36)
)
RETURNS TABLE
AS
RETURN
  IF (@roleid is NULL)
  BEGIN
    select * from actions
  END
  ELSE
    select *
    from actions
    where action_type_id in (
      select action_type_id
      from action_roles
      where role_id = isnull(@roleid,role_id)
    )
</code>```

What would be the best way to achieve this?

答:
You could simply move the check on the nullity of the parameter to the outer query.

This should do what you want, while simplifying the query and possibly making it more efficient (this gives a change to the query planner to not execute the subquery when the parameter is null).

```<code>select *
from actions
where
    @roleid is null
    or action_type_id in (select action_type_id from action_roles)
</code>```

Note: as commented by Vladimir Baranov, you should probably add option(recompile) to this query (it goes at the very end), to force the database to recompute the query plan for each execution, so it can possibly optimize the subquery away when the parameter is null.

Body:
CREATE FUNCTION [dbo].[fn_actions]
(
  @roleid varchar(36)
)
RETURNS TABLE
AS
RETURN
  select *
  from actions
  where action_type_id in (
    select action_type_id
    from action_roles
    where role_id = isnull(@roleid,role_id)
  )

The function above returns a list of actions from an actions_roles table that matches the @roleid parameter supplied.  However, there are some actions in the actions table that do not exist at all in the action_roles table.  So when a parameter of NULL is specified, I'd like the function to simply return

select * from actions

I tried using an if statement but that doesn't seem to work for inline table functions.

CREATE FUNCTION [dbo].[fn_actions]
(
  @roleid varchar(36)
)
RETURNS TABLE
AS
RETURN
  IF (@roleid is NULL)
  BEGIN
    select * from actions
  END
  ELSE
    select *
    from actions
    where action_type_id in (
      select action_type_id
      from action_roles
      where role_id = isnull(@roleid,role_id)
    )

What would be the best way to achieve this?

Body:
You could simply move the check on the nullity of the parameter to the outer query.

This should do what you want, while simplifying the query and possibly making it more efficient (this gives a change to the query planner to not execute the subquery when the parameter is null).

select *
from actions
where
    @roleid is null
    or action_type_id in (select action_type_id from action_roles)

Note: as commented by Vladimir Baranov, you should probably add option(recompile) to this query (it goes at the very end), to force the database to recompute the query plan for each execution, so it can possibly optimize the subquery away when the parameter is null.


问:
How to restore files from recycle bin

Possible Duplicate:

  How do I restore a file from the recycle bin using C#?

Someone knows how to restore files from recycle bin using C# with the Windows API?.

答:
Take a look at this project over here : Codeproject

C# does Shell, Part 2 :

Title: How to restore files from recycle bin


问:
ON DUPLICATE KEY revert values to DEFAULT
I have a table with a primary/duplicate key - id (not autoincremented) with ~8 columns with default values for all.

```<code>+-------+----+------+
| id    |Col1| Col2 |
+-------+----+------+
| 1     | A  | B    |
+-------+----+------+
</code>```

When an INSERT with (id) is performed, and id is already present, I want to revert Col1 and Col2 back to the default values.

So far I managed:

```<code>INSERT INTO table (id)
    VALUES (1)
    ON DUPLICATE KEY UPDATE
         Col1 = DEFAULT(Col1), Col2 = DEFAULT(Col2);
</code>```

which I think should work.

Can this be achieved with triggers instead? (If so, how?)

Is there a keyword to automatically do this on all columns without writing them out? ,e.g. ON DUPLICATE KEY UPDATE ALL COLUMNS = DEFAULT(ALL COLUMNS)?

Edit: Sorry for stating the question "misleading"

答:
Sounds to me like you just want</p>

```<code>REPLACE INTO table (id)
VALUES (1)
</code>```

Body:
I have a table with a primary/duplicate key - id (not autoincremented) with ~8 columns with default values for all.

+-------+----+------+
| id    |Col1| Col2 |
+-------+----+------+
| 1     | A  | B    |
+-------+----+------+

When an INSERT with (id) is performed, and id is already present, I want to revert Col1 and Col2 back to the default values.

So far I managed:

INSERT INTO table (id)
    VALUES (1)
    ON DUPLICATE KEY UPDATE
         Col1 = DEFAULT(Col1), Col2 = DEFAULT(Col2);

which I think should work.

Can this be achieved with triggers instead? (If so, how?)

Is there a keyword to automatically do this on all columns without writing them out? ,e.g. ON DUPLICATE KEY UPDATE ALL COLUMNS = DEFAULT(ALL COLUMNS)?

Edit: Sorry for stating the question "misleading"

Body:
Sounds to me like you just want

REPLACE INTO table (id)
VALUES (1)


问:
Issues with NameSpace import in Xquery
Im trying have my namespace imported but for some reason it will not budge.
Ive tried this as well as adding the path

```<code>import schema namespace r = "http://www.w3.org/2001/XMLSchema" at "Assignment-Xquery3.xsd";
</code>```

I keep getting this error:

```<code>Error in schema http://www.w3.org/2001/XMLSchema: No valid schema was found
</code>```

I tired "-Instance" as well but to no luck. I am run Saxon EE. I have tried to add my file path. Im not sure whats wrong, This is the template that my teacher has provided us.

The rest of  my code if needed:

```<code>import schema namespace r = "http://www.w3.org/2001/XMLSchema" at "Assignment-Xquery3.xsd";
<provider>{
    for $r in
    distinc-values(doc("instance.xml")/r:patient/r:treatment/r:provider)
    return
        <info>
        <patient>{string($r)}</patient>
            {for $rr in doc("instance.xml"/r:patient
            where $r = $rr/r:treatment}
            return
                <treatment>
                    <id>{$rr/r:id/text()}</id>
                   <diagnosis>{$rr/r:diagnosis/text()}</diagnosis>
                   <drug>{$rr/r:drug/text()}</drug>
                </treatment>

        </info>
}</provider>
</code>```

答:
It's not very clear what you are trying to achieve, but it's very clear what you are doing wrong.

When you write

```<code>import schema namespace r = "http://www.w3.org/2001/XMLSchema" at "Assignment-Xquery3.xsd";
</code>```

you are

(a) trying to load a schema at the location "Assignment-Xquery3.xsd". That's probably OK; I dare say there is probably a valid schema at that location.

(b) asserting that the schema at that location has a target namespace of "http://www.w3.org/2001/XMLSchema". This seems highly unlikely, since user-written applications are very unlikely to want to access the schema for schema documents.

(c) binding the prefix "r" to that namespace. Again this seems implausible, (i) because the usual prefix that people use for that namespace is "xs" or "xsd", and (ii) because you go on to use the name r:treatment, and there's certainly no name in this namespace with local name "treatment".

I strongly suspect, though I can't be sure, that you don't really want to import a schema at all; you just want to bind the prefix "r" to some namespace (perhaps http://www.example.org/review, but we can't be sure). If that's the case, then you simply want

```<code>declare namespace r = "http://www.example.org/review";
</code>```

Title: Issues with NameSpace import in Xquery

Body:
Im trying have my namespace imported but for some reason it will not budge.
Ive tried this as well as adding the path

import schema namespace r = "http://www.w3.org/2001/XMLSchema" at "Assignment-Xquery3.xsd";

I keep getting this error:

Error in schema http://www.w3.org/2001/XMLSchema: No valid schema was found

I tired "-Instance" as well but to no luck. I am run Saxon EE. I have tried to add my file path. Im not sure whats wrong, This is the template that my teacher has provided us.

The rest of  my code if needed:

import schema namespace r = "http://www.w3.org/2001/XMLSchema" at "Assignment-Xquery3.xsd";
<provider>{
    for $r in
    distinc-values(doc("instance.xml")/r:patient/r:treatment/r:provider)
    return
        <info>
        <patient>{string($r)}</patient>
            {for $rr in doc("instance.xml"/r:patient
            where $r = $rr/r:treatment}
            return
                <treatment>
                    <id>{$rr/r:id/text()}</id>
                   <diagnosis>{$rr/r:diagnosis/text()}</diagnosis>
                   <drug>{$rr/r:drug/text()}</drug>
                </treatment>

        </info>
}</provider>

Body:
It's not very clear what you are trying to achieve, but it's very clear what you are doing wrong.

When you write

import schema namespace r = "http://www.w3.org/2001/XMLSchema" at "Assignment-Xquery3.xsd";

you are

(a) trying to load a schema at the location "Assignment-Xquery3.xsd". That's probably OK; I dare say there is probably a valid schema at that location.

(b) asserting that the schema at that location has a target namespace of "http://www.w3.org/2001/XMLSchema". This seems highly unlikely, since user-written applications are very unlikely to want to access the schema for schema documents.

(c) binding the prefix "r" to that namespace. Again this seems implausible, (i) because the usual prefix that people use for that namespace is "xs" or "xsd", and (ii) because you go on to use the name r:treatment, and there's certainly no name in this namespace with local name "treatment".

I strongly suspect, though I can't be sure, that you don't really want to import a schema at all; you just want to bind the prefix "r" to some namespace (perhaps http://www.example.org/review, but we can't be sure). If that's the case, then you simply want

declare namespace r = "http://www.example.org/review";


问:
Duplicate tensor name worked while it is not supposed to
```<code>def convolutional_block(X, f, filters, stage, block, s = 2):
    conv_name_base = 'res' + str(stage) + block + '_branch'
    bn_name_base = 'bn' + str(stage) + block + '_branch'

    F1, F2, F3 = filters

    X_shortcut = X

    X = Conv2D(F1, (1, 1), strides = (s,s), name = conv_name_base + '2a', padding='valid', kernel_initializer = glorot_uniform(seed=0))(X)
    X = BatchNormalization(axis = 3, name = bn_name_base + '2a')(X)
    X = Activation('relu')(X)

    X = Conv2D(F2, (f, f), strides = (1,1), name = conv_name_base + '2b', padding='same', kernel_initializer = glorot_uniform(seed=0))(X)
    X = BatchNormalization(axis = 3, name = bn_name_base + '2b')(X)
    X = Activation('relu')(X)

    X = Conv2D(F3, (1, 1), strides = (1,1), name = conv_name_base + '2c', padding='valid', kernel_initializer = glorot_uniform(seed=0))(X)
    X = BatchNormalization(axis = 3, name = bn_name_base + '2c')(X)      # <<<  X = BatchNormalization(axis = 3, name = bn_name_base + '2b')(X) also works!

    X_shortcut = Conv2D(F3, (1, 1), strides = (s,s), name = conv_name_base + '1', padding='valid', kernel_initializer = glorot_uniform(seed=0))(X_shortcut)
    X_shortcut = BatchNormalization(axis = 3, name = bn_name_base + '1')(X_shortcut)

    X = Add()([X, X_shortcut])
    X = Activation('relu')(X)

    return X

tf.reset_default_graph()

with tf.Session() as test:
    np.random.seed(1)
    A_prev = tf.placeholder("float", [3, 4, 4, 6])
    X = np.random.randn(3, 4, 4, 6)
    A = convolutional_block(A_prev, f = 2, filters = [2, 4, 6], stage = 1, block = 'a')
    test.run(tf.global_variables_initializer())
    out = test.run([A], feed_dict={A_prev: X, K.learning_phase(): 0})
    print("out = " + str(out[0][1][1][0]))
    print(tf.global_variables())
</code>```

I am amazed by the fact that this line X = BatchNormalization(axis = 3, name = bn_name_base + '2c')(X) can be replicable with X = BatchNormalization(axis = 3, name = bn_name_base + '2b')(X) and the code gives no error. I expected it to give the duplicated name error. Could anyone explain why it works. Thank you.

答:
Tensorflow/Keras has its own internal variable name resolution. So when you name two variables with the same name (i.e. x_b and x_b), the latter will be renamed to x_b_1.

For example, in your code, here are the variables with name 2b in it. This is after changing the lines,

```<code>X = Conv2D(F3, (1, 1), strides = (1,1), name = conv_name_base + '2c', padding='valid', kernel_initializer = glorot_uniform(seed=0))(X)
    X = BatchNormalization(axis = 3, name = bn_name_base + '2c')(X)
</code>```

to

```<code>X = Conv2D(F3, (1, 1), strides = (1,1), name = conv_name_base + '2b', padding='valid', kernel_initializer = glorot_uniform(seed=0))(X)
    X = BatchNormalization(axis = 3, name = bn_name_base + '2b')(X)      # <<<  X = BatchNormalization(axis = 3, name = bn_name_base + '2b')(X) also works!
</code>```

As you can see ther are a two sets of variables (postfixed with 2b and 2b_1)

```<code><tf.Variable 'res1a_branch2b/kernel:0' shape=(2, 2, 2, 4) dtype=float32>
<tf.Variable 'res1a_branch2b/bias:0' shape=(4,) dtype=float32>
<tf.Variable 'bn1a_branch2b/gamma:0' shape=(4,) dtype=float32>
<tf.Variable 'bn1a_branch2b/beta:0' shape=(4,) dtype=float32>
<tf.Variable 'bn1a_branch2b/moving_mean:0' shape=(4,) dtype=float32>
<tf.Variable 'bn1a_branch2b/moving_variance:0' shape=(4,) dtype=float32>
<tf.Variable 'res1a_branch2b_1/kernel:0' shape=(1, 1, 4, 6) dtype=float32>
<tf.Variable 'res1a_branch2b_1/bias:0' shape=(6,) dtype=float32>
<tf.Variable 'bn1a_branch2b_1/gamma:0' shape=(6,) dtype=float32>
<tf.Variable 'bn1a_branch2b_1/beta:0' shape=(6,) dtype=float32>
<tf.Variable 'bn1a_branch2b_1/moving_mean:0' shape=(6,) dtype=float32>
<tf.Variable 'bn1a_branch2b_1/moving_variance:0' shape=(6,) dtype=float32>
</code>```

Body:
def convolutional_block(X, f, filters, stage, block, s = 2):
    conv_name_base = 'res' + str(stage) + block + '_branch'
    bn_name_base = 'bn' + str(stage) + block + '_branch'

    F1, F2, F3 = filters

    X_shortcut = X

    X = Conv2D(F1, (1, 1), strides = (s,s), name = conv_name_base + '2a', padding='valid', kernel_initializer = glorot_uniform(seed=0))(X)
    X = BatchNormalization(axis = 3, name = bn_name_base + '2a')(X)
    X = Activation('relu')(X)

    X = Conv2D(F2, (f, f), strides = (1,1), name = conv_name_base + '2b', padding='same', kernel_initializer = glorot_uniform(seed=0))(X)
    X = BatchNormalization(axis = 3, name = bn_name_base + '2b')(X)
    X = Activation('relu')(X)

    X = Conv2D(F3, (1, 1), strides = (1,1), name = conv_name_base + '2c', padding='valid', kernel_initializer = glorot_uniform(seed=0))(X)
    X = BatchNormalization(axis = 3, name = bn_name_base + '2c')(X)      # <<<  X = BatchNormalization(axis = 3, name = bn_name_base + '2b')(X) also works!

    X_shortcut = Conv2D(F3, (1, 1), strides = (s,s), name = conv_name_base + '1', padding='valid', kernel_initializer = glorot_uniform(seed=0))(X_shortcut)
    X_shortcut = BatchNormalization(axis = 3, name = bn_name_base + '1')(X_shortcut)

    X = Add()([X, X_shortcut])
    X = Activation('relu')(X)

    return X

tf.reset_default_graph()

with tf.Session() as test:
    np.random.seed(1)
    A_prev = tf.placeholder("float", [3, 4, 4, 6])
    X = np.random.randn(3, 4, 4, 6)
    A = convolutional_block(A_prev, f = 2, filters = [2, 4, 6], stage = 1, block = 'a')
    test.run(tf.global_variables_initializer())
    out = test.run([A], feed_dict={A_prev: X, K.learning_phase(): 0})
    print("out = " + str(out[0][1][1][0]))
    print(tf.global_variables())

I am amazed by the fact that this line X = BatchNormalization(axis = 3, name = bn_name_base + '2c')(X) can be replicable with X = BatchNormalization(axis = 3, name = bn_name_base + '2b')(X) and the code gives no error. I expected it to give the duplicated name error. Could anyone explain why it works. Thank you.

Body:
Tensorflow/Keras has its own internal variable name resolution. So when you name two variables with the same name (i.e. x_b and x_b), the latter will be renamed to x_b_1.

For example, in your code, here are the variables with name 2b in it. This is after changing the lines,

X = Conv2D(F3, (1, 1), strides = (1,1), name = conv_name_base + '2c', padding='valid', kernel_initializer = glorot_uniform(seed=0))(X)
    X = BatchNormalization(axis = 3, name = bn_name_base + '2c')(X)

to

X = Conv2D(F3, (1, 1), strides = (1,1), name = conv_name_base + '2b', padding='valid', kernel_initializer = glorot_uniform(seed=0))(X)
    X = BatchNormalization(axis = 3, name = bn_name_base + '2b')(X)      # <<<  X = BatchNormalization(axis = 3, name = bn_name_base + '2b')(X) also works!

As you can see ther are a two sets of variables (postfixed with 2b and 2b_1)

<tf.Variable 'res1a_branch2b/kernel:0' shape=(2, 2, 2, 4) dtype=float32>
<tf.Variable 'res1a_branch2b/bias:0' shape=(4,) dtype=float32>
<tf.Variable 'bn1a_branch2b/gamma:0' shape=(4,) dtype=float32>
<tf.Variable 'bn1a_branch2b/beta:0' shape=(4,) dtype=float32>
<tf.Variable 'bn1a_branch2b/moving_mean:0' shape=(4,) dtype=float32>
<tf.Variable 'bn1a_branch2b/moving_variance:0' shape=(4,) dtype=float32>
<tf.Variable 'res1a_branch2b_1/kernel:0' shape=(1, 1, 4, 6) dtype=float32>
<tf.Variable 'res1a_branch2b_1/bias:0' shape=(6,) dtype=float32>
<tf.Variable 'bn1a_branch2b_1/gamma:0' shape=(6,) dtype=float32>
<tf.Variable 'bn1a_branch2b_1/beta:0' shape=(6,) dtype=float32>
<tf.Variable 'bn1a_branch2b_1/moving_mean:0' shape=(6,) dtype=float32>
<tf.Variable 'bn1a_branch2b_1/moving_variance:0' shape=(6,) dtype=float32>


问:
Java: How to @SuppressWarnings unreachable code?
Sometimes when you are debugging, you have unreachable code fragment. Is there anyway to suppress the warning?</p>

答:
The only way to do this on any compiler is @SuppressWarnings("all").

If you're using Eclipse, try @SuppressWarnings("unused").


问:
How to compare two sheets and delete/add any column with a distinct value in row 1? Google Script
I want to compare two sheets (based on header values in row 1) and delete any column with a unique value (without a match). For example, Assuming Sheet1, Row 1 data and Sheet 2, Row 1 are uniform, if a user adds/deletes a column within any sheet, I want to always match the number of columns in both sheets with their values

Screenshots of sheets headings.

IF both sheets looks like this

And a user adds a new Column N

Or delete column N

How can I ensure that both sheet matches by deleting the odd/distinct column in Sheet 1?

I have tried modifying this code below but I can't just get the unique one out. This code only look for headers with a defined value.

```<code>function deleteAloneColumns(){
  var sheet = SpreadsheetApp.getActiveSheet();
  var lastColumnPos = sheet.getLastColumn();
  var headers = sheet.getRange( 1 ,1, 1, lastColumnPos ).getValues()[0];
  for( var i = lastColumnPos ; i < 1; i--){
    if( headers[i] === "alone" ) sheet.deleteColumn(i);
  }
 SpreadsheetApp.getUi().alert( 'Job done!' );
}
</code>```

Any help to compare and delete the column with the unique value will be appreciated.

答:
Problem

Balancing sheets based on header row values mismatch.

Solution

If I understood you correctly, you have a source sheet against which validation is run and two primary use cases: user adds a new column named differently than any other column (if you want to check that the column strictly matches the one in sheet1, it is easy to modify) in source sheet or deletes one that should be there.

```<code>const balanceSheets = (sourceShName = 'Sheet1',targetShName = 'Sheet2') => {
  const ss = SpreadsheetApp.getActiveSpreadsheet();

  const s1 = ss.getSheetByName(sourceShName);
  const s2 = ss.getSheetByName(targetShName);

  const s2lcol = s2.getLastColumn();

  //keep all vals from source to reduce I/O
  const s1DataVals = s1.getDataRange().getValues();

  const s2Vals = s2.getRange(1, 1, 1, s2lcol).getValues();

  const h1Vals = s1DataVals[0];
  const h2Vals = s2Vals[0];

  //assume s1 is source (validation) sheet
  //assume s2 is target sheet that a user can edit

  //case 1: target has value not present in source -> delete column in target
  let colIdx = 0;
  h2Vals.forEach(value => {
    const isOK = h1Vals.some(val => val===value);

    isOK ? colIdx++ : s2.deleteColumn(colIdx+1);
  });

  //case 2: target does not have values present in source -> append column from source
  h1Vals.forEach((value,index) => {
    const isOK = h2Vals.some(val => val===value);
    !isOK && s2.insertColumnAfter(index);

    const valuesToInsert = s1DataVals.map(row => [row[index]]);

    const numRowsToInsert = valuesToInsert.length;

    s2.getRange(1,index+1, numRowsToInsert,1).setValues(valuesToInsert);
  });

};
</code>```

Showcase

Here is a small demo of how it works as a macros:

Notes

Solving your problem with two forEach is suboptimal, but I kept number of I/O low (it can be lowered further by, for example, moving deleteColum out of the loop while only keeping track of column indices).

The script uses ES6 capabilities provided by V8, so please, be careful (although I would recommend migrating as soon as possible - even if you encounter bugs / inconsistencies , it is worth more than it costs.

UPD made script more flexible by moving sheet names to parameter list.

UPD2 after discussing the issue with deleteColumn() behaviour, the answer is updated to keep column pointer in bounds (for those curious about it - forEach kept incrementing the index, while deleteColumn reduced bounds for any given index).

Reference

insertColumnAfter() method reference

Body:
I want to compare two sheets (based on header values in row 1) and delete any column with a unique value (without a match). For example, Assuming Sheet1, Row 1 data and Sheet 2, Row 1 are uniform, if a user adds/deletes a column within any sheet, I want to always match the number of columns in both sheets with their values

Screenshots of sheets headings.

IF both sheets looks like this

And a user adds a new Column N

Or delete column N

How can I ensure that both sheet matches by deleting the odd/distinct column in Sheet 1?

I have tried modifying this code below but I can't just get the unique one out. This code only look for headers with a defined value.

function deleteAloneColumns(){
  var sheet = SpreadsheetApp.getActiveSheet();
  var lastColumnPos = sheet.getLastColumn();
  var headers = sheet.getRange( 1 ,1, 1, lastColumnPos ).getValues()[0];
  for( var i = lastColumnPos ; i < 1; i--){
    if( headers[i] === "alone" ) sheet.deleteColumn(i);
  }
 SpreadsheetApp.getUi().alert( 'Job done!' );
}

Any help to compare and delete the column with the unique value will be appreciated.

Body:
Problem

Balancing sheets based on header row values mismatch.

Solution

If I understood you correctly, you have a source sheet against which validation is run and two primary use cases: user adds a new column named differently than any other column (if you want to check that the column strictly matches the one in sheet1, it is easy to modify) in source sheet or deletes one that should be there.

const balanceSheets = (sourceShName = 'Sheet1',targetShName = 'Sheet2') => {
  const ss = SpreadsheetApp.getActiveSpreadsheet();

  const s1 = ss.getSheetByName(sourceShName);
  const s2 = ss.getSheetByName(targetShName);

  const s2lcol = s2.getLastColumn();

  //keep all vals from source to reduce I/O
  const s1DataVals = s1.getDataRange().getValues();

  const s2Vals = s2.getRange(1, 1, 1, s2lcol).getValues();

  const h1Vals = s1DataVals[0];
  const h2Vals = s2Vals[0];

  //assume s1 is source (validation) sheet
  //assume s2 is target sheet that a user can edit

  //case 1: target has value not present in source -> delete column in target
  let colIdx = 0;
  h2Vals.forEach(value => {
    const isOK = h1Vals.some(val => val===value);

    isOK ? colIdx++ : s2.deleteColumn(colIdx+1);
  });

  //case 2: target does not have values present in source -> append column from source
  h1Vals.forEach((value,index) => {
    const isOK = h2Vals.some(val => val===value);
    !isOK && s2.insertColumnAfter(index);

    const valuesToInsert = s1DataVals.map(row => [row[index]]);

    const numRowsToInsert = valuesToInsert.length;

    s2.getRange(1,index+1, numRowsToInsert,1).setValues(valuesToInsert);
  });

};

Showcase

Here is a small demo of how it works as a macros:

Notes

Solving your problem with two forEach is suboptimal, but I kept number of I/O low (it can be lowered further by, for example, moving deleteColum out of the loop while only keeping track of column indices).

The script uses ES6 capabilities provided by V8, so please, be careful (although I would recommend migrating as soon as possible - even if you encounter bugs / inconsistencies , it is worth more than it costs.

UPD made script more flexible by moving sheet names to parameter list.

UPD2 after discussing the issue with deleteColumn() behaviour, the answer is updated to keep column pointer in bounds (for those curious about it - forEach kept incrementing the index, while deleteColumn reduced bounds for any given index).

Reference

insertColumnAfter() method reference


问:
Applying homography to image
I am stuck at this homography problem.
I have to apply homography and then 2d bilinear interpolation to render a image so that I see a birds eye view.

I successfully computed the homography(I guess). I am unable to figure out how to apply this homography matrix to the source image to generate output image over blank 940x500 image.

Here is my code so far:

```<code>I = imread('image.png');
imshow(I)

% Mark more than 4 input points
[x,y] = getpts

xp = [0; 720; 720; 0;];
yp = [0; 0; 1280; 1280;];

for i=1:4
    A(2*i-1,:) = [x(i), y(i), 1, 0, 0, 0, -x(i)*xp(i), -xp(i)*y(i), -xp(i)];
    A(2*i,:) = [0, 0, 0, x(i), y(i), 1, -x(i)*yp(i), -yp(i)*y(i), -yp(i)];
end

[U,S,V] = svd(A);
h = V(:,9);

H = reshape(h,3,3);
</code>```

How do I apply this H matrix to the source image?

答:
You can use projective2d and imwarp:

```<code>tform = projective2d(H);
outputImage = imwarp(I, tform);
</code>```

I don't understand the example you gave, so I can't say if you need to invert H.

It could be that my answer is wrong - I can't execute your code sample for verifying the solution.

Please let me know if it solves your problem.

Title: Applying homography to image

Body:
I am stuck at this homography problem.
I have to apply homography and then 2d bilinear interpolation to render a image so that I see a birds eye view.

I successfully computed the homography(I guess). I am unable to figure out how to apply this homography matrix to the source image to generate output image over blank 940x500 image.

Here is my code so far:

I = imread('image.png');
imshow(I)

% Mark more than 4 input points
[x,y] = getpts

xp = [0; 720; 720; 0;];
yp = [0; 0; 1280; 1280;];

for i=1:4
    A(2*i-1,:) = [x(i), y(i), 1, 0, 0, 0, -x(i)*xp(i), -xp(i)*y(i), -xp(i)];
    A(2*i,:) = [0, 0, 0, x(i), y(i), 1, -x(i)*yp(i), -yp(i)*y(i), -yp(i)];
end

[U,S,V] = svd(A);
h = V(:,9);

H = reshape(h,3,3);

How do I apply this H matrix to the source image?

Body:
You can use projective2d and imwarp:

tform = projective2d(H);
outputImage = imwarp(I, tform);

I don't understand the example you gave, so I can't say if you need to invert H.

It could be that my answer is wrong - I can't execute your code sample for verifying the solution.

Please let me know if it solves your problem.


问:
javascript - call sync function as async
I want to call a sync function as async without making the function itself async. So what I'm basically trying to do is this: ("asynccall" is pseudocode for something calling the function as async)

asynccall doSomething(a, b, c);

function doSomething(a, b, c) {
   //doing something
}
```

<p>the closest I got to doing that is by creating an async function which calls the sync funtion:</p>

<pre class="lang-js prettyprint-override"><code>aDoSomething(a, b, c);

async function aDoSomething(a, b, c) {
   doSomething(a, b, c);
}

function doSomething(a, b, c) {
   //doing something
}
</code>```

which does work, but I don't want to create this redundant function. Is there a way to achieve what's done in example 2 in a way that looks like example 1?

答:
Wrapping your doSomething function in an async function does nothing more. If it fits your needs, then so will doSomething(a, b, c);

The asynchronous operation that you do in doSomething will not block the execution flow, the rest of your code will execute as soon as doSomething returns something, which should happen as soon as the asynchronous task has been queued.

Body:
I want to call a sync function as async without making the function itself async. So what I'm basically trying to do is this: ("asynccall" is pseudocode for something calling the function as async)

asynccall doSomething(a, b, c);

function doSomething(a, b, c) {
   //doing something
}

the closest I got to doing that is by creating an async function which calls the sync funtion:

aDoSomething(a, b, c);

async function aDoSomething(a, b, c) {
   doSomething(a, b, c);
}

function doSomething(a, b, c) {
   //doing something
}

which does work, but I don't want to create this redundant function. Is there a way to achieve what's done in example 2 in a way that looks like example 1?