问:
autofac and owned instances
I have been reasing about owned instances and I have a need to set one up.
http://docs.autofac.org/en/latest/advanced/owned-instances.html

I have 2 methods in the same class that use this owned instance. I have set it up like this:

```<code>private readonly Func<SessionDetails, Owned<ITroposUnitOfWork>> _paramatizedTroposUnitOfWork;
</code>```

My unit of work class constructor looks like this:

```<code>/// <summary>
/// Used for creating manual sessions
/// </summary>
/// <param name="sessionDetails">The details of the session to be created</param>
public TroposUnitOfWork(SessionDetails sessionDetails)
{

    // Throw if we don't supply any details
    ThrowIf.ArgumentIsNull(() => sessionDetails);

    // Start the session
    StartSession(sessionDetails);
}
</code>```

So, my understanding is that if I use a using block, then the unit of work will be disposed of at the end of the call. But it isn't.
Like I mentioned before, I have 2 methods that use this owned instance. They are:

```<code>/// <summary>
/// Creates the Tropos user
/// </summary>
/// <param name="model">The user to be created</param>
/// <param name="password">The password to set</param>
private async Task CreateTroposUserAsync(User model, string password)
{

    // If there is no password, throw an error
    ThrowIf.ArgumentIsNull(() => password);

    // Get our master user
    var user = await base.FindByNameAsync(model.Master);

    // If we have no master user, throw an error
    if (user == null) throw new ObjectNotFoundException();

    // Create our session details
    var sessionDetails = _troposSession.Value.Create(user);

    // User our new user
    using (var troposUnitOfWork = _paramatizedTroposUnitOfWork(sessionDetails))
    {

        try
        {

            // Create our tropos user service
            var userService = new TroposUserService(troposUnitOfWork.Value);

            // Create our user
            var transaction = userService.Create(model);

            // Save our changes (Don't throw an error if the user already exists)
            troposUnitOfWork.Value.RunTransaction(transaction);

        } catch (Exception ex)
        {

            // Display human readable messages
            throw new Exception(ex.Message);
        }
    }

    // Sets the new users password
    SetTroposPassword(model, password);

    // Update the flag
    model.HasTroposLogin = true;
}
</code>```

And the other one is:

```<code>/// <summary>
/// Sets the tropos password
/// </summary>
/// <param name="model">The user that needs the password setting</param>
/// <param name="password"></param>
private void SetTroposPassword(User model, string password)
{

    // Create our session details
    var sessionDetails = _troposSession.Value.Create(model.UserName);

    // Create our anonymous session
    using (var troposUnitOfWork = _paramatizedTroposUnitOfWork(sessionDetails))
    {

        // Create our tropos user service
        var userService = new TroposUserService(troposUnitOfWork.Value);

        // Set our password
        var transaction = userService.ChangePassword(password);

        // Save our changes
        troposUnitOfWork.Value.RunTransaction(transaction);
    }
}
</code>```

The first method does invoke the second method, but outside the using block. I put a breakpoint in the TroposUnitOfWork dispose method and it only gets hit once. The constructor is only hit once too.
Does anyone know why?

答:
We need to see the initialization of  _paramatizedTroposUnitOfWork.
What class has the CreateTroposUserAsync method? We need to see the constructor of that class. I suppose your overall goal is to get a unit of work implementation.

The reason why you only hit constructor once, might be due to the lifetime you used when registering. If its Owned. Then the two methods probably execute in the same lifetime scope and the dependency is only resolved once. Or put differently the _paramatizedTroposUnitOfWork(sessionDetails) returns the same instance.

I've solved similar problem using decorators and factories

```<code>public interface IEventHandlerFactory<in TNotification> where TNotification
    : class, IAsyncNotification
{
    IAsyncNotificationHandler<TNotification> Create( ILifetimeScope
                                                           lifetimeScope );
}

public class EventHandlerFactory<TNotification, TEventHandler> :
       IEventHandlerFactory<TNotification>
       where TNotification : class, IAsyncNotification
       where TEventHandler : class, IAsyncNotificationHandler<TNotification>
{
    public IAsyncNotificationHandler<TNotification> Create( ILifetimeScope
                   lifetimeScope )
    {
        return lifetimeScope.ResolveNamed<TEventHandler>( "EventHandler" )
                      as IAsyncNotificationHandler<TNotification>;
    }
}
</code>```

full .net fiddle is here https://dotnetfiddle.net/fw4IBw

Title: autofac and owned instances

Body:
I have been reasing about owned instances and I have a need to set one up.
http://docs.autofac.org/en/latest/advanced/owned-instances.html

I have 2 methods in the same class that use this owned instance. I have set it up like this:

private readonly Func<SessionDetails, Owned<ITroposUnitOfWork>> _paramatizedTroposUnitOfWork;

My unit of work class constructor looks like this:

///
/// Used for creating manual sessions
///
/// <param name="sessionDetails">The details of the session to be created</param>
public TroposUnitOfWork(SessionDetails sessionDetails)
{

    // Throw if we don't supply any details
    ThrowIf.ArgumentIsNull(() => sessionDetails);

    // Start the session
    StartSession(sessionDetails);
}

So, my understanding is that if I use a using block, then the unit of work will be disposed of at the end of the call. But it isn't.
Like I mentioned before, I have 2 methods that use this owned instance. They are:

///
/// Creates the Tropos user
///
/// <param name="model">The user to be created</param>
/// <param name="password">The password to set</param>
private async Task CreateTroposUserAsync(User model, string password)
{

    // If there is no password, throw an error
    ThrowIf.ArgumentIsNull(() => password);

    // Get our master user
    var user = await base.FindByNameAsync(model.Master);

    // If we have no master user, throw an error
    if (user == null) throw new ObjectNotFoundException();

    // Create our session details
    var sessionDetails = _troposSession.Value.Create(user);

    // User our new user
    using (var troposUnitOfWork = _paramatizedTroposUnitOfWork(sessionDetails))
    {

        try
        {

            // Create our tropos user service
            var userService = new TroposUserService(troposUnitOfWork.Value);

            // Create our user
            var transaction = userService.Create(model);

            // Save our changes (Don't throw an error if the user already exists)
            troposUnitOfWork.Value.RunTransaction(transaction);

        } catch (Exception ex)
        {

            // Display human readable messages
            throw new Exception(ex.Message);
        }
    }

    // Sets the new users password
    SetTroposPassword(model, password);

    // Update the flag
    model.HasTroposLogin = true;
}

And the other one is:

///
/// Sets the tropos password
///
/// <param name="model">The user that needs the password setting</param>
/// <param name="password"></param>
private void SetTroposPassword(User model, string password)
{

    // Create our session details
    var sessionDetails = _troposSession.Value.Create(model.UserName);

    // Create our anonymous session
    using (var troposUnitOfWork = _paramatizedTroposUnitOfWork(sessionDetails))
    {

        // Create our tropos user service
        var userService = new TroposUserService(troposUnitOfWork.Value);

        // Set our password
        var transaction = userService.ChangePassword(password);

        // Save our changes
        troposUnitOfWork.Value.RunTransaction(transaction);
    }
}

The first method does invoke the second method, but outside the using block. I put a breakpoint in the TroposUnitOfWork dispose method and it only gets hit once. The constructor is only hit once too.
Does anyone know why?

Body:
We need to see the initialization of  _paramatizedTroposUnitOfWork.
What class has the CreateTroposUserAsync method? We need to see the constructor of that class. I suppose your overall goal is to get a unit of work implementation.

The reason why you only hit constructor once, might be due to the lifetime you used when registering. If its Owned. Then the two methods probably execute in the same lifetime scope and the dependency is only resolved once. Or put differently the _paramatizedTroposUnitOfWork(sessionDetails) returns the same instance.

I've solved similar problem using decorators and factories

public interface IEventHandlerFactory<in TNotification> where TNotification
    : class, IAsyncNotification
{
    IAsyncNotificationHandler<TNotification> Create( ILifetimeScope
                                                           lifetimeScope );
}

public class EventHandlerFactory<TNotification, TEventHandler> :
       IEventHandlerFactory<TNotification>
       where TNotification : class, IAsyncNotification
       where TEventHandler : class, IAsyncNotificationHandler<TNotification>
{
    public IAsyncNotificationHandler<TNotification> Create( ILifetimeScope
                   lifetimeScope )
    {
        return lifetimeScope.ResolveNamed<TEventHandler>( "EventHandler" )
                      as IAsyncNotificationHandler<TNotification>;
    }
}

full .net fiddle is here https://dotnetfiddle.net/fw4IBw


来源: stackexchange

问:
Autoconf: Check if a program in an unsupported language compiles
To conditionally enable a part of an autotooled project, I need to check whether a short program stub in a language not supported by autotools out of the box compiles or not.

I need something like AC_TRY_COMPILE with an arbitrary compiler executable – create a temporary file, write a piece of code to it, and try if invoking the compiler (found via AC_CHECK_PROGS before) returns an exit code equal to zero or not.

What is the most elegant/common way to do this?

答:
AC_TRY_COMPILE (which is deprecated and replaced by AC_COMPILE_IFELSE) only supports a limited set of languages: C, C++, Fortran 77, Fortran, Erlang, Objective C, Objective C++ (source).

configure.ac can contain custom shell code - it just gets skipped over by autoconf (really m4). Why not just write your test in shell? If you're going to use more than one test, wrap it in an AC_DEFUN.

ContentLicense: CC BY-SA 2.5


问:
Import Elm front-end from github into Phoenix back-end
My team is working on a phoenix/elm application, and have decided to keep the two projects in separate repos, and to 'point' to the elm application from the phoenix app. This is sort of new terrain for me, and I've been looking into different ways to accomplish this. I've tried importing the Elm app as a dependency via package.json, but I believe node_modules/ doesn't recognize Elm code. I've also tried importing it as a dependency via mix.exs, but again deps/ it looking for a exs file. Are there any other approaches to this?</p>

答:
If you're using git, you may want use git submodules for this. It allows you to embed a separate repository within an existing one.

So you could essentially have your Phoenix app as normal, include the Elm app as a submodule, then in your brunch-config.js, reference the Elm app via the elm-brunch plugin.

```<code>elmBrunch: {
  mainModules: ['../path/to/submodule/Main.elm'],
  outputFolder: 'web/static/js/',
  makeParameters: ['--debug']
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If you're using git, you may want use git submodules for this. It allows you to embed a separate repository within an existing one.

So you could essentially have your Phoenix app as normal, include the Elm app as a submodule, then in your brunch-config.js, reference the Elm app via the elm-brunch plugin.

elmBrunch: {
  mainModules: ['../path/to/submodule/Main.elm'],
  outputFolder: 'web/static/js/',
  makeParameters: ['--debug']
}


问:
ruby: convert http response codes to it's meaning
how do you convert http response codes to it's meaning in ruby/rails.
I tried the (imaginary) .to_words method without success

```<code>(byebug) resp.code
201
(byebug) resp.code.to_words
"201 Created"
</code>```

答:
Try</p>

```<code>Rack::Utils::HTTP_STATUS_CODES[200]
</code>```

Body:
how do you convert http response codes to it's meaning in ruby/rails.
I tried the (imaginary) .to_words method without success

(byebug) resp.code
201
(byebug) resp.code.to_words
"201 Created"

Body:
Try

Rack::Utils::HTTP_STATUS_CODES[200]


问:
Multi-language syntax highlighting in Atom
I am doing a project where I have files which have markdown and perl in it. I would like to be able to syntax highlight both of them, is it possible in atom? </p>

答:
It is possible, but it is not perfect.

There is a well-written post about this on discuss.atom.io. Basically, you have to manually edit the language package (like language-markdown or language-perl) and add an extra grammar rule by referring to another language.

For example, adding

```<code>{
    'begin': '`'
    'beginCaptures':
      '0':
        'name': 'punctuation.definition.string.begin.coffee'
    'end': '`'
    'endCaptures':
      '0':
        'name': 'punctuation.definition.string.end.coffee'
    'name': 'string.quoted.script.coffee'
    'patterns': [
      {
        'include': 'source.js'
      }
    ]
  }
</code>```

to language-coffee-script enables syntax-highlighting of javascript between two instances of (`).

Body:
It is possible, but it is not perfect.

There is a well-written post about this on discuss.atom.io. Basically, you have to manually edit the language package (like language-markdown or language-perl) and add an extra grammar rule by referring to another language.

For example, adding

{
    'begin': '`'
    'beginCaptures':
      '0':
        'name': 'punctuation.definition.string.begin.coffee'
    'end': '`'
    'endCaptures':
      '0':
        'name': 'punctuation.definition.string.end.coffee'
    'name': 'string.quoted.script.coffee'
    'patterns': [
      {
        'include': 'source.js'
      }
    ]
  }

to language-coffee-script enables syntax-highlighting of javascript between two instances of (`).


问:
WooCommerce additional email on completed order
I have a question, which need a community support as I couldn't find anything on the web including WooCommerce support forum.

I have a WooCommerce site which is a closed e-commerce store used by local chain of restaurants. Each time stores order anything, GM would also like a email sent to him on completed order, so he can either block the order or approve it. GM1 is responsible for Store1, Store2 and Store3; GM2 is responsible for Store4, Store5, and Store 6 and so forth.

With the help of internet, this is what I have so far in function.php. Function is working properly and getting triggered, but all 3 GMs are getting email, but in theory, only one GM should get email. GM1 for Store1 OR Store2 OR Store3; and GM2 should get email if Store4 OR Store5 OR Store6 orders.

Really appreciate if somebody can point me to the right direction or atleast let me know why all three ifs are getting triggered.

```<code>add_filter( 'woocommerce_email_recipient_customer_completed_order', 'your_email_recipient_filter_function', 10, 2);

function your_email_recipient_filter_function($recipient, $object) {
    if( 'Store1@store.com' || 'Store2@store.com' || 'Store3@store.com' == $recipient ){
        $recipient = $recipient .= ', GM1@store.com';
    }

    if( 'Store4@store.com' || 'Store5@store.com' || 'Store6@store.com' == $recipient ){
        $recipient = $recipient .= ', GM2@store.com';
    }

    if( 'Store7@store.com' || 'Store8@store.com' || 'Store9@store.com' == $recipient ){
        $recipient = $recipient .= ', GM3@store.com';
    }

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

Thanks.

答:
I ended up using an array() as below which seems to be working:</p>

```<code>function your_email_recipient_filter_function( $recipient, $order ) {

$Stores1 = array('Store1@store.com', 'Store2@store.com', 'Store3@store.com');
$Stores2 = array('Store4@store.com', 'Store5@store.com', 'Store6@store.com');
$Stores3 = array('Store7@store.com', 'Store8@store.com', 'Store9@store.com');

$StoreEmail =  $order->billing_email;

if ( in_array( $StoreEmail, $Stores1)) {
    $recipient .= ', GM1@store.com';
} elseif ( in_array( $StoreEmail, $Stores2) ) {
    $recipient .= ', GM2@store.com';
} elseif ( in_array( $StoreEmail, $Stores3) ) {
    $recipient .= ', GM2@store.com';
}
return $recipient;
}
add_filter( 'woocommerce_email_recipient_customer_completed_order', 'your_email_recipient_filter_function', 10, 2);
</code>```

Body:
I have a question, which need a community support as I couldn't find anything on the web including WooCommerce support forum.

I have a WooCommerce site which is a closed e-commerce store used by local chain of restaurants. Each time stores order anything, GM would also like a email sent to him on completed order, so he can either block the order or approve it. GM1 is responsible for Store1, Store2 and Store3; GM2 is responsible for Store4, Store5, and Store 6 and so forth.

With the help of internet, this is what I have so far in function.php. Function is working properly and getting triggered, but all 3 GMs are getting email, but in theory, only one GM should get email. GM1 for Store1 OR Store2 OR Store3; and GM2 should get email if Store4 OR Store5 OR Store6 orders.

Really appreciate if somebody can point me to the right direction or atleast let me know why all three ifs are getting triggered.

add_filter( 'woocommerce_email_recipient_customer_completed_order', 'your_email_recipient_filter_function', 10, 2);

function your_email_recipient_filter_function($recipient, $object) {
    if( 'Store1@store.com' || 'Store2@store.com' || 'Store3@store.com' == $recipient ){
        $recipient = $recipient .= ', GM1@store.com';
    }

    if( 'Store4@store.com' || 'Store5@store.com' || 'Store6@store.com' == $recipient ){
        $recipient = $recipient .= ', GM2@store.com';
    }

    if( 'Store7@store.com' || 'Store8@store.com' || 'Store9@store.com' == $recipient ){
        $recipient = $recipient .= ', GM3@store.com';
    }

    return $recipient;
}

Thanks.

Body:
I ended up using an array() as below which seems to be working:

function your_email_recipient_filter_function( $recipient, $order ) {

$Stores1 = array('Store1@store.com', 'Store2@store.com', 'Store3@store.com');
$Stores2 = array('Store4@store.com', 'Store5@store.com', 'Store6@store.com');
$Stores3 = array('Store7@store.com', 'Store8@store.com', 'Store9@store.com');

$StoreEmail =  $order->billing_email;

if ( in_array( $StoreEmail, $Stores1)) {
    $recipient .= ', GM1@store.com';
} elseif ( in_array( $StoreEmail, $Stores2) ) {
    $recipient .= ', GM2@store.com';
} elseif ( in_array( $StoreEmail, $Stores3) ) {
    $recipient .= ', GM2@store.com';
}
return $recipient;
}
add_filter( 'woocommerce_email_recipient_customer_completed_order', 'your_email_recipient_filter_function', 10, 2);


问:
1/1 NotFoundHttpException in RouteCollection.php line 179:
Router file

```<code>Route::get('index',[
        'as'=>'home',
        'uses'=>'PageController@getIndex'
]);
</code>```

P age Controller

```<code>namespace App\Http\Controllers;
use Illuminate\Http\Request;
class `PageController` extends Controller
{
    public function getIndex(){
        return view('master');
    }
}
</code>```

please help me,i tried but there was a problem :NotFoundHttpException in RouteCollection.php line 179:
thank so much

答:
return view('master'); returns to the folder named master.
Inside that master folder you have to create a blade file, for instance this index.blade.php.

Afterwards you do this in your Controller:

```<code>return view('master.index');
</code>```

That will link to resources/views/master/index.blade.php

Body:
Router file

Route::get('index',[
        'as'=>'home',
        'uses'=>'PageController@getIndex'
]);

P age Controller

namespace App\Http\Controllers;
use Illuminate\Http\Request;
class `PageController` extends Controller
{
    public function getIndex(){
        return view('master');
    }
}

please help me,i tried but there was a problem :NotFoundHttpException in RouteCollection.php line 179:
thank so much

Body:
return view('master'); returns to the folder named master.
Inside that master folder you have to create a blade file, for instance this index.blade.php.

Afterwards you do this in your Controller:

return view('master.index');

That will link to resources/views/master/index.blade.php


问:
Not able to persist the DStream for use in next batch
```<code>JavaRDD<String> history_ = sc.emptyRDD();

java.util.Queue<JavaRDD<String> > queue = new LinkedList<JavaRDD<String>>();
queue.add(history_);
JavaDStream<String> history_dstream = ssc.queueStream(queue);

JavaPairDStream<String,ArrayList<String>> history = history_dstream.mapToPair(r -> {
  return new Tuple2< String,ArrayList<String> >(null,null);
});

 JavaPairInputDStream<String, GenericData.Record> stream_1 =
    KafkaUtils.createDirectStream(ssc, String.class, GenericData.Record.class, StringDecoder.class,
        GenericDataRecordDecoder.class, props, topicsSet_1);

JavaPairInputDStream<String, GenericData.Record> stream_2 =
    KafkaUtils.createDirectStream(ssc, String.class, GenericData.Record.class, StringDecoder.class,
        GenericDataRecordDecoder.class, props, topicsSet_2);
</code>```

then doing some transformation and creating twp DStream Data_1 and Data_2 of type

```<code>JavaPairDStream<String, <ArrayList<String>>
</code>```

and do the join as below , then filtering out those records for whom there was no joining key and saving them in history for using it in next batch by doing its union with Data_1

```<code> Data_1 = Data_1.union(history);

JavaPairDStream<String, Tuple2<ArrayList<String>, Optional<ArrayList<String>>>> joined =
    Data_1.leftOuterJoin(Data_2).cache();

JavaPairDStream<String, Tuple2<ArrayList<String>, Optional<ArrayList<String>>>> notNULL_join = joined.filter(r -> r._2._2().isPresent());
JavaPairDStream<String, Tuple2<ArrayList<String>, Optional<ArrayList<String>>>> dstream_filtered = joined.filter(r -> !r._2._2().isPresent());

history = dstream_filtered.mapToPair(r -> {
  return new Tuple2<>(r._1,r._2._1);
}).persist;
</code>```

I get history after the previous step(checked by saving it to hdfs) , but still this history is empty in batch while doing union.

答:
It's conceptually not possible to "remember" a DStream. DStreams are time-bound and on each clock-tick (called "batch interval") the DStream represents the observed data in the stream during that period of time.

Hence, we cannot have an "old" DStream saved to join with a "new" DStream. All DStreams live in the "now".

The underlying data structure of DStreams is the RDD: Each batch interval, our DStream will have 1 RDD of the data for that interval.
RDDs represent a distributed collection of data. RDDs are immutable and permanent, for as long as we have a reference to them.

We can combine RDDs and DStreams to create the "history roll over" that's required here.

It looks pretty similar to the approach on the question, but only using the history RDD.

Here's a high-level view of the suggested changes:

```<code>var history: RDD[(String, List[String]) = sc.emptyRDD()

val dstream1 = ...
val dstream2 = ...

val historyDStream = dstream1.transform(rdd => rdd.union(history))
val joined = historyDStream.join(dstream2)

... do stuff with joined as above, obtain dstreamFiltered ...

dstreamFiltered.foreachRDD{rdd =>
   val formatted = rdd.map{case (k,(v1,v2)) => (k,v1)} // get rid of the join info
   history.unpersist(false) // unpersist the 'old' history RDD
   history = formatted // assign the new history
   history.persist(StorageLevel.MEMORY_AND_DISK) // cache the computation
   history.count() //action to materialize this transformation
}
</code>```

This is only a starting point. There're additional considerations with regards to checkpointing. Otherwise the lineage of the history RDD will grow unbounded until some StackOverflow happens. This blog is quite complete on this particular technique: http://www.spark.tc/stateful-spark-streaming-using-transform/

I also recommend you using Scala instead of Java. The Java syntax is too verbose to use with Spark Streaming.

Body:
JavaRDD<String> history_ = sc.emptyRDD();

java.util.Queue<JavaRDD<String> > queue = new LinkedList<JavaRDD<String>>();
queue.add(history_);
JavaDStream<String> history_dstream = ssc.queueStream(queue);

JavaPairDStream<String,ArrayList<String>> history = history_dstream.mapToPair(r -> {
  return new Tuple2< String,ArrayList<String> >(null,null);
});

 JavaPairInputDStream<String, GenericData.Record> stream_1 =
    KafkaUtils.createDirectStream(ssc, String.class, GenericData.Record.class, StringDecoder.class,
        GenericDataRecordDecoder.class, props, topicsSet_1);

JavaPairInputDStream<String, GenericData.Record> stream_2 =
    KafkaUtils.createDirectStream(ssc, String.class, GenericData.Record.class, StringDecoder.class,
        GenericDataRecordDecoder.class, props, topicsSet_2);

then doing some transformation and creating twp DStream Data_1 and Data_2 of type

JavaPairDStream<String, <ArrayList<String>>

and do the join as below , then filtering out those records for whom there was no joining key and saving them in history for using it in next batch by doing its union with Data_1

 Data_1 = Data_1.union(history);

JavaPairDStream<String, Tuple2<ArrayList<String>, Optional<ArrayList<String>>>> joined =
    Data_1.leftOuterJoin(Data_2).cache();

JavaPairDStream<String, Tuple2<ArrayList<String>, Optional<ArrayList<String>>>> notNULL_join = joined.filter(r -> r._2._2().isPresent());
JavaPairDStream<String, Tuple2<ArrayList<String>, Optional<ArrayList<String>>>> dstream_filtered = joined.filter(r -> !r._2._2().isPresent());

history = dstream_filtered.mapToPair(r -> {
  return new Tuple2<>(r._1,r._2._1);
}).persist;

I get history after the previous step(checked by saving it to hdfs) , but still this history is empty in batch while doing union.

Body:
It's conceptually not possible to "remember" a DStream. DStreams are time-bound and on each clock-tick (called "batch interval") the DStream represents the observed data in the stream during that period of time.

Hence, we cannot have an "old" DStream saved to join with a "new" DStream. All DStreams live in the "now".

The underlying data structure of DStreams is the RDD: Each batch interval, our DStream will have 1 RDD of the data for that interval.
RDDs represent a distributed collection of data. RDDs are immutable and permanent, for as long as we have a reference to them.

We can combine RDDs and DStreams to create the "history roll over" that's required here.

It looks pretty similar to the approach on the question, but only using the history RDD.

Here's a high-level view of the suggested changes:

var history: RDD[(String, List[String]) = sc.emptyRDD()

val dstream1 = ...
val dstream2 = ...

val historyDStream = dstream1.transform(rdd => rdd.union(history))
val joined = historyDStream.join(dstream2)

... do stuff with joined as above, obtain dstreamFiltered ...

dstreamFiltered.foreachRDD{rdd =>
   val formatted = rdd.map{case (k,(v1,v2)) => (k,v1)} // get rid of the join info
   history.unpersist(false) // unpersist the 'old' history RDD
   history = formatted // assign the new history
   history.persist(StorageLevel.MEMORY_AND_DISK) // cache the computation
   history.count() //action to materialize this transformation
}

This is only a starting point. There're additional considerations with regards to checkpointing. Otherwise the lineage of the history RDD will grow unbounded until some StackOverflow happens. This blog is quite complete on this particular technique: http://www.spark.tc/stateful-spark-streaming-using-transform/

I also recommend you using Scala instead of Java. The Java syntax is too verbose to use with Spark Streaming.


问:
merge values in two rows in an sql table appear in two columns of one row
I need help in SQL. I have a table with this structure.

:

What I need is a query to return the data like this.

:

Thank you very much in advance!

Kind regards,
bgergoe

答:
This has been asked and answered dozens of times but it is super simple to write out the code. Conditional aggregation is pretty straight forward and the code is far less obtuse than PIVOT. Here is how you would go about this.</p>

```<code>SELECT ID
    , MAX(CASE WHEN Field = 'name' THEN Value END) AS name
    , MAX(CASE WHEN Field = 'phone number' THEN Value END) AS PhoneNumber
FROM YourTable
GROUP BY ID
</code>```

Body:
This has been asked and answered dozens of times but it is super simple to write out the code. Conditional aggregation is pretty straight forward and the code is far less obtuse than PIVOT. Here is how you would go about this.

SELECT ID
    , MAX(CASE WHEN Field = 'name' THEN Value END) AS name
    , MAX(CASE WHEN Field = 'phone number' THEN Value END) AS PhoneNumber
FROM YourTable
GROUP BY ID


问:
How to Apply Filter Couchbase Server Using c#
This is my json Data

```<code>{
"_id":"biking",
"_rev":"AE19EBC7654",
"type":"user",
"body":"My biggest hobby is mountainbiking. The other day...",
"date":"2009/01/30 18:04:11"
}
{
"_id":"biking",
"_rev":"AE19EBC7654",
"type":"testuser",
"body":"My biggest hobby is mountainbiking. The other day...",
"date":"2009/01/30 18:04:11"
}
</code>```

Here is what is tried so far

```<code>var pull = _db.CreatePullReplication(syncGatewayUri);
var push = _db.CreatePushReplication(syncGatewayUri);

 _db.SetFilter("byUser", (revision, filterParams) =>
{
var typeParam = filterParams["type"].ToString();

return (typeParam != null) && typeParam.Equals("USer");
});

pull.Filter ="byUser";
</code>```

i want to get result that contain only type user. But i not able to apply filter.

答:
So if you want to create a filter for Users only, you don't need a param. What you want to do is return true if the document's type is "user".

Here's an example :

```<code>var pull = _db.CreatePullReplication(syncGatewayUri);
var push = _db.CreatePushReplication(syncGatewayUri);

 _db.SetFilter("byUser", (revision, filterParams) =>
{
  //We get the type property
  var docType = (string)revision.GetProperty("type");
  //We make sure it's a user
  return !String.IsNullOrEmpty(docType) && docType.toLowerCase() == "user";
});

pull.Filter ="byUser";
</code>```

If you want to be more dynamic, you can create a filter byType and specify the "user" type parameter.

Example :

```<code>var pull = _db.CreatePullReplication(syncGatewayUri);
var push = _db.CreatePushReplication(syncGatewayUri);

 _db.SetFilter("byType", (revision, filterParams) =>
{
var typeParam = filterParams["type"].ToString();
var docType = (string)revision.GetProperty("type");
return (typeParam != null) && !String.isNullOrEmpty(docType) && typeParam.toLowerCase() == docType.toLowerCase();
})

pull.Filter ="byType";
pull.FilterParams = new Dictionary<string, object> { {"type", "user"} };
</code>```

For more details, see CouchBase documentation.

Body:
This is my json Data

{
"_id":"biking",
"_rev":"AE19EBC7654",
"type":"user",
"body":"My biggest hobby is mountainbiking. The other day...",
"date":"2009/01/30 18:04:11"
}
{
"_id":"biking",
"_rev":"AE19EBC7654",
"type":"testuser",
"body":"My biggest hobby is mountainbiking. The other day...",
"date":"2009/01/30 18:04:11"
}

Here is what is tried so far

var pull = _db.CreatePullReplication(syncGatewayUri);
var push = _db.CreatePushReplication(syncGatewayUri);

 _db.SetFilter("byUser", (revision, filterParams) =>
{
var typeParam = filterParams["type"].ToString();

return (typeParam != null) && typeParam.Equals("USer");
});

pull.Filter ="byUser";

i want to get result that contain only type user. But i not able to apply filter.

Body:
So if you want to create a filter for Users only, you don't need a param. What you want to do is return true if the document's type is "user".

Here's an example :

var pull = _db.CreatePullReplication(syncGatewayUri);
var push = _db.CreatePushReplication(syncGatewayUri);

 _db.SetFilter("byUser", (revision, filterParams) =>
{
  //We get the type property
  var docType = (string)revision.GetProperty("type");
  //We make sure it's a user
  return !String.IsNullOrEmpty(docType) && docType.toLowerCase() == "user";
});

pull.Filter ="byUser";

If you want to be more dynamic, you can create a filter byType and specify the "user" type parameter.

Example :

var pull = _db.CreatePullReplication(syncGatewayUri);
var push = _db.CreatePushReplication(syncGatewayUri);

 _db.SetFilter("byType", (revision, filterParams) =>
{
var typeParam = filterParams["type"].ToString();
var docType = (string)revision.GetProperty("type");
return (typeParam != null) && !String.isNullOrEmpty(docType) && typeParam.toLowerCase() == docType.toLowerCase();
})

pull.Filter ="byType";
pull.FilterParams = new Dictionary<string, object> { {"type", "user"} };

For more details, see CouchBase documentation.


问:
R Error in validObject(.Object) when running as script, but not in console
The following code works fine in the R console (R 3.3.0):

```<code>m = system.file("external/pores_1.mtx", package = "Matrix")
x = Matrix::readMM(m)
</code>```

I can put it in a script and it runs fine in R console as:

```<code>source("test.R")
</code>```

However, when I execute it as Rscript --vanilla test.R or Rscript test.R, I get an error:

```<code>Error in validObject(.Object) :
  invalid class “dgTMatrix” object: Not a valid 'Mnumeric' class object
Calls: <Anonymous> -> new -> initialize -> initialize -> validObject
Execution halted
</code>```

I don't know if this is related to that specific function. I am guessing this has something to do with how Rscript works, but I used it with various other libraries and functions previously and have never seen anything like this. Any idea what is happening?

答:
Oh dear.
I'm pretty (not 100% !) sure that this problem should not apply in newer version of R and Matrix.
Still I would claim this is not a Matrix bug in a proper sense, rather either an 'Rscript' vs 'R' bug -- as @Stu Field  mentions already;  Rscript does not by default attach the methods package to the search() path,  but regular R does.

OTOH, R CMD check Matrix nowadays should try to run Matrix without the methods package being in the search path, and hence the problem should not be present from Matrix 1.2-9 and newer, i.e., by default from R 3.4.0 and newer or then update the 'Matrix' package if you have an older version of R.

Again: Can  you please confirm that the problem is gone with R 3.4.0 (which has Matrix 1.2-9 "along with it") ?

Here is a more useful example script, I called  Rscript-tst.R.
Run as

```<code>Rscript --vanilla Rscript-tst.R > Rscript-tst.Rout 2>&1
</code>```

or (as myself with many R versions installed) something like

```<code>`R-3.4.0 RHOME`/bin/Rscript --vanilla Rscript-tst.R > Rscript-tst.Rout_R340 2>&1
</code>```

Rscript-tst.R :

```<code>options(echo = TRUE)# << even with "Rscript" or --slave ...
(m <- system.file("external/pores_1.mtx", package = "Matrix"))
packageDescription("Matrix")
## This *load*s the Matrix package but does not attach it to search()
str(Matrix::readMM)
sessionInfo()
x <- Matrix::readMM(m)
## used to fail because 'methods' was not "there" (in Rscript only)
</code>```

Body:
The following code works fine in the R console (R 3.3.0):

m = system.file("external/pores_1.mtx", package = "Matrix")
x = Matrix::readMM(m)

I can put it in a script and it runs fine in R console as:

source("test.R")

However, when I execute it as Rscript --vanilla test.R or Rscript test.R, I get an error:

Error in validObject(.Object) :
  invalid class “dgTMatrix” object: Not a valid 'Mnumeric' class object
Calls: <Anonymous> -> new -> initialize -> initialize -> validObject
Execution halted

I don't know if this is related to that specific function. I am guessing this has something to do with how Rscript works, but I used it with various other libraries and functions previously and have never seen anything like this. Any idea what is happening?

Body:
Oh dear.
I'm pretty (not 100% !) sure that this problem should not apply in newer version of R and Matrix.
Still I would claim this is not a Matrix bug in a proper sense, rather either an 'Rscript' vs 'R' bug -- as @Stu Field  mentions already;  Rscript does not by default attach the methods package to the search() path,  but regular R does.

OTOH, R CMD check Matrix nowadays should try to run Matrix without the methods package being in the search path, and hence the problem should not be present from Matrix 1.2-9 and newer, i.e., by default from R 3.4.0 and newer or then update the 'Matrix' package if you have an older version of R.

Again: Can  you please confirm that the problem is gone with R 3.4.0 (which has Matrix 1.2-9 "along with it") ?

Here is a more useful example script, I called  Rscript-tst.R.
Run as

Rscript --vanilla Rscript-tst.R > Rscript-tst.Rout 2>&1

or (as myself with many R versions installed) something like

`R-3.4.0 RHOME`/bin/Rscript --vanilla Rscript-tst.R > Rscript-tst.Rout_R340 2>&1

Rscript-tst.R :

options(echo = TRUE)# << even with "Rscript" or --slave ...
(m <- system.file("external/pores_1.mtx", package = "Matrix"))
packageDescription("Matrix")
## This *load*s the Matrix package but does not attach it to search()
str(Matrix::readMM)
sessionInfo()
x <- Matrix::readMM(m)
## used to fail because 'methods' was not "there" (in Rscript only)


问:
React cannot find entry file in any of the roots update
I have the following warning when running react-native run-ios:

I know that the question was asked before, but the solutions doesn't seem to work for me... I restarted my OS and it's still not working...

Any ideas?

答:
As I noted in the comments, you can check this github link

The workaround from that thread that seems to work consistently (at least in my case) is to do these steps:

In the current terminal: react-native start

In another terminal: react-native run-android


问:
Adding an array to the session array in Rails
I am using a session based cart for a rails application where I am not allowed to use a database.

I have written this helper to create a the cart if it does not exist in my line_items controller.

```<code>def ensure_cart_exists
  session.push(Array(:cart)) unless session.include?(:cart)
end
</code>```

But I get this error

```<code>undefined method `push' for #<ActionDispatch::Request::Session ...
</code>```

The line of code works in the IRB when I try it on an array. Is there something I don't understand about the session array that prevents me from using it here?

答:
You can do this as well, if you want a one liner:

(session[:cart] ||= []) << `some data`

Body:
I am using a session based cart for a rails application where I am not allowed to use a database.

I have written this helper to create a the cart if it does not exist in my line_items controller.

def ensure_cart_exists
  session.push(Array(:cart)) unless session.include?(:cart)
end

But I get this error

undefined method `push' for #<ActionDispatch::Request::Session ...

The line of code works in the IRB when I try it on an array. Is there something I don't understand about the session array that prevents me from using it here?


问:
Is there a way to use data-template inheritance in WPF?
Is it possible to have DataTemplate composition or inheritance (similar to "BasedOn" in Styles)? There are 2 instances where I need that.

For inherited classes: I have a base class with several inherited classes. I don't want to duplicate the base class template in each of the derived class's DataTemplate.

Different Views: for the same class I want to define a datatemplate, and then add to that template as appropriate. Ex. the base template will display the data in the object and then i want different templates that can perform different actions on the object, while displaying the data (inheriting the base template).

答:
The only thing that I have found do to for this kind of thing is this:

```<code><DataTemplate x:Key="BaseClass">
  <!-- base class template here -->
</DataTemplate>
<DataTemplate DataType="{x:Type app:BaseClass}">
  <ContentPresenter Content="{Binding}"
                    ContentTemplate="{StaticResource BaseClass}"/>
</DataTemplate>
<DataTemplate DataType="{x:Type app:DerivedClass}">
  <StackPanel>
    <ContentPresenter Content="{Binding}"
                      ContentTemplate="{StaticResource BaseClass}"/>
    <!-- derived class extra template here -->
  </StackPanel>
</DataTemplate>
</code>```

Basically this creates a "common" template that can be referenced using a key (BaseClass in this case).  Then we define the real DataTemplate for the base class, and any derived classes.  The derived class template would then add it's own "stuff".

There was some discussion about this on msdn a while back, but no one came up with a better solution that I saw.

Body:
The only thing that I have found do to for this kind of thing is this:

<DataTemplate x:Key="BaseClass">
  <!-- base class template here -->
</DataTemplate>
<DataTemplate DataType="{x:Type app:BaseClass}">
  <ContentPresenter Content="{Binding}"
                    ContentTemplate="{StaticResource BaseClass}"/>
</DataTemplate>
<DataTemplate DataType="{x:Type app:DerivedClass}">
  <StackPanel>
    <ContentPresenter Content="{Binding}"
                      ContentTemplate="{StaticResource BaseClass}"/>
    <!-- derived class extra template here -->
  </StackPanel>
</DataTemplate>

Basically this creates a "common" template that can be referenced using a key (BaseClass in this case).  Then we define the real DataTemplate for the base class, and any derived classes.  The derived class template would then add it's own "stuff".

There was some discussion about this on msdn a while back, but no one came up with a better solution that I saw.


问:
How stored procedure returns from multiple cursor
I have Oracle Stored Procedure below and I understood most of the logic inside except for the part where the caller of the procedure will get all the values from different cursors.

Did some reading that SP returns the OUT part in a procedure parameters shown in the sample below. But i fail to get any reference as to how p_returnCode can store resultsets from queries inside the stored procedure.

Procedure retrieveX(p_date date, p_loc varchar2, p_returnCode out integer)

The stored procedure below have 3 cursors cur1, cur2 and cur3. How or where does it store the values? Cur1 contains 2 columns with multiple rows and Cur2 and Cur3 contains one column with multiple rows.
Can anyone clarify this part?

Caller from cgi script

```<code>report.retrieveX(p_date,p_loc,p_return)
</code>```

Full Stored Procedure

```<code>PROCEDURE retrieveX(
    p_date DATE,
    p_loc VARCHAR2,
    p_returnCode OUT INTEGER
)
AS

    TYPE cur_typ IS REF CURSOR;
    cur1 cur_typ;
  cur2 cur_typ;
  cur3 cur_typ;
    query_str VARCHAR2(2000) := '';
    query_str2 VARCHAR2(2000) := '';
    query_str3 VARCHAR2(2000) := '';
    v_an VARCHAR2(20);
    v_tn VARCHAR2(20);
    v_sOID varchar2(20);

BEGIN

sqlRouteDT := 'AND  sp.ROUTE_DT = TO_DATE(''' || TO_CHAR(p_date, 'YYYY/MM/DD') || ''',''YYYY/MM/DD'')';

IF p_loc IS NOT NULL THEN
  sqlLocation := 'AND   act.location_cd = ''' || p_loc || '''';
END IF;

    p_returnCode := 0;
    query_str := '
                    SELECT distinct
                       sp.ab,
                       y.track,
                    FROM ship sp
                       inner join activ act on sp.soid=act.on
                       inner join peace y on act.on=y.soid
          where
             sp.man is not null
             ' || sqlLocation || '
             ' || sqlRouteDT || '
                    ORDER BY sp.ab asc
        ';
    OPEN cur1 FOR query_str1;
    LOOP
      FETCH cur1
      INTO
        v_AN,
        v_FN
      EXIT WHEN cur1%NOTFOUND;

      query_str2 := '
        SELECT DISTINCT INTER_CD
        FROM    TBL_INTR
        WHERE   AF = ''Y''
          AND   sOID = ''' || v_sOID || '''
        ORDER BY INTER_CD
        ';
      OPEN cur2 FOR query_str2;
      LOOP
        FETCH   cur2
        INTO    v_intr_cd;
        EXIT WHEN cur2%NOTFOUND;
        DBMS_OUTPUT.PUT_LINE('INTER_CD|' || v_intr_cd);
      END LOOP;
      CLOSE cur2;

      query_str3 := '
        SELECT DISTINCT hi_cd
        FROM    tbl_hi
        WHERE   AF = ''Y''
          AND   sOID = ''' || v_sOID || '''
        ORDER BY    hi_cd
        ';
      OPEN cur3 FOR query_str3;
      LOOP
        FETCH   cur3
        INTO    v_hi_c;
        EXIT WHEN cur3%NOTFOUND;
        DBMS_OUTPUT.PUT_LINE('hi_cd|' || v_hi_c);
      END LOOP;
      CLOSE cur3;
    END LOOP;
    CLOSE cur1;
EXCEPTION   WHEN OTHERS THEN
    p_returnCode := 1;
    DBMS_OUTPUT.PUT_LINE(SQLERRM);
END retrieveX;
</code>```

答:
I don't think possible to do that you want.

Maybe you should to considerate the use of pipelined function, please take a look at https://oracle-base.com/articles/misc/pipelined-table-functions

With this technique, you can write a pl/sql code to access to complex data and relationship table and get the result as a simple

```<code> select * from StoredProcedure(Parameter_1...);
</code>```

Body:
I have Oracle Stored Procedure below and I understood most of the logic inside except for the part where the caller of the procedure will get all the values from different cursors.

Did some reading that SP returns the OUT part in a procedure parameters shown in the sample below. But i fail to get any reference as to how p_returnCode can store resultsets from queries inside the stored procedure.

Procedure retrieveX(p_date date, p_loc varchar2, p_returnCode out integer)

The stored procedure below have 3 cursors cur1, cur2 and cur3. How or where does it store the values? Cur1 contains 2 columns with multiple rows and Cur2 and Cur3 contains one column with multiple rows.
Can anyone clarify this part?

Caller from cgi script

report.retrieveX(p_date,p_loc,p_return)

Full Stored Procedure

PROCEDURE retrieveX(
    p_date DATE,
    p_loc VARCHAR2,
    p_returnCode OUT INTEGER
)
AS

    TYPE cur_typ IS REF CURSOR;
    cur1 cur_typ;
  cur2 cur_typ;
  cur3 cur_typ;
    query_str VARCHAR2(2000) := '';
    query_str2 VARCHAR2(2000) := '';
    query_str3 VARCHAR2(2000) := '';
    v_an VARCHAR2(20);
    v_tn VARCHAR2(20);
    v_sOID varchar2(20);

BEGIN

sqlRouteDT := 'AND  sp.ROUTE_DT = TO_DATE(''' || TO_CHAR(p_date, 'YYYY/MM/DD') || ''',''YYYY/MM/DD'')';

IF p_loc IS NOT NULL THEN
  sqlLocation := 'AND   act.location_cd = ''' || p_loc || '''';
END IF;

    p_returnCode := 0;
    query_str := '
                    SELECT distinct
                       sp.ab,
                       y.track,
                    FROM ship sp
                       inner join activ act on sp.soid=act.on
                       inner join peace y on act.on=y.soid
          where
             sp.man is not null
             ' || sqlLocation || '
             ' || sqlRouteDT || '
                    ORDER BY sp.ab asc
        ';
    OPEN cur1 FOR query_str1;
    LOOP
      FETCH cur1
      INTO
        v_AN,
        v_FN
      EXIT WHEN cur1%NOTFOUND;

      query_str2 := '
        SELECT DISTINCT INTER_CD
        FROM    TBL_INTR
        WHERE   AF = ''Y''
          AND   sOID = ''' || v_sOID || '''
        ORDER BY INTER_CD
        ';
      OPEN cur2 FOR query_str2;
      LOOP
        FETCH   cur2
        INTO    v_intr_cd;
        EXIT WHEN cur2%NOTFOUND;
        DBMS_OUTPUT.PUT_LINE('INTER_CD|' || v_intr_cd);
      END LOOP;
      CLOSE cur2;

      query_str3 := '
        SELECT DISTINCT hi_cd
        FROM    tbl_hi
        WHERE   AF = ''Y''
          AND   sOID = ''' || v_sOID || '''
        ORDER BY    hi_cd
        ';
      OPEN cur3 FOR query_str3;
      LOOP
        FETCH   cur3
        INTO    v_hi_c;
        EXIT WHEN cur3%NOTFOUND;
        DBMS_OUTPUT.PUT_LINE('hi_cd|' || v_hi_c);
      END LOOP;
      CLOSE cur3;
    END LOOP;
    CLOSE cur1;
EXCEPTION   WHEN OTHERS THEN
    p_returnCode := 1;
    DBMS_OUTPUT.PUT_LINE(SQLERRM);
END retrieveX;

Body:
I don't think possible to do that you want.

Maybe you should to considerate the use of pipelined function, please take a look at https://oracle-base.com/articles/misc/pipelined-table-functions

With this technique, you can write a pl/sql code to access to complex data and relationship table and get the result as a simple

 select * from StoredProcedure(Parameter_1...);


问:
passing jar file in java code
I have a function that requires the path of a jar file

```<code>builder.add(EventAnnotator.createAnnotatorDescription("/org/apache/ctakes/temporal/ae/eventannotator/model.jar"));
</code>```

This refers to the jar file in my resource folder (as far as I can understand).
I have the same jar file in my maven local repo. and want to use it instead.
Is there a way to pass it as a string like this ?

答: well it seems we could directly use the path of the jar file, as per the structure of resources (if you put it there). Previously this wasn't working for me as I had a few other errors.</p>

Title: passing jar file in java code

Body:
I have a function that requires the path of a jar file

builder.add(EventAnnotator.createAnnotatorDescription("/org/apache/ctakes/temporal/ae/eventannotator/model.jar"));

This refers to the jar file in my resource folder (as far as I can understand).
I have the same jar file in my maven local repo. and want to use it instead.
Is there a way to pass it as a string like this ?


问:
Power off when cable is pulled using a timer: Boot up functionality
I'm working on a small project at the moment, and part of the functionality is to have the device shut off if the power cable is disconnected and a timer reaches zero.

Power Cable Off -> Timer Starts

Power Cable Connected -> Timer Resets(cancel).
Power Cable Connected when device is off -> Device boots up.

The problem arises when the device boots up, the app itself crashes. I've noticed two exceptions thrown.

Trying to cancel a countdown timer that is null.

PowerConnection Reciever is null. (Happens straight away on boot).

I was able to mitigate the first issue by making the countdown timer a static variable, and as opposed to instaniating it in onCreate(), I now do it as well in PowerConnectionReciever as per the code below.

```<code> public static class PowerConnectionReceiver extends BroadcastReceiver
 {
    @Override
    public void onReceive( Context context, Intent intent )
    {
        if( intent.getAction().equals( "android.intent.action.ACTION_POWER_DISCONNECTED" ) )
        {
            if( lShutdownTimer != null )
            {
                lShutdownTimer.start();
            }
            else
            {
                lShutdownTimer = createTimer( 50000, 30000 );
                lShutdownTimer.start();

            }

            Toast.makeText( context.getApplicationContext(), "Power cable disconnected", Toast.LENGTH_LONG ).show();
        }
        else if( intent.getAction().equals( "android.intent.action.ACTION_POWER_CONNECTED" ) )
        {
            Toast.makeText( context.getApplicationContext(), "Power cable connected", Toast.LENGTH_LONG ).show();
            if( lShutdownTimer != null )
                lShutdownTimer.cancel();
        }
    }
}
</code>```

Create timer is just a static class that returns a CountDownTimer:

```<code>private static CountDownTimer createTimer( int aLimit, int aInterval )
{
    return new CountDownTimer( aLimit, aInterval )
    {
        @Override
        public void onTick( long millisUntilFinished )
        {
            Toast.makeText( mContext.getApplicationContext(), "50 Seconds until power off", Toast.LENGTH_LONG ).show();
        }

        @Override
        public void onFinish()
        {
            powerOff();

        }
    };
}
</code>```

If someone could point me in the right direction as to how to handle bootup (so it works straight away), that would be fantastic. I've looked at a few options, but most seem relatively domain specific with services.

Following on, the app is fine when I boot up, if all code regarding the timer is removed.

This is the exception given:

```<code>                                             Process: MYAPP, PID: 7391
                                             java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
                                                 at MYAPP.MainActivity$1.onTick(MainActivity.java:349)
                                                 at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:133)
                                                 at android.os.Handler.dispatchMessage(Handler.java:102)
                                                 at android.os.Looper.loop(Looper.java:148)
                                                 at android.app.ActivityThread.main(ActivityThread.java:7399)
                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
</code>```

答:
Okay, thanks to Vlad Matvienko, changing create timer to take a context to use with the Toast solved the issue.

```<code>private static CountDownTimer createTimer( int aLimit, int aInterval )
{
    return new CountDownTimer( aLimit, aInterval, context )
    {
        @Override
        public void onTick( long millisUntilFinished )
        {
            Toast.makeText( context .getApplicationContext(), "50 Seconds until power off", Toast.LENGTH_LONG ).show();
        }

        @Override
        public void onFinish()
        {
            powerOff();

        }
    };
}
</code>```

It takes the context from onRecieve(), and uses that within the broadcast receiver.

Body:
I'm working on a small project at the moment, and part of the functionality is to have the device shut off if the power cable is disconnected and a timer reaches zero.

Power Cable Off -> Timer Starts

Power Cable Connected -> Timer Resets(cancel).
Power Cable Connected when device is off -> Device boots up.

The problem arises when the device boots up, the app itself crashes. I've noticed two exceptions thrown.

Trying to cancel a countdown timer that is null.

PowerConnection Reciever is null. (Happens straight away on boot).

I was able to mitigate the first issue by making the countdown timer a static variable, and as opposed to instaniating it in onCreate(), I now do it as well in PowerConnectionReciever as per the code below.

 public static class PowerConnectionReceiver extends BroadcastReceiver
 {
    @Override
    public void onReceive( Context context, Intent intent )
    {
        if( intent.getAction().equals( "android.intent.action.ACTION_POWER_DISCONNECTED" ) )
        {
            if( lShutdownTimer != null )
            {
                lShutdownTimer.start();
            }
            else
            {
                lShutdownTimer = createTimer( 50000, 30000 );
                lShutdownTimer.start();

            }

            Toast.makeText( context.getApplicationContext(), "Power cable disconnected", Toast.LENGTH_LONG ).show();
        }
        else if( intent.getAction().equals( "android.intent.action.ACTION_POWER_CONNECTED" ) )
        {
            Toast.makeText( context.getApplicationContext(), "Power cable connected", Toast.LENGTH_LONG ).show();
            if( lShutdownTimer != null )
                lShutdownTimer.cancel();
        }
    }
}

Create timer is just a static class that returns a CountDownTimer:

private static CountDownTimer createTimer( int aLimit, int aInterval )
{
    return new CountDownTimer( aLimit, aInterval )
    {
        @Override
        public void onTick( long millisUntilFinished )
        {
            Toast.makeText( mContext.getApplicationContext(), "50 Seconds until power off", Toast.LENGTH_LONG ).show();
        }

        @Override
        public void onFinish()
        {
            powerOff();

        }
    };
}

If someone could point me in the right direction as to how to handle bootup (so it works straight away), that would be fantastic. I've looked at a few options, but most seem relatively domain specific with services.

Following on, the app is fine when I boot up, if all code regarding the timer is removed.

This is the exception given:

                                             Process: MYAPP, PID: 7391
                                             java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
                                                 at MYAPP.MainActivity$1.onTick(MainActivity.java:349)
                                                 at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:133)
                                                 at android.os.Handler.dispatchMessage(Handler.java:102)
                                                 at android.os.Looper.loop(Looper.java:148)
                                                 at android.app.ActivityThread.main(ActivityThread.java:7399)
                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

Body:
Okay, thanks to Vlad Matvienko, changing create timer to take a context to use with the Toast solved the issue.

private static CountDownTimer createTimer( int aLimit, int aInterval )
{
    return new CountDownTimer( aLimit, aInterval, context )
    {
        @Override
        public void onTick( long millisUntilFinished )
        {
            Toast.makeText( context .getApplicationContext(), "50 Seconds until power off", Toast.LENGTH_LONG ).show();
        }

        @Override
        public void onFinish()
        {
            powerOff();

        }
    };
}

It takes the context from onRecieve(), and uses that within the broadcast receiver.


问:
Need a better understanding of these operations with const pointers in C
As a follow up to this question: How do you specify variables to be final in C?, I've been playing around with const variables. In particular, I've written and compiled the following program:

```<code>#include<stdio.h>

int main(void) {
    const int i = 5;
    int* i_ptr = &i;

    *i_ptr = *i_ptr + 1;      // (1)

    printf("%d %d\n", *i_ptr, i);

    int j = 10;
    const int* j_ptr = &j;

    j_ptr = i_ptr;       // (2)

    printf("%d %d\n", *j_ptr, j);

    return 0;
}
</code>```

I'm working with the following gcc compiler:

```<code>$ gcc --version
Apple LLVM version 8.1.0 (clang-802.0.42)
Target: x86_64-apple-darwin16.5.0
Thread model: posix
</code>```

In the code listing, I've marked two lines of code that behave differently than I'd expect:

(1)  I would expect the compiler to spit at me for trying to modify the const variable i that i_ptr but to my surprise it does not.

(2)  I would expect another error to be generated here because j_ptr has just been declared const and now modifying it is perfectly okay.

Further more, here is the output I get:

```<code>6 5
6 10
</code>```

What's surprising here is that, in the first line out output, i_ptr and i do not have the same values here. What gives? I certainly didn't call malloc and assign i_ptr to new memory.

So how is it pointing to something besides i?

What's even more puzzling is that, if I replace line (2) with this:

```<code>*j_ptr = *j_ptr + 1;
</code>```

I get

error: read-only variable is not assignable

I'd expect that, since j_ptr is pointing to non-const variable j, it should increment j. But that doesn't happen.

I'd really appreciate if someone could explain my observations, as I can't seem to come up with any reasons for why these const pointers should behave this counter-intuitively.

答:
You can modify const variable through pointer but this is undefined behaviour.

This should be an error:

```<code>const int i = 5;
int* i_ptr = &i;  //This is error!
</code>```

While this shouldn't be:

```<code>const int i = 5;
const int* i_ptr = &i;  //This is ok
*i_ptr = 4;    //This is error, you cannot write to pointer if it is expressed as const
</code>```

In second type, it means that you cannot write via i_ptr variable.

If const int a = 5 means that it is constant variable and can't be modified, const int* a_ptr means that variable points to some constant value but variable a_ptr itself is not constant and can be modified.

In some functions, you may see this function structure:

```<code>void funcname(const int* arr, size_t size) {

}
</code>```

Please focus on const part of function parameter. This const means for this function that code can not be modified via arr pointer, but only read can be done.

Example function to read data from array:

```<code>void funcname(const int* arr, size_t size) {
    while (size--) {
        a = *arr;        //You can read
        *arr = *arr * 2; //You cannot update it!
        arr++            //You can do that as you modify where pointer points not value on location where it points.
    }
}
</code>```

But if you want to prevent that also pointer where it points can't be modified, you can do this using below function. Check first parameter with double const.

```<code>void funcname(const int* const arr, size_t size) {
    while (size--) {
        a = *arr;        //You can read
        *arr = *arr * 2; //You cannot update it!
        arr++            //Error! You cannot even increase pointer because of second const keyword in parameter
    }
}
</code>```

Please check this too: http://publications.gbdirect.co.uk/c_book/chapter8/const_and_volatile.html

ContentLicense: CC BY-SA 4.0

Body:
As a follow up to this question: How do you specify variables to be final in C?, I've been playing around with const variables. In particular, I've written and compiled the following program:

#include<stdio.h>

int main(void) {
    const int i = 5;
    int* i_ptr = &i;

    *i_ptr = *i_ptr + 1;      // (1)

    printf("%d %d\n", *i_ptr, i);

    int j = 10;
    const int* j_ptr = &j;

    j_ptr = i_ptr;       // (2)

    printf("%d %d\n", *j_ptr, j);

    return 0;
}

I'm working with the following gcc compiler:

$ gcc --version
Apple LLVM version 8.1.0 (clang-802.0.42)
Target: x86_64-apple-darwin16.5.0
Thread model: posix

In the code listing, I've marked two lines of code that behave differently than I'd expect:

(1)  I would expect the compiler to spit at me for trying to modify the const variable i that i_ptr but to my surprise it does not.

(2)  I would expect another error to be generated here because j_ptr has just been declared const and now modifying it is perfectly okay.

Further more, here is the output I get:

6 5
6 10

What's surprising here is that, in the first line out output, i_ptr and i do not have the same values here. What gives? I certainly didn't call malloc and assign i_ptr to new memory.

So how is it pointing to something besides i?

What's even more puzzling is that, if I replace line (2) with this:

*j_ptr = *j_ptr + 1;

I get

error: read-only variable is not assignable

I'd expect that, since j_ptr is pointing to non-const variable j, it should increment j. But that doesn't happen.

I'd really appreciate if someone could explain my observations, as I can't seem to come up with any reasons for why these const pointers should behave this counter-intuitively.

Body:
You can modify const variable through pointer but this is undefined behaviour.

This should be an error:

const int i = 5;
int* i_ptr = &i;  //This is error!

While this shouldn't be:

const int i = 5;
const int* i_ptr = &i;  //This is ok
*i_ptr = 4;    //This is error, you cannot write to pointer if it is expressed as const

In second type, it means that you cannot write via i_ptr variable.

If const int a = 5 means that it is constant variable and can't be modified, const int* a_ptr means that variable points to some constant value but variable a_ptr itself is not constant and can be modified.

In some functions, you may see this function structure:

void funcname(const int* arr, size_t size) {

}

Please focus on const part of function parameter. This const means for this function that code can not be modified via arr pointer, but only read can be done.

Example function to read data from array:

void funcname(const int* arr, size_t size) {
    while (size--) {
        a = *arr;        //You can read
        *arr = *arr * 2; //You cannot update it!
        arr++            //You can do that as you modify where pointer points not value on location where it points.
    }
}

But if you want to prevent that also pointer where it points can't be modified, you can do this using below function. Check first parameter with double const.

void funcname(const int* const arr, size_t size) {
    while (size--) {
        a = *arr;        //You can read
        *arr = *arr * 2; //You cannot update it!
        arr++            //Error! You cannot even increase pointer because of second const keyword in parameter
    }
}

Please check this too: http://publications.gbdirect.co.uk/c_book/chapter8/const_and_volatile.html


问:
Read from bytes not filename to convert audio
I have small-sized sound files stored in MongoDB as BSON.
Task is to retrieve Binary data from the database, convert it to an appropriate format and send back to the front end.
The problem is with the converting. I have found pydub can be used for this.

My code is as follows

```<code> query_param = json_data['retriever']
 query_param1 = query_param.replace('"', "");
 data = db.soundData
 y = data.find_one({'name': query_param1})
 s = y['data'] // here I retrieve the binary data
 AudioSegment.from_file(s).export(x, format="mp3")
 return send_file(x, 'audio/mp3')
</code>```

The question is with Audiosegment line as it does not follow the standard of
AudioSegment.from_wav("/input/file.wav").export("/output/file.mp3", format="mp3")
and an error of 'bytes' object has no attribute 'read' is still thrown. Is it achievable with pydub?

答:
AudioSegment.from_file() takes a file path or file-like object as it's first argument. Assuming you have the raw bytes of a whole wave file (including wave headers, not just the audio data) then you can:

```<code>import io
s = io.BytesIO(y['data'])
AudioSegment.from_file(s).export(x, format='mp3')
</code>```

If you only have the bytes of the audio samples you would need to know some metadata about your audio data:

```<code>AudioSegment(y['data'], sample_width=???, frame_rate=???, channels=???)
</code>```

sample_width is the number of bytes in each sample (so for 16-bit/CD audio, you'd use 2)

frame_rate is number of samples/second (aka, sample rate, for CD audio it's 44100)

channels how many audio streams are there, stereo is 2, mono is 1, etc

Body:
I have small-sized sound files stored in MongoDB as BSON.
Task is to retrieve Binary data from the database, convert it to an appropriate format and send back to the front end.
The problem is with the converting. I have found pydub can be used for this.

My code is as follows

 query_param = json_data['retriever']
 query_param1 = query_param.replace('"', "");
 data = db.soundData
 y = data.find_one({'name': query_param1})
 s = y['data'] // here I retrieve the binary data
 AudioSegment.from_file(s).export(x, format="mp3")
 return send_file(x, 'audio/mp3')

The question is with Audiosegment line as it does not follow the standard of
AudioSegment.from_wav("/input/file.wav").export("/output/file.mp3", format="mp3")
and an error of 'bytes' object has no attribute 'read' is still thrown. Is it achievable with pydub?

Body:
AudioSegment.from_file() takes a file path or file-like object as it's first argument. Assuming you have the raw bytes of a whole wave file (including wave headers, not just the audio data) then you can:

import io
s = io.BytesIO(y['data'])
AudioSegment.from_file(s).export(x, format='mp3')

If you only have the bytes of the audio samples you would need to know some metadata about your audio data:

AudioSegment(y['data'], sample_width=???, frame_rate=???, channels=???)

sample_width is the number of bytes in each sample (so for 16-bit/CD audio, you'd use 2)

frame_rate is number of samples/second (aka, sample rate, for CD audio it's 44100)

channels how many audio streams are there, stereo is 2, mono is 1, etc


问:
Conditional Statement returning false
I'm trying to validate an input field with REGEX. Can anyone help me understand why this conditional statement is returning "Wrong" in the console?

```<code> <script>
            $('form[action*="paypal"]').submit(function(event) {

                if (/^DAM\d{10}/.test($('input[name="item_name"]'))){
                    console.log("Correct!");
                    return true;
                }
                else {
                    console.log("Wrong!");
                    event.preventDefault();
                }
            });
        </script>
</code>```

The form im targeting is:

```<code><form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="XN4BQ5WSZZCEQ">
<table>
<tr><td><input type="hidden" value="">Enter your number</td></tr><tr><td>
<input type="text" name="item_name" required></td></tr>
</table>
<input type="image" src="https://www.paypalobjects.com/en_GB/i/btn/btn_paynowCC_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>
</code>```

And i'm entering DAM1234567891 into the input field below:

```<code>  <input type="text" name="item_name" required></td></tr>
</code>```

答:
Try this:

```<code><script
   src="https://code.jquery.com/jquery-3.2.1.js"
   integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
   crossorigin="anonymous"></script>
<form action="paypal.php">
   <input name="item_name" value="DAM1234567891" />
   <input type="submit">
</form>
<script>
   $('form[action*="paypal"]').submit(function(event) {

       if (/^DAM\d{10}/.test($('input[name="item_name"]').val())){
           console.log("Correct!");
           event.preventDefault();
           return true;
       }
       else {
           console.log("Wrong!");
           event.preventDefault();
       }
   });
</script>
</code>```

Your input will need to start with DAM and have 10 digits.

Title: Conditional Statement returning false

Body:
I'm trying to validate an input field with REGEX. Can anyone help me understand why this conditional statement is returning "Wrong" in the console?

The form im targeting is:

<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="XN4BQ5WSZZCEQ">

<input type="hidden" value="">Enter your number

<input type="text" name="item_name" required>

<input type="image" src="https://www.paypalobjects.com/en_GB/i/btn/btn_paynowCC_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online!">

</form>

And i'm entering DAM1234567891 into the input field below:

  <input type="text" name="item_name" required>

Body:
Try this:

<script
   src="https://code.jquery.com/jquery-3.2.1.js"
   integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
   crossorigin="anonymous"></script>
<form action="paypal.php">
   <input name="item_name" value="DAM1234567891" />
   <input type="submit">
</form>
<script>
   $('form[action*="paypal"]').submit(function(event) {

       if (/^DAM\d{10}/.test($('input[name="item_name"]').val())){
           console.log("Correct!");
           event.preventDefault();
           return true;
       }
       else {
           console.log("Wrong!");
           event.preventDefault();
       }
   });
</script>

Your input will need to start with DAM and have 10 digits.


问:
Update NSProgress display from within ViewController Function Loop
I'm back again Hive Mind!

In my ViewController class, I have a function which iterates through a series of items in an array.  What I would like to happen is to have my progress bar update on each iteration of the loop, but it appears that it doesn't update the progress bar on screen until it completes the entire loop and exits my function.

I'm pretty certain that it's simply because the view only gets redrawn once each time through the application loop (I'm probably not using the right term here.)

What would be the proper way to force the ViewController view to update while I'm still inside of my ViewController function loop?

Here's basically what I'm doing right now:

```<code>func myFunction() {
     for item in collection {
         progressBar.increment(by:1)
         progressBar.display()
     }
     // execute my other code
}
</code>```

When that didn't work, I tried adding a needsSetDisplay after the progressBar.draw method, like this:

```<code>func myFunction() {
     for item in collection {
         progressBar.increment(by:1)
         progressBar.display()
         let rect = self.view.visibleRect
         self.view.needsSetDisplay(rect)
     }
     // execute my other code
}
</code>```

But it still didn't work.

I'm sure there's a way to accomplish what I need to do, but I suspect it involves something a bit more advanced such as running multiple processes, something I'm probably not qualified to do quite yet as I'm new to Swift, and it's been at least 10 years since I've coded in Obj-C (aka I forgot most of what I knew.)

Thanks!

EDIT Another thing I've attempted unsuccessfully was to call progressBar.displayAsNeeded() but it didn't seem to work either.

答:
Assuming you are running on the main thread then you are blocking until the method finishes.  No matter which 'need' style methods (setNeedsDisplay, displayAsNeeded, etc) you try to use the actual re-display won't happen until the method has finished (display updated are grouped to avoid it being continually updated).

What you could do is put the work onto a background thread and then put the UI update back onto the main thread similar to this:

```<code>DispatchQueue.global(qos: .background).async {
    for item in collection {
        DispatchQueue.main.async {
            progressBar.increment(by:1)
            progressBar.display()
        }
    }
}
</code>```

Of course that will raise other issues such as the user can now interact with the UI while the background thread is processing which you need to account for.

If you are already running in a background thread then you just need to dispatch the progress bar update onto the main thread.

Body:
I'm back again Hive Mind!

In my ViewController class, I have a function which iterates through a series of items in an array.  What I would like to happen is to have my progress bar update on each iteration of the loop, but it appears that it doesn't update the progress bar on screen until it completes the entire loop and exits my function.

I'm pretty certain that it's simply because the view only gets redrawn once each time through the application loop (I'm probably not using the right term here.)

What would be the proper way to force the ViewController view to update while I'm still inside of my ViewController function loop?

Here's basically what I'm doing right now:

func myFunction() {
     for item in collection {
         progressBar.increment(by:1)
         progressBar.display()
     }
     // execute my other code
}

When that didn't work, I tried adding a needsSetDisplay after the progressBar.draw method, like this:

func myFunction() {
     for item in collection {
         progressBar.increment(by:1)
         progressBar.display()
         let rect = self.view.visibleRect
         self.view.needsSetDisplay(rect)
     }
     // execute my other code
}

But it still didn't work.

I'm sure there's a way to accomplish what I need to do, but I suspect it involves something a bit more advanced such as running multiple processes, something I'm probably not qualified to do quite yet as I'm new to Swift, and it's been at least 10 years since I've coded in Obj-C (aka I forgot most of what I knew.)

Thanks!

EDIT Another thing I've attempted unsuccessfully was to call progressBar.displayAsNeeded() but it didn't seem to work either.

Body:
Assuming you are running on the main thread then you are blocking until the method finishes.  No matter which 'need' style methods (setNeedsDisplay, displayAsNeeded, etc) you try to use the actual re-display won't happen until the method has finished (display updated are grouped to avoid it being continually updated).

What you could do is put the work onto a background thread and then put the UI update back onto the main thread similar to this:

DispatchQueue.global(qos: .background).async {
    for item in collection {
        DispatchQueue.main.async {
            progressBar.increment(by:1)
            progressBar.display()
        }
    }
}

Of course that will raise other issues such as the user can now interact with the UI while the background thread is processing which you need to account for.

If you are already running in a background thread then you just need to dispatch the progress bar update onto the main thread.


问:
SAS - Custom Date Format - YYYYMMDDhhmmss
I need to add a current date to the output I am exporting from SAS in the following format: filename_YYYYMMDDhhmmss.csv

I am creating a macro variable the following way:

```<code>%let date_human = %sysfunc(today(), YYYYMMDDn8.);
</code>```

Does anybody know how to create a custom format for the date I have got? datetime20. gives an incorrect one.

Thank you.

答:
Two solutions:

1. Create a picture format with datetime directives using proc format

Here, we are creating a format called date_human. You can name this anything that you'd like.

```<code>proc format;
    picture date_human other='%0Y%0M%0D%0H%0M%0S' (datatype=datetime);
run;

%let date_human = %sysfunc(datetime(), date_human.);
</code>```

2. Mash together various macro variables

```<code>/* YYYYMMDD part */
%let yymmdd   = %sysfunc(today(), yymmdd8.);

%let datetime = %sysfunc(datetime());
%let time     = %sysfunc(putn(%sysfunc(timepart(&datetime.)), time8.0));

/* hhmmss part */
%let hour     = %scan(&time., 1, :);
%let min      = %scan(&time., 2, :);
%let sec      = %scan(&time., 2, :);

/* Put it all together */
%let date_human = &yymmdd.&hour.&min.&sec.;
</code>```

Body:
I need to add a current date to the output I am exporting from SAS in the following format: filename_YYYYMMDDhhmmss.csv

I am creating a macro variable the following way:

%let date_human = %sysfunc(today(), YYYYMMDDn8.);

Does anybody know how to create a custom format for the date I have got? datetime20. gives an incorrect one.

Thank you.

Body:
Two solutions:

1. Create a picture format with datetime directives using proc format

Here, we are creating a format called date_human. You can name this anything that you'd like.

proc format;
    picture date_human other='%0Y%0M%0D%0H%0M%0S' (datatype=datetime);
run;

%let date_human = %sysfunc(datetime(), date_human.);

2. Mash together various macro variables

/* YYYYMMDD part */
%let yymmdd   = %sysfunc(today(), yymmdd8.);

%let datetime = %sysfunc(datetime());
%let time     = %sysfunc(putn(%sysfunc(timepart(&datetime.)), time8.0));

/* hhmmss part */
%let hour     = %scan(&time., 1, :);
%let min      = %scan(&time., 2, :);
%let sec      = %scan(&time., 2, :);

/* Put it all together */
%let date_human = &yymmdd.&hour.&min.&sec.;


问:
Run app on iTouch w/o iTunes
I have written a small app using Ojective-C w/ XCode. It's only for personal fun and I don't want to pay Apple $99 to just let it run on my iTouch. Is there any alternative for me to run it on iTouch instead of iPhone simulator? Please give me some suggestion.</p>

答: If you jailbreak, you can use a fake certificate and install it through SSH.</p>

Title: Run app on iTouch w/o iTunes


问:
Will if / else if / else become an expressions in typescript / javascript at some point?
I really like this feature in Kotlin:

In Kotlin, if is an expression, i.e. it returns a value.

```<code>// As expression
val max = if (a > b) a else b
</code>```

(from https://kotlinlang.org/docs/reference/control-flow.html)

Is this also planned for typescript / javascript?

Update:

In reply to the ternary operator suggestions, of course I also mean cases with else if:

```<code>val bla = if ( 5 == 6) {
    7
} else if (5 == 7) {
    8
} else {
    9
}

println(bla) // prints 9
</code>```

答: It already exists Ternary Conditional</p>

Body:
I really like this feature in Kotlin:

In Kotlin, if is an expression, i.e. it returns a value.

// As expression
val max = if (a > b) a else b

(from https://kotlinlang.org/docs/reference/control-flow.html)

Is this also planned for typescript / javascript?

Update:

In reply to the ternary operator suggestions, of course I also mean cases with else if:

val bla = if ( 5 == 6) {
    7
} else if (5 == 7) {
    8
} else {
    9
}

println(bla) // prints 9

Body: It already exists Ternary Conditional


问:
using vba i fetched 5000 records from db, how to loop to paste evrey 1000 records into a new worksheet?
I am not sure how to loop to fetch only 1000 records and paste values in a new sheet so that as a result the workbook has 5 sheets.
Any help would be really appreciated.
Thanks!</p>

```<code>Sub text_analysis()
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
Dim rsstring As String
Dim cmd As ADODB.Command
Dim NewWorkbook As Workbook
Set NewWorkbook = Workbooks.Add

Set cmd = New ADODB.Command
Set conn = New ADODB.Connection

sConnString = "Provider=SQLOLEDB;Data Source=localhost\SQLEXPRESS;" & _
              "Initial Catalog=MDM-FINAL;" & _
              "Integrated Security=SSPI;"

Set rs = New ADODB.Recordset

conn.Open sConnString
rsstring = "exec text_analysis;"
rs.Open rsstring, sConnString

NewWorkbook.Activate
Do Until rs.EOF
Worksheets("sheet1").Range("A2").CopyFromRecordset rs, MaxRows:=100000
ActiveSheet.Name = "Text Analysis"
Range("A1").Value = "SAP Code 1"
Range("B1").Value = "SAP Desc 1"
Range("C1").Value = "SAP Code 2"
Range("D1").Value = "SAP Desc 2"
Range("E1").Value = "Diff Count"
Range("F1").Value = "Diff Value"
Range("G1").Value = "Similar %"
Range("H1").Value = "Similar Partial %"
Range("I1").Value = "Similar Sort %"
Range("J1").Value = "Similar Set %"
Loop

rs.Close
conn.Close

End Sub
</code>```

答:
this method is getting data as Variant from recordset</p>

```<code>Sub text_analysis()
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
Dim rsstring As String
Dim cmd As ADODB.Command
Dim NewWorkbook As Workbook
Set NewWorkbook = Workbooks.Add

Set cmd = New ADODB.Command
Set conn = New ADODB.Connection

sConnString = "Provider=SQLOLEDB;Data Source=localhost\SQLEXPRESS;" & _
              "Initial Catalog=MDM-FINAL;" & _
              "Integrated Security=SSPI;"

Set rs = New ADODB.Recordset

conn.Open sConnString
rsstring = "exec text_analysis;"
rs.Open rsstring, sConnString

'get data as Variant from recordset
    Dim R As Long, m As Long, c As Integer
    Dim i As Long, j As Integer
    Dim vR, Ws As Worksheet
    vR = rs.getRows
    R = UBound(vR, 2)
    c = UBound(vR, 1)
    For m = 0 To R Step 1000
        ReDim vResult(1 To 1000, 1 To c + 1)
        For i = 0 To 999
            If i + m > R Then Exit For
            For j = 0 To c
                vResult(i + 1, j + 1) = vR(j, i + m)
            Next j
        Next i
        Set Ws = Sheets.Add(after:=Sheets(Sheets.Count))
        With Ws
            For i = 0 To rs.Fields.Count - 1
               .Cells(1, i + 1).Value = rs.Fields(i).Name
            Next
            Range("a2").Resize(1000, c + 1) = vResult
        End With
    Next m

rs.Close
conn.Close

End Sub
</code>```

Body:
I am not sure how to loop to fetch only 1000 records and paste values in a new sheet so that as a result the workbook has 5 sheets.
Any help would be really appreciated.
Thanks!

Sub text_analysis()
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
Dim rsstring As String
Dim cmd As ADODB.Command
Dim NewWorkbook As Workbook
Set NewWorkbook = Workbooks.Add

Set cmd = New ADODB.Command
Set conn = New ADODB.Connection

sConnString = "Provider=SQLOLEDB;Data Source=localhost\SQLEXPRESS;" & _
              "Initial Catalog=MDM-FINAL;" & _
              "Integrated Security=SSPI;"

Set rs = New ADODB.Recordset

conn.Open sConnString
rsstring = "exec text_analysis;"
rs.Open rsstring, sConnString

NewWorkbook.Activate
Do Until rs.EOF
Worksheets("sheet1").Range("A2").CopyFromRecordset rs, MaxRows:=100000
ActiveSheet.Name = "Text Analysis"
Range("A1").Value = "SAP Code 1"
Range("B1").Value = "SAP Desc 1"
Range("C1").Value = "SAP Code 2"
Range("D1").Value = "SAP Desc 2"
Range("E1").Value = "Diff Count"
Range("F1").Value = "Diff Value"
Range("G1").Value = "Similar %"
Range("H1").Value = "Similar Partial %"
Range("I1").Value = "Similar Sort %"
Range("J1").Value = "Similar Set %"
Loop

rs.Close
conn.Close

End Sub

Body:
this method is getting data as Variant from recordset

Sub text_analysis()
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
Dim rsstring As String
Dim cmd As ADODB.Command
Dim NewWorkbook As Workbook
Set NewWorkbook = Workbooks.Add

Set cmd = New ADODB.Command
Set conn = New ADODB.Connection

sConnString = "Provider=SQLOLEDB;Data Source=localhost\SQLEXPRESS;" & _
              "Initial Catalog=MDM-FINAL;" & _
              "Integrated Security=SSPI;"

Set rs = New ADODB.Recordset

conn.Open sConnString
rsstring = "exec text_analysis;"
rs.Open rsstring, sConnString

'get data as Variant from recordset
    Dim R As Long, m As Long, c As Integer
    Dim i As Long, j As Integer
    Dim vR, Ws As Worksheet
    vR = rs.getRows
    R = UBound(vR, 2)
    c = UBound(vR, 1)
    For m = 0 To R Step 1000
        ReDim vResult(1 To 1000, 1 To c + 1)
        For i = 0 To 999
            If i + m > R Then Exit For
            For j = 0 To c
                vResult(i + 1, j + 1) = vR(j, i + m)
            Next j
        Next i
        Set Ws = Sheets.Add(after:=Sheets(Sheets.Count))
        With Ws
            For i = 0 To rs.Fields.Count - 1
               .Cells(1, i + 1).Value = rs.Fields(i).Name
            Next
            Range("a2").Resize(1000, c + 1) = vResult
        End With
    Next m

rs.Close
conn.Close

End Sub


问:
.gitignore two or more extensions file
I have the next files in my local repository:

app.component.js
core.component.js
core.service.local.js
core.service.power.ts

My question is very simple, How can I do to ignore the files with the extension .component.js and .service.local.js and other, I mean any file to end with .Any_String.ext

答: Use a wild character '*'. Example *.component.js

Title: .gitignore two or more extensions file