问:
in flutter app android I cant register account with flutter app just login ,, the error said "wrong email or password"?
i build flutter app and link with laravel php admin on web hosting (hostgrator) . I cant register account with flutter app just login , the error said "wrong email or password" . but when change api with default seller codecanyou api :

```<code>       {
     "base_url": "https://multi-restaurants.smartersvision.com/",
     "api_base_url": "https://multi-restaurants.smartersvision.com/api/"
     }
</code>```

its working 100% without any problem , just on my api problem .. my api is:

```<code>    {
"api_base_url": "https://eatandgohost.com/api/",
"base_url": "https://eatandgohost.com/"
}
</code>```

and my .env is :

```<code>    APP_NAME='Eat & Go'
    APP_ENV=local
    APP_KEY=base64:*******************
    APP_DEBUG=true
    APP_LOG_LEVEL=debug
    APP_URL=https://eatandgohost.com/

    DB_CONNECTION=mysql
    DB_HOST=localhost
    DB_PORT=3306
    DB_DATABASE=yasserdh_multi_restaurants
    DB_USERNAME=********
    DB_PASSWORD=********

    BROADCAST_DRIVER=log
    CACHE_DRIVER=file
    SESSION_DRIVER=file
    QUEUE_DRIVER=sync

    REDIS_HOST=127.0.0.1
    REDIS_PASSWORD=null
    REDIS_PORT=6379

    MAIL_DRIVER=smtp
    MAIL_HOST=smtp.mailtrap.io
    MAIL_PORT=2525
    MAIL_USERNAME=null
    MAIL_PASSWORD=null
    MAIL_ENCRYPTION=null

    PUSHER_APP_ID=
    PUSHER_APP_KEY=
    PUSHER_APP_SECRET=
</code>```

答: if you have the problem with register create account with flutter app mobile about this error "wrong email or password" or "the email is exist " , just try to change web hosting to "hostinger web hosting" , and problem fixed and mobile flutter register without any problem , thanks for all .

Body:
i build flutter app and link with laravel php admin on web hosting (hostgrator) . I cant register account with flutter app just login , the error said "wrong email or password" . but when change api with default seller codecanyou api :

       {
     "base_url": "https://multi-restaurants.smartersvision.com/",
     "api_base_url": "https://multi-restaurants.smartersvision.com/api/"
     }

its working 100% without any problem , just on my api problem .. my api is:

    {
"api_base_url": "https://eatandgohost.com/api/",
"base_url": "https://eatandgohost.com/"
}

and my .env is :

    APP_NAME='Eat & Go'
    APP_ENV=local
    APP_KEY=base64:*******************
    APP_DEBUG=true
    APP_LOG_LEVEL=debug
    APP_URL=https://eatandgohost.com/

    DB_CONNECTION=mysql
    DB_HOST=localhost
    DB_PORT=3306
    DB_DATABASE=yasserdh_multi_restaurants
    DB_USERNAME=********
    DB_PASSWORD=********

    BROADCAST_DRIVER=log
    CACHE_DRIVER=file
    SESSION_DRIVER=file
    QUEUE_DRIVER=sync

    REDIS_HOST=127.0.0.1
    REDIS_PASSWORD=null
    REDIS_PORT=6379

    MAIL_DRIVER=smtp
    MAIL_HOST=smtp.mailtrap.io
    MAIL_PORT=2525
    MAIL_USERNAME=null
    MAIL_PASSWORD=null
    MAIL_ENCRYPTION=null

    PUSHER_APP_ID=
    PUSHER_APP_KEY=
    PUSHER_APP_SECRET=


来源: stackexchange

问:
Can managed code perform computations as fast as unmamanged?
I've been interested in different chess engines lately. There are many open and closed sources project in this field. They are all (most of them anyway) written in C/C++. This is kind of an obvious thing - you have a computationally intensive task, you use C/C++ so you get both portability and speed. This seems like a no-brainier.

However, I would like to question that idea. When .NET first appeared, there were many people saying that .NET idea would not work because .NET programs were doomed to be super-slow. In reality this did not happen. Somebody did a good job with the VM, JIT, etc and we have decent performance for most tasks now. But not all. Microsoft never promised that .NET will be suitable for all task and admitted for some tasks you will still need C/C++.

Going back to the question of computationally heavy task - is there a way to write a .NET program so that it does not perform computations considerably worse that an unmanaged code using the same algorithms? I'd be happy with "constant" speed loss, but anything worse than that is going to be a problem.

What do you think? Can we be close in speed to unmanaged code for computations in managed code, or unmanaged code is the only viable answer? If we can, how? If we can't why?

Update:  a lot of good feedback here. I'm going to accept the most up-voted answer.

答:
This seems like an overly broad question.

There are some gratuitous hints to throw around: Yes you can use unsafe, unchecked, arrays of Structs and most importantly C++/CLI.

There is never going to be a match for C++'s inlining, compiletime template expansion (and ditto optimizations) etc.

But the bottom line is: it depends on the problem. What is computations anyway. Mono has nifty extensions to use SIMD instructions, on Win32 you'd have to go native to get those. Interop is cheating.

In my experience, though, porting toy projects (such as parsers and a Chess engine) is going to result in at least an order of magnitude speed difference, no matter how much you do optimize the .NET side of things. I reckon this has to do, mainly, with the Heap management and the service routines (System.String, System.IO).

There can be big pitfalls in .NET (overusing Linq, lambdas, accidentally relying on Enum.HasFlag to perform like a bitwise operation...) etc. YMMV and choose your weapons carefully

ContentLicense: CC BY-SA 3.0


问:
JPA EntityManager : save objects only when explicitly requested
I'm fairly new to Hibernate and JPA, and am currently working on an application that uses it through JPA's EntityManager.

When looking at some basic hibernate tutorials using Hibernate session, I see that I can do :

```<code>val session = HibernateUtil.getSessionFactory().getCurrentSession()
session.beginTransaction()
val coordinates = session.find(Coordinates::class.java, "12345")
coordinates.longitude = 0.0
session.save(coordinates)
session.getTransaction().commit()
</code>```

When using Entitymanager, it's done this way :

```<code>val em = emFactory.createEntityManager()
em.transaction.begin()
val coordinates = em.find(Coordinates::class.java, "12345")
coordinates.longitude = 0.0
em.transaction.commit()
</code>```

The main difference here is that using EntityManager, I don't have to explicitly make a call to a save function to actually update the object, which will be flushed eventually during commit. Of course, I coul do something like

```<code>if(obj.id == null) {
    return em.merge()
} else {
    val saved = em.persist(obj)
    return saved
}
</code>```

But what's the point for already existing objects if they get saved anyway, no matter if I call this or not ?

Surprisingly, the examples found around here seem to rely on a save method as well.

My question is : is there a way to configure EntityManager to update the objects only when requested specifically (i.e. mimick session behavior) ? Or do I have to use Session to achieve this ?

答:
merge is the opportunity for the EntityManager to actually perform database operations. Merging, persisting, flushing, and committing are essentially all contact points with the database.

For simple cases, you can simply rely on changing the behavior at commit and not physically merge yourself, but many like the control knowing when it will actually happen. Knowing that "after this, it's in the DB". Because after the merge, not only is the data persisted, along with any cascading behavior, but also any side effects from triggers etc. on the DB have happened as well.

They're not committed, but they've happened. Keys are assigned for parents and children, triggers have fired, lifecycle methods have fired, everything is "as it should be", "right now", vs "sometime in the future" even if that may only be milliseconds away.

ContentLicense: CC BY-SA 4.0

Body:
I'm fairly new to Hibernate and JPA, and am currently working on an application that uses it through JPA's EntityManager.

When looking at some basic hibernate tutorials using Hibernate session, I see that I can do :

val session = HibernateUtil.getSessionFactory().getCurrentSession()
session.beginTransaction()
val coordinates = session.find(Coordinates::class.java, "12345")
coordinates.longitude = 0.0
session.save(coordinates)
session.getTransaction().commit()

When using Entitymanager, it's done this way :

val em = emFactory.createEntityManager()
em.transaction.begin()
val coordinates = em.find(Coordinates::class.java, "12345")
coordinates.longitude = 0.0
em.transaction.commit()

The main difference here is that using EntityManager, I don't have to explicitly make a call to a save function to actually update the object, which will be flushed eventually during commit. Of course, I coul do something like

if(obj.id == null) {
    return em.merge()
} else {
    val saved = em.persist(obj)
    return saved
}

But what's the point for already existing objects if they get saved anyway, no matter if I call this or not ?

Surprisingly, the examples found around here seem to rely on a save method as well.

My question is : is there a way to configure EntityManager to update the objects only when requested specifically (i.e. mimick session behavior) ? Or do I have to use Session to achieve this ?


问:
how to correctly shape input of a multiclass classification using keras stacked LSTM model
I am working on a multiple classification problem and after dabbling with multiple neural network architectures, I settled for a stacked LSTM structure as it yields the best accuracy for my use-case. Unfortunately the network takes a long time (almost 48 hours) to reach a good accuracy (~1000 epochs) even when I use GPU acceleration. The resulting accuracy and loss functions are:

At this point, giving the good performance but the very slow training I suspect a bug in my code. I tested it using the golden tests mentioned here, which consist of running tests with 2 points only either in the testing set or the training set along with eliminating the dropouts. Unfortunately, the outputs of these runs result in testing accuracy better than the training accuracy, which should not be the case as far as I know. I suspect that I am shaping my data in the wrong way. Any hints, suggestions and advises are appreciated.

My code is the following:

# -*- coding: utf-8 -*-
import keras
import numpy as np
from time import time
from utils import dmanip, vis
from keras.models import Sequential
from keras.layers import LSTM, Dense
from keras.utils import to_categorical
from keras.callbacks import TensorBoard
from sklearn.preprocessing import LabelEncoder
from tensorflow.python.client import device_lib
from sklearn.model_selection import train_test_split

###############################################################################
####################### Extract the data from .csv file #######################
###############################################################################
# get data
data, column_names = dmanip.get_data(file_path='../data_one_outcome.csv')

# split data
X = data.iloc[:, :-1]
y = data.iloc[:, -1:].astype('category')

###############################################################################
########################## init global config vars ############################
###############################################################################
# check if GPU is used
print(device_lib.list_local_devices())

# init
n_epochs = 1500
n_comps = X.shape[1]

###############################################################################
################################## Keras RNN ##################################
###############################################################################
# encode the classification labels
le = LabelEncoder()
yy = to_categorical(le.fit_transform(y))

# split the dataset
x_train, x_test, y_train, y_test = train_test_split(X, yy, test_size=0.35,
                                                    random_state=True,
                                                    shuffle=True)

# expand dimensions
x_train = np.expand_dims(x_train, axis=2)
x_test = np.expand_dims(x_test, axis=2)

# define model
model = Sequential()
model.add(LSTM(units=n_comps, return_sequences=True,
               input_shape=(x_train.shape[1], 1),
               dropout=0.2, recurrent_dropout=0.2))
model.add(LSTM(64, return_sequences=True, dropout=0.2, recurrent_dropout=0.2))
model.add(LSTM(32, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(4 ,activation='softmax'))

# print model architecture summary
print(model.summary())

# compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

# Create a TensorBoard instance with the path to the logs directory
tensorboard = TensorBoard(log_dir='./logs/rnn/{}'.format(time()))

# fit the model
history = model.fit(x_train, y_train, epochs=n_epochs, batch_size=100,
                    validation_data=(x_test, y_test), callbacks=[tensorboard])

# plot results
vis.plot_nn_stats(history=history, stat_type="accuracy", fname="RNN-accuracy")
vis.plot_nn_stats(history=history, stat_type="loss", fname="RNN-loss")
```

<p>My data is a large 2d matrix (38607, 150), where 149 is the number of features and 38607 is the number of samples, with a target vector including 4 classes.</p>

```       feat1   feat2   ...  feat148  feat149  target
1      2.250   0.926   ...  16.0      0.0     class1
2      2.791   1.235   ...  1.0       0.0     class2
         .       .     .     .         .         .
         .       .      .    .         .         .
         .       .       .   .         .         .
38406  2.873   1.262   ...  281.0     0.0     class3
38407  3.222   1.470   ...  467.0     1.0     class4
```

答:
Regarding the Slowness of Training: You can think of using tf.data instead of Data Frames and Numpy Arrays because, Achieving peak performance requires an efficient input pipeline that delivers data for the next step before the current step has finished. The tf.data API helps to build flexible and efficient input pipelines.

For more information regarding tf.data, please refer this Tensorflow Documentation 1, Documentation 2.

This Tensorflow Tutorial guides you to convert your Data Frame to tf.data format.

One more important feature of use to you can be tf.profiler. Using Tensorflow Profiler, you can not only Visualize the Time and Memory Consumed in each phase of Data Science Project but it also provides us a Suggestion/Recommendation to reduce the Time/Memory Consumption and hence to Optimize our Project.

For more information on Tensorflow Profiler, refer this Documentation, this Tutorial and this Tensorflow DevSummit Youtube Video.

Regarding Testing Accuracy more than Training Accuracy: This is not a big problem and happens sometimes.

Probable Reason 1: Dropout ==> What is the reason for you to use Dropout and recurrent_dropout in your Model? Was the Model Overfitting? If the Model is not Overfitting, without Dropout and recurrent_dropout, then you can think of removing them because, If you set Dropout (0.2) and recurrent_dropout (0.2) it means 20% of features will be 0 and 20% of Time Steps will be 0, during training. However, during testing all the Features and Timesteps are used, so the model is more robust and have better testing accuracy.

Probable Reason 2: 35% of Testing Data is bit more than usual. You can make it either 20% or 25%.

Probable Reason 3: Your training data might have several arduous cases to learn and Your Testing data may contain easier cases to predict. To mitigate this, you can Split the Data Once again with different Random Seed.

For more information, please refer this Research Gate Link and this Stack Overflow Link.

Hope this helps. Happy Learning!

Body:
I am working on a multiple classification problem and after dabbling with multiple neural network architectures, I settled for a stacked LSTM structure as it yields the best accuracy for my use-case. Unfortunately the network takes a long time (almost 48 hours) to reach a good accuracy (~1000 epochs) even when I use GPU acceleration. The resulting accuracy and loss functions are:

At this point, giving the good performance but the very slow training I suspect a bug in my code. I tested it using the golden tests mentioned here, which consist of running tests with 2 points only either in the testing set or the training set along with eliminating the dropouts. Unfortunately, the outputs of these runs result in testing accuracy better than the training accuracy, which should not be the case as far as I know. I suspect that I am shaping my data in the wrong way. Any hints, suggestions and advises are appreciated.

My code is the following:

# -*- coding: utf-8 -*-
import keras
import numpy as np
from time import time
from utils import dmanip, vis
from keras.models import Sequential
from keras.layers import LSTM, Dense
from keras.utils import to_categorical
from keras.callbacks import TensorBoard
from sklearn.preprocessing import LabelEncoder
from tensorflow.python.client import device_lib
from sklearn.model_selection import train_test_split

###############################################################################
####################### Extract the data from .csv file #######################
###############################################################################
# get data
data, column_names = dmanip.get_data(file_path='../data_one_outcome.csv')

# split data
X = data.iloc[:, :-1]
y = data.iloc[:, -1:].astype('category')

###############################################################################
########################## init global config vars ############################
###############################################################################
# check if GPU is used
print(device_lib.list_local_devices())

# init
n_epochs = 1500
n_comps = X.shape[1]

###############################################################################
################################## Keras RNN ##################################
###############################################################################
# encode the classification labels
le = LabelEncoder()
yy = to_categorical(le.fit_transform(y))

# split the dataset
x_train, x_test, y_train, y_test = train_test_split(X, yy, test_size=0.35,
                                                    random_state=True,
                                                    shuffle=True)

# expand dimensions
x_train = np.expand_dims(x_train, axis=2)
x_test = np.expand_dims(x_test, axis=2)

# define model
model = Sequential()
model.add(LSTM(units=n_comps, return_sequences=True,
               input_shape=(x_train.shape[1], 1),
               dropout=0.2, recurrent_dropout=0.2))
model.add(LSTM(64, return_sequences=True, dropout=0.2, recurrent_dropout=0.2))
model.add(LSTM(32, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(4 ,activation='softmax'))

# print model architecture summary
print(model.summary())

# compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

# Create a TensorBoard instance with the path to the logs directory
tensorboard = TensorBoard(log_dir='./logs/rnn/{}'.format(time()))

# fit the model
history = model.fit(x_train, y_train, epochs=n_epochs, batch_size=100,
                    validation_data=(x_test, y_test), callbacks=[tensorboard])

# plot results
vis.plot_nn_stats(history=history, stat_type="accuracy", fname="RNN-accuracy")
vis.plot_nn_stats(history=history, stat_type="loss", fname="RNN-loss")

My data is a large 2d matrix (38607, 150), where 149 is the number of features and 38607 is the number of samples, with a target vector including 4 classes.

       feat1   feat2   ...  feat148  feat149  target
1      2.250   0.926   ...  16.0      0.0     class1
2      2.791   1.235   ...  1.0       0.0     class2
         .       .     .     .         .         .
         .       .      .    .         .         .
         .       .       .   .         .         .
38406  2.873   1.262   ...  281.0     0.0     class3
38407  3.222   1.470   ...  467.0     1.0     class4


问:
Count number of digits in Kotlin
I'm currently counting number of digits using simple string.length approach:

```<code>val number = 829
val length = number.toString().length
</code>```

I wonder whether this is a good way or there is a more appropriate way to do that in Kotlin.

答:
If there are not only digits.
For example: "-11.345F" </p>

```<code>fun countDigits(str: String): Int = str.filter{ Character.isDigit(it) }.count()

// countDigits("-11.345F") == 5
</code>```

Title: Count number of digits in Kotlin

Body:
I'm currently counting number of digits using simple string.length approach:

val number = 829
val length = number.toString().length

I wonder whether this is a good way or there is a more appropriate way to do that in Kotlin.

Body:
If there are not only digits.
For example: "-11.345F"

fun countDigits(str: String): Int = str.filter{ Character.isDigit(it) }.count()

// countDigits("-11.345F") == 5


问:
how to apply model developped in fast.ai / pytorch?
I've trained a model which i'm trying to apply onto new data. I'm totally new to fast.ai
i'm creating my databunch as below (ds being the data i want to score):

```<code>bs = 64
data_lm = (TextList.from_df(df, path, cols='comment_text')
            .split_by_rand_pct(0.1)
            .label_for_lm()
            .databunch(bs=bs))
</code>```

The problem being that I cannot ommit the .split_by_rand_pct(0.1), so I cannot score the whole data

I then go and load/apply the model as below

```<code>data_clas = load_data(path, 'data_clas.pkl', bs=bs)
learn = text_classifier_learner(data_clas, AWD_LSTM, drop_mult=0.5)
learn.load_encoder('fine_tuned_enc')
learn.load('third');
preds, target = learn.get_preds(DatasetType.Test, ordered=True)
labels = preds.numpy()
</code>```

But the problem is i'm only scoring 0.1 pct of my data as the first piece of code when I create the databunch is not correct...i'm wanting to apply the saved/loaded model onto the overall DF.

Many thanks in advance

答:
a colleague of mine actually provided me with the solution, I'm posting it here in case it's useful to anyone.</p>

```<code>learn.data.add_test(df['Contact_Text'])
preds,y = learn.get_preds(ds_type=DatasetType.Test)
preds
</code>```

Body:
I've trained a model which i'm trying to apply onto new data. I'm totally new to fast.ai
i'm creating my databunch as below (ds being the data i want to score):

bs = 64
data_lm = (TextList.from_df(df, path, cols='comment_text')
            .split_by_rand_pct(0.1)
            .label_for_lm()
            .databunch(bs=bs))

The problem being that I cannot ommit the .split_by_rand_pct(0.1), so I cannot score the whole data

I then go and load/apply the model as below

data_clas = load_data(path, 'data_clas.pkl', bs=bs)
learn = text_classifier_learner(data_clas, AWD_LSTM, drop_mult=0.5)
learn.load_encoder('fine_tuned_enc')
learn.load('third');
preds, target = learn.get_preds(DatasetType.Test, ordered=True)
labels = preds.numpy()

But the problem is i'm only scoring 0.1 pct of my data as the first piece of code when I create the databunch is not correct...i'm wanting to apply the saved/loaded model onto the overall DF.

Many thanks in advance

Body:
a colleague of mine actually provided me with the solution, I'm posting it here in case it's useful to anyone.

learn.data.add_test(df['Contact_Text'])
preds,y = learn.get_preds(ds_type=DatasetType.Test)
preds


问:
ASP.Net and listening to event through open connection - is it possible to raise number of concurrently executing threads?
I am trying to use IIS to host an event-driven web-application. Lets say I want to use it for a chat-type application.

Instead of polling once every second or so (delay) I want to leave an open connection to my application which returns once there is data available.

The problem is that I can't get more than 10 concurrent threads executing.

I've set MaxThreads to 5000/5000, MaxConcurrentRequestsPerCpu to 5000, QueueLimit is 5000 by default, MaxConcurrentThreadsPerCPU is 0 (unbounded).

The only thing is that DefaultConnectionLimit seems to be 12 by default, and I can't seem to change it in my web.config. I've managed to set it in global.asax Application_Start but I don't know if it is too late to set it at that point. It says in the documentation that it does not affect already initialized ServicePoints.

```<code><system.net>
  <connectionManagement>
     <add address="*" maxconnection="100" />
  </connectionManagement>
</system.net>
</code>```

The above is what I have in my web.config (that concerns DefaultConnectionLimit).

```<code>5/14/2011 3:34:45 PM with timediff 0         :  Entered method with threadId: 6, MaxThreads is 5000/5000, MaxConcurrentRequestsPerCPU is 5000, MaxConcurrentThreadsPerCPU is 0, MinThreads is 1, AvailableThreads is 4998 and DefaultConnectionLimit is 1500
5/14/2011 3:34:45 PM with timediff 0         :  Entered method with threadId: 5, MaxThreads is 5000/5000, MaxConcurrentRequestsPerCPU is 5000, MaxConcurrentThreadsPerCPU is 0, MinThreads is 1, AvailableThreads is 4998 and DefaultConnectionLimit is 1500
5/14/2011 3:34:46 PM with timediff 0.5       :  Entered method with threadId: 7, MaxThreads is 5000/5000, MaxConcurrentRequestsPerCPU is 5000, MaxConcurrentThreadsPerCPU is 0, MinThreads is 1, AvailableThreads is 4997 and DefaultConnectionLimit is 1500
5/14/2011 3:34:47 PM with timediff 1.5       :  Entered method with threadId: 8, MaxThreads is 5000/5000, MaxConcurrentRequestsPerCPU is 5000, MaxConcurrentThreadsPerCPU is 0, MinThreads is 1, AvailableThreads is 4996 and DefaultConnectionLimit is 1500
5/14/2011 3:34:48 PM with timediff 2.5       :  Entered method with threadId: 9, MaxThreads is 5000/5000, MaxConcurrentRequestsPerCPU is 5000, MaxConcurrentThreadsPerCPU is 0, MinThreads is 1, AvailableThreads is 4995 and DefaultConnectionLimit is 1500
5/14/2011 3:34:49 PM with timediff 3.5       :  Entered method with threadId: 10, MaxThreads is 5000/5000, MaxConcurrentRequestsPerCPU is 5000, MaxConcurrentThreadsPerCPU is 0, MinThreads is 1, AvailableThreads is 4994 and DefaultConnectionLimit is 1500
5/14/2011 3:34:50 PM with timediff 4.5       :  Entered method with threadId: 12, MaxThreads is 5000/5000, MaxConcurrentRequestsPerCPU is 5000, MaxConcurrentThreadsPerCPU is 0, MinThreads is 1, AvailableThreads is 4993 and DefaultConnectionLimit is 1500
5/14/2011 3:34:51 PM with timediff 5.5       :  Entered method with threadId: 13, MaxThreads is 5000/5000, MaxConcurrentRequestsPerCPU is 5000, MaxConcurrentThreadsPerCPU is 0, MinThreads is 1, AvailableThreads is 4992 and DefaultConnectionLimit is 1500
5/14/2011 3:34:52 PM with timediff 6.5       :  Entered method with threadId: 14, MaxThreads is 5000/5000, MaxConcurrentRequestsPerCPU is 5000, MaxConcurrentThreadsPerCPU is 0, MinThreads is 1, AvailableThreads is 4991 and DefaultConnectionLimit is 1500
5/14/2011 3:34:52 PM with timediff 7         :  Entered method with threadId: 15, MaxThreads is 5000/5000, MaxConcurrentRequestsPerCPU is 5000, MaxConcurrentThreadsPerCPU is 0, MinThreads is 1, AvailableThreads is 4990 and DefaultConnectionLimit is 1500
5/14/2011 3:36:45 PM with timediff 120       :      Exiting method with threadId: 6
5/14/2011 3:36:45 PM with timediff 120       :      Exiting method with threadId: 5
5/14/2011 3:36:46 PM with timediff 120.5     :      Exiting method with threadId: 7
5/14/2011 3:36:47 PM with timediff 121.5     :      Exiting method with threadId: 8
5/14/2011 3:36:48 PM with timediff 122.5     :      Exiting method with threadId: 9
5/14/2011 3:36:49 PM with timediff 123.5     :      Exiting method with threadId: 10
</code>```

The above is an excerpt from the log file I am producing to test thread concurrency. It is simply an MVC action method with a 120 second sleep in it. Timediff is the difference from first request to the current request being logged.

As you can see, AvailableThreads dip down to 4990, and then waits for the other threads to exit before continuing. The delay between requests seems to be Fiddlers fault (which I use to load test).

I've also tried BadBoy to issue the same requests, and it also suffers from the 10 thread limit.

Is this because the connections are from the same client? Is there some other limit I have missed? It's admittedly difficult to load-test with different hosts..

答: If you test your application under Windows 7. It has 10 concurrent connections limit. Additionally, you may find (IISTuner) useful. </p>

Body:
I am trying to use IIS to host an event-driven web-application. Lets say I want to use it for a chat-type application.

Instead of polling once every second or so (delay) I want to leave an open connection to my application which returns once there is data available.

The problem is that I can't get more than 10 concurrent threads executing.

I've set MaxThreads to 5000/5000, MaxConcurrentRequestsPerCpu to 5000, QueueLimit is 5000 by default, MaxConcurrentThreadsPerCPU is 0 (unbounded).

The only thing is that DefaultConnectionLimit seems to be 12 by default, and I can't seem to change it in my web.config. I've managed to set it in global.asax Application_Start but I don't know if it is too late to set it at that point. It says in the documentation that it does not affect already initialized ServicePoints.

<system.net>
  <connectionManagement>
     <add address="*" maxconnection="100" />
  </connectionManagement>
</system.net>

The above is what I have in my web.config (that concerns DefaultConnectionLimit).

5/14/2011 3:34:45 PM with timediff 0         :  Entered method with threadId: 6, MaxThreads is 5000/5000, MaxConcurrentRequestsPerCPU is 5000, MaxConcurrentThreadsPerCPU is 0, MinThreads is 1, AvailableThreads is 4998 and DefaultConnectionLimit is 1500
5/14/2011 3:34:45 PM with timediff 0         :  Entered method with threadId: 5, MaxThreads is 5000/5000, MaxConcurrentRequestsPerCPU is 5000, MaxConcurrentThreadsPerCPU is 0, MinThreads is 1, AvailableThreads is 4998 and DefaultConnectionLimit is 1500
5/14/2011 3:34:46 PM with timediff 0.5       :  Entered method with threadId: 7, MaxThreads is 5000/5000, MaxConcurrentRequestsPerCPU is 5000, MaxConcurrentThreadsPerCPU is 0, MinThreads is 1, AvailableThreads is 4997 and DefaultConnectionLimit is 1500
5/14/2011 3:34:47 PM with timediff 1.5       :  Entered method with threadId: 8, MaxThreads is 5000/5000, MaxConcurrentRequestsPerCPU is 5000, MaxConcurrentThreadsPerCPU is 0, MinThreads is 1, AvailableThreads is 4996 and DefaultConnectionLimit is 1500
5/14/2011 3:34:48 PM with timediff 2.5       :  Entered method with threadId: 9, MaxThreads is 5000/5000, MaxConcurrentRequestsPerCPU is 5000, MaxConcurrentThreadsPerCPU is 0, MinThreads is 1, AvailableThreads is 4995 and DefaultConnectionLimit is 1500
5/14/2011 3:34:49 PM with timediff 3.5       :  Entered method with threadId: 10, MaxThreads is 5000/5000, MaxConcurrentRequestsPerCPU is 5000, MaxConcurrentThreadsPerCPU is 0, MinThreads is 1, AvailableThreads is 4994 and DefaultConnectionLimit is 1500
5/14/2011 3:34:50 PM with timediff 4.5       :  Entered method with threadId: 12, MaxThreads is 5000/5000, MaxConcurrentRequestsPerCPU is 5000, MaxConcurrentThreadsPerCPU is 0, MinThreads is 1, AvailableThreads is 4993 and DefaultConnectionLimit is 1500
5/14/2011 3:34:51 PM with timediff 5.5       :  Entered method with threadId: 13, MaxThreads is 5000/5000, MaxConcurrentRequestsPerCPU is 5000, MaxConcurrentThreadsPerCPU is 0, MinThreads is 1, AvailableThreads is 4992 and DefaultConnectionLimit is 1500
5/14/2011 3:34:52 PM with timediff 6.5       :  Entered method with threadId: 14, MaxThreads is 5000/5000, MaxConcurrentRequestsPerCPU is 5000, MaxConcurrentThreadsPerCPU is 0, MinThreads is 1, AvailableThreads is 4991 and DefaultConnectionLimit is 1500
5/14/2011 3:34:52 PM with timediff 7         :  Entered method with threadId: 15, MaxThreads is 5000/5000, MaxConcurrentRequestsPerCPU is 5000, MaxConcurrentThreadsPerCPU is 0, MinThreads is 1, AvailableThreads is 4990 and DefaultConnectionLimit is 1500
5/14/2011 3:36:45 PM with timediff 120       :      Exiting method with threadId: 6
5/14/2011 3:36:45 PM with timediff 120       :      Exiting method with threadId: 5
5/14/2011 3:36:46 PM with timediff 120.5     :      Exiting method with threadId: 7
5/14/2011 3:36:47 PM with timediff 121.5     :      Exiting method with threadId: 8
5/14/2011 3:36:48 PM with timediff 122.5     :      Exiting method with threadId: 9
5/14/2011 3:36:49 PM with timediff 123.5     :      Exiting method with threadId: 10

The above is an excerpt from the log file I am producing to test thread concurrency. It is simply an MVC action method with a 120 second sleep in it. Timediff is the difference from first request to the current request being logged.

As you can see, AvailableThreads dip down to 4990, and then waits for the other threads to exit before continuing. The delay between requests seems to be Fiddlers fault (which I use to load test).

I've also tried BadBoy to issue the same requests, and it also suffers from the 10 thread limit.

Is this because the connections are from the same client? Is there some other limit I have missed? It's admittedly difficult to load-test with different hosts..


问:
OroPlatform without any entity alias
My OroPlatform-based system has no registered alias.

When I enter the command php bin/console oro:entity-alias:debug in the terminal, it returns only the result below:

```<code>Class Alias Plural Alias
</code>```

Does anyone have any idea what may have made all entity alias disappear?

答:
This could happen when you have an inconsistent cache.

Please, clear the cache with rm -rf var/cache/* and run php bin/console oro:platform:update command to warm all the caches up and synchronize the application code with the database.

Title: OroPlatform without any entity alias

Body:
My OroPlatform-based system has no registered alias.

When I enter the command php bin/console oro:entity-alias:debug in the terminal, it returns only the result below:

Class Alias Plural Alias

Does anyone have any idea what may have made all entity alias disappear?


问:
SQL return max in unnest
I have the following query:

```<code>SELECT
table_a.col1,
table_a.col2,
array.col1
FROM
table_a
LEFT JOIN UNNEST(table_a.array) AS array
</code>```

What should I do if I only want the query to return one array.col1 per row in table_a (let's say I want only the max value for each case)?

答:
You can use a subquery:</p>

```<code>select a.*,
       (select max(el)
        from unnest(a.array) el
       ) as max_el
from table_a a;
</code>```

Title: SQL return max in unnest

Body:
I have the following query:

SELECT
table_a.col1,
table_a.col2,
array.col1
FROM
table_a
LEFT JOIN UNNEST(table_a.array) AS array

What should I do if I only want the query to return one array.col1 per row in table_a (let's say I want only the max value for each case)?

Body:
You can use a subquery:

select a.*,
       (select max(el)
        from unnest(a.array) el
       ) as max_el
from table_a a;


问:
What does the (+) operator mean in a where-clause of PL/SQL?
I have a SQL query something like:-

```<code>Select Table1.attr1, Table1.attr2, Table2.attr3, Table2.attr4
From Tab1 Tabel1, Tab2 Tabel2
Where Tabel1.Attr = Tabel2.Attr (+)
</code>```

So what does the above mean? Is this a right outer join?

答: This is a a LEFT OUTER JOIN. You can find an example of using one here: https://www.techonthenet.com/oracle/joins.php</p>

ContentLicense: CC BY-SA 2.5

Body:
I have a SQL query something like:-

Select Table1.attr1, Table1.attr2, Table2.attr3, Table2.attr4
From Tab1 Tabel1, Tab2 Tabel2
Where Tabel1.Attr = Tabel2.Attr (+)

So what does the above mean? Is this a right outer join?


问:
Programmatically get the url of a page in liferay
I want to create a link in a portlet so that I can navigate to a different page in the liferay portal. I order to do that I am looking for an API (can be liferay specific) that given a page name, would return it's url (it can be the friendlyURL as well).</p>

答:
try this one for current url

```<code>${themeDisplay.getURLCurrent()}
</code>```

try this one for portal url

```<code>${themeDisplay.getPortalURL()}
</code>```

Body:
try this one for current url

${themeDisplay.getURLCurrent()}

try this one for portal url

${themeDisplay.getPortalURL()}


问:
Cant test if a database boolean is true in Laravel
I am trying to query our database to see if users can log in based on whether the organisation they belong to have logins enabled.

LoginController.php

```<code>protected function redirectTo()
{
    $user = Auth::user()->id;
    $userOrg = UserOrganization::where('user_id', $user)->first();
    $org = Organization::where('id', $userOrg->org_id)->first();

    if ($org->allow_org_login == 0) {

        return '/login';
    } else {
        if(Auth::user()->has_changed_temp_password == false)
        {
            DB::table('users')->where('id', $user)->update(['last_login' => Carbon::now()]);
            DB::table('users')->where('id', $user)->increment('total_logins');
            return '/user/password/change';
        } else {
            DB::table('users')->where('id', $user)->update(['last_login' => Carbon::now()]);
            DB::table('users')->where('id', $user)->increment('total_logins');
            return '/overview';
        }
    }
}
</code>```

trying to log in as a user belonging to an organisation with allow_org_login = 0 should redirect to the '/login' page, but instead it either logs the user in or prompts for a password change for a new user.

What am I doing wrong?

Edit: Debug contents of $org (allow_org_login on the bottom line)

答:
for redirectTo() method it will only fire when we using POST method for login.

inside you redirectTo() method your check condition and then you return '/login';
which it will redirectTo login page. but this time you already login then on login it will check if user login then it redirectTo url that we config on LoginController and protected $redirectTo; it will not call redirectTo() method. cuz this time we use redirect using GET method not POST.

if you want to put validate on redirectTo() method you can try below code:

```<code>protected function redirectTo()
{
    $user = Auth::user()->id;
    $userOrg = UserOrganization::where('user_id', $user)->first();
    $org = Organization::where('id', $userOrg->org_id)->first();

    if ($org->allow_org_login == 0) {
        Auth::logout(); // logout user before redirect
        return '/login';
    } else {
        if(Auth::user()->has_changed_temp_password == false)
        {
           // depend on you choice need to logout or not
            DB::table('users')->where('id', $user)->update(['last_login' => Carbon::now()]);
            DB::table('users')->where('id', $user)->increment('total_logins');
            return '/user/password/change';
        } else {
            // depend on you choice need to logout or not
            DB::table('users')->where('id', $user)->update(['last_login' => Carbon::now()]);
            DB::table('users')->where('id', $user)->increment('total_logins');
            return '/overview';
        }
    }
}
</code>```

but for my option i will create new middleware for handle this.

Body:
I am trying to query our database to see if users can log in based on whether the organisation they belong to have logins enabled.

LoginController.php

protected function redirectTo()
{
    $user = Auth::user()->id;
    $userOrg = UserOrganization::where('user_id', $user)->first();
    $org = Organization::where('id', $userOrg->org_id)->first();

    if ($org->allow_org_login == 0) {

        return '/login';
    } else {
        if(Auth::user()->has_changed_temp_password == false)
        {
            DB::table('users')->where('id', $user)->update(['last_login' => Carbon::now()]);
            DB::table('users')->where('id', $user)->increment('total_logins');
            return '/user/password/change';
        } else {
            DB::table('users')->where('id', $user)->update(['last_login' => Carbon::now()]);
            DB::table('users')->where('id', $user)->increment('total_logins');
            return '/overview';
        }
    }
}

trying to log in as a user belonging to an organisation with allow_org_login = 0 should redirect to the '/login' page, but instead it either logs the user in or prompts for a password change for a new user.

What am I doing wrong?

Edit: Debug contents of $org (allow_org_login on the bottom line)

Body:
for redirectTo() method it will only fire when we using POST method for login.

inside you redirectTo() method your check condition and then you return '/login';
which it will redirectTo login page. but this time you already login then on login it will check if user login then it redirectTo url that we config on LoginController and protected $redirectTo; it will not call redirectTo() method. cuz this time we use redirect using GET method not POST.

if you want to put validate on redirectTo() method you can try below code:

protected function redirectTo()
{
    $user = Auth::user()->id;
    $userOrg = UserOrganization::where('user_id', $user)->first();
    $org = Organization::where('id', $userOrg->org_id)->first();

    if ($org->allow_org_login == 0) {
        Auth::logout(); // logout user before redirect
        return '/login';
    } else {
        if(Auth::user()->has_changed_temp_password == false)
        {
           // depend on you choice need to logout or not
            DB::table('users')->where('id', $user)->update(['last_login' => Carbon::now()]);
            DB::table('users')->where('id', $user)->increment('total_logins');
            return '/user/password/change';
        } else {
            // depend on you choice need to logout or not
            DB::table('users')->where('id', $user)->update(['last_login' => Carbon::now()]);
            DB::table('users')->where('id', $user)->increment('total_logins');
            return '/overview';
        }
    }
}

but for my option i will create new middleware for handle this.


问:
How to enforce 32bit of .net String GetHashCode()

Possible Duplicate:

  GetHashCode() gives different results on different servers?

I used string GetHashCode() in my .net 4.0 program and store the value in the DB. The problem is that when I run the program on different setup, 64 vs 32, .net use different hashing algorithm for string hashing. So I won’t get the match all the time. So does anyone know how can I just compute the 32bit of string hashing even on a 64bit build.

答: The simple answer is to not do that. The values are specified as platform-dependent, and the exact behavior is not defined outside of satisfying the contract of GetHashCode. It's not guaranteed to stay the same across new releases of .NET, new architectures, or even patches. Use an actual hash algorithm whose behavior is defined, such as SHA-1, CRC, or something else (depending on the actual requirements).</p>


问:
SQL group_by and group_concat if all values present in group
```<code>/*
 cars                   cars_location
+------+---------+    +-------------+-----+            garages
| id   | int     |<---| car_id        | int |     +-------+---------+
| name | varchar |    | garage_id     | int | --->| id    | int     |
+------+---------+    +-------------+-----+       | name  | varchar |
                                                  +-------+---------+
*/
drop table if exists cars, garages, cars_location;
create table cars
(
    id   int not null,
    name varchar(255),
    primary key (id)
);
create table garages
(
    id   int not null,
    name varchar(255),
    primary key (id)
);
create table cars_location
(
    car_id     int not null,
    garage_id  int not null,
    primary key (car_id, garage_id)
);
insert into cars (id, name)
values (1, 'BMW'),
       (2, 'Audi'),
       (3, 'Volkswagen');
insert into garages (id, name)
values (1, 'Garage1'),
       (2, 'Garage2'),
       (3, 'Garage3'),
       (4, 'Garage4');
insert into cars_location (car_id, garage_id)
values (1, 1),
       (1, 2),
       (1, 3),
       (2, 1),
       (2, 2),
       (2, 3),
       (2, 4),
       (3, 1),
       (3, 2),
       (3, 4);
-- Find all cars placed in all requested garages at the same time.
-- Example below:
/*
---------------------------------------------------------
cars       |   garages
---------------------------------------------------------
BMW        | Garage1, Garage2, Garage3                 - RETURNED!!
Audi       | Garage1, Garage2, Garage3, Garage4        - RETURNED!!
Volkswagen | Garage1, Garage2,                 Garage4 - NOT returned
---------------------------------------------------------
*/

select cars.name as cars,
       group_concat(
           garages.name
           ) as places
from cars_location
         left join cars on cars.id = cars_location.car_id
         left join garages on garages.id = cars_location.garage_id
-- where places in (1,2,3) # problem here because Volkswagen doesnt exist in garage 3 so should not be visible
group by 1
</code>```

Find all cars placed in all requested garages at the same time. So I want to achieve this

```<code>---------------------------------------------------------
cars       |   garages
---------------------------------------------------------
BMW        | Garage1, Garage2, Garage3                 - RETURNED!!
Audi       | Garage1, Garage2, Garage3, Garage4        - RETURNED!!
Volkswagen | Garage1, Garage2,                 Garage4 - NOT returned because garage3 not present
---------------------------------------------------------
</code>```

I dont know how to build only one sql query

```<code>select cars.name as cars,
       group_concat(
           garages.name
           ) as places
from cars_location
         left join cars on cars.id = cars_location.car_id
         left join garages on garages.id = cars_location.garage_id
-- where places MUST BE in (1,2,3) # problem here because Volkswagen doesnt exist in garage 3 so should not be returned by sql
group by 1
</code>```

http://sqlfiddle.com/#!9/eadd7a/1

答:
Your problem is called Relational Division. Assuming cars_location (car_id, garage_id) is unique:

```<code>select cars.name as cars,
       group_concat(
           garages.name
           ) as places
from cars_location  -- no Outer Joins needed as you don't want non-matching locations
         join cars on cars.id = cars_location.car_id
         join garages on garages.id = cars_location.garage_id
where garages.id in (1,2,3)
group by 1
having count(*) = 3 -- exactly three rows
</code>```

Body:
/*
 cars                   cars_location
+------+---------+    +-------------+-----+            garages
| id   | int     |<---| car_id        | int |     +-------+---------+
| name | varchar |    | garage_id     | int | --->| id    | int     |
+------+---------+    +-------------+-----+       | name  | varchar |
                                                  +-------+---------+
*/
drop table if exists cars, garages, cars_location;
create table cars
(
    id   int not null,
    name varchar(255),
    primary key (id)
);
create table garages
(
    id   int not null,
    name varchar(255),
    primary key (id)
);
create table cars_location
(
    car_id     int not null,
    garage_id  int not null,
    primary key (car_id, garage_id)
);
insert into cars (id, name)
values (1, 'BMW'),
       (2, 'Audi'),
       (3, 'Volkswagen');
insert into garages (id, name)
values (1, 'Garage1'),
       (2, 'Garage2'),
       (3, 'Garage3'),
       (4, 'Garage4');
insert into cars_location (car_id, garage_id)
values (1, 1),
       (1, 2),
       (1, 3),
       (2, 1),
       (2, 2),
       (2, 3),
       (2, 4),
       (3, 1),
       (3, 2),
       (3, 4);
-- Find all cars placed in all requested garages at the same time.
-- Example below:
/*
---------------------------------------------------------
cars       |   garages
---------------------------------------------------------
BMW        | Garage1, Garage2, Garage3                 - RETURNED!!
Audi       | Garage1, Garage2, Garage3, Garage4        - RETURNED!!
Volkswagen | Garage1, Garage2,                 Garage4 - NOT returned
---------------------------------------------------------
*/

select cars.name as cars,
       group_concat(
           garages.name
           ) as places
from cars_location
         left join cars on cars.id = cars_location.car_id
         left join garages on garages.id = cars_location.garage_id
-- where places in (1,2,3) # problem here because Volkswagen doesnt exist in garage 3 so should not be visible
group by 1

Find all cars placed in all requested garages at the same time. So I want to achieve this

---------------------------------------------------------
cars       |   garages
---------------------------------------------------------
BMW        | Garage1, Garage2, Garage3                 - RETURNED!!
Audi       | Garage1, Garage2, Garage3, Garage4        - RETURNED!!
Volkswagen | Garage1, Garage2,                 Garage4 - NOT returned because garage3 not present
---------------------------------------------------------

I dont know how to build only one sql query

select cars.name as cars,
       group_concat(
           garages.name
           ) as places
from cars_location
         left join cars on cars.id = cars_location.car_id
         left join garages on garages.id = cars_location.garage_id
-- where places MUST BE in (1,2,3) # problem here because Volkswagen doesnt exist in garage 3 so should not be returned by sql
group by 1

http://sqlfiddle.com/#!9/eadd7a/1

Body:
Your problem is called Relational Division. Assuming cars_location (car_id, garage_id) is unique:

select cars.name as cars,
       group_concat(
           garages.name
           ) as places
from cars_location  -- no Outer Joins needed as you don't want non-matching locations
         join cars on cars.id = cars_location.car_id
         join garages on garages.id = cars_location.garage_id
where garages.id in (1,2,3)
group by 1
having count(*) = 3 -- exactly three rows


问:
How to declare SCSS <length> type attribute selector by REACT property
Basically I want to create a reusable component which can be slightly modified from the outside in react:

SomewhereElse.tsx

```<code>...
<FooComponent width={200}>
...
</code>```

FooComponent.tsx

```<code>interface IFooProps {
  //default width of 150px
  width?: 150;
  //default margin of 5px
  margin?: 5;
}

interface IFooState{
  checked: boolean;
}

class FooComponent extends Component<IFooProps, IFooState> {
    constructor(props: IFooProps) {
        super(props);
        ...
    }

...

    render(): ReactElement {
        return (
          <div className="foo-component"
              data-width={this.props.width + 'px'}
          >
          ...
</code>```

FooComponent.scss

```<code>.foo-component {
    ...
    width: attr(data-width length);
    ...
</code>```

But it always gives me the following error when running the application (chrome):

... Please consider that I need a "number" as property because I am doing some calculations based on that number for some of the inner components so everything fits together.

EDIT:

Using "style" is not working for me because I have some ::before ::after features in my scss which are broken when using style because they occasionally modify "right:" based on the width.

For better understanding, this is my base:
https://www.sitepoint.com/react-toggle-switch-reusable-component/

答:
An easier way would be using inline style:</p>

```<code>       return (
          <div className="foo-component"
              style=`width:${this.props.width};`
          >
</code>```

Body:
Basically I want to create a reusable component which can be slightly modified from the outside in react:

SomewhereElse.tsx

...
<FooComponent width={200}>
...

FooComponent.tsx

interface IFooProps {
  //default width of 150px
  width?: 150;
  //default margin of 5px
  margin?: 5;
}

interface IFooState{
  checked: boolean;
}

class FooComponent extends Component<IFooProps, IFooState> {
    constructor(props: IFooProps) {
        super(props);
        ...
    }

...

    render(): ReactElement {
        return (

          ...

FooComponent.scss

.foo-component {
    ...
    width: attr(data-width length);
    ...

But it always gives me the following error when running the application (chrome):

... Please consider that I need a "number" as property because I am doing some calculations based on that number for some of the inner components so everything fits together.

EDIT:

Using "style" is not working for me because I have some ::before ::after features in my scss which are broken when using style because they occasionally modify "right:" based on the width.

For better understanding, this is my base:
https://www.sitepoint.com/react-toggle-switch-reusable-component/

Body:
An easier way would be using inline style:

       return (
          <div className="foo-component"
              style=`width:${this.props.width};`
          >


问:
Read system call blocked sharing a pipe
I'm new in Unix systems programming and I'm struggling to understand file descriptors and pipes. Let's consider this simple code:

```<code>#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>

int main() {
  int fd[2], p;
  char *m = "123456789\n", c;
  pipe(fd);
  p = fork();
  if (p == 0) {
    // child
    while(read(fd[0], &c, 1) > 0) write(1, &c, 1);
  }
  else {
    // parent
    write(fd[1], m, strlen(m));
    close(fd[1]);
    wait(NULL);
  }
  exit (0);
}
</code>```

When I compile and run the code, it outputs 123456789 but the process never ends unless I issue ^C. Actually, both processes appear as stopped in htop.

If the child closes fd[1] prior to read() then it seems to work OK but I don't understand why. The fd are shared between both processes and the parent closes fd[1] after writing. Why then the child doesn't get the EOF when reading?

Thank you in advance!

答:
Well, first of all your parent process is waiting for the child to terminate in the wait(2) system call, whyle your child is blocked in the pipe to read(2) for another character.  Both processes are blocked... so you need to act externally to take them off.  The problem is that the child process doesn't close it's writing descriptor of the pipe (and also the parent doesn't close its reading descriptor of the pipe, but this doesn't affect here)  Simply the pipe blocks any reader while at least one such writing descriptor is still open. Only when all writing descriptors are closed, the read returns 0 to the reader.

When you did the fork(2) both pipe descriptors (fd[0] and fd[1]) were dup()ed on the child process, so you have a pipe with two open file descriptors (one in the parent, one in the child) for writing, and two open descriptors (again, one in the parent, one in the child) for reading, so as one writer remains with the pipe open for writing (the child process in this case) the read made by the child still blocks.  The kernel cannot detect this as an anomaly, because the child could still write on the pipe if another thread (or a signal handler) should want to.

By the way, I'm going to comment some things you made bad in your code:

first is that you consider only two cases from fork() for the parent, and for the child, but if the fork fails, it will return -1 and you'll have a parent process writing on a pipe with no reading process, so probably it should block (as I say, this is not your case, but it is an error either) You have always to check for errors from system calls, and don't assume your fork() call is never to fail (think that -1 is considered != 0 and so it falls through the parent's code).  There's only one system call that you can execute without checking it for errors, and it is close(2) (although there's much controversy on this)

This same happens with read() and write().  A better solution to your problem would be to have used a larger buffer (not just one char, to reduce the number of system calls made by your program and so speed it up) and use the return value of read() as a parameter on the write() call.

Your program should (it does on my system, indeed) work with just inserting the following line:

```<code>close(fd[1]);
</code>```

just before the while loop in the child code, as shown here:

```<code>#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>

int main() {
  int fd[2], p;
  char *m = "123456789\n", c;
  pipe(fd);
  p = fork();
  if (p == 0) {
    // child
    close(fd[1]);  // <--- this close is fundamental for the pipe to work properly.
    while(read(fd[0], &c, 1) > 0) write(1, &c, 1);
  }
  else if (p > 0) {
    // parent
    // another close(fd[0]); should be included here
    write(fd[1], m, strlen(m));
    close(fd[1]);
    wait(NULL);
  } else {
    // include error processing for fork() here
  }
  exit (0);
}
</code>```

Title: Read system call blocked sharing a pipe

Body:
I'm new in Unix systems programming and I'm struggling to understand file descriptors and pipes. Let's consider this simple code:

#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>

int main() {
  int fd[2], p;
  char *m = "123456789\n", c;
  pipe(fd);
  p = fork();
  if (p == 0) {
    // child
    while(read(fd[0], &c, 1) > 0) write(1, &c, 1);
  }
  else {
    // parent
    write(fd[1], m, strlen(m));
    close(fd[1]);
    wait(NULL);
  }
  exit (0);
}

When I compile and run the code, it outputs 123456789 but the process never ends unless I issue ^C. Actually, both processes appear as stopped in htop.

If the child closes fd[1] prior to read() then it seems to work OK but I don't understand why. The fd are shared between both processes and the parent closes fd[1] after writing. Why then the child doesn't get the EOF when reading?

Thank you in advance!

Body:
Well, first of all your parent process is waiting for the child to terminate in the wait(2) system call, whyle your child is blocked in the pipe to read(2) for another character.  Both processes are blocked... so you need to act externally to take them off.  The problem is that the child process doesn't close it's writing descriptor of the pipe (and also the parent doesn't close its reading descriptor of the pipe, but this doesn't affect here)  Simply the pipe blocks any reader while at least one such writing descriptor is still open. Only when all writing descriptors are closed, the read returns 0 to the reader.

When you did the fork(2) both pipe descriptors (fd[0] and fd[1]) were dup()ed on the child process, so you have a pipe with two open file descriptors (one in the parent, one in the child) for writing, and two open descriptors (again, one in the parent, one in the child) for reading, so as one writer remains with the pipe open for writing (the child process in this case) the read made by the child still blocks.  The kernel cannot detect this as an anomaly, because the child could still write on the pipe if another thread (or a signal handler) should want to.

By the way, I'm going to comment some things you made bad in your code:

first is that you consider only two cases from fork() for the parent, and for the child, but if the fork fails, it will return -1 and you'll have a parent process writing on a pipe with no reading process, so probably it should block (as I say, this is not your case, but it is an error either) You have always to check for errors from system calls, and don't assume your fork() call is never to fail (think that -1 is considered != 0 and so it falls through the parent's code).  There's only one system call that you can execute without checking it for errors, and it is close(2) (although there's much controversy on this)

This same happens with read() and write().  A better solution to your problem would be to have used a larger buffer (not just one char, to reduce the number of system calls made by your program and so speed it up) and use the return value of read() as a parameter on the write() call.

Your program should (it does on my system, indeed) work with just inserting the following line:

close(fd[1]);

just before the while loop in the child code, as shown here:

#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>

int main() {
  int fd[2], p;
  char *m = "123456789\n", c;
  pipe(fd);
  p = fork();
  if (p == 0) {
    // child
    close(fd[1]);  // <--- this close is fundamental for the pipe to work properly.
    while(read(fd[0], &c, 1) > 0) write(1, &c, 1);
  }
  else if (p > 0) {
    // parent
    // another close(fd[0]); should be included here
    write(fd[1], m, strlen(m));
    close(fd[1]);
    wait(NULL);
  } else {
    // include error processing for fork() here
  }
  exit (0);
}


问:
Discord.js not writing data to .json file
This is my ban command, im trying to export the code to work within a command handler. Iv had numerous issues with this command but eventually i have almost everything working. The code runs perfectly until the point where it should write to .json file (I changed the .json directory to make sure it was being found, and it threw an error so the previous line of code is definitely running, and its finding the .json). Any help would be greatly appreciated, thank you

I have also tried replacing this line

let bannedIDs = require('../../bannedIDs.json').ids || []

```

<p>with</p>

<pre class="lang-js prettyprint-override"><code>let file = fs.readFileSync('../../bannedIDs.json')
let bannedIDs = JSON.parse(file).ids || []
</code>```

still results in no data being written to the .json

const { RichEmbed } = require("discord.js");
const fs = require('fs');

module.exports = {
  config: {
    name: "ban",
    description: "Bans a user from the guild!",
    usage: "!ban",
    category: "moderation",
    accessableby: "Administrators",
    aliases: ["b", "banish", "remove"]
  },
  run: async (bot, message, args) => {

    if (!message.member.hasPermission(["BAN_MEMBERS", "ADMINISTRATOR"])) return message.channel.send("You do not have permission to perform this command!");

    const user1 = message.mentions.users.first();
    let member = message.mentions.members.first();

    if (member) {

      const member = message.mentions.members.first();

      let reason = args.slice(2).join(' ');
      var user = message.mentions.users.first();

      member.ban({ reason: `${args.slice(2).join(' ')}` }).then(() => {
        let uEmbed = new RichEmbed()
          .setTitle('**' + `Sucessfully Banned ${user1.tag}!` + '**')
          .setThumbnail('https://i.gyazo.com/8988806671312f358509cf0fd69341006.jpg')
          .setImage('https://media3.giphy.com/media/H99r2HtnYs492/giphy.gif?cid=ecf05e47db8ad81dd0dbb6b132bb551add0955f9b92ba021&rid=giphy.gif')
          .setColor(0x320b52)
          .setTimestamp()
          .setFooter('Requested by ' + message.author.tag, 'https://i.gyazo.com/8988806671312f358509cf0fd69341006.jpg');
        message.channel.send(uEmbed);

      }).catch(err => {
        message.channel.send('I was unable to kick the member');
        console.log(err);
      });
    } else {
      const PREFIX = '!';

      let args = message.content.substring(PREFIX.length).split(" ");

      let user = message.mentions.users.first(),
        userID = user ? user.id : args[1];

      if (isNaN(args[1])) return message.channel.send("You need to enter a vlaid @Member or UserID #");

      if (args[1].length <= 17 || args[1].length >= 19) return message.channel.send("UserID # must be 18 Digits");

      if (userID) {
        let bannedIDs = require('../../bannedIDs.json').ids || [];

        if (!bannedIDs.includes(userID)) bannedIDs.push(userID);

        fs.writeFileSync('../../bannedIDs.json', JSON.stringify({ ids: bannedIDs }));
        let reason = args.slice(2).join(' ');

        let uEmbed = new RichEmbed()
          .setTitle('**' + `UserID #${args[1]}\n Will be Banned on Return!` + '**')
          .setThumbnail('https://i.gyazo.com/8988806671312f358509cf0fd69341006.jpg')
          .setImage('https://i.imgur.com/6Sh8csf.gif')
          .setColor(0x320b52)
          .setTimestamp()
          .setFooter('Requested by ' + message.author.tag, 'https://i.gyazo.com/8988806671312f358509cf0fd69341006.jpg');
        message.channel.send(uEmbed);
        let reason1 = args.slice(2).join(' ');
      } else {
        message.channel.send('Error');
      }
    }
  }

};

```

答:
require('../../bannedIDs.json').ids || [] I'm guessing why this doesn't work is because if require(...) doesn't exist, you wouldn't be able to access .id, this is a common thing in js which you can usually just do obj && obj.property or with babel obj?.property

This is personally how I would do it

let file = require('../../bannedIDs.json') || { ids: [userID] };
const bannedIDs = file.bannedIDs;

if (!bannedIDs.includes(userID)) bannedIDs.push(userID);

fs.writeFile('../../bannedIDs.json', JSON.stringify(file));
```

<p>Also you can just do </p>

<pre class="lang-js prettyprint-override"><code>const collection = await <Guild>.fetchBans();
const ids = collection.map(e => e.user.id).array();
</code>```

To get a list of banned users or Ids

Body:
This is my ban command, im trying to export the code to work within a command handler. Iv had numerous issues with this command but eventually i have almost everything working. The code runs perfectly until the point where it should write to .json file (I changed the .json directory to make sure it was being found, and it threw an error so the previous line of code is definitely running, and its finding the .json). Any help would be greatly appreciated, thank you

I have also tried replacing this line

let bannedIDs = require('../../bannedIDs.json').ids || []

with

let file = fs.readFileSync('../../bannedIDs.json')
let bannedIDs = JSON.parse(file).ids || []

still results in no data being written to the .json

const { RichEmbed } = require("discord.js");
const fs = require('fs');

module.exports = {
  config: {
    name: "ban",
    description: "Bans a user from the guild!",
    usage: "!ban",
    category: "moderation",
    accessableby: "Administrators",
    aliases: ["b", "banish", "remove"]
  },
  run: async (bot, message, args) => {

    if (!message.member.hasPermission(["BAN_MEMBERS", "ADMINISTRATOR"])) return message.channel.send("You do not have permission to perform this command!");

    const user1 = message.mentions.users.first();
    let member = message.mentions.members.first();

    if (member) {

      const member = message.mentions.members.first();

      let reason = args.slice(2).join(' ');
      var user = message.mentions.users.first();

      member.ban({ reason: `${args.slice(2).join(' ')}` }).then(() => {
        let uEmbed = new RichEmbed()
          .setTitle('**' + `Sucessfully Banned ${user1.tag}!` + '**')
          .setThumbnail('https://i.gyazo.com/8988806671312f358509cf0fd69341006.jpg')
          .setImage('https://media3.giphy.com/media/H99r2HtnYs492/giphy.gif?cid=ecf05e47db8ad81dd0dbb6b132bb551add0955f9b92ba021&rid=giphy.gif')
          .setColor(0x320b52)
          .setTimestamp()
          .setFooter('Requested by ' + message.author.tag, 'https://i.gyazo.com/8988806671312f358509cf0fd69341006.jpg');
        message.channel.send(uEmbed);

      }).catch(err => {
        message.channel.send('I was unable to kick the member');
        console.log(err);
      });
    } else {
      const PREFIX = '!';

      let args = message.content.substring(PREFIX.length).split(" ");

      let user = message.mentions.users.first(),
        userID = user ? user.id : args[1];

      if (isNaN(args[1])) return message.channel.send("You need to enter a vlaid @Member or UserID #");

      if (args[1].length <= 17 || args[1].length >= 19) return message.channel.send("UserID # must be 18 Digits");

      if (userID) {
        let bannedIDs = require('../../bannedIDs.json').ids || [];

        if (!bannedIDs.includes(userID)) bannedIDs.push(userID);

        fs.writeFileSync('../../bannedIDs.json', JSON.stringify({ ids: bannedIDs }));
        let reason = args.slice(2).join(' ');

        let uEmbed = new RichEmbed()
          .setTitle('**' + `UserID #${args[1]}\n Will be Banned on Return!` + '**')
          .setThumbnail('https://i.gyazo.com/8988806671312f358509cf0fd69341006.jpg')
          .setImage('https://i.imgur.com/6Sh8csf.gif')
          .setColor(0x320b52)
          .setTimestamp()
          .setFooter('Requested by ' + message.author.tag, 'https://i.gyazo.com/8988806671312f358509cf0fd69341006.jpg');
        message.channel.send(uEmbed);
        let reason1 = args.slice(2).join(' ');
      } else {
        message.channel.send('Error');
      }
    }
  }

};

Body:
require('../../bannedIDs.json').ids || [] I'm guessing why this doesn't work is because if require(...) doesn't exist, you wouldn't be able to access .id, this is a common thing in js which you can usually just do obj && obj.property or with babel obj?.property

This is personally how I would do it

let file = require('../../bannedIDs.json') || { ids: [userID] };
const bannedIDs = file.bannedIDs;

if (!bannedIDs.includes(userID)) bannedIDs.push(userID);

fs.writeFile('../../bannedIDs.json', JSON.stringify(file));

Also you can just do

const collection = await <Guild>.fetchBans();
const ids = collection.map(e => e.user.id).array();

To get a list of banned users or Ids


问:
Why did I get this item wrong on my homework?
I got this problem wrong on my homework, and I can't figure out why:

```<code>procedure Main is
    X: Integer;
    procedure Sub1 is
       X: Integer;
    begin -- of Sub1
       Put(X);
    end; -- of Sub1
    procedure Sub2 is
       X: Integer;
    begin -- of Sub2
       X:=5;
       Sub1;
    end; -- of Sub2
begin -- of Main
    X:=12;
    Sub2;
end; -- of Main
</code>```

The Question is:
Assume the following Ada program was compiled and execute using static-scoping rules. What value of X is printed in procedure of Sub1? What if it was under dyncamic scoping rules?

I got 12 and 5 respectively, but this was marked incorrect. Why?

答: Step through the program more carefully. Where is the value coming from in Sub1?</p>

OwnerDisplayName: kylex

Body:
I got this problem wrong on my homework, and I can't figure out why:

procedure Main is
    X: Integer;
    procedure Sub1 is
       X: Integer;
    begin -- of Sub1
       Put(X);
    end; -- of Sub1
    procedure Sub2 is
       X: Integer;
    begin -- of Sub2
       X:=5;
       Sub1;
    end; -- of Sub2
begin -- of Main
    X:=12;
    Sub2;
end; -- of Main

The Question is:
Assume the following Ada program was compiled and execute using static-scoping rules. What value of X is printed in procedure of Sub1? What if it was under dyncamic scoping rules?

I got 12 and 5 respectively, but this was marked incorrect. Why?

OwnerDisplayName: Ryan Graham


问:
How to cancel requests incase of triggering them using forkJoin Rxjs , Angular
I have a set of 6 http get requests which I have to make irrespective of their sequence on a button click.I am using forkJoin for that purpose

```<code><button click="getData()">Get Data</button>

getData(){

  const ids = [1,2,3,4,5,6];

  const obs = ids.map(id => this.http.get('<my url>/' + id)

  forkJoin(...obs).subscribe(res => console.log(res));

}
</code>```

If a user clicks on the button multiple time, is there a way I could cancel previous uncompleted requests and only make new fresh calls to the backend ?

I did some research and understood switchMap operator helps in cancelling requests but I am not sure how I would be using it here.

Please help

答:
```<code>public subscription: Subscription;

getData(){

  const ids = [1,2,3,4,5,6];

  const obs = ids.map(id => this.http.get('<my url>/' + id)

  if(this.subscription){
     this.subscription.unsubscribe();
  }

  this.subscription = forkJoin(...obs).subscribe(res =>console.log(res))
}
</code>```

Body:
I have a set of 6 http get requests which I have to make irrespective of their sequence on a button click.I am using forkJoin for that purpose

<button click="getData()">Get Data</button>

getData(){

  const ids = [1,2,3,4,5,6];

  const obs = ids.map(id => this.http.get('<my url>/' + id)

  forkJoin(...obs).subscribe(res => console.log(res));

}

If a user clicks on the button multiple time, is there a way I could cancel previous uncompleted requests and only make new fresh calls to the backend ?

I did some research and understood switchMap operator helps in cancelling requests but I am not sure how I would be using it here.

Please help


问:
Vertex in Python Gremlin not updating
Using python gremlin on Neptune workbench, I have two functions:

The first adds a Vertex with a set of properties, and returns a reference to the traversal operation

The second adds to that traversal operation.

For some reason, the first function's operations are getting persisted to the DB, but the second operations do not.  Why is this?

Here are the two functions:

def add_v(v_type, name):
    tmp_id = get_id(f"{v_type}-{name}")
    result = g.addV(v_type).property('id', tmp_id).property('name', name)
    result.iterate()
    return result

def process_records(features):
    for i in features:
        v_type = i[0]
        name = i[1]
        v = add_v(v_type, name)

        if len(i) > 2:
            %debug
            props = i[2]
            for r in props:
                v.property(r[0], r[1]).iterate()

```

答: Your add_V method has already iterated the traversal. If you want to return the traversal from add_v in a way that you can add to it remove the iterate.

Title: Vertex in Python Gremlin not updating


问:
ReplicaSet doesn't delete Replication Controller pods?
When I created a replicaset and a replication controller the replicaset didn't delete the replication controller's pods and I'm trying to understand why.

Context: I gave the replicaset matchLabels section the same labels as in the replication controller's labels section.

From my understanding replicaset ensures there is only a set amount of pods with the specified labels in the matchlabel section. When I create a pod on its own with the same labels the replicaset gets rid of that pod but it doesn't seem to delete the replication controller's pods. So I guess my question is does the replication controller keep its pods running or does the replicaset not interfere with replication controller pods?

答:
I think it is related to metadata.ownerReferences. As per Replicaset documentation:

A ReplicaSet is linked to its Pods via the Pods’
  metadata.ownerReferences field, which specifies what resource the
  current object is owned by. All Pods acquired by a ReplicaSet have
  their owning ReplicaSet’s identifying information within their
  ownerReferences field. It’s through this link that the ReplicaSet
  knows of the state of the Pods it is maintaining and plans
  accordingly.

A ReplicaSet identifies new Pods to acquire by using its selector. If
  there is a Pod that has no OwnerReference or the OwnerReference is not
  a Controller and it matches a ReplicaSet’s selector, it will be
  immediately acquired by said ReplicaSet.

Owners and dependents page also supply you with an example of how to use and control metadata.ownerReferences

I played with nginx..

1) rs.yaml

```<code>apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: nginx-set
  labels:
    app: nginx
spec:
  # modify replicas according to your case
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx
        ports:
        - containerPort: 80
</code>```

2) rc.yaml

```<code>apiVersion: v1
kind: ReplicationController
metadata:
  name: nginx
spec:
  replicas: 3
  selector:
    app: nginx
  template:
    metadata:
      name: nginx
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx
        ports:
        - containerPort: 80
</code>```

3) manually create pod: kubectl run nginx --image=nginx --labels="app=nginx". In case of such start pod has NO ownerReferences at all

Both RS and RC delete nginx pod, if I start it manually. They both rely on "app: nginx" label.

However you can deploy simultaneously  both RS and RC - they will not touch each other pods.

The key difference is their OwnerReference.

RS:

```<code>ownerReferences:
  - apiVersion: apps/v1
    blockOwnerDeletion: true
    controller: true
    kind: ReplicaSet
    name: nginx-set
</code>```

RC:

```<code>ownerReferences:
  - apiVersion: v1
    blockOwnerDeletion: true
    controller: true
    kind: ReplicationController
    name: nginx
</code>```

So suppose this is thats why rc and rs live in peace and not touching each other ))

Body:
I think it is related to metadata.ownerReferences. As per Replicaset documentation:

A ReplicaSet is linked to its Pods via the Pods’
  metadata.ownerReferences field, which specifies what resource the
  current object is owned by. All Pods acquired by a ReplicaSet have
  their owning ReplicaSet’s identifying information within their
  ownerReferences field. It’s through this link that the ReplicaSet
  knows of the state of the Pods it is maintaining and plans
  accordingly.

A ReplicaSet identifies new Pods to acquire by using its selector. If
  there is a Pod that has no OwnerReference or the OwnerReference is not
  a Controller and it matches a ReplicaSet’s selector, it will be
  immediately acquired by said ReplicaSet.

Owners and dependents page also supply you with an example of how to use and control metadata.ownerReferences

I played with nginx..

1) rs.yaml

apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: nginx-set
  labels:
    app: nginx
spec:
  # modify replicas according to your case
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx
        ports:
        - containerPort: 80

2) rc.yaml

apiVersion: v1
kind: ReplicationController
metadata:
  name: nginx
spec:
  replicas: 3
  selector:
    app: nginx
  template:
    metadata:
      name: nginx
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx
        ports:
        - containerPort: 80

3) manually create pod: kubectl run nginx --image=nginx --labels="app=nginx". In case of such start pod has NO ownerReferences at all

Both RS and RC delete nginx pod, if I start it manually. They both rely on "app: nginx" label.

However you can deploy simultaneously  both RS and RC - they will not touch each other pods.

The key difference is their OwnerReference.

RS:

ownerReferences:
  - apiVersion: apps/v1
    blockOwnerDeletion: true
    controller: true
    kind: ReplicaSet
    name: nginx-set

RC:

ownerReferences:
  - apiVersion: v1
    blockOwnerDeletion: true
    controller: true
    kind: ReplicationController
    name: nginx

So suppose this is thats why rc and rs live in peace and not touching each other ))


问:
Attach ggplot image to tweet through Twitter share widget in Shiny app
I have a Shiny app that includes a widget to share a tweet with some pre-loaded text. It appears on the app as a button that says "Tweet" that sends the text located in the data-text line of the tags$div section of the code. I'd like to be able to also include an image of the ggplot chart in the tweet that's created when people use the Shiny app online.

Is this even possible? I've seen suggestions that Twitter cards may be an option, but I'm not familiar with those or how I would get one to work in this tool.

Below is my minimal reprex. The app is hosted on ffevaluator.com/tools/draftevaluator if you want to see the app in its full form.

ui:

```<code>ui <- fluidPage(
    mainPanel(
      plotOutput("draftPlot"),
      tags$div(
        HTML("<div style='float:right'>
             <a href='https://twitter.com/share'
             class='twitter-share-button'
             align='middle'
             data-url='www.mywebsite.com'
             data-text='Insert text here!'
             data-size='large'>Tweet
             </a>
             <script>!function(d,s,id){
             var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';
             if(!d.getElementById(id)){
             js=d.createElement(s);
             js.id=id;
             js.src=p+'://platform.twitter.com/widgets.js';
             fjs.parentNode.insertBefore(js,fjs);
             }
             }(document, 'script', 'twitter-wjs');
             </script>
             </div>")
        )) )
</code>```

server:

```<code>server <- function(input, output) {

  output$draftPlot <- renderPlot({
    ggplot() +
      geom_smooth() +
      geom_point()
  })

}
</code>```

I also posted this on the RStudio Community website (post here: https://community.rstudio.com/t/attach-ggplot-image-to-tweet-through-twitter-share-widget-in-shiny-app/67867) but haven't gotten any responses yet.

答: There's no way for the Twitter web sharing popup (twitter.com/share) to include an image, unfortunately. The way a Twitter Card could work would be if you were sharing a link to a static web page in the Tweet text, and if that page had some markup which included the image, so that the image would be shown as a preview for the link. I'm not familiar with Shiny as to whether that is something that could work here.

Body:
I have a Shiny app that includes a widget to share a tweet with some pre-loaded text. It appears on the app as a button that says "Tweet" that sends the text located in the data-text line of the tags$div section of the code. I'd like to be able to also include an image of the ggplot chart in the tweet that's created when people use the Shiny app online.

Is this even possible? I've seen suggestions that Twitter cards may be an option, but I'm not familiar with those or how I would get one to work in this tool.

Below is my minimal reprex. The app is hosted on ffevaluator.com/tools/draftevaluator if you want to see the app in its full form.

ui:

ui <- fluidPage(
    mainPanel(
      plotOutput("draftPlot"),
      tags$div(
        HTML("

             Tweet

")
        )) )

server:

server <- function(input, output) {

  output$draftPlot <- renderPlot({
    ggplot() +
      geom_smooth() +
      geom_point()
  })

}

I also posted this on the RStudio Community website (post here: https://community.rstudio.com/t/attach-ggplot-image-to-tweet-through-twitter-share-widget-in-shiny-app/67867) but haven't gotten any responses yet.


问:
Android UE4 ERROR Missing precompiled manifest for 'SteamShared'
I've been building a game in c++ using the the Unreal Engine 4 platform. I've been using the following tools and plugins:

Unreal Engine v4.24.3

Steam Shared Module v1.0 plugin

Online Subsystem Steam v1.1 plugin

Steam VR v1.0 plugin

I am able to run the game locally and package it for windows. As soon as I try to launch it on my mobile phone or package it for android it throws the following error:

```<code>    LogPlayLevel:   Compiling Native code with NDK API 'android-19'
    LogPlayLevel: Error:   ERROR: Missing precompiled manifest for 'SteamShared'. This module was most likely not flagged for being included in a precompiled build - set 'PrecompileForTargets = PrecompileTargetsType.Any;' in SteamShared.build.cs to override.
    LogPlayLevel: Took 8.1195446s to run UnrealBuildTool.exe, ExitCode=5
</code>```

Note that this was working before implementing the above stated plugins.

I proceeded to modify my steam plugin within my engine directory to meet the errors request but it did not change anything after rebuilding as seen
here

I then looked into my logs and found the below stack trace:

```<code>AndroidPlatform.SetUpSpecificEnvironment: PLATFORM_ANDROID_NDK_VERSION = 140200
AndroidPlatform.SetUpSpecificEnvironment: NDK toolchain: r14b, NDK version: 19, GccVersion: 4.9, ClangVersion: 3.8.275480
UnrealBuildTool.Main: ERROR: Missing precompiled manifest for 'SteamShared'. This module was most likely not flagged for being included in a precompiled build - set 'PrecompileForTargets = PrecompileTargetsType.Any;' in SteamShared.build.cs to override.
UnrealBuildTool.Main: BuildException: Missing precompiled manifest for 'SteamShared'. This module was most likely not flagged for being included in a precompiled build - set 'PrecompileForTargets = PrecompileTargetsType.Any;' in SteamShared.build.cs to override.
UnrealBuildTool.Main:    at UnrealBuildTool.UEBuildModuleCPP.Compile(ReadOnlyTargetRules Target, UEToolChain ToolChain, CppCompileEnvironment BinaryCompileEnvironment, FileReference SingleFileToCompile, ISourceFileWorkingSet WorkingSet, TargetMakefile Makefile) in D:\Build\++UE4\Sync\Engine\Saved\CsTools\Engine\Source\Programs\UnrealBuildTool\Configuration\UEBuildModuleCPP.cs:line 277
UnrealBuildTool.Main:    at UnrealBuildTool.UEBuildBinary.SetupBinaryLinkEnvironment(ReadOnlyTargetRules Target, UEToolChain ToolChain, LinkEnvironment LinkEnvironment, CppCompileEnvironment CompileEnvironment, FileReference SingleFileToCompile, ISourceFileWorkingSet WorkingSet, DirectoryReference ExeDir, TargetMakefile Makefile) in D:\Build\++UE4\Sync\Engine\Saved\CsTools\Engine\Source\Programs\UnrealBuildTool\Configuration\UEBuildBinary.cs:line 708
UnrealBuildTool.Main:    at UnrealBuildTool.UEBuildBinary.Build(ReadOnlyTargetRules Target, UEToolChain ToolChain, CppCompileEnvironment CompileEnvironment, LinkEnvironment LinkEnvironment, FileReference SingleFileToCompile, ISourceFileWorkingSet WorkingSet, DirectoryReference ExeDir, TargetMakefile Makefile) in D:\Build\++UE4\Sync\Engine\Saved\CsTools\Engine\Source\Programs\UnrealBuildTool\Configuration\UEBuildBinary.cs:line 186
UnrealBuildTool.Main:    at UnrealBuildTool.UEBuildTarget.Build(BuildConfiguration BuildConfiguration, ISourceFileWorkingSet WorkingSet, Boolean bIsAssemblingBuild, FileReference SingleFileToCompile) in D:\Build\++UE4\Sync\Engine\Saved\CsTools\Engine\Source\Programs\UnrealBuildTool\Configuration\UEBuildTarget.cs:line 1697
UnrealBuildTool.Main:    at UnrealBuildTool.BuildMode.CreateMakefile(BuildConfiguration BuildConfiguration, TargetDescriptor TargetDescriptor, ISourceFileWorkingSet WorkingSet) in D:\Build\++UE4\Sync\Engine\Saved\CsTools\Engine\Source\Programs\UnrealBuildTool\Modes\BuildMode.cs:line 450
UnrealBuildTool.Main:    at UnrealBuildTool.BuildMode.Build(List`1 TargetDescriptors, BuildConfiguration BuildConfiguration, ISourceFileWorkingSet WorkingSet, BuildOptions Options, FileReference WriteOutdatedActionsFile) in D:\Build\++UE4\Sync\Engine\Saved\CsTools\Engine\Source\Programs\UnrealBuildTool\Modes\BuildMode.cs:line 220
UnrealBuildTool.Main:    at UnrealBuildTool.BuildMode.Execute(CommandLineArguments Arguments) in D:\Build\++UE4\Sync\Engine\Saved\CsTools\Engine\Source\Programs\UnrealBuildTool\Modes\BuildMode.cs:line 192
UnrealBuildTool.Main:    at UnrealBuildTool.UnrealBuildTool.Main(String[] ArgumentsArray) in D:\Build\++UE4\Sync\Engine\Saved\CsTools\Engine\Source\Programs\UnrealBuildTool\UnrealBuildTool.cs:line 517
Timeline.Print: Timeline:
Timeline.Print:
Timeline.Print: [ 0.000]
Timeline.Print: [ 0.000](+0.022) <unknown>
Timeline.Print: [ 0.022](+0.002) FileMetadataPrefetch.QueueEngineDirectory()
Timeline.Print: [ 0.025](+0.162) XmlConfig.ReadConfigFiles()
Timeline.Print: [ 0.187](+0.000) SingleInstanceMutex.Acquire()
Timeline.Print: [ 0.187](+0.145) UEBuildPlatform.RegisterPlatforms()
Timeline.Print:   0.188          [ 0.001](+0.079) Initializing InstalledPlatformInfo
Timeline.Print:   0.267          [ 0.080](+0.000) Querying types
Timeline.Print:   0.272          [ 0.085](+0.002) MacPlatformFactory
Timeline.Print:   0.275          [ 0.087](+0.000) TVOSPlatformFactory
Timeline.Print:   0.275          [ 0.087](+0.045) AndroidPlatformFactory
Timeline.Print:   0.320          [ 0.133](+0.000) HoloLensPlatformFactory
Timeline.Print:   0.321          [ 0.133](+0.004) IOSPlatformFactory
Timeline.Print:   0.325          [ 0.138](+0.003) LinuxPlatformFactory
Timeline.Print:   0.329          [ 0.142](+0.000) LuminPlatformFactory
Timeline.Print:   0.330          [ 0.142](+0.003) WindowsPlatformFactory
Timeline.Print: [ 0.333](+0.021) <unknown>
Timeline.Print: [ 0.355](+0.020) TargetDescriptor.ParseCommandLine()
Timeline.Print: [ 0.375](+0.022) <unknown>
Timeline.Print: [ 0.397](+0.636) UEBuildTarget.Create()
Timeline.Print:   0.401          [ 0.003](+0.203) RulesCompiler.CreateTargetRulesAssembly()
Timeline.Print:   0.401            0.003          [ 0.000](+0.093) <unknown>
Timeline.Print:   0.494            0.096          [ 0.093](+0.029) Finding engine modules
Timeline.Print:   0.523            0.126          [ 0.122](+0.012) Finding plugin modules
Timeline.Print:   0.536            0.138          [ 0.134](+0.058) <unknown>
Timeline.Print:   0.595            0.197          [ 0.193](+0.003) Finding program modules
Timeline.Print:   0.598            0.200          [ 0.196](+0.001) Finding program targets
Timeline.Print:   0.605          [ 0.207](+0.026) RulesAssembly.CreateTargetRules()
Timeline.Print:   0.632          [ 0.234](+0.023) <unknown>
Timeline.Print:   0.655          [ 0.257](+0.035) UEBuildTarget constructor
Timeline.Print:   0.662            0.264          [ 0.006](+0.027) Reading source file metadata cache
Timeline.Print:   0.690          [ 0.293](+0.343) UEBuildTarget.PreBuildSetup()
Timeline.Print: [ 1.038](+0.156) UEBuildTarget.Build()
Timeline.Print:   1.038          [ 0.000](+0.052) <unknown>
Timeline.Print:   1.090          [ 0.052](+0.035) ExternalExecution.SetupUObjectModules()
Timeline.Print:   1.125          [ 0.087](+0.024) <unknown>
Timeline.Print:   1.150          [ 0.111](+0.003) ExternalExecution.UpdateDirectoryTimestamps()
Timeline.Print:   1.167          [ 0.129](+0.026) UEBuildBinary.Build()
Timeline.Print: [ 1.194](+0.035) <unknown>
Timeline.Print: [ 1.229](+0.000) FileMetadataPrefetch.Stop()
Timeline.Print: [ 1.231]
</code>```

Also my main project build.cs file has these modules being used:

PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "HeadMountedDisplay", "UMG", "OnlineSubsystem", "OnlineSubsystemSteam" })

If anyone has ran into this issue or requires more information please let me know, I am stumped at the moment.

答: I also had this problem. I removed "OnlineSubsystem", "OnlineSubsystemUtils" from Build.cs</p>

Body:
I've been building a game in c++ using the the Unreal Engine 4 platform. I've been using the following tools and plugins:

Unreal Engine v4.24.3

Steam Shared Module v1.0 plugin

Online Subsystem Steam v1.1 plugin

Steam VR v1.0 plugin

I am able to run the game locally and package it for windows. As soon as I try to launch it on my mobile phone or package it for android it throws the following error:

    LogPlayLevel:   Compiling Native code with NDK API 'android-19'
    LogPlayLevel: Error:   ERROR: Missing precompiled manifest for 'SteamShared'. This module was most likely not flagged for being included in a precompiled build - set 'PrecompileForTargets = PrecompileTargetsType.Any;' in SteamShared.build.cs to override.
    LogPlayLevel: Took 8.1195446s to run UnrealBuildTool.exe, ExitCode=5

Note that this was working before implementing the above stated plugins.

I proceeded to modify my steam plugin within my engine directory to meet the errors request but it did not change anything after rebuilding as seen
here

I then looked into my logs and found the below stack trace:

AndroidPlatform.SetUpSpecificEnvironment: PLATFORM_ANDROID_NDK_VERSION = 140200
AndroidPlatform.SetUpSpecificEnvironment: NDK toolchain: r14b, NDK version: 19, GccVersion: 4.9, ClangVersion: 3.8.275480
UnrealBuildTool.Main: ERROR: Missing precompiled manifest for 'SteamShared'. This module was most likely not flagged for being included in a precompiled build - set 'PrecompileForTargets = PrecompileTargetsType.Any;' in SteamShared.build.cs to override.
UnrealBuildTool.Main: BuildException: Missing precompiled manifest for 'SteamShared'. This module was most likely not flagged for being included in a precompiled build - set 'PrecompileForTargets = PrecompileTargetsType.Any;' in SteamShared.build.cs to override.
UnrealBuildTool.Main:    at UnrealBuildTool.UEBuildModuleCPP.Compile(ReadOnlyTargetRules Target, UEToolChain ToolChain, CppCompileEnvironment BinaryCompileEnvironment, FileReference SingleFileToCompile, ISourceFileWorkingSet WorkingSet, TargetMakefile Makefile) in D:\Build\++UE4\Sync\Engine\Saved\CsTools\Engine\Source\Programs\UnrealBuildTool\Configuration\UEBuildModuleCPP.cs:line 277
UnrealBuildTool.Main:    at UnrealBuildTool.UEBuildBinary.SetupBinaryLinkEnvironment(ReadOnlyTargetRules Target, UEToolChain ToolChain, LinkEnvironment LinkEnvironment, CppCompileEnvironment CompileEnvironment, FileReference SingleFileToCompile, ISourceFileWorkingSet WorkingSet, DirectoryReference ExeDir, TargetMakefile Makefile) in D:\Build\++UE4\Sync\Engine\Saved\CsTools\Engine\Source\Programs\UnrealBuildTool\Configuration\UEBuildBinary.cs:line 708
UnrealBuildTool.Main:    at UnrealBuildTool.UEBuildBinary.Build(ReadOnlyTargetRules Target, UEToolChain ToolChain, CppCompileEnvironment CompileEnvironment, LinkEnvironment LinkEnvironment, FileReference SingleFileToCompile, ISourceFileWorkingSet WorkingSet, DirectoryReference ExeDir, TargetMakefile Makefile) in D:\Build\++UE4\Sync\Engine\Saved\CsTools\Engine\Source\Programs\UnrealBuildTool\Configuration\UEBuildBinary.cs:line 186
UnrealBuildTool.Main:    at UnrealBuildTool.UEBuildTarget.Build(BuildConfiguration BuildConfiguration, ISourceFileWorkingSet WorkingSet, Boolean bIsAssemblingBuild, FileReference SingleFileToCompile) in D:\Build\++UE4\Sync\Engine\Saved\CsTools\Engine\Source\Programs\UnrealBuildTool\Configuration\UEBuildTarget.cs:line 1697
UnrealBuildTool.Main:    at UnrealBuildTool.BuildMode.CreateMakefile(BuildConfiguration BuildConfiguration, TargetDescriptor TargetDescriptor, ISourceFileWorkingSet WorkingSet) in D:\Build\++UE4\Sync\Engine\Saved\CsTools\Engine\Source\Programs\UnrealBuildTool\Modes\BuildMode.cs:line 450
UnrealBuildTool.Main:    at UnrealBuildTool.BuildMode.Build(List`1 TargetDescriptors, BuildConfiguration BuildConfiguration, ISourceFileWorkingSet WorkingSet, BuildOptions Options, FileReference WriteOutdatedActionsFile) in D:\Build\++UE4\Sync\Engine\Saved\CsTools\Engine\Source\Programs\UnrealBuildTool\Modes\BuildMode.cs:line 220
UnrealBuildTool.Main:    at UnrealBuildTool.BuildMode.Execute(CommandLineArguments Arguments) in D:\Build\++UE4\Sync\Engine\Saved\CsTools\Engine\Source\Programs\UnrealBuildTool\Modes\BuildMode.cs:line 192
UnrealBuildTool.Main:    at UnrealBuildTool.UnrealBuildTool.Main(String[] ArgumentsArray) in D:\Build\++UE4\Sync\Engine\Saved\CsTools\Engine\Source\Programs\UnrealBuildTool\UnrealBuildTool.cs:line 517
Timeline.Print: Timeline:
Timeline.Print:
Timeline.Print: [ 0.000]
Timeline.Print: [ 0.000](+0.022) <unknown>
Timeline.Print: [ 0.022](+0.002) FileMetadataPrefetch.QueueEngineDirectory()
Timeline.Print: [ 0.025](+0.162) XmlConfig.ReadConfigFiles()
Timeline.Print: [ 0.187](+0.000) SingleInstanceMutex.Acquire()
Timeline.Print: [ 0.187](+0.145) UEBuildPlatform.RegisterPlatforms()
Timeline.Print:   0.188          [ 0.001](+0.079) Initializing InstalledPlatformInfo
Timeline.Print:   0.267          [ 0.080](+0.000) Querying types
Timeline.Print:   0.272          [ 0.085](+0.002) MacPlatformFactory
Timeline.Print:   0.275          [ 0.087](+0.000) TVOSPlatformFactory
Timeline.Print:   0.275          [ 0.087](+0.045) AndroidPlatformFactory
Timeline.Print:   0.320          [ 0.133](+0.000) HoloLensPlatformFactory
Timeline.Print:   0.321          [ 0.133](+0.004) IOSPlatformFactory
Timeline.Print:   0.325          [ 0.138](+0.003) LinuxPlatformFactory
Timeline.Print:   0.329          [ 0.142](+0.000) LuminPlatformFactory
Timeline.Print:   0.330          [ 0.142](+0.003) WindowsPlatformFactory
Timeline.Print: [ 0.333](+0.021) <unknown>
Timeline.Print: [ 0.355](+0.020) TargetDescriptor.ParseCommandLine()
Timeline.Print: [ 0.375](+0.022) <unknown>
Timeline.Print: [ 0.397](+0.636) UEBuildTarget.Create()
Timeline.Print:   0.401          [ 0.003](+0.203) RulesCompiler.CreateTargetRulesAssembly()
Timeline.Print:   0.401            0.003          [ 0.000](+0.093) <unknown>
Timeline.Print:   0.494            0.096          [ 0.093](+0.029) Finding engine modules
Timeline.Print:   0.523            0.126          [ 0.122](+0.012) Finding plugin modules
Timeline.Print:   0.536            0.138          [ 0.134](+0.058) <unknown>
Timeline.Print:   0.595            0.197          [ 0.193](+0.003) Finding program modules
Timeline.Print:   0.598            0.200          [ 0.196](+0.001) Finding program targets
Timeline.Print:   0.605          [ 0.207](+0.026) RulesAssembly.CreateTargetRules()
Timeline.Print:   0.632          [ 0.234](+0.023) <unknown>
Timeline.Print:   0.655          [ 0.257](+0.035) UEBuildTarget constructor
Timeline.Print:   0.662            0.264          [ 0.006](+0.027) Reading source file metadata cache
Timeline.Print:   0.690          [ 0.293](+0.343) UEBuildTarget.PreBuildSetup()
Timeline.Print: [ 1.038](+0.156) UEBuildTarget.Build()
Timeline.Print:   1.038          [ 0.000](+0.052) <unknown>
Timeline.Print:   1.090          [ 0.052](+0.035) ExternalExecution.SetupUObjectModules()
Timeline.Print:   1.125          [ 0.087](+0.024) <unknown>
Timeline.Print:   1.150          [ 0.111](+0.003) ExternalExecution.UpdateDirectoryTimestamps()
Timeline.Print:   1.167          [ 0.129](+0.026) UEBuildBinary.Build()
Timeline.Print: [ 1.194](+0.035) <unknown>
Timeline.Print: [ 1.229](+0.000) FileMetadataPrefetch.Stop()
Timeline.Print: [ 1.231]

Also my main project build.cs file has these modules being used:

PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "HeadMountedDisplay", "UMG", "OnlineSubsystem", "OnlineSubsystemSteam" })

If anyone has ran into this issue or requires more information please let me know, I am stumped at the moment.