text:
Q: path of visual studio c compiler i use to compile c/c++ code with gcc and now i want to pass on vsc. So i read for configure the path i should go in my visual studio file C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC and use vcvarsall.bat. When i do that with the powershell, it just doesn't work. If i do it with the cmd.exe, i will be able the use cl but if i open a new cmd.exe it won't work again. I try to put manually C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin in the path but it doesn't work either.
Thank you for all the future help.

A: Finally what i did it's create a shortcut and change the target to %comspec% /k "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\VsDevCmd.bat".

A: Newer versions of Visual Studio/Build Tools create shortcuts for you
Lately, if you install Visual Studio or VS Build Tools - with Develop C++ Desktop applications package, you should get a bunch of shortcuts automatically in the Windows Start menu that will launch a command prompt for 64 or 32 bit compiler.
Just open start menu search bar (shortcut - Windows key) and type command:

You can do the following to find out how to run these files:

*

*Right-click on the item in Windows Start and choose Open File Location, which will open the shortcut link in File Explorer

*Right-click the shortcut link and choose Properties

*In the Properties windows, copy the "Target:" field (click in it and ctrl-a to select all, then ctrl-c to copy).

*The first item is the exe called (Should be %comspec%, and anything after the first space will be arguments.

For example, my x64 Native Tools Commmand Prompt for VS 2019 shortcut has a target of:
%comspec% /k "C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Auxiliary\Build\vcvars64.bat"

Armed with this info, you can build a profile (see below) to launch terminals from other apps, or just take the last argument - the path and name of the batch file - and run it in a command terminal to set it up correctly to find all the VC tools.
Setting up a profile with a terminal in another tool/app
To setup a profile for apps like Microsoft's "Windows Terminal" app (multiple, tabbed terminals of different types - see Windows Store to download), or for Visual Studio Code:
Use the info from the shortcuts that link to the vcvars.bat batch files, as explained above to create a profile. For example, here is the JSON to add to Visual Studio Code to add an x86 (32-bit) and 64 bit command window to the dropdown list:
In .vscode/settings.json:
"terminal.integrated.profiles.windows": {
  "Visual C Dev Prompt (x64)": {
    "path": "cmd.exe",
    "args": [
      "/k",
      "C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\BuildTools\\VC\\Auxiliary\\Build\\vcvars64.bat",
    ],
  },
  "Visual C Dev Prompt (x86)": {
    "path": "cmd.exe",
    "args": [
      "/k",
      "C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\BuildTools\\Common7\\Tools\\VsDevCmd.bat",
    ],
  },
},

Note that I changed the calling command from %comspec% to just cmd.exe, which should be in WINDOWS/system32 folder, which should already be on the path. I couldn't get it working with %comspec%. You can expand that in a command window to see the path on your PC as follows:
echo %comspec%

On my PC it was C:\WINDOWS\system32\cmd.exe.


text:
Q: MySQL insert in one of two tables based on condition for one table Consider two tables that have timestamp and data columns. I need to construct an SQL that does the following:

*

*Insert data (unique timestamp and data column) in one table if timestamp value is not present in the table ("insert my data in table 1 for timestamp="12:00 1999-01-01" only if that timestamp is not present in table 1...)

*Otherwise, insert very same data in different table without any checks, and overwrite if necessary  (... otherwise insert same set of fields in table 2).
How I could possibly achieve this on SQL? I could do it using a client but this is way slower. I use MySQL

A: Run a query for your 2nd bullet first. i.e. insert data into table 2 if it is present in table 1
insert into table2 (data, timestamp)
select 'myData', '12:00 1999-01-01'
from table1
where exists (
    select 1 from table1
    where timestamp = '12:00 1999-01-01'
)
limit 1

Then run your the query for your 1st bullet i.e. insert into table1 only if the data doesn't already exist
insert into table1 (data, timestamp)
select 'myData', '12:00 1999-01-01'
from table1
where not exists (
    select 1 from table1
    where timestamp = '12:00 1999-01-01'
)
limit 1

Running both these queries will always only insert 1 row into 1 table because if the row exists in table1, the not exists condition of the 2nd query will be false and if it doesn't exist in table1, then the exists condition of the 1st query will be false.
You may want to consider creating a unique constraint on table1 to automatically prevent duplicates so you can use insert ignore for your inserts into table1
alter table table1 add constraint myIndex (timestamp);
insert ignore into table1 (data,timestamp) values ('myData','12:00 1999-01-01');

A: A regural INSERT statement can insert records into one table only. You have 2 options:

*

*Code the logic within the application

*Create a stored procedure within mysql and code the application logic there

No matter which route you choose, I would

*

*Add a unique index on the timestamp column in both tables.

*Attempt to insert the data into the 1st table. If the insert succeeds, everything is OK. If the timestamp exists, then you will get an error (or a warning depending on mysql confioguration). Your solution handles the error (in mysql see DECLARE ... HANDLER ...).

*Insert the data into the 2nd table using INSERT INTO ... ON DUPLICATE KEY UPDATE ... statement, which will insert the data if the timestamp does not exists, or updates the record if it does.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Testing with a Stubbed Service I have created a stubbed web service to help my team implement and "integration" test their code without traversing the full stack, which is not possible in this case.
I want to create some different scenarios for them e.g. success, different kinds of failure. One way I have thought of handling these scenarios is if a particular input is e.g. "Smith" then return one object, if "Jones" return another.
I'm wondering if this scenario mapping is too fragile but mainly how I could manage these scenarios in a nice way that would allow the devs to extend the scenarios. One idea was to serialize the possible results they expect and store them with their parameters in a repository of some sort. This means they could be added to and amended. The serialization could break though and for complex object it would be awkward.
Feel like I'm really missing something here!

A: I really love stubbing out things like web services during development.  It allows the developers to target a system that might not be ready and still get work done.  Like you said it also allows them to integrate early, which is great.  When the actual service is ready, it should be easy to swap out the stubs for the actual service.
I think it's totally fine to create a simple/quick-and-dirty repository that mimics actual web service calls.  One set of parameters comes in and then some data goes back out.
Consider spending a few hours to write a tool that generates code/data structures for you.  You can write functions that generate random data (names, addresses, whatever) and then it's fairly easy to change parameters and re-generate stubbed data/stubbed code.
It's worth the work to stub stuff out because it will dramatically increase developer productivity.  I wouldn't be afraid to spend a day or two setting up something - it'll pay off over the life of the project.


text:
Q: Compiz effects not working on an Asus 1215B with FGLRX The title says it all.
ASUS 1215B, Ubuntu 12.04 64-bit up-to-date and proprietary FGLRX drivers activated. I followed some instructions given by an ubuntu user and managed to enable some features (like woobly windows), but compiz effects are still not working.
Any hints would be greatly appreciated.

A: I found a quick solution to enable compiz effects on my ASUS 1215B:
• Go to Applications > System Tools > CompizConfig Settings Manager > Effects;
• Click on Animations;
• Click on ">" until you find the "Effect Settings" tab;
• Enable (tick) "Random Animations For All Events".
Good luck!


text:
Q: Change the Timescale for Resource View Is it possible to change the Y-Axes scale to show days instead of hours? So you can show multiple resources across the top and then days down the left hand side?
Many Thanks
Greg


text:
Q: about older android versions on google market I have developed my app in android 2.2, and put it on google market (munspel-appen).
I could see in the statistics that 4% are using android version 2.1 i dont have access to such device, so I wonder if my app will still work on that older version device if downloaded from market too or is it only working from 2.2 and up? How can one tell?

A: The configuration of your app (https://play.google.com/store/apps/details?id=com.munspel.munspelappen) seems to limit the app to devices with 2.2 and higher.
Users with a lower OS Version then 2.2. can not download your app from google market.
I would test your App in an Android 2.1 Emulator and if it works there change the minSDK for your app to 2.1 and upload an update to the market. In that way your app will be available to as much users as possible.

A: you can try in the android emulator in eclipse for example

A: Your application may work for 2.1 version provided that your application is compatible with API Level 7.
Well you can specify android:minSdkVersion=8 in AndroidManifest, (from document)The Android system will prevent the user from installing the application if the system's API Level is lower than the value specified in this attribute, You can try running your application on Emulator running 2.1 version. read more http://developer.android.com/guide/topics/manifest/uses-sdk-element.html#uses

A: If you're willing to pay, there are several companies specializing in testing Android apps on physical devices. Examples:

*

*http://duarlander.ning.com

*http://www.perfectomobile.com
I think there's a lot more in google.

A: First, the Market should use the minSdkVersion in your Manifest to filter the apps when searched.
To test, you can use an emulator of version 2.1 and see whether it works.
Most probably most of the code will work except those new in 2.2.


text:
Q: Visual Studio C++ не подсвечивает ошибки Я не знаю баг это или фича, но Visual Studio C++ (VS 141) не подсвечивает ошибки если функция использует шаблонные параметры, да и вообще работает с шаблонном.

Что с этим делать и как можно решить данную проблему?

A: Visual Studio и не обязано "подсвечивать" ошибки. Функциональность IntelliSense предназначена для беглого поверхностного анализа кода и надежно обнаруживать ошибки не может. Тем более в шаблонном коде. Этого от IntelliSense никто и не ожидает и никакой проблемы тут нет.
Ошибки вам будет рапортовать компилятор, когда вы выполните компиляцию вашего кода.

A: IntelliSense вполне сносно работает с шаблонами. В VS 2019 в этом плане наблюдается прогресс. Однако многие категории ошибок в шаблонах становятся ошибками только после инстанцирования шаблона или их затруднительно обнаруживать без инстанцирования. Для такого случая в IntelliSense есть возможность предоставлять подсказки для конкретных параметров. Их можно задать кликнув на иконку <T> после объявления шаблона.

C++ team blog Announcing Template IntelliSense


text:
Q: TeamCity VSC checkout agent fails I started using TeamCity recently and I have a problem with checkout.
I get this warning:
Updating sources: Will use server side checkout: No supported VCS client found on the agent for vcs root 'mygiturl'. Details: Unable to run git

Git is installed on the agent VPS (windows machine). It is on the PATH as well and I also created what teamcity suggests the
%env.TEAMCITY_GIT_PATH%

Still getting this warning. Anyone knows why this happens. I am using latest TeamCity


text:
Q: Associativity of infinite series In my calculus notes, my professor presented the following proposition:
Proposition: Let $\sum_{n=1}^{\infty}a_n$ be a convergent series and let $1=n_1<n_2<n_3<...$ be an increasing sequence of indices. Consider the set of grouped sums of the sequence between these indices, i.e; $$A_k=\sum_{n=n_k}^{n_{k+1}-1}a_n.$$ Then, $$\sum_{k=1}^{\infty}A_k=\sum_{n=1}^{\infty}a_n$$
This proposition is supposed to say that if an infinite series converges, then the associative property holds. I was reading an equivalent proposition, but written in a different way, and I was able to prove it. However, I can't prove the statement the way my professor wrote it. Any help is welcome
Addendum:
The proposition I was able to prove is Exercise 2.5.3 (a) on page 65 from the book Understanding Analysis, 2nd ed by Stephen Abbott.

A: Hint: $$\sum_{k=1}^N A_k =\sum_{i=1}^{n_{N+1}-1} a_i$$ because finite sums are associative.

A: It's easy to see that the sequence of partial sums of the $A_k$ is Cauchy, so that sequence of partial sums (i.e., the infinite sum) must converge to something.  And since the sequence of partial sums of the $A_k$ is a subsequence of the sequence of partial sums of $a_n$, we know what that something has to be.

A: May be following view also will be helpful: $\sum\limits_{k=1}^N A_k$ is subsequence of $\sum\limits_{k=1}^N a_k$.


text:
Q: Retrieve current login user from sqlite in toolbar i am developing a chat app and when I click on the login button I am redirected to MainActivity where I have a toolbar where I want to show the current login user name and profile pic using SQLite DB but I can't understand what should I code. what do I code in main activity to show current user name and default profile pic?
DataBaseHelper
package com.example.chatapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

public class DataBaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "USER_RECORD";
    private static final String TABLE_NAME = "USER_DATA";
    private static final String COL_1 = "ID";
    private static final String COL_2 = "USERNAME";
    private static final String COL_3 = "EMAIL";
    private static final String COL_4 = "PASSWORD";

    public DataBaseHelper(@Nullable Context context) {
        super(context, DATABASE_NAME , null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT , USERNAME TEXT , EMAIL TEXT , PASSWORD TEXT )");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(" DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }

    public boolean registerUser(String username , String email , String password){

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COL_2 , username);
        values.put(COL_3 , email);
        values.put(COL_4 , password);

        long result = db.insert(TABLE_NAME , null , values);
        if(result == -1)
            return false;
        else
            return true;
    }

    public boolean checkUser(String email , String password){

        SQLiteDatabase db = this.getWritableDatabase();
        String [] columns = { COL_1 };
        String selection = COL_3 + "=?" + " and " + COL_4 + "=?";
        String [] selectionargs = { email , password};
        Cursor cursor = db.query(TABLE_NAME , columns , selection ,selectionargs , null , null , null);
        int count = cursor.getCount();
        db.close();
        cursor.close();
        if (count > 0)
            return true;
        else
            return false;

    }

    public User getLoggedInUser(String email){
        SQLiteDatabase db = this.getWritableDatabase();

        String [] columns = { COL_2 };
        String selection = COL_3  + "=?";
        String [] selectionargs = { email };
        Cursor cursor = db.query(TABLE_NAME , columns , selection ,selectionargs , null , null , null);

        User user = new User();

        if(cursor != null){
            user.setUsername(cursor.getString(Integer.parseInt("username")));

            //If you want more data you can set your user properties
        }

        return user;
    }

}

MainActivity
package com.example.chatapp;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import de.hdodenhof.circleimageview.CircleImageView;

public class MainActivity extends AppCompatActivity {
   CircleImageView  profile_image;
   TextView username;
   private DataBaseHelper myDB;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      Toolbar toolbar = findViewById(R.id.toolbar);
      setSupportActionBar(toolbar);
      getSupportActionBar().setTitle("");

      myDB = new DataBaseHelper(this);

   }
   public boolean onCreateOptionsMenu(Menu menu)
   {
      getMenuInflater().inflate(R.menu.menu, menu);
      return true;
   }

   public boolean onOptionsItemSelected(MenuItem item)
   {
      switch (item.getItemId()){

         case R.id.logout:
            startActivity(new Intent(MainActivity.this, StartActivity.class));
            finish();
            return true;
      }
      return false;
   }
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_height="wrap_content"
        android:layout_width="match_parent">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:background="@color/purple_700"
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/MenuStyle">

            <de.hdodenhof.circleimageview.CircleImageView
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:id="@+id/profile_image">
            </de.hdodenhof.circleimageview.CircleImageView>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/username"
                android:layout_marginLeft="25dp"
                android:textColor="#fff"
                android:textStyle="bold">

            </TextView>

        </androidx.appcompat.widget.Toolbar>

    </com.google.android.material.appbar.AppBarLayout>

</LinearLayout>

User class
package com.example.chatapp;

public class User {
    private String id;
    private String username;
    private String imageURL;

    public  User(String id, String username, String imageURL)
    {
        this.id=id;
        this.username=username;
        this.imageURL=imageURL;

    }

    public User() {

    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getImageURL() {
        return imageURL;
    }

    public void setImageURL(String imageURL) {
        this.imageURL = imageURL;
    }
}


text:
Q: Speed of CockroachDB schema changes during unit tests I have issues with schema changes in my testing infrastructure. We use a unit test framework, and truncate our database between each unit test. I've noticed that running a series of CREATE statements is very slow as well, specifically duplicating a database for running parallel tests. I'm finding it's taking upwards of 10 minutes to duplicate a database 10 times (I'm using SHOW CREATE ALL TABLES and running those statements).

A: The problem with CockroachDB schema changes getting slow in tests is known, but there are some workarounds. See this guide with some recommended settings for unit tests, which should help address some of the problems: https://www.cockroachlabs.com/docs/stable/local-testing.html#use-a-local-single-node-cluster-with-in-memory-storage
Future releases (that is, v22.2 and later) will continue improving the performance of schema changes when repeatedly dropping and creating tables.


text:
Q: Почему таблица bootstrap находится внизу?

              Company
              Contact
              Country

              Alfreds Futterkiste
              Maria Anders
              Germany

              Centro comercial Moctezuma
              Francisco Chang
              Mexico

https://codepen.io/kostyabagr/pen/oNddEPr  вот ссылка на код, почему то таблица на вкладке 'характеристики' находится внизу. Если отключить css файл, то таблица встает на свое место, но я не понимаю, что надо исправить

браузер видит, но не отображает таблицу
Спасибо за помощь


text:
Q: Error 215 Bad Authentication Data Twitter API 1.1 to validate user accounts with PHP + Zend Framework 1 I have a website that uses the Twitter API (verrsion 1.1) with PHP and Zend framework 1 for validating the user name that is entered into a text input by a user of the application.
I created the app on Twitter and generated the Consumer Key (API Key), Consumer Secret (Secret API), Access Token and Access Token Secret.
General permissions: Read, write, and direct messages
Tokens permissions: Read and write
My PHP code for the authentication with Twitter is:
$config = array(
        'version' => '1.1',
        'signatureMethod' => 'HMAC-SHA1',
        'callbackUrl' => 'http://example/main/twitter',
        'siteUrl' => 'https://api.twitter.com/oauth',
        'requestTokenUrl'=> 'https://api.twitter.com/oauth/request_token',
        'accessTokenUrl' => 'https://api.twitter.com/oauth/access_token',
        'authorizeUrl' => 'https://api.twitter.com/oauth/authorize',
        'consumerKey' => self::$_consumeKey,
        'consumerSecret' => self::$_consumeSecret
        );

$session = new Zend_Session_Namespace('OAUTH_TWITTER');

$consumer = new Zend_Oauth_Consumer( $config );

$token = $consumer->getRequestToken();

$session->request_token = serialize($token);

$consumer->redirect();

When this code is executed, in the line:
$token = $consumer->getRequestToken();

returns the following error:
Could not retrieve a valid Token response from Token URL:
error code="215" Bad Authentication data.
I do not know what I did because previously was working perfectly. I researched for 2 weeks and still can not find the solution. I tried to create the application again, regenerate keys and tokens and change the time zone of my server to UTC but has not been solved.
If you need more information about me, please let me know.
I appreciate any information you can give me. Regards.
PD: sorry by my bad english


text:
Q: C# Reflection Invoke - Object of Type 'XXX' Cannot Be Converted to type 'System.Object[]' I have created an instance called input that is of type:
public class TestInput
{
    public int TesTInt { get; set; }
}

I use this in this function:
public static class TestClass
{
    public static string TestFunction()
    {
        var testInput = new TestInput();
        string res = ServicesManager.Execute<string>((object) testInput);

        return res;
    }
}

The Execute function is here:
public static OUT Execute<OUT>(object input)
            where OUT : class
{
       var method = //getting method by reflection
       object[] arr = new object[] { input };
       return method.Invoke(null, arr) as OUT; //Error is triggered here
}

The method that I invoke is this one:
public static string TestFunctionProxy(object[] input)
{
       var serviceInput = input[0] as TestInput;
       //rest of code
}

I received the error in the title. (XXX - "TestInput" type)
What's happening and what is causing this error?
Note: method is static so no instance is required for the first parameter. Please correct me if I'm wrong.
Any help is appreciated.
EDIT: Updated the question with some more code for a complete example.

A: You are passing the wrong arguments to the method. It wants an object[] and you are giving a simpe object. This is how to fix it:
object[] arr = new object[] { new object[] { input } };

The 'outer' object[] is the parameter for Invoke, the 'inner' array is the parameter for your method.


text:
Q: Why does SSO between ASP.NET MVC and ASP.NET Core 2.0 only work on localhost? I have a problem with SSO between my two web apps.
I am using code from this tutorial https://learn.microsoft.com/en-us/aspnet/core/security/cookie-sharing?view=aspnetcore-2.1&tabs=aspnetcore2x
First app based on ASP .NET MVC:
public partial class Startup
    {
        public CronJobs _cronJobs;
        public Startup() { }

        public Startup(CronJobs cronJobs)
        {
            _cronJobs = cronJobs;
        }
        // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationUserDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
               // AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
               AuthenticationType = "Identity.Application",
                CookieName = ".AspNet.SharedCookie",
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    OnValidateIdentity =
             SecurityStampValidator
                 .OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                     validateInterval: TimeSpan.FromMinutes(30),
                     regenerateIdentity: (manager, user) =>
                         user.GenerateUserIdentityAsync(manager))
                },
                TicketDataFormat = new AspNetTicketDataFormat(
         new DataProtectorShim(
             DataProtectionProvider.Create(new DirectoryInfo(@"c:\keyring"),
                 (builder) => { builder.SetApplicationName("SharedCookieApp"); })
             .CreateProtector(
                 "Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware",
                 "Identity.Application",
                 "v2"))),
                CookieManager = new ChunkingCookieManager()
            });

            System.Web.Helpers.AntiForgeryConfig.UniqueClaimTypeIdentifier =
                "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name";

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            //

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
             app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            var hangfireContainer = new UnityContainer();
            GlobalConfiguration.Configuration.UseActivator(new UnityJobActivator(hangfireContainer));
            GlobalConfiguration.Configuration.UseSqlServerStorage("HangFireDB");

            app.UseHangfireServer();

            //this call placement is important
            var options = new DashboardOptions
            {
                Authorization = new[] { new CustomAuthorizationFilter() }
            };
            app.UseHangfireDashboard("/hangfire", options);

        }
    }

    public class CustomAuthorizationFilter : IDashboardAuthorizationFilter
    {

        public bool Authorize(DashboardContext context)
        {
            if (HttpContext.Current.User.IsInRole("admin"))
            {

                return true;
            }

            return false;
        }
    }

And my second app (Core 2.0)
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.AddDbContext<CatalogDbContext>(options =>
          options.UseSqlServer(Configuration.GetConnectionString("CatalogConnection")));

        services.AddDbContext<UsersDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("UsersConnection")));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<UsersDbContext>()
            .AddDefaultTokenProviders();

        services.AddDataProtection()
            .PersistKeysToFileSystem(GetKeyRingDirInfo())
            .SetApplicationName("SharedCookieApp");

        services.ConfigureApplicationCookie(options => {
            options.Cookie.Name = ".AspNet.SharedCookie";

        });

        services.AddTransient<UserManagerInfo>();

        services.AddMvc();
    }

    private DirectoryInfo GetKeyRingDirInfo()
    {

        var keyRingDirectoryInfo = new DirectoryInfo("C://keyring");
            if (keyRingDirectoryInfo.Exists)
            {
                return keyRingDirectoryInfo;
            }

            throw new Exception($"KeyRing folder could not be located");

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        var options = new RewriteOptions().AddRedirectToHttpsPermanent();

        app.UseRewriter(options);

        if (env.IsDevelopment())
        {
            app.UseBrowserLink();
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/error");
            app.UseStatusCodePages();
            app.UseStatusCodePagesWithRedirects("/error/{0}");

        }
        app.UseStaticFiles();

        app.UseAuthentication();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

It's working on localhost. It is not working on IIS Windows Server 2016. No errors, but it not works.
Both apps have a permission to read and write to folder "keyring".

A: Please check the following and let me know if anything helped, I am ready to advise you further.

*

*Check if you have set the right SameSite cookie policy - based on the way you deploy the website to IIS. https://learn.microsoft.com/en-us/aspnet/core/security/samesite?view=aspnetcore-2.0

*Check if you do correctly SingIn the user in you ASP.NET CORE 2.0 application. (Calling SingInAsync in your code. https://dotnetcoretutorials.com/2017/09/16/cookie-authentication-asp-net-core-2-0/)

This may be caused by thousands of things. If nothing from the list helps, please provide further info on the configuration of IIS. - The way you deploy both apps.


text:
Q: Facebook it's not reading any meta tag from Head on my React Web App Here is my code from the Head. I checked on https://validator.w3.org/ and it's ok. Facebook it's not reading almost any from the head. Not a single meta for example. Meanwhile google it's reading all the Head, I check the web with https://search.google.com/test/rich-results
Any Idea?  thanks !!
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset=UTF-8>
  <meta name="keywords" content="Menús digitales, carta digital, tu web digital, ofrece tus productos, carta digital de servicios y productos. Myqmp, kmepdido, quemepido. Servicio digital para negocios, restaurantes, comercios. Comercio digital, ecommerce. " >
  <link href="https://firebasestorage.googleapis.com/v0/b/lmyapp.appspot.com/o/logo-face.jpg?alt=media&token=a58ec397-77dc-4e6c-9998-87779-88776" rel="image_src">

  <link rel="canonical" href="https://myapp.com">

  <title>My App</title>
   <meta property='og:title' content='MyApp'>
   <meta property='og:description' content='MyApp es un motor web que permite crear rápidamente tu web.' >
   <meta property='og:type' content='website' >
   <meta property='og:url' content='https://myapp.com/' >
   <meta property='og:image' content='https://firebasestorage.googleapis.com/v0/b/14oppb7.appspot.com/o/logo-face.jpg?alt=media&token=a598ec397-77dc-4e6c-8003-9898986' >

    <meta charset="utf-8" >
    <link rel="icon" href="https://firebasestorage.googleapis.com/v0/b/899pp3bb7.appspot.com/o/landing%2Fico-myapp.ico?alt=media&token=cff43pppppp2-e578ppf4bc" >
    <meta name="viewport" content="width=device-width, initial-scale=1" >
    <meta name="theme-color" content="#000000" >
    <meta
      name="MyApp es un motor web. Crea rápidamente tu web y ofrece tus servicios digitales."
      content="Powered by  MyApp, Crea rápidamente tu web y ofrece tus servicios digitales. Microsites para webs en español. Menús digitales."
    >

    <!-- WEB FONTS -->
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link href='https://fonts.googleapis.com/css?family=Poppins:400,400i,700,700i&display=swap' rel='stylesheet' type='text/css'>
    <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>

  </head>

A: There is this page on Facebook: https://developers.facebook.com/tools/debug/
Copy the URL of your website into the form there and press return. This takes you to a page where you see what Facebook "knows" about that website (it knows much more, but well). Press the button "Scrape again" (or similar). This should fix your problem if all the og meta tags are correct.

A: Finally it's reading the dynamic Head info from my App.
Here is the solution: just wait, and in a few days Facebook will see all the content.


text:
Q: How to make month over month Dynamic? below script is hard coded January and february WITH ctetable AS
(
    SELECT DISTINCT
        [site id],
        DATENAME(MONTH, [wcp_createddate]) AS MonthNames
    FROM
        [dbo].[getsiteharveyballscores]
)
SELECT
    *,
   january + february AS Combine,
   IIF((january + february) = 1
        AND february = 0, 'Drop', IIF((january + february) = 1
                                     AND february = 1, 'New', 'Continue')) AS Flag
FROM
    (SELECT
         monthnames,
         [site id] AS SiteId,
         [site id]
     FROM
         ctetable) AS SourceTable
PIVOT
    (COUNT([site id])
         FOR monthnames IN (january, february)) AS pivottable;


text:
Q: No valid ext_emconf.php file found for package in TYPO3 7.6 I want to install an extension via direct upload in Extension Manager. But allways i get the Message "No valid ext_emconf.php file found for package ...". Somebody out there that can help with this problem?
<?php

$EM_CONF[$_EXTKEY] = array (
    'title' => 'Interfrog Themeconfiguration',
    'description' => 'contains all themeconfiguration tables config,color,font,colorshemes without an existing theme',
    'category' => 'misc',
    'author' => 'Interfrog',
    'author_email' => 'info@interfrog.de',
    'author_company' => 'Interfrog Produktion GmbH',
    'state' => 'beta',
    'uploadfolder' => true,
    'createDirs' => NULL,
    'clearCacheOnLoad' => true,
    'version' => '2.3.1',
    'constraints' => array(
        'depends' => array(
            'extbase' => '7.6',
            'fluid' => '7.6',
            'typo3' => '7.6',
        ),
        'conflicts' => array(
        ),
        'suggests' => array(
        ),
    ),
    'autoload' => array(
        'psr-4' => array('Interfrog\\IfThemeconfiguration\\' => 'Classes')
    ),
);

?>

A: Dependencies must have both upper and lower boundaries defined.
Technically your line 'extbase' => '7.6', has no value at all.

*

*Do you want to restrict from 7.6 upwards?

*Or restrict to a maximum of 7.6?

What's 7.6 after all?

*

*7.6.9970970?

*7.6.0?

You see, there is no valuable information that can be pulled from this.
This is why you need to provide specific boundaries like this for example:
'extbase' => '7.6.15-7.6.99'
PSA:
Be extremely careful with loose upper bounds. We see people going 7.6.0-9.99.99.
Unless you own some magic crystal ball that can foretell the future, it's better to raise the dependency constraints once you actually tested them.

A: At our last Usergroup we figured out the reason. We found out that the problem arises when zipping the extension locally on Mac OSX command line. All files looses its access rights and properties that causes the effect that the ext_emconf.php can't be found during the install process. If you download the zip from an installed live system everything is fine.
We doesn't work out the correct command on Mac OSX command line. It would be awesome if someone can work out the right command for zipping on command line.

A: Regarding the issue on a Mac
The problem is not (only) the hidden MAC_OS folders. The issue is, that OS X does not put the content of chosen Typo3-Extension-Folder into the archive but the folder as single root element itself. Then Typo3 cannot find the files. You must go into the extension folder and run then the zip command.
Example: We are in my working directory which is named output. The extension folder is called jfmulticontent_3.0.0-dev_201810051125. Then you would have to run:
BOB-NB2:output bob$ cd jfmulticontent_3.0.0-dev_201810051125/
BOB-NB2:jfmulticontent_3.0.0-dev_201810051125 bob$ zip -r -X ../jfmulticontent_3.0.0-dev_201810051125.zip *


text:
Q: Can´t edit sourcecode in VS Texteditor when resharper is running For some time I use Resharper in Visual Studio 12, but since a few days I have a problem. If Resharper running, I can not type anything in the source code editor in Visual Studio.
I'm using the version 8.2.0.2160
and StyleCop version 4.7.49.0
All settings I have completely reset. I have also deleted the settings files. I have also uninstalled Resharper and StyleCop and reinstalled.
Nothing helps! The strange thing is, that I (except C# and xaml) can probably edit in other files.
Or when I restart Visual Studio and there investing a new project. Then everything works properly.
I do not know how to fix the problem. What could I even check what I could try?

A: It was a shredded cache in PersistentCache directory of resharper. When I deleted the directory, resharper had re-creates it and everything worked perfectly again!

A: go to the following location:
%AppData%\..\Local\JetBrains\ReSharper\v8.2\SolutionCaches\

Delete the desired solution cache. I have not sufficient reputation to comment that's why posting as answer, could be helpful for someone to locate the directory of solution cache.


text:
Q: Admin Post List Only Show One Category I want a user to only be able to view a single category type when clicking "posts" in admin. I've tried messing with list_terms_exclusions, but that only seems to be effecting the category management page. Can anyone point me in the correct direction?

A: I found a hacky solution involving redirecting the user:
if ((basename($_SERVER['SCRIPT_NAME']) == 'edit.php')) {
// your code here
$author = wp_get_current_user();
if(isset($author->roles[0])){
    $current_role = $author->roles[0];
}else{
    $current_role = 'no_role';
}

if($current_role == 'ai1ec_event_assistant' && ($_GET['post_type']==''&&$_GET['category_name']=='')){
    header("Location:/wp-admin/edit.php?category_name=events-list");
}

}


text:
Q: Why reflectance map in pix4d dont are normalized I want to know, why my reflectance map, dont have value between 0 and 1. Because my calibration table said me: for example red band has max value = 0.88 nm, and my reflectance map in red band have max value= 1.2 nm.

A: As you mentioned the reflectance values for the Blue, Green, Red, RedEdge and NIR should be between 0 and 1 and NDVI should be between -1 and 1. If you are having a reflectance value above 1, I would check to see if the raw images are over or under exposed.If that is the case I would remove those images. I am not sure what software you are using to get your reflectance outputs but if you are using Pix4D, you may try Camera only calibration option. Based on my experience Camera only calibration option re-adjusts reflectance values to be slightly lower.

A: Try using Camera only calibration option in Pix4D. Alternatively you may try to identify those inaccurate reflectance areas using QGIS or Arcmap once you have the reflectance maps. It may be an outlier like a car something.


text:
Q: get sum of a object in array Javasript and store it i have this array :
here is a snippet :
[
  {
    "month": 9,
    "date": "2022-09-01T00:00:00",
    "week_nb": 35,
    "total_Value": 31.356,

  },
  {
    "month": 9,
    "date": "2022-09-17T00:00:00",
    "week_nb": 36,
    "total_Value": 67.726,

  },
  {
    "month": 9,
    "date": "2022-09-08T00:00:00",
    "week_nb": 35,
    "total_Value": 98.63,
  },
  {
    "month": 9,
    "date": "2022-09-24T00:00:00",
    "week_nb": 36,
    "total_Value": 55.178,

  },
....

i already specify this by month number
i want to get the sum of TOTALE_VALUE  of each  WEEK_NB
and store it inside a new array containt 2 objects like
{week_number : X,  SumOfTotale_value : X },{week_number : X,  SumOfTotale_value : X }...

A: You could use Array.reduce() to sum the total value grouped by week.
We'd create an object with a property for each week number, then sum for each matching item.
Object.values() can then be used to convert this object to an array as required.

const input = [ { "month": 9, "date": "2022-09-01T00:00:00", "week_nb": 35, "total_Value": 31.356,  }, { "month": 9, "date": "2022-09-17T00:00:00", "week_nb": 36, "total_Value": 67.726,  }, { "month": 9, "date": "2022-09-08T00:00:00", "week_nb": 35, "total_Value": 98.63, }, { "month": 9, "date": "2022-09-24T00:00:00", "week_nb": 36, "total_Value": 55.178,  } ]

const result = Object.values(input.reduce((acc, { week_nb, total_Value }) => {
    acc[week_nb] = acc[week_nb] || { week_number: week_nb, SumOfTotale_value: 0 };
    acc[week_nb].SumOfTotale_value += total_Value;
    return acc;
}, {}));

console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }

You can also use a for..of loop to get the same result:

const input = [ { "month": 9, "date": "2022-09-01T00:00:00", "week_nb": 35, "total_Value": 31.356,  }, { "month": 9, "date": "2022-09-17T00:00:00", "week_nb": 36, "total_Value": 67.726,  }, { "month": 9, "date": "2022-09-08T00:00:00", "week_nb": 35, "total_Value": 98.63, }, { "month": 9, "date": "2022-09-24T00:00:00", "week_nb": 36, "total_Value": 55.178,  } ]

const map = {};

for(let { week_nb, total_Value } of input) {
    map[week_nb] = map[week_nb] || { week_number: week_nb, SumOfTotale_value: 0 }
    map[week_nb].SumOfTotale_value += total_Value;
}

console.log('Result:', Object.values(map))
.as-console-wrapper { max-height: 100% !important; }


text:
Q: What is the purpose of ImportSystemModules? What is the purpose of ImportSystemModules? Using help ImportSystemModules -Full produces an empty shell description.
PS 09:12  C:\src
>get-command *module*

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Function        Find-Module                                        2.2.1      PowerShellGet
Function        Get-InstalledModule                                2.2.1      PowerShellGet
Function        **ImportSystemModules**
Function        InModuleScope                                      3.4.0      Pester
Function        Install-Module                                     2.2.1      PowerShellGet
...

A: From Roger Lipscombe's blog, it used to do the following:

This runs Powershell.exe -ImportSystemModules, which, in turn, runs the ImportSystemModules command. You can call this command as part of your profile, if you want these modules loaded each time you run PowerShell.
Various places on the Internet state that it loads the available modules from C:\Windows\System32\WindowsPowerShell\v1.0\Modules. Among these are modules for managing IIS, Hyper-V, etc.
It turns out that it also loads snap-ins from C:\Users\rogerl\Documents\WindowsPowerShell\Snapins

However, according to another SO answer:

The -ImportSystemModules switch has no impact in v3, looks like it is going away.

And the Powershell changelog states for v6 beta 9 states the argument has been removed entirely:

Remove parameters -importsystemmodules and -psconsoleFile from powershell.exe. (#4995)

And indeed, running Get-Command ImportSystemModules on Powershell Core v6 cannot find the command anymore:
> Get-Command ImportSystemModules
Get-Command : The term 'ImportSystemModules' is not recognized as the name of a cmdlet, function, script file, or operable program.

As to why it's still there and defined in v5.1 and earlier? Perhaps it's for backwards compatibility, v2 compatibility was guaranteed for a long time.


text:
Q: Is it possible to have an user-interface and macros on sharepoint? Context
I'm making a project on a company that must have an user interface and a database or work directly over an excel. Also I need this on SharePoint.
Info
The problem is that in the company, users can't install nothing. That's why i want it in SharePoint, for example.
We use excels because periodically we receive an .csv with updates, we use that to work over another excel.
I read that the security of many sites dont't allow this. LINK. That's a problem beacuse here there is a lot of security so probably they won´t let me execute anything on SharePoint.
However, this says that I can run .exe if I am on IE with some JavaScript.
Question
So the question is if can I make for example a Visual or Java mini-interface that allows the user to access a excel and modify fields with some macros or directly with the program?
I am open-mind to use other method that permit working in a intranet on an user interface over a database.
Thanks!

A: "They're excels because periodically we receive an .csvwith updates, we use that to work over other excel. "
You could use the excel services module in SharePoint.  This would allow you to display a master Excel file on SharePoint that you would keep updated with your new csv information. Users could then copy the cell information by doing a ctl+c to paste information into their spreadsheets.


text:
Q: DataGridView Event to Catch When Cell Value Has Been Changed by User I have a Winforms app written in C#.
In one of my DataGridViews I have set all columns except one called 'Reference' to ReadOnly = true;
I want the application to know when a User has changed anything in the 'Reference' column, but all the events I have tried so far fire a lot more than when a user has made changes.  For example CurrentCellChanged fires when the DataGridView is initially rendered and everytime the user simply clicks or tabs along the rows etc.
I'm only interested in catching user changes to data in the 'Reference' column which is the ONLY column where ReadOnly = false;
Which is the best event to use for this?

A: CellValueChanged is what you need:
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e){
  if(dataGridView1.Columns[e.ColumnIndex].Name == "Reference"){
    //your code goes here
  }
}

I think the event CellEndEdit is also suitable for your want:
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e){
  if(dataGridView1.Columns[e.ColumnIndex].Name == "Reference"){
    //your code goes here
  }
}

A: In my case CellValueChanged event was also triggering while the DGV was initializing, so I wanted to use CellEndEdit, as King King mentioned in his answer.
To make King King's second answer more bullet-proof (see JPProgrammer's comment), i.e. only react, if a value was entered in the cell, you can do the following:
   private void DataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
   {
        int? rowIdx = e?.RowIndex;
        int? colIdx = e?.ColumnIndex;
        if (rowIdx.HasValue && colIdx.HasValue)
        {
            var dgv = (DataGridView)sender;
            var cell = dgv?.Rows?[rowIdx.Value]?.Cells?[colIdx.Value]?.Value;
            if (!string.IsNullOrEmpty(cell?.ToString()))
            {
                // your code goes here
            };
        };
   }

Notice the null handling by using ?. and ?[ operators. I have written it so that it can be used in a more general way, but of course you can add the check for the "Reference" column, just replace the inner if statement above by the following:
       if (dgv.Columns[colIdx.Value].Name == "Reference")
       {
          if (!string.IsNullOrEmpty(cell?.ToString()))
          {
               // your code goes here
          };
       };


text:
Q: How to generate a serie of date without create a new database object? I need to create a query which returns years and months from april 2013 to now like following:
2013  | 4
2013  | 5
2013  | 6
2013  | 7
2013  | 8
....  | .
....  | .
....  | .
2015  | 1
2015  | 2
2015  | 3
2015  | 4

It must works with SQLServer 2000, and all solution I found on SE are only SQLServer2005+ compatible.
Is there a way to do it with this (very) old SGBD?
If there is no solution I would consider to create a table of numbers but I don't find it really elegant...

A: declare @Startdate AS DateTime = Dateadd( year,-2,Getdate()) ,
        @EndDate DateTime = Getdate()
Declare @YearTable as Table ( CalYear int , calmonth int)

While @Startdate <= @EndDate
BEGIN
    Insert Into @YearTable values(YEAR(@Startdate),MONTH(@Startdate))
    set @Startdate = DateADD(Month,1,@Startdate)
END

select * from @YearTable


text:
Q: Android Sensor event always return AK8973 3-axis Magnetic field sensor I tried several time to get Sensor.TYPE_ACCELEROMETER, but it always return AK8973 3-axis Magnetic field sensor. When i shaking mobile device, it always return same AK8973 3-axis Magnetic field sensor. I registered inside resume method, here is code :
boolean supported = mSensorMgr.registerListener(this,
    mSensorMgr.getDefaultSensor(SensorManager.SENSOR_ACCELEROMETER),
    sensorManager.SENSOR_DELAY_GAME);

However, i couldn't get (sensor.getType() == Sensor.TYPE_ACCELEROMETER) inside onSensorChanged(SensorEvent event) method. I couldn't understand why it always return Magnetic field sensor.
Thank you

A: I solved problem, i mistake in
mSensorMgr.getDefaultSensor(SensorManager.SENSOR_ACCELEROMETER) instead of SensorManager.SENSOR_ACCELEROMETER, i change Sensor.TYPE_ACCELEROMETER and it works.


text:
Q: Prefetch_related failing against SQL Server Using Django 2.X, and Pyodbc driver (installed from anaconda conda-forge django-pyodbc-azure) against MS Sql Server (not sure which version), I regularly have bugs using prefetch_related. An example looks simply like:
for obj in MyORMType.objects.prefetch_related('otherormtype_set').all():
    pass

where OtherOrmType has a simple foreign key to MyOrmType, the error is:
...
/opt/conda/lib/python3.6/site-packages/django/db/backends/utils.py in _execute(self, sql, params, *ignored_wrapper_args)
     83                 return self.cursor.execute(sql)
     84             else:
---> 85                 return self.cursor.execute(sql, params)
     86
     87     def _executemany(self, sql, param_list, *ignored_wrapper_args):

/opt/conda/lib/python3.6/site-packages/sql_server/pyodbc/base.py in execute(self, sql, params)
    544         self.last_params = params
    545         try:
--> 546             return self.cursor.execute(sql, params)
    547         except Database.Error as e:
    548             self.connection._on_error(e)

ProgrammingError: ('The SQL contains -2098 parameter markers, but 128974 parameters were supplied', 'HY000')

I can fall back to the dumb equivalent:
for obj in MyORMType.objects.all():
    other_objs = obj.otherormtype_set.all()

but this is obviously quite slow. This bug occurs regularly for me under many different circumstances in this particular setup (always same Django version, driver, and DB), it's not a one-off annoyance. Is this my fault or an issue with SQL Server or Pyodbc (or Django)? Is there a way to work around the error without having to fetch each obj.otherormtype_set one at a time?

A: Under the hood the prefetch_related feature uses IN (...large number of IDs) queries to retrieve objects which seems to be a know issue with the django-pyodbc-azure package you are using.
You can find a bit more details on the Github issues of the package itself.

*

*https://github.com/michiya/django-pyodbc-azure/issues/101

*https://github.com/michiya/django-pyodbc-azure/issues/143
From a quick investigation it looks like .features.max_query_params will need to be adjusted which is what I suggested doing.
It looks like it could be a limitation similar to the SQLite one with regards to number of allowed parameters.


text:
Q: doc.save() throwing error with jspdf When I try and use the save() function for jsPDF it's throwing the following error:
ReferenceError: saveAs is not defined
I'm just trying a very simple example:
var doc = new jsPDF();
doc.text(20, 20, 'Hello world!');
doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.');
doc.addPage();
doc.text(20, 20, 'Do you like that?');

doc.save('test.pdf');

Anyone have any ideas what's wrong?

A: Found out what the issue was. The saveAs function is part of FileSaver.js so I just needed to include this and everything worked.

A: I don't have enough to comment yet, so I'm adding this as an answer... saveAs() is a w3c interface. If adding FileSaver fixed your issue, that means you were using an old browser; FileSaver.js is used as a shim for jsPDF to support older browsers that don't have that function natively.

A: You can also use jspdf.debug.js it contains all of the plugins in one file. This way you are covered if something else is needed.
-Cheers

A: <!DOCTYPE html>

    <meta charset="utf-8">
    <title>Hello world</title>

Hello world


text:
Q: Connecting to a CDMA network IN from Java Am using java to develop program that receives and processes SMS messages. I have been able to code the processing of the SMS Messages received and its working perfectly. Now the challenge i have is receiving the the SMS Messages from the CDMA network. When the application is about to go live, the CDMA network will setup a VPN connection which will enable my application to connect to its IN or its IN connect to my application to deliver the SMS Messages to my application over the VPN. Now, in what format will be SMS be sent to the application? Or will i just need to listen on the VPN and read data's when they become available? Thank you very much for your time.
Thanks.

A: I assume that by IN you mean Intelligent Network? Usually IN is not relevant for sending/receiving SMS messages - you need to connect to the Short Message Service Center (SMSC) (or some proxy/gateway) in order to do that.
As also pointed out by Bombe, there are several protocols that you can use to connect to the mobile operators SMSC, it is all quite vendor-specific, due to historic reasons. Common protocols are:

*

*SMPP (most popular, becoming the de-facto standard). There are two SMPP java libraries:

*

*SMPP API at SourceForge - very stable and mature library, I have personally used it in several projects and can recommend it.

*Logica OpenSMPP - library from the company that developed the SMPP specification. I have never used this, so I cannot comment on its maturity or stability.

*UCP (specification) - quite old standard. I'm not aware of any open java libraries for this protocol. However, as it is all ASCII-based, it is fairly easy to implement yourself (as long as you like messing with bytes :-)).

*CIMD2 - specification for communicating with Nokia SMSCs. It is becoming legacy, as I have heard that newer Nokia SMSC releases also support SMPP. No known open java libraries for this either.

*and finally, there are gazillions of custom protocols implemented to make it "easier" for 3rd-party developers to connect to SMSCs. These are usually based on HTTP and XML (SOAP, if you are lucky).

To sum up, the choice of protocol is not yours to make. It is usually dictated by the SMSC vendor or the mobile operator (in case they have developed some sort of "proxy/gateway", to shield their SMSC from potential programming errors that external developers can make).
P.S. in case you are not limited to java, you can also have a look at Kannel - the Open Source WAP and SMS gateway. I have not used it myself, but as far as I have heard, they should have all major protocols covered.

A: Different protocols like SMPP (1, 2), UCP (1, 2), or even HTTP can be employed to transfer SMS from one party to another. You need to check with your upstream provider what protocols they offer.

A: If the messages come into you over SMPP have a look at the SMPPAPI.
http://smppapi.sourceforge.net/
Talk to your mobile network they will tell you what format your messages will be delivered in.


text:
Q: Question on similar matrices and diagonalization. Let $A$ and $B$ be two $n\times n$ matrices with entries in a field $k$.
If $A$ and $B$ are similar, then can each one be obtained from the other via a combination of elementary row and column operations? Is the converse true?
I recall learning an equivalence relation on the set of $m \times n$ matrices with entries in $k$ that defined $Q$ and $P$ to be equivalent if they can be obtained from each other via combinations of elementary row and column operations, and I recall learning that this characterization is equivalent to saying there exists an invertible $m \times m$ matrix $U$ and an invertible $n\times n$ matrix $V$ such that $Q=UPV$. Is similarity the same relation restricted to the set of $n \times n$ matrices?

A: Any invertible matrix can be written as a product of elementary operations.  If you extend this arguement a bit, you'll see that, under the equivalence relation you've defined above, two matrices are equivalent if and only if they have the same rank.
If $A$ and $B$ are similar, then $A = M B M^{-1}$ for some invertible matrix $M$.  Thus, if two matrices are similar then they are equivalent under your relation.
However, most matrices that have the same rank are not similar.  From the Rational Canonical Form for Matrices, we know that every matrix is similar to a block diagonal matrix (called the Rational Canonical Form) where the blocks are the companion matrices of certian polynomials called invariant factors of the matrix.  Two matrices are similar if and only if they have the same rational canonical form up to reorderings of the blocks.  Equivalently, two matrices are similar if and only if they have the same multiset of invariant factors.  Thus, by choosing the invariant factors appropriately, we can construct matrices that have the same rank but are not similar.
If the field has more than two elements, then a simpler argument is possible since similar matrices must have the same multiset of eigenvalues.  However, we can choose diagonal matrices that have different sets of eigenvalues but still have the same rank.  (This corresponds to the case where the invariant factors are linear polynomials.)  The advantage of the above argument is that it works even for $\Bbb{F}_2$.

A: Not always. Note that if you could find similar matrices by simple row/column interchanges, then you could easily diagonalize a symmetric real matrix, which means you can easily find its eigenvalues. But finding eigenvalues is a strictly iterative method and cannot be done in polynomial number of steps, because if you could find all eigenvalues, it would essentially mean you could completely determine the roots of a polynomial of degree $n$, but by Abel-Ruffini theorem, there exists no closed form expression for the roots of a polynomial of degree greater than $4$.
But suppose $A$ is a scalar matrix then any row interchange and subsequent column interchange will give you only $A$, so $A$ is similar only to itself.


text:
Q: SQL Server showing values grouped in columns from rows based on specific field value I have this table of information
fk_studentID | fk_courseID | fk_educationalSemesterID | value
-------------+-------------+--------------------------+------
    1        |      1      |          1               |  18
    1        |      2      |          1               |  18
    1        |      3      |          1               |  14
    1        |      4      |          1               |  17
    1        |      5      |          1               |  14
    1        |      6      |          1               |  17
    1        |      8      |          1               |  18
    1        |      1      |          2               |  19
    1        |      2      |          2               |  19
    1        |      3      |          2               |  18
    1        |      4      |          2               |  15
    1        |      4      |          2               |  19
    1        |      5      |          2               |  20
    1        |      1      |          3               |  17
    1        |      8      |          3               |  20

Need to prepare output result as:
fk_studentID | fk_courseID | 1st Semester | 2nd Semester | 3rd Semester
-------------+-------------+--------------+--------------+-------------
    1        |       1     |     18       |     19       |     17
    1        |       2     |     18       |     19       |
    1        |       3     |     14       |     18       |
    1        |       4     |     17       |     15       |
    1        |       5     |     14       |     19       |
    1        |       6     |     17       |              |
    1        |       8     |     18       |     20       |     20

Please help

A: I think you are just looking for a standard pivot query:
SELECT fk_studentID,
       fk_courseID,
       MAX(CASE WHEN fk_educationalSemesterID = 1 THEN value END) AS 1st_semester,
       MAX(CASE WHEN fk_educationalSemesterID = 2 THEN value END) AS 2nd_semester,
       MAX(CASE WHEN fk_educationalSemesterID = 3 THEN value END) AS 3rd_semester
FROM yourTable
GROUP BY fk_studentID,
         fk_courseID


text:
Q: Losing decimal places in database lookup step I have a database lookup step that is retrieving 3 fields from a SQL Server table. One of the fields is a decimal (8,6). When retrieved, the field values appear to be integers, losing all decimal places. I have spent several hours trying to resolve this issue and have found a reference to using an alter step to ensure the decimal places are available.
In the database lookup step I have tried different data types (number, string etc.) and I've followed this with a select values step, where I'm altering the field to a number field with decimal places. Nothing has worked, so any help with what I'm sure should be a simple problem to solve would be greatly appreciated. Apologies if the answer is obvious and I've missed it.

A: The Group By step has a similar issue when the Sum function is used, it uses a new mask that rounds up the number, thuough in the Group By case it is just a mask. I usually fix it using a Select Values step, altering the meta-data to Number, precision 2, format 0.00 and expliciting the decimal sign, like so:

Note that the decimal sign shown in the format does not alter the decimal sign to a dot, it's just a mask.


text:
Q: How do I use two lists in one Django for tag? I have two letters that I would like to show in my template at the same time. How can I do it in the template the fastest and easiest way?
Where set_1 = A, B, C, D,
ser_2 = result from my django queryset
Is there something like the below? Any help will be appreciated
{% for b in set_1 and a in set_2 %}

{{ b }} - {{ a }}

{% endfor %}

EDIT:
How can I use this when my queryset returns a list of fields in my form, as in the view below?
views.py
def account(request):
    data_now = datetime.datetime.now().strftime("%Y-%m-%d")
    test = Time.objects.filter(day_time__day_name='Monday')
    #my form
    TimeFormSet = modelformset_factory(Time, fields=('free_or_no',), labels={'free_or_no': '*odznacz jeżeli zajęte',})

    if request.method == "POST":
        formset = TimeFormSet(
            request.POST,
            queryset=Time.objects.filter(day_time__day_name='Monday'),
        )
        if formset.is_valid():
            formset.save()
            return HttpResponseRedirect(reverse('app:account'))
    else:
        formset = TimeFormSet(queryset=Time.objects.filter(day_time__day_name='Monday'))

    list_form = zip(formset, test)

    context = {'data_now': data_now, 'time_edit_form': formset, 'test': test, 'list_form': list_form}
    return render(request, 'account.html', context)

If I do everything as in your link, my browser returns an error:
IntegrityError at /account/
NOT NULL constraint failed: app_time.time_equivalent

html file
<form action="." method="post">
    {% csrf_token %}
    {{ time_edit_form.management_form }}
        {% for item1, item2 in list_form %}

{{item2}} {{item1}}

        {% endfor %}
    <button type="submit" class="btn btn-block btn-primary"> ZapiszXXX</button>
</form>


text:
Q: Explanation of part of a Open Leontief proof This question is from my notes on Open Leontief Models. It talks about the consumption matrix C (a square matrix). All entries are less than 1 (in abs terms) and if the sum of each column is less than 1, then C is called a productive consumption matrix. (Every department "contributes") The theorem is to show that $(I-C)^{-1}$ also has only positive entries. Part of the proof relies on the necessary fact that $C^n→0$ for $n→$ infinity. This is to be shown without the use of eigenvalues and eigenvectors. My book says to assume the largest entry in $C$ to be $a$ and the largest column-sum to be $b$. Prove that the largest entry of $C^n$ is always less than $ab^{n-1}$ How do you do that in a layman's method? Any suggestions/explanation = welcome

A: Let $c_{ij}$ be the entries of $C\in \mathbb R^{m,m}$. We know $0\le c_{ij}\le a$ for all $i,j$. Moreover,
$$
\sum_{i=1}^m c_{ij} \le b<1
$$
for $i$.
The proof is by induction on $n$. The induction start $n=1$ is trivial.
Denote by $c_{ij,n}$ the $(i,j)$-entry of $C^n$. Note that all entries of $C^n$ are non-negative.
Now assume that for some $n$, the largest entry of $C^n$ is less than $ab^{n-1}$. Then the $(i,j)$-entry of $C^{n+1}$ can be estimated as
$$
0\le c_{ij,n+1} = \sum_{k=1}^m c_{ik,n}c_{kj}
\le ab^{n-1} \sum_{k=1}^m c_{kj}\le ab^{n-1} \cdot b = ab^n,
$$
which is the claim.

Now for $n\to \infty$ it follows that $C^n\to0$ since $0\le b<1$.


text:
Q: What is the best practice for displaying multiple views in Codeigniter? I'm trying to determine the best practice for calling multiple views from the same method in a controller.
Is it preferable in the controller to make one view call, then have that view call all the views it needs, or call all the views you need in sequence in the controller?
Example:
function index(){
   //set all data variables
   //then send them to the view
   $this->load->view($index_view, $data);
}

or
function index(){
  //set variables
  //then call each view
  $this->load->view($header_view, $header_data);
  $this->load->view($body_view, $body_data);
  $this->load->view($footer_view, $footer_data);

The Codeigniter guide shows both ways, but does not seem to advise to the best practice...is there one?

A: I didn't like the way of including the header/footer within the view, and I didn't like loading the footer and header each time in every single Controller function.
To fix this, I extended the Controller class with my own view display function.
<?php
// in application/libraries/MY_Controller.php
class MY_Controller extends Controller {
    function _displayPage($page, $data = array()) {
        $this->view->load('header', $data);
        $this->view->load($page, $data);
        $this->view->load('footer', $data);
    }
}
?>

// in application/controllers/home.php
<?php
class Home extends MY_Controller {
    function index() {
        $this->_displayPage('home/index', array('title' => 'Home'));
    }
}
?>

Not sure if this is CodeIgniter "best practice" but it makes sense to me.

A: I don't think there is a definitive answer for that. Choose one and stick with it, it's important to be consistent.
Anyway, I'd prefer the second one.

A: I would say that the controller should only display one view. Then it's up to the view if it wants to show a header, footer, sidebar or whatever. The controller shouldn't have to care, its job is to get data from a model and hand it to a view. Not decide if the view should have a header and a footer.

A: Agree with Christian Davén: its view / display logic not data or business / logic. essentially its the same as using php includes for snippets like navigation, footer etc. you're just embedding markup.

A: This is expected behavior.  Once variables are set they become available within the controller class and its view files.  Sending an array in $this->load->view() is the same as sending an array directly to $this->load->vars() before calling the view file.  This simplifies things for most people using multiple views in a controller.  If you are using multiple view files in a single controller and want them to each have their own set of variables exclusively, you'll need to manually clear out the $this->load->_ci_cached_vars array between view calls.
A code comment in the Loader class describes another situation showing why this is the desired default behavior:

*

*You can either set variables using the dedicated $this->load_vars()

*function or via the second parameter of this function. We'll merge

*the two types and cache them so that views that are embedded within

*other views can have access to these variables.


text:
Q: ERROR Uncaught throwable from user code: java.lang.IllegalStateException in spark Streaming I have 2 streaming query like bellow
val streamingQuery = injectableDependencies.writeStreamDfToDeltaFile(validDF, dataPath, checkPointPath, configuration.pollingTimerSeconds, queryName, configuration.outputMode, configuration.partitionBy)

//streamingQuery for Invalid tables
val streamingQueryInvalid = injectableDependencies.writeStreamDfToDeltaFile(inValidDF, dataPathInvalid, checkPointPath, configuration.pollingTimerSeconds, queryNameInvalid, configuration.outputMode, configuration.partitionBy)

//creating valid tables
injectableDependencies.createTableOverDeltaFile(configuration.tableName, configuration.databaseName, dataPath, streamingQuery)

//creating invalid tables
injectableDependencies.createTableOverDeltaFile("Invalid"+configuration.tableName, configuration.databaseName, dataPath, streamingQueryInvalid)

below i am trying to write streams
  df
  .writeStream
  .format("DELTA")
  .option("path", dataPath)
  .option("checkpointLocation", checkPointPath)
  .partitionBy(partitionBy.getOrElse(List[String]()): _*)
  .outputMode(outputMode)
  .trigger(Trigger.ProcessingTime(pollingTimerSeconds.seconds))
  .queryName(queryName)
  .start()

i am getting bellow error
ERROR Uncaught throwable from user code: java.lang.IllegalStateException: Cannot start query with id 74e6b948-bc55-419c-af42-34ef7ea015ba as another query with same id is already active. Perhaps you are attempting to restart a query from the checkpoint that is already active.

Can anybody please suggest what going wrong

A: I had the same issue and solved it by ensuring that each streaming query gets its dedicated checkpointLocation as option in the writeStream call.


text:
Q: Can I have multiple [mysqldump] sections in ~/.my.cnf? After reading the answers on MYSQLDUMP without the password prompt I was wondering :

Is it possible to store multiple credentials, to different db accounts, in one ~/.my.cnf file? If so, what is the syntax?

N.B.: I reckon that could rise security issues but that's strictly for local/dev environment.

A: Asking on IRC #mysql here is what I got:

MrAmmon | not really, no.  You can, if you like, have multiple files
  and reference them, though MrAmmon | example - mysql
  --defaults-file=~/.my.cnf-bobby

Solution

*

*Create a credentials file for your project ;

*Reference it when doing the dump (--defaults-file= must be the first option):

mysqldump --defaults-file="$HOME/.my.project.cnf" -u projectUser --no-create-db --no-create-info projectDb

Others options
There is several argument to control options:

--no-defaults: Don't read default options from any option file.
--defaults-file=#: Only read default options from the given file #.
--defaults-extra-file=#: Read this file after the global files are read.


text:
Q: react-script not returning function So I have a react-js script that I have a core/main.js and the main app.js file.
The data in main.js won't appear in the div "welcome" in app.js - when I call the function that should fire it.
main.js
import React from 'react';
import ReactDOM  from 'react-dom';

export default function tick() {
    const element = (

Hello, world!

It is {new Date().toLocaleTimeString()}.

    );
    // highlight-next-line
    ReactDOM.render(element, document.getElementById('welcome'));
  }

App.js
import React from 'react';
import tick from './core/Main.js'
//import logo from './logo.svg';
import './App.css';

function App() {
  return (

          {tick}

  );
}

export default App;

How can I get this to show? I am trying to better understand this type of functions.

A: You should turn your function tick into a component (e.g. Tick, just to name in properly):
export default function Tick() {
  return (

Hello, world!

It is {new Date().toLocaleTimeString()}.

  );
}

If you do this you can then use it like any other React component:
import React from "react";
import Tick from "./core/Main.js";
//import logo from './logo.svg';
import "./App.css";

function App() {
  return (

          <Tick />

  );
}

export default App;

If you want to stick to your original way of using tick as a function (e.g. if you have some special requirements) you need to actually call that function somewhere, preferably after the initial render of App, inside a useEffect:
import React from "react";
import tick from "./core/Main.js";
//import logo from './logo.svg';
import "./App.css";

function App() {
  React.useEffect(() => {
    tick();
  }, []);

  return (

  );
}

export default App;


text:
Q: how to calculate the area of $S=\{x\in\mathbb{R}|x_1^{2}+x_2^{2}+x_3=4 , 0\leq x_3\}$ How to calculate the area of $$S=\left\lbrace x\in\mathbb{R}:x_1^{2}+x_2^{2}+x_3=4 ,\, 0\leq x_3\right\rbrace$$
I think the difficulty(for me) is to parametrize this function. I thought that it would be smart to say that $x_1^{2}+x_2^{2}=4-x_3$ so I can get my parametrisation in a form of a circle-parametrization(though I see that the graph is a cone).
But then i think i get trouble with my $x_3$.
I think I am supposed to get something like: $x_1 = r\cos(\phi)$, $x_2 = r\sin(\phi)$, $x_3 = 4-r^{2}$
But when I calculate the area of this parametrisation I don't get the right answer so I'm doing something wrong.
Any hints,tricks?
Kees

A: So here is a method from single variable calculus that you can use. The surface you are given is a Surface of Revolution.
In fact, it is exactly what you obtain by taking the graph of the parabola $y = 4 - x^2$ on the $xy$-plane and revolving it around the $y$-axis.
If you do this, $y$ becomes $x_3$ in your problem.
The formula for the surface area of such an object is found in the link given above. You just need to use the correct bounds of integration.
The way I have things set up, it would be correct to use
$\displaystyle\int_c^d 2\pi x \sqrt{1 + \left(\dfrac{dx}{dy}\right)^2} dy$
which is equation (6) or (7) in the link. I would personally use a slight variant:
$\displaystyle\int_a^b 2\pi x \sqrt{1 + \left(\dfrac{dy}{dx}\right)^2} dx$
I can provide a more detailed answer if you'd like. Just let me know.


text:
Q: scheduled alarm to repeat every minute of the clock android I have an app which requires a code to be executed every minute. But the issue is that the code has to be executed at every minute change of the clock. Which means,
If its 12:34 then the code will execute at 12:35 and goes on. But my current code works but it includes the seconds. Meaning,
If its 12:34:30 and the alarm starts, the code is executed. But the code is then executed at 12:35:30.
I want the code to be executed each minute according to the clock of the phone. Below is the current code.
 Intent intent2 = new Intent(MainActivity.this, MyABService.class);
                PendingIntent pintent = PendingIntent.getService(MainActivity.this, 0, intent2, 0);
                AlarmManager alarm_manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                alarm_manager.setRepeating(AlarmManager.RTC, c.getTimeInMillis(), 1 * 1000, pintent);

Im making it execute every second so that the effect takes place at the exact time. Instead of having it every second i need it to repeat itself at every minute change of the clock (every minute)
How do i go about this

A: Use a Calendar to set the time to trigger to the next full minute, and repeat it every minute (60*1000ms)
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.MINUTE, 1);
calendar.set(Calendar.SECOND, 0);

long triggerAt = calendar.getTimeInMillis();
long repeatAfter = 60 * 1000;

alarm_manager.setRepeating(AlarmManager.RTC, triggerAt, repeatAfter, pintent);

A: Use Intent.ACTION_TIME_TICK This is a broadcast intent fired every minute by the Android OS. Register to it as you would register to a normal system broadcast in code (doesn't work from manifest)
tickReceiver=new BroadcastReceiver(){
    @Override
    public void onReceive(Context context, Intent intent) {
    if(intent.getAction().compareTo(Intent.ACTION_TIME_TICK)==0)
    {
      //do something
    }
  };

  //Register the broadcast receiver to receive TIME_TICK
  registerReceiver(tickReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));

This article describes the complete process.

A: Calendar calendar = Calendar.getInstance();
Intent intent = new Intent(context, AnyClass.class);
            PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
            AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
            alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 60*1000, pendingIntent);

Hope this code solved your problem

A: Use the Quartz Schedular API, make the corn job which run at every min.
 "0 0/1 * * * ?" // Corn expression run at  every min

Build the Schedular and trigger like that
     SchedulerFactory schedFact = new  org.quartz.impl.StdSchedulerFactory();

     Scheduler sched = schedFact.getScheduler();

     sched.start();

   // define the job and tie it to our HelloJob class
   JobDetail job = newJob(HelloJob.class)
  .withIdentity("myJob", "group1")
  .build();

  // Trigger the job to run now, and then every 1 min
    Trigger trigger =trigger = newTrigger()
    .withIdentity("trigger1", "group1")
    .withSchedule(cronSchedule("0 0/1 * * * ?"))
    .forJob("myJob", "group1")
    .build();

   // Tell quartz to schedule the job using our trigger
    sched.scheduleJob(job, trigger);

and write your code in HelloJob class
 public class HelloJob implements Job {

  public void execute(JobExecutionContext context)
  throws JobExecutionException;

 // Here you write your code which exceute on every min
}

A: You can use below code for your requirement,
    Calendar initialCalendar = Calendar.getInstance();
    initialCalendar.setTimeInMillis(System.currentTimeMillis());
    initialCalendar.set(Calendar.SECOND, 0);

    long triggerAtMillis = initialCalendar.getTimeInMillis();
    long intervalMillis = 60 * 1000;

    alarm_manager.setRepeating(AlarmManager.RTC, triggerAtMillis, intervalMillis, pintent);

A: You can use Intent.ACTION_TIME_TICK.
Broadcast Action: The current time has changed. Sent every minute. You cannot receive this through components declared in manifests, only by explicitly registering for it with Context.registerReceiver().
Source:https://developer.android.com/reference/android/content/Intent.html#ACTION_TIME_TICK
IntentFilter tickIntent = new IntentFilter(Intent.ACTION_TIME_TICK);
private BroadcastReceiver receiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context c, Intent i) {
        // perform per minute task
    }
};
registerReceiver(receiver, tickIntent);


text:
Q: How to pass a user instance in a class-based view

I would like to pass the user instance of the current user to a variable in a class-based view and feed it in a second step, within a python script, to a database table column defined as author = models.ForeignKey(User, on_delete=models.PROTECT). Related to that column I get the following integrity error: NOT NULL constraint failed.. From the traceback I can see that my variable loggedUser, which I had attributed self.request.user, is a SimpleLazyObject.

I have found another question similar to mine. But it discusses the issue related to functions - I am having difficulties to adapt the answers to my case of a class-based view.

How can I pass my user instance?
Thank you!

models.py
from django.db import models
from django.contrib.auth.models import User

class Data(models.Model):
    temperature = models.FloatField(max_length=5)
    author = models.ForeignKey(User, on_delete=models.PROTECT)

views.py
from . import apythonscript
from django.views.generic import TemplateView

class PlotGraphView(TemplateView):

    def get_context_data(self, **kwargs):
        loggedUser = self.request.user
        context['plot'] = apythonscript.putDataInDB(loggedUser)
        return context

apythonscript.py
from app.models import Data

def putDataInDB(loggedUser):
    mydata=json.loads(response)

    for line in mydata['feeds']:
    #    try:
        data_handle = Data(temperature=line['field1'], author=loggedUser,)
        data_handle.save()
    #    except:
    #        continue

traceback
link to traceback

A: to get the currently logged in user in Django, you can simply use, request.user. In CBV, request is a class object, so you should use self.request to access request data.
example
class PlotGraphView(LoginRequiredMixin, TemplateView):
    # your stuff

    def get_current_user(self):  # this is just a custom function, you don't
        return self.request.user

So, anywhere in the CBV's scope, you can access the current user by self.request.user


text:
Q: How to fix corrupted NTFS I was trying to backup my linux box (ext4) into an external NTFS HDD using rsync I got some failure errors and then I deleted the backup on External HDD using "rm -r" & "rm -rf" which was not able to delete all files/DIRs and there was some weird sounds coming out of HDD after this process (even if it was not mounted {Yes, I could still mount it} ) this happend couple of times (re-backup and delete again) then I pluged the device into an MS-Windows and  tried "chkdsk /f" which fixed the sound issue and created some folders/files named "found.000 to found.999" (I was not able to see them on windows even with the hidden option enabled) it was somehow a recovey of what I had tried to get rid of with rm -rf and at the end I decided to remove all found.000-999 folders using on linux with rm -rf.
Now neither on windows nor on linux Im not able to mount it, I can see the device using diskmgmt.msc on windows and using lsblk/fdisk on linux before the disaster it was an one partition HDD now its divided to 4-5!
However Its VERY IMPORTANT/VITAL to save the data
Here is some output
# fdisk -l /dev/sdc

Disk /dev/sdc: 1.8 TiB, 2000365289472 bytes, 3906963456 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x6e697373

Device     Boot      Start        End    Sectors   Size Id Type
/dev/sdc1  ?    1936269394 3772285809 1836016416 875.5G 4f QNX4.x 3rd part
/dev/sdc2  ?    1917848077 2462285169  544437093 259.6G 73 unknown
/dev/sdc3  ?    1818575915 2362751050  544175136 259.5G 2b unknown
/dev/sdc4  ?    2844524554 2844579527      54974  26.9M 61 SpeedStor

Partition table entries are not in disk order.

,
# ntfsfix -d /dev/sdc
Mounting volume... ntfs_mst_post_read_fixup_warn: magic: 0x00000000  size: 1024   usa_ofs: 0  usa_count: 65535: Invalid argument
Record 0 has no FILE magic (0x0)
Failed to load $MFT: Input/output error
FAILED
Attempting to correct errors... ntfs_mst_post_read_fixup_warn: magic: 0x00000000  size: 1024   usa_ofs: 0  usa_count: 65535: Invalid argument
Record 0 has no FILE magic (0x0)
Failed to load $MFT: Input/output error
FAILED
Failed to startup volume: Input/output error
Checking for self-located MFT segment... ntfs_mst_post_read_fixup_warn: magic: 0x00000000  size: 1024   usa_ofs: 0  usa_count: 65535: Invalid argument
OK
ntfs_mst_post_read_fixup_warn: magic: 0x00000000  size: 1024   usa_ofs: 0  usa_count: 65535: Invalid argument
Record 0 has no FILE magic (0x0)
Failed to load $MFT: Input/output error
Volume is corrupt. You should run chkdsk.

THANKS

A: I found a great opensource tool called testdisk & followed this tutorial AND YES It put a fresh spirit upon the HDD

A: I/O

Input/output error

That may suggest a hardware problem with the drive and/or disk.
If there's a problem at either of those levels then it may be inadvisable to attempt repair of the file system.
Record … has no FILE magic
Amongst the responses to Tuxera Support - View topic - Record 6 has no FILE magic: Input/output error (2008-02-18) was this, from the CTO of Tuxera:

0x44414142= "DAAB" which is little-endian, so it should be read from the right, that is "BAAD".
The BAAD file magic on the disc refers to hardware problems (bad sectors), exactly as I suspected.
A reformat could help temporarily but your data will never be safe until the disk gets replaced with a reliable one.
Sorry for the bad news, good luck with the replacement.


text:
Q: font problem in photoshop used via playonlinux I had installed Photoshop under Playonlinux , but i got a problem with fonts in the dialog; for example when i want to create a new PSD document as shown:

I had searched in google for a solution , and i had seen many people said that they resolved the problem by installing Microsoft fonts but i din't find it.

A: To fix this open Terminal using (Ctrl+Alt+T) and type the below:
sudo apt-get install msttcorefonts

Reopen Photoshop and it should work. This basically installs the Standard Microsoft Fonts onto your computer and configures them in wine.


text:
Q: Python return corresponding cell with time data between 2 values Currently I am in the process of writing some software to do data analysis. I have had a little issue with my code and now some of the data is corrupted with wrong time values. I would like python to find the rows of data where the time value is between 00:00:00 and 03:59:00 and return to me the corresponding 'Ticker' and 'Exchange' value from the same row, but unfortunately I am having issues accomplishing this and was hoping someone on here could help me out.
Example data frame:
   Ticker Exchange      Date      Time
0    AAPL   NASDAQ  20200501  01:00:00
1    AAPL   NASDAQ  20200501  02:00:00
2    AAPL   NASDAQ  20200501  03:00:00
3    AAPL   NASDAQ  20200502  01:00:00
4    AAPL   NASDAQ  20200502  02:00:00
5    AAPL   NASDAQ  20200502  03:00:00
6    TSLA   NASDAQ  20200501  05:00:00
7    TSLA   NASDAQ  20200501  06:00:00
8    TSLA   NASDAQ  20200501  07:00:00
9    TSLA   NASDAQ  20200502  05:00:00
10   TSLA   NASDAQ  20200502  06:00:00
11   TSLA   NASDAQ  20200502  07:00:00

Example output:
  Ticker Exchange
0   AAPL   NASDAQ

In this case, 'AAPL' stock from 'NASDAQ' exchange has time values between 00:00:00 and 03:59:00 and therefore python should return to me the ticker and the exchange.
I hope I was able to make myself clear and that someone on here can help me out.
Example code for copy paste:
import pandas as pd

df1 = pd.DataFrame({'Ticker': ['AAPL', 'AAPL', 'AAPL', 'AAPL', 'AAPL', 'AAPL','TSLA', 'TSLA', 'TSLA', 'TSLA', 'TSLA', 'TSLA'],
                'Exchange': ['NASDAQ','NASDAQ','NASDAQ','NASDAQ','NASDAQ','NASDAQ','NASDAQ','NASDAQ','NASDAQ','NASDAQ','NASDAQ','NASDAQ'],
                'Date': [20200501, 20200501, 20200501, 20200502, 20200502, 20200502, 20200501, 20200501, 20200501, 20200502, 20200502, 20200502],
                'Time': ['01:00:00','02:00:00','03:00:00','01:00:00','02:00:00','03:00:00','05:00:00','06:00:00','07:00:00','05:00:00','06:00:00','07:00:00',]})
print(df1)

output = pd.DataFrame({'Ticker': ['AAPL'],
                'Exchange': ['NASDAQ']})

print(output)

#Code from MaKaNu that results in error: "TypeError: cannot astype a datetimelike from [datetime64[ns]] to [int32]"

minimal = pd.DataFrame({'time': [pd.to_datetime('00:00:00')]})
maximal = pd.DataFrame({'time': [pd.to_datetime('03:59:00')]})

#The lines below give the error
minimal = pd.to_datetime(minimal['time']).astype(int) / 10**9
maximal = pd.to_datetime(maximal['time']).astype(int) / 10**9

df_unix_sec = pd.to_datetime(df1['Time']).astype(int) / 10**9

series = df_unix_sec.between(minimal[0], maximal[0])
result = df1.loc[series == True][['Ticker', 'Exchange']].loc[0]
print(result)

A: To look between your two conditions you first step is to create number values out of your string. To be continous I created two small dataframe with just the min and the max values
minimal = pd.DataFrame({'time': [pd.to_datetime('0:00:00')]})
maximal = pd.DataFrame({'time': [pd.to_datetime('3:59:00')]})

than used the function pd.to_datetime and set it as integer and devided by 10 to the power 9 to create reasonable values.
minimal = pd.to_datetime(minimal['time']).astype(int) / 10**9
maximal = pd.to_datetime(maximal['time']).astype(int) / 10**9

Next step is to do the same with the column 'Time' in the original dataframe.
df_unix_sec = pd.to_datetime(df1['Time']).astype(int) / 10**9

As a last step I used the built-in function between and used the first entry from minimal and maximal as arguments.
print(df_unix_sec.between(minimal[0], maximal[0]))

The Result which I printed is a pandas series with Boolean values:
0      True
1      True
2      True
3      True
4      True
5      True
6     False
7     False
8     False
9     False
10    False
11    False
Name: Time, dtype: bool

As you can see all the values between your condition are True.
Now we just save this series and use them as a mask for our original dataframe.
series = df_unix_sec.between(minimal[0], maximal[0])
print(df1.loc[series == True])

The result looks like this:
  Ticker Exchange      Date      Time
0   AAPL   NASDAQ  20200501  01:00:00
1   AAPL   NASDAQ  20200501  02:00:00
2   AAPL   NASDAQ  20200501  03:00:00
3   AAPL   NASDAQ  20200502  01:00:00
4   AAPL   NASDAQ  20200502  02:00:00
5   AAPL   NASDAQ  20200502  03:00:00

And if you just need the example outpout from your question:
result = df1.loc[series == True][['Ticker', 'Exchange']].loc[0]
print(result)

Result:
Ticker        AAPL
Exchange    NASDAQ
Name: 0, dtype: object


text:
Q: Ruby group_by values as resource collection I have Record model.
record.rb
scope :some_record_scope ...

I can use this scope on model Record.some_record_scope
But i need grouped this model by hour (for example). And after use each value with some scopes as Record`s collection.
My code:
records = Record.all.order(:created_at)
grouped_records = records.group_by{ |r| r.created_at.strftime('%H') }

grouped_records.each do |interval, collection|
  collection.some_record_scope
  ...
end

But i see error:
NoMethodError: undefined method `some_record_scope' for #<Array:0x007fbb4d104b30>

How i can use it as collection?

A: Record.some_record_scope.order(:created_at).group_by {|r| r.created_at.strftime('%H') }

A: To add more information and explanation to the above answer, the reason your getting the error is because you have called .all and .group_by before calling the scope, the previous answers:
Record.some_record_scope.order(:created_at).group_by {|r| r.created_at.strftime('%H') }

works because some_record_scope is being called on the ActiveRelation object as it should be,
and in terms of multiple scopes, I think you can just chain the scope references like Record.some_scope.another_scope.order......


text:
Q: I miss Management Tools features when installing in SQL Server 2016 I downloaded SQL Server 2016 and try to install but when selected feature I don't know why but I cant find Management Tools in Features I searched a lot but I cant find any solution.

I know after "Documentation Components" should be Management Tools but it doesn't?
I uninstalled SQL Server 2014 before installing this.

A: It was decoupled from SQL Server setup to allow for different servicing model and different update frequency. It can be now downloaded and installed independently of SQL Server.


text:
Q: Issue with recursion in Assembly: Coding Minesweeper So right now I am attempting to code minesweeper for a class. The part that I am stuck on is attempting to update all the grid after a user clicks on a blank tile.
Unfortunately whenever I try to run my code it just crashes. Can anyone help?
whitespaceClick PROC uses eax ebx ecx esi edi
call convertXYval
mov GridValues[eax], 250
call updateSurroundings

mov edi, 0
call clearAroundArray
call fillAroundArray

cmp edi, 0 ;if no spaces around it
je done
mov ecx, 8
mov esi, 0

store:
  cmp aroundArray[esi], 3
  jne skp
    mov bh, aroundArrayX[esi]
    mov bl, aroundArrayY[esi]
    push bx
  skp:
  inc esi
loop store

mov eax, 0
mov ecx, edi
update:
  pop ax
  mov X, ah
  mov Y, al
  call whitespaceClick
loop update
Done:
ret
whitespaceClick ENDP

Notes:

*

*X and Y are variables of type BYTE that are used to keep track of the current location

*convertXYval is a procedure that converts the x,y values into a single value that corresponds to the location in an array

*fillAroundArray will fill an 8 element array with values (0,1,2,3) and also returns the number of spaces surrounding the current location in edi

*whitespaceClick updates the surrounding values to numbers if they are touching bombs

A: Both loops will iterate the same number of times only if fillAroundArray knows that white space is encoded with number 3. To verify...
 whitespaceClick PROC uses eax ebx ecx esi edi

Does tagging your procedure with uses ... automatically means that those registers are preserved?
If it doesn't then you need to save/restore the value of the loop counter around your recursive call.
 mov  Y, al
 push ecx
 call whitespaceClick
 pop  ecx
loop update

In 16-bit code using ECX for a small loop counter would be silly. So I conclude this is 32-bit code and then I would advice to change both push bx and pop ax into dword variants. This would maintain a dword aligned stack throughout those recursive calls.