text:
Q: How do I switch between languages on Windows 10 like I do in OS X? OS X has this really nice feature when you have 3+ keyboard input sources (languages) and press Cmd + Space you switch between only two of them.
If you want to switch to another (third) language you just hold Cmd and press Space to choose from the list of input sources available.
How can I have similar functionality on Windows 10? I have 3 input sources and looping through them to get to the one I need is really annoying.

A: One can assign in Windows 10 a keyboard shortcut to a language :

*

*Go to Control Panel -> Clock, Language, and Region -> Language -> Advanced settings.

*Under Switching input methods, click Change language bar hot keys,
then click on your language, and finally on Change Key Sequence.

*This will display a dialog where you can assign a shortcut key to that language:

Since the above shortcut keys are quite limited,
it is possible by using for example AutoHotkey to change this to any other
keyboard combination. Once you learn AutoHotkey, it will be easy to reproduce the exact behavior of OSX (one can also ask for help on their forum).
Many AutoHotkey scripts can be found on the Internet and one can tailor them
to fit any need.
The following example script aims at improving the functioning of
Alt+Shift as a toggle between the English and Russian keyboards for the current window :
; This should be replaced by whatever your native language is. See
; http://msdn.microsoft.com/en-us/library/dd318693%28v=vs.85%29.aspx
; for the language identifiers list.
ru := DllCall("LoadKeyboardLayout", "Str", "00000419", "Int", 1)
en := DllCall("LoadKeyboardLayout", "Str", "00000409", "Int", 1)

!Shift::
w := DllCall("GetForegroundWindow")
pid := DllCall("GetWindowThreadProcessId", "UInt", w, "Ptr", 0)
l := DllCall("GetKeyboardLayout", "UInt", pid)
if (l = en)
{
    PostMessage 0x50, 0, %ru%,, A
}
else
{
    PostMessage 0x50, 0, %en%,, A
}

Here are some threads offering scripts for changing the keyboard layout
with various functionality :

*

*Keyboard layout switcher

*Keyboard layout switcher for many layouts

*Using CapsLock to switch the keyboard language layout
Here are some free products that do that as well :

*

*keyla - Can define keyboard shortcuts or use a taskbar icon

*Recaps - Uses CapsLock to switch the keyboard language

A: If you want the exact behavior as in macOS, without having to configure, you can use Ctrl+Win+Space to switch between the two recently used languages, like what you get from Cmd+Space.
To switch to other input methods, like when you hit Cmd+Space twice, just use Win+Space.

A: How to switch languages in Windows 10 (almost) like in OS X, Android, IPhone
There is (almost perfect) solution for this issue in Windows 7,
which is possible to implement in Windows 10 with few additional steps.
Background
The solution is based on the fact that there're two distinct entities
in Windows: Input Language and Keyboard Layout.
By default Alt+Shift loops through configured Input Languages
and it is Input Language which people usually add when they require
additional languages in their systems.
But.

*

*It is possible to alter behavior of Alt+Shift (or Ctrl+Shift
if you prefer) to loop through Keyboard Layouts and not to change
Input Language.

*It is possible to specify different keyboard shortcut
for every Input Language (as it is also described in one of other answers to this question)

*Most importantly it is possible to add unrelated Keyboard Layout to an Input Language (even layout with different script), for example Hebrew Layout to English Language. This step is a bit tricky in Windows 10, but doable.

Finally you'll end up having several different Input Languages,
for each of which you'll have separate keyboard shortcut, but
once you choose Input Language you'll be able to use regular Alt+Shift
which will loop between defined Keyboard Layouts "inside" of the Input Language.
Configuration in Windows 10
For simplicity, let's assume that you want to use 3 languages: English, Russian and Hebrew. Upon completing the steps below you'll have three modes
of operation:

*

*English mode, used by default, selected with Ctrl+1 and Alt+Shift (or Ctrl+Shift) looping between English and Russian

*Hebrew mode, selected with Ctrl+2 and with Alt+Shift (or Ctrl+Shift) looping between English and Hebrew

*Russian mode, selected with Ctrl+3  and with Alt+Shift (or Ctrl+Shift) looping between English and Russian

Steps to configure.

*

*Ctrl-Esc (which opens Start Menu) - or Windows Button in the left bottom corner of the screen

*Type Language (which should bring up Language item from Control Panel), press Enter

*Depending on your vendor you might have English and your regional language. Assuming you have only English, add Russian and Hebrew with Add a language button

*Every language comes with default Input Method, which corresponds to the language. Now we will add "unrelated" Input Method to each Input Language:

*

*Download Microsoft Keyboard Layout Creator

*File -> Load Existing Keyboard.

*Choose the layout which you want to add (let's start with Russian Layout for English Input Language)

*Project -> Properties

*Modify Language to match Input Language for which you want this keyboard layout to be available. It would be English (United States) in our case.

*Press OK. You might need to modify Description slightly if you get "Keyboard description is identical" error message. Just add some suffix.

*Open the Project menu and choose Build DLL and Setup Package. Ignore warning, agree to open directory where Windows Installer package was built.

*Run setup.exe, which installs your Keyboard Layout for the chosen Input Language

*If you reopen (close and open once again) Language screen (from step 2) and choose Options for English (United States) language, you should see two input methods now: US and Unavailable input method

*Repeat steps 4.1-4.9 for all the needed keyboard layouts (for the example that we're discussing, we would need two more repetitions: load English keyboard set Language to Russian in Project -> Properties and build it, load English keyboard again, set Language to Hebrew in Project -> Properties and build it).

*Upon successful completion of previous steps you should have Unavailable input method on the Options screen for every language that you used as the target language in step 4.5.

*Last step is to configure keyboard shortcuts. Open Language screen (steps 1-2)

*

*Choose Advanced settings (on the left pane of Language screen)

*Choose Change language bar hot keys

*Choose Between input languages (left mouse click) and press Change Key Sequence button

*Choose Not Assigned in the Switch Input Language pane

*Choose Left Alt + Shift (or the one you prefer) in Switch Keyboard Layout pane

*Confirm (OK).

*Choose To English (United States) - US (left mouse click), press Change Key Sequence button, check Enable Key Sequence, choose Ctrl and 1 (or any other preferrable), confirm

*Choose To Hebrew (Israel) - Hebrew (Standard) (left mouse click), press Change Key Sequence button, check Enable Key Sequence, choose Ctrl and 2 (or any other preferrable), confirm

*Choose To Russian (Russia) - Russian (left mouse click), press Change Key Sequence button, check Enable Key Sequence, choose Ctrl and 3 (or any other preferrable), confirm

*Reboot (yes, keyboard shortcuts are quite buggy in Windows, once you change them, you'll need to reboot so that they're registered correctly).

Configuration in Windows 7
Configuring the same use case in Windows 7 is simpler and doesn't require
downloading additional tools.

*

*Ctrl-Esc (which opens Start Menu) - or Windows Button in the left bottom corner of the screen

*Type Region and Language (which should bring up Language item from Control Panel), press Enter

*Keyboards and Languages tab -> Change keyboards

*Choose Add button and search for English (United States) section

*Click + (plus sign) which open Keybord section

*Open it and click Show More... item, which will complement the list with all the different languages, find Russian in this list and check it (make sure you selected Russian inside of Keyboard inside of English (United States) list.

*After confirming you should have two Keyboards under EN English (United States): US and Russian.

*Click Add, search for Hebrew (Israel) and select Hebrew, Show more..., United States-International (which will be available only after choosing Show more), confirm

*Click Add, search for Russian (Russia) and select Russia, Show more..., US (which will be available only after choosing Show more), confirm

*Go to Advanced Key Settings tab

*Choose Between input languages (left mouse click)

*Choose Change Key Sequence button

*Set Switch Input Language to None, Switch Keyboard Layout to Left Alt + Shift (or Ctrl + Shift), confirm

*To English (United States) - US -> Change Key Sequence -> Enable Key Sequence, set to Ctrl+1, confirm

*To Hebrew (Israel) - United States-International -> Change Key Sequence -> Enable Key Sequence, set to Ctrl+2, confirm

*To Russian (Russia) - US -> Change Key Sequence -> Enable Key Sequence, set to Ctrl+3, confirm

*Confirm (OK).

*Reboot.

Notes
There's one peculiarity: in some programs you might get garbled characters, unless you switch to the right Input Language (for example, if you get garbled Russian input, use Ctrl+3 to switch to Russian keyboard layout). But it happens quite rarely and only in some unusual circumstances (for most of Windows users), doesn't really bother me a lot.

A: ; AutoHotkey Script
#SPACE::
  Send ^#{SPACE}
Return

; ♥
; macOS-like input language change algorithm
; Just use WIN + SPACE as normal
; Hold the WIN then tap SPACE to loop

; Test environment
; OS Version  : Windows 10 1803
; AHK Version : 1.1.30.01

; Title  : default setting should be like this
; Date   : 4/8/2019
; Author : who cares

A: You can simply use the keyboard shortcut Alt + Shift to iterate throught the defined languages (and it loops ;) ).

A: I caught your meaning.You mean IME (Input Method).you can use Ctrl + Space to set defeat IME,and Ctrl + Shift to move to next IME .

A: The direct registry setting to disable the keyboard layout toggle hotkeys is:
reg add "HKCU\Keyboard Layout\Toggle" /v "Layout Hotkey" /d 3

You might also want
reg add "HKCU\Keyboard Layout\Toggle" /v "Language Hotkey" /d 3
reg add "HKCU\Keyboard Layout\Toggle" /v "Hotkey" /d 3

And for new users, try this (in an elevated prompt):
reg load HKEY_USERS\temp "%USERPROFILE%\..\Default\NTUSER.DAT"
reg add "HKEY_USERS\temp\Keyboard Layout\Toggle" /v "Layout Hotkey" /d 3
reg unload HKEY_USERS\temp

A: Type in the search bar of the start menu Control Panel -> Click Language -> Click Advanced settings -> Click Change language bar hot keys -> Click Change Key Sequence

A: For anyone like myself who found themselves here by searching for the default key command for toggling keyboards, the default in Windows is Left Alt + Shift.

A: Alt + Shift is useful if you only have two input methods, but if you have more than two you'll need to use the left and right Alt + Shift combo:

*

*left Alt + left Shift: switching input methods from the top to the bottom

*right Alt + right Shift: switching input methods from the bottom to the top
Then if you switch from input method 1 to 2 using left Alt + left Shift, you can go back by using the right Alt + right Shift.
These are default hotkeys in Windows 10 & 11, no other settings are needed.

For nerds: if you use Alt + Shift to switch between the input methods, the actual order of switching depends on the last key you hit.

*

*L Alt + R Shift will also do bottom -> top

*R Alt + L Shift will also do top -> bottom

Samething for L Shift + R Alt and R Shift + L Alt.


text:
Q: what is the meaning of "cost of option setting rt-wise" comment in MySQL Connector/J ClientPreparedStatement#executeBatchInternal? Env: mysql-connector-java 8.0.19
I have noticed that there is a comment says "cost of option setting rt-wise" in com.mysql.cj.jdbc.ClientPreparedStatement#executeBatchInternal  source code, when I do some batch operations using PreparedStament. Source code snippet from MySQL Connector/J as below:
if (!this.batchHasPlainStatements && this.rewriteBatchedStatements.getValue()) {
    if (((PreparedQuery<?>) this.query).getParseInfo().canRewriteAsMultiValueInsertAtSqlLevel()) {
        return executeBatchedInserts(batchTimeout);
    }

    if (!this.batchHasPlainStatements && this.query.getBatchedArgs() != null
            && this.query.getBatchedArgs().size() > 3 /* cost of option setting rt-wise */) {
        return executePreparedBatchAsMultiStatement(batchTimeout);
    }
}

so, my questions are:

*

*what is the exact meaning of "cost of option setting rt-wise" phrase?

*why MySQL Connector/J choose 3 as the bottom line to rewrite batched statements, why not 4 or other numbers?

thanks.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Laravel 5.4 MailMessage::action() renders html incorrectly I have a Notification with this code:
public function toMail($notifiable)
{
  return (new MailMessage)
    ->subject("Welcome to My App")
    ->greeting('Welcome to My App')
    ->line('Hello, ' . $notifiable->name)
    ->line('You have been registered to My App.')
    ->line('Please do change your temporary password upon your login.')
    ->line('Your email: ' . $notifiable->email)
    ->line('Your temporary password: ' . $this->password)
    ->action('Login to My App', url('/'));
}

It seems that upon receiving the mail, it renders incorrectly and the HTML generated by the action() method is wrong.
Gmail's render:

When I inspected the HTML of the mail via Mailtrap, this is the source:

As you can see, special html characters became html entities.
I've tried updating Laravel via composer update but didn't solve the problem.

A: Oh my bad. I edited my /resources/views/vendor/notifications/email.blade.php file long ago after running php artisan vendor:publish --tag=laravel-notifications.
I tried to set alignments on that template which in turn made the email template render incorrectly.


text:
Q: Android map api-2 disable click I'm in the middle of migrating one of my app to the Android map V2. I'm showing a marker on the map and don't want to send touch events to the map to change the position/zoom level etc. in the earlier version, i was able to disable touch by setting android:clickable="false" in the MapView . how can i do the same thing in the Android map V2?

A: yourmap.getUiSettings().setAllGesturesEnabled(false);

A: Figured it out myself.
mMapFragment.getView().setClickable(false);


text:
Q: Why CreateFileMappingA and CreateFileA uses different return values on error? Both CreateFileMappingA and CreateFileA returns HANDLE type, but CreateFileMappingA returns NULL on error, and CreateFileA returns INVALID_HANDLE_VALUE instead.
I'm wondering why the API is designed like that, why won't those APIs both use NULL or INVALID_HANDLE_VALUE?

A: As explained by Raymond Chen in Why are HANDLE return values so inconsistent?:

Why are the return values so inconsistent?
The reasons, as you may suspect, are historical.
The values were chosen to be compatible with 16-bit Windows


text:
Q: Convert decimal to balanced Heptavintimal I'm trying to make a function to convert decimal to balanced Heptavintimal (0123456789ABCDEFGHKMNPRTVXZ)
where 0 represent -13, D : 0 and Z 13
I have tried this but some cases are not working properly:
static const std::string HEPT_CHARS = "0123456789ABCDEFGHKMNPRTVXZ";

std::string heptEnc(int value){
    std::string result = "";

    do {
        int pos = value % 27;
        result = std::string(HEPT_CHARS[(pos + 13)%27] + result);
        value = value / 27;
    } while (value != 0);

    return result;
}

Here is what I get in this example -14, -15, 14, 15 isn't working
call(x) - expect: result
heptEnc(-9841) - 000: 000
heptEnc(-15) - CX:
heptEnc(-14) - CZ:
heptEnc(-13) - 0: 0
heptEnc(-1) - C: C
heptEnc(0) - D: D
heptEnc(1) - E: E
heptEnc(13) - Z: Z
heptEnc(14) - E0: 0
heptEnc(15) - E1: 1
heptEnc(9841) - ZZZ: ZZZ

A: Just got it working, here is the code:
static const std::string HEPT_CHARS = "0123456789ABCDEFGHKMNPRTVXZ";

inline int modulo(int a, int b)
{
    const int result = a % b;
    return result >= 0 ? result : result + b;
}

std::string heptEnc(int value)
{
    std::string result = "";

    do {
        int pos = value%27;
        result = std::string(HEPT_CHARS[modulo(pos + 13,27)] + result);
        value = (value+pos) / 27;
    } while (value != 0);

    return result;
}

Apparently a mix of mathematical modulo, C++ modulo and modifying the way you update your value did the trick.

A: You're using mod (%) incorrectly.  It's difficult/complicated to know what a signed int will initially be set to. So try this instead:
unsigned int uvalue = std::abs(value);
unsigned int upos = uvalue % 27;
int pos = static_cast<int>(upos) - 13;

Of course you'll have to deal with the sign of your conversion separately:
int sign = value >= 0 ? 1 : -1;


text:
Q: Can Cassandra prevent TTL from updating on upsert of table I have a Cassandra table that is like this...
CREATE TABLE IF NOT EXISTS analytics.data(
    id double,
    data text,
    PRIMARY KEY(id, data)
) WITH default_time_to_live = 120 AND gc_grace_seconds = 60;

My understanding is inserts default to upserts. The problem is according to the docs, upserts still increase the TTL. Short of manually managing this, is there a way to turn off TTL on upsert and just have it updated on insert?
Possible Solution
Using TTL on the upsert allows overriding the table definition and TTL(data) allows us to get the existing TTL. Is a pre select query the only way to do this?


text:
Q: AngularJS: Can't I set a variable value on ng-click? I have a modal that uses ng-show="prefs" to determine visibility.
My desire is to use the close button in the modal to set $scope.prefs to false and to use an anchor tag to set the value to true. However, all I can find on google uses a checkbox rather than anchor tags.
Is there a way to use ng-click to set a variable to false?

A: Just do:
ng-click="prefs = false"

A: While @tymeJV gave a correct answer, the way to do this to be inline with angular would be:
ng-click="hidePrefs()"
and then in your controller:
$scope.hidePrefs = function() {
  $scope.prefs = false;
}

A: You can use some thing like this

<!DOCTYPE html>

      <input type="submit" ng-disabled="btn1||btn2" ng-click="btn1=true" ng-model="btn1" />

      <button ng-disabled="btn1||btn2" ng-model="btn2" ng-click="btn2=true">Click Me!</button>

A: If you are using latest versions of Angular (2/5/6) :
In your component.ts
//x.component.ts
prefs = false;

hidePrefs(){
   this.prefs = true;
}


text:
Q: MSSQL Server Query using correlated query I have two tables:
Employee(EmployeeNum, Ename, Job, MGR, HireDate, SAL,COMM, DeptNo)
Department (DeptNo, DName, LOC)

I am trying to find the following:
Q. Who is the most recently hired employee in each department?
The Query is:
SELECT Employee.Ename,
(SELECT MAX(HireDate)
FROM Department
WHERE Employee.DeptNo = Department.DeptNo)
AS HireDate
FROM Employee;

But I am getting the following error:

Msg 8120, Level 16, State 1, Line 112
  Column 'Employee.Ename' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

What is the correct query that will help me to obtain the most recently hired employee from each department?
Thanks!

A: If this is SQL Server (assuming from that error message) you can use ROW_NUMBER() window function to get at this pretty easily:
SELECT D.DName, E.EName, E.HireDate
FROM
    Department D
    INNER JOIN (
            SELECT EmployeeNum, ENAme, HireDate, ROW_NUMBER() OVER (PARTITION BY DeptNo ORDER BY HireDate Desc) as hirerank
            FROM Employee
        ) E ON D.DeptNo = E.DeptNo
WHERE E.hirerank = 1

A: You have to set group by when you are using max condition :
     SELECT Ename,
     DeptNo
    , MAX(HireDate)
    FROM Employee
    group by Employee.Ename,DeptNo


text:
Q: What is an alternative to PowerDesigner or IBM Rational Rose? I need a powerful development manager like Sybase Power Designer or IBM Rational Rose that support sequence diagrams, data flow diagrams and so on.
Can somebody suggest a good alternative?

A: Dia
Dia is a diagram editor that can be used to draw flow charts, UML diagrams etc.

A: you can try one of these:

*

*Visual Paradim

*EMF - Eclipse Modeling Framework  is a good starting point and here is a tutotial for it.

*Visual Paradigm: SDE for NetBeans

*ArgoUML

*Umbrello

*Dia

A: Also take a look at OpenModelsphere. It is more oriented towards data modeling and can be used for both forward and reverse engineering of physical databases plus it supports a (almost) full range of UML, data modeling and business process modeling diagrams.
Oh, and its GPL v3, so no "community" versions or "non-commercial" or other "Thou shall not ..." restrictions :-)


text:
Q: boost circular buffer in stl vector crashes in release I have a class where I define a circular buffer like so:
class cTest
{
    public:
    boost::circular_buffer<std::vector<std::pair<double, double>>> circDat;
       cTest() : circDat(1000)
       {
       }
};

I then create a stl vector of type cTest
std::vector<cTest> vC;

Afterwards I try to fill the vector like this:
for (unsigned int i = 0; i < 4; ++i)
{
    cTest obj;
    vC.push_back(obj);
}

While this works in Debug mode, in Release, it crashes (sometimes, when I run with from Visual Studio, I get a Heap Corruption message). The boost documentation mentions, that in Debug mode, the uninitialized memory is filled with '0xcc'. I assume, the error I get, has its root in uninitialized memory. But I am not really sure, how to fix this problem.
If I use pointers, it seems to work:
std::vector<cTest*> vC;
for (unsigned int i = 0; i < 4; ++i)
{
    cTest* obj = new cTest;
    vC.push_back(obj);
}

But I still do not know, what the problem with the first version is. If anyone does know, I'd appreciate the help.
Edit:
I've tried to create a minimal, reproducable code but failed. It also seemed to crash randomly, not really correlating to the lines added/removed. I then stumbled on the /GL flag in Visual Studio 2015.
After turning the /GL flag off (in the GUI project - in the library project it can stay on), I've been unable to recreate the crash. I do not know, if this is really a fix. But it seems like there was a similar problem present in Visual Studio 2010:
crash-in-program-using-openmp-x64-only
Edit2:
I've managed to pull together a minimal working example. The code can be downloaded here:
https://github.com/davidmarianovak/crashtest
You need Boost (I used 1.60) and QT5 (I used 5.6.3). Build GoAcquire in Release (/GL is active in Visual Studio). Afterwards, build GoGUI in Release (activate /GL and use 'standard' for link-time code generation). After you've built it, run it and it should crash.
The crash can be avoided by changing this in 'GoInterface.hpp' line 22:
void fillGraphicsViews(std::vector<cSensorConstruct> vSens);

to
void fillGraphicsViews(std::vector<cSensorConstruct> &vSens);

But I do not really believe that it is the problem. Can anyone tell me, what I'm doing wrong? I'm using Visual Studio 2015 for this.

A: I bet you're forgetting about iterator/reference invalidation. So the problem is not with the code shown.

*

*Iterator invalidation rules
This makes sense since you report that pointers seem to work: the pointers stay the same even if push_back causes reallocation.
Simply don't hold on to references/iterators to vector elements when you don't know that they're going to stay valid.
If your vector has a known maximum size, you could "cheat" by reserving the capacity ahead of time:
static constexpr size_t MAX_BUFFERS = 100;

std::vector<cTest> vC;
vC.reserver(MAX_BUFFERS); // never more

And then perhaps guard the invariant:
assert(vC.size() < MAX_BUFFERS);
vC.push_back(obj);


text:
Q: Vibrator In Android, Stopping when the app exits I am basically developing an Applicatin which requires the App to Vibrate just before it closes down.
Now when I call the vibrator.vibrate() function and then call the finish() function, the Vibration is stopped and the app is exited, before the Vibration completes.
I want the app to wait until the vibration gets over and then exit!
Thanks in Advance!

A: I think you need set a duration for vibration for this purpose given links can help you       Can you increase vibrator strength on android devices?.
http://techblogon.com/vibrate-android-phone-programmatically/
After setting duration you need set a timer before exiting that equals to the vibration milliseconds :) so your application will exit after vibration period completed.


text:
Q: Unrecognized selector sent to class (singleton) I have found a few related topics on this question, but I don't understand how the solutions presented there are applicable to a singleton class.
When my app starts up, I call gamestate.shardInstance() in applicationDidBecomeActive but it immediately crashes with the same error every time:
2017-03-22 11:09:09.102 project-mars[46108:28079112] +[project_mars.gameState encodeWithCoder:]: unrecognized selector sent to class 0x103670e60
2017-03-22 11:09:09.107 project-mars[46108:28079112] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[project_mars.gameState encodeWithCoder:]: unrecognized selector sent to class 0x103670e60'

Can someone please help me understand what exactly is happening in this error and how to fix it? Thank you!
class gameState: NSObject, NSCoding {

var GameSettings:gameSettings   //Structure that stores all the game settings
var PlayerStats:gameStatistics     //Structure that stores all game stats
var GameBoard:gameBoard        //Contains the information of the gameboard

private static var Instance: gameState = {
    let instance = gameState.loadgameState()
    //Closure for configuration
    return instance!
}()

private override init(){
    self.GameSettings = gameSettings()
    self.PlayerStats = gameStatistics()
    self.GameBoard = gameBoard()
    super.init()
}

class func sharedInstance() -> gameState{
    return gameState.Instance
}

required init?(coder aDecoder: NSCoder) {
    self.GameSettings = (aDecoder.decodeObject(forKey: "GameSettings") as? gameSettings)!
    self.PlayerStats = (aDecoder.decodeObject(forKey: "PlayerStats") as? gameStatistics)!
    self.GameBoard = (aDecoder.decodeObject(forKey: "GameBoard") as? gameBoard)!
}
func encode(with aCoder: NSCoder) {
    aCoder.encode(gameState.sharedInstance().GameSettings, forKey: "GameSettings")
    aCoder.encode(gameState.sharedInstance().PlayerStats, forKey: "PlayerStats")
    aCoder.encode(gameState.sharedInstance().GameBoard, forKey: "GameBoard")
}
class func loadgameState() ->gameState? {
    let path = gameState.getFilePath()
    print("PATH: \(path) \n")
    if gameState.fileExistsAtPath(path: path){
        if let rawData = NSData(contentsOfFile: path) {
            /// do we get serialized data back from the attempted path?
            /// if so, unarchive it into an AnyObject, and then convert to a GameData object
            if(rawData.length != 0){
                if let data = NSKeyedUnarchiver.unarchiveObject(with: rawData as Data) as? gameState {
                    return data
                }
            }
        }
        return gameState()
    }else{
        return gameState()
    }
}

A: I think you should be able to use the local instance, without calling out to the singleton here.  You're already in the singleton instance
func encode(with aCoder: NSCoder) {
    aCoder.encode(gameState.GameSettings, forKey: "GameSettings")
    aCoder.encode(gameState.PlayerStats, forKey: "PlayerStats")
    aCoder.encode(gameState.GameBoard, forKey: "GameBoard")
}

Please share the gameState.loadgameState() static method - my guess is something else is happening there.


text:
Q: Storing Passwords for Third Party Services My application is ruby-on-rails, but I expect any answers to this question will probably be framework agnostic.
My application sends emails via gmail SMTP using rails ActionMailers a-la:
mail = MyActionMailerSubclass.setup_email

options = { :address          => "smtp.gmail.com",
        :port                 => 587,
        :domain               => 'mydomain.com',
        :user_name            => 'myuser@mydomain.com',
        :password             => 's3cur3p@s$w0rd',
        :authentication       => 'plain',
        :enable_starttls_auto => true  }

mail.delivery_method :smtp, options
mail.deliver

Ok, that's great...there's my password for gmail in plain text in the application code.  Or I could store it in the database in plain text.  Obviously both are unacceptable.
Salting and hashing, the usual technique wont work here because I need to send the password along to gmail.
So, what strategies are there for securing a password for a third party service?
Ultimately that user name and password wont even belong to me, they will belong to the application end-user.

A: Gmail's SMTP server supports two authentication mechanisms: PLAIN and XOAUTH. The PLAIN mechanism requires that you know the user's plaintext password, and I'm glad you aren't prepared to store those.
Take a look at the OAuth protocol as used by Gmail. I haven't ever used it and I just found out that Gmail supports it for SMTP, so I can't help any further, but I'd say that's precisely what you want. OAuth is a way for a service (such as Gmail) to allow third-party services (such as yours) to perform a limited set of actions on behalf of users without logging in with their password.

A: If the application is private then this should be of no concern, but I'm guessing it's for a public / open-source application.
If that is the case, then add a basic example of that file as config/initializers/mail.rb.example and add the real thing to your .gitignore file so that it's never committed. After that, add instructions to the README that people will need to copy over the mail.rb.example file to mail.rb in order for the application to work as intended.


text:
Q: Как в WPF просмотреть изображение? Имеется объект System.Drawing.Bitmap. В WinForms можно было просто использовать PictureBox, чтобы просмотреть изображение. В WPF есть контрол Image, которому Bitmap скормить нельзя. Нашел способ переделки в BitmapImage
    using (MemoryStream ms = new MemoryStream())
            {
                bitmap.Save(ms, ImageFormat.Png);
                ms.Position = 0;
                BitmapImage bi = new BitmapImage();
                bi.BeginInit();
                bi.StreamSource = ms;
                bi.EndInit();
                return bi;
            }

    ImageBox.Source = logic.NextPage(); // это объект Image

Но ничего не происходит (хотя и ошибок нет). Нужна помощь.

A: Попробуйте добавить
bi.CacheOption = BitmapCacheOption.OnLoad;

перед
bi.StreamSource = ms;

Пояснение: BitmapImage содержит внутри оптимизацию, которая не грузит данные сразу, а запоминает StreamSource и грузит потом. Но вы уничтожаете MemoryStream (что правильно), поэтому BitmapImage не может позже загрузит данные.

Для будущих поколений:
System.Windows.Media.ImageSource BitmapToImageSource(System.Windows.Bitmap bmp)
{
    using (var ms = new System.IO.MemoryStream())
    {
        bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        ms.Position = 0;
        var img = new System.Windows.Media.Imaging.BitmapImage();
        img.BeginInit();
        img.CacheOption = System.Windows.Media.Imaging.BitmapCacheOption.OnLoad;
        img.StreamSource = ms;
        img.EndInit();
        return img;
    }
}


text:
Q: What is predicted and controlled in reinforcement Learning? In reinforcement learning, I saw many notions with respect to control and prediction, like Monte Carlo prediction and Monte Carlo control.
But what are we actually predicting and controlling?

A: The term control comes from dynamical systems theory, specifically, optimal control. As Richard Sutton writes in the 1.7 Early History of Reinforcement Learning section of his book [1]

Connections between optimal control and dynamic programming, on the
  one hand, and learning, on the other, were slow to be recognized. We
  cannot be sure about what accounted for this separation, but its main
  cause was likely the separation between the disciplines involved and
  their different goals.

He even goes on to write

We consider all of the work in optimal control also to be, in a sense,
  work in reinforcement learning. We define a reinforcement learning
  method as any effective way of solving reinforcement learning problems,
  and it is now clear that these problems are closely related to optimal
  control problems, particularly stochastic optimal control problems
  such as those formulated as MDPs. Accordingly, we must consider the
  solution methods of optimal control, such as dynamic programming, also
  to be reinforcement learning methods.

Prediction is described as the computation of $v_\pi(s)$ and $q_\pi(s, a)$ for a fixed arbitrary policy $\pi$, where

*

*$v_\pi(s)$ is the value of a state $s$ under policy $\pi$, given a set of episodes obtained by following $\pi$ and passing through $s$.

*$q_\pi(s, a)$ is the action-value for a state-action pair $(s, a)$. It's the expected return when starting in state $s$, taking action $a$, and thereafter following policy $\pi$.

Control is described as approximating optimal policies. When doing control, one maintains both an approximate policy and an approximate value function. The value function is repeatedly altered to more closely approximate the value function for the current policy, and the policy is repeatedly improved with respect to the current value function. This is the idea of generalised policy iteration (GPI). See 5.1 Monte Carlo Control in [1].
[1] Reinforcement Learning: An Introduction, by Richard S. Sutton and Andrew G. Barto

A: The difference between prediction and control is to do with goals regarding the policy. The policy describes the way of acting depending on current state, and in the literature is often noted as $\pi(a|s)$, the probability of taking action $a$ when in state $s$.

So, my question is for prediction, predict what?

A prediction task in RL is where the policy is supplied, and the goal is to measure how well it performs. That is, to predict the expected total reward from any given state assuming the function $\pi(a|s)$ is fixed.

for control, control what?

A control task in RL is where the policy is not fixed, and the goal is to find the optimal policy. That is, to find the policy $\pi(a|s)$ that maximises the expected total reward from any given state.
A control algorithm based on value functions (of which Monte Carlo Control is one example) usually works by also solving the prediction problem, i.e. it predicts the values of acting in different ways, and adjusts the policy to choose the best actions at each step. As a result, the output of the value-based algorithms is usually an approximately optimal policy and the expected future rewards for following that policy.


text:
Q: How to create a dynamic group in AAD using AAD Graph I am able to create a group using ActiveDirectoryClient:
await activeDirectoryClient.Groups.AddGroupAsync(new Group() {
    DisplayName = "Group4",
    MailNickname = "test",
    MailEnabled = false,
    SecurityEnabled = true
});

However, this Group model doesn't provide property which specifies the group type and dynamic group rule.
I also find a way to make an API call which can have the group type figured in the body, but this example doesn't show how to specify the dynamic group rule:
https://learn.microsoft.com/en-us/graph/api/group-post-groups?view=graph-rest-1.0
I would like to know how to do it with C# code implementing the same logic with Azure Portal Ibiza
Azure Portal UI
I used the F12 dev tool to view the api call used by Azure Portal, https://main.iam.ad.ext.azure.com/api/groups/
and the request body is like Screen shot of request body

A: After investigation, I find that MS Graph's Group Model provide the property related with dynamic group staff and could implement my purpose there, so I will go with MS Graph instead of AAD Graph.


text:
Q: Runtime Exception can be thrown? I have written a class in which i am trying to throw a runtime exception. The code is as follows
public class ExceptionTest

{

    public static void ReadFile() throws RuntimeException, FileNotFoundException{
    try{

    BufferedReader b =new BufferedReader(new FileReader("I:\\Workspace\\Basic Java\\bin\\Exceptions\\List To Read.txt"));
    String s = b.readLine();
    while(s!=null){
        System.out.println(s);
        s=b.readLine();
    }
    }
    catch(RuntimeException e){
        throw e;
    }
    catch(FileNotFoundException e){
        throw e;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }

And my main class looks like
public class TheMain {
public static void main(String args[]){
    ExceptionTest.ReadFile();
}
}

my  doubt is can we throw a run time exception?
Please help

A: RunTimeException is an unchecked exception. You can throw it, but you don't necessarily have to, unless you want to explicitly specify to the user of your API that this method can throw an unchecked exception. But even this doesn't seem to be necessary if you mention this fact (that the method can throw a RunTimeException) in the javadoc for this method.
So, in short, yes, you can throw it, but you don't have to, as it does not provide you any given advantage and costs you a few extra lines of code

A: You can throw a java.lang.RuntimeException (or any derived exception), as it is a normal exception. The difference to other exceptions is that you do not need to mention it in the list of thrown but uncaught exceptions a method can throw, ie.

public void foo(int bar) throws RuntimeException {
    throw new RuntimeException("foo(bar)");
}

has the same effect as

public void foo(int bar) {
    throw new RuntimeException("foo(bar)");
}

Despite that, a java.lang.RuntimeException (or anything derived) behaves like a normal exception, ie. it terminates your program, if not caught.

A: throw new RuntimeException('someMessagehere')

A: Ideally Runtime exception should never be thrown deliberately. Java has categorised exception in Checked Exception and Unchecked i.e Runtime exception. We should always throw checked exception. The unchecked exceptions should never occur in the program as they are supposed to be handled programmatically and not by throwing them.


text:
Q: Set the value of an input field How would you set the default value of a form <input> text field in JavaScript?

A: I use setAttribute():
<input type="text" id="example"> // Setup text field
<script type="text/javascript">
  document.getElementById("example").setAttribute('value','My default value');
</script>

A: The simple answer is not in Javascript the simplest way to get the placeholder is through the place holder attribute
<input type="text" name="text_box_1" placeholder="My Default Value" />

A: document.getElementById("fieldId").value = "Value";

or
document.forms['formId']['fieldId'].value = "Value";

or
document.getElementById("fieldId").setAttribute('value','Value');

A: It's simple; An example is:
<input type="text" id="example"> // Setup text field
<script type="text/javascript">
var elem = document.getElementById("example"); // Get text field
elem.value = "My default value"; // Change field
</script>

A: if your form contains an input field like
<input type='text' id='id1' />

then you can write the code in javascript as given below to set its value as
document.getElementById('id1').value='text to be displayed' ;

A: 2023 Answer
Instead of using document.getElementById() you can now use document.querySelector() for different cases
more info from another Stack Overflow answer:

querySelector lets you find elements with rules that can't be
expressed with getElementById and getElementsByClassName

EXAMPLE:
document.querySelector('input[name="myInput"]').value = 'Whatever you want!';

or
let myInput = document.querySelector('input[name="myInput"]');
myInput.value = 'Whatever you want!';

Test:

document.querySelector('input[name="myInput"]').value = 'Whatever you want!';
<input type="text" name="myInput" id="myInput" placeholder="Your text">

A: If you are using multiple forms, you can use:
<form name='myForm'>
    <input type='text' name='name' value=''>
</form>

<script type="text/javascript">
    document.forms['myForm']['name'].value = "New value";
</script>

A: Try out these.
document.getElementById("current").value = 12

// or

var current = document.getElementById("current");
current.value = 12

A: If the field for whatever reason only has a name attribute and nothing else, you can try this:
document.getElementsByName("INPUTNAME")[0].value = "TEXT HERE";

A: The answer is really simple
// Your HTML text field

<input type="text" name="name" id="txt">

//Your javascript

<script type="text/javascript">
document.getElementById("txt").value = "My default value";
</script>

Or if you want to avoid JavaScript entirely: You can define it just using HTML
<input type="text" name="name" id="txt" value="My default value">

A: This is one way of doing it:
document.getElementById("nameofid").value = "My value";

A: <input id="a_name" type="text" />

Here is the solution using jQuery:
$(document).ready(function(){
  $('#a_name').val('something');
});

Or, using JavaScript:
document.getElementById("a_name").value = "Something";

Happy coding :)

A: <form>
  <input type="number"  id="inputid"  value="2000" />
</form>

<script>
var form_value = document.getElementById("inputid").value;
</script>

You can also change the default value to a new value
<script>
document.getElementById("inputid").value = 4000;
</script>

A: This part you use in html
<input id="latitude" type="text" name="latitude"></p>

This is javaScript:
<script>
document.getElementById("latitude").value=25;
</script>

A: You can also try:
document.getElementById('theID').value = 'new value';

A: Direct access
If you use ID then you have direct access to input in JS global scope

myInput.value = 'default_value'
<input id="myInput">

A: The following code work perfectly well:
var $div = ('#js-div-hour input');
$div.attr('value','2022/01/10');


text:
Q: Error running pod install in Android Studio I dont know how to solve this error i am using first time flutter in MacBook
Running pod install...                                             990ms
CocoaPods' output:
↳
CDN: trunk Relative path: CocoaPods-version.yml exists! Returning local because checking is only performed in repo update
Error output from CocoaPods:
↳
Ignoring ffi-1.15.5 because its extensions are not built. Try: gem pristine ffi --version 1.15.5
WARNING: CocoaPods requires your terminal to be using UTF-8 encoding.
Consider adding the following to ~/.profile:
    export LANG=en_US.UTF-8

/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/unicode_normalize/normalize.rb:141:in `normalize': Unicode Normalization
not appropriate for ASCII-8BIT (Encoding::CompatibilityError)
    from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/config.rb:166:in `unicode_normalize'
    from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/config.rb:166:in `installation_root'
    from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/config.rb:226:in `podfile_path'
    from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/user_interface/error_report.rb:105:in `markdown_podfile'
    from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/user_interface/error_report.rb:30:in `report'
    from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/command.rb:66:in `report_error'
    from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/claide-1.1.0/lib/claide/command.rb:396:in `handle_exception'
    from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/claide-1.1.0/lib/claide/command.rb:337:in `rescue in run'
    from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/claide-1.1.0/lib/claide/command.rb:324:in `run'
    from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/command.rb:52:in `run'
    from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/bin/pod:55:in `<top (required)>'
    from /usr/local/Cellar/cocoapods/1.11.3/libexec/bin/pod:23:in `load'
    from /usr/local/Cellar/cocoapods/1.11.3/libexec/bin/pod:23:in `<main>'
/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/unicode_normalize/normalize.rb:141:in `normalize': Unicode Normalization
not appropriate for ASCII-8BIT (Encoding::CompatibilityError)
    from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/config.rb:166:in `unicode_normalize'
    from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/config.rb:166:in `installation_root'
    from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/config.rb:226:in `podfile_path'
    from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/config.rb:205:in `podfile'
    from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/command.rb:160:in `verify_podfile_exists!'
    from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/command/install.rb:46:in `run'
    from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/claide-1.1.0/lib/claide/command.rb:334:in `run'
    from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/command.rb:52:in `run'
    from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/bin/pod:55:in `<top (required)>'
    from /usr/local/Cellar/cocoapods/1.11.3/libexec/bin/pod:23:in `load'
    from /usr/local/Cellar/cocoapods/1.11.3/libexec/bin/pod:23:in `<main>'

Error running pod install
Error launching application on iPhone 14 Pro Max.

A: Seems after upgrading the MacOS to v13, gem will use universal-darwin22 to compile files. If you check /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/include/ruby-2.6.0/ there is only universal-darwin21 availble. So, the solution is simple, try to create a link for universal-darwin22 then install ffi.
On terminal:
cd /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/include/ruby-2.6.0/

sudo ln -sf universal-darwin21 universal-darwin22

sudo gem install ffi


text:
Q: weird 'piratebay.org' hostname on my computer? It appeared many days ago. I was writing down thepiratebay.org on the URL search bar on my browser. But I unintentionally hit enter on piratebay.org and then firefox loads this:
My apache 'index of' home
Have you ever seen this before?
Some more info about:
terminal1
Terminal 2:
iqbal@iqbal:~$ nslookup piratebay.org
;; Got SERVFAIL reply from 127.0.0.1, trying next server
Server:     209.222.18.222
Address:    209.222.18.222#53

Non-authoritative answer:
Name:   piratebay.org
Address: 127.0.0.1

iqbal@iqbal:~$ host piratebay.org
piratebay.org has address 127.0.0.1
Host piratebay.org not found: 4(NOTIMP)
iqbal@iqbal:~$ cat /etc/hosts
127.0.0.1   localhost
127.0.1.1   iqbal
#127.0.1.1  www.facebook.com
192.168.1.34    iqbal   omen.iqbal
192.168.1.33    iqbal   omen.iqbal

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

Terminal 3:
iqbal@iqbal:~$ hostnamectl status
   Static hostname: iqbal
         Icon name: computer-laptop
           Chassis: laptop
        Machine ID: bb5927fcc4fa49d6842b425a4bd2108f
           Boot ID: 6bc61f826871450e88f9523bca4881cf
  Operating System: Ubuntu 16.10
            Kernel: Linux 4.8.0-34-generic
      Architecture: x86-64
iqbal@iqbal:~$ ps aux|grep piratebay
iqbal     6524  0.0  0.0  14232   980 pts/4    S+   20:50   0:00 grep --color=auto piratebay
iqbal@iqbal:~$ lsof|grep piratebay //->nothing here

A: Someone set DNS A record of piratebay.org to 127.0.0.1, so that's loopbacking to server which is on your computer.
See: dig
piratebay.org.      3599    IN  A   127.0.0.1


text:
Q: Multiple View Controller Using Swift My Storyboard Hi I'm new to programming but I'm trying to create an IOS application where I display facts and teach a topic and then at the end do a Quiz. I thought several multiple view controllers would be best for this and have a view controller for each topic then a view controller for each quiz. (Is that the right way of doing it?)
I haven't started on the facts part yet as I don't know how to run a series of facts in order from a data file in swift (Only random ones) when clicking a button, (any idea what the best solution is for this?). On the third view controller which is for my quiz after the teaching part, I tried to implement it and access it through a button from the 2nd view controller, it got onto the 2nd view controller fine and went back from the navigation bar  however it won't let me access the third view controller (which my quiz is on) and when it tries to load up it crashes and goes to the debugging screen. Any help would be Greatly appreciated. As Once I've got one sorted should be easier doing the others.
    `//  BasicsQuizViewController.swift
    //  Java Fun; Learning How To Code
    //
    //  Created by Adam Brooke on 30/03/2017.

//  Copyright © 2017 Adam Brooke. All rights reserved.
//
import UIKit
class BasicsQuizViewController: UIViewController {
@IBOutlet weak var QuestionLabel: UILabel!
@IBOutlet weak var Button1: UIButton!
@IBOutlet weak var Button2: UIButton!
@IBOutlet weak var Button3: UIButton!
@IBOutlet weak var Button4: UIButton!

var CorrectAnswer = String()

override func viewDidLoad() {
    super.viewDidLoad()

    RandomQuestions()

    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func RandomQuestions(){
    var RandomNumber = arc4random() % 4
    RandomNumber += 1

    switch(RandomNumber){

    case 1:
        QuestionLabel.text = "Hello World, What i My Name?"
        Button1.setTitle("John", for: UIControlState.normal)
        Button2.setTitle("Boo", for: UIControlState.normal)
        Button3.setTitle("Adam", for: UIControlState.normal)
        Button4.setTitle("Bill", for: UIControlState.normal)
        CorrectAnswer = "2"
        break
    case 2:
        QuestionLabel.text = "What would you like for tea?"
        Button1.setTitle("Curry", for: UIControlState.normal)
        Button2.setTitle("Hot Dog", for: UIControlState.normal)
        Button3.setTitle("Poo", for: UIControlState.normal)
        Button4.setTitle("Mc D's", for: UIControlState.normal)
        CorrectAnswer = "4"

        break
    case 3:
        QuestionLabel.text = "Are you Gay?"
        Button1.setTitle("Yeah", for: UIControlState.normal)
        Button2.setTitle("No", for: UIControlState.normal)
        Button3.setTitle("Maybe", for: UIControlState.normal)
        Button4.setTitle("A Little", for: UIControlState.normal)
        CorrectAnswer = "2"

        break
    case 4:
        QuestionLabel.text = "What sport do you like?"
        Button1.setTitle("Football", for: UIControlState.normal)
        Button2.setTitle("Rugby", for: UIControlState.normal)
        Button3.setTitle("Tennis", for: UIControlState.normal)
        Button4.setTitle("Golf", for: UIControlState.normal)
        CorrectAnswer = "1"

        break
    default:

        break
    }

}

@IBAction func Button1Action(_ sender: Any) {
    if (CorrectAnswer == "1"){

    NSLog("Correct")
}
else{
    NSLog("Sorry You are Wrong")
    }
}
@IBAction func Button2Action(_ sender: Any) {
    if (CorrectAnswer == "2"){

    NSLog("Correct")
}
else{
    NSLog("Sorry You are Wrong")
    }
}

@IBAction func Button3Action(_ sender: Any) {
    if (CorrectAnswer == "3"){

    NSLog("Correct")
}
    else{
        NSLog("Sorry You are Wrong")
    }
}

@IBAction func Button4Action(_ sender: Any) {
    if (CorrectAnswer == "4"){

    NSLog("Correct")
}
    else{
        NSLog("Sorry You are Wrong")
    }
}

/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}
The Errors 1


text:
Q: WORHP very slow on locally affine function I have a problem where I need to minimize a locally affine function and I choose to use WORHP (later the locally affine property shall be replaced by other local conditions) . The value of the function as well as the derivative and the hessian (which is trivial) is provided as user input and is computed very fast. I have simple box constraints, i.e. all variables should be between 0 and 1 and no other constraints. I consider this as a rather easy problem. Still WORHP need to iterate over 350 times leading to a computation time which is rather high for the easy problem.
Is there a way to choose better parameters for this kind of situation?
The python code I use is given below (The input values are computed by another process.)
def worhp_minimize(n, f, df, hmf, xl, xu, init_x):#f:R^n -> R, df: R^n -> R^n, g:R^n -> R^m, gl in R^m, gu in R^m, dg in R^nxm, hmf:R^n -> R^k, hmg: R^(n+m) -> R^k
  def vectorize(attribute):
    return [float(attribute[i]) for i in range(0,len(attribute))]
  def assign(attribute,list):
    for i in range(0,len(list)):
      if list[i] == "inf":
        attribute[i] = par.infty
      elif list[i] == "-inf":
        attribute[i] = -par.infty
      else:
        if isinstance(list[i],int):
          attribute[i] = list[i]
        else:
          attribute[i] = float(list[i])
  def user_f(opt, wsp, par, cnt):
    opt.f = wsp.scale_obj * f(vectorize(opt.x))
  def user_df(opt, wsp, par, cnt):
    assign(wsp.df.val, wsp.scale_obj*df(vectorize(opt.x)))
  #def user_dg(opt, wsp, par, cnt):
  #  assign(wsp.dg.val, dg(vectorize(opt.x)))
  def user_hm(opt, wsp, par, cnt):
    hess = wsp.scale_obj * hmf(vectorize(opt.x))
    l = len(hess)
    index = 0
    for j in range(0,l):
      wsp.hm.val[l*(l-1)//2 + j] = hess[j][j]
      for i in range(j,l):
        wsp.hm.val[index] = hess[i][j]
        index +=1
  if worhp.check_version(worhp.MAJOR, worhp.MINOR, worhp.PATCH):
    exit(1)
  opt = worhp.OptVar()
  wsp = worhp.Workspace()
  par = worhp.Params()
  cnt = worhp.Control()
  worhp.pre_init(opt, wsp, par, cnt)
  worhp.init_params(par)
  par.NLPprint = 1
  status = worhp.read_params_no_init("worhp.xml", par)
  if status == worhp.DATA_ERROR or status == worhp.INIT_ERROR:
    exit(1)
  opt.n = n
  opt.m = 0
  worhp.init(opt, wsp, par, cnt)
  if cnt.status != worhp.FIRST_CALL:
    print("Main: Initialisation failed.")
    exit(1)
  assign(opt.x, init_x)
  assign(opt.Lambda, [0.]*n)
  assign(opt.xl, xl)
  assign(opt.xu, xu)
  while cnt.status < worhp.TERMINATE_SUCCESS and cnt.status > worhp.TERMINATE_ERROR:
    if worhp.get_user_action(cnt, worhp.Action.CALL_WORHP):
        #print("call worhp")
        worhp.worhp(opt, wsp, par, cnt)
    if worhp.get_user_action(cnt, worhp.Action.ITER_OUTPUT):
        #print("iter output")
        worhp.iteration_output(opt, wsp, par, cnt)
        worhp.done_user_action(cnt, worhp.Action.ITER_OUTPUT)
    if worhp.get_user_action(cnt, worhp.Action.EVAL_F):
        #print("eval f")
        user_f(opt, wsp, par, cnt)
        worhp.done_user_action(cnt, worhp.Action.EVAL_F)
    if worhp.get_user_action(cnt, worhp.Action.EVAL_DF):
        #print("eval df")
        user_df(opt, wsp, par, cnt)
        worhp.done_user_action(cnt, worhp.Action.EVAL_DF)
    if worhp.get_user_action(cnt, worhp.Action.EVAL_HM):
        #print("eval hm")
        user_hm(opt, wsp, par, cnt)
        worhp.done_user_action(cnt, worhp.Action.EVAL_HM)
    if worhp.get_user_action(cnt, worhp.Action.FIDIF):
        #print("fidif")
        worhp.fidif(opt, wsp, par, cnt)
        # No done_user_action!
  worhp.status_msg(opt, wsp, par, cnt)
  return opt.f, vectorize(opt.x)

A: If the Hessian is 0, WORHP will apply some regularisation to get positive definiteness which might slow down convergence. You could try setting the parameter StartBettsTau to a very small value like 1e-16 to avoid much of the regularisation.


text:
Q: Clear Form in Rails(Not Reset Form) I want to create a button that just clears the entire form, not reset it.  I currently have this, but it just resets the form to what it was right after the form submission.
Any Ideas?

A: Does this answer your question? https://stackoverflow.com/a/14313638/6665421
Let me know if that is what you are talking about.

A: You will need to add some JavaScript to target each input and use the correct js function to set them. For most inputs you can just use
$("#id_for_input").val("")
So you will need to create so js that looks similar to this
$("#clear_form_button").on("click", function() {
  $("#first_input").val("");
  $("#second_input").val("");
  $("#third_input").val("");
  $("#fourth_input").val("");
});


text:
Q: Azure App Service and Microsoft.Office.Interop.Word I am developing .Net Core APIs using C#. In my use case, I have password protected Word documents. I need to open these documents programatically and read all the contents from it.
I cannot use OpenXML SDK, since it does not support processing of password protected documents.
I do not want to use any REST APIs since my documents contains GDPR/personal data.
I am trying to use Microsoft.Office.Interop.Word nuget package, which works fine locally. But does not work when we publish my APIs into Azure App Service. Since this package is a Office 365 package, this is expecting Microsoft Word to be installed, which cannot be done in Azure App Service.
Can someone suggest me if there any way where we can deploy Microsoft.Office.Interop.Word libraries into Azure App Service?
Is there any other alternative nuget packages available to which supports extracting text from password protected word document?
Regards, Madhu


text:
Q: If in a UFD every maximal ideal is principal then it is a PID
I want to prove that if in a UFD every maximal ideal is principal then it is a PID.

My line of attack is: If it is a field i.e. it has no non-zero proper ideal, then we are done. Otherwise consider a non-zero proper ideal. Then, by Zorn's lemma, it is contained in some maximal ideal, hence contained in a principal ideal which is not the whole ring. Now we know that if in a UFD every proper ideal is contained a proper principal ideal, then it is a PID, hence we are done.

Is there any other solution without using Zorn's lemma?

A: To prove the result I will use two facts which can be easily find in internet (if not, just tell me):

*

*Let $R$ be a integral domain. Then, $R$ is a UFD iff every non zero prime ideal contains a prime element (Kaplansky criterion).

*In an integral domain every prime ideal is principal iff it is a PID.

Now we are going to prove:

If $R$ is a UFD of Krull dimension one, then it is a PID.

Let $ \mathfrak{p} $ be a non-trivial prime ideal of $ R $ (the ideal $ \langle 0\rangle $ is principal and prime since we are working over integral domains). Since $ R $ is a UFD, we know that there exists some prime element $ p\in\mathfrak{p} $ (Kaplansky). But then $ \langle p\rangle\subseteq\mathfrak{p} $ which implies that $ \mathfrak{p}=\langle p\rangle$, as we assumed every prime ideal to be maximal. Since every non trivial prime ideal is now principal, we conclude that $ R $ is a PID.
Actually you can prove that the converse is also true, using the fact that every PID is a UFD. Then take a prime ideal which we know to be principal and suppose that it is not maximal, which leads you directly to a contradiction

A: The question reduces easily to Prove that a UFD is a PID if and only if every nonzero prime ideal is maximal.
Let $\mathfrak p$ be a non-zero prime ideal. Since the ring is a UFD there is a prime element $p\in\mathfrak p$. If $\mathfrak p$ is not maximal, then there exists a maximal ideal $\mathfrak m$ such that $\mathfrak p\subsetneq\mathfrak m$. By hypothesis $\mathfrak m$ is principal, so $\mathfrak m=(q)$ where $q$ is also prime. From $(p)\subsetneq (q)$ we get $q\mid p$ hence $q$ and $p$ are associates. This means $(p)=(q)$, a contradiction.


text:
Q: Unsupported Modules Detected 2nd question in 2 days - not going well.
I am trying to learn how to use Android Studio via Udacity and struggling to get one of their repository's to work from github. They state that we may have a few issues with syncing as it may have been built using an older SDK than what currently exists
here are the trouble shooting steps they have provided if I come into syncing issues

*

*Fork this repository to your GitHub account.

*Open Android Studio.

*File -> New -> Project from version control - GitHub

*Paste a link from your repository of the forked Miwok app, push Clone.

*Agree the presented terms. Update everything that's asked

but once I have cloned the repository it provides me with this sync error:
Unsupported Modules Detected: Compilation is not supported for following modules: ud839_Miwok. Unfortunately you can't have non-Gradle Java modules and Android-Gradle modules in one project.
and also syncing error:
Gradle sync failed: Could not create parent directory for lock file C:\Program Files\Android\Android Studio\gradle-4.7\wrapper\dists\gradle-2.10-all\a4w5fzrkeut1ox71xslb49gst\gradle-2.10-all.zip.lck
Currently using Android Studio 3.1.3 had trouble ever since the update
All help is appreciated!


text:
Q: Joomla! Timezone I'm a little confused with something: if I setup the timezone on Joomla! Admin (Global Configuration > Location Settings > Server Time Zone) the line below would show the date in my timezone, right?
$JDate = JFactory::getDate('now');
echo $JDate->format('Y-m-d H:i:s', true);

Why I need to do this:
$JDate = JFactory::getDate('now', new DateTimeZone('America/Sao_Paulo'));
echo $JDate->format('Y-m-d H:i:s', true);

I understand it wrong?

A: JFactory::getDate() will always stay in UTC. This is good for storing dates into the database and other calculations.
For displaying a date to a user, it is recommended to use JHtml::date(). This will automatically use your timezone setting.
JHtml::date('now', 'Y-m-d H:i:s');

For more information and to see the code behind this function: http://docs.joomla.org/API16:JHtml/date


text:
Q: Proper way to create unique_ptr that holds an allocated array What is the proper way to create an unique_ptr that holds an array that is allocated on the free store? Visual studio 2013 supports this by default, but when I use gcc version 4.8.1 on Ubuntu I get memory leaks and undefined behaviour.
The problem can be reproduced with this code:
#include <memory>
#include <string.h>

using namespace std;

int main()
{
    unique_ptr<unsigned char> testData(new unsigned char[16000]());

    memset(testData.get(),0x12,0);

    return 0;
}

Valgrind will give this output:
==3894== 1 errors in context 1 of 1:
==3894== Mismatched free() / delete / delete []
==3894==    at 0x4C2BADC: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3894==    by 0x400AEF: std::default_delete<unsigned char>::operator()(unsigned char*) const (unique_ptr.h:67)
==3894==    by 0x4009D0: std::unique_ptr<unsigned char, std::default_delete<unsigned char> >::~unique_ptr() (unique_ptr.h:184)
==3894==    by 0x4007A9: main (test.cpp:19)
==3894==  Address 0x5a1a040 is 0 bytes inside a block of size 16,000 alloc'd
==3894==    at 0x4C2AFE7: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3894==    by 0x40075F: main (test.cpp:15)

A: Use the array version :
auto testData = std::unique_ptr<unsigned char[]>{ new unsigned char[16000] };

Or with c++14, a better form ( VS2013 already has it ):
auto testData = std::make_unique<unsigned char[]>( 16000 );

A: unsigned int size=16000;
std::unique_ptr<unsigned char[], std::default_delete<unsigned char[]>> pData(new unsigned char[size]);

A: Using the T[] specialisation:
std::unique_ptr<unsigned char[]> testData(new unsigned char[16000]());

Note that, in an ideal world, you would not have to explicitly use new to instantiate a unique_ptr, avoiding a potential exception safety pitfall. To this end, C++14 provides you with the std::make_unique function template. See this excellent GOTW for more details. The syntax is:
auto testData = std::make_unique<unsigned char[]>(16000);

A: A most likely better way would be to use std::vector<unsigned char> instead
#include <vector>
#include <string>

using namespace std;

int main()
{
    vector<unsigned char> testData(0x12, 0); // replaces your memset
    // bla
}

The advantage is that this is much less error-prone and gives you access to all kinds of features such as easy iteration, insertion, automatic reallocation when capacity has been reached.
There is one caveat: if you are moving your data around a lot, a std::vector costs a little more because it keeps track of the size and capacity as well, rather than only the beginning of the data.
Note: your memset doesn't do anything because you call it with a zero count argument.

A: Seems like a goofup, i will explain what i mean
class Object {
private :
    static int count;
public :
    Object() {
        cout << "Object Initialized " << endl;
        count++;
    }
    ~Object() {
        cout << "Object destroyed " << endl;
    }
    int print()
    {
        cout << "Printing" << endl;
        return count;
    }
};

int Object::count = 0;

int main(int argc,char** argv)
{
    // This will create a pointer of Object
    unique_ptr<Object> up2 = make_unique<Object>();
    up2->print();
    // This will create a pointer to array of Objects, The below two are same.
    unique_ptr<Object[]> up1 = std::make_unique<Object[]>(30);
    Object obj[30];
    cout << up1.get()[8].print();
    cout << obj[8].print();

    // this will create a array of pointers to obj.
        unique_ptr<Object*[]> up= std::make_unique<Object*[]>(30);
        up.get()[5] = new Object();
        unique_ptr<Object> mk = make_unique<Object>(*up.get()[5]);
        cout << up.get()[5]->print();

        unique_ptr<unique_ptr<Object>[]> up3 =  std::make_unique<unique_ptr<Object>[]>(20);
        up3.get()[5] = make_unique<Object>();

    return 0;
}

Objective of the post is that there are hidden small subtle things you need to understand. Creating array of objects is same as object array of unique_ptr. It will make difference only when you pass it in the argument. Creating array of object pointers of unique_ptr is also not very useful. So only below two you need to use in most scenarios.
unique_ptr<Object> obj;
//and
unique_ptr<unique_ptr<Object>[]>= make_unique<unique_ptr<Object>[]>(20);

A: Probably something like the following?
using namespace std;

int size = get_size();
int const init_value = 123;

unique_ptr<int[]> p = make_unique<int[]>(size)
fill(p.get(), p.get() + size, init_value);


text:
Q: MySQL ReGex statement I have never come across RegEx in mySQL, In a column I have over 500 different server versions. is it possible to only fetch anything before a forward slash so that i can detect the most common servers by filtering out the versions?
Microsoft-IIS/7.5
Microsoft-IIS/6.0
Apache/2.2.24 (Unix)
Apache/2.2.15 (CentO
Apache/1.3.42 (Unix)
Apache/2.2.22 (Ubunt
Resin/3.0.23
Apache/2.2.0 (Linux/

A: In mysql regex cannot return a matched substring, but only return a boolean if the string matches a regular expression or not.
What you need is just a SUBSTR
SUBSTRING(col, 1, LOCATE('/', col) - 1)

but keep in mind that if there is no / in the string you'll end up with an empty string as a result

A: here,
SELECT DISTINCT SUBSTRING(version,1,LOCATE('/', version)-1) FROM TableName

*

*SQLFiddle Demo
because of DISTINCT, only unique rows are displayed.


text:
Q: Recorded script by blaze Meter & browser is showling all cookies but JMeter is not i.e. ai_user & ai_session, how do I get those cookies values? Browser shows all cookies when we hit home request

These are the cookies that appear in browser when we execute home page 1st time, but not in Jmeter request

Its JMeter response that shows cookies

My issue is when I execute home page in browser it shows all cookies 1st time when we hit request but in JMeter home request don't show up all cookies as shown in picture.
I want cookies values i.e. ai_user & ai_session  and pass them to UserSessionId & AppSessionId in HTTP request header. So how do I get those values? I already user HTTP CookiesManager in my script to handle cookies but can't get ai_user & ai_session cookies values.

A: *

*Given you send the same request in JMeter as in the real browser you should get the same response so double check all the request details like:

*

*URL

*Headers

*Body

*etc.

*Try using clean browser session or at least private mode

*Look at Set-Cookie header for the first request and see if the cookies you're looking for are there. It might be the case that the cookies are being set by JavaScript and as per JMeter Project main page

JMeter is not a browser, it works at protocol level. As far as web-services and remote services are concerned, JMeter looks like a browser (or rather, multiple browsers); however JMeter does not perform all the actions supported by browsers. In particular, JMeter does not execute the Javascript found in HTML pages. Nor does it render the HTML pages as a browser does (it's possible to view the response as HTML etc., but the timings are not included in any samples, and only one sample in one thread is ever displayed at a time).

So if this is the case you will need to mimic the JavaScript code logic using JSR223 PostProcessor or just extract the values from the response if they are there using other suitable Post-Processor


text:
Q: AWS SDK for Java version 2 - Delete S3 "folder" or Delete multiple S3 objects I am searching how to delete a S3 folder using AWS SDK for Java version 2. I only managed to find AWS SDK version 1 examples.
I know that S3 is an object store and that the concept of folder does not exist. What I mean here is :

*

*List the S3 objects of a given bucket with a given prefix

*Delete the returned objects using a DeleteObjectsRequest to be able to delete up to 1000 objects in a single HTTP call towards AWS API

When I am searching for examples, I constantly go back to this page : https://docs.aws.amazon.com/AmazonS3/latest/dev/DeletingMultipleObjectsUsingJava.html where it seems this is the version 1 of the AWS SDK for Java that is used. At least, on my side, I imported AWS SDK 2 and I cannot directly instantiate DeleteObjectsRequest as it is shown in this example. I am forced to use builders then I don't find the same methods to specify the list of keys to be deleted.

A: I managed to make it work with the piece of code below.
But I find this way of doing quite cumbersome and I still would like to check with the community if this is the correct way of doing. I especially find quite cumbersome the need to go from a collection of S3Object to a collection of ObjectIdentifier and the chains of builders needed. Why DeleteObjectsRequest's builder does not simply allow to specify a collection of strings being the keys of the objects to be deleted ?
public static void deleteS3Objects(String bucket, String prefix) {
    ListObjectsV2Request request = ListObjectsV2Request.builder().bucket(bucket).prefix(prefix).build();
    ListObjectsV2Iterable list = s3Client.listObjectsV2Paginator(request);
    for (ListObjectsV2Response response : list) {
        List<S3Object> objects = response.contents();
        List<ObjectIdentifier> objectIdentifiers = objects.stream().map(o -> ObjectIdentifier.builder().key(o.key()).build()).collect(Collectors.toList());
        DeleteObjectsRequest deleteObjectsRequest = DeleteObjectsRequest.builder().bucket(bucket).delete(Delete.builder().objects(objectIdentifiers).build()).build();
        s3Client.deleteObjects(deleteObjectsRequest);
    }
}

A: This is an improvement on @Comencau's helpful answer, it handles the case of no objects being found: MalformedXML: The XML you provided was not well-formed or did not validate against our published schema
public static void deleteS3Data(String bucket, String prefix) {
    S3Client s3Client = S3Client.builder().region(region).build();
    ListObjectsV2Request request = ListObjectsV2Request.builder().bucket(bucket).prefix(prefix).build();
    ListObjectsV2Iterable list = s3Client.listObjectsV2Paginator(request);

    List<ObjectIdentifier> objectIdentifiers = list
            .stream()
            .flatMap(r -> r.contents().stream())
            .map(o -> ObjectIdentifier.builder().key(o.key()).build())
            .collect(Collectors.toList());

    if (objectIdentifiers.isEmpty()) return;
    DeleteObjectsRequest deleteObjectsRequest = DeleteObjectsRequest
            .builder()
            .bucket(bucket)
            .delete(Delete.builder().objects(objectIdentifiers).build())
            .build();
    s3Client.deleteObjects(deleteObjectsRequest);
}


text:
Q: Received IP packet header is different from wireshark I'm trying to recode ping command in C as educational purpose.
The ICMP sending seems OK (I compared it to original ping on wireshark) but on IP packet reception I have the following problem:
The 16 bits of total length in IP header are different from what I see on wireshark.
I use recvmsg() function to receive data in a buffer as below.
UPDATE: I do have this behavior on macos but not on a linux VM
    struct msghdr msg;
    struct iovec iov[1];
    char databuf[1000];
    char datacontrol[1000];

    bzero(&(msg), sizeof(msg));
    bzero(&(iov), sizeof(iov));
    bzero(&(databuf), sizeof(databuf));
    bzero(&(datacontrol), sizeof(datacontrol));

    msg.msg_name = env->addr->ai_addr;
    msg.msg_namelen = env->addr->ai_addrlen;
    iov[0].iov_base = &(databuf[0]);
    iov[0].iov_len = sizeof(databuf);
    msg.msg_iov = iov;
    msg.msg_iovlen = 1;
    msg.msg_control = &(datacontrol[0]);
    msg.msg_controllen = sizeof(datacontrol);
    msg.msg_flags = 0;

    int retrecv = recvmsg(env.sockfd, &(msg), MSG_WAITALL);

When I display the data I receive in databuf as below:
    for (int i = 0; i < 20; i++)
    {
        for (int j = 7; j >= 0; j--)
            printf("%d", ((databuf[i] >> j) & 1));
        printf("  ");
        if (i == 7 || i == 15)
            printf("\n");
    }

I have this as result:
01000101  00000000  01000000  00000000  00000000  00000000  00000000  00000000
01110100  00000001  11010111  00110011  11011000  00111010  11010101  01001110
11000000  10101000  00000001  01000100

when currently on wireshark I have:
01000101  00000000  00000000  01010100  00000000  00000000  00000000  00000000
01110100  00000001  11010111  00110011  11011000  00111010  11010101  01001110
11000000  10101000  00000001  01000100

All bits are same except the 3th and 4th (total length of IP packet). I'm aware of little/big endian issue but I don't understand the difference there.
Thank you !


text:
Q: Multiplying two columns In Access Query I want to multiply two columns in a query
Example : Column A * Column B and have the result be displayed in Column C

A: I assume you have a table YourTable containing the columns A and B and that the columns A and B also should be displayed in the resulting query.
So here it is:
Select A, B, A * B As C From YourTable
If not, use just this:
Select A * B As C From YourTable


text:
Q: How do I use Azure Devops TFS REST API to get older TestRuns of a TestPoint/TestCase/TestSuite? The API call:
https://dev.azure.com/{organization}/{project}/_apis/test/Plans/{planId}/Suites/{suiteId}/points?api-version=7.0

Returns JSON data with objects "LastTestRun" and "LastTestResult" that contain their Ids. I am trying to find a proper way of getting older (not last) data of TestResults of the given TestPoint using API calls.
I tried the following API call:
https://dev.azure.com/{organization}/{project}/_apis/test/runs?planId=123

That returns me a list of all TestRuns in the given TestPlan. I can loop through the list and make API call for every single TestRun:
https://dev.azure.com/{organization}/{project}/_apis/test/Runs/{runId}/results

And, then retrieve the TestPointId. The problem is I'm working with large amounts of data, so I'm looping through 7000 API calls and it takes too much time (parallel of course).
I tried calling the last API call with $select so I can retrieve only the TestPointId but it is not supported.
A version of the AzureDevops I am working with: Version Azure DevOps Server 2020 Update 1.2.

A: Based on your expectation, I have tested as well to get test results with only test point value and tested get the runs of a specific test case in a test suite. Neither succeeded.
Currently there seemed no official API support the test point filter. For this, you may access this URL: https://aka.ms/AzDevOpsIdeas to submit any comments and proposals for future releases and implementations.


text:
Q: How Can I Include Navigation Drawer into My XML Layout File I have xml layout main_activity.xml and the root layout element is LinearLayout. I want to include navigation drawer in my application. so I created a menu.xml and header.xml layout file. Then I included the code for the drawer into my activity_main.xml. but it is not working. I think it might be b/c the root element needs to be DrawerLayout. But if I change LinearLayout to DrawerLayout, then my xml is all messed up. It can't find the listview or make sense of the views in the page. I have include the appropiate plugins in my gradle file in order to add DrawerLayout. How can I include navigation drawer in my app. Thanks
main_activity.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/linearLayout_main"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".activity.MainActivity">

    <!--custome toolbar-->
    <include layout="@layout/tool_bar" />

    <!--Wifi name and state-->
    <LinearLayout
        android:id="@+id/linear_wifi_name"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:orientation="horizontal"
        android:layout_marginTop="5dp">

        <ImageView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.20"
            android:gravity="left"
            android:layout_gravity="center_vertical"
            android:src="@drawable/ic_wifi_img"
            />

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.15"
            android:orientation="vertical"
            >

            <TextView
                android:id="@+id/wifi_lable"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"

                android:textSize="17sp"
                android:gravity="left"
                android:layout_gravity="center_vertical"
                android:textColor="@color/colorAccent"
                android:text="WIFI: " />

            <TextView
                android:id="@+id/ip_lable"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="16sp"
                android:gravity="left"
                android:layout_gravity="center_vertical"
                android:textColor="@color/colorAccent"
                android:text="IP: " />

        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.60"
            android:orientation="vertical"
            >

            <TextView
                android:id="@+id/wifi_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="16sp"
                android:gravity="left"
                android:layout_gravity="center_vertical"
                android:textColor="@color/textColor"
                android:text="PORTTECH" />

            <TextView
                android:id="@+id/ipaddress"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="16sp"
                android:gravity="left"
                android:layout_gravity="center_vertical"
                android:textColor="@color/textColor"
                android:text="192.168.1.29/255.255.255.0" />

        </LinearLayout>

    </LinearLayout>

    <!--Progess bar-->
    <ProgressBar
        style="@android:style/Widget.DeviceDefault.Light.ProgressBar.Horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:visibility="visible"
        android:id="@+id/progress_bar" />

    <TextView
        android:id="@+id/result_local"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:typeface="monospace"
        android:text="Local Network:"
        android:paddingLeft="5dp"
        android:textColor="@color/colorAccent"
        android:textSize="18sp"/>

    <ListView
        android:id="@+id/local_network"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <android.support.design.widget.NavigationView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        app:menu="@menu/drawer_menu"
        android:layout_gravity="start"
        app:headerLayout="@layout/drawer_header"
        android:fitsSystemWindows="true"
        android:id="@+id/nav_drawer">

    </android.support.design.widget.NavigationView>

    <RelativeLayout android:layout_width="fill_parent"
        android:id="@+id/ad_layout"
        android:layout_height="wrap_content"
        android:gravity="bottom"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="10dp"
        android:layout_alignBottom="@+id/home_layout">
        <ImageView
            android:id="@+id/scan_button"
            android:layout_width="55dp"
            android:layout_height="55dp"
            android:background="@drawable/round_button"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:src="@drawable/ic_next_button"
            android:layout_marginRight="10dp"/>

    </RelativeLayout>
</LinearLayout>

header file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/nav_header"
    android:layout_width="match_parent"
    android:layout_height="160dp"
    android:background="@color/colorPrimary"
    android:clickable="true"
    android:focusable="true"
    android:foreground="?attr/selectableItemBackgroundBorderless"
    android:gravity="bottom"
    android:orientation="vertical"
    android:padding="16dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">

    <ImageView
        android:id="@+id/nav_header_imageView"
        android:layout_width="64dp"
        android:layout_height="64dp"
        android:src="@mipmap/ic_launcher" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Netdroid"
        android:textSize="22dp"
        android:layout_marginTop="10dp"/>

</LinearLayout>

menu file
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:showIn="navigation_view">

    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_camera"
            android:icon="@drawable/ic_menu_camera"
            android:title="Import" />
        <item
            android:id="@+id/nav_gallery"
            android:icon="@drawable/ic_menu_gallery"
            android:title="Gallery" />
        <item
            android:id="@+id/nav_slideshow"
            android:icon="@drawable/ic_menu_slideshow"
            android:title="Slideshow" />
        <item
            android:id="@+id/nav_manage"
            android:icon="@drawable/ic_menu_manage"
            android:title="Tools" />
    </group>

</menu>

A: Have you add this to your activity ?
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
     this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();

EDIT :
You right you have to use a Drawer Activity, you could use an "include" in your layout like this
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/content_visualisation"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_visualisation"
        app:menu="@menu/activity_visualisation_drawer"/>

</android.support.v4.widget.DrawerLayout>


text:
Q: How can I mutably share an i32 between threads? I'm new to Rust and threading and I'm trying to print out a number while adding to it in another thread. How can I accomplish this?
use std::thread;
use std::time::Duration;

fn main() {
    let mut num = 5;
    thread::spawn(move || {
        loop {
            num += 1;
            thread::sleep(Duration::from_secs(10));
        }
    });
    output(num);
}

fn output(num: i32) {
    loop {
        println!("{:?}", num);
        thread::sleep(Duration::from_secs(5));
    }
}

The above code doesn't work: it always prints 5 as if the number is never incremented.

A: The other answer solves the problem for any type, but as pnkfelix observes, atomic wrapper types are another solution that will work for the specific case of i32.
Since Rust 1.0, you can use AtomicBool, AtomicPtr<T>, AtomicIsize and AtomicUsize to synchronize multi-threaded access to bool, *mut T, isize and usize values. In Rust 1.34, several new Atomic types have been stabilized, including AtomicI32. (Check the std::sync::atomic documentation for the current list.)
Using an atomic type is most likely more efficient than locking a Mutex or RwLock, but requires more attention to the low-level details of memory ordering. If your threads share more data than can fit in one of the standard atomic types, you probably want a Mutex instead of multiple Atomics.
That said, here's a version of kennytm's answer using AtomicI32 instead of Mutex<i32>:
use std::sync::{
    atomic::{AtomicI32, Ordering},
    Arc,
};
use std::thread;
use std::time::Duration;

fn main() {
    let num = Arc::new(AtomicI32::new(5));
    let num_clone = num.clone();

    thread::spawn(move || loop {
        num.fetch_add(1, Ordering::SeqCst);
        thread::sleep(Duration::from_secs(10));
    });

    output(num_clone);
}

fn output(num: Arc<AtomicI32>) {
    loop {
        println!("{:?}", num.load(Ordering::SeqCst));
        thread::sleep(Duration::from_secs(5));
    }
}

Arc is still required for shared ownership (but see How can I pass a reference to a stack variable to a thread?).
Choosing the right memory Ordering is far from trivial. SeqCst is the most conservative choice, but if there is only one memory address being shared, Relaxed should also work. See the links below for more information.
Links

*

*std::sync::atomic module documentation

*Atomics (chapter of The Rustonomicon)

*LLVM Memory Model for Concurrent Operations and Atomic Instructions and Concurrency Guide

A: Please read the "Shared-State Concurrency" chapter of The Rust Book, it explains how to do this in detail.
In short:

*

*Your program does not work because num is copied, so output() and the thread operate on different copies of the number. The Rust compiler will fail to compile with an error if num is not copyable.

*Since you need to share the same variable between multiple threads, you need to wrap it in an Arc (atomic reference-counted variable)

*Since you need to modify the variable inside the Arc, you need to put it in a Mutex or RwLock. You use the .lock() method to obtain a mutable reference out of a Mutex. The method will ensure exclusive access across the whole process during the lifetime of that mutable reference.

use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;

fn main() {
    let num = Arc::new(Mutex::new(5));
    // allow `num` to be shared across threads (Arc) and modified
    // (Mutex) safely without a data race.

    let num_clone = num.clone();
    // create a cloned reference before moving `num` into the thread.

    thread::spawn(move || {
        loop {
            *num.lock().unwrap() += 1;
            // modify the number.
            thread::sleep(Duration::from_secs(10));
        }
    });

    output(num_clone);
}

fn output(num: Arc<Mutex<i32>>) {
    loop {
        println!("{:?}", *num.lock().unwrap());
        // read the number.
        //  - lock(): obtains a mutable reference; may fail,
        //    thus return a Result
        //  - unwrap(): ignore the error and get the real
        //    reference / cause panic on error.
        thread::sleep(Duration::from_secs(5));
    }
}

You may also want to read:

*

*Why does Rust have mutexes and other sychronization primitives, if sharing of mutable state between tasks is not allowed?

*What happens when an Arc is cloned?

*How do I share a mutable object between threads using Arc? (for why we need Arc<Mutex<i32>> instead of Arc<i32>)

*When would you use a Mutex without an Arc? (for why we need Arc<Mutex<i32>> instead of Mutex<i32>)


text:
Q: Write ConfigureServices Method In Another Class File We have a template for our projects in our company in which they write AddTransient<>() methods inside another class. I want to know how to put ConfigureServices method of startup inside another class.
See we have a very simple startup project like this:
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddTransient<LocationService, LocationService>();
        services.AddTransient<PersonService, PersonService>();
        services.AddTransient<UserService, UserService>();
        services.AddAutoMapper(typeof(Startup));
    }

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

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

I want to move my (dependent class registration) to another class inside my project.
So this will be my new Startup.cs:
 public class Startup
{
public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddAutoMapper(typeof(Startup));
}

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

    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}
}

And this will be my ExampleFileName.cs :
 public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<LocationService, LocationService>();
    services.AddTransient<PersonService, PersonService>();
    services.AddTransient<UserService, UserService>();
}

A: First, you have to create a folder named Extensions and there you will create a file name whatever you want. I give my file name is ApplicationService.
Extensions/ApplicationServiceExtensions.cs
namespace API.Extensions
{
    public static class ApplicationServiceExtensions
    {
        public static IServiceCollection AddApplicationServices(this IServiceCollection services, IConfiguration config)
        {

            services.AddTransient<LocationService, LocationService>();
            services.AddTransient<PersonService, PersonService>();
            services.AddTransient<UserService, UserService>();

            return services;

        }
    }
}

startup.cs
 private readonly IConfiguration _config;
        public Startup(IConfiguration config)
        {
            _config = config;

        }

        public IConfiguration Configuration { get; }

        //clarify code

 public void ConfigureServices(IServiceCollection services)
        {
           services.AddApplicationServices(_config);

            //clarify code
        }

So,it's an example of putting the ConfigureServices method of startup inside another class. and which you want.

A: I Typed this blind, but is this what you want?
public abstract class StartUpBase
{
    public virtual void ConfigureServices(IServiceCollection services)
    {
        services.AddTransient<LocationService, LocationService>();
        services.AddTransient<PersonService, PersonService>();
        services.AddTransient<UserService, UserService>();
    }
}

public class StartUp : StartUpBase
{
     public override ConfigureServices(IServiceCollection services)
     {
          services.AddControllers();
          base.ConfigureServices(services);
          services.AddAutoMapper(typeof(Startup));

     }
}

Alternative:
public static class Another
{
   public static IServiceCollection AddTransitentServices(IServiceCollection services)
   {
       //add your transistent services here

       return services;
   }
}

public class StartUp
{
     public override ConfigureServices(IServiceCollection services)
     {
          services.AddControllers();
          services = Another.AddTransitentServices(services)
          services.AddAutoMapper(typeof(Startup));

     }
}