问:
How to remove colon from the pie chart - Amcharts?
I just wan to remove the color from the pie chart. Please find the reference in the attachment.

答:
You can modify the labelText property to customize the label. By default it's set to "[[title]]: [[percents]]%", so changing it to "[[percents]]%" will get what you want.

```<code>var chart = AmCharts.makeChart("chartdiv", {
  // ...
  "labelText": "[[percents]]%",
  // ...
});
</code>```

Demo below:

var chart = AmCharts.makeChart( "chartdiv", {
  "type": "pie",
  "theme": "light",
  "labelText": "[[percents]]%",
  "dataProvider": [ {
    "country": "Lithuania",
    "litres": 501.9
  }, {
    "country": "Czech Republic",
    "litres": 301.9
  }, {
    "country": "Ireland",
    "litres": 201.1
  }, {
    "country": "Germany",
    "litres": 165.8
  }, {
    "country": "Australia",
    "litres": 139.9
  }, {
    "country": "Austria",
    "litres": 128.3
  }, {
    "country": "UK",
    "litres": 99
  }, {
    "country": "Belgium",
    "litres": 60
  }, {
    "country": "The Netherlands",
    "litres": 50
  } ],
  "valueField": "litres",
  "titleField": "country",
   "balloon":{
   "fixedPosition":true
  },
  "export": {
    "enabled": true
  }
} );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" src="//www.amcharts.com/lib/3/amcharts.js"></script>
<script type="text/javascript" src="//www.amcharts.com/lib/3/pie.js"></script>
<script type="text/javascript" src="//www.amcharts.com/lib/3/themes/light.js"></script>
<div id="chartdiv" style="width: 100%; height: 400px;"></div></code>```

Body:
You can modify the labelText property to customize the label. By default it's set to "[[title]]: [[percents]]%", so changing it to "[[percents]]%" will get what you want.

var chart = AmCharts.makeChart("chartdiv", {
  // ...
  "labelText": "[[percents]]%",
  // ...
});

Demo below:

var chart = AmCharts.makeChart( "chartdiv", {
  "type": "pie",
  "theme": "light",
  "labelText": "[[percents]]%",
  "dataProvider": [ {
    "country": "Lithuania",
    "litres": 501.9
  }, {
    "country": "Czech Republic",
    "litres": 301.9
  }, {
    "country": "Ireland",
    "litres": 201.1
  }, {
    "country": "Germany",
    "litres": 165.8
  }, {
    "country": "Australia",
    "litres": 139.9
  }, {
    "country": "Austria",
    "litres": 128.3
  }, {
    "country": "UK",
    "litres": 99
  }, {
    "country": "Belgium",
    "litres": 60
  }, {
    "country": "The Netherlands",
    "litres": 50
  } ],
  "valueField": "litres",
  "titleField": "country",
   "balloon":{
   "fixedPosition":true
  },
  "export": {
    "enabled": true
  }
} );

<script type="text/javascript" src="//www.amcharts.com/lib/3/amcharts.js"></script>
<script type="text/javascript" src="//www.amcharts.com/lib/3/pie.js"></script>
<script type="text/javascript" src="//www.amcharts.com/lib/3/themes/light.js"></script>
<div id="chartdiv" style="width: 100%; height: 400px;"></div>


来源: stackexchange

问:
lateinit modifier is not allowed on primitive type properties in Kotlin
I am defining like a instance variable in kotlin and want to initialize it onCreate method of an activity.

```<code>var count: Int
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    count.inc()
}
</code>```

Here I am getting a below error on count variable.

Property must be initialized or be abstract in Kotlin

Well, I read this thread Property must be initialized or be abstract and tried same but again I am getting a below error.

lateinit modifier is not allowed on primitive type properties

```<code>lateinit var count: Int
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    count.inc()
}
</code>```

Is there any way to do this in Kotlin ?

答:
There's no reason to leave it uninitialized. Just initialize it to 0 or -1.

lateinit is for non-null object references that can't easily be initialized in the class body definition.

ContentLicense: CC BY-SA 3.0

Body:
I am defining like a instance variable in kotlin and want to initialize it onCreate method of an activity.

var count: Int
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    count.inc()
}

Here I am getting a below error on count variable.

Property must be initialized or be abstract in Kotlin

Well, I read this thread Property must be initialized or be abstract and tried same but again I am getting a below error.

lateinit modifier is not allowed on primitive type properties

lateinit var count: Int
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    count.inc()
}

Is there any way to do this in Kotlin ?


问:
Code igniter code for connect Remote Mysql DB from Localhost
i am try to access all remote server mysql data from my localhost. but i don't know how to connect remote database server my  local database.
and my local database connection code is</p>

```<code>$db['on_app']['hostname'] = 'host ip address';
$db['on_app']['username'] = 'host username';
$db['on_app']['password'] = 'host password';
$db['on_app']['database'] = 'host db name';
$db['on_app']['dbdriver'] = 'mysql'`enter code here`;
$db['on_app']['dbprefix'] = '';
$db['on_app']['pconnect'] = TRUE;
$db['on_app']['db_debug'] = FALSE;

$db['on_app']['cache_on'] = FALSE;
$db['on_app']['cachedir'] = '';
$db['on_app']['char_set'] = 'utf8';
$db['on_app']['dbcollat'] = 'utf8_general_ci';
$db['on_app']['swap_pre'] = '';
$db['on_app']['autoinit'] = TRUE;
$db['on_app']['stricton'] = FALSE;
</code>```

答:
In the database.php file under the application->config folder edit the default connection with your details

```<code>$db['default'] = array(
'dsn'   => '',
'hostname' => 'your.server.ip.address',
'username' => 'yourserverusername',
'password' => 'your_db_password',
'database' => 'your_db_name',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
</code>```

you will have to create a user on your server and open the database to either all ips or whichever ips you wish

Body:
i am try to access all remote server mysql data from my localhost. but i don't know how to connect remote database server my  local database.
and my local database connection code is

$db['on_app']['hostname'] = 'host ip address';
$db['on_app']['username'] = 'host username';
$db['on_app']['password'] = 'host password';
$db['on_app']['database'] = 'host db name';
$db['on_app']['dbdriver'] = 'mysql'`enter code here`;
$db['on_app']['dbprefix'] = '';
$db['on_app']['pconnect'] = TRUE;
$db['on_app']['db_debug'] = FALSE;

$db['on_app']['cache_on'] = FALSE;
$db['on_app']['cachedir'] = '';
$db['on_app']['char_set'] = 'utf8';
$db['on_app']['dbcollat'] = 'utf8_general_ci';
$db['on_app']['swap_pre'] = '';
$db['on_app']['autoinit'] = TRUE;
$db['on_app']['stricton'] = FALSE;

Body:
In the database.php file under the application->config folder edit the default connection with your details

$db['default'] = array(
'dsn'   => '',
'hostname' => 'your.server.ip.address',
'username' => 'yourserverusername',
'password' => 'your_db_password',
'database' => 'your_db_name',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);

you will have to create a user on your server and open the database to either all ips or whichever ips you wish


问:
How to amalgamate 2 Clearcase Servers which each have an ADMIN Pvob
We have a need to amalgamate 2 clearcase servers with everything then residing on one of them.

Clearcase Version 7.1.2.6 FL5 & Schema 54

Both instances have their own Admin PVOB.

How do we move and amalgamate the PVOBS or reestablish the correct links once the vobs are moved?

Is this possible?

答:
It depends if the servers have the same architecture or not.

The general idea is to follow the Administration Guide (for CC 7.1.2) describing how to move VOB (and PVob) from one server to another.

The different scenario are described here.


问:
Symfony 3 - Doctrine wrong query structure - multi tables
I have a problem with Doctrine woring in my Symfony project.
That's my code:

```<code>use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Doctrine\Common\Persistence\ObjectManager;
use Factory\MainBundle\Entity\Lastauction;
use Factory\MainBundle\Entity\Offers;

class AuctionListController extends Controller
{
    private $em;
    private $qb;
    private $offer;

    public function getAuctionListAction()
    {
        $this->em = $this->getDoctrine()->getEntityManager();
        $this->qb = $this->em->createQueryBuilder();
        getAllAccount();
        for($offset=0; $offset<20000; $offset++)
        {
            $this->insertOffers();
        }
        return new Response('Offers list generated');
    }

    private function getAllAccount()
    {
        $this->qb->select('ac.mail')
            ->from('FactoryMainBundle:Account', 'ac');
        $result = $this->qb->getQuery()->getResult();
        $this->accounts = array_column($result, 'mail');
    }

    private function insertOffers()
    {
        foreach($this->offers as $id => $offer)
        {
            if($this->checkIfExsistOffer($offer))
            {
                echo $offer .'<br>';
                $offerObj = new Offers();
                $offerObj->setOffer($offer);
                $offerObj->setPage(2);
                $this->em = $this->getDoctrine()->getManager();
                $this->em->persist($offerObj);
                if (($id % $this->batchSize) == 0)
                {
                    $this->em->flush();
                    $this->em->clear();
                }
            }
        }
        $this->em->flush();
        $this->em->clear();
        $this->offers = array();
    }

    private function checkIfExsistOffer($offerUrl)
    {
        $this->qb->select('o.id')
            ->from('FactoryMainBundle:Offers', 'o')
            ->where("o.offer=:offer")
            ->setParameter('offer', $offerUrl);
        $result = $this->qb->getQuery()->getResult();
        return (isset($result['0']['id'])) ? 1 : 0;
    }

}
</code>```

And I get this error:

[Semantical Error] line 0, col 134 near 'o WHERE o.of': Error: 'o' is already defined.

[2/2] QueryException: [Semantical Error] line 0, col 134 near 'o WHERE o.of': Error: 'o' is already defined.

  [1/2] QueryException: SELECT o.id FROM FactoryMainBundle:Account ac, FactoryMainBundle:Lastauction la, FactoryMainBundle:Offers o, FactoryMainBundle:Offers o WHERE o.offer='123'

Why Doctrine takes tables from other queries?

答:
```<code>$this->qb->select('o.id')
        ->from('FactoryMainBundle:Offers', 'o')
        ->where("o.offer=:offer")
        ->setParameter('offer', $offerUrl);
    $result = $this->qb->getQuery()->getResult();
</code>```

Body:
I have a problem with Doctrine woring in my Symfony project.
That's my code:

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Doctrine\Common\Persistence\ObjectManager;
use Factory\MainBundle\Entity\Lastauction;
use Factory\MainBundle\Entity\Offers;

class AuctionListController extends Controller
{
    private $em;
    private $qb;
    private $offer;

    public function getAuctionListAction()
    {
        $this->em = $this->getDoctrine()->getEntityManager();
        $this->qb = $this->em->createQueryBuilder();
        getAllAccount();
        for($offset=0; $offset<20000; $offset++)
        {
            $this->insertOffers();
        }
        return new Response('Offers list generated');
    }

    private function getAllAccount()
    {
        $this->qb->select('ac.mail')
            ->from('FactoryMainBundle:Account', 'ac');
        $result = $this->qb->getQuery()->getResult();
        $this->accounts = array_column($result, 'mail');
    }

    private function insertOffers()
    {
        foreach($this->offers as $id => $offer)
        {
            if($this->checkIfExsistOffer($offer))
            {
                echo $offer .'
';
                $offerObj = new Offers();
                $offerObj->setOffer($offer);
                $offerObj->setPage(2);
                $this->em = $this->getDoctrine()->getManager();
                $this->em->persist($offerObj);
                if (($id % $this->batchSize) == 0)
                {
                    $this->em->flush();
                    $this->em->clear();
                }
            }
        }
        $this->em->flush();
        $this->em->clear();
        $this->offers = array();
    }

    private function checkIfExsistOffer($offerUrl)
    {
        $this->qb->select('o.id')
            ->from('FactoryMainBundle:Offers', 'o')
            ->where("o.offer=:offer")
            ->setParameter('offer', $offerUrl);
        $result = $this->qb->getQuery()->getResult();
        return (isset($result['0']['id'])) ? 1 : 0;
    }

}

And I get this error:

[Semantical Error] line 0, col 134 near 'o WHERE o.of': Error: 'o' is already defined.

[2/2] QueryException: [Semantical Error] line 0, col 134 near 'o WHERE o.of': Error: 'o' is already defined.

  [1/2] QueryException: SELECT o.id FROM FactoryMainBundle:Account ac, FactoryMainBundle:Lastauction la, FactoryMainBundle:Offers o, FactoryMainBundle:Offers o WHERE o.offer='123'

Why Doctrine takes tables from other queries?


问:
Generate and stream compressed file with Flask
I am able to generate and stream text on the fly, but unable to generate and stream a compressed file on the fly.

```<code>from flask import Flask, request, Response,stream_with_context
import zlib
import gzip

app = Flask(__name__)

def generate_text():
    for x in range(10000):
        yield f"this is my line: {x}\n".encode()

@app.route('/stream_text')
def stream_text():
    response = Response(stream_with_context(generate_text()))
    return response

def generate_zip():
    for x in range(10000):
        yield zlib.compress(f"this is my line: {x}\n".encode())

@app.route('/stream_zip')
def stream_zip():
    response = Response(stream_with_context(generate_zip()), mimetype='application/zip')
    response.headers['Content-Disposition'] = 'attachment; filename=data.gz'
    return response

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000, debug=True)
</code>```

Than using curl and gunzip:

```<code>curl http://127.0.0.1:8000/stream_zip > data.gz

gunzip data.gz
gunzip: data.gz: not in gzip format
</code>```

I don't care if it is zip, gzip, or any other type of compression.

generate_text in my real code generates over 4 GB of data so I would like to compress on the fly.

Saving text to file, zipping, returning zip file, and than deleting is not the solution I'm after.

I need to be in a loop generating some text -> compress that text -> streaming compressed data until I'm done.

zip/gzip ... anything is fine as long as it works.

答:
You are yielding a series of compressed documents, not a single compressed stream. Don't use zlib.compress(), it includes the header and forms a single document.

You need to create a zlib.compressobj() object instead, and use the Compress.compress() method on that object to produce a stream of data (followed by a final call to Compress.flush()):

```<code>def generate_zip():
    compressor = zlib.compressobj()
    for x in range(10000):
        chunk = compressor.compress(f"this is my line: {x}\n".encode())
        if chunk:
            yield chunk
    yield compressor.flush()
</code>```

The compressor can produce empty blocks when there is not enough data yet to produce a full compressed-data chunk, the above only yields if there is actually anything to send. Because your input data is so highly repetitive and thus the data can be efficiently compressed, this yields only 3 times (once with 2-byte header, once with about 21kb of compressed data covering the first 8288 iterations over range(), and finally with the remaining 4kb for the rest of the loop).

In aggregate, this produces the same data as a single zlib.compress() call with all inputs concatenated. The correct mime-type for this data format is application/zlib, not application/zip.

This format is not readily decompressible with gzip however, not without some trickery. That's because the above doesn't yet produce a GZIP file, it just produces a raw zlib-compressed stream. To make it GZIP compatible, you need to configure the compression correctly, send a header first, and add a CRC checksum and data length value at the end:

```<code>import zlib
import struct
import time

def generate_gzip():
    # Yield a gzip file header first.
    yield bytes([
        0x1F, 0x8B, 0x08, 0x00,  # Gzip file, deflate, no filename
        *struct.pack('<L', int(time.time())),  # compression start time
        0x02, 0xFF,  # maximum compression, no OS specified
    ])

    # bookkeeping: the compression state, running CRC and total length
    compressor = zlib.compressobj(
        9, zlib.DEFLATED, -zlib.MAX_WBITS, zlib.DEF_MEM_LEVEL, 0)
    crc = zlib.crc32(b"")
    length = 0

    for x in range(10000):
        data = f"this is my line: {x}\n".encode()
        chunk = compressor.compress(data)
        if chunk:
            yield chunk
        crc = zlib.crc32(data, crc) & 0xFFFFFFFF
        length += len(data)

    # Finishing off, send remainder of the compressed data, and CRC and length
    yield compressor.flush()
    yield struct.pack("<2L", crc, length & 0xFFFFFFFF)
</code>```

Serve this as application/gzip:

```<code>@app.route('/stream_gzip')
def stream_gzip():
    response = Response(stream_with_context(generate_gzip()), mimetype='application/gzip')
    response.headers['Content-Disposition'] = 'attachment; filename=data.gz'
    return response
</code>```

and the result can be decompressed on the fly:

```<code>curl http://127.0.0.1:8000/stream_gzip | gunzip -c | less
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am able to generate and stream text on the fly, but unable to generate and stream a compressed file on the fly.

from flask import Flask, request, Response,stream_with_context
import zlib
import gzip

app = Flask(__name__)

def generate_text():
    for x in range(10000):
        yield f"this is my line: {x}\n".encode()

@app.route('/stream_text')
def stream_text():
    response = Response(stream_with_context(generate_text()))
    return response

def generate_zip():
    for x in range(10000):
        yield zlib.compress(f"this is my line: {x}\n".encode())

@app.route('/stream_zip')
def stream_zip():
    response = Response(stream_with_context(generate_zip()), mimetype='application/zip')
    response.headers['Content-Disposition'] = 'attachment; filename=data.gz'
    return response

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000, debug=True)

Than using curl and gunzip:

curl http://127.0.0.1:8000/stream_zip > data.gz

gunzip data.gz
gunzip: data.gz: not in gzip format

I don't care if it is zip, gzip, or any other type of compression.

generate_text in my real code generates over 4 GB of data so I would like to compress on the fly.

Saving text to file, zipping, returning zip file, and than deleting is not the solution I'm after.

I need to be in a loop generating some text -> compress that text -> streaming compressed data until I'm done.

zip/gzip ... anything is fine as long as it works.

Body:
You are yielding a series of compressed documents, not a single compressed stream. Don't use zlib.compress(), it includes the header and forms a single document.

You need to create a zlib.compressobj() object instead, and use the Compress.compress() method on that object to produce a stream of data (followed by a final call to Compress.flush()):

def generate_zip():
    compressor = zlib.compressobj()
    for x in range(10000):
        chunk = compressor.compress(f"this is my line: {x}\n".encode())
        if chunk:
            yield chunk
    yield compressor.flush()

The compressor can produce empty blocks when there is not enough data yet to produce a full compressed-data chunk, the above only yields if there is actually anything to send. Because your input data is so highly repetitive and thus the data can be efficiently compressed, this yields only 3 times (once with 2-byte header, once with about 21kb of compressed data covering the first 8288 iterations over range(), and finally with the remaining 4kb for the rest of the loop).

In aggregate, this produces the same data as a single zlib.compress() call with all inputs concatenated. The correct mime-type for this data format is application/zlib, not application/zip.

This format is not readily decompressible with gzip however, not without some trickery. That's because the above doesn't yet produce a GZIP file, it just produces a raw zlib-compressed stream. To make it GZIP compatible, you need to configure the compression correctly, send a header first, and add a CRC checksum and data length value at the end:

import zlib
import struct
import time

def generate_gzip():
    # Yield a gzip file header first.
    yield bytes([
        0x1F, 0x8B, 0x08, 0x00,  # Gzip file, deflate, no filename
        *struct.pack('<L', int(time.time())),  # compression start time
        0x02, 0xFF,  # maximum compression, no OS specified
    ])

    # bookkeeping: the compression state, running CRC and total length
    compressor = zlib.compressobj(
        9, zlib.DEFLATED, -zlib.MAX_WBITS, zlib.DEF_MEM_LEVEL, 0)
    crc = zlib.crc32(b"")
    length = 0

    for x in range(10000):
        data = f"this is my line: {x}\n".encode()
        chunk = compressor.compress(data)
        if chunk:
            yield chunk
        crc = zlib.crc32(data, crc) & 0xFFFFFFFF
        length += len(data)

    # Finishing off, send remainder of the compressed data, and CRC and length
    yield compressor.flush()
    yield struct.pack("<2L", crc, length & 0xFFFFFFFF)

Serve this as application/gzip:

@app.route('/stream_gzip')
def stream_gzip():
    response = Response(stream_with_context(generate_gzip()), mimetype='application/gzip')
    response.headers['Content-Disposition'] = 'attachment; filename=data.gz'
    return response

and the result can be decompressed on the fly:

curl http://127.0.0.1:8000/stream_gzip | gunzip -c | less


问:
Using multiple values for the same param in a multipart's PartMap request with Retrofit 2
I want to send multiple values of the same param in a multipart query. Here is my code:

Interface:

```<code>@Multipart
@POST("user")
Observable<Void> updateUser(@PartMap() Map<String, RequestBody> partMap, @Part MultipartBody.Part photo);
</code>```

This request allow me to update a user with a new picture and some parameters. In the parameters I can specify the user's skills with a parameter named "skills[]". To specify the parameters that can vary in number I use a HashMap; however with a HashMap I cannot specify multiple parameters using the same name.

i.e. I cannot do:

```<code>for(Integer skill : skills) {
    RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), skill.toString());
    map.put("skills[]", body);
}
</code>```

Because the map will only accept one value of the same key.

How can I specify multiple values of a parameter. I have no problem doing it using Postman to test the request.

I tried to use a HashMap<String, List<RequestBody>> instead:

```<code>List<RequestBody> bodies = new ArrayList<>();
for(Integer skill : skills) {
    RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), skill.toString());
    bodies.add(body);
}
map.put("skills[]", bodies);
</code>```

but it seems that it's not supported. The query created contains null values for the request bodies:

```<code>Content-Disposition: form-data; name="skills[]"
Content-Transfer-Encoding: binary
Content-Type: application/json; charset=UTF-8
Content-Length: 16

[null,null,null]
</code>```

答:
Use this to create text RequestBody objects:

```<code>  RequestBody userPhone = RequestBody.create(MediaType.parse("text/plain"), phoneNumber);
  RequestBody userEmail = RequestBody.create(MediaType.parse("text/plain"), email);
</code>```

Hope this helps.

Body:
I want to send multiple values of the same param in a multipart query. Here is my code:

Interface:

@Multipart
@POST("user")
Observable<Void> updateUser(@PartMap() Map<String, RequestBody> partMap, @Part MultipartBody.Part photo);

This request allow me to update a user with a new picture and some parameters. In the parameters I can specify the user's skills with a parameter named "skills[]". To specify the parameters that can vary in number I use a HashMap; however with a HashMap I cannot specify multiple parameters using the same name.

i.e. I cannot do:

for(Integer skill : skills) {
    RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), skill.toString());
    map.put("skills[]", body);
}

Because the map will only accept one value of the same key.

How can I specify multiple values of a parameter. I have no problem doing it using Postman to test the request.

I tried to use a HashMap<String, List<RequestBody>> instead:

List<RequestBody> bodies = new ArrayList<>();
for(Integer skill : skills) {
    RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), skill.toString());
    bodies.add(body);
}
map.put("skills[]", bodies);

but it seems that it's not supported. The query created contains null values for the request bodies:

Content-Disposition: form-data; name="skills[]"
Content-Transfer-Encoding: binary
Content-Type: application/json; charset=UTF-8
Content-Length: 16

[null,null,null]

Body:
Use this to create text RequestBody objects:

  RequestBody userPhone = RequestBody.create(MediaType.parse("text/plain"), phoneNumber);
  RequestBody userEmail = RequestBody.create(MediaType.parse("text/plain"), email);

Hope this helps.


问:
Three js curved (bend) CSS3DObject
I am trying to bend a three js CSS3DObject:

```<code>var element = document.createElement('iframe');
element.src = 'https://example.com/';
var cssObject = new THREE.CSS3DObject( element );
</code>```

but I cannot use the bend modifier on it, like I do on other meshes, e.g.:

```<code>var dir = new THREE.Vector3( 0, 0, -1 );
var ax =  new THREE.Vector3( 0, 1, 0 );
var ang = Math.PI / 4;
modifier.set( dir, ax, ang ).modify(mesh.geometry);
</code>```

Is there some way to do it or it is not possible?

The bend effect I am trying to achieve is similar to this:

答:
First, I would consider the possibility of using not a fully curved surface, but a series of flat square elements arranged in a curved manner- a la helix mode in this example. This is the easiest method and you don't lose anything of value from a UX perspective

The underlying issue is that it looks like the CSS3dobject does inherit Object3d elements, but the css3d renderer doesn't use geometry anywhere, it's just performing matrix transforms on the css elements, so performing transformations on geometry will have no effect on the css elements, since the renderer is only using camera information to transform and move the css element. It takes width, height, and then moves them around. Everything is a plane.

If what you're trying to do is to use the iframe because you want to re-use another website, you could maybe try using the CSS clip parameter to split the iframe into a series of chunks (duplicate elements added to the dom with different clip parameters) that you then arrange into a cylindrical shape. I made a fiddle with a basic gist of what you could try.. But if you take this template, bind the url locations/scrolling etc together on those iframes, you can keep them syncd, and then work out the trig to position and rotate them, you might have what you're looking for - but its hacky.

But like I said, i would recommend using 2d elements arranged in 3d if you have to use css3d, or the canvas renderer + raycasting for button clicks + js for functionality.

Title: Three js curved (bend) CSS3DObject

Body:
I am trying to bend a three js CSS3DObject:

var element = document.createElement('iframe');
element.src = 'https://example.com/';
var cssObject = new THREE.CSS3DObject( element );

but I cannot use the bend modifier on it, like I do on other meshes, e.g.:

var dir = new THREE.Vector3( 0, 0, -1 );
var ax =  new THREE.Vector3( 0, 1, 0 );
var ang = Math.PI / 4;
modifier.set( dir, ax, ang ).modify(mesh.geometry);

Is there some way to do it or it is not possible?

The bend effect I am trying to achieve is similar to this:


问:
What CSS properties are likely to cause problems in Internet Explorer?
I designed a web page with lot of CSS properties, and when viewing it in IE its alignment is not so proper compared to all other browsers.

For the next time, what are the CSS properties I should take care with in IE?

Thank you.

答:
First thing to say is that you should make sure your HTML code always has a <!DOCTYPE> declaration. This will force it into "standards mode", which makes IE much more consistent with other browsers. (it's still got tons of missing and broken features, but its nothing compared to the disaster you'll get without a doctype).

For finding out what those missing and broken features are, I recommend you take a look at http://www.quirksmode.org/css/contents.html.

The Quirksmode site has an excellent set of tables showing exactly which CSS properties and other functionality work in which browsers. It also has details of exactly what the bugs are in specific cases. If I ever have a question like this, Quirksmode is the first place I go to find the answer.

The second place I go to find the answer is http://caniuse.com/. However this site focusses more on newer features, so may not tell you everything you need to know.

ContentLicense: CC BY-SA 2.5


问:
What are values starting with "t" and how to ignore them for counting
I am trying to query the frequency of certain attributes in Wikidata, using SPARQL.

For example, to find out what the frequency of different values for gender is, I have the following query:

```<code>SELECT ?rid (COUNT(?rid) AS ?count)
WHERE { ?qid wdt:P21 ?rid.
  BIND(wd:Q5 AS ?human)
  ?qid wdt:P31 ?human.
} GROUP BY ?rid
</code>```

I get the following result:

```<code>wd:Q6581097 2752163
wd:Q6581072 562339
wd:Q1052281 223
wd:Q1097630 68
wd:Q2449503 67
wd:Q48270   36
wd:Q44148   8
wd:Q43445   4
t152990852  1
t152990762  1
t152990752  1
t152990635  1
t152775383  1
t152775370  1
t152775368  1
...
</code>```

I have the following questions regarding this:

What do those t152... values refer to?

How can I ignore the tuples containing t152...?

I tried FILTER ( !strstarts(str(?rid), "wd:") ) but it timed out.

How can I count the distinct number of answers?

I tried SELECT (COUNT(DISTINCT ?rid) AS ?count) with the above query, but again it timed out.

答:
Values starting with t are "skolemized" unknown values (see, e.g., Q2423351 for a person of unknown sex or gender).

In order to improve performance, I suggest you to divide your query into three parts:

All "normal" genders:

SELECT ?rid (COUNT(?qid) AS ?count)
WHERE {
   ?qid wdt:P31 wd:Q5.
   ?qid wdt:P21 ?rid.
   ?rid wdt:P31 wd:Q48264
} GROUP BY ?rid ORDER BY DESC(?count)
```

<p>Please note that, according Wikidata, wd:Q746411 is a subclass of wd:Q48270, etc.</p></li>
<li><p>All "non-normal" genders:</p>

<pre class="lang-sql prettyprint-override"><code>SELECT ?rid (COUNT(?qid) AS ?count)
WHERE {
   ?qid wdt:P31 wd:Q5.
   ?qid wdt:P21 ?rid.
   FILTER (?rid NOT IN
           (
            wd:Q6581097,
            wd:Q6581072,
            wd:Q1052281,
            wd:Q2449503,
            wd:Q48270,
            wd:Q746411,
            wd:Q189125,
            wd:Q1399232,
            wd:Q3277905
           )
          ).
   FILTER (isURI(?rid))
} GROUP BY ?rid ORDER BY DESC(?count)
</code>```

I do not use FILTER NOT EXISTS {?rid wdt:P31 wd:Q48264 } due to performance reasons.

All (i.e. 1) "unknown" genders:

SELECT (COUNT(?qid) AS ?count)
WHERE {
   ?qid wdt:P31 wd:Q5.
   ?qid wdt:P21 ?rid.
   FILTER (!isURI(?rid))
}
```

In fact, it is not very important in your case — to count distinct wd:Q5 or count them not distinct — but the latter is preferable due to performance reasons.

Body:
I am trying to query the frequency of certain attributes in Wikidata, using SPARQL.

For example, to find out what the frequency of different values for gender is, I have the following query:

SELECT ?rid (COUNT(?rid) AS ?count)
WHERE { ?qid wdt:P21 ?rid.
  BIND(wd:Q5 AS ?human)
  ?qid wdt:P31 ?human.
} GROUP BY ?rid

I get the following result:

wd:Q6581097 2752163
wd:Q6581072 562339
wd:Q1052281 223
wd:Q1097630 68
wd:Q2449503 67
wd:Q48270   36
wd:Q44148   8
wd:Q43445   4
t152990852  1
t152990762  1
t152990752  1
t152990635  1
t152775383  1
t152775370  1
t152775368  1
...

I have the following questions regarding this:

What do those t152... values refer to?

How can I ignore the tuples containing t152...?

I tried FILTER ( !strstarts(str(?rid), "wd:") ) but it timed out.

How can I count the distinct number of answers?

I tried SELECT (COUNT(DISTINCT ?rid) AS ?count) with the above query, but again it timed out.

Body:
Values starting with t are "skolemized" unknown values (see, e.g., Q2423351 for a person of unknown sex or gender).

In order to improve performance, I suggest you to divide your query into three parts:

All "normal" genders:

SELECT ?rid (COUNT(?qid) AS ?count)
WHERE {
   ?qid wdt:P31 wd:Q5.
   ?qid wdt:P21 ?rid.
   ?rid wdt:P31 wd:Q48264
} GROUP BY ?rid ORDER BY DESC(?count)

Please note that, according Wikidata, wd:Q746411 is a subclass of wd:Q48270, etc.

All "non-normal" genders:

SELECT ?rid (COUNT(?qid) AS ?count)
WHERE {
   ?qid wdt:P31 wd:Q5.
   ?qid wdt:P21 ?rid.
   FILTER (?rid NOT IN
           (
            wd:Q6581097,
            wd:Q6581072,
            wd:Q1052281,
            wd:Q2449503,
            wd:Q48270,
            wd:Q746411,
            wd:Q189125,
            wd:Q1399232,
            wd:Q3277905
           )
          ).
   FILTER (isURI(?rid))
} GROUP BY ?rid ORDER BY DESC(?count)

I do not use FILTER NOT EXISTS {?rid wdt:P31 wd:Q48264 } due to performance reasons.

All (i.e. 1) "unknown" genders:

SELECT (COUNT(?qid) AS ?count)
WHERE {
   ?qid wdt:P31 wd:Q5.
   ?qid wdt:P21 ?rid.
   FILTER (!isURI(?rid))
}

In fact, it is not very important in your case — to count distinct wd:Q5 or count them not distinct — but the latter is preferable due to performance reasons.


问:
VueJS + VueRouter: Conditionally Disabling A Route
I wonder how to disable a route in VueRouter conditionally, so that it can't be accessed anymore!

I tried to redirect with this.$router.replace('/') but the URL did show the route that I wanted to skip.

Any thoughts?

EDIT:

this is my VUEX-Store: Have a look at router.replace('/')

```<code>const store = new Vuex.Store({
  state: {
    users: [ ],
    friendships: [ ],
    userID: null
  },
  mutations: {
    signUp(state, payload) {
      auth.createUserWithEmailAndPassword(payload.email, payload.password).then((user) => {
        if (user !== null) {
          state.userID = user.uid
          router.replace('/')
        }
        else {
          state.userID = null
        }
      })
    },
    signIn(state, payload) {
      auth.signInWithEmailAndPassword(payload.email, payload.password).then((user) => {
        if (user !== null) {
          state.userID = user.uid
          router.replace('/')
        }
        else {
          state.userID = null
        }
      })
    },
    signOut(state) {
      auth.signOut()
      state.userID = null
      router.replace('/signin')
    },
    authenticate(state) {
      auth.onAuthStateChanged((user) => {
        if (user !== null) {
          state.userID = user.uid
          router.replace('/')
        }
        else {
          state.userID = null
        }
      })
    }
  },
  actions: {
    signUp({ commit }) {
      commit('signUp')
    },
    signIn({ commit }) {
      commit('signIn')
    },
    signOut({ commit }) {
      commit('signOut')
    },
    authenticate({ commit }) {
      commit('authenticate')
    },
    redirect({ commit }) {
      commit('redirect')
    }
  }
})
</code>```

and here is my component:

```<code><template>
  <div id="you">
    <h1>you</h1>
    <p>You are on your secret page!</p>
    <p>{{ $store.state.userID }}</p>
  </div>
</template>

<script>
  export default {
    name: 'you',
    beforeCreate() {
      if (this.$store.state.userID === null) {
        this.$router.replace('/signin')
      }
    }
  }
</script>
</code>```

答:
You can add a meta feild to that route you want to conditionally disable it like this:

```<code>export const routes = [
  {path: '/', component: foo},
  {path: '/bar', component: bar, meta:{conditionalRoute:true}}
];
</code>```

And use router.beforeEach in your main.js :

```<code>router.beforeEach((to, from, next) => {
    if (to.matched.some(record => record.meta.conditionalRoute)) {
        // this route requires condition to be accessed
        // if not, redirect to home page.
        if (!checkCondition) {
            //check codition is false
            next({ path: '/'})
        } else {
            //check codition is true
            next()
        }
    } else {
        next() // make sure to always call next()!
    }
})
</code>```

Or else use beforeRouteEnter() navigation guard locally on that route's component

```<code>beforeRouteEnter(to, from, next){
    next(vm => {
        // access to component instance via `vm`
        if(checkCondition){
            next();
        }else{
            next('/');
        }
    })
}
</code>```

In your signin component

```<code>beforeRouteEnter(to, from, next){
    next(vm => {
        // access to component instance via `vm`
        if(vm.$store.state.userUID !== null){
            next('/');
        }else{
            next();
        }
    })
}
</code>```

Body:
I wonder how to disable a route in VueRouter conditionally, so that it can't be accessed anymore!

I tried to redirect with this.$router.replace('/') but the URL did show the route that I wanted to skip.

Any thoughts?

EDIT:

this is my VUEX-Store: Have a look at router.replace('/')

const store = new Vuex.Store({
  state: {
    users: [ ],
    friendships: [ ],
    userID: null
  },
  mutations: {
    signUp(state, payload) {
      auth.createUserWithEmailAndPassword(payload.email, payload.password).then((user) => {
        if (user !== null) {
          state.userID = user.uid
          router.replace('/')
        }
        else {
          state.userID = null
        }
      })
    },
    signIn(state, payload) {
      auth.signInWithEmailAndPassword(payload.email, payload.password).then((user) => {
        if (user !== null) {
          state.userID = user.uid
          router.replace('/')
        }
        else {
          state.userID = null
        }
      })
    },
    signOut(state) {
      auth.signOut()
      state.userID = null
      router.replace('/signin')
    },
    authenticate(state) {
      auth.onAuthStateChanged((user) => {
        if (user !== null) {
          state.userID = user.uid
          router.replace('/')
        }
        else {
          state.userID = null
        }
      })
    }
  },
  actions: {
    signUp({ commit }) {
      commit('signUp')
    },
    signIn({ commit }) {
      commit('signIn')
    },
    signOut({ commit }) {
      commit('signOut')
    },
    authenticate({ commit }) {
      commit('authenticate')
    },
    redirect({ commit }) {
      commit('redirect')
    }
  }
})

and here is my component:

<template>

you

You are on your secret page!

{{ $store.state.userID }}

</template>

Body:
You can add a meta feild to that route you want to conditionally disable it like this:

export const routes = [
  {path: '/', component: foo},
  {path: '/bar', component: bar, meta:{conditionalRoute:true}}
];

And use router.beforeEach in your main.js :

router.beforeEach((to, from, next) => {
    if (to.matched.some(record => record.meta.conditionalRoute)) {
        // this route requires condition to be accessed
        // if not, redirect to home page.
        if (!checkCondition) {
            //check codition is false
            next({ path: '/'})
        } else {
            //check codition is true
            next()
        }
    } else {
        next() // make sure to always call next()!
    }
})

Or else use beforeRouteEnter() navigation guard locally on that route's component

beforeRouteEnter(to, from, next){
    next(vm => {
        // access to component instance via `vm`
        if(checkCondition){
            next();
        }else{
            next('/');
        }
    })
}

In your signin component

beforeRouteEnter(to, from, next){
    next(vm => {
        // access to component instance via `vm`
        if(vm.$store.state.userUID !== null){
            next('/');
        }else{
            next();
        }
    })
}


问:
UIViewControllerHierarchyInconsistency
I am trying to build my app and at one point I push a UIViewController and then I get this error. I am not exactly sure why.

'UIViewControllerHierarchyInconsistency', reason: 'A view can only be
  associated with at most one view controller at a time! View > is associated with . Clear this association before associating this view with
  .'

```<code>PageViewController *viewController;

viewController = [[PageViewController alloc] initWithManagedObjectContext:managedObjectContext];
dataSource = [[PagesDataSource alloc] initWithManagedObjectContext:managedObjectContext];

PVPage *selectedPage = [[dataSource pages] objectAtIndex:itemIndex];
[viewController setRepresentedPage:selectedPage];

PageFlipperAppDelegate *appDelegate = (PageFlipperAppDelegate *)[[UIApplication sharedApplication] delegate];
[(UINavigationController *)[[appDelegate window] rootViewController] setToolbarHidden:YES animated:YES];
[(UINavigationController *)[[appDelegate window] rootViewController] pushViewController:viewController animated:YES];
</code>```

In my pageViewController...................

```<code>- (id)initWithManagedObjectContext:(NSManagedObjectContext *)initManagedObjectContext
{
    if ((self = [super initWithNibName:@"PageView" bundle:nil]))
    {
        [self setManagedObjectContext:initManagedObjectContext];
        dataSource = [[PagesDataSource alloc] initWithManagedObjectContext:[self managedObjectContext]];
    }
    return self;
}
</code>```

答: One of the reason I stuck on was that I copied the ViewController from a storyboard to a xib file to be loaded programmatically for my need. But in a xib I should really copy the view not the entire view controller. And set the file owner to my custom view controller. That solves my similar error problem.

Title: UIViewControllerHierarchyInconsistency

Body:
I am trying to build my app and at one point I push a UIViewController and then I get this error. I am not exactly sure why.

'UIViewControllerHierarchyInconsistency', reason: 'A view can only be
  associated with at most one view controller at a time! View > is associated with . Clear this association before associating this view with
  .'

PageViewController *viewController;

viewController = [[PageViewController alloc] initWithManagedObjectContext:managedObjectContext];
dataSource = [[PagesDataSource alloc] initWithManagedObjectContext:managedObjectContext];

PVPage *selectedPage = [[dataSource pages] objectAtIndex:itemIndex];
[viewController setRepresentedPage:selectedPage];

PageFlipperAppDelegate *appDelegate = (PageFlipperAppDelegate *)[[UIApplication sharedApplication] delegate];
[(UINavigationController *)[[appDelegate window] rootViewController] setToolbarHidden:YES animated:YES];
[(UINavigationController *)[[appDelegate window] rootViewController] pushViewController:viewController animated:YES];

In my pageViewController...................

- (id)initWithManagedObjectContext:(NSManagedObjectContext *)initManagedObjectContext
{
    if ((self = [super initWithNibName:@"PageView" bundle:nil]))
    {
        [self setManagedObjectContext:initManagedObjectContext];
        dataSource = [[PagesDataSource alloc] initWithManagedObjectContext:[self managedObjectContext]];
    }
    return self;
}


问:
Django does not migrate app
I'm working on a django project for learning purpose. I've created an app organization and installed it. When I run python manage.py makemigrations organization it works fine shows the changes.

```<code>Migrations for 'organization':
  organization/migrations/0001_initial.py:
    - Create model Organization
    - Create model Principle
</code>```

But when I run python manage.py migrate organization it doesn't migrate and shows no changes to apply.

```<code>Operations to perform:
  Apply all migrations: organization
Running migrations:
  No migrations to apply.
</code>```

I'm using postgresql and tried drop owned by user_name; after deleting all migrations folders. But still doesn't work. It shows every time the same thing. How to resolve this ?

Environment:

OS version Ubuntu 16.04

Django version 1.10.3

PostgreSQL version 9.5.7

organization/models.py

```<code>from django.db import models
from django.contrib.postgres.fields import JSONField

class Principle(models.Model):
    name = models.CharField(max_length=256)
    description = models.CharField(max_length=256)
    contact_no = models.CharField(max_length=256)
    status = models.BooleanField()

class Organization(models.Model):
    name = models.CharField(max_length=256)
    liceneses = [
        ('pvt','Private Limited',),
        ('pub','Public Limited',),
        ('part','Partnership',),
        ('prop','proprietary',)
    ]

    licenese_type = models.CharField(max_length=10, choices=liceneses)
    key_person_name = models.CharField(max_length=256)
    key_person_position = models.CharField(max_length=256)
    key_person_contact_no = models.CharField(max_length=45)
    primary_organization_contact = models.CharField(max_length=45)
    organization_address = models.TextField()
    additional_info = JSONField()
    date_of_registration = models.CharField(max_length=45)
    status = models.BooleanField()
</code>```

答:
in these case delete all the migrations files from migration folder except __init__.py file for all apps, make sure you have the apps in the installed apps

then delete the database tables

NOTE: Be careful to backup important FILES when you delete your DATABASE !

```<code>run python manage.py migrate
run python manage.py makemigrations
run python manage.py migrate
</code>```

Title: Django does not migrate app

Body:
I'm working on a django project for learning purpose. I've created an app organization and installed it. When I run python manage.py makemigrations organization it works fine shows the changes.

Migrations for 'organization':
  organization/migrations/0001_initial.py:
    - Create model Organization
    - Create model Principle

But when I run python manage.py migrate organization it doesn't migrate and shows no changes to apply.

Operations to perform:
  Apply all migrations: organization
Running migrations:
  No migrations to apply.

I'm using postgresql and tried drop owned by user_name; after deleting all migrations folders. But still doesn't work. It shows every time the same thing. How to resolve this ?

Environment:

OS version Ubuntu 16.04

Django version 1.10.3

PostgreSQL version 9.5.7

organization/models.py

from django.db import models
from django.contrib.postgres.fields import JSONField

class Principle(models.Model):
    name = models.CharField(max_length=256)
    description = models.CharField(max_length=256)
    contact_no = models.CharField(max_length=256)
    status = models.BooleanField()

class Organization(models.Model):
    name = models.CharField(max_length=256)
    liceneses = [
        ('pvt','Private Limited',),
        ('pub','Public Limited',),
        ('part','Partnership',),
        ('prop','proprietary',)
    ]

    licenese_type = models.CharField(max_length=10, choices=liceneses)
    key_person_name = models.CharField(max_length=256)
    key_person_position = models.CharField(max_length=256)
    key_person_contact_no = models.CharField(max_length=45)
    primary_organization_contact = models.CharField(max_length=45)
    organization_address = models.TextField()
    additional_info = JSONField()
    date_of_registration = models.CharField(max_length=45)
    status = models.BooleanField()

Body:
in these case delete all the migrations files from migration folder except __init__.py file for all apps, make sure you have the apps in the installed apps

then delete the database tables

NOTE: Be careful to backup important FILES when you delete your DATABASE !

run python manage.py migrate
run python manage.py makemigrations
run python manage.py migrate


问:
The value along x-axis in the chart.js is breaking?
I am using chart.js .The problem which I am facing is that ,the value along x-axis is breaking. And it is only the last value. I even increased the width but still same problem.enter image description here</p>

答:
To resolve the issue, you can set right-padding accordingly for your chart layout.

To do so, add the following in your chart options ...

```<code>options: {
   layout: {
      padding: {
         right: 50, //set that suits the best
      }
   },
   ...
}
</code>```

Body:
To resolve the issue, you can set right-padding accordingly for your chart layout.

To do so, add the following in your chart options ...

options: {
   layout: {
      padding: {
         right: 50, //set that suits the best
      }
   },
   ...
}


问:
MongoDB - unable to check if value is $gte val X and $lte val Y
I'm doing an aggregate, use $lookup to get data from another collection and then use $filter in the project-stage to filter the new data.

After getting the new data my output looks like this (reservations being the data I get from a different database):

```<code> [0] => stdClass Object
        (
            [_id] => 592fffe7f509270850281871
            [name] => Table 1
            [seats] => 4
            [reservations] => Array
                (
                    [0] => stdClass Object
                        (
                            [_id] => 59367485f5092753f477f2c1
                            [guests] => 3
                            [date] => stdClass Object
                                (
                                    [$date] => 1496768400000
                                    [$unixtime] => 1496768400
                                    [_datetime] => 2017-06-06 17:00:00
                                )

                            [dateString] => 2017-06-06
                            [duration] => 45
                            [startUTime] => 1496761200
                            [endUTime] => 1496763900
                            [tables] => Array
                                (
                                    [0] => 592fffe7f509270850281871
                                    [1] => 592fffe7f509270850281874
                                )

                            [reservedAt] => stdClass Object
                                (
                                    [$date] => 1496740997000
                                    [$unixtime] => 1496740997
                                    [_datetime] => 2017-06-06 09:23:17
                                )
                        )
                )
        )
</code>```

Now I want to filter the reservations. I have a variable called reqStartTime and a variable called reqEndTime. Those are unixtimes of a newly requested reservation. I want to check if either of those values are in between the startUTime and endUTime of the current reservations.

Let's say reqStartTime is 1496761600 and reqEndTime is 1496764200.

Using $filter in the project-stage:

```<code>{
        '$project' : {
            name: 1,
            seats: 1,
            reservations : {
               '$filter': {
                   input : "$reservations",
                   as: "res",
                   cond :
                        { '$or' : [
                             { '$and' : [
                                { '$gte' : [ reqStartTime, "$$res.startUTime" ] },
                                { '$lte' : [ reqStartTime, "$$res.endUTime" ] }
                            ]},
                            { '$and' : [
                                { '$gte' : [ reqEndTime, "$$res.startUTime" ] },
                                { '$lte' : [ reqEndTime, "$$res.endUTime" ] }
                            ]}
                        ]}
                }
            }
        }
    }
</code>```

Problem is, this filters out ALL reservations - the output is always an empty array. I've tested setting the variables reqStartTime and reqEndTime manually to be sure they're within range, but no luck.

答: The query turns out to be a valid one- the problem was that my variables got converted to string. Converting them back to integers fixed the problem. </p>

Body:
I'm doing an aggregate, use $lookup to get data from another collection and then use $filter in the project-stage to filter the new data.

After getting the new data my output looks like this (reservations being the data I get from a different database):

 [0] => stdClass Object
        (
            [_id] => 592fffe7f509270850281871
            [name] => Table 1
            [seats] => 4
            [reservations] => Array
                (
                    [0] => stdClass Object
                        (
                            [_id] => 59367485f5092753f477f2c1
                            [guests] => 3
                            [date] => stdClass Object
                                (
                                    [$date] => 1496768400000
                                    [$unixtime] => 1496768400
                                    [_datetime] => 2017-06-06 17:00:00
                                )

                            [dateString] => 2017-06-06
                            [duration] => 45
                            [startUTime] => 1496761200
                            [endUTime] => 1496763900
                            [tables] => Array
                                (
                                    [0] => 592fffe7f509270850281871
                                    [1] => 592fffe7f509270850281874
                                )

                            [reservedAt] => stdClass Object
                                (
                                    [$date] => 1496740997000
                                    [$unixtime] => 1496740997
                                    [_datetime] => 2017-06-06 09:23:17
                                )
                        )
                )
        )

Now I want to filter the reservations. I have a variable called reqStartTime and a variable called reqEndTime. Those are unixtimes of a newly requested reservation. I want to check if either of those values are in between the startUTime and endUTime of the current reservations.

Let's say reqStartTime is 1496761600 and reqEndTime is 1496764200.

Using $filter in the project-stage:

{
        '$project' : {
            name: 1,
            seats: 1,
            reservations : {
               '$filter': {
                   input : "$reservations",
                   as: "res",
                   cond :
                        { '$or' : [
                             { '$and' : [
                                { '$gte' : [ reqStartTime, "$$res.startUTime" ] },
                                { '$lte' : [ reqStartTime, "$$res.endUTime" ] }
                            ]},
                            { '$and' : [
                                { '$gte' : [ reqEndTime, "$$res.startUTime" ] },
                                { '$lte' : [ reqEndTime, "$$res.endUTime" ] }
                            ]}
                        ]}
                }
            }
        }
    }

Problem is, this filters out ALL reservations - the output is always an empty array. I've tested setting the variables reqStartTime and reqEndTime manually to be sure they're within range, but no luck.


问:
Best practices to use own type in golang. Alians to build type
I wonder when or if it should be use own type in golang. When this will be more friendly to understand my code, or when I shouldn't use own type.

Example:
I want to create map type with MAC, and name host:

in first way the simplest I can do that

```<code>var machines map[string]string{
   "11:22...": "myHost",
   "22:33..":  "yourHost",
}
</code>```

in second way

```<code>type MAC string
type HOST string

  machines := map[MAC]HOST{
       MAC("11:22..") : HOST("myHost"),
       MAC("22:33..") : HOST("yourHost"),
    }
</code>```

In above exmaple I can get additional controle on my type MAC, HOST trought write method to validation, compare etc it is better ?

Third way

```<code>type MACHINES map[string]string

m := MACHINES{}
    m = map[string]string{
     "11:22.." : "myHost",
     "22:33" : "yourHost",
    }
</code>```

above example for me is worst to understand  less intuitive to some else. I think that above example should be also filled about HOST, and MAC because type MACHINE nothing to say developer how this should be implement so I would like

```<code>  type MACHINES map[MAC]HOST
</code>```

However, please about comment to better understand about usage own type in golang.

答:
I think another reason to use your own types, that hasn't been mentioned here, is if you are not sure exactly what the right type for something is e.g. uint8 / uint16 and you want to easily change it later all in one place.

This will however make conversions necessary whenever you want to use the built-in types' methods. Or you will need to define them on your own type.

Body:
I wonder when or if it should be use own type in golang. When this will be more friendly to understand my code, or when I shouldn't use own type.

Example:
I want to create map type with MAC, and name host:

in first way the simplest I can do that

var machines map[string]string{
   "11:22...": "myHost",
   "22:33..":  "yourHost",
}

in second way

type MAC string
type HOST string

  machines := map[MAC]HOST{
       MAC("11:22..") : HOST("myHost"),
       MAC("22:33..") : HOST("yourHost"),
    }

In above exmaple I can get additional controle on my type MAC, HOST trought write method to validation, compare etc it is better ?

Third way

type MACHINES map[string]string

m := MACHINES{}
    m = map[string]string{
     "11:22.." : "myHost",
     "22:33" : "yourHost",
    }

above example for me is worst to understand  less intuitive to some else. I think that above example should be also filled about HOST, and MAC because type MACHINE nothing to say developer how this should be implement so I would like

  type MACHINES map[MAC]HOST

However, please about comment to better understand about usage own type in golang.


问:
Exporting from Google Spreadsheet to Firebase, ERROR
I think most of my errors come from the updates of Firebase. But I'm getting there.

Still loving Firebase!

Ok, I'm trying to export a column demo Spreadsheet to Firebase (code bellow). The error seems to be related to the Firebase reference. I know how to fix it in my Firebase projects, but this is hooked into the Script editor of the spreadsheet.

ERROR: ReferenceError: "FirebaseApp" is not defined. (line 13, file
  "export")

```<code>function writeDataToFirebase() {
  var ss =

SpreadsheetApp.openById("1rV2_S2q5rcakOuHs2E1iLeKR2floRIozSytAt2iRXo8");
  var sheet = ss.getSheets()[0];
  var data = sheet.getDataRange().getValues();
  var dataToImport = {};
  for(var i = 1; i < data.length; i++) {
    var year = data[i][0];
    dataToImport[year] = {
    caption:data[i][1]
  };
}

 var firebaseUrl = "https://test-db-9833d.firebaseio.com/";

 // ERROR HERE ********************************************

 var base = FirebaseApp.getDatabaseByUrl(firebaseUrl);
 base.setData("", dataToImport);

}
</code>```

答:
for Google Sheets to be able to write to your Firebase instance, there can be a couple of reasons that you can't write to it, check this:

did you give sheet permission to access your Google account info and Docs

did you reference the firebase database url correctly

did you loosen permissions on firebase, for testing perposes you can give writing true,  just to see if that works for start, and then use full perm setup

did you tried to use debugging tool like Logger.log to see what you get in log on specific sections of code?

also I have been able to record full screencast of my process and you can watch it here: https://www.youtube.com/watch?v=9SIAnjgKZZQ&feature=youtu.be

here is the code that I changed to use dinamic header titles for labels for our data and not have it "hardcoded" way :)

```<code>function onfire() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];
  var range = sheet.getDataRange();
  var values = range.getValues();
  var allvals = []; var row = {};
  for(var i = 1; i < values.length; i++) {
    for( var j = 0; j < values[i].length; j++ ){
      if( values[i][j] ) {
        row[ values[0][j].toString() ] = values[i][j] ;
      }
    }
    allvals.push( row ); // insert row
    row = {}; // blank template obj
  }
  var firebaseUrl = "https://my-android-app-demo1.firebaseio.com/sheet";
  var base = firebase.getDatabaseByUrl(firebaseUrl, sec);
  // Logger.log( allvals );
  base.setData("", allvals );
}
</code>```

hth, kres

Body:
I think most of my errors come from the updates of Firebase. But I'm getting there.

Still loving Firebase!

Ok, I'm trying to export a column demo Spreadsheet to Firebase (code bellow). The error seems to be related to the Firebase reference. I know how to fix it in my Firebase projects, but this is hooked into the Script editor of the spreadsheet.

ERROR: ReferenceError: "FirebaseApp" is not defined. (line 13, file
  "export")

function writeDataToFirebase() {
  var ss =

SpreadsheetApp.openById("1rV2_S2q5rcakOuHs2E1iLeKR2floRIozSytAt2iRXo8");
  var sheet = ss.getSheets()[0];
  var data = sheet.getDataRange().getValues();
  var dataToImport = {};
  for(var i = 1; i < data.length; i++) {
    var year = data[i][0];
    dataToImport[year] = {
    caption:data[i][1]
  };
}

 var firebaseUrl = "https://test-db-9833d.firebaseio.com/";

 // ERROR HERE ********************************************

 var base = FirebaseApp.getDatabaseByUrl(firebaseUrl);
 base.setData("", dataToImport);

}

Body:
for Google Sheets to be able to write to your Firebase instance, there can be a couple of reasons that you can't write to it, check this:

did you give sheet permission to access your Google account info and Docs

did you reference the firebase database url correctly

did you loosen permissions on firebase, for testing perposes you can give writing true,  just to see if that works for start, and then use full perm setup

did you tried to use debugging tool like Logger.log to see what you get in log on specific sections of code?

also I have been able to record full screencast of my process and you can watch it here: https://www.youtube.com/watch?v=9SIAnjgKZZQ&feature=youtu.be

here is the code that I changed to use dinamic header titles for labels for our data and not have it "hardcoded" way :)

function onfire() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];
  var range = sheet.getDataRange();
  var values = range.getValues();
  var allvals = []; var row = {};
  for(var i = 1; i < values.length; i++) {
    for( var j = 0; j < values[i].length; j++ ){
      if( values[i][j] ) {
        row[ values[0][j].toString() ] = values[i][j] ;
      }
    }
    allvals.push( row ); // insert row
    row = {}; // blank template obj
  }
  var firebaseUrl = "https://my-android-app-demo1.firebaseio.com/sheet";
  var base = firebase.getDatabaseByUrl(firebaseUrl, sec);
  // Logger.log( allvals );
  base.setData("", allvals );
}

hth, kres


问:
Extending TypeScript Global object in node.js
I have a node.js app that attaches some config information to the global object:

```<code>global.myConfig = {
    a: 1,
    b: 2
}
</code>```

The TypeScript compiler doesn't like this because the Global type has no object named myConfig:

TS2339: Property 'myConfig' does not exist on type 'Global'.

I don't want to do this:

```<code>global['myConfig'] = { ... }
</code>```

How do I either extend the Global type to contain myConfig or just tell TypeScript to shut up and trust me? I'd prefer the first one.

I don't want to change the declarations inside node.d.ts. I saw this SO post and tried this:

```<code>declare module NodeJS  {
    interface Global {
        myConfig: any
    }
}
</code>```

as a way to extend the existing Global interface, but it doesn't seem to have any effect.

答:
To avoid Typescript claim something like this:

TS2339: Property 'myConfig' does not exist on type 'Global'.

I suggest to define custom types. I do it under src/types/custom.d.ts file in my project:

```<code>declare global {
  namespace NodeJS {
    interface Global {
        myConfig: {
          a: number;
          b: number;
        }
    }
  }
}
</code>```

Then I ensure these are considered by Typescript in tsconfig.json file:

```<code>{
  ...
  "files": [
    ...
    "src/types/custom.d.ts"
  ]
}
</code>```

Now you're safe to use your custom property:

```<code>console.log(global.myConfig.a);
</code>```

Body:
I have a node.js app that attaches some config information to the global object:

global.myConfig = {
    a: 1,
    b: 2
}

The TypeScript compiler doesn't like this because the Global type has no object named myConfig:

TS2339: Property 'myConfig' does not exist on type 'Global'.

I don't want to do this:

global['myConfig'] = { ... }

How do I either extend the Global type to contain myConfig or just tell TypeScript to shut up and trust me? I'd prefer the first one.

I don't want to change the declarations inside node.d.ts. I saw this SO post and tried this:

declare module NodeJS  {
    interface Global {
        myConfig: any
    }
}

as a way to extend the existing Global interface, but it doesn't seem to have any effect.

Body:
To avoid Typescript claim something like this:

TS2339: Property 'myConfig' does not exist on type 'Global'.

I suggest to define custom types. I do it under src/types/custom.d.ts file in my project:

declare global {
  namespace NodeJS {
    interface Global {
        myConfig: {
          a: number;
          b: number;
        }
    }
  }
}

Then I ensure these are considered by Typescript in tsconfig.json file:

{
  ...
  "files": [
    ...
    "src/types/custom.d.ts"
  ]
}

Now you're safe to use your custom property:

console.log(global.myConfig.a);


问:
Creating a GridView From Listview in ReactNative?(Without using libraries)
Consider a simple app in React Native that fetches listings from a remote JSON source and displays them on screen.

So far,I've managed to get the results to display using the ListView components in rows (i.e. 2 result per row, see screenshot).

in one row.both the grids display data of a single person,i want
details in a consecutive manner not repeating.

```<code>        </Content>
          <View style={{backgroundColor: 'white'}}>
           <Text style={{color: 'black',fontSize: 17,marginTop: 25,marginLeft: 15}}>Employees</Text>
          </View>
          <List dataArray={currentContext.props.employeeList}
            renderRow={(data) =>
              <ListItem>
                {this.renderRow(data)}
              </ListItem>
           } />
          </Content>
</code>```

The function renderRow(data) is given by

```<code>renderRow(data){
  return(
    typeOne()
  )
  function typeOne(){
    return(
      <View style={styles.gridContainer}>
        <Content contentContainerStyle={{
            padding:6,
            paddingBottom:0
          }}>
        <View style={{flex:1,}}>
            <Row>
              {renderCell(data.photo_url, 0,data.name)}
              {renderCell(data.photo_url, 1,data.name)}
            </Row>
        </View>
          </Content>
      </View>
    )
   function renderCell(bg,pos,title){
      if (pos%2==0) {
        return(
          <Col style={[{marginRight:3},styles.colStyle]}>
            {cellContent(bg,title)}
          </Col>
        )
      }else{
        return(
          <Col style={[{marginLeft:3},styles.colStyle]}>
            {cellContent(bg,title)}
          </Col>
        )
      }
      function cellContent(bg,title){
        if(bg==null){
          return null
        }
        return(
          <Button style={{flex:1,alignSelf:'stretch'}} underLayouColor='red'>
            <View style={styles.cellContent}>
              <Image style={{height:230,alignItems: 'stretch'}} source={{uri:bg}} blurRadius={1}/>
              <View style={[styles.cellTitleBg,{opacity: 0.5,marginTop: 10}]}>
              <Text style={[styles.cellTitle,{position:'absolute',bottom:0,right:5}]}>{title}</Text>
              </View>
            </View>
          </Button>
        )
      }
    }
  }
}
</code>```

How can get the list-view to return 2 data's per row ?

I will give you similar question for reference in the below link

ListView grid in React Native

please help me solve this issue.

The style part

```<code>const styles = StyleSheet.create({
    container: {
        flex:1,
        backgroundColor:'white',
    },
    button:{
        color:'white'
    },
    overLayView: {
        position:'absolute',
        alignSelf:'center',

    },
    gridContainer: {backgroundColor:'#EDF0F2',flex:1,},
    colStyle:{height:210,flex:1,marginBottom:6,marginRight:10,marginLeft:10},
    cellContent:{position:'absolute',left:0,right:0,top:0,bottom:0},
    cellTitleBg:{bottom:65,backgroundColor:'#778899',height:35},
    cellTitle:{bottom:65,color:'white',fontWeight:'bold',fontSize:17,right:0,textAlign:'right',right:0}
})
</code>```

答:
Try this out...

pass index from the renderRow function down to this function where this view is defined.

```<code><Button key={index} style={{flex:1,alignSelf:'stretch'}} underLayouColor='red'>
            <View key={index} style={styles.cellContent}>
              <Image key={index} style={{height:230,alignItems: 'stretch'}} source={{uri:bg}} blurRadius={1}/>
              <View key={index} style={[styles.cellTitleBg,{opacity: 0.5,marginTop: 10}]}>
              <Text key={index} style={[styles.cellTitle,{position:'absolute',bottom:0,right:5}]}>{title}</Text>
              </View>
            </View>
          </Button>
</code>```

Body:
Consider a simple app in React Native that fetches listings from a remote JSON source and displays them on screen.

So far,I've managed to get the results to display using the ListView components in rows (i.e. 2 result per row, see screenshot).

in one row.both the grids display data of a single person,i want
details in a consecutive manner not repeating.

        </Content>
          <View style={{backgroundColor: 'white'}}>
           <Text style={{color: 'black',fontSize: 17,marginTop: 25,marginLeft: 15}}>Employees</Text>
          </View>
          <List dataArray={currentContext.props.employeeList}
            renderRow={(data) =>
              <ListItem>
                {this.renderRow(data)}
              </ListItem>
           } />
          </Content>

The function renderRow(data) is given by

renderRow(data){
  return(
    typeOne()
  )
  function typeOne(){
    return(
      <View style={styles.gridContainer}>
        <Content contentContainerStyle={{
            padding:6,
            paddingBottom:0
          }}>
        <View style={{flex:1,}}>
            <Row>
              {renderCell(data.photo_url, 0,data.name)}
              {renderCell(data.photo_url, 1,data.name)}
            </Row>
        </View>
          </Content>
      </View>
    )
   function renderCell(bg,pos,title){
      if (pos%2==0) {
        return(
          <Col style={[{marginRight:3},styles.colStyle]}>
            {cellContent(bg,title)}
          </Col>
        )
      }else{
        return(
          <Col style={[{marginLeft:3},styles.colStyle]}>
            {cellContent(bg,title)}
          </Col>
        )
      }
      function cellContent(bg,title){
        if(bg==null){
          return null
        }
        return(
          <Button style={{flex:1,alignSelf:'stretch'}} underLayouColor='red'>
            <View style={styles.cellContent}>
              <Image style={{height:230,alignItems: 'stretch'}} source={{uri:bg}} blurRadius={1}/>
              <View style={[styles.cellTitleBg,{opacity: 0.5,marginTop: 10}]}>
              <Text style={[styles.cellTitle,{position:'absolute',bottom:0,right:5}]}>{title}</Text>
              </View>
            </View>
          </Button>
        )
      }
    }
  }
}

How can get the list-view to return 2 data's per row ?

I will give you similar question for reference in the below link

ListView grid in React Native

please help me solve this issue.

The style part

const styles = StyleSheet.create({
    container: {
        flex:1,
        backgroundColor:'white',
    },
    button:{
        color:'white'
    },
    overLayView: {
        position:'absolute',
        alignSelf:'center',

    },
    gridContainer: {backgroundColor:'#EDF0F2',flex:1,},
    colStyle:{height:210,flex:1,marginBottom:6,marginRight:10,marginLeft:10},
    cellContent:{position:'absolute',left:0,right:0,top:0,bottom:0},
    cellTitleBg:{bottom:65,backgroundColor:'#778899',height:35},
    cellTitle:{bottom:65,color:'white',fontWeight:'bold',fontSize:17,right:0,textAlign:'right',right:0}
})

Body:
Try this out...

pass index from the renderRow function down to this function where this view is defined.

<Button key={index} style={{flex:1,alignSelf:'stretch'}} underLayouColor='red'>
            <View key={index} style={styles.cellContent}>
              <Image key={index} style={{height:230,alignItems: 'stretch'}} source={{uri:bg}} blurRadius={1}/>
              <View key={index} style={[styles.cellTitleBg,{opacity: 0.5,marginTop: 10}]}>
              <Text key={index} style={[styles.cellTitle,{position:'absolute',bottom:0,right:5}]}>{title}</Text>
              </View>
            </View>
          </Button>


问:
taking multiple inputs in a specific format as a single input in java
I have been using the scanner so far for taking inputs in java but what i need for this particular task is setting values for 4 variables with a single line input i.e.  07:05:45PM

The C equivalent solution for this particular solution is as follows:

```<code>scanf("%d:%d:%d%s", &hh, &mm, &ss, t12) ;
</code>```

I am looking for the java equivalent of this code.

答:
You can try delimiter option in scanner, but it will not support multiple delimiters together. So it will not support your requirement of ""%d:%d:%d%s"" fully.

Please have a look at

How to read comma separated integer inputs in java

Just curious to know, why don't you look at the SimpleDateFormatter to parse the single string and get hour, minutes, seconds

Body:
I have been using the scanner so far for taking inputs in java but what i need for this particular task is setting values for 4 variables with a single line input i.e.  07:05:45PM

The C equivalent solution for this particular solution is as follows:

scanf("%d:%d:%d%s", &hh, &mm, &ss, t12) ;

I am looking for the java equivalent of this code.


问:
Why apprend("

")is so strange
I got a problem with append in jquery

When i write the code like

```<code><script>
  $(document).ready(function(){
    for(var a=0;a<5;a++){
          var u=$("#nav").append("<li >a_"+a);
               u.append("<ul>");
                   for(var b=0;b<5;b++){
                       u.append("<li>b_"+b+"</li>");
                   }
                u.append("</ul>")

          $("#nav").append("</li>")
     }
    });

 </script>
  <div class="section-tree">
  <ul id="nav"></ul>         </div>
</code>```

It output like:

Is not what i want

What i want is:

```<code>  <ul>

   <li>
    a_0
      <ul>
         <li>b_1</li>
         <li>b_2</li>
         <li>b_3</li>
         <li>b_4</li>
         <li>b_5</li>
      </ul>
   </li>

   <li>
   a_1
      <ul>
        <li>b_1</li>
        <li>b_2</li>
        <li>b_3</li>
        <li>b_4</li>
        <li>b_5</li>
      </ul>
  </li>
        ...
</ul>
</code>```

why it's not right?

hellowworld
hellowworld
hellowworld
hellowworld

答:
.append() append complete elements, You should create DOM element and then append it. Here is an example

Use

$(document).ready(function() {
  for (var a = 0; a < 5; a++) {
    //Create LI elementFromPoint
    var li = $("
a_" + a + "
");

    //Create Sub UL
    var u = $("
");
    for (var b = 0; b < 5; b++) {
      u.append("
b_" + b + "
");
    }

    //Append Sub UL ti LI
    li.append(u);

    //Append li
    $("#nav").append(li)
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="section-tree">
  <ul id="nav"></ul>
</div></code>```

Title: Why apprend("<ul><li>")is so strange

Body:
I got a problem with append in jquery

When i write the code like

It output like:

Is not what i want

What i want is:

    a_0

b_1

b_2

b_3

b_4

b_5

   a_1

b_1

b_2

b_3

b_4

b_5

        ...

why it's not right?

hellowworld
hellowworld
hellowworld
hellowworld

Body:
.append() append complete elements, You should create DOM element and then append it. Here is an example

Use

$(document).ready(function() {
  for (var a = 0; a < 5; a++) {
    //Create LI elementFromPoint
    var li = $("<li >a_" + a + "</li>");

    //Create Sub UL
    var u = $("<ul>");
    for (var b = 0; b < 5; b++) {
      u.append("<li>b_" + b + "</li>");
    }

    //Append Sub UL ti LI
    li.append(u);

    //Append li
    $("#nav").append(li)
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="section-tree">
  <ul id="nav"></ul>
</div>


问:
What are the most common SQL anti-patterns?
All of us who work with relational databases have learned (or are learning) that SQL  is different. Eliciting the desired results, and doing so efficiently, involves a tedious process partly characterized by learning unfamiliar paradigms, and finding out that some of our most familiar  programming patterns don't work here. What are the common antipatterns you've seen (or yourself committed)?</p>

答:
Joining redundant tables into a query like this:</p>

```<code>select emp.empno, dept.deptno
from emp
join dept on dept.deptno = emp.deptno;
</code>```

OwnerDisplayName: doofledorfer

LastEditorDisplayName: le dorfier

Body:
Joining redundant tables into a query like this:

select emp.empno, dept.deptno
from emp
join dept on dept.deptno = emp.deptno;

OwnerDisplayName: Tony Andrews


问:
How can I strip punctuation from a string?
For the hope-to-have-an-answer-in-30-seconds part of this question, I'm specifically looking for C#

But in the general case, what's the best way to strip punctuation in any language?

I should add: Ideally, the solutions won't require you to enumerate all the possible punctuation marks.

Related: Strip Punctuation in Python

OwnerDisplayName: AviewAnew

LastEditorDisplayName: AviewAnew

Body: $newstr=ereg_replace("[[:punct:]]",'',$oldstr);


问:
Python iterating through a short spreadsheet and copying matching values into a large spreadsheet
I'm working with pandas, trying to use a list of devices, device_master.xlsx, to automatically fill a number of columns in my main spreadsheet, detailed_billing.xlsx.

I can read the contents of both sheets, and I can make other transformations to my main spreadsheet, but I'm new to this and I can't figure out how to iterate through each line of device_master.xlsx sheet and compare it to/ populate the required columns in my main sheet.

So far what I'm doing to the rest of the sheet looks like this:

```<code>import numpy as np
import pandas as pd
import csv
#import re

# import the list of devices with work order numbers and project codes:

devmaster_xls = pd.read_excel('device_master.xlsx', 'device master', header = [0], index_col = None)
print('Device Master sheet columns:', devmaster_xls.columns, '\n') #debug, check the columns are right

# import the billing information which will need transforming with work order/ project codes:

data_xls = pd.read_excel('DetailedBilling.xlsx', 'Sheet1', header = [0], index_col = None)
print('Billing sheet columns read in:', data_xls.columns, '\n') #debug, check the columns before

data_xls.insert(13, 'WO Ref', '')
data_xls.insert(14, 'WO Description', '')
data_xls.insert(15, 'Project Code', '')

print('Billing sheet columns with WO additions:',
data_xls.columns, '\n') #debug, check the columns after

wait = input("Press enter to continue...")

# magic sauce to add work order and cost tracking goes in here
# magic sauce to add work order and cost tracking goes in here
#

data_writer = pd.ExcelWriter('DetailedBilling_edit.xlsx', engine = 'xlsxwriter')
data_xls.to_excel(data_writer, index = False)

#defining the book/sheet to work with
workbook = data_writer.book
worksheet = data_writer.sheets['Sheet1']

# formatting changes
worksheet.set_zoom(85)

server_fmt = workbook.add_format({'font_color': '#800000', 'bold': True})
dollar_fmt = workbook.add_format({'num_format': """_($* #,##0.00_);_($* -#,##0.00;_($* "0.00"_);_(@_)""", 'bold': True})
bold_fmt = workbook.add_format({'bold': True})

worksheet.set_column('A:A', 34, server_fmt)
worksheet.set_column('B:B', 85)
worksheet.set_column('F:F', 28)
worksheet.set_column('G:G', 9)
worksheet.set_column('H:K', 11, dollar_fmt)
worksheet.set_column('L:P', 12.5)
worksheet.set_column('O:O', 85)

#
#what size is this sheet?
count_row = len(data_xls.index)
#count_row = data_xls.shape[0]
print("Total rows: ", count_row, '\n')

data_writer.save()
</code>```

What I want to say is something like:

```<code>data_xls['WO Ref'].loc[(data_xls['Server'] = devmaster_xls['Device Name'])] = devmaster_xls['WO Ref']
</code>```

I've tried putting it in a loop but haven't gotten very far with it - any assistance would be appreciated!

EDIT: Thanks to @frankyjuang I'm getting the right data, which is great, but for some reason I can't get it to write into the spreadsheet. I do this:

```<code>>>> for index, row in data_xls.iterrows():
... rowdata = devmaster_xls.loc[devmaster_xls['Device Name'] == row['Server']]
... print(index, rowdata['WO Ref'])
</code>```

it looks good, returning something like:

```<code>555 19    REF###
Name: WO Ref, dtype: object
556 19    REF###
Name: WO Ref, dtype: object
557 19    REF###
Name: WO Ref, dtype: object
558 19    REF###
Name: WO Ref, dtype: object
559 19    REF###
Name: WO Ref, dtype: object
560 19    REF###
Name: WO Ref, dtype: object
561 19    REF###
Name: WO Ref, dtype: object
562 19    REF###
Name: WO Ref, dtype: object
563 19    REF###
Name: WO Ref, dtype: object
</code>```

I'm trying to insert with this:

```<code>>>> for index, row in data_xls.iterrows():
... rowdata = devmaster_xls.loc[devmaster_xls['Device Name'] == row['Server']]
... row['WO Ref'] = rowdata['WO Ref']
</code>```

But print(data_xls['WO Ref']) shows the rows are NaN.

答:
Due to my inexperience, I was struggling with the answer @frankyjuang provided - I couldn't fit my head around the results that I was getting versus what I wanted to achieve. So, after more research, I came up with the following solution, which has solved the problem:

First, we will need to index both spreadsheets with a shared key. In this case, it's the servernames, in the format servername1.com, servername2.com, etc. But - I don't want to permanently alter my dataframe, so instead, will create a new column which can be used as the index.

This copies the server column, converts it to lowercase to account for any case mismatches later, and sets it as the index:

```<code>data_xls['Serverindex'] = data_xls['Server'].str.lower()
data_xls.set_index('Serverindex', inplace = True)
</code>```

Grabbing my device master sheet:

```<code>devmaster_xls = pd.read_excel('device_master.xlsx', 'device master', header = [0], index_col = None)
</code>```

And as above, creating the index from an existing column, converting it to lowercase on the way:

```<code>devmaster_xls['Devindex'] = devmaster_xls['Device Name'].str.lower()
devmaster_xls.set_index('Devindex', inplace = True)
</code>```

Then copying the relevant data from the device master sheet into the main sheet is as simple as:

```<code>data_xls.loc[:,'WO Ref'] = devmaster_xls.loc[:,'WO Ref']
data_xls.loc[:,'WO Description'] = devmaster_xls.loc[:,'WO Description']
data_xls.loc[:,'Project Code'] = devmaster_xls.loc[:,'Project code']
</code>```

Finally, we don't want to write out that index, so:

```<code>data_xls = data_xls.reset_index(drop = True)
devmaster_xls = devmaster_xls.reset_index(drop = True)
</code>```

If this method is really bad practice, I'd be interested to find out why, and what I could do to improve it. However it did solve the problem and is quick to implement!

Body:
I'm working with pandas, trying to use a list of devices, device_master.xlsx, to automatically fill a number of columns in my main spreadsheet, detailed_billing.xlsx.

I can read the contents of both sheets, and I can make other transformations to my main spreadsheet, but I'm new to this and I can't figure out how to iterate through each line of device_master.xlsx sheet and compare it to/ populate the required columns in my main sheet.

So far what I'm doing to the rest of the sheet looks like this:

import numpy as np
import pandas as pd
import csv
#import re

# import the list of devices with work order numbers and project codes:

devmaster_xls = pd.read_excel('device_master.xlsx', 'device master', header = [0], index_col = None)
print('Device Master sheet columns:', devmaster_xls.columns, '\n') #debug, check the columns are right

# import the billing information which will need transforming with work order/ project codes:

data_xls = pd.read_excel('DetailedBilling.xlsx', 'Sheet1', header = [0], index_col = None)
print('Billing sheet columns read in:', data_xls.columns, '\n') #debug, check the columns before

data_xls.insert(13, 'WO Ref', '')
data_xls.insert(14, 'WO Description', '')
data_xls.insert(15, 'Project Code', '')

print('Billing sheet columns with WO additions:',
data_xls.columns, '\n') #debug, check the columns after

wait = input("Press enter to continue...")

# magic sauce to add work order and cost tracking goes in here
# magic sauce to add work order and cost tracking goes in here
#

data_writer = pd.ExcelWriter('DetailedBilling_edit.xlsx', engine = 'xlsxwriter')
data_xls.to_excel(data_writer, index = False)

#defining the book/sheet to work with
workbook = data_writer.book
worksheet = data_writer.sheets['Sheet1']

# formatting changes
worksheet.set_zoom(85)

server_fmt = workbook.add_format({'font_color': '#800000', 'bold': True})
dollar_fmt = workbook.add_format({'num_format': """_($* #,##0.00_);_($* -#,##0.00;_($* "0.00"_);_(@_)""", 'bold': True})
bold_fmt = workbook.add_format({'bold': True})

worksheet.set_column('A:A', 34, server_fmt)
worksheet.set_column('B:B', 85)
worksheet.set_column('F:F', 28)
worksheet.set_column('G:G', 9)
worksheet.set_column('H:K', 11, dollar_fmt)
worksheet.set_column('L:P', 12.5)
worksheet.set_column('O:O', 85)

#
#what size is this sheet?
count_row = len(data_xls.index)
#count_row = data_xls.shape[0]
print("Total rows: ", count_row, '\n')

data_writer.save()

What I want to say is something like:

data_xls['WO Ref'].loc[(data_xls['Server'] = devmaster_xls['Device Name'])] = devmaster_xls['WO Ref']

I've tried putting it in a loop but haven't gotten very far with it - any assistance would be appreciated!

EDIT: Thanks to @frankyjuang I'm getting the right data, which is great, but for some reason I can't get it to write into the spreadsheet. I do this:

>>> for index, row in data_xls.iterrows():
... rowdata = devmaster_xls.loc[devmaster_xls['Device Name'] == row['Server']]
... print(index, rowdata['WO Ref'])

it looks good, returning something like:

555 19    REF###
Name: WO Ref, dtype: object
556 19    REF###
Name: WO Ref, dtype: object
557 19    REF###
Name: WO Ref, dtype: object
558 19    REF###
Name: WO Ref, dtype: object
559 19    REF###
Name: WO Ref, dtype: object
560 19    REF###
Name: WO Ref, dtype: object
561 19    REF###
Name: WO Ref, dtype: object
562 19    REF###
Name: WO Ref, dtype: object
563 19    REF###
Name: WO Ref, dtype: object

I'm trying to insert with this:

>>> for index, row in data_xls.iterrows():
... rowdata = devmaster_xls.loc[devmaster_xls['Device Name'] == row['Server']]
... row['WO Ref'] = rowdata['WO Ref']

But print(data_xls['WO Ref']) shows the rows are NaN.

Body:
Due to my inexperience, I was struggling with the answer @frankyjuang provided - I couldn't fit my head around the results that I was getting versus what I wanted to achieve. So, after more research, I came up with the following solution, which has solved the problem:

First, we will need to index both spreadsheets with a shared key. In this case, it's the servernames, in the format servername1.com, servername2.com, etc. But - I don't want to permanently alter my dataframe, so instead, will create a new column which can be used as the index.

This copies the server column, converts it to lowercase to account for any case mismatches later, and sets it as the index:

data_xls['Serverindex'] = data_xls['Server'].str.lower()
data_xls.set_index('Serverindex', inplace = True)

Grabbing my device master sheet:

devmaster_xls = pd.read_excel('device_master.xlsx', 'device master', header = [0], index_col = None)

And as above, creating the index from an existing column, converting it to lowercase on the way:

devmaster_xls['Devindex'] = devmaster_xls['Device Name'].str.lower()
devmaster_xls.set_index('Devindex', inplace = True)

Then copying the relevant data from the device master sheet into the main sheet is as simple as:

data_xls.loc[:,'WO Ref'] = devmaster_xls.loc[:,'WO Ref']
data_xls.loc[:,'WO Description'] = devmaster_xls.loc[:,'WO Description']
data_xls.loc[:,'Project Code'] = devmaster_xls.loc[:,'Project code']

Finally, we don't want to write out that index, so:

data_xls = data_xls.reset_index(drop = True)
devmaster_xls = devmaster_xls.reset_index(drop = True)

If this method is really bad practice, I'd be interested to find out why, and what I could do to improve it. However it did solve the problem and is quick to implement!


问:
Bitbucket Pull Not working suddenly
When tried to pull the repo today, it say below error, but last several months it was working. Have tried with Bitbucket website, but no info about it. Is anyone in facing the same? Is Atalassian provided any work around for it?</p>

```<code> sudo git pull

Password for 'https://stutzen@bitbucket.org':
remote: Repositories on team accounts can only be accessed through a team member. Using a team password is not allowed.
</code>```

答:
In the "url = " line of the .git/config file, you'll want to edit the 'USERNAME' portion as in the example below to be your new individual user id.

```<code>[remote "origin"]
    url = https://USERNAME@bitbucket.org/TEAM_ID/REPO_SLUG
    fetch = +refs/heads/*:refs/remotes/origin/*
[remote "origin"]
    url = https://USERNAME@bitbucket.org/TEAM_ID/REPO_SLUG
    fetch = +refs/heads/*:refs/remotes/origin/*
</code>```

Source: https://confluence.atlassian.com/bbkb/team-account-changes-454361799.html

Title: Bitbucket Pull Not working suddenly

Body:
When tried to pull the repo today, it say below error, but last several months it was working. Have tried with Bitbucket website, but no info about it. Is anyone in facing the same? Is Atalassian provided any work around for it?

 sudo git pull

Password for 'https://stutzen@bitbucket.org':
remote: Repositories on team accounts can only be accessed through a team member. Using a team password is not allowed.

Body:
In the "url = " line of the .git/config file, you'll want to edit the 'USERNAME' portion as in the example below to be your new individual user id.

[remote "origin"]
    url = https://USERNAME@bitbucket.org/TEAM_ID/REPO_SLUG
    fetch = +refs/heads/*:refs/remotes/origin/*
[remote "origin"]
    url = https://USERNAME@bitbucket.org/TEAM_ID/REPO_SLUG
    fetch = +refs/heads/*:refs/remotes/origin/*

Source: https://confluence.atlassian.com/bbkb/team-account-changes-454361799.html


问:
How to dynamically generate a list of classes with commas separating them?
I'm working with the SCSS syntax of SASS to create a dynamic grid system but I've hit a snag.

I'm trying to make the grid system completely dynamic like this:

```<code>$columns: 12;
</code>```

then I create the columns like this:

```<code>@mixin col-x {
  @for $i from 1 through $columns {
  .col-#{$i} { width: $column-size * $i; }
  }
}
</code>```

Which outputs:

```<code>.col-1 {
    width: 4.16667%;
  }

.col-2 {
    width: 8.33333%;
}
etc...
</code>```

This works well but what I want to do next is dynamically generate a long list of column classes separated by commas based on the number of $columns chosen - e.g I want it to look like this:

```<code>.col-1,
.col-2,
.col-3,
.col-4,
 etc... {
float: left;
}
</code>```

I've tired this:

```<code>@mixin col-x-list {
  @for $i from 1 through $columns - 1 {
  .col-#{$i}-m { float: left; }
  }
}
</code>```

but the output is this:

```<code>.col-1 {
  float: left;
}
.col-2 {
  float: left;
}
etc...
</code>```

I'm a little stuck on the logic here as well as the SCSS syntax required to create something like this.

Does anyone have any ideas?

答:
thnx to @davidtheclark here is a more generic version:

```<code>@mixin attr-x($attr, $attr-count: 10, $attr-steps: 10, $unit: '%') {
    $attr-list: null;
    @for $i from 1 through $attr-count {
        $attr-value: $attr-steps * $i;

        .#{$attr}#{$attr-value} {
            #{$attr}: #{$attr-value}#{$unit};
        }

        $attr-list: append($attr-list, unquote(".#{$attr}-#{$attr-value}"), comma);
    }

    #{$attr-list} {
        //append style to all classes
    }
}
</code>```

Use it like this:

```<code>@include attr-x('margin-left', 6, 5, 'px');
//or
@include attr-x('width');
</code>```

The result looks like this:

```<code>.margin-left5 {
  margin-left: 5px; }

.margin-left10 {
  margin-left: 10px; }

...

.margin-left30 {
  margin-left: 30px; }

.width10 {
  width: 10%; }

.width20 {
  width: 20%; }

...

.width100 {
  width: 100%; }
</code>```

Body:
I'm working with the SCSS syntax of SASS to create a dynamic grid system but I've hit a snag.

I'm trying to make the grid system completely dynamic like this:

$columns: 12;

then I create the columns like this:

@mixin col-x {
  @for $i from 1 through $columns {
  .col-#{$i} { width: $column-size * $i; }
  }
}

Which outputs:

.col-1 {
    width: 4.16667%;
  }

.col-2 {
    width: 8.33333%;
}
etc...

This works well but what I want to do next is dynamically generate a long list of column classes separated by commas based on the number of $columns chosen - e.g I want it to look like this:

.col-1,
.col-2,
.col-3,
.col-4,
 etc... {
float: left;
}

I've tired this:

@mixin col-x-list {
  @for $i from 1 through $columns - 1 {
  .col-#{$i}-m { float: left; }
  }
}

but the output is this:

.col-1 {
  float: left;
}
.col-2 {
  float: left;
}
etc...

I'm a little stuck on the logic here as well as the SCSS syntax required to create something like this.

Does anyone have any ideas?

Body:
thnx to @davidtheclark here is a more generic version:

@mixin attr-x($attr, $attr-count: 10, $attr-steps: 10, $unit: '%') {
    $attr-list: null;
    @for $i from 1 through $attr-count {
        $attr-value: $attr-steps * $i;

        .#{$attr}#{$attr-value} {
            #{$attr}: #{$attr-value}#{$unit};
        }

        $attr-list: append($attr-list, unquote(".#{$attr}-#{$attr-value}"), comma);
    }

    #{$attr-list} {
        //append style to all classes
    }
}

Use it like this:

@include attr-x('margin-left', 6, 5, 'px');
//or
@include attr-x('width');

The result looks like this:

.margin-left5 {
  margin-left: 5px; }

.margin-left10 {
  margin-left: 10px; }

...

.margin-left30 {
  margin-left: 30px; }

.width10 {
  width: 10%; }

.width20 {
  width: 20%; }

...

.width100 {
  width: 100%; }