问:
How to use equal condition in Handelbars (HBS) with each condition?
I am using Handlebar and try to use if condition with equal like if(value.A==value.B).

Below is the code where i am trying this.

```<code><div>
    {{#each Data}}
     {{#ifCond value.A value.B}}
               <tr>
            <td>{{value.C}}</td>
            <td>{{value.D}}</td>
            <td>{{value.E}}</td>

        </tr>
     {{/ifCond}}
    {{/each}}
</div>
</code>```

I have used below code but it is giving TypeError: hbs.registerHelper is not a function

The code is in app.js :-

```<code>var expressHbs =  require('express-handlebars');

app.engine('.hbs', expressHbs.engine({ defaultLayout: 'layout', extname: '.hbs'}));
app.set('view engine', '.hbs');

var hbs = expressHbs.create({});
hbs.registerHelper('ifCond', function(v1, v2, options) {
    if(v1 === v2) {
      return options.fn(this);
    }
    return options.inverse(this);
  });
</code>```

答:
There are a few problems here.

First, as your error indicates, registerHelper is not a function on the instance object returned by expressHbs.create({}). The returned object is an instance of an ExpressHandlebars object and this is not the same thing as the Handlebars library which has a registerHelper function.

The way to register helpers on an instance of ExpressHandlebars is via the configuration object passed to .create():

```<code>var hbs = expressHbs.create({
  helpers: {
    ifCond(v1, v2, options) {
      if (v1 === v2) { return options.fn(this); }
      return options.inverse(this);
    },
  }
});

</code>```

Unfortunately, this change alone will not suffice. It will lead to the Error:

Missing helper: "ifCond"

The issue here is that we have created the ifCond helper on the hbs instance, but the hbs instance is not the one we are setting as our Express View Engine.

Our Express View Engine is set with the result of a call to expressHbs.engine with some configuration properties.

Express-Handlebars gives us the option of using the .engine function to construct an engine object or the .create function to create instances of ExpressHandlebars, each with its own .engine object.

In your example, you are not doing anything with the hbs instance. Your helpers need to be added to the configuration passed in your expressHbs.engine call:

```<code>app.engine(
  ".hbs",
  expressHbs.engine({
    defaultLayout: "layout",
    extname: ".hbs",
    helpers: {
      ifCond(v1, v2, options) {
        if (v1 === v2) { return options.fn(this); }
        return options.inverse(this);
      },
    },
  })
);
</code>```

var hbs = expressHbs.create({}); can be removed.

Body:
I am using Handlebar and try to use if condition with equal like if(value.A==value.B).

Below is the code where i am trying this.

    {{#each Data}}
     {{#ifCond value.A value.B}}

            {{value.C}}
            {{value.D}}
            {{value.E}}

     {{/ifCond}}
    {{/each}}

I have used below code but it is giving TypeError: hbs.registerHelper is not a function

The code is in app.js :-

var expressHbs =  require('express-handlebars');

app.engine('.hbs', expressHbs.engine({ defaultLayout: 'layout', extname: '.hbs'}));
app.set('view engine', '.hbs');

var hbs = expressHbs.create({});
hbs.registerHelper('ifCond', function(v1, v2, options) {
    if(v1 === v2) {
      return options.fn(this);
    }
    return options.inverse(this);
  });

Body:
There are a few problems here.

First, as your error indicates, registerHelper is not a function on the instance object returned by expressHbs.create({}). The returned object is an instance of an ExpressHandlebars object and this is not the same thing as the Handlebars library which has a registerHelper function.

The way to register helpers on an instance of ExpressHandlebars is via the configuration object passed to .create():

var hbs = expressHbs.create({
  helpers: {
    ifCond(v1, v2, options) {
      if (v1 === v2) { return options.fn(this); }
      return options.inverse(this);
    },
  }
});

Unfortunately, this change alone will not suffice. It will lead to the Error:

Missing helper: "ifCond"

The issue here is that we have created the ifCond helper on the hbs instance, but the hbs instance is not the one we are setting as our Express View Engine.

Our Express View Engine is set with the result of a call to expressHbs.engine with some configuration properties.

Express-Handlebars gives us the option of using the .engine function to construct an engine object or the .create function to create instances of ExpressHandlebars, each with its own .engine object.

In your example, you are not doing anything with the hbs instance. Your helpers need to be added to the configuration passed in your expressHbs.engine call:

app.engine(
  ".hbs",
  expressHbs.engine({
    defaultLayout: "layout",
    extname: ".hbs",
    helpers: {
      ifCond(v1, v2, options) {
        if (v1 === v2) { return options.fn(this); }
        return options.inverse(this);
      },
    },
  })
);

var hbs = expressHbs.create({}); can be removed.


来源: stackexchange

问:
store.connect(imap.gmail.com, email, pass) can't connect to host, port imap.gmail.com, 993; timeout -1;
I'm trying to create an app to send and receive emails, but whenever I run it in my emulator I get this error:
System.err: com.sun.mail.util.MailConnectException: Couldn't connect to host, port: imap.gmail.com, 993; timeout -1; Using socket factory class javax.net.ssl.SSLSocketFactory;

I have checked my firewall and it doesn't block any ports as far as I can tell.
This code is not in the main activity and the user email and password are transfered in extras.
Any help would be appreciated.

```<code>private Adapter adapter = new Adapter(this);

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    final LinearLayout Activity_Email = findViewById(R.id.LinearLayout_ActivityEmail);
    final LinearLayout Activity_Main = findViewById(R.id.LinearLayout_ActivityMain);

    final Button Button_NewEmail = findViewById(R.id.Button_NewEmail);
    final Button Button_UserProfile = findViewById(R.id.Button_UserProfile);
    final Button Button_Contacts = findViewById(R.id.Button_Contacts);
    final Button Button_ProfileFolders = findViewById(R.id.Button_ProfileFolders);
    final Button Button_Settings = findViewById(R.id.Button_Settings);

    ListView ListView_Emails = findViewById(R.id.ListView_EmailList);
    final EditText EditText_Filter = findViewById(R.id.EditText_EmailFilter);

    final Bundle extras = getIntent().getExtras();

    Properties properties = System.getProperties();
    properties.put("mail.store.protocol", "imaps");
    properties.put("mail.imaps.port", "993");

    properties.setProperty("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    properties.setProperty("mail.imaps.socketFactory.fallback", "false");

    Session imapSession = Session.getInstance(properties);

    Thread thread = new Thread()
    {
        @Override
        public void run()
        {
            try {
                System.out.println("\nGetting store\n");
                Folder inbox;
                System.out.println("\nConnecting store\n");
                Store store = imapSession.getStore("imaps");
                System.out.println("\nGetting folder\n");

                store.connect("imap.gmail.com", extras.getString("USER_EMAIL"), extras.getString("PASSWORD"));
                inbox=store.getFolder("Inbox");

                inbox.open(Folder.READ_ONLY);
                Message messages[] = inbox.getMessages();

                int numberOfEmails = messages.length;
                for(int i = 0; i < numberOfEmails; i++)
                {
                    List_Email new_email = new List_Email(Arrays.toString(messages[i].getFrom()), extras.getString("USER_EMAIL"), messages[i].getSubject(), messages[i].getContent().toString());
                    adapter.addList_Email(new_email);
                }
            } catch (MessagingException e) {
                System.out.println("Prekid ovde Message\n");
                e.printStackTrace();
            } catch (IOException e) {
                System.out.println("Prekid ovde IO\n");
                e.printStackTrace();
            }
        }
    };
    thread.run();

    ListView_Emails.setAdapter(adapter);

    ListView_Emails.setOnItemClickListener(new MyOnItemClickListener());

    Button_NewEmail.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(Emails_Activity.this, NewEmailActivity.class);

            intent.putExtra("USER_EMAIL", extras.getString("USER_EMAIL"));
            intent.putExtra("PASSWORD", extras.getString("PASSWORD"));

            startActivity(intent);
        }
    });

    Button_ProfileFolders.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(Emails_Activity.this, FoldersActivity.class);
            startActivity(intent);
        }
    });
}

private class MyOnItemClickListener implements AdapterView.OnItemClickListener {

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Bundle extras =getIntent().getExtras();
        List_Email mail = (List_Email) adapter.getItem(position);
        Intent intent = new Intent(Emails_Activity.this, EmailActivity.class);

        String senderEmail = mail.Sender;
        String title = mail.Title;
        String content = mail.Content;

        intent.putExtra("Sender", senderEmail);
        intent.putExtra("Title", title);
        intent.putExtra("Content", content);

        startActivity(intent);
    }
}
</code>```

}

In case it is needed, here is the AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/Theme.MyEmailApp2">
    <activity android:name=".Emails_Activity">
    </activity>
    <activity android:name=".EmailActivity">
    </activity>
    <activity android:name=".NewEmailActivity">
    </activity>
    <activity android:name=".LoginActivity">
    </activity>
    <activity android:name=".FoldersActivity">
    </activity>
    <activity android:name=".MainActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</code>```

Here is the output in the Run tab when I get to the error while running the app on the emulator:

```<code>D/EGL_emulation: eglMakeCurrent: 0xda01a360: ver 3 1 (tinfo 0xda00f800)
I/chatty: uid=10135(com.example.myemailapp2) RenderThread identical 3 lines
D/EGL_emulation: eglMakeCurrent: 0xda01a360: ver 3 1 (tinfo 0xda00f800)
D/OpenGLRenderer: endAllActiveAnimators on 0xc299ab80 (RippleDrawable) with handle 0xda00fa50
D/EGL_emulation: eglMakeCurrent: 0xda01a360: ver 3 1 (tinfo 0xda00f800)
W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy@8318084
I/System.out: Getting store
I/System.out: Connecting store
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
I/System.out: Prekid ovde Message
W/System.err: com.sun.mail.util.MailConnectException: Couldn't connect to host, port: imap.gmail.com, 993; timeout -1; Using socket factory class javax.net.ssl.SSLSocketFactory;
  nested exception is:
    android.os.NetworkOnMainThreadException
W/System.err:     at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:735)
    at javax.mail.Service.connect(Service.java:366)
    at javax.mail.Service.connect(Service.java:246)
    at com.example.myemailapp2.Emails_Activity$1.run(Emails_Activity.java:79)
    at com.example.myemailapp2.Emails_Activity.onCreate(Emails_Activity.java:107)
    at android.app.Activity.performCreate(Activity.java:7802)
    at android.app.Activity.performCreate(Activity.java:7791)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
    at android.os.Handler.dispatchMessage(Handler.java:107)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7356)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
W/System.err: Caused by: android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1565)
    at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:115)
    at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:103)
    at java.net.InetAddress.getByName(InetAddress.java:1106)
    at java.net.InetSocketAddress.<init>(InetSocketAddress.java:235)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:352)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:217)
    at com.sun.mail.iap.Protocol.<init>(Protocol.java:124)
    at com.sun.mail.imap.protocol.IMAPProtocol.<init>(IMAPProtocol.java:128)
    at com.sun.mail.imap.IMAPStore.newIMAPProtocol(IMAPStore.java:758)
    at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:693)
    ... 19 more
D/EGL_emulation: eglMakeCurrent: 0xda01a360: ver 3 1 (tinfo 0xda00f800)
D/EGL_emulation: eglMakeCurrent: 0xda01a360: ver 3 1 (tinfo 0xda00f800)
</code>```

答:
Your full stack trace shows the problem:

```<code>nested exception is:
    android.os.NetworkOnMainThreadException
</code>```

You may not do any networking on the main thread of your android application.  You must create a worker thread or similar and do it there.

The documentation for the NetworkOnMainThread exception further describes the problem and links to a document about why and how to deal with it.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to create an app to send and receive emails, but whenever I run it in my emulator I get this error:
System.err: com.sun.mail.util.MailConnectException: Couldn't connect to host, port: imap.gmail.com, 993; timeout -1; Using socket factory class javax.net.ssl.SSLSocketFactory;

I have checked my firewall and it doesn't block any ports as far as I can tell.
This code is not in the main activity and the user email and password are transfered in extras.
Any help would be appreciated.

private Adapter adapter = new Adapter(this);

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    final LinearLayout Activity_Email = findViewById(R.id.LinearLayout_ActivityEmail);
    final LinearLayout Activity_Main = findViewById(R.id.LinearLayout_ActivityMain);

    final Button Button_NewEmail = findViewById(R.id.Button_NewEmail);
    final Button Button_UserProfile = findViewById(R.id.Button_UserProfile);
    final Button Button_Contacts = findViewById(R.id.Button_Contacts);
    final Button Button_ProfileFolders = findViewById(R.id.Button_ProfileFolders);
    final Button Button_Settings = findViewById(R.id.Button_Settings);

    ListView ListView_Emails = findViewById(R.id.ListView_EmailList);
    final EditText EditText_Filter = findViewById(R.id.EditText_EmailFilter);

    final Bundle extras = getIntent().getExtras();

    Properties properties = System.getProperties();
    properties.put("mail.store.protocol", "imaps");
    properties.put("mail.imaps.port", "993");

    properties.setProperty("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    properties.setProperty("mail.imaps.socketFactory.fallback", "false");

    Session imapSession = Session.getInstance(properties);

    Thread thread = new Thread()
    {
        @Override
        public void run()
        {
            try {
                System.out.println("\nGetting store\n");
                Folder inbox;
                System.out.println("\nConnecting store\n");
                Store store = imapSession.getStore("imaps");
                System.out.println("\nGetting folder\n");

                store.connect("imap.gmail.com", extras.getString("USER_EMAIL"), extras.getString("PASSWORD"));
                inbox=store.getFolder("Inbox");

                inbox.open(Folder.READ_ONLY);
                Message messages[] = inbox.getMessages();

                int numberOfEmails = messages.length;
                for(int i = 0; i < numberOfEmails; i++)
                {
                    List_Email new_email = new List_Email(Arrays.toString(messages[i].getFrom()), extras.getString("USER_EMAIL"), messages[i].getSubject(), messages[i].getContent().toString());
                    adapter.addList_Email(new_email);
                }
            } catch (MessagingException e) {
                System.out.println("Prekid ovde Message\n");
                e.printStackTrace();
            } catch (IOException e) {
                System.out.println("Prekid ovde IO\n");
                e.printStackTrace();
            }
        }
    };
    thread.run();

    ListView_Emails.setAdapter(adapter);

    ListView_Emails.setOnItemClickListener(new MyOnItemClickListener());

    Button_NewEmail.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(Emails_Activity.this, NewEmailActivity.class);

            intent.putExtra("USER_EMAIL", extras.getString("USER_EMAIL"));
            intent.putExtra("PASSWORD", extras.getString("PASSWORD"));

            startActivity(intent);
        }
    });

    Button_ProfileFolders.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(Emails_Activity.this, FoldersActivity.class);
            startActivity(intent);
        }
    });
}

private class MyOnItemClickListener implements AdapterView.OnItemClickListener {

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Bundle extras =getIntent().getExtras();
        List_Email mail = (List_Email) adapter.getItem(position);
        Intent intent = new Intent(Emails_Activity.this, EmailActivity.class);

        String senderEmail = mail.Sender;
        String title = mail.Title;
        String content = mail.Content;

        intent.putExtra("Sender", senderEmail);
        intent.putExtra("Title", title);
        intent.putExtra("Content", content);

        startActivity(intent);
    }
}

}

In case it is needed, here is the AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/Theme.MyEmailApp2">
    <activity android:name=".Emails_Activity">
    </activity>
    <activity android:name=".EmailActivity">
    </activity>
    <activity android:name=".NewEmailActivity">
    </activity>
    <activity android:name=".LoginActivity">
    </activity>
    <activity android:name=".FoldersActivity">
    </activity>
    <activity android:name=".MainActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Here is the output in the Run tab when I get to the error while running the app on the emulator:

D/EGL_emulation: eglMakeCurrent: 0xda01a360: ver 3 1 (tinfo 0xda00f800)
I/chatty: uid=10135(com.example.myemailapp2) RenderThread identical 3 lines
D/EGL_emulation: eglMakeCurrent: 0xda01a360: ver 3 1 (tinfo 0xda00f800)
D/OpenGLRenderer: endAllActiveAnimators on 0xc299ab80 (RippleDrawable) with handle 0xda00fa50
D/EGL_emulation: eglMakeCurrent: 0xda01a360: ver 3 1 (tinfo 0xda00f800)
W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy@8318084
I/System.out: Getting store
I/System.out: Connecting store
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
I/System.out: Prekid ovde Message
W/System.err: com.sun.mail.util.MailConnectException: Couldn't connect to host, port: imap.gmail.com, 993; timeout -1; Using socket factory class javax.net.ssl.SSLSocketFactory;
  nested exception is:
    android.os.NetworkOnMainThreadException
W/System.err:     at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:735)
    at javax.mail.Service.connect(Service.java:366)
    at javax.mail.Service.connect(Service.java:246)
    at com.example.myemailapp2.Emails_Activity$1.run(Emails_Activity.java:79)
    at com.example.myemailapp2.Emails_Activity.onCreate(Emails_Activity.java:107)
    at android.app.Activity.performCreate(Activity.java:7802)
    at android.app.Activity.performCreate(Activity.java:7791)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
    at android.os.Handler.dispatchMessage(Handler.java:107)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7356)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
W/System.err: Caused by: android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1565)
    at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:115)
    at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:103)
    at java.net.InetAddress.getByName(InetAddress.java:1106)
    at java.net.InetSocketAddress.<init>(InetSocketAddress.java:235)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:352)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:217)
    at com.sun.mail.iap.Protocol.<init>(Protocol.java:124)
    at com.sun.mail.imap.protocol.IMAPProtocol.<init>(IMAPProtocol.java:128)
    at com.sun.mail.imap.IMAPStore.newIMAPProtocol(IMAPStore.java:758)
    at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:693)
    ... 19 more
D/EGL_emulation: eglMakeCurrent: 0xda01a360: ver 3 1 (tinfo 0xda00f800)
D/EGL_emulation: eglMakeCurrent: 0xda01a360: ver 3 1 (tinfo 0xda00f800)

Body:
Your full stack trace shows the problem:

nested exception is:
    android.os.NetworkOnMainThreadException

You may not do any networking on the main thread of your android application.  You must create a worker thread or similar and do it there.

The documentation for the NetworkOnMainThread exception further describes the problem and links to a document about why and how to deal with it.


问:
Are there any compression and encryption libraries in C#?
I want to compress some files (into the ZIP format) and encrypt them if possible using C#. Is there some way to do this?

Can encryption be done as a part of the compression itself?

答:
There isn't anything you can use directly in C#, however you can use some libraries from J# to do it for you:

http://msdn.microsoft.com/en-us/magazine/cc164129.aspx

Should do just what you want?

With regards to the encryption, have a look at these links:

http://www.codeproject.com/KB/security/fileencryptdecrypt.aspx

http://www.obviex.com/samples/EncryptionWithSalt.aspx

OwnerDisplayName: Niyaz

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Mark Ingram


问:
Lock someone to a particular domain
We have a dll that is a plug-in for a asp.net shopping cart software that customers can purchase. However, we want to lock that dll to a particular domain for security reasons and we don't want them to be able to read that dll or use that dll in another domain they may have. How can we do this?</p>

答: The DLL could look at the incoming request's host header.</p>

OwnerDisplayName: jumbojs

Title: Lock someone to a particular domain

OwnerDisplayName: David


问:
How to write condition in struct
Based on condition, how to set Array of Dictionary else only Dictionary for struct.

```<code>   struct Data {
        let id: String?
        let name: String?
        let subData:  Environment.Dev == "Dev_URL" ? [SubData]? : SubData?

        init(_ json: JSON) {
            id = json["id"].stringValue
            name = json["name"].stringValue
            subData =  Environment.Dev == "Dev_URL" ? json["sub_data"].arrayValue.map { SubData($0) } : SubData(json["sub_data"])
        }
    }
</code>```

// SubData Struct

```<code>   struct SubData {
        let id: String?
        init(_ json: JSON) {
            id = json["id"].stringValue
   }
}
</code>```

My response structure changes due to environment changes.

How to set struct Data for let subData [SubData] i.e array of dictionary else SubData normal dictionary based on Dev or other.

答:
An easy way to make it array in both cases as type can't be determined at runtime

```<code>let subData:[SubData]?
</code>```

Then

```<code>subData =  Environment.Dev == "Dev_URL"
            ? json["sub_data"].arrayValue.map { SubData($0) }
            : [SubData(json["sub_data"])]
</code>```

Also you can change your response sub_data to be an array in both cases so above line be

```<code>subData = json["sub_data"].arrayValue.map { SubData($0) }
</code>```

That way you work in development and release smoothly

Title: How to write condition in struct

Body:
Based on condition, how to set Array of Dictionary else only Dictionary for struct.

   struct Data {
        let id: String?
        let name: String?
        let subData:  Environment.Dev == "Dev_URL" ? [SubData]? : SubData?

        init(_ json: JSON) {
            id = json["id"].stringValue
            name = json["name"].stringValue
            subData =  Environment.Dev == "Dev_URL" ? json["sub_data"].arrayValue.map { SubData($0) } : SubData(json["sub_data"])
        }
    }

// SubData Struct

   struct SubData {
        let id: String?
        init(_ json: JSON) {
            id = json["id"].stringValue
   }
}

My response structure changes due to environment changes.

How to set struct Data for let subData [SubData] i.e array of dictionary else SubData normal dictionary based on Dev or other.

Body:
An easy way to make it array in both cases as type can't be determined at runtime

let subData:[SubData]?

Then

subData =  Environment.Dev == "Dev_URL"
            ? json["sub_data"].arrayValue.map { SubData($0) }
            : [SubData(json["sub_data"])]

Also you can change your response sub_data to be an array in both cases so above line be

subData = json["sub_data"].arrayValue.map { SubData($0) }

That way you work in development and release smoothly


问:
Write a program that will take three integers as input and will print the second largest number
I have tried this program to take 3 integers and print the 2nd largest number:

```<code>#include<stdio.h>
int main()
{
    int a,b,c,max2;
    printf("Enter 3 integers: ");
    scanf("%d%d%d",&a,&b,&c);
    max2=a;
    if(a>b){
        max2=b;
        printf("")
    }
    return 0;
}
</code>```

Now i am stuck here. I am unable to find the logic behind this code. What can I do?

答:
```<code>       #include <stdio.h>
        main()
       {
              int a,b,c;

               scanf("%d %d %d",&a,&b,&c);
               // largest //
               if(a>b&&a>c)
               printf("largest=%d",a);
               if(b>a&&b>c)
               printf("largest=%d",b);
               if(c>b&&c>a)
              printf("largest=%d",c);
             // second largest//
              if(a>b&&a<c)
             printf("\nscenond largest=%d",a);
            if(b>a&&b<c)
             printf("\nscenond largest=%d",b);
             if(c>a&&c<b)
           printf("\nscenond largest=%d",c);

       }

this will output the largest and the second largest number.
</code>```

Body:
I have tried this program to take 3 integers and print the 2nd largest number:

#include<stdio.h>
int main()
{
    int a,b,c,max2;
    printf("Enter 3 integers: ");
    scanf("%d%d%d",&a,&b,&c);
    max2=a;
    if(a>b){
        max2=b;
        printf("")
    }
    return 0;
}

Now i am stuck here. I am unable to find the logic behind this code. What can I do?


问:
Improve execution time with Multithreading in python
How can I implement multithreading to make this process faster? The program generates 1million random numbers and writes them on a file. It takes just over 2 seconds, but I'm wondering if multithreading would make it any faster.</p>
```<code>import random
import time

startTime = time.time()

data = open("file2.txt", "a+")

for i in range(1000000):
  number = str(random.randint(1, 9999))
  data.write(number + '\n')
data.close()

executionTime = (time.time() - startTime)
print('Execution time in seconds: ', + str(executionTime))
</code>```

答:
write the string @ once to the file rather than individually writing each number to file & I have tested it with multithreading and its actually degrading performance since you are writing to same file if you do threading you have to also synchronize which will affect performance.

Code: (Execution time in seconds: 1.943817138671875)

```<code>import time

startTime = time.time()

import random
size = 1000_000
# pre declaring the list to save time from resize it later
l = [None] * size
# l = list(str(random.randint(1, 99999)) for i in range(size))
# random.randrange(0, )
for i in range(size):
    # l[i] = str(random.randint(1, 99999)) + "\n"
    l[i] = f"{random.randint(1, 99999)}\n"

# writing data @ once to the file
with open('file2.txt', 'w+') as data:
    data.write(''.join(l))

executionTime = (time.time() - startTime)

print('Execution time in seconds: ' + str(executionTime))
</code>```

Output:

```<code>Execution time in seconds: 1.943817138671875
</code>```

Body:
How can I implement multithreading to make this process faster? The program generates 1million random numbers and writes them on a file. It takes just over 2 seconds, but I'm wondering if multithreading would make it any faster.

import random
import time

startTime = time.time()

data = open("file2.txt", "a+")

for i in range(1000000):
  number = str(random.randint(1, 9999))
  data.write(number + '\n')
data.close()

executionTime = (time.time() - startTime)
print('Execution time in seconds: ', + str(executionTime))

Body:
write the string @ once to the file rather than individually writing each number to file & I have tested it with multithreading and its actually degrading performance since you are writing to same file if you do threading you have to also synchronize which will affect performance.

Code: (Execution time in seconds: 1.943817138671875)

import time

startTime = time.time()

import random
size = 1000_000
# pre declaring the list to save time from resize it later
l = [None] * size
# l = list(str(random.randint(1, 99999)) for i in range(size))
# random.randrange(0, )
for i in range(size):
    # l[i] = str(random.randint(1, 99999)) + "\n"
    l[i] = f"{random.randint(1, 99999)}\n"

# writing data @ once to the file
with open('file2.txt', 'w+') as data:
    data.write(''.join(l))

executionTime = (time.time() - startTime)

print('Execution time in seconds: ' + str(executionTime))

Output:

Execution time in seconds: 1.943817138671875


问:
how to use redux useSelector to check state and do a fetch to a database
I am using redux in a project and I want to make a  useSelector that  would check to see if the values in the redux state are the default values if not it will do a request to the database and update the  the state I feel like it is quite complicated though and I am having a hard time getting my head around how I need to do this.
I need to do this because sometimes the  correct state is not loaded in the  state I am considering just  doing a check  every time I use useSelector  to check if the values are the default values  then fetch from the database but I would much prefer to write  it a way that would allow to be handled within the redux selector but I can't really grasp I how I need to do it.

```<code> const info =  useSelector(getInfo)
</code>```

Ideally I would like the info to be handled when I fetch here

```<code>import { SET_USER_DETAILS } from "../constants/userConstants";

const intialState = {
  user: { },
};

const userReducer = (state = intialState, action: any) => {
  switch (action.type) {
    case SET_USER_DETAILS:
      return { ...state, user: action.payload };
    default:
      return state;
  }
};
</code>```

here is what my current reducer looks like what would be the best way to do this as I am finding it a little bit difficult to follow the documentation on the  redux website.

答:
You can use redux-thunk. https://redux.js.org/usage/writing-logic-thunks
then your thunk could look something like that:

```<code>const thunkFunction = (dispatch, getState) => {
  // logic here that can dispatch actions or read state

  const currentState = getState() as typeof initialState;
  // check if state is default state
  if (JSON.stringify(initialState) === JSON.stringify(currentState)) {
    fetch(url).then(data => {
      dispatch({type: SET_USER_DETAILS, payload: data})
    })
  }
}
</code>```

You need first to fetch data in react component:

const MyComponent = () => {
  // while fetch is fetching, data will be default state,
  // and when fetch is done, that component will automatically
  // rerender with new data

  const data = useSelector(getInfo);
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(thunkFunction)
  },[])
  return {JSON.stringify(data, null, 2)}
}
```

I did not test it so may require some changes
but in general concept is like this

Body:
I am using redux in a project and I want to make a  useSelector that  would check to see if the values in the redux state are the default values if not it will do a request to the database and update the  the state I feel like it is quite complicated though and I am having a hard time getting my head around how I need to do this.
I need to do this because sometimes the  correct state is not loaded in the  state I am considering just  doing a check  every time I use useSelector  to check if the values are the default values  then fetch from the database but I would much prefer to write  it a way that would allow to be handled within the redux selector but I can't really grasp I how I need to do it.

 const info =  useSelector(getInfo)

Ideally I would like the info to be handled when I fetch here

import { SET_USER_DETAILS } from "../constants/userConstants";

const intialState = {
  user: { },
};

const userReducer = (state = intialState, action: any) => {
  switch (action.type) {
    case SET_USER_DETAILS:
      return { ...state, user: action.payload };
    default:
      return state;
  }
};

here is what my current reducer looks like what would be the best way to do this as I am finding it a little bit difficult to follow the documentation on the  redux website.

Body:
You can use redux-thunk. https://redux.js.org/usage/writing-logic-thunks
then your thunk could look something like that:

const thunkFunction = (dispatch, getState) => {
  // logic here that can dispatch actions or read state

  const currentState = getState() as typeof initialState;
  // check if state is default state
  if (JSON.stringify(initialState) === JSON.stringify(currentState)) {
    fetch(url).then(data => {
      dispatch({type: SET_USER_DETAILS, payload: data})
    })
  }
}

You need first to fetch data in react component:

const MyComponent = () => {
  // while fetch is fetching, data will be default state,
  // and when fetch is done, that component will automatically
  // rerender with new data

  const data = useSelector(getInfo);
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(thunkFunction)
  },[])
  return <code>{JSON.stringify(data, null, 2)}</code>
}

I did not test it so may require some changes
but in general concept is like this


问:
How do you write an IsPressed (a function that should only return true on first press)?
I need a function in a game loop that should only return true on first press.

I don't know which game I can give an example from which game is currently on the market, but I will explain this request in detail (I haven't played/can't play any of the modern games because I'm blind).

For example, there is an event you are listening to in the loop. When the user presses the S key, a text showing the last status of the character appears on the screen: Stamina, energy etc.
This loop can run thousands of times per second, as the loops depend on the speed of the hardware and the code you write.
We only need to detect the first press of the user. It should return false when the key is hold pressed. Otherwise, the last status of the user is shown thousands of times on the screen.

I am trying to provide this functionality using win32api. GetAsyncKeyState seems like the right option for this scenario but I don't understand how this can be done.

bool IsPressed(int key) {
return GetAsyncKeyState(key) & 1 != 0;
}
```

The function I wrote acts like a char event.

How can I write this?

I tried using other answers on StackOwerflow. However, I could not find an answer to the question I asked. Still, these answers helped me with some issues:
What is the fastest way to determine a key press and key holding in Win32?

答:
While the GetAsyncKeyState can indicate via least significant bit whether the key has been pressed since the last call to this function, this behavior cannot be relied on.

If the most significant bit is set, the key is down, and if the least significant bit is set, the key was pressed after the previous call to GetAsyncKeyState. However, you should not rely on this last behavior...

Although the least significant bit of the return value indicates whether the key has been pressed since the last query, due to the preemptive multitasking nature of Windows, another application can call GetAsyncKeyState and receive the "recently pressed" bit instead of your application.

Therefore, you can't rely on the Windows API to do the bookkeeping for you. I suggest wrapping any key queries in a class that you'll use for any button presses.

```<code>
class KeyInput {
public:
    using key_type = int;

    enum class Transition {
        none,
        pressed,
        released,
    };

    struct PressResult {
        bool pressed;
        Transition transition;
    };

    PressResult state(key_type key) {
        PressResult result;
        result.pressed = (GetAsyncKeyState(key) < 0);
        if (auto it = last_states_.find(key); it != last_states_.end()) {
            if (last_states_[key] == result.pressed) {
                result.transition = Transition::none;
            }
            else if (result.pressed) {
                result.transition = Transition::pressed;
            }
            else {
                result.transition = Transition::released;
            }
        }
        else {
            result.transition = Transition::none;
        }

        last_states_[key] = result.pressed;

        return result;
    };

private:
    std::unordered_map<key_type, bool> last_states_{};
};
</code>```

See it in action

Note

This will not capture transitions since the last iteration of your program. In order to handle that, you'll need your class to check every button press (that you care about) on every iteration.

Body:
I need a function in a game loop that should only return true on first press.

I don't know which game I can give an example from which game is currently on the market, but I will explain this request in detail (I haven't played/can't play any of the modern games because I'm blind).

For example, there is an event you are listening to in the loop. When the user presses the S key, a text showing the last status of the character appears on the screen: Stamina, energy etc.
This loop can run thousands of times per second, as the loops depend on the speed of the hardware and the code you write.
We only need to detect the first press of the user. It should return false when the key is hold pressed. Otherwise, the last status of the user is shown thousands of times on the screen.

I am trying to provide this functionality using win32api. GetAsyncKeyState seems like the right option for this scenario but I don't understand how this can be done.

bool IsPressed(int key) {
return GetAsyncKeyState(key) & 1 != 0;
}

The function I wrote acts like a char event.

How can I write this?

I tried using other answers on StackOwerflow. However, I could not find an answer to the question I asked. Still, these answers helped me with some issues:
What is the fastest way to determine a key press and key holding in Win32?

Body:
While the GetAsyncKeyState can indicate via least significant bit whether the key has been pressed since the last call to this function, this behavior cannot be relied on.

If the most significant bit is set, the key is down, and if the least significant bit is set, the key was pressed after the previous call to GetAsyncKeyState. However, you should not rely on this last behavior...

Although the least significant bit of the return value indicates whether the key has been pressed since the last query, due to the preemptive multitasking nature of Windows, another application can call GetAsyncKeyState and receive the "recently pressed" bit instead of your application.

Therefore, you can't rely on the Windows API to do the bookkeeping for you. I suggest wrapping any key queries in a class that you'll use for any button presses.

class KeyInput {
public:
    using key_type = int;

    enum class Transition {
        none,
        pressed,
        released,
    };

    struct PressResult {
        bool pressed;
        Transition transition;
    };

    PressResult state(key_type key) {
        PressResult result;
        result.pressed = (GetAsyncKeyState(key) < 0);
        if (auto it = last_states_.find(key); it != last_states_.end()) {
            if (last_states_[key] == result.pressed) {
                result.transition = Transition::none;
            }
            else if (result.pressed) {
                result.transition = Transition::pressed;
            }
            else {
                result.transition = Transition::released;
            }
        }
        else {
            result.transition = Transition::none;
        }

        last_states_[key] = result.pressed;

        return result;
    };

private:
    std::unordered_map<key_type, bool> last_states_{};
};

See it in action

Note

This will not capture transitions since the last iteration of your program. In order to handle that, you'll need your class to check every button press (that you care about) on every iteration.


问:
Python, Vscode: Code snippet in documentation
When we are writing documentation, we usually add some examples of how to use the code.

For example, from pytorch Conv2d function

```<code>Examples:
        >>> # With square kernels and equal stride
        >>> m = nn.Conv2d(16, 33, 3, stride=2)
        >>> # non-square kernels and unequal stride and with padding
        >>> m = nn.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2))
</code>```

Is there a faster way or shortcut to insert >>> at the beginning of each line, like ctrl+/ for comment?

答:
Define a key binding

{
  "key": "shift+ctrl+alt+/",  // or other key combo
  "command": "type",
  "args": { "text": "    >>> " },
  "when": "editorTextFocus"
}
```

Body:
When we are writing documentation, we usually add some examples of how to use the code.

For example, from pytorch Conv2d function

Examples:
        >>> # With square kernels and equal stride
        >>> m = nn.Conv2d(16, 33, 3, stride=2)
        >>> # non-square kernels and unequal stride and with padding
        >>> m = nn.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2))

Is there a faster way or shortcut to insert >>> at the beginning of each line, like ctrl+/ for comment?


问:
Error when running gridsearchcv with pipeline
I want to create a pipeline structure that contains all the processes in the model training process. After making the relevant libraries and definitions, I created the following structure to experiment. I used telco churn dataset.

```<code>ohe_f =["gender","SeniorCitizen","Partner","Dependents","PhoneService","MultipleLines",
    "InternetService","OnlineSecurity","OnlineBackup","DeviceProtection","TechSupport",
    "StreamingTV","StreamingMovies","Contract","PaperlessBilling","PaymentMethod"]

X_train, X_test, y_train, y_test = train_test_split(X,
                                                    y,
                                                    test_size=0.2,
                                                    stratify=y,
                                                    random_state=11)

pipeline = Pipeline(steps = [['smote', SMOTE(random_state=11)],
                             ['scaler', MinMaxScaler()],
                             ['encoder', OneHotEncoder(),ohe_f],
                             ['classifier', LogisticRegression(random_state=11)]])

stratified_kfold = StratifiedKFold(n_splits=3,
                                       shuffle=True,
                                       random_state=11)

param_grid = {'classifier__C':[0.01, 0.1, 1, 10, 100]}

grid_search = GridSearchCV(estimator=pipeline,
                           param_grid=param_grid,
                           scoring='roc_auc',
                           cv=stratified_kfold,
                           n_jobs=-1)
</code>```

When I start training the model I get the following error. How can I solve it?

```<code>---------------------------------------------------------------------------
_RemoteTraceback                          Traceback (most recent call last)
_RemoteTraceback:
"""
Traceback (most recent call last):
  File "C:\Users\burak\anaconda3\lib\site-packages\joblib\externals\loky\process_executor.py", line 436, in _process_worker
    r = call_item()
  File "C:\Users\burak\anaconda3\lib\site-packages\joblib\externals\loky\process_executor.py", line 288, in __call__
    return self.fn(*self.args, **self.kwargs)
  File "C:\Users\burak\anaconda3\lib\site-packages\joblib\_parallel_backends.py", line 595, in __call__
    return self.func(*args, **kwargs)
  File "C:\Users\burak\anaconda3\lib\site-packages\joblib\parallel.py", line 262, in __call__
    return [func(*args, **kwargs)
  File "C:\Users\burak\anaconda3\lib\site-packages\joblib\parallel.py", line 262, in <listcomp>
    return [func(*args, **kwargs)
  File "C:\Users\burak\anaconda3\lib\site-packages\sklearn\utils\fixes.py", line 216, in __call__
    return self.function(*args, **kwargs)
  File "C:\Users\burak\anaconda3\lib\site-packages\sklearn\model_selection\_validation.py", line 668, in _fit_and_score
    estimator = estimator.set_params(**cloned_parameters)
  File "C:\Users\burak\anaconda3\lib\site-packages\sklearn\pipeline.py", line 188, in set_params
    self._set_params("steps", **kwargs)
  File "C:\Users\burak\anaconda3\lib\site-packages\sklearn\utils\metaestimators.py", line 54, in _set_params
    super().set_params(**params)
  File "C:\Users\burak\anaconda3\lib\site-packages\sklearn\base.py", line 239, in set_params
    valid_params = self.get_params(deep=True)
  File "C:\Users\burak\anaconda3\lib\site-packages\sklearn\pipeline.py", line 167, in get_params
    return self._get_params("steps", deep=deep)
  File "C:\Users\burak\anaconda3\lib\site-packages\sklearn\utils\metaestimators.py", line 33, in _get_params
    out.update(estimators)
ValueError: dictionary update sequence element #2 has length 3; 2 is required
"""

The above exception was the direct cause of the following exception:

ValueError                                Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_1388/1962240236.py in <module>
     23                            n_jobs=-1)
     24
---> 25 grid_search.fit(X_train, y_train)
     26 cv_score = grid_search.best_score_
     27 test_score = grid_search.score(X_test, y_test)

~\anaconda3\lib\site-packages\sklearn\model_selection\_search.py in fit(self, X, y, groups, **fit_params)
    889                 return results
    890
--> 891             self._run_search(evaluate_candidates)
    892
    893             # multimetric is determined here because in the case of a callable

~\anaconda3\lib\site-packages\sklearn\model_selection\_search.py in _run_search(self, evaluate_candidates)
   1390     def _run_search(self, evaluate_candidates):
   1391         """Search all candidates in param_grid"""
-> 1392         evaluate_candidates(ParameterGrid(self.param_grid))
   1393
   1394

~\anaconda3\lib\site-packages\sklearn\model_selection\_search.py in evaluate_candidates(candidate_params, cv, more_results)
    836                     )
    837
--> 838                 out = parallel(
    839                     delayed(_fit_and_score)(
    840                         clone(base_estimator),

~\anaconda3\lib\site-packages\joblib\parallel.py in __call__(self, iterable)
   1054
   1055             with self._backend.retrieval_context():
-> 1056                 self.retrieve()
   1057             # Make sure that we get a last message telling us we are done
   1058             elapsed_time = time.time() - self._start_time

~\anaconda3\lib\site-packages\joblib\parallel.py in retrieve(self)
    933             try:
    934                 if getattr(self._backend, 'supports_timeout', False):
--> 935                     self._output.extend(job.get(timeout=self.timeout))
    936                 else:
    937                     self._output.extend(job.get())

~\anaconda3\lib\site-packages\joblib\_parallel_backends.py in wrap_future_result(future, timeout)
    540         AsyncResults.get from multiprocessing."""
    541         try:
--> 542             return future.result(timeout=timeout)
    543         except CfTimeoutError as e:
    544             raise TimeoutError from e

~\anaconda3\lib\concurrent\futures\_base.py in result(self, timeout)
    443                     raise CancelledError()
    444                 elif self._state == FINISHED:
--> 445                     return self.__get_result()
    446                 else:
    447                     raise TimeoutError()

~\anaconda3\lib\concurrent\futures\_base.py in __get_result(self)
    388         if self._exception:
    389             try:
--> 390                 raise self._exception
    391             finally:
    392                 # Break a reference cycle with the exception in self._exception

ValueError: dictionary update sequence element #2 has length 3; 2 is required
</code>```

答: Your need to split your pipeline into 2 parts : one to process the numeric features (with the min max scaler) and another one to process categorical features (with the one hot encoder). You can use the class ColumnTransformer from scikit-learn : https://scikit-learn.org/stable/auto_examples/compose/plot_column_transformer_mixed_types.html

Body:
I want to create a pipeline structure that contains all the processes in the model training process. After making the relevant libraries and definitions, I created the following structure to experiment. I used telco churn dataset.

ohe_f =["gender","SeniorCitizen","Partner","Dependents","PhoneService","MultipleLines",
    "InternetService","OnlineSecurity","OnlineBackup","DeviceProtection","TechSupport",
    "StreamingTV","StreamingMovies","Contract","PaperlessBilling","PaymentMethod"]

X_train, X_test, y_train, y_test = train_test_split(X,
                                                    y,
                                                    test_size=0.2,
                                                    stratify=y,
                                                    random_state=11)

pipeline = Pipeline(steps = [['smote', SMOTE(random_state=11)],
                             ['scaler', MinMaxScaler()],
                             ['encoder', OneHotEncoder(),ohe_f],
                             ['classifier', LogisticRegression(random_state=11)]])

stratified_kfold = StratifiedKFold(n_splits=3,
                                       shuffle=True,
                                       random_state=11)

param_grid = {'classifier__C':[0.01, 0.1, 1, 10, 100]}

grid_search = GridSearchCV(estimator=pipeline,
                           param_grid=param_grid,
                           scoring='roc_auc',
                           cv=stratified_kfold,
                           n_jobs=-1)

When I start training the model I get the following error. How can I solve it?

---------------------------------------------------------------------------
_RemoteTraceback                          Traceback (most recent call last)
_RemoteTraceback:
"""
Traceback (most recent call last):
  File "C:\Users\burak\anaconda3\lib\site-packages\joblib\externals\loky\process_executor.py", line 436, in _process_worker
    r = call_item()
  File "C:\Users\burak\anaconda3\lib\site-packages\joblib\externals\loky\process_executor.py", line 288, in __call__
    return self.fn(*self.args, **self.kwargs)
  File "C:\Users\burak\anaconda3\lib\site-packages\joblib\_parallel_backends.py", line 595, in __call__
    return self.func(*args, **kwargs)
  File "C:\Users\burak\anaconda3\lib\site-packages\joblib\parallel.py", line 262, in __call__
    return [func(*args, **kwargs)
  File "C:\Users\burak\anaconda3\lib\site-packages\joblib\parallel.py", line 262, in <listcomp>
    return [func(*args, **kwargs)
  File "C:\Users\burak\anaconda3\lib\site-packages\sklearn\utils\fixes.py", line 216, in __call__
    return self.function(*args, **kwargs)
  File "C:\Users\burak\anaconda3\lib\site-packages\sklearn\model_selection\_validation.py", line 668, in _fit_and_score
    estimator = estimator.set_params(**cloned_parameters)
  File "C:\Users\burak\anaconda3\lib\site-packages\sklearn\pipeline.py", line 188, in set_params
    self._set_params("steps", **kwargs)
  File "C:\Users\burak\anaconda3\lib\site-packages\sklearn\utils\metaestimators.py", line 54, in _set_params
    super().set_params(**params)
  File "C:\Users\burak\anaconda3\lib\site-packages\sklearn\base.py", line 239, in set_params
    valid_params = self.get_params(deep=True)
  File "C:\Users\burak\anaconda3\lib\site-packages\sklearn\pipeline.py", line 167, in get_params
    return self._get_params("steps", deep=deep)
  File "C:\Users\burak\anaconda3\lib\site-packages\sklearn\utils\metaestimators.py", line 33, in _get_params
    out.update(estimators)
ValueError: dictionary update sequence element #2 has length 3; 2 is required
"""

The above exception was the direct cause of the following exception:

ValueError                                Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_1388/1962240236.py in <module>
     23                            n_jobs=-1)
     24
---> 25 grid_search.fit(X_train, y_train)
     26 cv_score = grid_search.best_score_
     27 test_score = grid_search.score(X_test, y_test)

~\anaconda3\lib\site-packages\sklearn\model_selection\_search.py in fit(self, X, y, groups, **fit_params)
    889                 return results
    890
--> 891             self._run_search(evaluate_candidates)
    892
    893             # multimetric is determined here because in the case of a callable

~\anaconda3\lib\site-packages\sklearn\model_selection\_search.py in _run_search(self, evaluate_candidates)
   1390     def _run_search(self, evaluate_candidates):
   1391         """Search all candidates in param_grid"""
-> 1392         evaluate_candidates(ParameterGrid(self.param_grid))
   1393
   1394

~\anaconda3\lib\site-packages\sklearn\model_selection\_search.py in evaluate_candidates(candidate_params, cv, more_results)
    836                     )
    837
--> 838                 out = parallel(
    839                     delayed(_fit_and_score)(
    840                         clone(base_estimator),

~\anaconda3\lib\site-packages\joblib\parallel.py in __call__(self, iterable)
   1054
   1055             with self._backend.retrieval_context():
-> 1056                 self.retrieve()
   1057             # Make sure that we get a last message telling us we are done
   1058             elapsed_time = time.time() - self._start_time

~\anaconda3\lib\site-packages\joblib\parallel.py in retrieve(self)
    933             try:
    934                 if getattr(self._backend, 'supports_timeout', False):
--> 935                     self._output.extend(job.get(timeout=self.timeout))
    936                 else:
    937                     self._output.extend(job.get())

~\anaconda3\lib\site-packages\joblib\_parallel_backends.py in wrap_future_result(future, timeout)
    540         AsyncResults.get from multiprocessing."""
    541         try:
--> 542             return future.result(timeout=timeout)
    543         except CfTimeoutError as e:
    544             raise TimeoutError from e

~\anaconda3\lib\concurrent\futures\_base.py in result(self, timeout)
    443                     raise CancelledError()
    444                 elif self._state == FINISHED:
--> 445                     return self.__get_result()
    446                 else:
    447                     raise TimeoutError()

~\anaconda3\lib\concurrent\futures\_base.py in __get_result(self)
    388         if self._exception:
    389             try:
--> 390                 raise self._exception
    391             finally:
    392                 # Break a reference cycle with the exception in self._exception

ValueError: dictionary update sequence element #2 has length 3; 2 is required


问:
Solidity - Balance is zero for the deployed ERC20 contract
I'm trying to create an ERC20 token using truffle and upgradable openzeppelin contracts.
The problem is that the token balance is zero when I add the contract address into the Metamask extension.
When I use remix, Everything is Ok and I can see the correct balance of the deployed contract in the Metamask.
But I don't know where is the problem when I use it in localhost using Truffle and Ganache.

Token.sol:

```<code>pragma solidity ^0.8.2;

import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20SnapshotUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";

contract Token is
  Initializable,
  ERC20Upgradeable,
  ERC20SnapshotUpgradeable,
  OwnableUpgradeable,
  PausableUpgradeable
{
  /// @custom:oz-upgrades-unsafe-allow constructor
  constructor() initializer {}

  function initialize() public initializer {
    __ERC20_init("Token", "TKN");
    __ERC20Snapshot_init();
    __Ownable_init();
    __Pausable_init();

    _mint(msg.sender, 10000000000 * 18**decimals());
  }

  function snapshot() public onlyOwner {
    _snapshot();
  }

  function pause() public onlyOwner {
    _pause();
  }

  function unpause() public onlyOwner {
    _unpause();
  }

  function _beforeTokenTransfer(
    address from,
    address to,
    uint256 amount
  )
    internal
    override(ERC20Upgradeable, ERC20SnapshotUpgradeable)
    whenNotPaused
  {
    super._beforeTokenTransfer(from, to, amount);
  }
}
</code>```

truffle-config.js:

```<code>networks: {
    development: {
      host: "localhost",
      port: 7545,
      network_id: "*",
    },
    //  test: {
    //    host: "127.0.0.1",
    //    port: 7545,
    //    network_id: "*"
    //  }
  },
</code>```

Metamask network config:

TKN token balance:

Video:
https://youtu.be/HHWsnlJxZ7Y

答:
This code might help you i, since i have used tuffle and ganache to connect metamask locally. make sure you are using truffle hdwallet provider HERE</p>
```<code>const path = require("path");
require("dotenv").config({path: "./.env"});
const HDWalletProvider = require("@truffle/hdwallet-provider");
const AccountIndex = 0;

module.exports = {
  // See <http://truffleframework.com/docs/advanced/configuration>
  // to customize your Truffle configuration!
  contracts_build_directory: path.join(__dirname, "client/src/contracts"),
  networks: {
    development: {
      port: 7545,
      host: "127.0.0.1",
      network_id: 5777
    },
    ganache_local: {
      provider: function() {
        return new HDWalletProvider(process.env.MNEMONIC, "http://127.0.0.1:7545", AccountIndex)
      },
      network_id: 5777
    },
    goerli_infura: {
      provider: function() {
        return new HDWalletProvider(process.env.MNEMONIC, "https://goerli.infura.io/v3/ffa60321cbbd4cfda3352014c556e3c3", AccountIndex)
      },
      network_id: 5
    },
    ropsten_infura: {
      provider: function() {
        return new HDWalletProvider(process.env.MNEMONIC, "https://ropsten.infura.io/v3/ffa60321cbbd4cfda3352014c556e3c3", AccountIndex)
      },
      network_id: 3
    }
  },
  compilers: {
    solc: {
      version: "0.6.1"
    }
  }
};
</code>```

Body:
I'm trying to create an ERC20 token using truffle and upgradable openzeppelin contracts.
The problem is that the token balance is zero when I add the contract address into the Metamask extension.
When I use remix, Everything is Ok and I can see the correct balance of the deployed contract in the Metamask.
But I don't know where is the problem when I use it in localhost using Truffle and Ganache.

Token.sol:

pragma solidity ^0.8.2;

import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20SnapshotUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";

contract Token is
  Initializable,
  ERC20Upgradeable,
  ERC20SnapshotUpgradeable,
  OwnableUpgradeable,
  PausableUpgradeable
{
  /// @custom:oz-upgrades-unsafe-allow constructor
  constructor() initializer {}

  function initialize() public initializer {
    __ERC20_init("Token", "TKN");
    __ERC20Snapshot_init();
    __Ownable_init();
    __Pausable_init();

    _mint(msg.sender, 10000000000 * 18**decimals());
  }

  function snapshot() public onlyOwner {
    _snapshot();
  }

  function pause() public onlyOwner {
    _pause();
  }

  function unpause() public onlyOwner {
    _unpause();
  }

  function _beforeTokenTransfer(
    address from,
    address to,
    uint256 amount
  )
    internal
    override(ERC20Upgradeable, ERC20SnapshotUpgradeable)
    whenNotPaused
  {
    super._beforeTokenTransfer(from, to, amount);
  }
}

truffle-config.js:

networks: {
    development: {
      host: "localhost",
      port: 7545,
      network_id: "*",
    },
    //  test: {
    //    host: "127.0.0.1",
    //    port: 7545,
    //    network_id: "*"
    //  }
  },

Metamask network config:

TKN token balance:

Video:
https://youtu.be/HHWsnlJxZ7Y

Body:
This code might help you i, since i have used tuffle and ganache to connect metamask locally. make sure you are using truffle hdwallet provider HERE

const path = require("path");
require("dotenv").config({path: "./.env"});
const HDWalletProvider = require("@truffle/hdwallet-provider");
const AccountIndex = 0;

module.exports = {
  // See <http://truffleframework.com/docs/advanced/configuration>
  // to customize your Truffle configuration!
  contracts_build_directory: path.join(__dirname, "client/src/contracts"),
  networks: {
    development: {
      port: 7545,
      host: "127.0.0.1",
      network_id: 5777
    },
    ganache_local: {
      provider: function() {
        return new HDWalletProvider(process.env.MNEMONIC, "http://127.0.0.1:7545", AccountIndex)
      },
      network_id: 5777
    },
    goerli_infura: {
      provider: function() {
        return new HDWalletProvider(process.env.MNEMONIC, "https://goerli.infura.io/v3/ffa60321cbbd4cfda3352014c556e3c3", AccountIndex)
      },
      network_id: 5
    },
    ropsten_infura: {
      provider: function() {
        return new HDWalletProvider(process.env.MNEMONIC, "https://ropsten.infura.io/v3/ffa60321cbbd4cfda3352014c556e3c3", AccountIndex)
      },
      network_id: 3
    }
  },
  compilers: {
    solc: {
      version: "0.6.1"
    }
  }
};


问:
My VBA code is extremely slow when running
Basically I want to loop through column H (with 430 rows) and if its value is "Tera" then I want to change the value of the cell in column E (i.e. 6th column) with the value in column F (7th column).

```<code>Sub R_Adj()
Sheets("Sheet5").Select
temp = 7
For Each i In Worksheets("Sheet5").Range("H8:H430").Cells
temp = temp + 1
Set column_to = Worksheets("Sheet5").Cells(temp, 6)
Set column_from = Worksheets("Sheet5").Cells(temp, 7)
If i.Value = "Tera" Then column_to.Value = column_from.Value
Next
End Sub
</code>```

The running time is about 10 seconds which is too much in my opinion for such an easy algorithm. Does anybody have any suggestions to improve the performance and running time of this code?

答:
Perhaps the following may improve running time a bit:</p>
```<code>    Sub RTB_justering()
    Dim sh5 As Worksheet
    Dim rng As Range
    Set sh5 = Worksheets("Sheets5")
    sh5.Select
    For Each rng In sh5.Range("H8:H430")
        If rng.Value2 = "Tera" Then
            '    value2 in Column E <-- value2 in Column F
            rng.Offset(0, -3).Value2 = rng.Offset(0, -2).Value2
        End If
    Next
End Sub
</code>```

Body:
Basically I want to loop through column H (with 430 rows) and if its value is "Tera" then I want to change the value of the cell in column E (i.e. 6th column) with the value in column F (7th column).

Sub R_Adj()
Sheets("Sheet5").Select
temp = 7
For Each i In Worksheets("Sheet5").Range("H8:H430").Cells
temp = temp + 1
Set column_to = Worksheets("Sheet5").Cells(temp, 6)
Set column_from = Worksheets("Sheet5").Cells(temp, 7)
If i.Value = "Tera" Then column_to.Value = column_from.Value
Next
End Sub

The running time is about 10 seconds which is too much in my opinion for such an easy algorithm. Does anybody have any suggestions to improve the performance and running time of this code?

Body:
Perhaps the following may improve running time a bit:

    Sub RTB_justering()
    Dim sh5 As Worksheet
    Dim rng As Range
    Set sh5 = Worksheets("Sheets5")
    sh5.Select
    For Each rng In sh5.Range("H8:H430")
        If rng.Value2 = "Tera" Then
            '    value2 in Column E <-- value2 in Column F
            rng.Offset(0, -3).Value2 = rng.Offset(0, -2).Value2
        End If
    Next
End Sub


问:
Why won't renderDT() return a table on my Shiny app?
I'm trying to create a function on my Shiny app which allows someone to upload a file. The uploaded file will always contain a column called "Index". I want the Shiny app to be able to take this Index (e.g. A0AVT1_Y44) and extract information to add three additional columns to the table: Protein_id (A0AVT1), Residue (Y), and Position (44). I've already created a successful function which does this. However, when I run this code and then renderDT(), no data table shows up even though there is no error message. Does anyone know what's happening?

Code:

```<code>library(dplyr)
library(viridis)
library(tidyverse)
library(rio)
library(shiny)

options(shiny.maxRequestSize = 30*1024^2)

ui <- fluidPage(
  titlePanel("File Upload"),
  sidebarLayout(
    sidebarPanel(
      fileInput("file1", "Browse...",
                multiple = TRUE,
                accept = c("text/csv",
                           "text/tab-separated-values",
                           ".csv",
                           "text/tsv",
                           "text/comma-separated-values",
                           ".tsv")),
                placeholder = "No file selected",
      tags$hr(),
      radioButtons("disp", "Display",
                   choices = c(Head = "head",
                               All = "all"),
                   selected = "head")
    ),
    mainPanel(
      DT::dataTableOutput(outputId = "exp_df")
    )
  )
)

server <- function(input, output) {
  exp_df <- reactive({return(
    cbind(
      iris[input$file1],
      Residue = nv(),
      Position = nvar(),
      Protein_id = newvar())
  )
  })

  return(exp_df)

  nv <- reactive({
    exp_df[[gsub('[0-9]*','', sub(".*?_(.*?)$", "\\1",
</code>```

input$file1$Index))]]
})

```<code>  nvar <- reactive({
    exp_df[[gsub('[0-9.-]','', sub(".*?_(.*?)$","\\1",
</code>```

input$file1$Index))]]
})

```<code>  newvar <-reactive({
    exp_df[[sub("_\\D(\\d)+$","",sub(".*?_(.*?)$","\\1",
</code>```

input$file1$Index))]]
})

```<code>  output$exp_df <- DT::renderDT({
    exp_df()
    })
}

shinyApp(ui=ui, server=server)
</code>```

I then ran options(shiny.trace = TRUE) and received the following output:

runApp('~/BioInf Proj')

```<code>Listening on http://127.0.0.1:4700
SEND {"config":{"workerId":"","sessionId":"2a9472a1d0a0da6562eac28841de4ff2","user":null}}
RECV {"method":"init","data":{"file1:shiny.file":null,"disp":"head",".clientdata_output_exp_df_hidden":false,".clientdata_pixelratio":1,".clientdata_url_protocol":"http:",".clientdata_url_hostname":"127.0.0.1",".clientdata_url_port":"4700",".clientdata_url_pathname":"/",".clientdata_url_search":"",".clientdata_url_hash_initial":"",".clientdata_url_hash":"",".clientdata_singletons":""}}
SEND {"busy":"busy"}
SEND {"recalculating":{"name":"exp_df","status":"recalculating"}}
SEND {"recalculating":{"name":"exp_df","status":"recalculated"}}
SEND {"busy":"idle"}
SEND {"errors":{"exp_df":{"message":"","call":"NULL","type":["shiny.silent.error","validation"]}},"values":{},"inputMessages":[]}
RECV {"method":"uploadInit","args":[[{"name":"pY_cml.csv","size":336901,"type":"application/vnd.ms-excel"}]],"tag":0}
SEND {"response":{"tag":0,"value":{"jobId":"3ad1ee2355d914f1b88e13e5","uploadUrl":"session/2a9472a1d0a0da6562eac28841de4ff2/upload/3ad1ee2355d914f1b88e13e5?w="}}}
RECV {"method":"uploadEnd","args":["3ad1ee2355d914f1b88e13e5","file1"],"tag":1}
SEND {"progress":{"type":"binding","message":{"id":"exp_df"}}}
SEND {"busy":"busy"}
SEND {"response":{"tag":1,"value":null}}
SEND {"recalculating":{"name":"exp_df","status":"recalculating"}}
SEND {"recalculating":{"name":"exp_df","status":"recalculated"}}
SEND {"busy":"idle"}
SEND {"errors":{"exp_df":{"message":"","call":"NULL","type":["shiny.silent.error","validation"]}},"values":{},"inputMessages":[]}
</code>```

答: It turns out the issue was with the file I was inputting, not the code! Thanks for the help!</p>

Body:
I'm trying to create a function on my Shiny app which allows someone to upload a file. The uploaded file will always contain a column called "Index". I want the Shiny app to be able to take this Index (e.g. A0AVT1_Y44) and extract information to add three additional columns to the table: Protein_id (A0AVT1), Residue (Y), and Position (44). I've already created a successful function which does this. However, when I run this code and then renderDT(), no data table shows up even though there is no error message. Does anyone know what's happening?

Code:

library(dplyr)
library(viridis)
library(tidyverse)
library(rio)
library(shiny)

options(shiny.maxRequestSize = 30*1024^2)

ui <- fluidPage(
  titlePanel("File Upload"),
  sidebarLayout(
    sidebarPanel(
      fileInput("file1", "Browse...",
                multiple = TRUE,
                accept = c("text/csv",
                           "text/tab-separated-values",
                           ".csv",
                           "text/tsv",
                           "text/comma-separated-values",
                           ".tsv")),
                placeholder = "No file selected",
      tags$hr(),
      radioButtons("disp", "Display",
                   choices = c(Head = "head",
                               All = "all"),
                   selected = "head")
    ),
    mainPanel(
      DT::dataTableOutput(outputId = "exp_df")
    )
  )
)

server <- function(input, output) {
  exp_df <- reactive({return(
    cbind(
      iris[input$file1],
      Residue = nv(),
      Position = nvar(),
      Protein_id = newvar())
  )
  })

  return(exp_df)

  nv <- reactive({
    exp_df[[gsub('[0-9]*','', sub(".*?_(.*?)$", "\\1",

input$file1$Index))]]
})

  nvar <- reactive({
    exp_df[[gsub('[0-9.-]','', sub(".*?_(.*?)$","\\1",

input$file1$Index))]]
})

  newvar <-reactive({
    exp_df[[sub("_\\D(\\d)+$","",sub(".*?_(.*?)$","\\1",

input$file1$Index))]]
})

  output$exp_df <- DT::renderDT({
    exp_df()
    })
}

shinyApp(ui=ui, server=server)

I then ran options(shiny.trace = TRUE) and received the following output:

runApp('~/BioInf Proj')

Listening on http://127.0.0.1:4700
SEND {"config":{"workerId":"","sessionId":"2a9472a1d0a0da6562eac28841de4ff2","user":null}}
RECV {"method":"init","data":{"file1:shiny.file":null,"disp":"head",".clientdata_output_exp_df_hidden":false,".clientdata_pixelratio":1,".clientdata_url_protocol":"http:",".clientdata_url_hostname":"127.0.0.1",".clientdata_url_port":"4700",".clientdata_url_pathname":"/",".clientdata_url_search":"",".clientdata_url_hash_initial":"",".clientdata_url_hash":"",".clientdata_singletons":""}}
SEND {"busy":"busy"}
SEND {"recalculating":{"name":"exp_df","status":"recalculating"}}
SEND {"recalculating":{"name":"exp_df","status":"recalculated"}}
SEND {"busy":"idle"}
SEND {"errors":{"exp_df":{"message":"","call":"NULL","type":["shiny.silent.error","validation"]}},"values":{},"inputMessages":[]}
RECV {"method":"uploadInit","args":[[{"name":"pY_cml.csv","size":336901,"type":"application/vnd.ms-excel"}]],"tag":0}
SEND {"response":{"tag":0,"value":{"jobId":"3ad1ee2355d914f1b88e13e5","uploadUrl":"session/2a9472a1d0a0da6562eac28841de4ff2/upload/3ad1ee2355d914f1b88e13e5?w="}}}
RECV {"method":"uploadEnd","args":["3ad1ee2355d914f1b88e13e5","file1"],"tag":1}
SEND {"progress":{"type":"binding","message":{"id":"exp_df"}}}
SEND {"busy":"busy"}
SEND {"response":{"tag":1,"value":null}}
SEND {"recalculating":{"name":"exp_df","status":"recalculating"}}
SEND {"recalculating":{"name":"exp_df","status":"recalculated"}}
SEND {"busy":"idle"}
SEND {"errors":{"exp_df":{"message":"","call":"NULL","type":["shiny.silent.error","validation"]}},"values":{},"inputMessages":[]}


问:
C++ Dynamic Arrays Creation
I am prompted with the question as follows

Write a program that prints dynamic arrays.

The program creates an int 1D dynamic array of 3 elements and
a float 2D dynamic array of 3 ROWS and 3 COLS.

Initialize both arrays with random values.

Both arrays will be printed separately in two separate functions

void print_2d_array(float**);

void print_1d_array(int*);"

I have created a code that will not produce any output. I am guessing the issue is in the initialization of the arrays, but I cannot figure it out. How do I get it to display the randomly generated numbers?

#include <iostream>
#include <iomanip>

using namespace std;

void print_2d_array(float**);
void print_1d_array(int*);

int main() {
    srand(time(NULL));

    int* arr[3];
    float** arr_two[3][3];

    for (int i = 0; i < 3; i++)
        *arr[i] = rand() % 100;

    for (int j = 0; j < 3; j++)
        for (int k = 0; k < 3; k++)
            **arr_two[j][k] = rand() % 100;

    print_1d_array(*arr);
    print_2d_array(**arr_two);
}

void print_2d_array(float** arr_two) {
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++)
            cout << arr_two[i][j];
    }
    cout << endl;
}

void print_1d_array(int* arr) {
    for (int i = 0; i < 3; i++)
        cout << arr[i];
}
```

答:
I want to post my code because this was a nightmare for me with a lot of testing

This would help with a 1Dimensional array for dynamic array assignment

I can't find all the stack overflow comments that helped me reach this conclusion of code so, this is how I give back. Hopefully this helps make sense of it.

I read a lot of stack questions saying this isn't possible and use a vector, if I find them I intend to post this there as well.

```<code>#include <iostream>
#include <array>
using namespace std;
</code>```

// Reference
// https://www.learncpp.com/cpp-tutorial/dynamically-allocating-arrays/
// https://www.youtube.com/watch?v=FHhcSncuHEI

```<code>int main()
{

 int size;
 int number = 0;
 int count  = 0;
 cout << "enter size for array: ";
 cin  >> size;
 int *array;
 int *tempArray;
 tempArray = new int[size];
 array     = new int[size];

 // can also be declared
 // int *array = new int[size];

 while(number != -1)
 {

  cout << " enter values for array: ";
  cin  >> number;

  if(number == -1)
  {
      break;
  }

  if(count == size)
  {
      delete [] tempArray;
      size = size + 1;
      tempArray = new int[size];

     for(int i=0; i < count; i++)
     {
         tempArray[i] = array[i];
     }
         delete [] array;
         array = new int[size];                 // re-use array pointer

     for(int i=0; i < count; i++)
     {
         array[i] = tempArray[i];
     }
  }

 array[count] = number;
 count++;

}

//   if(number == -1)
//     {
//     for(int i=0; i < count; i++)
//       {
//     cout << &array[i];
//       }
//     }

cout << endl;

// proves the array is tracking in memory to the same places.
// if it goes out of bounds of memory, the cout will just
// print the memory address of the last memory address block
// of the dynamic array, the assignment out of bounds does not
// cause significant change.

// array[0] = 1;
// array[1] = 2;
// array[2] = 3;
// array[3] = 4;

// cout << &array[0];
// cout << &array[1];
// cout << &array[2];
// cout << &array[3];

// cout << sizeof(array)/sizeof(array[0]);

// cout << endl;

// cout << array[0];
// cout << array[1];
// cout << array[2];
// cout << array[3];
// cout << array[4];
// cout << array[5];

// cout << endl;

for(int i=0; i < size; i++)
{
cout <<  "array element " << i << ": " << array[i] << endl;
}

return 0;

}
</code>```

https://onlinegdb.com/YKF9skF2Ql

Title: C++ Dynamic Arrays Creation

Body:
I want to post my code because this was a nightmare for me with a lot of testing

This would help with a 1Dimensional array for dynamic array assignment

I can't find all the stack overflow comments that helped me reach this conclusion of code so, this is how I give back. Hopefully this helps make sense of it.

I read a lot of stack questions saying this isn't possible and use a vector, if I find them I intend to post this there as well.

#include <iostream>
#include <array>
using namespace std;

// Reference
// https://www.learncpp.com/cpp-tutorial/dynamically-allocating-arrays/
// https://www.youtube.com/watch?v=FHhcSncuHEI

int main()
{

 int size;
 int number = 0;
 int count  = 0;
 cout << "enter size for array: ";
 cin  >> size;
 int *array;
 int *tempArray;
 tempArray = new int[size];
 array     = new int[size];

 // can also be declared
 // int *array = new int[size];

 while(number != -1)
 {

  cout << " enter values for array: ";
  cin  >> number;

  if(number == -1)
  {
      break;
  }

  if(count == size)
  {
      delete [] tempArray;
      size = size + 1;
      tempArray = new int[size];

     for(int i=0; i < count; i++)
     {
         tempArray[i] = array[i];
     }
         delete [] array;
         array = new int[size];                 // re-use array pointer

     for(int i=0; i < count; i++)
     {
         array[i] = tempArray[i];
     }
  }

 array[count] = number;
 count++;

}

//   if(number == -1)
//     {
//     for(int i=0; i < count; i++)
//       {
//     cout << &array[i];
//       }
//     }

cout << endl;

// proves the array is tracking in memory to the same places.
// if it goes out of bounds of memory, the cout will just
// print the memory address of the last memory address block
// of the dynamic array, the assignment out of bounds does not
// cause significant change.

// array[0] = 1;
// array[1] = 2;
// array[2] = 3;
// array[3] = 4;

// cout << &array[0];
// cout << &array[1];
// cout << &array[2];
// cout << &array[3];

// cout << sizeof(array)/sizeof(array[0]);

// cout << endl;

// cout << array[0];
// cout << array[1];
// cout << array[2];
// cout << array[3];
// cout << array[4];
// cout << array[5];

// cout << endl;

for(int i=0; i < size; i++)
{
cout <<  "array element " << i << ": " << array[i] << endl;
}

return 0;

}

https://onlinegdb.com/YKF9skF2Ql


问:
Can you tell if an object is awaiting an async member function in TypeScript?
I'm working on the client-side of a web application using TypeScript.

I have my own "framework" where I've developed a class (ViewBinder) that uses an async "show" method to load information from the server, extract HTML, and insert it into the document within a parent "placeholder" element.  Its derived classes can then "bind" data from a client state object to the loaded HTML.

Here is some of the code from that class for reference (not an executable example):

```<code>export class ViewBinder extends PropertyChangedNotifier {
    // Lots of member stuff not shown for brevity...

    public async show(callbackAfterShow?: (wasSuccessful: boolean) => void): Promise<HtmlLoadViewResult> {
        this.showWasCanceled = false;
        const loadResult = await this.loadView();
        if (this.showWasCanceled) {    // Helps my situation some but not fully
            // If this.clear() was called during loadView, we just move on...
            loadResult.wasCanceled = true;
        } else {
            // HERE is where I can have a problem: if this.clear() is called
            // while a derived class is doing its setupAfterShowing, the underlying
            // HTML will be removed and the attempt to setup (binding data to the
            // HTML) will cause an unwanted error.
            await this.setupAfterShowing(loadResult);
            // CODE REMOVED FOR BREVITY
        }
        return loadResult;
    }

    public clear(): void {
        // If the show function is awaiting anything, tell it it was canceled
        // BUT: what I WANT to do is somehow wait until show() is done before
        // continuing the execution of this function... see the question text
        this.showWasCanceled = true;
        this.localViewBinders.forEach((viewBinder) => viewBinder?.clear());
        this.localBindingContexts.forEach((context) => context?.clear());
        if (this.parentElement) {
            this.parentElement.innerHTML = "";
            if (this.isModalDialog) {
                this.parentElement.remove();
            } else {
                this.collapse();
            }
            this.parentElement = null;  // We are no longer associated with the element
            this.notifyPropertyChanged("visibility");
            this.removeAllPropertyChangedListeners();
        }
    }

}
</code>```

Note that derived classes will develop setupAfterShowing methods that "bind" data from the client state object to the HTML that has been loaded (and can call show on their own "child" ViewBinders).  There is also a clear command that removes all the HTML from the parent element and clears out all the "data bindings" as well.

However, there are rare times when the underlying client state object changes while a ViewBinder is awaiting the show command (during the loadView or setupAfterShowing calls), and those changes cause the code to call the clear method, removing the body of the parent element where it was supposed to insert it's HTML and bind the data.

In general, if the ViewBinder doesn't find a parent element or can't find a place in that element to display data, I consider that a bug and I throw an error.  However, in this case the HTML will be removed "legitimately" while the async code is awaiting results.

Note that I've tried to use showWasCanceled to avoid this issue, but there are too many cases of potential issues inside derived setupAfterShowing methods to ensure I'm always aborting if showWasCanceled is set to true.

SO, here is my question:

Is there a way for my clear function determine if the show function is "being awaited" and pause execution until "show" is done?

答:
I'm going to accept the answer from @ABOS since it provides a solution in the spirit of an async/await process (having clear() await a promise that show() can resolve).

However, I ended up taking a somewhat old-school approach and wanted to document it here in case others found it useful.

Note that this also prevented me from having to make clear an async method (which caused me to go async "all-the-way-down" in a lot of places).

Here's the description:

First I added two booleans to the class: clearWasCalled and isRunningShow.

When show() is called, it sets this.clearWasCalled = false and this.isRunningShow = true.  At the end of show(), it sets this.isRunningShow = false and if this.clearWasCalled === true it will call this.clear().

When clear() is called, it checks if this.isRunningShow === true, and if so, it sets this.clearWasCalled = true and exits.

So, when awaiting the show() method, if something calls clear(), it does not interrupt the show() function but merely sets a flag.  When show() is done, it checks whether the flag was set and if so it makes sure the clear action is accomplished.

Here is the basic idea in code:

```<code>export class ViewBinder extends PropertyChangedNotifier {
    // Lots of member stuff not shown for brevity...

    public clearWasCalled = false;
    public isRunningShow = false;

    public async show(callbackAfterShow?: (wasSuccessful: boolean) => void): Promise<HtmlLoadViewResult> {
        this.clearWasCalled = false;
        this.isRunningShow = true;
        const loadResult = await this.loadView();
        if (this.clearWasCalled === false) {    // Just in case...
            // If this.clear() was called during loadView, we just move on...
            loadResult.wasCanceled = true;
        } else {
            await this.setupAfterShowing(loadResult);
            // CODE REMOVED FOR BREVITY
        }
        this.isRunningShow = false;
        if (this.clearWasCalled) {
            this.clear();
            loadResult.wasCanceled = true;
        }
        return loadResult;
    }

    public clear(): void {
        // If we're running a show method, don't clear until it's done
        if (this.isRunningShow) {
            this.clearWasCalled = true;
            return;
        }

        // PERFORM CLEAR ACTIONS...
    }

}
</code>```

Body:
I'm working on the client-side of a web application using TypeScript.

I have my own "framework" where I've developed a class (ViewBinder) that uses an async "show" method to load information from the server, extract HTML, and insert it into the document within a parent "placeholder" element.  Its derived classes can then "bind" data from a client state object to the loaded HTML.

Here is some of the code from that class for reference (not an executable example):

export class ViewBinder extends PropertyChangedNotifier {
    // Lots of member stuff not shown for brevity...

    public async show(callbackAfterShow?: (wasSuccessful: boolean) => void): Promise<HtmlLoadViewResult> {
        this.showWasCanceled = false;
        const loadResult = await this.loadView();
        if (this.showWasCanceled) {    // Helps my situation some but not fully
            // If this.clear() was called during loadView, we just move on...
            loadResult.wasCanceled = true;
        } else {
            // HERE is where I can have a problem: if this.clear() is called
            // while a derived class is doing its setupAfterShowing, the underlying
            // HTML will be removed and the attempt to setup (binding data to the
            // HTML) will cause an unwanted error.
            await this.setupAfterShowing(loadResult);
            // CODE REMOVED FOR BREVITY
        }
        return loadResult;
    }

    public clear(): void {
        // If the show function is awaiting anything, tell it it was canceled
        // BUT: what I WANT to do is somehow wait until show() is done before
        // continuing the execution of this function... see the question text
        this.showWasCanceled = true;
        this.localViewBinders.forEach((viewBinder) => viewBinder?.clear());
        this.localBindingContexts.forEach((context) => context?.clear());
        if (this.parentElement) {
            this.parentElement.innerHTML = "";
            if (this.isModalDialog) {
                this.parentElement.remove();
            } else {
                this.collapse();
            }
            this.parentElement = null;  // We are no longer associated with the element
            this.notifyPropertyChanged("visibility");
            this.removeAllPropertyChangedListeners();
        }
    }

}

Note that derived classes will develop setupAfterShowing methods that "bind" data from the client state object to the HTML that has been loaded (and can call show on their own "child" ViewBinders).  There is also a clear command that removes all the HTML from the parent element and clears out all the "data bindings" as well.

However, there are rare times when the underlying client state object changes while a ViewBinder is awaiting the show command (during the loadView or setupAfterShowing calls), and those changes cause the code to call the clear method, removing the body of the parent element where it was supposed to insert it's HTML and bind the data.

In general, if the ViewBinder doesn't find a parent element or can't find a place in that element to display data, I consider that a bug and I throw an error.  However, in this case the HTML will be removed "legitimately" while the async code is awaiting results.

Note that I've tried to use showWasCanceled to avoid this issue, but there are too many cases of potential issues inside derived setupAfterShowing methods to ensure I'm always aborting if showWasCanceled is set to true.

SO, here is my question:

Is there a way for my clear function determine if the show function is "being awaited" and pause execution until "show" is done?

Body:
I'm going to accept the answer from @ABOS since it provides a solution in the spirit of an async/await process (having clear() await a promise that show() can resolve).

However, I ended up taking a somewhat old-school approach and wanted to document it here in case others found it useful.

Note that this also prevented me from having to make clear an async method (which caused me to go async "all-the-way-down" in a lot of places).

Here's the description:

First I added two booleans to the class: clearWasCalled and isRunningShow.

When show() is called, it sets this.clearWasCalled = false and this.isRunningShow = true.  At the end of show(), it sets this.isRunningShow = false and if this.clearWasCalled === true it will call this.clear().

When clear() is called, it checks if this.isRunningShow === true, and if so, it sets this.clearWasCalled = true and exits.

So, when awaiting the show() method, if something calls clear(), it does not interrupt the show() function but merely sets a flag.  When show() is done, it checks whether the flag was set and if so it makes sure the clear action is accomplished.

Here is the basic idea in code:

export class ViewBinder extends PropertyChangedNotifier {
    // Lots of member stuff not shown for brevity...

    public clearWasCalled = false;
    public isRunningShow = false;

    public async show(callbackAfterShow?: (wasSuccessful: boolean) => void): Promise<HtmlLoadViewResult> {
        this.clearWasCalled = false;
        this.isRunningShow = true;
        const loadResult = await this.loadView();
        if (this.clearWasCalled === false) {    // Just in case...
            // If this.clear() was called during loadView, we just move on...
            loadResult.wasCanceled = true;
        } else {
            await this.setupAfterShowing(loadResult);
            // CODE REMOVED FOR BREVITY
        }
        this.isRunningShow = false;
        if (this.clearWasCalled) {
            this.clear();
            loadResult.wasCanceled = true;
        }
        return loadResult;
    }

    public clear(): void {
        // If we're running a show method, don't clear until it's done
        if (this.isRunningShow) {
            this.clearWasCalled = true;
            return;
        }

        // PERFORM CLEAR ACTIONS...
    }

}


问:
How do you know when your learning rate should be reduced?
The question is more of a general question on tips on how to know if it should be reduced. If you aren't getting good results, would a reduction in learning rate help?

Generally you have a start and and end and step down miles stones. How do you know the learning rate should not just go lower and lower? "Just try it" is probably the answer.

There was a paper where it equated learning rate with complexity. So as a model runs it's learning rate needs to be reduced to build more complex data patterns.

Any insights would be great.

Thanks.

答:
Often it makes sense to reduce the learning rate when no more improvements can be achieved with the currently set learning rate. The whole process can also be automated. If you use Pytorch have a look here: https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-rate

But it is important to find a good learning rate for the beginning. I often try it out for a few epochs. If you don't get good results, it may be due to the learning rate, but it doesn't have to be. It can also be too small as well as too large. If the loss values fluctuate strongly, it is probably too large and if they do not go down too small.


问:
Can we use WCF Discovery to discover services outside your local network?
Is it possible to use WCF discovery to access services that reside outside your local network ?</p>

答:
The short answer is no.

Discovery uses a UDP broadcast packet. You can discover anything that your UDP broadcast packet is allowed to reach.  There is the catch, most routers, firewalls, and commercial switches block udp broadcast packets. You may be able to change the settings on your router where you connect to the next larger network (or internet), and you 'might' extend your discovery slightly.  Again though, the very next switch or router you hit will most likely be set to block udp.

In this situation, most people design a "report in" server.  This is one static place to which all other hosts and clients and pre-programmed to "report in" on startup.  This one server keeps a table of where all hosts and clients are, and if one client wants to find a certain host, it asks this main server for the uri of the host its looking for.

EDIT:
Robin mentioned increasing the TTL (Time To Live) from the default of 1 to a higher number. Maybe this will help someone.
https://serverfault.com/a/619825/146341

ContentLicense: CC BY-SA 3.0