问:
CGImage to MPSTexture or MPSImage
I have an CGImage which is constructed out of a CVPixelbuffer (ARGB). I want to convert that CGImage into a MTLTexture. I use:

```<code>  let texture: MTLTexture = try m_textureLoader.newTexture(with: cgImage, options: [MTKTextureLoaderOptionSRGB : NSNumber(value: true)] )
</code>```

Later I want to use the texture in an MPSImage having 3 channels:

```<code>let sid   = MPSImageDescriptor(channelFormat: MPSImageFeatureChannelFormat.float16, width: 40, height: 40, featureChannels: 3)
preImage    = MPSTemporaryImage(commandBuffer:  commandBuffer, imageDescriptor: sid)
lanczos.encode(commandBuffer: commandBuffer, sourceTexture: texture!, destinationTexture: preImage.texture)
scale.encode  (commandBuffer: commandBuffer, sourceImage: preImage, destinationImage: srcImage)
</code>```

Now my questions:
How does textureLoader.newTexture(...) map the four ARGB channels to the 3 channels specified in the MPSImageDescriptor ?
How can I ensure that the RGB components are used and not e.g. ARG ?
Is there a way to specify that channel mapping ?

Thanks, Chris

答:
Why not construct the MTLTexture from the CVPixelBuffer directly? Is much quicker!

Do this once at the beginning of your program:

```<code>// declare this somewhere, so we can re-use it
var textureCache: CVMetalTextureCache?

// create the texture cache object
guard CVMetalTextureCacheCreate(kCFAllocatorDefault, nil, device, nil, &textureCache) == kCVReturnSuccess else {
  print("Error: could not create a texture cache")
  return false
}
</code>```

Do this once your have your CVPixelBuffer:

```<code>let width = CVPixelBufferGetWidth(pixelBuffer)
let height = CVPixelBufferGetHeight(pixelBuffer)

var texture: CVMetalTexture?
CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault, textureCache,
      pixelBuffer, nil, .bgra8Unorm, width, height, 0, &texture)

if let texture = texture {
  metalTexture = CVMetalTextureGetTexture(texture)
}
</code>```

Now metalTexture contains an MTLTexture object with the contents of the CVPixelBuffer.

Title: CGImage to MPSTexture or MPSImage

Body:
I have an CGImage which is constructed out of a CVPixelbuffer (ARGB). I want to convert that CGImage into a MTLTexture. I use:

  let texture: MTLTexture = try m_textureLoader.newTexture(with: cgImage, options: [MTKTextureLoaderOptionSRGB : NSNumber(value: true)] )

Later I want to use the texture in an MPSImage having 3 channels:

let sid   = MPSImageDescriptor(channelFormat: MPSImageFeatureChannelFormat.float16, width: 40, height: 40, featureChannels: 3)
preImage    = MPSTemporaryImage(commandBuffer:  commandBuffer, imageDescriptor: sid)
lanczos.encode(commandBuffer: commandBuffer, sourceTexture: texture!, destinationTexture: preImage.texture)
scale.encode  (commandBuffer: commandBuffer, sourceImage: preImage, destinationImage: srcImage)

Now my questions:
How does textureLoader.newTexture(...) map the four ARGB channels to the 3 channels specified in the MPSImageDescriptor ?
How can I ensure that the RGB components are used and not e.g. ARG ?
Is there a way to specify that channel mapping ?

Thanks, Chris

Body:
Why not construct the MTLTexture from the CVPixelBuffer directly? Is much quicker!

Do this once at the beginning of your program:

// declare this somewhere, so we can re-use it
var textureCache: CVMetalTextureCache?

// create the texture cache object
guard CVMetalTextureCacheCreate(kCFAllocatorDefault, nil, device, nil, &textureCache) == kCVReturnSuccess else {
  print("Error: could not create a texture cache")
  return false
}

Do this once your have your CVPixelBuffer:

let width = CVPixelBufferGetWidth(pixelBuffer)
let height = CVPixelBufferGetHeight(pixelBuffer)

var texture: CVMetalTexture?
CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault, textureCache,
      pixelBuffer, nil, .bgra8Unorm, width, height, 0, &texture)

if let texture = texture {
  metalTexture = CVMetalTextureGetTexture(texture)
}

Now metalTexture contains an MTLTexture object with the contents of the CVPixelBuffer.


来源: stackexchange

问:
How to add a custom button on an item that does not have Stock?
I'm working with Wordpress and WooCommerce, I need to add a contact button if in my store some product runs out of stock, ie:

If Stock is 0, show me a contact button.

The following image looks more specific about where I want to insert it:

I have found out how to add the button, but it is added to all the products, and I just want the button to appear when I have no stock on any of my products.
Here is the code used:

```<code>add_action('woocommerce_after_add_to_cart_button', 'boton_subasta');
function boton_subasta(){
     global $product;
    if ( ! $product->is_in_stock()){

        echo '<button type="submit" class="button alt" onclick="window.location.href=http://http://138.197.9.71/prov-individuales/">contacto</button>';
    }
}
</code>```

答:
Solved :

I have already found a solution thanks to all of you, who have taken me on a good research path, use the following code:

```<code>add_action( 'woocommerce_single_product_summary', 'boton_sub_producto_single', 6 );
function boton_sub_producto_single() {
        global $product;
            if ( ! $product->is_in_stock() || ! $product->is_purchasable() ){
                echo '<button type="submit" class="button alt" onclick="window.location.href=http://http://138.197.9.71/prov-individuales/">contacto</button>';
            }
            return $product;
    }
</code>```

It work for me .

ContentLicense: CC BY-SA 4.0

Body:
I'm working with Wordpress and WooCommerce, I need to add a contact button if in my store some product runs out of stock, ie:

If Stock is 0, show me a contact button.

The following image looks more specific about where I want to insert it:

I have found out how to add the button, but it is added to all the products, and I just want the button to appear when I have no stock on any of my products.
Here is the code used:

add_action('woocommerce_after_add_to_cart_button', 'boton_subasta');
function boton_subasta(){
     global $product;
    if ( ! $product->is_in_stock()){

        echo '<button type="submit" class="button alt" onclick="window.location.href=http://http://138.197.9.71/prov-individuales/">contacto</button>';
    }
}

Body:
Solved :

I have already found a solution thanks to all of you, who have taken me on a good research path, use the following code:

add_action( 'woocommerce_single_product_summary', 'boton_sub_producto_single', 6 );
function boton_sub_producto_single() {
        global $product;
            if ( ! $product->is_in_stock() || ! $product->is_purchasable() ){
                echo '<button type="submit" class="button alt" onclick="window.location.href=http://http://138.197.9.71/prov-individuales/">contacto</button>';
            }
            return $product;
    }

It work for me .

ContentLicense: CC BY-SA 3.0


问:
Run time segmentation fault for std::basicstring in multi threaded C++ ignite process
I am facing a segmentation fault in the run time of the process, that is random but observed that this happens only when I start the process with more that 3 threads, with another ignite node up.

here is the code that i am using:

```<code>    namespace ignite
{
 struct CacheSubData
   {
   std::string data1;
   char IMSI[21];
   CacheSubData() :
 data1()
   {
 // No-op.
 data1.assign(1024, 'b');
 sprintf(IMSI, "9876543210");
   }
   };

   struct CacheData
   {
 std::string data;
 char TxnNumber[50];
 int count;
 CacheSubData mCacheSubData;
 CacheData() :
   data()
 {
   // No-op.
   data.assign(1024, 'a');
   sprintf(TxnNumber, "abcdefghijklmnopqrstuvwxyz1234567890");
   count = 100;
 }
   };
}

namespace ignite
{
  namespace binary
  {
  template <>
 struct BinaryType<CacheSubData>
 {
   IGNITE_BINARY_GET_TYPE_ID_AS_HASH("CacheSubData")

   IGNITE_BINARY_GET_TYPE_NAME_AS_IS("CacheSubData")

   IGNITE_BINARY_GET_FIELD_ID_AS_HASH

   static int32_t GetHashCode(ignite::CacheSubData obj)
   {
 return 0;
   }

   static bool IsNull(ignite::CacheSubData obj)
   {
   return false;
   }

   static void GetNull(ignite::CacheSubData& dst)
   {
   dst = ignite::CacheSubData();
   }

   static void Write(BinaryWriter& writer, const ignite::CacheSubData& obj)
   {
   writer.WriteString("IMSI", obj.IMSI);
   }

   static void Read(BinaryReader& reader, ignite::CacheSubData& dst)
   {
   sprintf(dst.IMSI, "%s", (char*)reader.ReadString("IMSI").data());

   }
 };

  template <>
 struct BinaryType<CacheData>
 {
   IGNITE_BINARY_GET_TYPE_ID_AS_HASH("CacheData")

   IGNITE_BINARY_GET_TYPE_NAME_AS_IS("CacheData")

   IGNITE_BINARY_GET_FIELD_ID_AS_HASH

   static int32_t GetHashCode(ignite::CacheData obj)
   {
 return 0;
   }
   static bool IsNull(ignite::CacheData obj)
   {
   return false;
   }

   static void GetNull(ignite::CacheData& dst)
   {
   dst = ignite::CacheData();
   }

   static void Write(BinaryWriter& writer, const ignite::CacheData& obj)
   {
   writer.WriteInt32("count", obj.count);
   writer.WriteString("TxnNumber", obj.TxnNumber);
   BinaryType<CacheSubData>::Write(writer, obj.mCacheSubData);
   }

   static void Read(BinaryReader& reader, ignite::CacheData& dst)
   {
   dst.count = reader.ReadInt32("count");
   sprintf(dst.TxnNumber, "%s", (char*)reader.ReadString("TxnNumber").data());
   BinaryType<CacheSubData>::Read(reader, dst.mCacheSubData);

   }
 };
  }
  }
</code>```

The error thrown by the JVM is:

```<code># A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x00007ff4b8373f48, pid=32201, tid=0x00007ff462309700
#
# JRE version: Java(TM) SE Runtime Environment (8.0_131-b11) (build 1.8.0_131-b11)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.131-b11 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# C  [libstdc++.so.6+0xbef48]  std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::string const&)+0x18
#
# Core dump written. Default location: /home/ignite/core or core.32201
#
# An error report file with more information is saved as:
# /home/ignite/hs_err_pid32201.log
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
</code>```

It created the core file on doing break through found these stack trace:

```<code>#0  0x00007ff4b7a111d7 in raise () from /lib64/libc.so.6
#1  0x00007ff4b7a128c8 in abort () from /lib64/libc.so.6
#2  0x00007ff4b730f3b5 in os::abort(bool) () from /usr/java/default/jre/lib/amd64/server/libjvm.so
#3  0x00007ff4b74b1673 in VMError::report_and_die() () from /usr/java/default/jre/lib/amd64/server/libjvm.so
#4  0x00007ff4b73148bf in JVM_handle_linux_signal () from /usr/java/default/jre/lib/amd64/server/libjvm.so
#5  0x00007ff4b730ae13 in signalHandler(int, siginfo*, void*) () from /usr/java/default/jre/lib/amd64/server/libjvm.so
#6  <signal handler called>
#7  0x00007ff4b8373f48 in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::string const&) () from /lib64/libstdc++.so.6
#8  0x00007ff4b87f3ff7 in ignite::impl::binary::BinaryTypeSnapshot::BinaryTypeSnapshot (this=0x7ff47c028bd0, another=...)
at src/impl/binary/binary_type_snapshot.cpp:39
#9  0x00007ff4b87f1530 in ignite::impl::binary::BinaryTypeHandler::OnFieldWritten (this=0x7ff47c028a40, fieldId=fieldId@entry=94851343,
fieldName="count", fieldTypeId=fieldTypeId@entry=3) at src/impl/binary/binary_type_handler.cpp:40
#10 0x00007ff4b87f28cc in ignite::impl::binary::BinaryWriterImpl::WriteFieldId (this=this@entry=0x7ff462308b90,
fieldName=fieldName@entry=0x404e40 "count", fieldTypeId=fieldTypeId@entry=3) at src/impl/binary/binary_writer_impl.cpp:682
#11 0x00007ff4b87f2fc0 in WritePrimitive<int> (func=<optimized out>, typ=3 '\003', len=4, val=100, fieldName=0x404e40 "count",
this=0x7ff462308b90) at ./include/ignite/impl/binary/binary_writer_impl.h:868
#12 ignite::impl::binary::BinaryWriterImpl::WriteInt32 (this=0x7ff462308b90, fieldName=0x404e40 "count", val=100)
at src/impl/binary/binary_writer_impl.cpp:140
#13 0x0000000000404b27 in ignite::impl::In2Operation<double, ignite::CacheData>::ProcessInput(ignite::impl::binary::BinaryWriterImpl&) ()
#14 0x00007ff4b8c34d81 in ignite::impl::interop::InteropTarget::WriteTo (this=this@entry=0x7ff47c028050, mem=0x7ff47c0265c0, inOp=...,
err=...) at src/impl/interop/interop_target.cpp:54
#15 0x00007ff4b8c3525a in ignite::impl::interop::InteropTarget::OutOp (this=0x7ff47c028050, opType=26, inOp=..., err=...)
at src/impl/interop/interop_target.cpp:94
#16 0x000000000040406e in func(void*) ()
#17 0x00007ff4b8e48dc5 in start_thread () from /lib64/libpthread.so.0
#18 0x00007ff4b7ad376d in clone () from /lib64/libc.so.6
</code>```

答: It seems like it's a known bug and it is fixed in master and is going to be included in upcoming 2.1 release</p>

Body:
I am facing a segmentation fault in the run time of the process, that is random but observed that this happens only when I start the process with more that 3 threads, with another ignite node up.

here is the code that i am using:

    namespace ignite
{
 struct CacheSubData
   {
   std::string data1;
   char IMSI[21];
   CacheSubData() :
 data1()
   {
 // No-op.
 data1.assign(1024, 'b');
 sprintf(IMSI, "9876543210");
   }
   };

   struct CacheData
   {
 std::string data;
 char TxnNumber[50];
 int count;
 CacheSubData mCacheSubData;
 CacheData() :
   data()
 {
   // No-op.
   data.assign(1024, 'a');
   sprintf(TxnNumber, "abcdefghijklmnopqrstuvwxyz1234567890");
   count = 100;
 }
   };
}

namespace ignite
{
  namespace binary
  {
  template <>
 struct BinaryType<CacheSubData>
 {
   IGNITE_BINARY_GET_TYPE_ID_AS_HASH("CacheSubData")

   IGNITE_BINARY_GET_TYPE_NAME_AS_IS("CacheSubData")

   IGNITE_BINARY_GET_FIELD_ID_AS_HASH

   static int32_t GetHashCode(ignite::CacheSubData obj)
   {
 return 0;
   }

   static bool IsNull(ignite::CacheSubData obj)
   {
   return false;
   }

   static void GetNull(ignite::CacheSubData& dst)
   {
   dst = ignite::CacheSubData();
   }

   static void Write(BinaryWriter& writer, const ignite::CacheSubData& obj)
   {
   writer.WriteString("IMSI", obj.IMSI);
   }

   static void Read(BinaryReader& reader, ignite::CacheSubData& dst)
   {
   sprintf(dst.IMSI, "%s", (char*)reader.ReadString("IMSI").data());

   }
 };

  template <>
 struct BinaryType<CacheData>
 {
   IGNITE_BINARY_GET_TYPE_ID_AS_HASH("CacheData")

   IGNITE_BINARY_GET_TYPE_NAME_AS_IS("CacheData")

   IGNITE_BINARY_GET_FIELD_ID_AS_HASH

   static int32_t GetHashCode(ignite::CacheData obj)
   {
 return 0;
   }
   static bool IsNull(ignite::CacheData obj)
   {
   return false;
   }

   static void GetNull(ignite::CacheData& dst)
   {
   dst = ignite::CacheData();
   }

   static void Write(BinaryWriter& writer, const ignite::CacheData& obj)
   {
   writer.WriteInt32("count", obj.count);
   writer.WriteString("TxnNumber", obj.TxnNumber);
   BinaryType<CacheSubData>::Write(writer, obj.mCacheSubData);
   }

   static void Read(BinaryReader& reader, ignite::CacheData& dst)
   {
   dst.count = reader.ReadInt32("count");
   sprintf(dst.TxnNumber, "%s", (char*)reader.ReadString("TxnNumber").data());
   BinaryType<CacheSubData>::Read(reader, dst.mCacheSubData);

   }
 };
  }
  }

The error thrown by the JVM is:

# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x00007ff4b8373f48, pid=32201, tid=0x00007ff462309700
#
# JRE version: Java(TM) SE Runtime Environment (8.0_131-b11) (build 1.8.0_131-b11)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.131-b11 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# C  [libstdc++.so.6+0xbef48]  std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::string const&)+0x18
#
# Core dump written. Default location: /home/ignite/core or core.32201
#
# An error report file with more information is saved as:
# /home/ignite/hs_err_pid32201.log
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.

It created the core file on doing break through found these stack trace:

#0  0x00007ff4b7a111d7 in raise () from /lib64/libc.so.6
#1  0x00007ff4b7a128c8 in abort () from /lib64/libc.so.6
#2  0x00007ff4b730f3b5 in os::abort(bool) () from /usr/java/default/jre/lib/amd64/server/libjvm.so
#3  0x00007ff4b74b1673 in VMError::report_and_die() () from /usr/java/default/jre/lib/amd64/server/libjvm.so
#4  0x00007ff4b73148bf in JVM_handle_linux_signal () from /usr/java/default/jre/lib/amd64/server/libjvm.so
#5  0x00007ff4b730ae13 in signalHandler(int, siginfo*, void*) () from /usr/java/default/jre/lib/amd64/server/libjvm.so
#6  <signal handler called>
#7  0x00007ff4b8373f48 in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::string const&) () from /lib64/libstdc++.so.6
#8  0x00007ff4b87f3ff7 in ignite::impl::binary::BinaryTypeSnapshot::BinaryTypeSnapshot (this=0x7ff47c028bd0, another=...)
at src/impl/binary/binary_type_snapshot.cpp:39
#9  0x00007ff4b87f1530 in ignite::impl::binary::BinaryTypeHandler::OnFieldWritten (this=0x7ff47c028a40, fieldId=fieldId@entry=94851343,
fieldName="count", fieldTypeId=fieldTypeId@entry=3) at src/impl/binary/binary_type_handler.cpp:40
#10 0x00007ff4b87f28cc in ignite::impl::binary::BinaryWriterImpl::WriteFieldId (this=this@entry=0x7ff462308b90,
fieldName=fieldName@entry=0x404e40 "count", fieldTypeId=fieldTypeId@entry=3) at src/impl/binary/binary_writer_impl.cpp:682
#11 0x00007ff4b87f2fc0 in WritePrimitive<int> (func=<optimized out>, typ=3 '\003', len=4, val=100, fieldName=0x404e40 "count",
this=0x7ff462308b90) at ./include/ignite/impl/binary/binary_writer_impl.h:868
#12 ignite::impl::binary::BinaryWriterImpl::WriteInt32 (this=0x7ff462308b90, fieldName=0x404e40 "count", val=100)
at src/impl/binary/binary_writer_impl.cpp:140
#13 0x0000000000404b27 in ignite::impl::In2Operation<double, ignite::CacheData>::ProcessInput(ignite::impl::binary::BinaryWriterImpl&) ()
#14 0x00007ff4b8c34d81 in ignite::impl::interop::InteropTarget::WriteTo (this=this@entry=0x7ff47c028050, mem=0x7ff47c0265c0, inOp=...,
err=...) at src/impl/interop/interop_target.cpp:54
#15 0x00007ff4b8c3525a in ignite::impl::interop::InteropTarget::OutOp (this=0x7ff47c028050, opType=26, inOp=..., err=...)
at src/impl/interop/interop_target.cpp:94
#16 0x000000000040406e in func(void*) ()
#17 0x00007ff4b8e48dc5 in start_thread () from /lib64/libpthread.so.0
#18 0x00007ff4b7ad376d in clone () from /lib64/libc.so.6


问:
Unable to import numpy library in python
I have installed python 3.6 and through pip added numpy module, but getting below error while trying to import the library. Kindly help here:

```<code>>>> import numpy
Traceback (most recent call last):
  File "C:\Users\as338011\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\core\__init__.py", line 16, in
<module>
    from . import multiarray
ImportError: DLL load failed: The specified procedure could not be found.
</code>```

During handling of the above exception, another exception occurred:

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\as338011\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\__init__.py", line 142, in <mod
ule>
    from . import add_newdocs
  File "C:\Users\as338011\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\add_newdocs.py", line 13, in <m
odule>
    from numpy.lib import add_newdoc
  File "C:\Users\as338011\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\lib\__init__.py", line 8, in <m
odule>
    from .type_check import *
  File "C:\Users\as338011\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\lib\type_check.py", line 11, in
 <module>
    import numpy.core.numeric as _nx
  File "C:\Users\as338011\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\core\__init__.py", line 26, in
<module>
    raise ImportError(msg)
ImportError:
Importing the multiarray numpy extension module failed.  Most
likely you are trying to import a failed build of numpy.
If you're working with a numpy git repo, try `git clean -xdf` (removes all
files not under version control).  Otherwise reinstall numpy.
</code>```

Original error was: DLL load failed: The specified procedure could not be found.

答:
As your terminal suggests, you may have installed the incorrect version of numpy. If you're using python 3, you'll want to do pip3 install numpy rather than using normal (python 2.7) pip. Either way, you should try reinstalling numpy, or if that still doesn't work you can build it from source.
This is based on the fact that the problem seems to be with the numpy package rather than your system itself.</p>

Body:
I have installed python 3.6 and through pip added numpy module, but getting below error while trying to import the library. Kindly help here:

>>> import numpy
Traceback (most recent call last):
  File "C:\Users\as338011\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\core\__init__.py", line 16, in
<module>
    from . import multiarray
ImportError: DLL load failed: The specified procedure could not be found.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\as338011\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\__init__.py", line 142, in <mod
ule>
    from . import add_newdocs
  File "C:\Users\as338011\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\add_newdocs.py", line 13, in <m
odule>
    from numpy.lib import add_newdoc
  File "C:\Users\as338011\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\lib\__init__.py", line 8, in <m
odule>
    from .type_check import *
  File "C:\Users\as338011\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\lib\type_check.py", line 11, in
 <module>
    import numpy.core.numeric as _nx
  File "C:\Users\as338011\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\core\__init__.py", line 26, in
<module>
    raise ImportError(msg)
ImportError:
Importing the multiarray numpy extension module failed.  Most
likely you are trying to import a failed build of numpy.
If you're working with a numpy git repo, try `git clean -xdf` (removes all
files not under version control).  Otherwise reinstall numpy.

Original error was: DLL load failed: The specified procedure could not be found.


问:
How do I iterate through a child's private fields?
After reading this question
One idea for my problem was to implement the method in the child classes like:

```<code>class Child {
    private $childField = "Want to see";
    public $pubChildField = "Will see";

    public function method()
    {
        $assoc = []; // a associative array
        foreach ($this as $field => $value) {
            $assoc[$field] = doStuff($value);
        }
        return $assoc;
    }
}
var_dump((new Child())->jsonSerialize());
</code>```

But for this I'd have to copycat the code in each child class. For readability, I want to refactor it into an (already existing) parentClass similar to:

```<code>abstract class parentClass {
    public function method()
    {
        $assoc = []; // a associative array
        foreach ($this as $field => $value) {
            $assoc[$field] = doStuff($value);
        }
        return $assoc;
    }
}
class Child extends parentClass {
    private $childField;
    public $pubChildField;
}
var_dump((new Child())->jsonSerialize());
</code>```

Both foreach ($this as $k=>$v) and get_object_vars() will get the public fields from the instance. I need to get it's private fields thou, for serialization.

Edit 1: Typo abstract method - what was i thinking

Edit 2: Clarified the example

Edit 3: Reformulated the question since there seemed to be misconception

答:
The correct solution is to declare the base class implements the JsonSerializable interface and implement the JsonSerializable::jsonSerialize() method in all children classes.

You can let it unimplemented in the base class to force all the children classes implement it or you can provide a default implementation (return array();) in the base class for the children classes that do not need to be serialized.

The implementation in each class should not iterate over the list of object properties. Usually, not all object properties must be serialized and the serializable properties are not born equal.

```<code>abstract class parentClass implements JsonSerializable {

    // You can remove this default implementation
    // to force all children class implement the method
    public function jsonSerialize()
    {
        return array();
    }
}

class childClass extends parentClass {
    private $childField;
    public $pubChildField;

    public function jsonSerialize()
    {
        return array(
            'field1' => $this->childField,
            'field2' => base64_encode($pubChildField),
            // etc ...
        );
    }
}

var_dump((new Child())->jsonSerialize());
</code>```

Try to write code that is easier to read and understand. You will thank yourself later.

Body:
After reading this question
One idea for my problem was to implement the method in the child classes like:

class Child {
    private $childField = "Want to see";
    public $pubChildField = "Will see";

    public function method()
    {
        $assoc = []; // a associative array
        foreach ($this as $field => $value) {
            $assoc[$field] = doStuff($value);
        }
        return $assoc;
    }
}
var_dump((new Child())->jsonSerialize());

But for this I'd have to copycat the code in each child class. For readability, I want to refactor it into an (already existing) parentClass similar to:

abstract class parentClass {
    public function method()
    {
        $assoc = []; // a associative array
        foreach ($this as $field => $value) {
            $assoc[$field] = doStuff($value);
        }
        return $assoc;
    }
}
class Child extends parentClass {
    private $childField;
    public $pubChildField;
}
var_dump((new Child())->jsonSerialize());

Both foreach ($this as $k=>$v) and get_object_vars() will get the public fields from the instance. I need to get it's private fields thou, for serialization.

Edit 1: Typo abstract method - what was i thinking

Edit 2: Clarified the example

Edit 3: Reformulated the question since there seemed to be misconception

Body:
The correct solution is to declare the base class implements the JsonSerializable interface and implement the JsonSerializable::jsonSerialize() method in all children classes.

You can let it unimplemented in the base class to force all the children classes implement it or you can provide a default implementation (return array();) in the base class for the children classes that do not need to be serialized.

The implementation in each class should not iterate over the list of object properties. Usually, not all object properties must be serialized and the serializable properties are not born equal.

abstract class parentClass implements JsonSerializable {

    // You can remove this default implementation
    // to force all children class implement the method
    public function jsonSerialize()
    {
        return array();
    }
}

class childClass extends parentClass {
    private $childField;
    public $pubChildField;

    public function jsonSerialize()
    {
        return array(
            'field1' => $this->childField,
            'field2' => base64_encode($pubChildField),
            // etc ...
        );
    }
}

var_dump((new Child())->jsonSerialize());

Try to write code that is easier to read and understand. You will thank yourself later.


问:
Unique word count on selected word in file python
With Python 2.7 I open an external file which contains:

```<code>Text another word1
Lorem ipsem word1 something
hello first word2 post
</code>```

I want to perform an unique count on the word word only, not on the 3rd row.

Desired output:

```<code>$ script.py
2x word1
1x word2
</code>```

What I got so far but fails..:

```<code>import os
import sys
from collections import Counter

with open('./file.txt', 'r') as file:
        for item in file:
            if '.sh' in item:
                    all = item.split()[2]
                    print Counter(all.split())
</code>```

答:
If I understand your problem correctly, you want to count the number of occurence of a specified word in a plain text file.

For that, I'd recommend turning the text file to a list of words

```<code>f = open("yourfile.txt","r") # Open the file
txt = f.read()               # read it
f.close()                    # always close it
a1 = txt.split("\n")         # split each line
a2 = []                      # create an empty array
for i in a1:                 # for each line
  a2 += a1.split(" ")        # append every word
</code>```

And then simply use

```<code>a2.count("yourword")
</code>```

You can try that here

Body:
With Python 2.7 I open an external file which contains:

Text another word1
Lorem ipsem word1 something
hello first word2 post

I want to perform an unique count on the word word only, not on the 3rd row.

Desired output:

$ script.py
2x word1
1x word2

What I got so far but fails..:

import os
import sys
from collections import Counter

with open('./file.txt', 'r') as file:
        for item in file:
            if '.sh' in item:
                    all = item.split()[2]
                    print Counter(all.split())

Body:
If I understand your problem correctly, you want to count the number of occurence of a specified word in a plain text file.

For that, I'd recommend turning the text file to a list of words

f = open("yourfile.txt","r") # Open the file
txt = f.read()               # read it
f.close()                    # always close it
a1 = txt.split("\n")         # split each line
a2 = []                      # create an empty array
for i in a1:                 # for each line
  a2 += a1.split(" ")        # append every word

And then simply use

a2.count("yourword")

You can try that here


问:
Converting System.IO.Stream to Byte[]
I am looking for a solution in C# language which can convert System.IO.Stream to byte[]. I have tried the below code but i am receiving byte[] as null. Can some one guide what i am missing from below code ? I am receiving from Alfresco Web service, no way i can read the file unless saving in to temp location.</p>

```<code> private static byte[] ReadFile(Stream fileStream)
    {
        byte[] bytes = new byte[fileStream.Length];

        fileStream.Read(bytes, 0, Convert.ToInt32(fileStream.Length));
        fileStream.Close();

        return bytes;

        //using (MemoryStream ms = new MemoryStream())
        //{
        //    int read;
        //    while ((read = fileStream.Read(bytes, 0, bytes.Length)) > 0)
        //    {
        //        fileStream.CopyTo(ms);
        //    }
        //    return ms.ToArray();
        //}
    }
</code>```

答:
Once I made an extension method for it:</p>

```<code>public static byte[] ToArray(this Stream s)
{
    if (s == null)
        throw new ArgumentNullException(nameof(s));
    if (!s.CanRead)
        throw new ArgumentException("Stream cannot be read");

    MemoryStream ms = s as MemoryStream;
    if (ms != null)
        return ms.ToArray();

    long pos = s.CanSeek ? s.Position : 0L;
    if (pos != 0L)
        s.Seek(0, SeekOrigin.Begin);

    byte[] result = new byte[s.Length];
    s.Read(result, 0, result.Length);
    if (s.CanSeek)
        s.Seek(pos, SeekOrigin.Begin);
    return result;
}
</code>```

Title: Converting System.IO.Stream to Byte[]

Body:
I am looking for a solution in C# language which can convert System.IO.Stream to byte[]. I have tried the below code but i am receiving byte[] as null. Can some one guide what i am missing from below code ? I am receiving from Alfresco Web service, no way i can read the file unless saving in to temp location.

 private static byte[] ReadFile(Stream fileStream)
    {
        byte[] bytes = new byte[fileStream.Length];

        fileStream.Read(bytes, 0, Convert.ToInt32(fileStream.Length));
        fileStream.Close();

        return bytes;

        //using (MemoryStream ms = new MemoryStream())
        //{
        //    int read;
        //    while ((read = fileStream.Read(bytes, 0, bytes.Length)) > 0)
        //    {
        //        fileStream.CopyTo(ms);
        //    }
        //    return ms.ToArray();
        //}
    }

Body:
Once I made an extension method for it:

public static byte[] ToArray(this Stream s)
{
    if (s == null)
        throw new ArgumentNullException(nameof(s));
    if (!s.CanRead)
        throw new ArgumentException("Stream cannot be read");

    MemoryStream ms = s as MemoryStream;
    if (ms != null)
        return ms.ToArray();

    long pos = s.CanSeek ? s.Position : 0L;
    if (pos != 0L)
        s.Seek(0, SeekOrigin.Begin);

    byte[] result = new byte[s.Length];
    s.Read(result, 0, result.Length);
    if (s.CanSeek)
        s.Seek(pos, SeekOrigin.Begin);
    return result;
}


问:
How to make a copy of a swift array of class objects
In code below, list1 is original Array.
when i copy list1 in list2, it passes "allCardList" array as reference but i want to create copy of list1 so when i change in list2 it shouldn't change original Array (list1)

```<code>class Card {
    var availableBalance        = "5"
}
class DataCacheManager: NSObject {
    var allCardList             = [Card]()
}
var card = Card()
card.availableBalance = "10"

var list1 = DataCacheManager()
list1.allCardList.append(card)

var list2 = DataCacheManager()

for item in list1.allCardList {
    list2.allCardList.append(item)
}

list2.allCardList[0].availableBalance = "20"

print(list1.allCardList[0].availableBalance) // print 20 but should return 10
</code>```

Any help you that?

答:
A class has reference semantics. The simplest solution is to use value semantics

```<code>struct Card ...
</code>```

Body:
In code below, list1 is original Array.
when i copy list1 in list2, it passes "allCardList" array as reference but i want to create copy of list1 so when i change in list2 it shouldn't change original Array (list1)

class Card {
    var availableBalance        = "5"
}
class DataCacheManager: NSObject {
    var allCardList             = [Card]()
}
var card = Card()
card.availableBalance = "10"

var list1 = DataCacheManager()
list1.allCardList.append(card)

var list2 = DataCacheManager()

for item in list1.allCardList {
    list2.allCardList.append(item)
}

list2.allCardList[0].availableBalance = "20"

print(list1.allCardList[0].availableBalance) // print 20 but should return 10

Any help you that?

Body:
A class has reference semantics. The simplest solution is to use value semantics

struct Card ...


答:
Take a look at this question, it describes the process of copying a single object.

Implementing copy() in Swift

After you added the ability of copying, iterate through your array with a for loop to create a copied array from your existing data.

Title: How to make a copy of a swift array of class objects


问:
running openCL in android
Well there are many tutorials and post about this, but I am not getting exactly how to deal with libOpenCL.so file. Many vendors does not include it inside phone, but my app needs to support maximum available phones today, so do I need to get compatible libOpenCL.so file for each of them?  </p>

答:
Adding to the answer of @Morrison Chang:

You can not rely on all version of OpenCL in all devices to have everything supported. So I would do a dinamic library loading, and query at runtime for the OpenCL methods are available.

Regarding the library with OpenCL support, sometimes is not even called like that. For example libGLESmali.so has OpenCL symbols and can be used directly.

Title: running openCL in android


问:
While coding, an error of "name not defined" is generated
I was coding for the question "Write a Python function that takes two lists and returns True if they have at least one common member"

Code:

```<code>first = [a,b,c,d,e,f]
second = [a,s,d,f,g,h]
for word1 in first:
    for word2 in second:
     if word1==word2:
        print("success")
</code>```

Error:

```<code>first = list[a,b,c,d,e,f]
NameError: name 'a' is not defined
</code>```

How can I fix this?

答:
Name 'a' is not defined, because you never define the Python variable 'a'. I think that you meant to compare arrays of strings, like this:</p>

```<code>first = ["a", "b", "c", "d", "e", "f"]
second = ["a", "s", "d", "f", "g", "h"]
for word1 in first:
    for word2 in second:
     if word1==word2:
        print("success")
</code>```

Body:
I was coding for the question "Write a Python function that takes two lists and returns True if they have at least one common member"

Code:

first = [a,b,c,d,e,f]
second = [a,s,d,f,g,h]
for word1 in first:
    for word2 in second:
     if word1==word2:
        print("success")

Error:

first = list[a,b,c,d,e,f]
NameError: name 'a' is not defined

How can I fix this?

Body:
Name 'a' is not defined, because you never define the Python variable 'a'. I think that you meant to compare arrays of strings, like this:

first = ["a", "b", "c", "d", "e", "f"]
second = ["a", "s", "d", "f", "g", "h"]
for word1 in first:
    for word2 in second:
     if word1==word2:
        print("success")


问:
Creating a join condition using hibernate criteria
I have an application class and document class. I want to only display application that has a document

Application.java

```<code> private int appId;

 private String lname;

 private String fname;

//getters setter generated
</code>```

Document.java

```<code>private int appId;

private int docId;
//getters setters generated
</code>```

I have not made any relation between Application and Document in the persistence class. I want to join them using criteria

```<code>Criteria criteria = session.createCriteria(Application.class, "application");

criteria.createAlias("Document.appId","app", CriteriaSpecification.LEFT_JOIN,Restrictions.eqProperty("app", "application.appId"));
</code>```

This is not giving any results. Do I need to make any changes in persistence class . Any help will be appreciated.

答:
I agree that without associations this cannot be achieved and here is how i made the association in Applicaition.java class</p>

```<code>private int appId;

private String lname;

private String fname;

@ManyToOne
@JoinColumn(name="appId", referencedColumnName="appId", nullable = false, insertable=false, updatable=false)
@NotFound(action = NotFoundAction.IGNORE)
Private Document document

//getters and setter generated
</code>```

Body:
I have an application class and document class. I want to only display application that has a document

Application.java

 private int appId;

 private String lname;

 private String fname;

//getters setter generated

Document.java

private int appId;

private int docId;
//getters setters generated

I have not made any relation between Application and Document in the persistence class. I want to join them using criteria

Criteria criteria = session.createCriteria(Application.class, "application");

criteria.createAlias("Document.appId","app", CriteriaSpecification.LEFT_JOIN,Restrictions.eqProperty("app", "application.appId"));

This is not giving any results. Do I need to make any changes in persistence class . Any help will be appreciated.

Body:
I agree that without associations this cannot be achieved and here is how i made the association in Applicaition.java class

private int appId;

private String lname;

private String fname;

@ManyToOne
@JoinColumn(name="appId", referencedColumnName="appId", nullable = false, insertable=false, updatable=false)
@NotFound(action = NotFoundAction.IGNORE)
Private Document document

//getters and setter generated


问:
C++ Integer Division to Float
My C++ program takes in three integer inputs and does some computations including division. At first, the end result was not a decimal. After searching a little on Stack Overflow (Dividing two integers to produce a float result), I found out that I'm supposed to add a (float), like this:

```<code>int a;
int b;
float c;

a = 5;
b = 2;

c = (float)a / b;
</code>```

So I tried that but I ended up with my result being -nan(ind). First off, what does that mean? And second, how do I make my program work?

Here is the math I am trying to do in my program by the way.

```<code>int v;
int e;
int a;
float r;

r = ((float)e - v) / ((float)a / 1000);
</code>```

Edit: Sorry, my mistake. I meant to type 1000 in the second example, not c.

答:
You have to initialize every variables like your first example and also assign values of each and every variables.

Try this :

```<code>int v;
int e;
int a;
int c;
float r;

a = 5;
c = 2;
e = 5;
v = 2;

r = ((float)e - v) / (float)a / c;
cout << r;
</code>```

Title: C++ Integer Division to Float

Body:
My C++ program takes in three integer inputs and does some computations including division. At first, the end result was not a decimal. After searching a little on Stack Overflow (Dividing two integers to produce a float result), I found out that I'm supposed to add a (float), like this:

int a;
int b;
float c;

a = 5;
b = 2;

c = (float)a / b;

So I tried that but I ended up with my result being -nan(ind). First off, what does that mean? And second, how do I make my program work?

Here is the math I am trying to do in my program by the way.

int v;
int e;
int a;
float r;

r = ((float)e - v) / ((float)a / 1000);

Edit: Sorry, my mistake. I meant to type 1000 in the second example, not c.

Body:
You have to initialize every variables like your first example and also assign values of each and every variables.

Try this :

int v;
int e;
int a;
int c;
float r;

a = 5;
c = 2;
e = 5;
v = 2;

r = ((float)e - v) / (float)a / c;
cout << r;


问:
Visual Basic format number to hower many number on left of decimal and 1 decimal without rounding
I am acutally using SSRS but it is for an expression so this is VB code. I am wondering how I would get a number such as 236.4723423 to appear at 236.4 instead of 236.5, so basically I jsut want to truncate it always after 1 decimal.

I tried Format = "N1" this rounds it
I tried Formate = "#######.0" and "######.#" and this rounds it as well.

Any ideas?

答:
```<code>    value = Math.Floor(value * 10) / 10
</code>```

ContentLicense: CC BY-SA 2.5

Body: value = Math.Floor(value * 10) / 10


问:
Convert integer minutes into String "hh:mm"
I need to convert minutes (defined as Integer) into the following String format "hh:mm" assuming that the startTime is "00:00". The below-given code is what I have so far, but it does not work properly. Also it does not take into account that the newTime should be shifted in accordance to startTime. Is there any other solution?

```<code>String startTime = "00:00";
int minutes = 120;
double time = minutes/60;
String timeS = Double.toString(time);
String[] hourMin = timeS.split(".");
String h = hourMin[0];
String m = hourMin[1];
String newTime = "";
newTime.concat(h+":"+m);
</code>```

答:
apines' answer is good but if you want to remove the warning in Android, add 'Locale' :</p>

```<code>int hours = 3;
int minutes = 6;
private static final String TIME_SEPARATOR = ":";
String.format(Locale.getDefault(), "%02d"+TIME_SEPARATOR+"%02d", hours, minutes);
</code>```

Body:
I need to convert minutes (defined as Integer) into the following String format "hh:mm" assuming that the startTime is "00:00". The below-given code is what I have so far, but it does not work properly. Also it does not take into account that the newTime should be shifted in accordance to startTime. Is there any other solution?

String startTime = "00:00";
int minutes = 120;
double time = minutes/60;
String timeS = Double.toString(time);
String[] hourMin = timeS.split(".");
String h = hourMin[0];
String m = hourMin[1];
String newTime = "";
newTime.concat(h+":"+m);

Body:
apines' answer is good but if you want to remove the warning in Android, add 'Locale' :

int hours = 3;
int minutes = 6;
private static final String TIME_SEPARATOR = ":";
String.format(Locale.getDefault(), "%02d"+TIME_SEPARATOR+"%02d", hours, minutes);


问:
How do I run two while True statements in python?
I am trying to make a door swipe card system in Python for my Raspberry Pi. I broke the program into two: A Door Alarm and a Card Swipe Recording system. The two programs work individually but how do I combine the two programs into one python file? I've tried threading but it doesn't seem to work.

Below are the programs:
1.) Door Alarm: If door is left open for a certain duration, an led will blink, then an alarm will ring

```<code>import time
import RPi.GPIO as gpio

led = 37
buzzer = 11
door = 16

gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)
gpio.setup(buzzer, gpio.OUT)
gpio.setup(led, gpio.OUT)
gpio.setup(door, gpio.IN, pull_up_down=gpio.PUD_UP)

def blink(buzzer):
    gpio.output(buzzer, True)
    time.sleep(0.1)
    gpio.output(buzzer, False)
    time.sleep(0.1)
    return

def blink(led):
    gpio.output(led, True)
    time.sleep(1)
    gpio.output(led, False)
    time.sleep(1)
    return

while True:
    if gpio.input(door):
        time.sleep(3)
        for i in range(0,5):
                blink(led)
        for i in range (0,5):
                blink(buzzer)
    else:
        gpio.output(buzzer, False)

gpio.cleanup()
</code>```

2.) Card Swipe Recording System: When someone swipes their card, the led blinks and a picture is taken

```<code>import datetime
import time
import os
import RPi.GPIO as gpio

led = 37
t = datetime.datetime.now()

gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)
gpio.setup(led, gpio.OUT)

def blink(led):
    gpio.output(led, True)
    time.sleep(0.1)
    gpio.output(led, False)
    time.sleep(0.1)

while True:
    card = raw_input()
    f = open("Laptop Sign Out" + '.txt', 'a')
    f.write("OneCard Number: " + card[1:10] + " Time: " + t.strftime("%m-%d-%Y %H:%M:%S"))
    f.write('\n')
    f.write(';')
    f.write('\n')
    f.close()
    time.sleep(1)
    for i in range(0,3):
        blink(led)
    os.system('fswebcam ~/Desktop/Photos/%H%M%S.jpeg')
    time.sleep(3)

gpio.cleanup()
</code>```

(UPDATE) Also, below is my attempt at threading:

```<code>import time
import RPi.GPIO as gpio
import os
import datetime
from threading import Thread

led = 37
buzzer = 11
door = 16
t = datetime.datetime.now()

gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)
gpio.setup(buzzer, gpio.OUT)
gpio.setup(led, gpio.OUT)
gpio.setup(door, gpio.IN, pull_up_down=gpio.PUD_UP)

def blink(buzzer):
    gpio.output(buzzer, True)
    time.sleep(0.1)
    gpio.output(buzzer, False)
    time.sleep(0.1)
    return

def blink(led):
    gpio.output(led, True)
    time.sleep(1)
    gpio.output(led, False)
    time.sleep(1)
    return

def doorsensor():
    while True:
        if gpio.input(door):
            time.sleep(3)
            for i in range(0,5):
                    blink(led)
            for i in range (0,5):
                    blink(buzzer)
        else:
            gpio.output(buzzer, False)

def cardreader():
    while True:
        card = raw_input()
        f = open("Laptop Sign Out" + '.txt', 'a')
        f.write("OneCard Number: " + card[1:10] + " Time: " + t.strftime("%m-%d-%Y %H:%M:%S"))
        f.write('\n')
        f.write(';')
        f.write('\n')
        f.close()
        time.sleep(1)
        for i in range(0,3):
            blink(led)
        os.system('fswebcam ~/Desktop/Photos/%H%M%S.jpeg')
        time.sleep(3)

f1 = Thread(target = doorsensor())
f2 = Thread(target = cardreader())

f2.start()
f1.start()

gpio.cleanup()
</code>```

答:
I'm presenting a thread-less approach.
The idea is to turn your while bodies into update functions, and call them alternatively.

First off, your door loop becomes

```<code>def update_door():
    if gpio.input(door):
        time.sleep(3)
        for i in range(0,5):
                blink(led)
        for i in range (0,5):
                blink(buzzer)
    else:
        gpio.output(buzzer, False)
</code>```

Then your card swipe recording system becomes

```<code>def update_card():
    card = raw_input()
    f = open("Laptop Sign Out" + '.txt', 'a')
    f.write("OneCard Number: " + card[1:10] + " Time: " + t.strftime("%m-%d-%Y %H:%M:%S"))
    f.write('\n')
    f.write(';')
    f.write('\n')
    f.close()
    time.sleep(1)
    for i in range(0,3):
        blink(led)
    os.system('fswebcam ~/Desktop/Photos/%H%M%S.jpeg')
    time.sleep(3)
</code>```

Finally, your main loop becomes:

```<code>while True:
    update_door()
    update_card()
</code>```

But a problem arises: time.sleep in update_card will delay update_door as well.
Here, you have three solutions:

1 - It's ok if update_door is delayed

Well, ok.

2 - It's not ok if update_door is delayed, but it's ok if update_card is not delayed

Then just remove time.sleep(3).

3 - You need update_door not to be delayed, and update_card to be delayed

Then you can set a manual timer, using the time module.

```<code>lastCardUpdate = time.time()
while True:
    update_door()
    now = time.time()
    if now - lastCardUpdate >= 3:
        update_card()
        lastCardUpdate = now
</code>```

But raw_input in update_card is a blocking method, waiting for a user input.
If you do need this user input to happen every three seconds, then this approach cannot be used.
If you can move it before the while, ie outside of the update_card function, then it's fine.
Else, you will indeed need to use threads.

Body:
I am trying to make a door swipe card system in Python for my Raspberry Pi. I broke the program into two: A Door Alarm and a Card Swipe Recording system. The two programs work individually but how do I combine the two programs into one python file? I've tried threading but it doesn't seem to work.

Below are the programs:
1.) Door Alarm: If door is left open for a certain duration, an led will blink, then an alarm will ring

import time
import RPi.GPIO as gpio

led = 37
buzzer = 11
door = 16

gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)
gpio.setup(buzzer, gpio.OUT)
gpio.setup(led, gpio.OUT)
gpio.setup(door, gpio.IN, pull_up_down=gpio.PUD_UP)

def blink(buzzer):
    gpio.output(buzzer, True)
    time.sleep(0.1)
    gpio.output(buzzer, False)
    time.sleep(0.1)
    return

def blink(led):
    gpio.output(led, True)
    time.sleep(1)
    gpio.output(led, False)
    time.sleep(1)
    return

while True:
    if gpio.input(door):
        time.sleep(3)
        for i in range(0,5):
                blink(led)
        for i in range (0,5):
                blink(buzzer)
    else:
        gpio.output(buzzer, False)

gpio.cleanup()

2.) Card Swipe Recording System: When someone swipes their card, the led blinks and a picture is taken

import datetime
import time
import os
import RPi.GPIO as gpio

led = 37
t = datetime.datetime.now()

gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)
gpio.setup(led, gpio.OUT)

def blink(led):
    gpio.output(led, True)
    time.sleep(0.1)
    gpio.output(led, False)
    time.sleep(0.1)

while True:
    card = raw_input()
    f = open("Laptop Sign Out" + '.txt', 'a')
    f.write("OneCard Number: " + card[1:10] + " Time: " + t.strftime("%m-%d-%Y %H:%M:%S"))
    f.write('\n')
    f.write(';')
    f.write('\n')
    f.close()
    time.sleep(1)
    for i in range(0,3):
        blink(led)
    os.system('fswebcam ~/Desktop/Photos/%H%M%S.jpeg')
    time.sleep(3)

gpio.cleanup()

(UPDATE) Also, below is my attempt at threading:

import time
import RPi.GPIO as gpio
import os
import datetime
from threading import Thread

led = 37
buzzer = 11
door = 16
t = datetime.datetime.now()

gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)
gpio.setup(buzzer, gpio.OUT)
gpio.setup(led, gpio.OUT)
gpio.setup(door, gpio.IN, pull_up_down=gpio.PUD_UP)

def blink(buzzer):
    gpio.output(buzzer, True)
    time.sleep(0.1)
    gpio.output(buzzer, False)
    time.sleep(0.1)
    return

def blink(led):
    gpio.output(led, True)
    time.sleep(1)
    gpio.output(led, False)
    time.sleep(1)
    return

def doorsensor():
    while True:
        if gpio.input(door):
            time.sleep(3)
            for i in range(0,5):
                    blink(led)
            for i in range (0,5):
                    blink(buzzer)
        else:
            gpio.output(buzzer, False)

def cardreader():
    while True:
        card = raw_input()
        f = open("Laptop Sign Out" + '.txt', 'a')
        f.write("OneCard Number: " + card[1:10] + " Time: " + t.strftime("%m-%d-%Y %H:%M:%S"))
        f.write('\n')
        f.write(';')
        f.write('\n')
        f.close()
        time.sleep(1)
        for i in range(0,3):
            blink(led)
        os.system('fswebcam ~/Desktop/Photos/%H%M%S.jpeg')
        time.sleep(3)

f1 = Thread(target = doorsensor())
f2 = Thread(target = cardreader())

f2.start()
f1.start()

gpio.cleanup()

Body:
I'm presenting a thread-less approach.
The idea is to turn your while bodies into update functions, and call them alternatively.

First off, your door loop becomes

def update_door():
    if gpio.input(door):
        time.sleep(3)
        for i in range(0,5):
                blink(led)
        for i in range (0,5):
                blink(buzzer)
    else:
        gpio.output(buzzer, False)

Then your card swipe recording system becomes

def update_card():
    card = raw_input()
    f = open("Laptop Sign Out" + '.txt', 'a')
    f.write("OneCard Number: " + card[1:10] + " Time: " + t.strftime("%m-%d-%Y %H:%M:%S"))
    f.write('\n')
    f.write(';')
    f.write('\n')
    f.close()
    time.sleep(1)
    for i in range(0,3):
        blink(led)
    os.system('fswebcam ~/Desktop/Photos/%H%M%S.jpeg')
    time.sleep(3)

Finally, your main loop becomes:

while True:
    update_door()
    update_card()

But a problem arises: time.sleep in update_card will delay update_door as well.
Here, you have three solutions:

1 - It's ok if update_door is delayed

Well, ok.

2 - It's not ok if update_door is delayed, but it's ok if update_card is not delayed

Then just remove time.sleep(3).

3 - You need update_door not to be delayed, and update_card to be delayed

Then you can set a manual timer, using the time module.

lastCardUpdate = time.time()
while True:
    update_door()
    now = time.time()
    if now - lastCardUpdate >= 3:
        update_card()
        lastCardUpdate = now

But raw_input in update_card is a blocking method, waiting for a user input.
If you do need this user input to happen every three seconds, then this approach cannot be used.
If you can move it before the while, ie outside of the update_card function, then it's fine.
Else, you will indeed need to use threads.


问:
unsupported operand type(s) for /: ‘map’ and 'int’
```<code>##models.py
    from django.db import models
    from django.contrib.auth.models import User
    import numpy as np

    class Wine(models.Model):
        name=models.CharField(max_length=200)
        def average_rating(self):
            all_ratings = map(lambda x: x.rating, self.review_set.all())
            return np.mean(all_ratings)
        def __unicode__(self):
            return self.name
</code>```

Why is this error showing?What is wrong at line 7?

答:
This will work for you:-</p>

```<code>from django.db import models
from django.contrib.auth.models import User
import numpy as np

class Wine(models.Model):
    name=models.CharField(max_length=200)
    def average_rating(self):
        all_ratings = list(map(lambda x: x.rating, self.review_set.all()))
        return np.mean(all_ratings)
    def __unicode__(self):
        return self.name
</code>```

Body:
##models.py
    from django.db import models
    from django.contrib.auth.models import User
    import numpy as np

    class Wine(models.Model):
        name=models.CharField(max_length=200)
        def average_rating(self):
            all_ratings = map(lambda x: x.rating, self.review_set.all())
            return np.mean(all_ratings)
        def __unicode__(self):
            return self.name

Why is this error showing?What is wrong at line 7?

Body:
This will work for you:-

from django.db import models
from django.contrib.auth.models import User
import numpy as np

class Wine(models.Model):
    name=models.CharField(max_length=200)
    def average_rating(self):
        all_ratings = list(map(lambda x: x.rating, self.review_set.all()))
        return np.mean(all_ratings)
    def __unicode__(self):
        return self.name


问:
Getting results where no association between database tables are found using hibernate criteria
I want to find the applications that has no documents and I want to do it using hibernate criteria. Once I use createAlias in criteria, I only find the tables with associations. Does anyone have idea how can I do so or is it even possible?

Application.java

```<code>private int appId;

private String lname;

private String fname;

//getters setter generated
</code>```

Document.java

```<code>private int appId;

private int docId;
//getters setters generated
</code>```

Here is what my criteria looks like

```<code>Criteria criteria = session.createCriteria(Application.class, "application");
 criteria.createAlias("application.appId","document");

 if (looking for no association)
 {
 criteria.add(Restrictions.isNull("document.appId"));
 }
</code>```

Basically with the way I am setting criteria, I am creating inner join so the restriction condition is not working.

答:
Try this:

```<code>Criteria criteria = session.createCriteria(Application.class);
criteria.createAlias("document");
if (looking for no association) {
    criteria.add(Restrictions.isNull("document.appId"));
}
</code>```

Firstly you create a criteria based on Application class. Secondly you assign the alias you want to and finally you apply the desired restriction.

Body:
I want to find the applications that has no documents and I want to do it using hibernate criteria. Once I use createAlias in criteria, I only find the tables with associations. Does anyone have idea how can I do so or is it even possible?

Application.java

private int appId;

private String lname;

private String fname;

//getters setter generated

Document.java

private int appId;

private int docId;
//getters setters generated

Here is what my criteria looks like

Criteria criteria = session.createCriteria(Application.class, "application");
 criteria.createAlias("application.appId","document");

 if (looking for no association)
 {
 criteria.add(Restrictions.isNull("document.appId"));
 }

Basically with the way I am setting criteria, I am creating inner join so the restriction condition is not working.

Body:
Try this:

Criteria criteria = session.createCriteria(Application.class);
criteria.createAlias("document");
if (looking for no association) {
    criteria.add(Restrictions.isNull("document.appId"));
}

Firstly you create a criteria based on Application class. Secondly you assign the alias you want to and finally you apply the desired restriction.


问:
ImportError: No Module named demiso in Jython
I'm new to the Jython and I'm trying to run a python class using Jython in Java. But I'm running into some issues.

The Java class that I've defined:

```<code>public class DemistoCalls {

    PythonInterpreter interpreter = null;

    public DemistoCalls()
    {
        PythonInterpreter.initialize(System.getProperties(),
                System.getProperties(), new String[0]);

        this.interpreter = new PythonInterpreter();
    }

    void execfile( final String fileName )
    {
        this.interpreter.execfile(fileName);
    }

    PyInstance createClass( final String className, final String opts )
    {
        return (PyInstance) this.interpreter.eval(className + "(" + opts + ")");
    }

    public static void main(String[] args) {
        DemistoCalls demistoCalls = new DemistoCalls();

        demistoCalls.execfile("C:\\Users\\AlokNath\\Desktop\\Demisto_Project\\demisto-py-master\\demisto\\SimpleConnect.py");

    }

}
</code>```

The SampleConnect.py file that I'm trying to run:

```<code>import sys
sys.path.append("C:\Users\AlokNath\Desktop\Demisto_Project\demisto-py-
master\demisto")
import demisto
</code>```

While Running the java file, I'm getting this error:

File "C:\Users\AlokNath\Desktop\Demisto_Project\demisto-py-master\demisto\SimpleConnect.py", line 3, in <module>
    import demisto
ImportError: No module named demisto

Although I've defined the "demisto" module in the system path and checked that the system path in python contains the appropriate path to Jython 2.7.lb2 Library. I'm not sure where am I going wrong. Any help is appreciated.

Regards,
Alok

答: I found a solution to the import error problem. We need to copy the missing module to the “site-packages” folder under "modeler-installation/lib/jython/Lib". This will resolve the dependency problem.</p>

Body:
I'm new to the Jython and I'm trying to run a python class using Jython in Java. But I'm running into some issues.

The Java class that I've defined:

public class DemistoCalls {

    PythonInterpreter interpreter = null;

    public DemistoCalls()
    {
        PythonInterpreter.initialize(System.getProperties(),
                System.getProperties(), new String[0]);

        this.interpreter = new PythonInterpreter();
    }

    void execfile( final String fileName )
    {
        this.interpreter.execfile(fileName);
    }

    PyInstance createClass( final String className, final String opts )
    {
        return (PyInstance) this.interpreter.eval(className + "(" + opts + ")");
    }

    public static void main(String[] args) {
        DemistoCalls demistoCalls = new DemistoCalls();

        demistoCalls.execfile("C:\\Users\\AlokNath\\Desktop\\Demisto_Project\\demisto-py-master\\demisto\\SimpleConnect.py");

    }

}

The SampleConnect.py file that I'm trying to run:

import sys
sys.path.append("C:\Users\AlokNath\Desktop\Demisto_Project\demisto-py-
master\demisto")
import demisto

While Running the java file, I'm getting this error:

File "C:\Users\AlokNath\Desktop\Demisto_Project\demisto-py-master\demisto\SimpleConnect.py", line 3, in <module>
    import demisto
ImportError: No module named demisto

Although I've defined the "demisto" module in the system path and checked that the system path in python contains the appropriate path to Jython 2.7.lb2 Library. I'm not sure where am I going wrong. Any help is appreciated.

Regards,
Alok


问:
sql restricted count query
I'm not certain how to structure a SQL query to return the number of rows where a column equals certain values.

For instance,

In table myTable, how can I return the count of all the rows where myColumn = "xyz" and where myColumn = "abc"? Is this possible with a single query?

To clarify, say there are 10 rows where myColumn = "xyx" and 7 rows where myColumn = "abc", the query would return something like:

```<code>firstCountResult: 10
secondCountResult: 7
</code>```

答:
How about?:

```<code>SELECT
    COUNT(*),
    myColumn
FROM myTable
WHERE myColumn IN ('xyz', 'abc')
GROUP BY myColumn
</code>```

This approach also works with other aggregate functions like MIN, MAX, AVG, SUM... You get the aggregate result per the grouped column's value versus across all rows.

```<code>--min myDate per myColumn value
SELECT
    MIN(myDate),
    myColumn
FROM myTable
WHERE myColumn IN ('xyz', 'abc')
GROUP BY myColumn

--sum of myNumericCol per myColumn value
SELECT
    SUM(myNumericCol),
    myColumn
FROM myTable
WHERE myColumn IN ('xyz', 'abc')
GROUP BY myColumn
</code>```

Title: sql restricted count query

Body:
I'm not certain how to structure a SQL query to return the number of rows where a column equals certain values.

For instance,

In table myTable, how can I return the count of all the rows where myColumn = "xyz" and where myColumn = "abc"? Is this possible with a single query?

To clarify, say there are 10 rows where myColumn = "xyx" and 7 rows where myColumn = "abc", the query would return something like:

firstCountResult: 10
secondCountResult: 7

Body:
How about?:

SELECT
    COUNT(*),
    myColumn
FROM myTable
WHERE myColumn IN ('xyz', 'abc')
GROUP BY myColumn

This approach also works with other aggregate functions like MIN, MAX, AVG, SUM... You get the aggregate result per the grouped column's value versus across all rows.

--min myDate per myColumn value
SELECT
    MIN(myDate),
    myColumn
FROM myTable
WHERE myColumn IN ('xyz', 'abc')
GROUP BY myColumn

--sum of myNumericCol per myColumn value
SELECT
    SUM(myNumericCol),
    myColumn
FROM myTable
WHERE myColumn IN ('xyz', 'abc')
GROUP BY myColumn


问:
MERGE statement DELETE alternative in SQL Server
I have a Query using T-SQL MERGE Statement. Due to performance issues I am re writing the Query using IF Exists Update and If Not Exists Insert. I am able to write Insert/Update without any issue. But I am unable to handle the DELETE. Can some one please help me on this?

Here is the sample

```<code>---SAMPLE MERGE STATEMENT
MERGE
   member_topic AS target
USING
   someOtherTable AS source
ON
   target.mt_member = source.mt_member

WHEN MATCHED THEN
   UPDATE SET target.mt_notes = source.mt_notes
WHEN NOT MATCHED THEN
   INSERT (mt_member, mt_topic, mt_notes) VALUES (source.mt_member, source.mt_notes)

WHEN NOT MATCHED BY SOURCE THEN
DELETE member_topic;

--UPDATE

UPDATE T SET T.mt_notes = S.mt_notes
FROM member_topic T
JOIN someOtherTable S ON T.mt_member=S.mt_member

--INSERT

INSERT INTO member_topic(mt_member, mt_topic, mt_notes)
SELECT mt_member, mt_topic, mt_notes
FROM someOtherTable S
WHERE NOT EXISTS(SELECT 1
                 FROM member_topic T
                 WHERE T.mt_member=S.mt_member)
</code>```

How to handle

```<code>WHEN NOT MATCHED BY SOURCE THEN
DELETE member_topic;
</code>```

in single DELETE Statement.

答:
Try </p>

```<code>DELETE T
FROM member_topic T
WHERE NOT EXISTS(SELECT 1
                 FROM someOtherTable S
                 WHERE T.mt_member=S.mt_member)
</code>```

Body:
I have a Query using T-SQL MERGE Statement. Due to performance issues I am re writing the Query using IF Exists Update and If Not Exists Insert. I am able to write Insert/Update without any issue. But I am unable to handle the DELETE. Can some one please help me on this?

Here is the sample

---SAMPLE MERGE STATEMENT
MERGE
   member_topic AS target
USING
   someOtherTable AS source
ON
   target.mt_member = source.mt_member

WHEN MATCHED THEN
   UPDATE SET target.mt_notes = source.mt_notes
WHEN NOT MATCHED THEN
   INSERT (mt_member, mt_topic, mt_notes) VALUES (source.mt_member, source.mt_notes)

WHEN NOT MATCHED BY SOURCE THEN
DELETE member_topic;

--UPDATE

UPDATE T SET T.mt_notes = S.mt_notes
FROM member_topic T
JOIN someOtherTable S ON T.mt_member=S.mt_member

--INSERT

INSERT INTO member_topic(mt_member, mt_topic, mt_notes)
SELECT mt_member, mt_topic, mt_notes
FROM someOtherTable S
WHERE NOT EXISTS(SELECT 1
                 FROM member_topic T
                 WHERE T.mt_member=S.mt_member)

How to handle

WHEN NOT MATCHED BY SOURCE THEN
DELETE member_topic;

in single DELETE Statement.

Body:
Try

DELETE T
FROM member_topic T
WHERE NOT EXISTS(SELECT 1
                 FROM someOtherTable S
                 WHERE T.mt_member=S.mt_member)


问:
Counting multiple instances of an object in an image using machine learning
I am a beginner and have just started studying machine learning and neural networks and have just understood the very basics of this vast and interesting domain.

  From my basic knowledge, I know that a model/classifier can be used to Classify an image as something. But I was curious if there is a way to detect multiple instances of the same object and count the same.

  Basically I wanted to calculate the density of traffic at a red light to dynamically control the flow of traffic, so I was curious if there was a way to detect multiple cars and count the number of cars at a red light by training the ConvNet on Images of Cars (and if there is a way to implement the same using tensor-flow)

答:
CNN is one branch of the machine learning. It can be trained to classify different cars as one class, just like many other technologies applied in machine learning.

My understanding of your question is: you want to count the number of cars at the red light and make decision of the traffic dynamically. So I would seperate your question into two part

Count the number of cars

Optimize the traffic flow

For the question 1 which you are actually interested in
I would suggest you to have a look at:
Counting the number of vehicles from an image with machine learning

I hope this can be helpful


问:
Is it possible in Bash 4.0 to substring and uppercase a variable in one
Given a variable var=toucan I can do the following:

```<code>echo ${var^^}
TOUCAN
echo ${var:3}
can
</code>```

Is it possible to do something similar to echo ${var:3^^} to get CAN?

```<code>echo ${var:3^^}
bash: var: 3^^: syntax error: operand expected (error token is "^")
</code>```

答: No; bash doesn't let you combine special parameter expansions like that (for any of them, including remove-affix, value-if-null, value-if-null-or-empty, etc.) You will have to do it in two steps, or use a program outside of bash.</p>

Body:
Given a variable var=toucan I can do the following:

echo ${var^^}
TOUCAN
echo ${var:3}
can

Is it possible to do something similar to echo ${var:3^^} to get CAN?

echo ${var:3^^}
bash: var: 3^^: syntax error: operand expected (error token is "^")


问:
Will performFetchWithCompletionHandler be called if the app has been terminated
It's surprisingly difficult to find a definitive answer to this; couldn't find it mentioned in the Apple documentation and couldn't find a definite yes/no after searching past questions.

The question is simple - if the app requests a background fetch to be performed after N time, then the user terminates the app. Will the OS still launch the app into the background to perform the background fetch?

答:
EDIT:

https://devforums.apple.com/message/873265#873265 (login required)

Also keep in mind that if you kill your app from the app switcher
  (i.e. swiping up to kill the app) then the OS will never relaunch the
  app regardless of push notification or background fetch.  In this case
  the user has to manually relaunch the app once and then from that
  point forward the background activities will be invoked. -pmarcos

That post was by an Apple employee so I think i can trust that this information is correct.

OLD answer:

According to this answer wrote by a top user: iOS background fetch: your app won't be woken up again.

Make sure you're not killing the app (i.e. by double tapping on the
  home button and swiping up on your app for force the app to
  terminate). If the app is killed, it will prevent background fetch
  from working correctly.

It really doesn't make sense for it to be woken up...it kinda invalidates the user killing the app.

Having that said there are different ways a terminated/force quit app can be launched again:

Tapping on a notification.

Tapping on the app icon.

Using openUrl to open your app from another app.

If you use PushKit...then your app would be launched. Imagine if had a  VOIP app e.g. Skype, WhatsApp and a friend was calling you but you had have force-quit the app, you wouldn't receive calls. For more see here.

Location updates either through use of region monitoring or the significant-change location service. See  this answer and make sure to read  this entire page from Apple docs.

Rebooting the device would also undo anything blocked through force-quit


问:
How to parse json response swift3?
My response looks like this:

```<code>[
    {
        "Part" : {
            "id" : "418502",
            "uuid" : "21ec7cdb-cd2d-4b12-8a90-775762eb0f26"
        },
        "Category" : {
            "category_name" : "Regulators",
            "category_code" : "RG"
        }
    },
    {
        "Part" : {
             "id" : "418502",
             "uuid" : "21ec7cdb-cd2d-4b12-8a90-775762eb0f26"
        },
        "Category" : {
             "category_name" : "Regulators",
             "category_code" : "RG"
        }
    }
]
</code>```

So I need to parse the above response to get Part array and Category array. After searching in google I found:

```<code>let resultJson = try JSONSerialization.jsonObject(with: data, options: []) as? [String : AnyObject]
print(resultJson!)
</code>```

But it throws fatal error: unexpectedly found nil while unwrapping an Optional value.

I'm new to swift I don't know how to convert it. I have completed this in Android so I can surely say I get above response from server. I write a common function for calling web service, it works for other services so I think there is no problem in that.

How can I parse my response so I can get Part array and Category array?
Thank you.

答:
Your JSON structure has a top level array, so you cannot parse is as a dictionary. Try to do this

```<code>let resultJson = try JSONSerialization.jsonObject(with: data, options: []) as? [Any]
dump(resultJson!)
</code>```

Sample code will be something like this. Don't forget to handle unwrap stuff

```<code>let str = "[{\"Part\":{\"id\":\"418502\",\"uuid\":\"21ec7cdb-cd2d-4b12-8a90-775762eb0f26\"},\"Category\":{\"category_name\":\"Regulators\",\"category_code\":\"RG\"}},{\"Part\":{\"id\":\"418502\",\"uuid\":\"21ec7cdb-cd2d-4b12-8a90-775762eb0f26\"},\"Category\":{\"category_name\":\"Regulators\",\"category_code\":\"RG\"}}]"

let data = str.data(using: .utf8)

do{
    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [Any]
    let dicInFirstElement = json?[0] as? [String: Any]
    let part = dicInFirstElement?["Part"]
    dump(part)
    //Pass this json into the following function
}catch let error{

}
</code>```

Title: How to parse json response swift3?

Body:
My response looks like this:

[
    {
        "Part" : {
            "id" : "418502",
            "uuid" : "21ec7cdb-cd2d-4b12-8a90-775762eb0f26"
        },
        "Category" : {
            "category_name" : "Regulators",
            "category_code" : "RG"
        }
    },
    {
        "Part" : {
             "id" : "418502",
             "uuid" : "21ec7cdb-cd2d-4b12-8a90-775762eb0f26"
        },
        "Category" : {
             "category_name" : "Regulators",
             "category_code" : "RG"
        }
    }
]

So I need to parse the above response to get Part array and Category array. After searching in google I found:

let resultJson = try JSONSerialization.jsonObject(with: data, options: []) as? [String : AnyObject]
print(resultJson!)

But it throws fatal error: unexpectedly found nil while unwrapping an Optional value.

I'm new to swift I don't know how to convert it. I have completed this in Android so I can surely say I get above response from server. I write a common function for calling web service, it works for other services so I think there is no problem in that.

How can I parse my response so I can get Part array and Category array?
Thank you.

Body:
Your JSON structure has a top level array, so you cannot parse is as a dictionary. Try to do this

let resultJson = try JSONSerialization.jsonObject(with: data, options: []) as? [Any]
dump(resultJson!)

Sample code will be something like this. Don't forget to handle unwrap stuff

let str = "[{\"Part\":{\"id\":\"418502\",\"uuid\":\"21ec7cdb-cd2d-4b12-8a90-775762eb0f26\"},\"Category\":{\"category_name\":\"Regulators\",\"category_code\":\"RG\"}},{\"Part\":{\"id\":\"418502\",\"uuid\":\"21ec7cdb-cd2d-4b12-8a90-775762eb0f26\"},\"Category\":{\"category_name\":\"Regulators\",\"category_code\":\"RG\"}}]"

let data = str.data(using: .utf8)

do{
    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [Any]
    let dicInFirstElement = json?[0] as? [String: Any]
    let part = dicInFirstElement?["Part"]
    dump(part)
    //Pass this json into the following function
}catch let error{

}


问:
Django. How to return QuerySet order_by result of a fuzzy wuzzy method?
Here is my model:

```<code>class Item(models.Model):
    status = models.IntegerField(choices=STATUS_CHOICES, default=3)
    def __str__(self):
        return 'Item: {0}'.format(self.id)

class Name(models.Model):
    name = models.CharField(, max_length=600, default='')
    item = models.ForeignKey(Item, db_index=True, blank=True, null=True)
    main = models.BooleanField(default=False)

    def __str__(self):
        return '{}'.format(self.name)
</code>```

I would like to query set Items, so it returns X items sorted by Fuzzy wuzzy.
Basically, I need to find matching Items and merge them.

I tried to create a dictionary, but it is extremely slow. I have about 80 000 items and it's still counting.

I tried to something like:

```<code>items = Item.objects.filter(status=3)
                 .annotate( score=fuzz.ratio(query,i.name_set.all().first().name))
                 .order_by('-score')
</code>```

Can anyone give me some light on the topic?
thanks

答:
If there are 80.000 entries in the database you have to consider the options:

(A) let the database sort (preferrably using some pre-created index) and return only the chosen rows. This allows for paging via the database.

(B) return everything from the DB as fast as possible and sort all 80.000 in RAM. If you want to stick to the python module FuzzyWuzzy you would have to do that. But as you have experienced by now, this might not be fast. You'd have to do paging on your own.

[FuzzyWuzzy] uses Levenshtein Distance to calculate the differences between sequences in a simple-to-use package.

If you are using PostgreSQL as backend, you can use the levenshtein function as described here:

https://www.postgresql.org/docs/9.1/static/fuzzystrmatch.html

There seem to be contributions to Django to integrate this:
https://github.com/django/django/pull/4825

TrigramSimilarity is already available. You could have a look at the source code and implement something similar based on the postgres levenshtein. But I'd recommend to first try it out. It might already suit your needs.

EDIT:

In general for tables of this size and more, make sure that your DB has indexes where required and makes use of them. For example: Django's __icontains filter is not covered by Django's db_index. You have to add a trigram index on that column yourself.

It could be that your current code takes this long because the query already takes unnecessarily long.

Body:
Here is my model:

class Item(models.Model):
    status = models.IntegerField(choices=STATUS_CHOICES, default=3)
    def __str__(self):
        return 'Item: {0}'.format(self.id)

class Name(models.Model):
    name = models.CharField(, max_length=600, default='')
    item = models.ForeignKey(Item, db_index=True, blank=True, null=True)
    main = models.BooleanField(default=False)

    def __str__(self):
        return '{}'.format(self.name)

I would like to query set Items, so it returns X items sorted by Fuzzy wuzzy.
Basically, I need to find matching Items and merge them.

I tried to create a dictionary, but it is extremely slow. I have about 80 000 items and it's still counting.

I tried to something like:

items = Item.objects.filter(status=3)
                 .annotate( score=fuzz.ratio(query,i.name_set.all().first().name))
                 .order_by('-score')

Can anyone give me some light on the topic?
thanks


问:
Test value between x and y
I have two data.frames, one with the value "size" to test and the other has the interval N1 to N2 to test. If it's the case, so it will print TRUE into a new column "test"

答:
Not 100% sure, do you want TRUE/FALSE be based if size from Df1 is within N1 and N2 from Df2? If so you could use %between% from data.table.

```<code>df1 <- read.table(text = "size    ID
                   399     ID1
                  887     ID2
                  350     ID1
                  1400    ID2
                  1455    ID2
                  1700    ID2
                  1654    ID1
                  928     ID1
                  1228    ID1", header = T)

df2 <- read.table(text = "ID  N1      N2
ID1 298     500
                  ID1 560     706
                  ID1 809     925
                  ID1 959     1195
                  ID1 1126    1472
                  ID1 1386    1413
                  ID2  800    950
                  ID2 1074    1203
                  ID2 1462    1486
                  ID2 1542    1658", header = T)
</code>```

library(data.table)

```<code>df1$Test <- ifelse(df1$size %between% c(df2$N1, df2$N2), TRUE, FALSE)
</code>```

This answer does not return what you expect though, as I dont really understand what the TRUE/FALSE should be based on.

Title: Test value between x and y

Body:
Not 100% sure, do you want TRUE/FALSE be based if size from Df1 is within N1 and N2 from Df2? If so you could use %between% from data.table.

df1 <- read.table(text = "size    ID
                   399     ID1
                  887     ID2
                  350     ID1
                  1400    ID2
                  1455    ID2
                  1700    ID2
                  1654    ID1
                  928     ID1
                  1228    ID1", header = T)

df2 <- read.table(text = "ID  N1      N2
ID1 298     500
                  ID1 560     706
                  ID1 809     925
                  ID1 959     1195
                  ID1 1126    1472
                  ID1 1386    1413
                  ID2  800    950
                  ID2 1074    1203
                  ID2 1462    1486
                  ID2 1542    1658", header = T)

library(data.table)

df1$Test <- ifelse(df1$size %between% c(df2$N1, df2$N2), TRUE, FALSE)

This answer does not return what you expect though, as I dont really understand what the TRUE/FALSE should be based on.


问:
AppKernel.php weird behavior
So, I am trying to make a new project, but something is happening with kernel, which I don't really understand.
Every time when I generate new Bundle and try to create Controllers or anything, this error appears:

PHP Fatal error:  Uncaught
Symfony\Component\Debug\Exception\ClassNotFoundException: Attempted to
load class "ContactBoxBundle" from namespace "ContactBoxBundle". Did
you forget a "use" statement for another namespace? in
/var/www/ContactBox/app/AppKernel.php:19 Stack trace:

0 /var/www/ContactBox/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php(450):

AppKernel->registerBundles()

1 /var/www/ContactBox/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php(116):

Symfony\Component\HttpKernel\Kernel->initializeBundles()

2 /var/www/ContactBox/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Console/Application.php(137):

Symfony\Component\HttpKernel\Kernel->boot()

3 /var/www/ContactBox/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Console/Application.php(124):

Symfony\Bundle\FrameworkBundle\Console\Application->registerCommands()

4 /var/www/ContactBox/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php(90):

Symfony\Bundle\FrameworkBundle\Console\Application->ad in
/var/www/ContactBox/app/AppKernel.php on line 19

I have made project on Symfony before and it have never happen to me. Any ideas? I generated Bundle using console command "bin/console generate:bundle". It generate everything what it supposed to, co default controller, templates and class, but I am not able to do anything with this further, because of this error. Any ideas?

AppKernel.php

```<code><?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = [
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new AppBundle\AppBundle(),
            new ContactBoxBundle\ContactBoxBundle(),
        ];

        if (in_array($this->getEnvironment(), ['dev', 'test'], true)) {
            $bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();

            if ('dev' === $this->getEnvironment()) {
                $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
                $bundles[] = new Symfony\Bundle\WebServerBundle\WebServerBundle();
            }
        }

        return $bundles;
    }

    public function getRootDir()
    {
        return __DIR__;
    }

    public function getCacheDir()
    {
        return dirname(__DIR__).'/var/cache/'.$this->getEnvironment();
    }

    public function getLogDir()
    {
        return dirname(__DIR__).'/var/logs';
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');
    }
}
</code>```

ContacBoxBundle.php

```<code><?php

namespace ContactBoxBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class ContactBoxBundle extends Bundle
{
}
</code>```

composer.json

```<code>{
    "name": "root/contactbox",
    "license": "proprietary",
    "type": "project",
    "autoload": {
        "psr-4": {
            "AppBundle\\": "src/AppBundle"
        },
        "classmap": [
            "app/AppKernel.php",
            "app/AppCache.php"
        ]
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        },
        "files": [
            "vendor/symfony/symfony/src/Symfony/Component/VarDumper/Resources/functions/dump.php"
        ]
    },
    "require": {
        "php": ">=5.5.9",
        "doctrine/doctrine-bundle": "^1.6",
        "doctrine/orm": "^2.5",
        "incenteev/composer-parameter-handler": "^2.0",
        "sensio/distribution-bundle": "^5.0.19",
        "sensio/framework-extra-bundle": "^3.0.2",
        "symfony/monolog-bundle": "^3.1.0",
        "symfony/polyfill-apcu": "^1.0",
        "symfony/swiftmailer-bundle": "^2.3.10",
        "symfony/symfony": "3.3.*",
        "twig/twig": "^1.0||^2.0"
    },
    "require-dev": {
        "sensio/generator-bundle": "^3.0",
        "symfony/phpunit-bridge": "^3.0"
    },
    "scripts": {
        "symfony-scripts": [
            "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::prepareDeploymentTarget"
        ],
        "post-install-cmd": [
            "@symfony-scripts"
        ],
        "post-update-cmd": [
            "@symfony-scripts"
        ]
    },
    "config": {
        "sort-packages": true
    },
    "extra": {
        "symfony-app-dir": "app",
        "symfony-bin-dir": "bin",
        "symfony-var-dir": "var",
        "symfony-web-dir": "web",
        "symfony-tests-dir": "tests",
        "symfony-assets-install": "relative",
        "incenteev-parameters": {
            "file": "app/config/parameters.yml"
        },
        "branch-alias": null
    }
}
</code>```

Please help, I'm getting crazy because of that!

答:
Try to change your composer.json file from this:

```<code>"psr-4": {
    "AppBundle\\": "src/AppBundle"
 }
</code>```

to this:

```<code>"psr-4": {
    "": "src/"
},
</code>```

In this way you load all Bundle under src.

Like this:

```<code>"psr-4": {
    "AppBundle\\": "src/AppBundle",
    "ContactBoxBundle\\": "src/ContactBoxBundle",
}
</code>```

Or you can specify every Bundle to load if you want.

After that you need to make from console:

```<code>composer dump-autoload
</code>```

Title: AppKernel.php weird behavior

Body:
So, I am trying to make a new project, but something is happening with kernel, which I don't really understand.
Every time when I generate new Bundle and try to create Controllers or anything, this error appears:

PHP Fatal error:  Uncaught
Symfony\Component\Debug\Exception\ClassNotFoundException: Attempted to
load class "ContactBoxBundle" from namespace "ContactBoxBundle". Did
you forget a "use" statement for another namespace? in
/var/www/ContactBox/app/AppKernel.php:19 Stack trace:

0 /var/www/ContactBox/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php(450):

AppKernel->registerBundles()

1 /var/www/ContactBox/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php(116):

Symfony\Component\HttpKernel\Kernel->initializeBundles()

2 /var/www/ContactBox/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Console/Application.php(137):

Symfony\Component\HttpKernel\Kernel->boot()

3 /var/www/ContactBox/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Console/Application.php(124):

Symfony\Bundle\FrameworkBundle\Console\Application->registerCommands()

4 /var/www/ContactBox/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php(90):

Symfony\Bundle\FrameworkBundle\Console\Application->ad in
/var/www/ContactBox/app/AppKernel.php on line 19

I have made project on Symfony before and it have never happen to me. Any ideas? I generated Bundle using console command "bin/console generate:bundle". It generate everything what it supposed to, co default controller, templates and class, but I am not able to do anything with this further, because of this error. Any ideas?

AppKernel.php

<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = [
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new AppBundle\AppBundle(),
            new ContactBoxBundle\ContactBoxBundle(),
        ];

        if (in_array($this->getEnvironment(), ['dev', 'test'], true)) {
            $bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();

            if ('dev' === $this->getEnvironment()) {
                $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
                $bundles[] = new Symfony\Bundle\WebServerBundle\WebServerBundle();
            }
        }

        return $bundles;
    }

    public function getRootDir()
    {
        return __DIR__;
    }

    public function getCacheDir()
    {
        return dirname(__DIR__).'/var/cache/'.$this->getEnvironment();
    }

    public function getLogDir()
    {
        return dirname(__DIR__).'/var/logs';
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');
    }
}

ContacBoxBundle.php

<?php

namespace ContactBoxBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class ContactBoxBundle extends Bundle
{
}

composer.json

{
    "name": "root/contactbox",
    "license": "proprietary",
    "type": "project",
    "autoload": {
        "psr-4": {
            "AppBundle\\": "src/AppBundle"
        },
        "classmap": [
            "app/AppKernel.php",
            "app/AppCache.php"
        ]
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        },
        "files": [
            "vendor/symfony/symfony/src/Symfony/Component/VarDumper/Resources/functions/dump.php"
        ]
    },
    "require": {
        "php": ">=5.5.9",
        "doctrine/doctrine-bundle": "^1.6",
        "doctrine/orm": "^2.5",
        "incenteev/composer-parameter-handler": "^2.0",
        "sensio/distribution-bundle": "^5.0.19",
        "sensio/framework-extra-bundle": "^3.0.2",
        "symfony/monolog-bundle": "^3.1.0",
        "symfony/polyfill-apcu": "^1.0",
        "symfony/swiftmailer-bundle": "^2.3.10",
        "symfony/symfony": "3.3.*",
        "twig/twig": "^1.0||^2.0"
    },
    "require-dev": {
        "sensio/generator-bundle": "^3.0",
        "symfony/phpunit-bridge": "^3.0"
    },
    "scripts": {
        "symfony-scripts": [
            "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::prepareDeploymentTarget"
        ],
        "post-install-cmd": [
            "@symfony-scripts"
        ],
        "post-update-cmd": [
            "@symfony-scripts"
        ]
    },
    "config": {
        "sort-packages": true
    },
    "extra": {
        "symfony-app-dir": "app",
        "symfony-bin-dir": "bin",
        "symfony-var-dir": "var",
        "symfony-web-dir": "web",
        "symfony-tests-dir": "tests",
        "symfony-assets-install": "relative",
        "incenteev-parameters": {
            "file": "app/config/parameters.yml"
        },
        "branch-alias": null
    }
}

Please help, I'm getting crazy because of that!

Body:
Try to change your composer.json file from this:

"psr-4": {
    "AppBundle\\": "src/AppBundle"
 }

to this:

"psr-4": {
    "": "src/"
},

In this way you load all Bundle under src.

Like this:

"psr-4": {
    "AppBundle\\": "src/AppBundle",
    "ContactBoxBundle\\": "src/ContactBoxBundle",
}

Or you can specify every Bundle to load if you want.

After that you need to make from console:

composer dump-autoload