text:
Q: Cannot create a object of Type 'ReactJsContext' In web Api My problem is when i run the migration command dotnet ef migration add --project pname i get this error
Unable to Create a object of type "Dbcontext"
i follow all solution that i found on google but this error does not fix.I doesnt find any solution to
My Dbcontext
namespace ReactJsNew.Data
{
    public class ReactJsContext : DbContext
    {
        public ReactJsContext(DbContextOptions<ReactJsContext> options)
               : base(options)
        {
        }

        public DbSet<Login> Logins { get; set; }
        public DbSet<Register> Registers { get; set; }
    }

}

This is my Program File
namespace ReactJsNew
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

This is my startup file
namespace ReactJsNew
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
            services.AddSignalR();

            services.AddCors(options =>
            {
                services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
           .AddJwtBearer(options => {
                    //options.SaveToken = true;
                    options.TokenValidationParameters = new TokenValidationParameters
               {
                   ValidateIssuer = true,
                   ValidateAudience = true,
                   ValidateLifetime = true,
                   ValidateIssuerSigningKey = true,
                   ValidIssuer = Configuration["Jwt:Issuer"],
                   ValidAudience = Configuration["Jwt:Audience"],
                   IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
               };
           });
                services.AddMvc();
                services.AddControllersWithViews();
                services.AddDbContext<ReactJsContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("ReactJsNew")));
                options.AddPolicy("ClientPermission", policy =>
                {
                    policy.AllowAnyHeader()
                        .AllowAnyMethod()
                        .WithOrigins("http://localhost:3000")
                        .AllowCredentials();
                });
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseCors("ClientPermission");

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub<ChatHub>("/hubs/chat");
            });
        }
    }
}

A: You can try to use below code. It should works for you.
namespace ReactJsNew.Data
{
    public class ReactJsContext : DbContext
    {
        // add this
        public ReactJsContext (){
        }

        public ReactJsContext(DbContextOptions<ReactJsContext> options)
               : base(options)
        {
        }

        public DbSet<Login> Logins { get; set; }
        public DbSet<Register> Registers { get; set; }
    }

}


text:
Q: Pandas: rolling count if within a loop In my data frame I want to create a column '5D_Peak' as a rolling max, and then another column with rolling count of historical data that's close to the peak. I wonder if there is an easier way to simply or ideally vectorise the calculation.
This is my codes in a plain but complicated way:
import numpy as np
import pandas as pd

df = pd.DataFrame([[1,2,4],[4,5,2],[3,5,8],[1,8,6],[5,2,8],[1,4,10],[3,5,9],[1,4,7],[1,4,6]], columns=list('ABC'))

df['5D_Peak']=df['C'].rolling(window=5,center=False).max()

for i in range(5,len(df.A)):
    val=0
    for j in range(i-5,i):
        if df.loc[j,'C']>df.loc[i,'5D_Peak']-2 and df.loc[j,'C']<df.loc[i,'5D_Peak']+2:
            val+=1
    df.loc[i,'5D_Close_to_Peak_Count']=val

This is the output I want:
   A  B   C  5D_Peak  5D_Close_to_Peak_Count
0  1  2   4      NaN                     NaN
1  4  5   2      NaN                     NaN
2  3  5   8      NaN                     NaN
3  1  8   6      NaN                     NaN
4  5  2   8      8.0                     NaN
5  1  4  10     10.0                     0.0
6  3  5   9     10.0                     1.0
7  1  4   7     10.0                     2.0
8  1  4   6     10.0                     2.0

A: I believe this is what you want.  You can set the two values below:
'''the window within which to search "close-to_peak" values'''
lkp_rng = 5

'''how close is close?'''
closeness_measure = 2

'''function to count the number of "close-to_peak" values in the lkp_rng'''
fc = lambda x: np.count_nonzero(np.where(x >= x.max()- closeness_measure))

'''apply fc to the coulmn you choose'''
df['5D_Close_to_Peak_Count'] = df['C'].rolling(window=lkp_range,center=False).apply(fc)
df.head(10)
        A   B   C   5D_Peak     5D_Close_to_Peak_Count
    0   1   2   4   NaN            NaN
    1   4   5   2   NaN            NaN
    2   3   5   8   NaN            NaN
    3   1   8   6   NaN            NaN
    4   5   2   8   8.0            3.0
    5   1   4   10  10.0           3.0
    6   3   5   9   10.0           3.0
    7   1   4   7   10.0           3.0
    8   1   4   6   10.0           2.0

I am guessing what you mean by "historical data".

redpajama_set_name: RedPajamaStackExchange


text:
Q: Zero predictions despite masking support for zero-padded mini batch LSTM training in keras Problem Statement
I'm training a many-to-many LSTM in keras with tensorflow backend (tf version 1.13.1) on tagged text sequences to predict the tag of each element in the sequence using pretrained GloVe embeddings. My training regime involves mini batch stochastic gradient descent, with each mini batch matrix zero-padded column-wise to ensure equal length input to the network.
Crucially, because of custom constrains on my mini batches due to the nature of the task and the data, I am not using the keras embedding layer. My goal is to implement a masking mechanism for my zero-padded cells to ensure the loss computation does not spuriously treat these cells as genuine data points.
Approach
As explained in the keras documentation, keras has three ways in which a masking layer can be set up:

*

*Configuring a keras.layers.Embedding layer with mask_zero
set to True.

*Adding a keras.layers.Masking layer;

*Passing a mask argument manually when calling recurrent layers.

Because I am not using an embedding layer to encode my data for training, option (1) with a masked embedding layer is not available to me. So instead, I chose (2) and added a masking layer right after initializing my model. This change, however, does not seem to have had an effect. In fact, not only has the accuracy of my model not improved, at the prediction stage the model still generates zero predictions. Why does my masking layer not mask zero-padded cells? Could it have to do with the fact that in my dense layer I'm specifying 3 classes rather than 2 (thus including 0 as a separate class)?
Limitations of Existing Resources
Similar questions have been asked and answered, but I wasn't able to use them to resolve my issue. While this post received no direct response, a linked post mentioned in a comment focuses on how to preprocess data to assign mask value, which is uncontroversial here. The masking layer initializtion, however, is identical to the one used here. This post mentions the same problem - a masking layer has no effect on performance - and the answer defines the masking layer in the same way as I do, but again focuses on converting specific values to mask values. Finally, the answer in this post provides the same layer initialization without elaborating further.
Toy Data Generation
To reproduce my problem, I have generated a toy 10-batch dataset with two classes (1,2). A batch is a variable-length sequence post-padded with zeros to a maximum length of 20 embeddings, with each embedding vector consisting of 5 cells, so input_shape=(20,5). Embedding values for the two classes were generated from different but partially-overlapping truncated normal distributions to create a learnable but not trivial problem for the network. I've included the toy data below so you can reproduce the problem.
import pandas as pd
from keras.models import Sequential
from keras.layers import LSTM, Dense, TimeDistributed, Bidirectional, Dropout, Masking
from keras import optimizers

# *** model initialization ***

model = Sequential()
model.add(Masking(mask_value=0., input_shape=(20, 5))) # <- masking layer here
model.add(Bidirectional(LSTM(20, return_sequences=True), input_shape=(20, 5)))
model.add(Dropout(0.2))
model.add(TimeDistributed(Dense(3, activation='sigmoid')))

sgd = optimizers.SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='sparse_categorical_crossentropy', optimizer=sgd, metrics=['mse'])

# *** model training ***

for epoch in range(10):

    for X,y in data_train:

        X = X.reshape(1, 20, 5)
        y = y.reshape(1, 20, 1)

        history = model.fit(X, y, epochs=1, batch_size=20, verbose=0)

# *** model prediction ***

preds = pd.DataFrame(columns=['true', 'pred'])

for index, (X,y) in enumerate(data_test):
    X = X.reshape(1, 20, 5)
    y = y.reshape(1, 20, 1)

    y_pred = model.predict_classes(X, verbose=0)

    df = pd.DataFrame(columns=['true', 'pred'])

    df['true'] = [y[0, i][0] for i in range(20)]
    df['pred'] = [y_pred[0, i] for i in range(20)]

    preds = preds.append(df, ignore_index=True)

# convert true labels to int & drop padded rows (where y_true=0)
preds['true'] = [int(label) for label in preds['true']]
preds = preds[preds['true']!=0]

This is the summary of the model with masking:
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
masking_2 (Masking)          (None, 20, 5)             0
_________________________________________________________________
bidirectional_4 (Bidirection (None, 20, 40)            4160
_________________________________________________________________
dropout_4 (Dropout)          (None, 20, 40)            0
_________________________________________________________________
time_distributed_4 (TimeDist (None, 20, 3)             123
=================================================================
Total params: 4,283
Trainable params: 4,283
Non-trainable params: 0

I trained one model with and one without the masking layer and calculated accuracy using:
np.round(sum(preds['true']==preds['pred'])/len(preds)*100,1)

I got 53.3% accuracy for the model without masking and 33.3% for the model with masking. More surprisingly, I kept on getting zero as a predicted label in both models. Why does the masking layer fail to ignore zero-padded cells?

Data for reproducing issue:
data_train = list(zip(X_batches_train, y_batches_train))
data_test = list(zip(X_batches_test, y_batches_test))

X_batches_train
[array([[-1.00612917,  1.47313952,  2.68021318,  1.54875809,  0.98385996,
          1.49465265,  0.60429106,  1.12396908, -0.24041602,  1.77266187,
          0.1961381 ,  1.28019637,  1.78803092,  2.05151245,  0.93606708,
          0.51554755,  0.        ,  0.        ,  0.        ,  0.        ],
        [-0.97596563,  2.04536053,  0.88367922,  1.013342  , -0.16605355,
          3.02994344,  2.04080806, -0.25153046, -0.5964068 ,  2.9607247 ,
         -0.49722121,  0.02734492,  2.16949987,  2.77367066,  0.15628842,
          2.19823207,  0.        ,  0.        ,  0.        ,  0.        ],
        [ 0.31546283,  3.27420503,  3.23550769, -0.63724013,  0.89150128,
          0.69774266,  2.76627308, -0.58408384, -0.45681779,  1.98843041,
         -0.31850477,  0.83729882,  0.45471165,  3.61974147, -1.45610756,
          1.35217453,  0.        ,  0.        ,  0.        ,  0.        ],
        [ 1.03329532,  1.97471646,  1.33949611,  1.22857243, -1.46890642,
          1.74105506,  1.40969261,  0.52465603, -0.18895266,  2.81025597,
          2.64901037, -0.83415186,  0.76956826,  1.48730868, -0.16190164,
          2.24389007,  0.        ,  0.        ,  0.        ,  0.        ],
        [-1.0676654 ,  3.08429323,  1.7601179 ,  0.85448051,  1.15537064,
          2.82487842,  0.27891413,  0.57842569, -0.62392063,  1.00343057,
          1.15348843, -0.37650332,  3.37355345,  2.22285473,  0.43444434,
          0.15743873,  0.        ,  0.        ,  0.        ,  0.        ]]),
 array([[ 1.05258873, -0.17897376, -0.99932932, -1.02854121,  0.85159208,
          2.32349131,  1.96526709, -0.08398597, -0.69474809,  1.32820222,
          1.19514151,  1.56814867,  0.86013263,  1.48342922,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
        [ 0.1920635 , -0.48702788,  1.24353985, -1.3864121 ,  0.16713229,
          3.10134683,  0.61658271, -0.63360643,  0.86000807,  2.74876157,
          2.87604877,  0.16339724,  2.87595396,  3.2846962 ,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
        [ 0.1380241 , -0.76783029,  0.18814436, -1.18165209, -0.02981728,
          1.49908113,  0.61521007, -0.98191097,  0.31250199,  1.39015803,
          3.16213211, -0.70891214,  3.83881766,  1.92683533,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
        [ 1.39080778, -0.59179216,  0.80348201,  0.64638205, -1.40144268,
          1.49751413,  3.0092166 ,  1.33099666,  1.43714841,  2.90734268,
          3.09688943,  0.32934884,  1.14592787,  1.58152023,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
        [-0.77164353,  0.50293096,  0.0717377 ,  0.14487556, -0.90246591,
          2.32612179,  1.98628857,  1.29683166, -0.12399569,  2.60184685,
          3.20136653,  0.44056647,  0.98283455,  1.79026663,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ]]),
 array([[-0.93359914,  2.31840281,  0.55691601,  1.90930758, -1.58260431,
         -1.05801881,  3.28012523,  3.84105406, -1.2127093 ,  0.00490079,
          1.28149304,  0.        ,  0.        ,  0.        ,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
        [-1.03105486,  2.7703693 ,  0.16751813,  1.12127987, -0.44070271,
         -0.0789227 ,  2.79008301,  1.11456745,  1.13982551, -1.10128658,
          0.87430834,  0.        ,  0.        ,  0.        ,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
        [-0.69710668,  1.72702833, -2.62599502,  2.34730002,  0.77756661,
          0.16415884,  3.30712178,  1.67331828, -0.44022431,  0.56837829,
          1.1566811 ,  0.        ,  0.        ,  0.        ,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
        [-0.71845983,  1.79908544,  0.37385522,  1.3870915 , -1.48823234,
         -1.487419  ,  3.0879945 ,  1.74617784, -0.91538815, -0.24244522,
          0.81393954,  0.        ,  0.        ,  0.        ,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
        [-1.38501563,  3.73330047, -0.52494265,  2.37133716, -0.24546709,
         -0.28360782,  2.89384717,  2.42891743,  0.40144022, -1.21850571,
          2.00370751,  0.        ,  0.        ,  0.        ,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ]]),
 array([[ 1.27989188,  1.16254538, -0.06889142,  1.84133355,  1.3234908 ,
          1.29611702,  2.0019294 , -0.03220116,  1.1085194 ,  1.96495985,
          1.68544302,  1.94503544,  0.        ,  0.        ,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
        [ 1.3004439 ,  2.48768923,  0.59809607,  2.38155155,  2.78705889,
          1.67018683,  0.21731778, -0.59277191,  2.87427207,  2.63950475,
          2.39211459,  0.93083423,  0.        ,  0.        ,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
        [ 2.39239371,  0.30900383, -0.97307155,  1.98100711,  0.30613735,
          1.12827171,  0.16987791,  0.31959096,  1.30366416,  1.45881023,
          2.45668401,  0.5218711 ,  0.        ,  0.        ,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
        [ 0.0826574 ,  2.05100254,  0.013161  ,  2.95120798,  1.15730011,
          0.75537024,  0.13708569, -0.44922143,  0.64834001,  2.50640862,
          2.00349347,  3.35573624,  0.        ,  0.        ,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
        [ 0.47135124,  2.10258532,  0.70212032,  2.56063126,  1.62466971,
          2.64026892,  0.21309489, -0.57752813,  2.21335957,  0.20453233,
          0.03106993,  3.01167822,  0.        ,  0.        ,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ]]),
 array([[-0.42125521,  0.54016939,  1.63016057,  2.01555253, -0.10961255,
         -0.42549555,  1.55793753, -0.0998756 ,  0.36417335,  3.37126414,
          1.62151191,  2.84084192,  0.10831384,  0.89293054, -0.08671363,
          0.49340353,  0.        ,  0.        ,  0.        ,  0.        ],
        [-0.37615411,  2.00581062,  2.30426605,  2.02205839,  0.65871664,
          1.34478836, -0.55379752, -1.42787727,  0.59732227,  0.84969282,
          0.54345723,  0.95849568, -0.17131602, -0.70425277, -0.5337757 ,
          1.78207229,  0.        ,  0.        ,  0.        ,  0.        ],
        [-0.13863276,  1.71490034,  2.02677925,  2.60608619,  0.26916522,
          0.35928298, -1.26521844, -0.59859219,  1.19162219,  1.64565259,
          1.16787165,  2.95245196,  0.48681084,  1.66621053,  0.918077  ,
         -1.10583747,  0.        ,  0.        ,  0.        ,  0.        ],
        [ 0.87763797,  2.38740754,  2.9111822 ,  2.21184069,  0.78091173,
         -0.53270909,  0.40100338, -0.83375593,  0.9860009 ,  2.43898437,
         -0.64499989,  2.95092003, -1.52360727,  0.44640918,  0.78131922,
         -0.24401283,  0.        ,  0.        ,  0.        ,  0.        ],
        [ 0.92615066,  3.45437746,  3.28808981,  2.87207404, -1.60027223,
         -1.14164941, -1.63807699,  0.33084805,  2.92963629,  3.51170824,
         -0.3286093 ,  2.19108385,  0.97812366, -1.82565766, -0.34034678,
         -2.0485913 ,  0.        ,  0.        ,  0.        ,  0.        ]]),
 array([[ 1.96438618e+00,  1.88104784e-01,  1.61114494e+00,
          6.99567690e-04,  2.55271963e+00,  0.00000000e+00,
          0.00000000e+00,  0.00000000e+00,  0.00000000e+00,
          0.00000000e+00,  0.00000000e+00,  0.00000000e+00,
          0.00000000e+00,  0.00000000e+00,  0.00000000e+00,
          0.00000000e+00,  0.00000000e+00,  0.00000000e+00,
          0.00000000e+00,  0.00000000e+00],
        [ 2.41578815e+00, -5.70625661e-01,  2.15545894e+00,
         -1.80948908e+00,  1.62049331e+00,  0.00000000e+00,
          0.00000000e+00,  0.00000000e+00,  0.00000000e+00,
          0.00000000e+00,  0.00000000e+00,  0.00000000e+00,
          0.00000000e+00,  0.00000000e+00,  0.00000000e+00,
          0.00000000e+00,  0.00000000e+00,  0.00000000e+00,
          0.00000000e+00,  0.00000000e+00],
        [ 1.97017040e+00, -1.62556528e+00,  2.49469152e+00,
          4.18785985e-02,  2.61875866e+00,  0.00000000e+00,
          0.00000000e+00,  0.00000000e+00,  0.00000000e+00,
          0.00000000e+00,  0.00000000e+00,  0.00000000e+00,
          0.00000000e+00,  0.00000000e+00,  0.00000000e+00,
          0.00000000e+00,  0.00000000e+00,  0.00000000e+00,
          0.00000000e+00,  0.00000000e+00],
        [ 3.14277819e+00,  3.01098398e-02,  7.40376369e-01,
          1.76517344e+00,  2.68922918e+00,  0.00000000e+00,
          0.00000000e+00,  0.00000000e+00,  0.00000000e+00,
          0.00000000e+00,  0.00000000e+00,  0.00000000e+00,
          0.00000000e+00,  0.00000000e+00,  0.00000000e+00,
          0.00000000e+00,  0.00000000e+00,  0.00000000e+00,
          0.00000000e+00,  0.00000000e+00],
        [ 2.06250296e+00,  4.67605528e-01,  1.55927230e+00,
          1.85788889e-01,  1.30359922e+00,  0.00000000e+00,
          0.00000000e+00,  0.00000000e+00,  0.00000000e+00,
          0.00000000e+00,  0.00000000e+00,  0.00000000e+00,
          0.00000000e+00,  0.00000000e+00,  0.00000000e+00,
          0.00000000e+00,  0.00000000e+00,  0.00000000e+00,
          0.00000000e+00,  0.00000000e+00]]),
 array([[ 1.22152427,  3.74926839,  0.64415552,  2.35268329,  1.98754653,
          2.89384829,  0.44589817,  3.94228743,  2.72405657,  0.86222004,
          0.68681903,  3.89952458,  1.43454512,  0.        ,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
        [-0.02203262,  0.95065123,  0.71669023,  0.02919391,  2.30714524,
          1.91843002,  0.73611294,  1.20560482,  0.85206836, -0.74221506,
         -0.72886308,  2.39872927, -0.95841402,  0.        ,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
        [ 0.55775319,  0.33773314,  0.79932151,  1.94966883,  3.2113281 ,
          2.70768249, -0.69745554,  1.23208345,  1.66199957,  1.69894081,
          0.13124461,  1.93256147, -0.17787952,  0.        ,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
        [ 0.45089205,  2.62430534, -1.9517961 ,  2.24040577,  1.75642049,
          1.94962325,  0.26796497,  2.28418304,  1.44944487,  0.28723885,
         -0.81081633,  1.54840214,  0.82652939,  0.        ,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
        [ 1.27678173,  1.17204606, -0.24738322,  1.02761617,  1.81060444,
          2.37830861,  0.55260134,  2.50046334,  1.04652821,  0.03467176,
         -2.07336654,  1.2628897 ,  0.61604732,  0.        ,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ]]),
 array([[ 3.86138405,  2.35068317, -1.90187438,  0.600788  ,  0.18011722,
          1.3469559 , -0.54708828,  1.83798823, -0.01957845,  2.88713217,
          3.1724991 ,  2.90802072,  0.        ,  0.        ,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
        [ 1.26785642,  0.51076756,  0.32070756,  2.33758816,  2.08146669,
         -0.60796736,  0.93777509,  2.70474711,  0.44785738,  1.61720609,
          1.52890594,  3.03072971,  0.        ,  0.        ,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
        [ 3.30219394,  3.1515445 ,  1.16550716,  2.07489374,  0.66441859,
          0.97529244,  0.35176367,  1.22593639, -1.80698271,  1.19936482,
          3.34017172,  2.15960657,  0.        ,  0.        ,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
        [ 2.34839018,  2.24827352, -1.61070856,  2.81044265, -1.21423372,
          0.24633846, -0.82196609,  2.28616568,  0.033922  ,  2.7557593 ,
          1.16178372,  3.66959512,  0.        ,  0.        ,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
        [ 1.32913219,  1.63231852,  0.58642744,  1.55873546,  0.86354741,
          2.06654246, -0.44036504,  3.22723595,  1.33279468,  0.05975892,
          2.48518999,  3.44690602,  0.        ,  0.        ,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ]]),
 array([[ 0.61424344, -1.03068819, -1.47929328,  2.91514641,  2.06867196,
          1.90384921, -0.45835234,  1.22054782,  0.67931536,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
        [ 2.76480464,  1.12442631, -2.36004758,  2.91912726,  1.67891181,
          3.76873596, -0.93874096, -0.32397781, -0.55732374,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
        [ 0.39953353, -1.26828104,  0.44482517,  2.85604975,  3.08891062,
          2.60268725, -0.15785176,  1.58549879, -0.32948578,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
        [ 1.65156484, -1.56545168, -1.42771206,  2.74216475,  1.8758154 ,
          3.51169147,  0.18353058, -0.14704149,  0.00442783,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
        [ 1.27736372,  0.37407608, -1.25713475,  0.53171176,  1.53714914,
          0.21015523, -1.06850669, -0.09755327, -0.92373834,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ]]),
 array([[-1.39160433,  0.21014669, -0.89792475,  2.6702794 ,  1.54610601,
          0.84699037,  2.96726482,  1.84236946,  0.02211578,  0.32842575,
          1.02718924,  1.78447936, -1.20056829,  2.26699318, -0.23156537,
          2.50124959,  1.93372501,  0.10264369, -1.70813962,  0.        ],
        [ 0.38823591, -1.30348049, -0.31599117,  2.60044143,  2.32929389,
          1.40348483,  3.25758736,  1.92210728, -0.34150988, -1.22336921,
          2.3567069 ,  1.75456835,  0.28295694,  0.68114898, -0.457843  ,
          1.83372069,  2.10177851, -0.26664178, -0.26549595,  0.        ],
        [ 0.08540346,  0.71507504,  1.78164285,  3.04418137,  1.52975256,
          3.55159169,  3.21396003,  3.22720346,  0.68147142,  0.12466013,
         -0.4122895 ,  1.97986653,  1.51671949,  2.06096825, -0.6765908 ,
          2.00145086,  1.73723014,  0.50186043, -2.27525744,  0.        ],
        [ 0.00632717,  0.3050794 , -0.33167875,  1.48109172,  0.19653696,
          1.97504239,  2.51595821,  1.74499313, -1.65198805, -1.04424953,
         -0.23786945,  1.18639347, -0.03568057,  3.82541131,  2.84039446,
          2.88325909,  1.79827675, -0.80230291,  0.08165052,  0.        ],
        [ 0.89980086,  0.34690991, -0.60806566,  1.69472308,  1.38043417,
          0.97139487,  0.21977176,  1.01340944, -1.69946943, -0.01775586,
         -0.35851919,  1.81115864,  1.15105661,  1.21410373,  1.50667558,
          1.70155313,  3.1410754 , -0.54806167, -0.51879299,  0.        ]])]

y_batches_train
[array([1., 2., 2., 1., 1., 2., 2., 1., 1., 2., 1., 1., 2., 2., 1., 2., 0.,
        0., 0., 0.]),
 array([1., 1., 1., 1., 1., 2., 2., 1., 1., 2., 2., 1., 2., 2., 0., 0., 0.,
        0., 0., 0.]),
 array([1., 2., 1., 2., 1., 1., 2., 2., 1., 1., 2., 0., 0., 0., 0., 0., 0.,
        0., 0., 0.]),
 array([2., 2., 1., 2., 2., 2., 1., 1., 2., 2., 2., 2., 0., 0., 0., 0., 0.,
        0., 0., 0.]),
 array([1., 2., 2., 2., 1., 1., 1., 1., 2., 2., 1., 2., 1., 1., 1., 1., 0.,
        0., 0., 0.]),
 array([2., 1., 2., 1., 2., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0.]),
 array([1., 2., 1., 2., 2., 2., 1., 2., 2., 1., 1., 2., 1., 0., 0., 0., 0.,
        0., 0., 0.]),
 array([2., 2., 1., 2., 1., 1., 1., 2., 1., 2., 2., 2., 0., 0., 0., 0., 0.,
        0., 0., 0.]),
 array([2., 1., 1., 2., 2., 2., 1., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0.]),
 array([1., 1., 1., 2., 2., 2., 2., 2., 1., 1., 1., 2., 1., 2., 1., 2., 2.,
        1., 1., 0.])]

X_batches_test
[array([[ 0.74119496,  1.97273418,  1.76675805,  0.51484268,  1.39422086,
          2.97184667, -1.35274514,  2.08825434, -1.2521965 ,  1.11556387,
          0.19776789,  2.38259223, -0.57140597, -0.79010112,  0.17038974,
          1.28075761,  0.696398  ,  3.0920007 , -0.41138503,  0.        ],
        [-1.39081797,  0.41079718,  3.03698894, -2.07333633,  2.05575621,
          2.73222939, -0.98182787,  1.06741172, -1.36310914,  0.20174856,
          0.35323654,  2.70305775,  0.52549713, -0.7786237 ,  1.80857093,
          0.96830907, -0.23610863,  1.28160768,  0.7026651 ,  0.        ],
        [ 1.16357113,  0.43907935,  3.40158623, -0.73923043,  1.484668  ,
          1.52809569, -0.02347205,  1.65349967,  1.79635118, -0.46647772,
         -0.78400883,  0.82695404, -1.34932627, -0.3200281 ,  2.84417045,
          0.01534261,  0.10047148,  2.70769609, -1.42669461,  0.        ],
        [-1.05475682,  3.45578027,  1.58589338, -0.55515227,  2.13477478,
          1.86777473,  0.61550335,  1.05781415, -0.45297406, -0.04317595,
         -0.15255388,  0.74669395, -1.43621979,  1.06229278,  0.99792794,
          1.24391783, -1.86484584,  1.92802343,  0.56148011,  0.        ],
        [-0.0835337 ,  1.89593955,  1.65769335, -0.93622246,  1.05002869,
          1.49675624, -0.00821712,  1.71541053,  2.02408452,  0.59011484,
          0.72719784,  3.44801858, -0.00957537,  0.37176007,  1.93481168,
          2.23125062,  1.67910471,  2.80923862,  0.34516993,  0.        ]]),
 array([[ 0.40691415,  2.31873444, -0.83458005, -0.17018249, -0.39177831,
          1.90353251,  2.98241467,  0.32808584,  3.09429553,  2.27183083,
          3.09576659,  0.        ,  0.        ,  0.        ,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
        [ 1.6862473 ,  1.0690102 , -0.07415598, -0.09846767,  1.14562424,
          2.52211963,  1.71911351,  0.41879894,  1.62787544,  3.50533394,
          2.69963456,  0.        ,  0.        ,  0.        ,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
        [ 3.27824216,  2.25067953,  0.40017321, -1.36011162, -1.41010106,
          0.98956203,  2.30881584, -0.29496046,  2.29748247,  3.24940966,
          1.06431776,  0.        ,  0.        ,  0.        ,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
        [ 2.80167214,  3.88324559, -0.6984172 ,  0.81889567,  1.86945352,
          3.07554419,  3.10357189,  1.31426767,  0.28163147,  2.75559628,
          2.00866885,  0.        ,  0.        ,  0.        ,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
        [ 1.54574419,  1.00720596, -1.55418837,  0.70823839,  0.14715209,
          1.03747262,  0.82988672, -0.54006372,  1.4960777 ,  0.34578788,
          1.10558132,  0.        ,  0.        ,  0.        ,  0.        ,
          0.        ,  0.        ,  0.        ,  0.        ,  0.        ]])]

y_batches_test
[array([1., 2., 2., 1., 2., 2., 1., 2., 1., 1., 1., 2., 1., 1., 2., 2., 1.,
        2., 1., 0.]),
 array([2., 2., 1., 1., 1., 2., 2., 1., 2., 2., 2., 0., 0., 0., 0., 0., 0.,
        0., 0., 0.])]

A: First problem: your X data after reshaping is not what you expected. If you look at the first sample after reshaping, it is:
array([[[-1.00612917,  1.47313952,  2.68021318,  1.54875809,
          0.98385996],
        [ 1.49465265,  0.60429106,  1.12396908, -0.24041602,
          1.77266187],
        [ 0.1961381 ,  1.28019637,  1.78803092,  2.05151245,
          0.93606708],
        [ 0.51554755,  0.        ,  0.        ,  0.        ,
          0.        ],
        [-0.97596563,  2.04536053,  0.88367922,  1.013342  ,
         -0.16605355],
        [ 3.02994344,  2.04080806, -0.25153046, -0.5964068 ,
          2.9607247 ],
        [-0.49722121,  0.02734492,  2.16949987,  2.77367066,
          0.15628842],
        [ 2.19823207,  0.        ,  0.        ,  0.        ,
          0.        ],
        [ 0.31546283,  3.27420503,  3.23550769, -0.63724013,
          0.89150128],
        [ 0.69774266,  2.76627308, -0.58408384, -0.45681779,
          1.98843041],
        [-0.31850477,  0.83729882,  0.45471165,  3.61974147,
         -1.45610756],
        [ 1.35217453,  0.        ,  0.        ,  0.        ,
          0.        ],
        [ 1.03329532,  1.97471646,  1.33949611,  1.22857243,
         -1.46890642],
        [ 1.74105506,  1.40969261,  0.52465603, -0.18895266,
          2.81025597],
        [ 2.64901037, -0.83415186,  0.76956826,  1.48730868,
         -0.16190164],
        [ 2.24389007,  0.        ,  0.        ,  0.        ,
          0.        ],
        [-1.0676654 ,  3.08429323,  1.7601179 ,  0.85448051,
          1.15537064],
        [ 2.82487842,  0.27891413,  0.57842569, -0.62392063,
          1.00343057],
        [ 1.15348843, -0.37650332,  3.37355345,  2.22285473,
          0.43444434],
        [ 0.15743873,  0.        ,  0.        ,  0.        ,
          0.        ]]])

So actually no timestep is masked, because Masking layer only mask timesteps where all features are 0, so the above 20 timesteps are not masked because none of them are completely 0.
For the Masking layer, to ensure you have the mask propogated to the output layer successfully, you can do:
for i, l in enumerate(model.layers):
    print(f'layer {i}: {l}')
    print(f'has input mask: {l.input_mask}')
    print(f'has output mask: {l.output_mask}')

layer 0: <tensorflow.python.keras.layers.core.Masking object at 0x6417b7f60>
has input mask: None
has output mask: Tensor("masking/Identity_1:0", shape=(None, 20), dtype=bool)
layer 1: <tensorflow.python.keras.layers.wrappers.Bidirectional object at 0x641e25cf8>
has input mask: Tensor("masking/Identity_1:0", shape=(None, 20), dtype=bool)
has output mask: Tensor("masking/Identity_1:0", shape=(None, 20), dtype=bool)
layer 2: <tensorflow.python.keras.layers.core.Dropout object at 0x641814128>
has input mask: Tensor("masking/Identity_1:0", shape=(None, 20), dtype=bool)
has output mask: Tensor("masking/Identity_1:0", shape=(None, 20), dtype=bool)
layer 3: <tensorflow.python.keras.layers.wrappers.TimeDistributed object at 0x6433b6ba8>
has input mask: Tensor("masking/Identity_1:0", shape=(None, 20), dtype=bool)
has output mask: Tensor("time_distributed/Reshape_3:0", shape=(None, 20), dtype=bool)

So you can see that the final layer also has the output_mask, which means the masks are successfully propogated. You seem to have a misunderstanding of how Masking works in Keras, what it actually does is it will generate a mask, which is a boolean array, the shape of the mask is (None, Timesteps), since in your model definition, the Timestep dimension is always kept the same, so the mask will be propogated to the end without any changes. Then when Keras calculate loss (and of course when it calculate gradients), the timesteps which has a mask value False will be ignored. The Masking layer doesn't change the output value and of course your model will still predict class 0, what it only does is to produce a boolean array indicating which timestep should be skipped and pass it to the end (if all the layers accept the mask).
So what you can do is change one line of your model definition as follows and make your y_labels shifted by 1, which means your current classes:
0 -> 0 (since the loss of these timesteps will be ignored, not contributing to the training of the model, so whether it is 0 or 1 doesn't matter)
1 -> 0
2 -> 1
# I would prefer softmax if doing classification
# here we only need to specify 2 classes
# and actually TimeDistributed can be thrown away (at least in recent Keras versions)
model.add(TimeDistributed(Dense(2, activation='softmax')))

You can also see my answer here https://stackoverflow.com/a/59313862/11819266 for understanding how the loss are calculated with / without masking.


text:
Q: Solaris 10 new disk discovering I'm having issues with a Solaris 10 SPARC host... It seems not able to discover newly provisioned disks. The disks are fed through a QLogic 2300 FC HBA.
I've tried cfgadm -al/cfgadm -f -c configure c0 + cfgadm -f -c configure c1, devfsadm -Cv as suggested by Google results, but these commands didn't seem to work...
Does anyone know any other way for Solaris 10 to scan/rescan for newly added FC disks?

A: I talked to QLogic customer support and their Level 2 engineers suggest doing
/opt/QLogic_Corporation/drvutil/qla2300/qlreconfig -d qla2300

or use their ioctl tool to perform a rescan on the HBA.
I tried both and found doing a rescan using the ioctl tool didn't work very well, but the qlreconfig always worked. What qlreconfig does is basically to unload and reload the driver HBA. Therefore, it is disruptive…
As suggested in the command path, this solution is only tested with qla2300 driver. Other QLogic HBA models may not have this issue, but I haven't got a chance to confirm that. If the directory "/opt/QLogic_Corporation" cannot be found, the system may be using the HBA driver shipped with Solaris. You would have to install the driver provided by QLogic to use the utility.


text:
Q: TFS release managment test result view fails with JSON error I have a TFS (on premises version 15.105.25910.0) server with build and release management definitions. One of the definitions deploys a web site, the test assemblies and then runs my MSTest based Selenium tests. Most pass, some are not run, and a few fail.
When I attempt to view the test results in the TFS web portal the view of "failed" test results fails and it shows the following error message:

can't run your query: bad json escape sequence: \p. path
  'build.branchname', line 1, position 182.

Can anyone explain how this fault arises? or more to the point what steps I might take to either diagnose this further or correct the fault
The troublesome environment and its "Run Functional Tests" task are shown below

Attempted diagnostics
As suggested by Patrick-MSFT I added the requisite three steps to a build (the one that makes the selenium tests)

*

*Windows machine file copy (Copy MStest assembly containing selenium test to c:\tests on a test machine)

*Visualstudio test agent deploy (to same machine)

*Run functional tests (the assembly shipped in 1)

The test run (and have the same mix of pass fail, skipped) but the test results can be browsed just fine with the web pages test links.

Results after hammering the same test into a different environment to see how that behaves...
Well, same 3 steps (targeting the same test machine) in a different environment works as expected - same mix of results, but view shows results without errors.
To be clear this is a different (pre-existing) environment in the same release definition, targeting the same test PC. It would seem the issue is somehow tied to that specific environment. So how do I fix that then?
So next step, clone the failing environment and see what happens. Back later with the results.

A: Try to run the test with same settings in build definition instead of release. This could narrow down if the issue is  related to your tests or task configuration.
Double check you have use the right settings of related tasks. You could refer related tutorial for Selenium test in MSDN: Get started with Selenium testing in a continuous integration pipeline
Try to run the same release in another environment.
Also go through your log files to see if there are some related info for troubleshooting.


text:
Q: How do computers calculate the log of a value? I'm not sure if this question belongs on StackOverflow or here (please let me know if the former, and i'll delete this and ask there), but I was wondering how the log or ln of a value is calculated computationally with accuracy? Is some series implemented that approximates a value?
I looked into the Taylor series for the natural logarithm, but that is apparently only accurate for 0 < x < 2, and I can't find anything else. I tried looking for source code for Java's Math#log function as well to see what algorithm they implemented, but couldn't find any since it's implemented in a native language rather than in Java.

A: If the computer stores a floating point number as $a \times 2^b$ for $1 \le a \lt 2$ and $b$ an integer then $\log_e (a \times 2^b) = \log_e (a) +  b \times \log_e(2)$.
For example you can use the Taylor series for  $\log_e (1+x)$ to find $\log_e (a)$ and can store $\log_e(2)$ as a constant.


text:
Q: IOS CGContextSelectFont and CGContextShowText deprecated what to use now In iOS7 CGContextSelectFont and CGContextShowText is deprecated. Deprecation message says that I have to use Core Text, but I don't know which is the exact equivalent of this piece of code:
- (void)drawTextInContext:(CGContextRef)context
{
    CGContextSelectFont(context, [self.font.fontName cStringUsingEncoding:[NSString defaultCStringEncoding]], self.font.pointSize, kCGEncodingMacRoman);

    CGRect textRect = [self textRectForBounds:self.bounds limitedToNumberOfLines:1];
    CGContextSetTextPosition(context, textRect.origin.x, textRect.origin.y + 5.0f);

    CGContextShowText(context, [self.text cStringUsingEncoding:[NSString defaultCStringEncoding]], strlen([self.text cStringUsingEncoding:[NSString defaultCStringEncoding]]));
}

A: An equivalent replacement : AttributedString
[txtString drawAtPoint:CGPointMake(x, y)
           withAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"OpenSans"                                                               size:12.0]
                            }];


text:
Q: How do I open a "custom" command prompt in Windows? I have a flash drive with subversion, python, php and notepad++ on it along with several of my ongoing projects. I do this to be able to resume work on any PC with an internet connection. Currently I have a .bat file that sets up the necessary paths as well as setting the current directory to my projects folder. I run this .bat file by opening a commend prompt and drag&dropping it in.
Here is what I'd prefer: Opening the .bat file would open the configured command prompt and stay open.
Alternatively my flash drive could contain a shortcut to c:/Windows/System32/cmd.exe with the bat file as an argument (if that is possible)
Any way this could be done would be helpful and timesaving

A: End the .bat file with:
cmd

or
%COMSPEC%

A: Command Prompt Portable from Portable Apps might be what you are looking for.

Features
Command Prompt Portable is a simple utility that allows you to have a
  custom command line setup on any Windows computer you come across. It
  has built in support for the command line interpreters on both Windows
  95/98/Me and Windows 2000/XP/Vista as well as the ability to customize
  using simple DOS commands by editing the .bat file within
  CommandPromptPortable\Data\batch after you've run it once. You can
  customize the prompt, colors, window title, columns and more. A basic
  batch file is included with some simple settings.
You can also pass in paths you'd like the command prompt to start in
  by starting CommandPromptPortable.exe with a command line parameter of
  the path (Windows 2000 and up only). Advanced users can enable
  auto-complete by following the directions within the
  Other\Source\readme.txt file.
Helpful Tip: Launch a command prompt with your own portable command
  line tools in the path by adding SET PATH=%~d0\UtilsDirectory;%PATH%
  to the batch file and placing your tools in X:\UtilsDirectory

A: Open notepad and enter:
command.com

Then save it as anything.bat. Open it and use cmd.


text:
Q: How to debug a IE8 client-side issues for a website? One of my website's users is experiencing Javascript problems with his IE8/WinXP setup, with code execution apparently aborting halfway through, but there are no alert boxes or other hints as to why and I'm unable to replicate the problem locally.  How can I get any information out of his system, so I can start debugging this?
Just figuring out where the code aborts would be very helpful, but AFAIK IE8 doesn't have anything like Firefox's Error Console that just logs warnings.  I know IE8 has Developer Tools built-in, but is it of any use if the user is not a developer?
The following question suggests logging in remotely to the client's system, but I'm not sure this will be possible to arrange.
How to remotely debug customer issues with a website

A: The user can turn on Javascript logging in IE8, if they are tech-savvy enough. (It's not hard, but we all know how good users normally are with computers...):
Get them to go to Internet Options -> Advanced. There is a "Display a notification about every script error" option, which should be checked. This should now cause all Javascript errors to be logged - you can view them, iirc, by clicking on a yellow warning triangle which will appear on websites where there is broken Javascript (aka, almost every website in the world...). The user could then copy this information to you.
It does rely on the user being fairly tech-savvy - you really just want to get at their machine tbh.

A: IE7/IE8 has an addon named developer tools and its real good (comparable to FireBug for FireFox) and you can do all debug, watch etc for your javascript on clientside.
See a similar (duplicate?) post on SO: Firebug alternative for the IE

A: IE 8 dev tools are rather handy, but I don't think they would be of any help to a non-developer... You could potentially ask him to install them, start the debugger, and have it break on all errors. But even that is likely too technical for a non developer. Also you'd be stuck asking him to describe exactly where and how the error was occurring.
Getting physical or remote access to his machine would be the best option. Also ensure you have explicit instructions to reproduce the error, just in case you're missing something locally.
One final option would be to add logging into your javascript to catch and record errors, perhaps they would give you some clues.

A: You can still ask the person to open the developer tools, go to the scripts tag and start debugging. Even he doesn't know what it means you might get helpful information when some code gets hit by an exception.
In the past we usually went to that client to help him/her out.
Most of the times it turned out to be that some script didn't get loaded properly or not in time.


text:
Q: How to generate data with given correlation, one distribution counting intergers, the other normal? I would like to do a Monte Carlo simulation related to this post: How to predict the degree to which an extraneous variable will attenuate a correlation?
I need to generate a dataset with a Pearson r of .25 between order of grading a test and the test grade.  One variable will have integer numbers as values (in my case, the counting numbers between 1 and 150.) The other variable will be continuous and preferably normal.
In other words, I would like to create a dataset with a new variable with a specified correlation with the counting numbers 1, 2, 3 ... 150.


text:
Q: Переделать регулярное-выражения Нужно удалить запятые только внутри кавычек "". Есть файл с множеством строк такого типа (First Name,Last Name,Company,"Head of Product Development, Casino",Email,Phone Numbers,Notes,Tags) Есть регулярное-выражение но там удаляется все что в кавычках "[^"]*"

A: Вы можете использовать своё регулярное выражение в скрипте PythonScript, где совпадение можно дополнительно обработать в лямбда-выражении.

*

*Установите PythonScript

*Щёлкните Плагины -> Python Script -> New Script

*Создайте файл comma_removal.py

*Добавьте в файл строку

editor.rereplace(r'"[^"]+"', lambda x: x.group().replace(",", ""))

Теперь можно запускать скрипт из меню Плагины -> Python Script -> Scripts -> comma_removal


text:
Q: don't know why my cursorForObjectInConnection returns null? I am having this error on response:

Cannot return null for non-nullable field TodoEdge.cursor.

This is my mutation code:
  mutateAndGetPayload: async ({text}, context) => {
      let newTodo = new TodoModel({ text, _creatorUserId: context.user._id });
      await newTodo.save();
      return {newTodo};
  },
  outputFields: {
    todoEdge: {
      type: GraphQLTodoEdge,
      resolve: async ({newTodo}, args,context) => {
        const todos = await getTodosByUserContext(context.user._id, 'any');
        console.log("cursorForObjectInConnection = ",cursorForObjectInConnection(todos, newTodo)) // this logs null?
        return {
          cursor: cursorForObjectInConnection(todos, newTodo),
          node: newTodo,
        };
      },
    },

todos and newTodo is retreived from mongoose database. I think I am following this relevant todo-modern sample properly. Help?

A: Let's try following:
1) Get todos from your DB like
const todos = await Todo.find({});

You can get todos for a specific user as per your Todo Schema. Todo.find({ userid: context.user._id});
2) once you get your todos then get cursor:
const cursor = offsetToCursor(todos.length);

This worked for me. Give it a try.


text:
Q: Differential Equation $y'''-3y''=x^2-1$ $y'''-3y''=x^2-1$
I'm not sure how to solve this. I tried to use the method of undetermined coefficients but the third derivative of $(x^2)-1$ is $0$. Can that be correct?

A: Put $y''=v$ then try to solve it.

A: As Saheb alluded to in his answer, that differential equation is nothing more than a first-order equation in $y''$, so you can treat $y''$ as a regular function, solve for it, and the find the second antiderivative of the answer you get by doing that; that will be $y$.

A: $$y'''-3y''=x^2-1 \implies R^3-3R^2=R^2(R-3)=0 \implies R=0,3$$
$$y_H=c_1e^{3x}+c_2+c_3x$$
For the particular solution you need a polynomial of degree at least 4
$$y_P=Bx^4+Cx^3+Dx^2$$

Or just integrate directly
$$y'''-3y''=x^2-1 $$
$$y''-3y'=\frac {x^3}3-x+K_1 $$
Integrate again
$$y'-3y=\frac {x^4} {12}-\frac {x^2}2+K_1x+K_2 $$
Simple first ode now...

Or consider it as first order if you substitute $y''=z$
$$y'''-3y''=x^2-1$$
$$z'-3z=x^2-1$$
$e^{-3x}$ as integrating factor
$$(ze^{-3x})'=(x^2-1)e^{-3x}$$
Integrate
$$ze^{-3x}=\int(x^2-1)e^{-3x}dx=\frac{e^{-3x}}3+\int x^2e^{-3x}dx$$
$$y''=\frac 13+e^{3x}\int x^2e^{-3x}dx$$
$$y''=\frac 13-\frac {x^2}{3}+\frac {2e^{3x}}3\int xe^{-3x}dx$$
$$y''=-\frac {x^2}{3}-\frac {2x}9+\frac 7{27}+K_1e^{3x}$$
Integrate twice to get the final solution
$$y'=-\frac {x^3}{9}-\frac {x^2}{9}+\frac {7x}{27}++K_1e^{3x}+K_2$$
$$\boxed{y=-\frac {x^4}{36}-\frac {x^3}{27}+\frac {7x^2}{54}+K_1e^{3x}+K_2x+K_3}$$

A: According to undetermined coefficient, the characteristics equation is
$$r^3-3r^2=0$$
$$r^2(r-3)-0$$
so the roots are
$$x_0=0$$
$$x_1=0$$
$$x_2=3$$
the complementary solution is
$$y_c=c_0+c_1x+c_2e^{3x}$$
the particular solution
$$y_p=Ax^2+Bx+C\rightarrow Ax^4+Bx^3+Cx^2$$
then you can complete the solution


text:
Q: How can I send multi response data using Netty? I want to return multiple response data to a client on a server using Netty(4.1.51).
According to our specifications, the first response data is in the format of HttpHeader and body, abd the second and subsequent data must return just byte array or string data.
I'm coding the follow code, but I'm executing the flush() method in channelContext, but it's not received on the client side.
Our client program can receive it by ChannelFuture.CLOSE i.e. channel is close, but we can still receive only the first data.
What am I missing ? Or is it wrong?
Server side
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup)
     .channel(NioServerSocketChannel.class)
     .childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("codec", new HttpServerCodec());
            ch.pipeline().addLast("decode", new HttpRequestDecoder());
            ch.pipeline().addLast("aggregator", new HttpObjectAggregator(Short.MAX_VALUE));
            ch.pipeline().addLast(new ChannelHandler());
            ch.pipeline().addLast("encode", new HttpResponseEncoder());
            //    :

public class ChannelHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
    public void channelRead(ChannelContext chlCtx, Object msg) {
        byte[] firstData = new byte[1024];
        byte[] secondData = new byte[1024];
        //    :
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
        HttpResponseStatus.OK, Unpooled.copiedBuffer(firstData));
        //    :
        chlCtx.write(response);
        chlCtx.flush();
        ChannelFuture lastFuture = chlCtx.writeAndFlush(Unpooled.copiedBuffer(secondData));
        // Client program is no received data.
        //    :
        lastFuture.addListener(ChannelFutureListener.CLOSE);
        // Client program is received only first data.
        //    :

}
### Client side ###

    Socket chl = new Socket();
    //    :
    in = new BufferedReader(new InputStreamReader(chl.getInputStream()));
    while (true){
        while ((recv = in.readLine()) != null) {
            System.out.println(recv);
        }
        if (recv.substring(0,4).equals("LAST"){
            break;
        }
    }


text:
Q: windows phone 8 map not displaying in user control I want to implement an 'attach location' feature in my application.
I've decided to create a user control and put my map in it, then upon a certain button click I show this control in a full screen popup/custom message box.
The problem is that everything works fine except that the map is simply not being displayed; I can retrieve my location, put pushpins, zooming seems working(despite the fact that I'm not seeing anything!).
Whats more weird is that the same code copied and pasted to a phone application page works fine and map appears. I don't understand, is this a limitation that I don't know of?
Here's my code:
    <UserControl
       .....
        xmlns:maps="clr-namespace:Microsoft.Phone.Controls.Maps;assembly=Microsoft.Phone.Controls.Maps"
        mc:Ignorable="d"
     ....
    >
<Grid x:Name="LayoutRoot" Background="Black">

        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <maps:Map Mode="AerialWithLabels"
                    Grid.Row="0"
                    Height="300"
                    HorizontalAlignment="Left"
                    Name="map1" VerticalAlignment="Top"
                    Width="460" Margin="-12,0,0,0">
            </maps:Map>
            <Button Content="share location"
                    Name="btn_SendLocation"
                    IsEnabled="False"
                    Grid.Row="1"
                    Click="Button_Click_1"/>
            <ListBox Grid.Row="2"
                     Name="lst_NearBy"
                     DataContext="{Binding Location}"
                     Tap="lst_NearBy_Tap">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Margin="0,5">
                            <TextBlock Text="{Binding mName}" Style="{StaticResource PhoneTextLargeStyle}"/>
                            <TextBlock Text="{Binding mVicinity}" Margin="10,0,0,0" Foreground="Gray"/>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </Grid>
    </Grid>

A: Did you try adding the map programatically?
private Constructor()
{
    Map my_map = new Map();
    my_map.Name= "map1";
    my_map.mode = "AerialWithLabels";
    my_map.Height = 300;
    my_map.Margin = new Thickness(-12,0,0,0);
    my_map.VerticalAlignment = System.Windows.VerticalAlignment.Top;
    my_map.HorizontalAlignment= System.Windows.HorizontalAlignment.Left;
    ContentPanel.Children.Add(my_map);
}


text: Q: Диалоговое окно для выбора файла потока ввода Написал простой векторный редактор и сохранение изображения идет в текстовый документ. Как сделать чтобы при нажатии на соответствующую кнопку открывалось диалоговое окно которое позволяло бы выбрать файл для открытия (точнее чтобы этот файл был потоком ввода ifstream)


text:
Q: java regex find but not include in group Consider this simple example:
String myPattern= "\\[(\"(.+[^\"])\",\\s*){1,3}(\"(.+[^\"])\")\\]";
final Pattern compile1 = Pattern.compile(myPattern);
final Matcher matcher = compile1.matcher(myString);

I have two groups in matcher for this "((.+[^\"])\",\s*){1,3}":
((.+[^\"])\",\s*)

and
(.+[^\"])

But I want only one group - (.+[^\"]). How do I enclose in brackets the expression for {1,3} to evaluate so that it is not included into groups?
I tried using square brackets, but it did not work. I am really fed up with this issue and finally decided to ask, since I often have to do
matcher.getGroup(1);
matcher.getGroup(3);

A: Use non-capturing group (?: ) i.e (?:yourregex)
It means match but dont include in capture group.


text:
Q: using windows event viewer to log from net core console application I have c# net core 3.1 console app.
How to get log messages to windows event viewer?
Now I have this, and it not work...
            services.AddLogging(configure => configure.AddFilter<EventLogLoggerProvider>(level => level >= LogLevel.Warning))
                .Configure<LoggerFilterOptions>(options => options.MinLevel = LogLevel.Warning)
                .AddTransient<Program>();
...
            _serviceProvider = services.BuildServiceProvider(true);

If I try to use configure.AddConsole() instead configure.AddFilter<EventLogLoggerProvider> It work perfectly and give me a log data in Console window.
Thank you!


text:
Q: How to check if python module exists and can be imported I am using debug toolbar with django and would like to add it to project if two conditions are true:

*

*settings.DEBUG is True

*module itself exists

It's not hard to do the first one
# adding django debug toolbar
if DEBUG:
    MIDDLEWARE_CLASSES += 'debug_toolbar.middleware.DebugToolbarMiddleware',
    INSTALLED_APPS += 'debug_toolbar',

But how do I check if module exists?
I have found this solution:
try:
    import debug_toolbar
except ImportError:
    pass

But since import happens somewhere else in django, I need if/else logic to check if module exists, so I can check it in settings.py
def module_exists(module_name):
    # ??????

# adding django debug toolbar
if DEBUG and module_exists('debug_toolbar'):
    MIDDLEWARE_CLASSES += 'debug_toolbar.middleware.DebugToolbarMiddleware',
    INSTALLED_APPS += 'debug_toolbar',

Is there a way to do it?

A: You can use the same logic inside your function:
def module_exists(module_name):
    try:
        __import__(module_name)
    except ImportError:
        return False
    else:
        return True

There is no performance penalty to this solution because modules are imported only once.


text:
Q: targeting mysqli assoc array indivdual values easily How should I be doing this? $id1 returns the first character of the value, I also tried $id1 = $row[0]['id']; but that didn't seem to return anything.
$sql = "SELECT id,postid FROM table WHERE postid='$postid' LIMIT 3";
$query = mysqli_query($db_conx, $sql);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$id1 = $row['id'][0];
$postid1 = $row['postidx'][0];
$id2 = $row['id'][1];
$postid2 = $row['postid'][1];
$id2 = $row['id'][2];
$postid2 = $row['postid'][2];
}

A: You have to understand the concept of loops.
Your code works not the way you think. You will get your subsequent rows as the loop iterates. So you need to get only current row values within the loop, and use them accordingly
$sql = "SELECT id,postid FROM table WHERE postid='$postid' LIMIT 3";
$query = mysqli_query($db_conx, $sql);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
    $id = $row['id'];
    $postid = $row['postid'];
    // use these two variables
}


text:
Q: Using javascript to replace the html content I am trying to replace the content of id='js' with javascript, but this is not working for me. here is the code.

       <title></title>

Result Here

A: Because the element is not initialized yet, it's not working.  You can either move the javascript to the end of the HTML (preferred) as shown below:

   <title></title>

Result Here

Or you can use jquery document.ready to achieve the same thing.


text:
Q: I'm trying to set the base price of an item to $3 but it's messing with the rest of my math (java) So right now everything works fine so long as the volume of the item(p1v and p2v) is greater than 1 but I can't figure out a way for the console to print the base price of $3 if the volume is less than 1.  For reference the cost of an item starts at $3 for the first unit of volume or part thereof then increases by $1 for each additional unit.
public void calculateCost() {

        NumberFormat currency = NumberFormat.getCurrencyInstance();

        if (p1v < 1) {
            double cost = 3;
            System.out.printf("%nPackage 1 will cost " + currency.format(cost) + " to ship.");
        }

        if (p2v < 1) {
            double cost2 = 3;
            System.out.printf("%nPackage 1 will cost " + currency.format(cost2) + " to ship.");
        }

        if (p1v < 1 && p2v < 1) {

        double cost = 3 + p1v - 1;
        String message = "Package 1 will cost " + currency.format(cost) + " to ship.";
        System.out.printf("%n" + message);

        double cost2 = 3 + p2v - 1;
        String message2 = "Package 2 will cost " + currency.format(cost2) + " to ship.";
        System.out.printf("%n" + message2);

        if (cost >= 5 * cost2) {
            System.out.printf("%nThe first package is " + cost / cost2 + "times the cost of the second package.");
        } else if (cost2 >= 5 * cost) {
            System.out.printf("%nThe second package is " + cost2 / cost + "times the cost of the first package.");
        } else if (cost == cost2) {
            System.out.printf("%nThe first package is the same cost as the second package.");
        } else if (cost < 5 * cost2 && cost >= 4 * cost2) {
            System.out.printf("%nThe first package is quadruple the cost of the second package.");
        } else if (cost2 < 5 * cost && cost2 >= 4 * cost) {
            System.out.printf("%nThe second package is quadruple more than the cost of the first package.");
        } else if (cost < 4 * cost2 && cost >= 3 * cost2) {
            System.out.printf("%nThe first package is triple the cost of the first package.");
        } else if (cost2 < 4 * cost && cost2 >= 3 * cost) {
            System.out.printf("%nThe second package is triple the cost of the second package.");
        } else if (cost < 3 * cost2 && cost >= 2 * cost2) {
            System.out.printf("%nThe first package is twice the cost of the first package.");
        } else if (cost2 < 3 * cost && cost2 >= 2 * cost) {
            System.out.printf("%nThe second package is twice the cost of the second package.");
        } else if (cost < 2 * cost2) {
            System.out.printf("%nThe second package is slightly more than the cost of the first package.");
        } else if (cost2 < 2 * cost) {
            System.out.printf("%nThe first package is slightly more than the cost of the second package.");
        }

    }

}


text:
Q: How to get values from JSP and redirect to appropriate JSP in springwebflows? I am new to spring webflows.I need to get text field value from jsp.and depending on text value need to redirect to appropriate jsp.I am unable to get the jsp value in webflow xml always showing blank "" value.
<input type="text" name="depositAmt"/>

through script using href am sending deposit amount value to webflow.xml
<input name="depositAmt" value="form.depositAmt"/>
<actionstate expression="form.getDepositAmt()>
<transition on="" to="payment">
<transition on-exception="" to="summary">
</actionstate>

A: There are a couple of ways you can achieve your goal. Either using a decision state to parse the text param and map the value to a predefined view, action, or end state. Or from the UI you can use javascript to change the eventId value passed in the URL based on the values inputted by the user.
Moreover, your syntax is filled with errors. If you were going to use a decision-state It should be
    <!-- <input name="depositAmt" value="form.depositAmt"/> You would only use the input tag for HTTP GET params -->

    <decision-state id="depositAmtCondition">
         <on-entry>
              <set name="depositAmt" value="expression="form.getDepositAmt()">
         </on entry>

         <if test="depositAmt.equals('someVal')" then="processForm" else="someOtherState" />

</decision-state>

    <action-state id="processForm">

        <transition on="someEvent" to="payment">           <!-- the 'on' attribute needs to be the eventId value passed in the HTTP GET URL params -->
        <transition on-exception="my.package.some.ClassException" to="summary">
    </action-state>

...

Also see this explanation for further explanation of how SWF works:
How to include a pop-up dialog box in subflow
Also for debugging purposes I recommend using logging like this:
Printing log from flow.xml


text:
Q: Не могу распарсить JSON Хочу распарсить Json от Yandex Geocoder для получения адреса по координатам, но не могу. Что я делаю не так?
public void OnClick(View view) {

    Gson gson = new Gson();

    response SourceJs = gson.fromJson(source,response.class);

    Toast.makeText(getApplicationContext(), (CharSequence) SourceJs[1], Toast.LENGTH_LONG).show();
class response {
    List<GeoObjectCollection>  GeoObjectCollection;
}

class GeoObjectCollection {
    List<featureMember> featureMember;
}

class  featureMember {
    List<GeoObject> GeoObject;
}

class  GeoObject {
    String name;
}

Сам Json

A: Я посмотрел ваш json ответ от сервера, там только один элемент response передается, зачем вы пытаетесь считать результат в массив Result[]? Считывать нужно Result, а не Result[].
И еще, приложите описание класса Result, возможно в нем есть ошибка.


text:
Q: How much extra time is needed to add unit test in a development task? My team is considering moving to test-driven development. Currently we have almost no unit testing, we have been only relying on the user acceptance test, and developer's own manual test. Not everyone have agreed with this proposal. In the team, no one really has an experience on unit testing, so it's hard to convince everyone the benefit of doing it. One of the objection is the time needed.
My question is, how much extra time is usually needed to add unit test, relative to the task itself? Let's say if the coding of a task (excluding acceptance test) takes half a day, how much time will the unit test take, in average? This estimation is important for us to explain the relative benefit of doing unit test, and to adjust our planning.
If it matters, we are mostly working with .NET desktop application (with a GUI and a database), and it is not safety-critical (I mean, it's not for a nuclear power plant or stuff like that). Also note that none of us have experience, so there will be a learning curve

A: It's difficult to provide a definitive answer without better understanding the development processes that you usually use, the experience of your team, and more importantly, the complexity of the tasks at hand. To this I should also probably add the way in which you generally write your methods and the design choices you have made.
Unit testing always adds time to the development, and if you are testing your code properly, then you should be spending more time writing tests than implementation code. This sounds quite horrendous at first and is probably one of the main reasons why many choose to avoid unit testing in the first place.  Even in my present workplace, it took me more than 4 years to convince everybody that their concerns over testing overheads were only as a result of not fully understanding the longer term benefits.
In the shorter term, and particularly when you first start unit testing, you find that your development time slows down considerably. This is a necessary learning period.  You'll find most developers will be selective about where they apply unit tests, or will write their code first, and apply tests after the implementation is essentially complete.  In doing so, they will find bugs, which will require a change in the implementation code, requiring a subsequent change in the tests.  This will prove to be a very counter-productive process, and will make most developers wonder why they bother if they are always playing catch-up with the tests. The real epiphany will come when your developers start to code complete tests before writing the implementation code, because the resulting code will most likely be more concise, and will be much quicker to write.
An advantage of the test first approach is in the fact that the test will indicate the implementation code works at the exact moment that the code is written to satisfy the conditions of the test.  Further, if the implementation code has been kept relatively concise it will likely be easier to modify with the tests, providing you with the real advantage of testing first, which is the assurance of a system that will identify the exact moment when the code has been modified to include an error. Modifications to code are much easier with supporting tests already in place, which significantly reduce your maintenance overheads and make debugging efforts much less onerous.
When you are very comfortable with unit testing and test first, then you will find that your estimates for tasks will become easier to make, and won't be messed up by lengthy and unexpected delays caused by bugs and the subsequently difficult to estimate debugging effort, as you will find that the majority of your potential bugs will have been dealt with simply by focusing your development efforts around testing. Where you may have previously found yourself dealing with a lengthy debugging process during the user acceptance testing period, you should in future find the post-implementation debugging phase, and user acceptance tests taking much less time.
So the real issue then becomes less about how much additional time testing adds, and more about a trade-off between the longer time to implement verses the shorter post implementation time spent debugging and maintaining your product, and also about how your test suite will benefit you when it comes time to change any part of your code base. More importantly, how all of this translates into a real and measurable value to your business.  As a very rough example of what I am talking about, when my team first started seriously writing unit tests, I took some measurements relating to bug issues and time to develop modules for our product, and I added in a comparison between the amount of time working on new developments versus maintenance issues.  Before test first unit testing, our maintenance efforts were triple the development efforts, whereas on those projects where we had moved entirely to unit testing first (and after a few months of experience), our effort expended on new development work is greater than the effort expended on maintenance. This amounts to a measurable saving with a real dollar value attached.  It means that the team has been able to take on more work without needing to expend more cash and juggle resources.
How this will exactly translate into your own working environment is difficult to predict specifically, and I can only recommend having a couple of people act as method champions and work in a test-first manner for a while to get a real feel for how it will fit within you working environment. One suggestion would be to do a little experimental development.  Have a couple of people work on a couple of similar tasks (or duplicating the same task if you can afford to allocate the time) for a short while and see what the difference is in terms of time to implement vs time to debug after completion, and conduct code reviews to examine code quality issues as each task progresses. Give it a little time, and see whether your teams objections diminish or become stronger.
Personally, I can't think of any real reasons why you shouldn't be unit testing, however I don't work in your particular environment so I can't really speak for you, and at the end of the day unit testing is merely a practice. It's a tool that if used well can provide you with great results, yet if the entire team is unable to use the tool, or if the use of a tool results in a pattern of failures within a team, then perhaps that tool isn't right for you. The only way you can know for certain is to try it and see for yourselves.

A: My experience has been that unit tests don't add much time; they save implementation time, in fact. If you write your code to be testable, you tend to write clearer, more modular code that you feel more confident is correct. You also end up with tests that prove correctness in the cases you've tested and demonstrate how you intend your methods to be called.
You stated that no one on your team has a lot of tesing experience yet. There will be some ramp up time before everyone feels confident in the tools and what makes a good test. On the team I work with, it took about two months before all of us fully understood how to split code down into testable chunks. The biggest challenge we had was learning to leave seams in our classes so that external dependencies, like database managers, could be injected for testing. The results were well worth it though - we ended up with a clear pattern of keeping database connection details separate from the code requiring them. Should we ever need to change our DB scheme, we've been able to limit the affected areas down to a single layer. Not only that, but all references to the DB can be found quickly using our IDE.


text:
Q: Different models of Distributed Architecture I just want to know different models to implement/design a distributed architecture.
I know some of the technologies in this field like

*

*RPC

*Java RMI & Socket

*.Net Remoting & Socket

*XML-RPC

*SOAP based web service

*HTTP based web application

*REST ful web service
But there are lot more technologies that I know, but what are different models to implement distributed architecture?

A: At an architecture level there are 4 ways to integrate systems:

*

*Shared Database

*Message Queue

*Request Response Call

*Message Transfer

Within each one there are many technologies that are available

A: We can categorize architectures into 6 different types from one of videos of Neal Ford; Mark Richards

*

*Traditional layered architecture like Model View Controller (Spring MVC etc)

*Event driven architecture using Messaging API, where an event has been dispatched to Queue/Topics & subscribers/receivers consume the events so that different components are loosely coupled

*Service oriented architecture, very lengthy to explain but you can find lot of info from google

*Pipe line (or filter) architecture - A message will be flown from producer to consumer through transformer and transformer modifies the message depending on business need

*Micro kernel architecture ( plug and play) - It will have one core system, common to multiple components & specific components (plug-in module) ,which can be plugged in on need basis

*Space based architecture - The architecture is scalable by adding more resources to it (it is best suitable if you are using non relational database like NoSQL database)

A: You really should start with requirements, they have major impact on architecture.

*

*Single machine / multiple / multiple and geo-reduntant ?

*Shared / private memory / mix ?

*Synchronous / asynchronous communication / both ?

*Fault tolerance ? Recovery ?

*Scalability ? Transactions ?

*Large data / computationally intensive ?

Please add further questions I'm sure I forgot something important.


text:
Q: POST JSON string with PHP and CURL to a php page and get response I'm trying to learn how to POST a PHP through CURL to another PHP page and read the response.
I have 2 pages.  The first is test.php
<?php
$array['User'] = array();
$array['User']['AppId'] = 'sdfgfd9-sdfgsdf-sdfgfdgfgff';
$array['User']['UserName'] = 'me@example.co.uk';
$array['User']['Token'] = 'fsdgf5-455g-223ee-bggg-asdsadsda';
$array['User']['Timestamp'] = '2018-05-30BST16:28:293600';

$url = "https://www.myurl.co.uk/api/index.php";
$content = json_encode($array['User']);

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);

$json_response = curl_exec($curl);

$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ( $status != 201 )
{
   die("Error: call to URL $url failed with status $status, response
  $json_response, curl_error " . curl_error($curl) . ", curl_errno " .
  curl_errno($curl));
}

curl_close($curl);

$response = json_decode($json_response, true);
echo $response;
?>

Then on the page I'm getting data from I simply have;
<?php
$userArray = array();
$userArray = trim(file_get_contents("php://input"));
echo json_decode($userArray, true);
?>

When I run the script on test.php the repsonse I'm getting is;
Error: call to URL https://www.myurl.co.uk/api/index.php failed with status 200, response Array, curl_error , curl_errno 0

I don't understand the error enough to understand what to change to make this work?

A: try:
curl_setopt($curl, CURLOPT_HTTPHEADER,
array(
'method' => 'POST',
'header' => 'Content-Type: application/json' . "\r\n"
. 'Content-Length: ' . strlen($data_string) . "\r\n",
'content' => $data_string,
);
or similar


text:
Q: cell of collection view not displaying in row I have 12 images and i want to display this images in UICollectionView with 4 rows where each rows have 3 images.

Here is my .h file code

    @interface MyMusic : UIViewController<UICollectionViewDataSource,UICollectionViewDelegate>
{
UICollectionView *_collectionView;
}
@end

and here is my .m file code
- (void)viewDidLoad{
enter code hereUICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setItemSize:CGSizeMake(100, 100)];
[flowLayout setMinimumLineSpacing:5];
[flowLayout setMinimumInteritemSpacing:5];
[flowLayout setSectionInset:UIEdgeInsetsMake(0, 0, 0, 0)];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];

_collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(10,238, 300, 200) collectionViewLayout:flowLayout];
_collectionView.backgroundColor = [UIColor redColor];
[_collectionView setDataSource:self];
[_collectionView setDelegate:self];
[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"];
[self.view addSubview:_collectionView];
}

 - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 4;}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{return 3;}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
enter  UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

cell.backgroundColor=[UIColor greenColor];
return cell;
}

above code working fine but my output will not come in proper

its looking like this

any one can help me how can i solve this ?

A: Your UICollectionView width is 300 points, and your item's width is 100 points.
Interitem space is 5 points, so
100*3 + 5*2 = 310.

That's why you see only 2 columns.
Make your cells' width a little smaller, for example 290
Or set interitem spacing to 0.
Main rule - your UICollecitionView width should be larger or equal to sum of your cells widths  + interitem spacing

A: replace
[flowLayout setItemSize:CGSizeMake(100, 100)];

by
[flowLayout setItemSize:CGSizeMake(75,100 )];

I am using 75 just for the trial purpose and consider iphone screen.so that width of column are equal.
However you should not use hard-coded values.


text:
Q: invalid argument(s) no host specifed in url file in flutter 3.0 import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:hasfilx/Services/news_service.dart';
import 'package:hasfilx/models/news.dart';

class TopStories extends StatefulWidget {
  @override
  _TopStoriesState createState() => _TopStoriesState();
}

class _TopStoriesState extends State<TopStories> {
  News _featuredNews = new News();

  @override
  void initState() {
    super.initState();
    _getFeaturedNews();
  }

  _getFeaturedNews() async {
    final _newsService = NewsService();
    var _result = await _newsService.getFeaturedNews();
    // print(_result.body);
    var featuredNews = json.decode(_result.body);

    setState(() {
      _featuredNews.id = featuredNews['news']['id'];
      _featuredNews.title = featuredNews['news']['title'];
      _featuredNews.imageUrl =
          "http://192.168.1.106:3000" + featuredNews['news']['news_photo'];
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Center(
        child: ListView(
          children: [
            Card(
              child: Column(
                children: [
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Image.network(_featuredNews.imageUrl??""),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text(
                      _featuredNews.title??"",
                      style: TextStyle(
                          fontSize: 18.0,
                          fontWeight: FontWeight.bold,
                          color: Colors.black),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

flutter (19602): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: NoSuchMethodError: The getter 'body' was called on null.
flutter (19602): Receiver: null
flutter (19602): Tried calling: body
flutter (19602): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:38:5)
flutter (19602): #1      _TopStoriesState._getFeaturedNews (package:hasfilx/widgets/top_stories.dart:26:44)
E/flutter (19602):
I don't understand what i do


text:
Q: JavaFX, problems with setScene() I had a bug in my program, so I have made this little example code to illustrate what is going on. What happens is that the first scene doesn't seem to go away, and when I set the scene a second time, the old one keeps on interfering with the new scene. I am not sure why this happens. If you have any suggestions to why this happens, or/and know a workaround, I would be happy to hear and try them.
thanks alot!

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;

public class Main extends Application{

private Stage window;
private Scene scene1, scene2;
private Button button1, button2;

public static void main(String[] args){
    launch(args);
}

@Override
public void start(Stage primaryStage) throws Exception {
    button1 = new Button("Click me");
    button2 = new Button("Click me 2");

    scene1 = new Scene(button1);
    scene2 = new Scene(button2);

    window = primaryStage;

    window.setScene(scene1);
    window.show();

    button1.setOnAction(e -> window.setScene(scene2));
    button2.setOnAction(e -> window.setScene(scene1));
    }
}


text:
Q: Solution of Integral equation with simple means I need to find $x$ such that the following equation works, $x(s)-\int_o^1 2stx(t)dt=sin(\pi s)$ ,where $  s\in [0,1], y\in C[0,1], k\in C([0,1]^2)$. I know that it can be resolved using operator theory, but i wanted to find the solution with simpler means. Can somebody give me a hint ?
Thanks.

A: $$x(s)-\int_0^1 2st\,x(t)\,dt=x(s)-2s\int_0^1 t\,x(t)\,dt=\sin(\pi s)$$ means
$$x(s)=\sin(\pi s)+2s\int_0^1 t\,x(t)\,dt=\sin(\pi s)+2As,\tag1$$ where
$$A=\int_0^1 t\,x(t)\,dt\tag2.$$ If we substitute (1) into (2), we get the equation $$A=\int_0^1 t\,\sin(\pi t)\,dt+2A\int_0^1 t^2\,dt.$$ Can you finish from here?


text:
Q: how to introduce section content in a thesis In my thesis work I want to explain the content of a section,
my question is which is the best form to introduce the section, for example:
In this section are described the technologies ...
or
In this section have been described the technologies ...
thanks in advance
Dom

A: "Described in this section are the technologies that ..."
"Described in the following section are the technologies that ..."


text:
Q: VBA function to calculate Great Circle distances given lat/lon values I am trying to declare multiple variables in my custom function. Here is what I have so far:
Public Function myDistance(w As Double, x As Double, y As Double, z As Double) As Double
      myDistance = Excel.WorksheetFunction.Acos(Cos(radians(90 - w)) * Cos(radians(90 - y))) + Sin(radians(90 - w) * Sin(radians(90 - x)) * Cos(radians(y - z))) * 3958.756
End Function

When I attempt to run the function in my query I get the following error:
Compile Error
Sub or Function Not Defined

My suspicion is the syntax when declaring the variables is incorrect, but I am unsure of how to remedy this. I ran a more simple version of this function without any problem. See below:
Public Function myDistance(x as double) as double
     myDistance = Excel.WorksheetFunction.Acos(x)
End Function

The function itself will be used to calculate the distance between two places using latitude and longitude. Do you know how to correct the issue I am having?
Thank you.

A: This is the function that I use to calculate Great Circle distances, courtesy of
http://www.cpearson.com/excel/LatLong.aspx
Option Compare Database
Option Explicit

' ref: http://www.cpearson.com/excel/LatLong.aspx

Private Const C_RADIUS_EARTH_KM As Double = 6370.97327862
Private Const C_RADIUS_EARTH_MI As Double = 3958.73926185
Private Const C_PI As Double = 3.14159265358979

Function GreatCircleDistance(Latitude1 As Double, Longitude1 As Double, _
            Latitude2 As Double, Longitude2 As Double, _
            ValuesAsDecimalDegrees As Boolean, _
            ResultAsMiles As Boolean) As Double

Dim Lat1 As Double
Dim Lat2 As Double
Dim Long1 As Double
Dim Long2 As Double
Dim X As Long
Dim Delta As Double

If ValuesAsDecimalDegrees = True Then
    X = 1
Else
    X = 24
End If

' convert to decimal degrees
Lat1 = Latitude1 * X
Long1 = Longitude1 * X
Lat2 = Latitude2 * X
Long2 = Longitude2 * X

' convert to radians: radians = (degrees/180) * PI
Lat1 = (Lat1 / 180) * C_PI
Lat2 = (Lat2 / 180) * C_PI
Long1 = (Long1 / 180) * C_PI
Long2 = (Long2 / 180) * C_PI

' get the central spherical angle
Delta = ((2 * ArcSin(Sqr((Sin((Lat1 - Lat2) / 2) ^ 2) + _
    Cos(Lat1) * Cos(Lat2) * (Sin((Long1 - Long2) / 2) ^ 2)))))

If ResultAsMiles = True Then
    GreatCircleDistance = Delta * C_RADIUS_EARTH_MI
Else
    GreatCircleDistance = Delta * C_RADIUS_EARTH_KM
End If

End Function

Function ArcSin(X As Double) As Double
    ' VBA doesn't have an ArcSin function. Improvise.
    ArcSin = Atn(X / Sqr(-X * X + 1))
End Function


text:
Q: why does application not start with systemd script I would like to executea script as root whenever I boot the system.
I wrote a shell script:
# cat /home/root/demo_wrap.sh
#!/bin/bash
`/home/root/demo_start.sh` > /dev/null &

that works great when I invoke it from the shell.
I wrote the following service file:
(Updated according to comments from Edgar Magallon):
# cat /etc/systemd/system/demo_start.service
[Unit]
Description=starts the MH11 demo on EVK

[Service]
Environment="DISPLAY=:0"
Type=forking
XAUTHORITY=/home/root/.Xauthority
ExecStart=/home/root/demo_wrap.sh

[Install]
WantedBy=graphical.target

(I have also tried with DISPLAY:1 s well as XAUTHORITY=/run/user/0 with no success)
but for some reason, # systemctl start demo_start will not invoke the application but report:
[[0;1;31m*[[0m demo_start.service - starts the MH11 demo on EVK
     Loaded: loaded (/etc/systemd/system/demo_start.service; enabled; vendor preset: disabled)
     Active: [[0;1;31mfailed[[0m (Result: exit-code) since Wed 2022-05-11 18:58:25 UTC; 1min 11s ago
    Process: 251 ExecStart=/home/root/demo_wrap.sh (code=exited, status=0/SUCCESS)
   Main PID: 252 (code=exited, status=127)

May 11 18:58:18 smarc-rzv2l systemd[1]: Starting starts the MH11 demo on EVK...
May 11 18:58:18 smarc-rzv2l systemd[1]: Started starts the MH11 demo on EVK.
May 11 18:58:25 smarc-rzv2l demo_wrap.sh[254]: error: XDG_RUNTIME_DIR not set in the environment.
May 11 18:58:25 smarc-rzv2l demo_wrap.sh[254]: Connecting to display server failed!: No such file or directory
May 11 18:58:25 smarc-rzv2l demo_wrap.sh[254]: [ERROR] Wayland::init failed
May 11 18:58:25 smarc-rzv2l demo_wrap.sh[252]: /home/root/demo_wrap.sh: line 2: RZ/V2L: No such file or directory
May 11 18:58:25 smarc-rzv2l systemd[1]: [[0;1;39m[[0;1;31m[[0;1;39mdemo_start.service: Main process exited, code=exited, status=127/n/a[[0m
May 11 18:58:25 smarc-rzv2l systemd[1]: [[0;1;38;5;185m[[0;1;39m[[0;1;38;5;185mdemo_start.service: Failed with result 'exit-code'.[[0m

While export XDG_RUNTIME_DIR="/run/user/0" is set in /etc/profile:
export XDG_RUNTIME_DIR=/run/user/$UID

and the weston display manager launches and displays properly on the HDMI screen.
ENVIRONMENT:
This is on an embedded platform with a Yocto built distribution that runs the Weston compositor. When I start a shell window in Weston and type echo $DISPLAY, it does not print anything I expected this to be :0 or :1 (per Edgar Magallon, below). As the terminal window appears prperly on the Weston desktop. This is an embedded reference platform and only has one user root. It is not connected to a network nor will anybody have access to it by connecting any other means of hardware to it. Security is not a concern!
I found the following on the system:
# cat /lib/systemd/system/weston\@.service
[Unit]
Description=Weston Wayland Compositor
RequiresMountsFor=/run
Conflicts=plymouth-quit.service
After=systemd-user-sessions.service plymouth-quit-wait.service

[Service]
User=%i
PAMName=login
EnvironmentFile=-/etc/default/weston
StandardError=journal
PermissionsStartOnly=true
IgnoreSIGPIPE=no

ExecStart=/usr/bin/weston-start -v -e -- $OPTARGS

and my demo should be started after this but it's a bit odd:
# systemctl status weston.service shows me:
[[0;1;32m*[[0m weston.service
     Loaded: loaded (/etc/init.d/weston; generated)
     Active: [[0;1;32mactive (exited)[[0m since Wed 2022-05-11 18:57:23 UTC; 33min ago
       Docs: man:systemd-sysv-generator(8)
    Process: 189 ExecStart=/etc/init.d/weston start (code=exited, status=0/SUCCESS)

May 11 18:57:22 smarc-rzv2l systemd[1]: Starting weston.service...
May 11 18:57:23 smarc-rzv2l systemd[1]: Started weston.service.
May 11 18:57:34 smarc-rzv2l weston[196]: Connecting to display server failed!: No such file or directory
May 11 18:57:34 smarc-rzv2l weston[196]: [ERROR] Wayland::init failed
May 11 18:57:35 smarc-rzv2l weston[190]: /etc/profile.d/zz1-demo_wrap.sh: line 2: RZ/V2L: No such file or directory

while Weston is up & running fine.

A: What happens is that your service file is trying to execute your application before other services have been started.
You need to add to your demo_start.service the directive After that tells the service to run only if the other services are already running. Given the fact that you need the Weston compositor you must add the weston.service to the directive.
Also, regarding the XDG_RUNTIME_DIR error, the same logic applies. For this case you need to add the systemd-user-sessions.service so the /run/user/0 directory is created before trying to execute your application. Besides that, you need to set to the directive Environment the path to the XDG_RUNTIME_DIR directory.
Your demo_start.service file should have the following directives:
[Unit]
Description = starts the MH11 demo on EVK
After = weston.service systemd-user-sessions.service

[Service]
User = root
Environment = "XDG_RUNTIME_DIR=/run/user/0"
ExecStart = /home/root/demo_wrap.sh

[Install]
WantedBy = multi-user.target


text:
Q: AFNetworking + download images in queue + cancel operations I need to download a queue of images.
I created my operations first, then add them with the "enqueue" method of AFNetworking.
I have 2 problems :
1) I didn't have the progress bar working for the queue (and I have it working with a custom operation queue)
2) I didn't find the solution to stop the queue when I want
I created first operations to batch and add theme in a array:
  while ((dict = [enumerator nextObject]))
  {
    NSMutableURLRequest *request = [[MyHTTPClient sharedClient] requestWithMethod:@"GET" path:@"ws/webapp/services/pull_image" parameters:dict];

    AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:request
imageProcessingBlock:nil                                                                                cacheName:nil
    success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image)
    {
      NSLog(@"image : %@", [image description]);
      // process images
    }
    failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error)
    {
      // manage errors
    }];

    [operations addObject:operation];
  }

Then, I enqueue the operations:
     [[MyHTTPClient sharedClient] enqueueBatchOfHTTPRequestOperations:operations
       progressBlock:^(NSUInteger numberOfCompletedOperations, NSUInteger totalNumberOfOperations)
       {
           float percentDone = ((float)((int)numberOfCompletedOperations) / (float)((int)totalNumberOfOperations));
  [delegate syncServicesController:self updateProgressView:percentDone];
       }
       completionBlock:^(NSArray *operations)
      {
        //
      }];

So, the progress download didn't work.
But I can see the progress of numberOfCompletedOperations... ? 1,2,3,4,5... Does I need to force the refresh of the progress view in the main thread ?
And when I tried to stop the network tasks:
- (void)cancelAllRequests
{
  [[MyHTTPClient sharedClient] cancelAllHTTPOperationsWithMethod:@"GET" path:@"ws/webapp/services/pull_image"];

}

I don't understand how to stop the queue of requests... This seems that works but I have this error :  -[NSBlockOperation request]: unrecognized selector sent to instance 0x16f54c70

A: These were actually just fixed in the last day or two :)
Go ahead and update to the latest version of master, which includes the following:
cc2115e469: Progress blocks now dispatch to main by default, just like all of the other completion blocks in AFNetworking. This should fix any issues around the UI not updating there.
cac44aeb34: Fixes that problem with NSBlockOperation being sent request. There was an incorrect assumption baked into cancelAllHTTPOperationsWithMethod: that all operations were AFHTTPRequestOperation. The only downside is that it will not handle your batched operations. For that, you can always iterate through httpClient.operationQueue.operations and pick out the one you want.


text:
Q: Word for "ability to find & leverage advantages in the environment"? I'm hoping for a contemporary word to use in a computer game I'm developing that describes a person's ability to continuously find the best locations, paths that avoid danger and maximize protection and security while traveling through unexplored and dangerous terrain, or to find and use natural defenses during a modern combat situation (to lessen the chance of being discovered or ambushed while still being able to shoot at the hostiles).
"Survival" is too generic (no need to find edible plants and avoid poisons or cure illness/wounds) and "Tactics" doesn't focus on the terrain aspect enough and is too mixed with giving orders to a team regarding combat formation.
A ninja, for example, would be at an "extraordinary" or "superhuman" level at this skill.

A: After some clarification in comments under the question, in the context of using a phrase in a game, and then defining it within that game to cover a list of related skills, a reasonably appropriate choice is situational awareness.
From "10 Ways to Improve Your Situational Awareness":

Situational Awareness is the ability to identify, process, and comprehend information about how to survive in an emergency situation. More simply, it's knowing what is going on around you. It is dynamic, hard to maintain, and easy to lose.

From "How to Develop the Situational Awareness of Jason Bourne":

As the names implies, situational awareness is simply knowing what's going on around you. It sounds easy in principle, but in reality requires much practice. And while it is taught to soldiers, law enforcement officers, and yes, government-trained assassins, it's an important skill for civilians to learn as well. In a dangerous situation, being aware of a threat even seconds before everyone else can keep you and your loved ones safe.

Finally, from Wikipedia's more general description:

Situational awareness or situation awareness (SA) is the perception of environmental elements and events with respect to time or space, the comprehension of their meaning, and the projection of their future status.
Situation awareness has been recognized as a critical, yet often elusive, foundation for successful decision-making across a broad range of situations, many of which involve the protection of human life and property, including aviation, air traffic control, ship navigation, health care, emergency response, military command and control operations, and offshore oil and nuclear power plant management. Lacking or inadequate situation awareness has been identified as one of the primary factors in accidents attributed to human error.

A: Another possibility is resourceful.
From Cambridge:

resourceful: skilled at solving problems and making decisions on your own

From M-W:

resourceful: able to deal well with new or difficult situations and to find solutions to problems

A Jason Bourne or a ninja would be at the level of extraordinary or superhuman when it comes to resourcefulness, i.e., being resourceful. One might say that they are super resourceful in every possible situation, no matter how challenging.

A: Adaptability describes a person's ability to successfully handle new situations that they have not experienced before. This could be a good "catch-all" term to describe success at a wide variety of activities that aren't regularly performed. Adaptability would improve a person's chances to find cover in an unfamiliar environment, or improvise their way into a heavily guarded compound, or survive in a hostile environment. It allows one to come up with a plan on the fly, and respond to circumstances that could not be planned for, using skills that aren't rigorously practiced.