text:
Q: Initializing member data of pointer type to NULL in constructor that uses Builder Pattern I have a constructor which uses an internal Builder object to instantiate a complex object. Five of the members in the data structure are of pointer types. However, using this pattern I am running into problems when the object is destroyed. The following is what my constructor looks like, with member initialization list:
Player::Player(const Builder& builder)
    :m_name(builder._name)
    ,m_description(builder._description)
    ,m_primaryAttributes(builder._primaryAttributes)
    ,m_abilityAttributes(builder._abilityAttributes)
    ,m_armor(builder._armor)
    ,m_weapon(builder._weapon)
    ,m_inventory(new ComponentMap())
{}

The client code works well, as expected:
Player* player = Player::Builder()
    .name("Dylan")
    .description("Super bad-ass hero of the game")
    .primaryAttributes(createPrimaryAttributes())
    .abilityAttributes(createAbilityAttributes())
    .weapon(createWeapon())
    .armor(createArmor())
    .build();

However, if I omit one of the arguments in the message chain, and then destroy my Player object, bad stuff happens:
Player* player = Player::Builder()
    .name("Dylan")
    .description("Super bad-ass hero of the game")
    .primaryAttributes(createPrimaryAttributes())
    .abilityAttributes(createAbilityAttributes())
    .armor(createArmor())
    .build();

// ...

delete player;

// ...

// cleanMemory() gets called in Player::~Player()
void Player::cleanMemory()
{
    if(m_primaryAttributes != NULL )
        delete m_primaryAttributes;
    if(m_abilityAttributes != NULL )
        delete m_abilityAttributes;
    if(m_inventory != NULL )
        delete m_inventory;
    if(m_weapon != NULL)          // oops, bad stuff happens here
        delete m_weapon;
    if(m_armor != NULL)
        delete m_armor;
}

Clearly, this happens because the pointer for weapon didn't get initialized to either NULL or an instance of Weapon object. The constructor also doesn't appear to allow for a default of NULL (at least from what I can see) in the event that one Builder method is omitted from the chain. For now, the client must either give Weapon a pointer to NULL or an instance of an object.
Is there any possible way to get around this without revising this Builder constructor completely? Or, should this be refactored using another pattern, such as Factory, and just go back to a regular constructor with positional parameter list?

A: I sample code you referred isn't very good code base, I would simply suggest below build pattern:
class Builder
{
   Weapon* BuildWeapon() { return new Weapon(); }
   Armor*  BuildArmor(); { return new Armor(); }
};

class Player
{
public:
  Player(const Builder& builder)
  : weapon_ptr(builder.BuildWeapon()),
    armer_ptr(builder.BuildArmor())

private:
  std::shared_ptr<Weapon> weapon_ptr;
  std::shared_ptr<Armor>  armor_ptr;
};

usage:
Builder builder;
std::shared_ptr<Player> player(new Player(builder));

Or you could just
class Player2
{
public:
  Player() {}
  void SetWeapon(Weapon* p) { weapon_ptr.reset(p); }
  void SetArmor(Armor* p) { armor_ptr.reset(p); }

private:
  std::shared_ptr<Weapon> weapon_ptr;
  std::shared_ptr<Armer>  armer_ptr;
};

usage:
   Builder builder;
   std::shared_ptr<Player> player;
   player->SetWeapon(builder.BuildWeaper());
   player->SetArmor(builder.BuildArmor());

As weapon_ptr, armer_ptr are smart pointers, there is no need to call delete for the dynamically allocated memory anymore, thus cleanMemory() function can be removed.
This is just a simple sample, you could expand the Player's interfaces to provide ability to build different element after player object is created.


text:
Q: Need suggestion on Silverlight application I am a beginner in silver light. I created a test application, in which on top there are menus like Home, About Us etc?? and there is a grid control to show content related to menu.
I created controls for Home, About Us etc, and I add this control on a click of associated menu. but I am looking for some generic way, rather than handling click of each menu separately, I also created a common click event, but the problem how can I get the Home COntrol or a About Us Control to add in a grid. In click event method I can get the clicked menu Information. I can write switch statement but it will also not called as a generic.
Something Like find a particular page/Control by its name in a whole silverlight application and add it to my grid.
Thanx!

A: Take a look at Ria Services and MEF. I'm currently on a Silverlight project and we are relying heavily on Ria Services and MEF. We are using a VMMV approach. It's working out nicely.

A: Silverlight has the Frame and Page controls to help you with some of these issues.
Check out:
  http://msdn.microsoft.com/en-us/library/cc838245%28v=vs.95%29.aspx

A: This could be solved by using silverlight navigation, have a look at this blog and here
you can then do something like:
this.MainFrame.Navigate(new Uri("Page2.Xaml",UriKind.Relative));
// where page 2 is your page name taken from your menu item

redpajama_set_name: RedPajamaStackExchange


text:
Q: MAME in Ubuntu 16.04? I've searched this and can only find older threads and for older versions of Linux.
I want to install MAME (arcade emulator) on Ubuntu 16.04. Anyone that has actually got MAME working on Ubuntu 16.04 please let me know the exact process. Thanks.

A: I came across this video on YouTube which shows additional configuration steps. Not tested by myself so take with a grain of salt.
In summary:
sudo add-apt-repository ppa:c.falco/mame
sudo apt-get update
sudo apt-get install mame

Then edit the configuration file to set your default rompath
gedit ~/.mame/mame.ini

And change the rompath line if necessary. The video shows it as
rompath     $HOME/mame/roms;/usr/local/share/games/mame/roms

Don't follow the video's advice to use sudo nautilus - that's a very bad idea. If you really need to open nautilus as root (which should not often be the case, do
sudo -i
nautilus <some directory> &

and when done, remember to type
exit

in the terminal to drop privileges

A: You can get very clear instructions at http://sdlmame.wallyweek.org/repository/ on how to install MAME via an unofficial PPA, which I copy verbatim here because there isn't anything to add:
Open a terminal window (commands may be typed directly or pasted into it) and:

*

*Remove old sdlmame repositories (if any):
sudo rm -f /etc/apt/sources.list.d/sdlmame4ubuntu.*

*Add the main repository for unofficial builds:
sudo add-apt-repository ppa:c.falco/mame

*(optionally) add the repository for "u"(nstable) builds:
(Skip this step to stick with main, stable, not-"u" releases!)
sudo add-apt-repository ppa:c.falco/umame

*Now update the information on your box:
sudo apt-get update

*Finally install the package from the repository:
sudo apt-get install mame


text:
Q: How to sum up a total of two instances in a dice game, after rolling multiple times I have started a project, where it involves generating random numbers and reaching a certain total.
In this project, this is a dice game called "Twenty-One". It's where the user rolls a set of two dice multiple times, until it reaches a total of 21 (not in the number of rolls). During this time, when the user reaches a total of 15, only one die can be used to add up the remaining numbers. If the user reaches exactly 21, then a message will pop up saying he or she won; if it's over 21, then they lose. Here's an example:
2+5 = 7
1+3 = 4 (up to 11)
2+2 = 4 (up to 15)
3+3 = 6 (up to 21) "WINNER!!"

I've have a created a code for this problems, but it's a work in progress. I've also added to the code a series of if and else statements that will show the two dice. This is my code so far:
//"Roll The Dice" button click
private void btnRollDice_Click(object sender, EventArgs e) {
    //Generating random numbers
    Random random = new Random();

    int diceIntA = new int();
    int diceIntB = new int();
    int diaVal, dibVal, total;

    diceIntA = random.Next(1, 7);
    diceIntB = ranbom.Next(1, 7);
    diaVal = diceIntA + 1;
    dibVal = diceIntB + 1;
    total = diaVal + dibVal;

    lblTotal.Text(total.ToString());

    //Image of the first die
        if (diceIntA == 1)
            pbdShow1.Image = pboxDice1.Image;
        else if (diceIntA == 2)
            pbdShow1.Image = pboxDice2.Image;
        else if (diceIntA == 3)
            pbdShow1.Image = pboxDice3.Image;
        else if (diceIntA == 4)
            pbdShow1.Image = pboxDice4.Image;
        else if (diceIntA == 5)
            pbdShow1.Image = pboxDice5.Image;
        else
            pbdShow1.Image = pboxDice6.Image;

        //Image of the second die
        if (diceIntB == 1)
            pbdShow2.Image = pboxDice1.Image;
        else if (diceIntB == 2)
            pbdShow2.Image = pboxDice2.Image;
        else if (diceIntB == 3)
            pbdShow2.Image = pboxDice3.Image;
        else if (diceIntB == 4)
            pbdShow2.Image = pboxDice4.Image;
        else if (diceIntB == 5)
            pbdShow2.Image = pboxDice5.Image;
        else
            pbdShow2.Image = pboxDice6.Image;
}

After reviewing my code, I've thought up of so many ideas where I could add up the numbers of the two dice. An example of this is the following code:
int twentyOne = 21;
int oneDie = 15;

if (total = twentyOne) {
    MessageBox.Show("WINNER!");
}
else (total > twentyOne) {
    MessageBox.Show("You went over 21. You lose.");
}

If the latter code is not efficient, what other method should I use to make the dice total up to 21?


text:
Q: Finding node in group by matching nodes of other group I have XML docs like this:
<groups>
  <group id="A">
    <file id="kr3" href="..."/>
    <file id="6ft" href="..."/>
    ...
  </group>
  <group id="B">
    <file id="8dg" href="..."/>
    <file id="g32" href="..."/>
    ...
  </group>
</groups>
<structs>
  <struct id="abc1">
    <filepointer id="kr3"/>
    <filepointer id="8dg"/>
    ...
  </struct>
  <struct id="abc2">
    <filepointer id="6ft"/>
    <filepointer id="g32"/>
    ...
  </struct>
</struct>

In XSLT I want to find the targetFileUrl.
The struct defines a mapping between files of different group nodes. So I provide a sourceUrl and a targetGroupId. And I want to get out the matching  node that is mapped in struct.
So I need to go this way:

*

*sourcehUrl = 'http://...'

*targetGroupId = 'B'

*sourceFileId = //file[@href=$sourcehUrl]/@id

*structId = //struct/filepointer[@id=$sourceFileId]/../@id

*targetFileId = ???

*targetFileUrl = //file[@id=$targetFileId]/@href
How to find the correct file ID that matches one filepointer in the given struct?


text:
Q: В каком слое нужно реализовывать логику выбора источника данных (локальные данные или сеть)? В каких случаях Domain слой (бизнес-логика) может знать о существовании разных источников данных? Например, у меня есть такой код:
GetUserUseCase {

    UserRepository userRepository;

    GetUserUseCase(UserRepository userRepository) {
       //...
    }

    public Observble<User> getUser(int id) {
        return Observable.merge(userRepository.getLocal(id), userRepository.getRemote(id));
    }

}

т.е. мой репозиторий может отдавать данные из двух источников. Насколько это корректно с точки зрения "Чистой архитектуры"?
Это простой пример, у меня есть более сложные кейсы, когда мне необходимо точно знать из какого источника получены эти данные. Должен ли я пересмотреть свою архитектуру таким образом, чтобы UseCase не знал о разных источниках, т.е. у меня в репозитории был бы один метод getUser(), или это нормальная ситуация?

A: Зависит от требований к приложению, глобально есть два подхода:
1) Умный репозиторий Тогда это на уровне репозитория, а интерактор только просит данные. То есть бизнес логика без понятия откуда и как получены данные. А репозиторий управляет всеми кешами.
2) Глупый репозиторий Репозиторий только знает как достать и как сохранить данные, а интерактор сам говорит откуда и когда. А также именно интерактор решает когда сохранять, очищать данные и так далее
Обычно на практике более прост первый подход, так как пользователю и логике приложения не известно про локальные кеши и прочее.


text:
Q: Using Factless Fact table used as source for Fact Table I have a design for a Property / Occupancy factless fact so I can capture the data for when customers move in and out of properties.
However I am not sure if it is best practice to use this as a source for maybe a occupied flag for my SCD property?
Or a fact table that needs to capture the status of the occupancy?
Please advise :)

A: I would never (or only in exceptional cases) build a fact table just to provide information to update other tables in your DW. Your source system presumably provides the occupancy information so you can use this to update dimensional attributes, where necessary, as part of your ETL processes


text:
Q: Invariant Violation: TurboModuleRegistry.getEnforcing(...): 'NativeReanimated' could not be found so this is the first time I used Reanimated 2 and unfortunately my  App get crashed with the above message. Unable to view my app screen.

Invariant Violation: TurboModuleRegistry.getEnforcing(...): 'NativeReanimated' could not be found. Verify that a module by this name is registered in the native binary.

I'm using reanimated here
import React from 'react'
import Item from '../../Common/Item'
import {View,Text,FlatList,StyleSheet , TouchableOpacity} from 'react-native'

import Animated, {useAnimatedStyle} from 'react-native-reanimated';
import {bin,mix,useTiming} from 'react-native-redash'

const {interpolate,not}=Animated
const SectorItem=({sector,clients,index,opened,toggleSector})=> {
        const {name}=sector
        const ITEM_HEIGHT = 100
        const transition = useTiming(opened)
        const style = useAnimatedStyle(()=>({
          height: mix(transition,0,clients.length * ITEM_HEIGHT)
        }))

        //here we wll also have the clients of each sector
        return <Item xStyle={styles.item}>
                <View>
                    <Text>{name}</Text>
                    <TouchableOpacity onPress={e=>toggleSector(index)}>
                      <Text>open</Text>
                    </TouchableOpacity>
                </View>
                <Animated.View style={style}>
                    <FlatList
                       data   = {clients}
                       style  = {{...styles.Clientlist,display:opened?'flex':'none'}}
                       contentContainerStyle = {props =>(styles.flatList)}
                       showsVerticalScrollIndicator={false}
                       renderItem   = {({ item }) =><Item xStyle={{marginBottom:8}}>
                         <TouchableOpacity>
                           {/* redirect to client  */}
                              <Text>{item.name} </Text>
                         </TouchableOpacity>
                       </Item> }
                       keyExtractor = {(item, index) => index.toString()}
                    />
                </Animated.View>
        </Item>

}

export default SectorItem
var styles = StyleSheet.create({
    list:{
        borderColor:'#fff',
        padding:16,
    },
    Clientlist:{
        borderColor:'#fff',
        padding:16,
    },
    flatList:{
        alignItems: 'center',
         justifyContent: 'center',
         height:200,
         flex:1
    },
    item:{
        marginBottom:8
    }
  });

my package.json :
{
  "name": "DistributionApp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "@react-native-community/masked-view": "^0.1.10",
    "@react-navigation/drawer": "^5.11.5",
    "@react-navigation/native": "^5.9.0",
    "@react-navigation/stack": "^5.13.0",
    "@rematch/core": "^2.0.0-next.10",
    "cross-fetch": "^3.0.6",
    "nanoid": "^3.1.20",
    "react": "16.13.1",
    "react-native": "0.63.4",
    "react-native-elements": "^3.1.0",
    "react-native-fast-image": "^8.3.4",
    "react-native-gesture-handler": "^1.9.0",
    "react-native-reanimated": "^2.0.0-rc.2",
    "react-native-redash": "^16.0.8",
    "react-native-safe-area-context": "^3.1.9",
    "react-native-screens": "^2.16.1",
    "react-redux": "^7.2.2",
    "redux": "^4.0.5",
    "typescript": "^4.1.3"
  },
  "devDependencies": {
    "@babel/core": "^7.8.4",
    "@babel/runtime": "^7.8.4",
    "@react-native-community/eslint-config": "^1.1.0",
    "babel-jest": "^25.1.0",
    "eslint": "^6.5.1",
    "jest": "^25.1.0",
    "metro-react-native-babel-preset": "^0.59.0",
    "react-test-renderer": "16.13.1"
  },
  "jest": {
    "preset": "react-native"
  }
}

A: reanimated package is not auto-linked in android, please follow the steps mentioned on the official documentation.
You need to make changes in
android/app/build.gradle
project.ext.react = [
 enableHermes: true,  // clean and rebuild if changing
]

add following in babel.config.js
plugins: ['react-native-reanimated/plugin']

add following in MainApplication.java
    @Override
    protected JSIModulePackage getJSIModulePackage() {
      return new ReanimatedJSIModulePackage(); // <- add
    }

A: I've downgrande "react-native-reanimated": "2.0.0" to "react-native-reanimated": "1.13.0",
Past in terminal yarn add react-native-reanimated@1.13.0 or
npm install react-native-reanimated@1.13.0 --save
Fixed.

A: I had experienced the same issue with React Native ^0.64.0 and react-navigation 5.x
Reanimated dependency "react-native-reanimated": "^2.0.0" as stated in the official documentation requires some additional configs, including babel, Hermes, and MainApplication.java
Please follow the official documentation to resolve React Native Reanimated

requires additional steps apart from just adding a dependency to
package.json

After making changes make sure to clear gradle and yarn( or npm ) caches

A: following an official guid helped me doc

A: Running npx react-native link react-native-reanimated fixed the issue for me.
Appears that this added the following line to ios/Podfile:
pod 'RNReanimated', :path => '../node_modules/react-native-reanimated'

A: For iOS

Notes: Im using Xcode Version 13.4.1 (13F100) and running the app in Mac M1.

I think this error is same like what i got, i got this error :
Invariant Violation: TurboModuleRegistry.getEnforcing(...): 'ImageLoader' could not be found
And i fix the error with add arm64,amv7 at Exclude Architectures -> Debug -> Any SDK

A: Error - TurboModuleRegistry.getEnforcing(...): 'NativeReanimated'
Cause - React Native Reanimated 2.0

I got this TurboModuleRegistry.getEnforcing(...): 'NativeReanimated' error and I found the solution:
Step 1 - Download react native project from github: https://github.com/software-mansion-labs/reanimated-2-playground
Step 2 - Then run command
npm install
react-native start
react-native run-android

and build app.
Step 3 - when it works, move your required project files and install your required npm pakages.
Step 4 - Then run commands
npm cache clean --force
cd android
gradlew clean
gradle cleanBuildCache
gradlew build --refresh-dependencies
cd..
npx react-native start --reset-cache
npx react-native run-android


text:
Q: Taking a screenshot of surfaceview programmatically in android I have a project that uses SurfaceView to draw some stuff on the screen. User should be able to take screenshot by pressing the button on that screen. Problem is that I always get blank screen when screenshot is taken from SurfaceView. I tried a lot of different answers however none of them worked for me. Here's what I tried:
void takeScre() {
        File file = saveBitmap(getBitmap());
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file), "image/*");
        startActivity(intent);
    }

    Bitmap getBitmap() {
        dots_screen_view.setDrawingCacheEnabled(true);
        return dots_screen_view.getDrawingCache();
    }

//----------
 Bitmap getBitmap() {
        Bitmap b = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
        dots_screen_view.draw(c);

        return b;
    }

//-----------
Bitmap getBitmap() {
        Bitmap b = Bitmap.createBitmap(dots_screen_view.getWidth() , dots_screen_view.getHeight(), Bitmap.Config.ARGB_8888);
        dots_screen_view.setDrawingCacheEnabled(false);
        dots_screen_view.layout(0, 0, dots_screen_view.getLayoutParams().width, dots_screen_view.getLayoutParams().height);
        dots_screen_view.draw(new Canvas(b));

        return b;
    }

Also I have tried those libraries:

https://android-arsenal.com/details/1/6985
https://android-arsenal.com/details/1/6163
https://android-arsenal.com/details/3/5293

However none of them works for me. Any other ideas?

A: Give Selfie a go... I've used it to create social media posts before without any problems. Its open source so if it works, you can see why it works :)

A: Try below code:
/**
    * Check for permissions and create a snapshot
    *
    * @param activity Activity used by Selfie.
    * @return {@code true} if the screenshot was taken, false otherwise.
    */
   public boolean snap(Activity activity) {
      boolean hasPermission = (ContextCompat.checkSelfPermission(activity,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
      if (!hasPermission) {
         ActivityCompat.requestPermissions(activity,
               new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
               REQUEST_WRITE_STORAGE);
         return false;
      } else {
         return takeScreenShot(activity);
      }
   }

   /**
    * This method is responsible for taking the screenshot and creating a file
    *
    * @param activity Activity used by Selfie.
    * @return {@code true} if the screenshot was taken, false otherwise.
    */
   private boolean takeScreenShot(Activity activity) {
      Date now = new Date();
      android.text.format.DateFormat.format(fileFormat, now);

      // create bitmap screen capture
      View v1 = activity.getWindow().getDecorView().getRootView();
      v1.setDrawingCacheEnabled(true);
      Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
      v1.setDrawingCacheEnabled(false);

      // image naming and path to include sd card appending name you choose for file
      String path = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";

      File imageFile = new File(path);

      try {
         FileOutputStream outputStream = new FileOutputStream(imageFile);
         bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
         outputStream.flush();
         outputStream.close();
      } catch (IOException ex) {
         return false;
      }

      return true;
   }

Please add write permission inside the manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

A: I was on similar crossroads earlier and had to do a lot of trial runs to take a screenshot of my custom view class.
Try the following code
public String getBitmapFromView() {

    int dwidth,dheight;
    DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
    if(displayMetrics.widthPixels > displayMetrics.heightPixels)
    {
        //orientation is landscape
        dwidth=displayMetrics.heightPixels;
        dheight=displayMetrics.widthPixels;
    }
    else
    {
        dwidth = displayMetrics.widthPixels;
        dheight=displayMetrics.heightPixels;
    }

    setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

    //If the view wasnt displayed before this , you will get 0,0 measured widths and heights
    //Thus measure the layout
    measure(MeasureSpec.makeMeasureSpec(dwidth, MeasureSpec.AT_MOST),MeasureSpec.makeMeasureSpec(dheight, MeasureSpec.AT_MOST));

    layout(0, 0, getMeasuredWidth(), getMeasuredHeight());

    //Create a bitmap backed Canvas to draw the into
    Bitmap bitmap = Bitmap.createBitmap(getMeasuredWidth(), getMeasuredHeight(), Bitmap.Config.ARGB_8888);
        if (getMeasuredWidth() == 0 && getMeasuredHeight() == 0) {
          //You will get blank bitmap
            return "";
        } else {
            Canvas c = new Canvas(bitmap);

            //Now that the view is here and we have a canvas, ask the to draw itself into the canvas
            draw(c);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 60, stream);
            byte[] byteArray = stream.toByteArray();
            return Base64.encodeToString(byteArray, Base64.DEFAULT);
        }

}

In my scenario I needed to convert the bitmap into String, however, you can convert it into bytes, use bitmap directly, use OutputStream to write this directly to your file.


text:
Q: Show user cards when hovering over name User cards work when the cursor hovers on a shaded user's avatar. (i.e. user with the Established User privilege who filled their About Me section.)
I would prefer it appeared when hovering over the user's display name too. This is because I tend to click the name to reach the user profile. The user card should act like a preview for the profile I'm considering visiting.

I propose we add this functionality to the names, as well as the avatars.

A: You definitely have a good point there, since the name and the gravatar links to the user's profile they both should trigger the expansion of the user card.
I also share your oppinion that it is more intuitive to hover over the name rather than the picture, since we are all used to navigate via text-links over the last decades of surfing through the www.

A: I agree with this. On community wiki posts, you can't view the hovercard, so it would make sense to make the text expand rather than the image. I originally thought it was the text that made the hovercard, simply because it seems more normal for it to be what makes the hovercard show up.

A: I would make an argument against that. Links are not buttons, or images. A user expects a link to go somewhere. Having that link move itself when you hover over it breaks user's expectations and can lead to frustration.


text:
Q: Defining a virtual attribute in Rails and making it available as a symbol I've defined a couple of virtual attributes, defining both the setter and the getters methods:
class Post < ActiveRecord::Base

  def shared_to_all
    # evaluates some expression of the attribute privacy
  end

  def shared_to_friends
    # evaluates some other expression of the attribute privacy
  end

  def shared_to_all=(bool)
    # write_attribute( :privacy, ... )
  end

  def shared_to_friends=(bool)
    # write_attribute( :privacy, ... )
  end

end

So far so good, but I want also to make this virtual attributes available using symbols, so I can do something like @post= Post.first; @post[:shared_to_all]= true
[Edit:]
A Ruby approach would be to override [] and []= operators, like in:
def [](shared_to_all)
  shared_to_all
end

def []=(shared_to_all, bool)
  self.shared_to_all= (bool)
end

But this seems to break Rails relationship methods (those brought by has_one - has_many - belongs_to - has_and_belongs_to_many directives): e.g. now Post.first.author => nil and Author.first.posts => []

A: Seems like this should do it:
def [](attr)
  attr
end
def []=(attr, value)
  self.attr = value
end


text:
Q: using localStorage in Backbone.js I am putting together a backbone example in which models are created edited and deleted. I am able to save new models and edits to local storage, but am having a problem getting localstorage to properly display on refresh. It seems to be loading as a single object, and therefore gives me one model regardless of how many were added.
 var Thing = Backbone.Model.extend({
     defaults: {
         title: 'blank'
     }
 });
 var ThingView = Backbone.View.extend({
     template: _.template('<button id="remove">X</button> <button id="edit">Edit</button> <%= title %>'),
     editTemplate: _.template('<input class="name" value="<%= name %>" /><button id="save">Save</button>'),
     events: {
         "click #remove": "deleteItem",
         "click #edit": "editItem",
         "click #save": "saveItem",
     },
     deleteItem: function () {
         console.log('deleted');
         this.model.destroy();
         this.remove();
     },
     editItem: function () {
         console.log('editing');
         this.$el.html(this.editTemplate(this.model.toJSON()));
     },
     saveItem: function () {
         console.log('saved');
         editTitle = $('input.name').val();
         console.log(editTitle);
         this.model.save({
             title: editTitle
         });
         this.$el.html(this.template(this.model.toJSON()));
     },
     render: function () {
         var attributes = this.model.toJSON();
         this.$el.append(this.template(attributes));
         return this;
     }
 });
 var ThingsList = Backbone.Collection.extend({
     model: Thing,
     localStorage: new Store("store-name"),
 });
 var storeVar = localStorage.getItem("store-name");
 console.log(storeVar);
 var thingsList = new ThingsList;
 thingsList.reset(storeVar);
 var ThingsListView = Backbone.View.extend({
     el: $('body'),
     events: {
         'click #add': 'insertItem',
     },
     initialize: function () {
         this.render();
         this.collection.on("add", this.renderThing, this);
     },
     insertItem: function (e) {
         newTitle = $('input').val();
         newThing = new Thing({
             title: newTitle
         });
         this.collection.add(newThing);
         newThing.save();
         console.log(this.collection.length);
     },
     render: function () {
         _.each(this.collection.models, function (items) {
             this.renderThing(items);
         }, this);
     },
     renderThing: function (items) {
         var thingView = new ThingView({
             model: items
         });
         this.$el.append(thingView.render().el);
     }
 });
 var thingsListView = new ThingsListView({
     collection: thingsList
 });

A: You need to add the items to your collection, and then to read it in you need to call fetch. You also have a couple of extra trailing commas in your objects.
Here's a slightly modified version of your code which seems to work.
var Thing = Backbone.Model.extend({
  defaults:{
    title:'blank'
  }
 });

 var ThingView = Backbone.View.extend({
    //el: $('body'),
     template: _.template('<button id="remove">X</button> <button id="edit">Edit</button> <%= title %>'),
     editTemplate: _.template('<input class="name" value="<%= name %>" /><button id="save">Save</button>'),

    events: {
    "click #remove": "deleteItem",
    "click #edit": "editItem",
    "click #save": "saveItem",
    },

    deleteItem: function(){
      console.log('deleted');

            this.model.destroy();
            //remove view from page
            this.remove();
    },

    editItem: function(){
     console.log('editing');
     this.$el.html(this.editTemplate(this.model.toJSON()));
    },

    saveItem: function(){
     console.log('saved');
     editTitle = $('input.name').val();
     console.log(editTitle);
     this.model.save({title: editTitle});
     this.$el.html(this.template(this.model.toJSON()));
    },

    render: function(){
      var attributes = this.model.toJSON();
      this.$el.append(this.template(attributes));
      return this;
    }
 });

 var storeVar = localStorage.getItem("store-name");

 var ThingsList = Backbone.Collection.extend({
   model: Thing,
   localStorage: new Store("store-name")
});

 var things = [
  { title: "Macbook Air", price: 799 },
  { title: "Macbook Pro", price: 999 },
  { title: "The new iPad", price: 399 },
  { title: "Magic Mouse", price: 50 },
  { title: "Cinema Display", price: 799 }
];

console.log(things);

var thingsList = new ThingsList;

var ThingsListView = Backbone.View.extend({
   el: $('body'),

events: {
      'click #add': 'insertItem'
    },

initialize: function () {
    this.render();
    this.collection.on("add", this.renderThing, this);
    },

    insertItem: function(e){
      newTitle = $('input').val();
      newThing = new Thing({ title: newTitle });
      this.collection.add(newThing);
      newThing.save();
      //this.model.saveItem;
      console.log(this.collection.length);
    },

   render: function(){
     _.each(this.collection.models, function (items) {
            this.renderThing(items);
        }, this);
    },

  renderThing: function(items) {
    //console.log('added something');
    var thingView = new ThingView({ model: items });
        items.save();
    this.$el.append(thingView.render().el);
  }

});

var thingsListView = new ThingsListView( {collection: thingsList} );
thingsList.fetch();
console.log(thingsList.toJSON());
thingsList.reset(things);

Edit: I see you are trying to read in the value stored in local storage under "store-name", the way backbone-localStorage works is that it uses the name of the store (in your case "Store-name") to store the ids of the rest of the models and then saves each model under a combination of the store name and the id, so say you had three models, you would end up with 4 entries in local storage,
  localStorage["store-name"]  //id1, id2, id3"
  localStorage["store-name-id1"] //model with id1
  localStorage["store-name-id2"] // model with id2
  localStorage["store-name-id3"] // model with id3

EDIT 2
Here's a link to a jsfiddle of your code, to start I'm leaving the line thingsList.fetch(); commented out, uncomment that line and comment out thingsList.add(things); and run it a second time and it should pull the models from local Storage (I left an alert in there).

A: var Thing = Backbone.Model.extend({
     defaults: {
         title: 'blank'
     }
 });
 var ThingView = Backbone.View.extend({
     template: _.template('<button id="remove">X</button> <button id="edit">Edit</button> <%= title %>'),
     editTemplate: _.template('<input class="name" value="<%= name %>" /><button id="save">Save</button>'),
     events: {
         "click #remove": "deleteItem",
         "click #edit": "editItem",
         "click #save": "saveItem",
     },
     deleteItem: function () {
         console.log('deleted');
         this.model.destroy();
         this.remove();
     },
     editItem: function () {
         console.log('editing');
         this.$el.html(this.editTemplate(this.model.toJSON()));
     },
     saveItem: function () {
         console.log('saved');
         editTitle = $('input.name').val();
         console.log(editTitle);
         this.model.save({
             title: editTitle
         });
         this.$el.html(this.template(this.model.toJSON()));
     },
     render: function () {
         var attributes = this.model.toJSON();
         this.$el.append(this.template(attributes));
         return this;
     }
 });
 var ThingsList = Backbone.Collection.extend({
     model: Thing,
     localStorage: new Store("store-name"),
 });
 var storeVar = localStorage["store-name-7ee7d1e3-bbb7-b3e4-1fe8-124f76c2b64d"];
 console.log(storeVar);
 var thingsList = new ThingsList;
 //thingsList.reset(storeVar);
 var ThingsListView = Backbone.View.extend({
     el: $('body'),
     events: {
         'click #add': 'insertItem',
     },
     initialize: function () {
    thingsList.fetch();
    thingsList.toJSON();
         this.render();
         this.collection.on("add", this.renderThing, this);
     },
     insertItem: function (e) {
         newTitle = $('input').val();
         newThing = new Thing({
             title: newTitle
         });
         this.collection.add(newThing);
         newThing.save();
         console.log(this.collection.length);
     },
     render: function () {
         _.each(this.collection.models, function (items) {
             this.renderThing(items);
         }, this);
     },
     renderThing: function (items) {
         var thingView = new ThingView({
             model: items
         });
         this.$el.append(thingView.render().el);
     }
 });
 var thingsListView = new ThingsListView({
     collection: thingsList
 });


text:
Q: How to pass a method to another method that accepts Func? I've this method:
RateLimiter.Perform(Func<Task> perform)

and I want to perform this method:
await PassMessageAsync(message, id, name)

It shows no error, just to make sure, is this the correct way?:
await RateLimiter.Perform(async () => { await PassMessageAsync(message, id, name);});

Update:
The idea is to limit number of concurrent methods.
public async Task<T> Perform<T>(Func<Task<T>> perform, CancellationToken cancellationToken)
{
    cancellationToken.ThrowIfCancellationRequested();
    using (await _AwaitableConstraint.WaitForReadiness(cancellationToken))
    {
        return await perform();
    }
}

How can I change the signature to accept any method with any much parameters, and await it?

A: Since there have been no answers at all so far, I will attempt to answer your specific questions. Regarding:
await RateLimiter.Perform(async () => { await PassMessageAsync(message, id, name);});

It shows no error, just to make sure, is this the correct way?:

That will work, but the lambda does not need to be async. You simply need to pass in something that can be awaited, e.g. Task/Task<T>:
await RateLimiter.Perform(() => PassMessageAsync(message, id, name));

By doing this you are making your code cleaner and eliminating an extra await.

How can I change the signature to accept any method with any much
  parameters, and await it?

You could probably manage this with dynamics or some such loose typing, but I wouldn't. What you can do is change what you are passing in to match the signature you have. As it happens, that is precisely what you have done in creating a lambda statement.
So how does that answer your question? Well, assuming that we are only interested in passing methods that return Task or Task<T> to Perform, you will need two methods: one for each. You already have a function for Task<T>. The function for Task will look like this:
public async Task Perform(Func<Task> perform, CancellationToken cancellationToken)
{
  cancellationToken.ThrowIfCancellationRequested();
  using (await _AwaitableConstraint.WaitForReadiness(cancellationToken))
  {
    await perform();
  }
}

These two methods should be all you need.


text:
Q: If $\alpha \vdash \phi$ and $\beta \vdash \phi$, does it mean that $\alpha \cap \beta \vdash \phi$? I would like to know if this is correct.

A: Consider the following example :
$A = \{ p \land q \}$ and $B = \{ q \land r \}$.
We have $A \vdash q$ and $B \vdash q$.
But $A \cap B = \emptyset$ and :

$\emptyset \nvdash q$,

because $q$ is not a tautology.


text:
Q: OpenGL context without a monitor I want to create an opengl context but that context must be created without a monitor attach to the system. The reason I want this is because this program should ran in a linux ubuntu server. Inside a docker image to be specific. I'm using many opengl libraries including modern opengl(GLSL), GLFW, glad and glm. I've found this question but I'm not sure whether or not one of the methods will work and it might be a bit outdated. I've also seen someone using something like this on an obsolete site but I'm not sure how to implement it:
glXMakeContextCurrent(display,None,None,context);

I think it still needs a window as display, if not what is the type of display and context variable and where can i download glX?
Edit: I'm only using GLFW for window/context creation on my local machine so I can exclude it.

A: You can use an X Virtual Framebuffer that allows to emulate presence of a physical display in Linux.
It can be installed via
apt-get install xvfb

And used as
xvfb-run -a "your command"


text:
Q: OrientDB query too slow OrientDB v2.1.1,
I have tow class: NOrder and NPassenger, relationship 1 : n, so NOrder has a filed named "passengers",whose type is linklist.
I have two fields (NOrder order_id, NPassenger. Name) index is established
NOrder ducuments count is 3 millon .
I explain these query:
 1)select from NOrder where passengers contains(name = 'xxx')
  why this query not involved index .

 2)select from NOrder where 'xxx' in passengers.name
  this query involved indexeses

this query cost 120sec .
thanks

A: I have tried with this structure
create class NPassenger
create property NPassenger.name String
create index NPassenger.name on NPassenger (name) NOTUNIQUE_HASH_INDEX

create class NOrder
create property NOrder.order_id String
create property NOrder.passengers linklist NPassenger
create index NOrder.order_id on NOrder (order_id) UNIQUE_HASH_INDEX

insert into NPassenger(name) values ("xxx")  // 12:0
insert into NPassenger(name) values ("Alessandro")  //12:1

insert into NOrder(order_id,passengers) values ("order 1",[12:0])
insert into NOrder(order_id,passengers) values ("order 2",[12:1])

Query 1
explain select from NOrder where passengers contains(name = 'xxx')

Query 2
explain select from NOrder where 'xxx' in passengers.name

None of the two queries use the index because the class target is NOrder.
UPDATE
Now I have 50002 NOrder and 50002 NPassenger.
If I execute the queries
explain select from NOrder where passengers contains(name = 'xxx')
and
explain select from NOrder where 'xxx' IN passengers.name'

I get

this is because no index on the name field is used (because the target class is the Norder class) and then the search is done on all 50002 records of the class Norder.
If I use the query
explain select from NPassenger where name = "xxx"

the index NPassenger.name is used because the target class is NPassenger


text:
Q: Shrink a banach space to a closed linear span of an into isometry Theorem $2.2$ states that

Let $X$ and $Y$ be separable Banach spaces and suppose that $f:X \rightarrow Y$ is an into isometry, then $X$ is linearly isometric to a subspace of $Y$.

In the proof, the author mentioned that

We may assume that $Y$ is equal to the closed linear span of $f(X)$.

Question: Why can we assume that?

A: If $X$ is isometric to a subspace of $\overline{f(X)}$, then of course it is isometric to a subspace of $Y$.  So, we might as well assume $\overline{f(X)}=Y$.

A: Let $Z$ be the closed linear span of $f(X)$. Then, (due to the closure!) $Z$ is again a Banach space and $X$ is linearly isomorphic to a subspace of $Z$ iff it is linearly isomorphic to a subspacef of $Y$.


text:
Q: Lock Portrait Orientation in IOS on Application Boot from Landscape So i've run into a fun little bug. I have a UINavigationController with several subviews that it will display that we only want to be viewable in Portrait View. To achieve this we subclassed the UINavigationController and added the following:
override func shouldAutorotate() -> Bool {
    return false
}

override func supportedInterfaceOrientations() -> Int {
    return Int(UIInterfaceOrientationMask.Portrait.rawValue)
}

This works great, and the app is locked into Portrait and cannot rotate EXCEPT if the user turns the device sideways and then loads the app from landscape. The expected outcome was for the device to load in portrait, however it loads in landscape, and won't let the user rotate back to portrait ever.
The only way I've been able to replicate this is by loading the app from a device already in landscape mode. Any ideas? There are lots of posts about device orientation, but none I could find talking about on app boot.

A: Remove autorotate and it should work fine.


text:
Q: Converting log time stamp Date Time offset/dst to epoch time I am trying to convert date/time stamps that look like this:
20160131|235501[-0700/0]
20160621|225549[-0600/1]
to epoch time.  These come from a remote machine that is in a different time zones so I need a method that works only with the time stamps and not the local machine time.
I've found a similar questions, but I was not able to find a clear answer to how to properly handle offsets as a general case since the time stamps come from a different time zone than the local machine.  The python doc's don't provide enough context for me to understand how to work with time offsets.
Since this code needs to run on a small ARM system, I am limited to python 2.7.9
Any assistance would be much appreciated.

A: There's surely a more pythonic way to do this but if you can install dateutil maybe something like this works:
# epoch_date.py
import datetime
from dateutil.parser import parse
import re

raw_dts = '20160131|235501[-0700/0] 20160621|225549[-0600/1]'
dts = raw_dts.split(' ')
print '{:27s} {:5}'.format('date/time stamp', 'epoch')
for dt in dts:
    dt_fmt = re.compile(r'[^\d-]+')
    time_str = dt_fmt.sub('', dt)
    time_date = ''.join(time_str[:-1])
    date_obj = parse(time_date)
    tz = date_obj.tzinfo
    epoch_fmt = (date_obj - datetime.datetime(1970,1,1,tzinfo=tz)).total_seconds()
    print '{:28s}{:7.1f}'.format(dt, epoch_fmt)

will print
$ python epoch_date.py
date/time stamp             epoch
20160131|235501[-0700/0]    1454284501.0
20160621|225549[-0600/1]    1466549749.0

Ingore most that is just formatting over a list of dates into output, but the idea is using re to organize the text into a datetime object that can be parsed by datetime
Hope that helps!


text:
Q: Like instagram photo with selenium python I'm trying to code my own bot python selenium bot for instagram to experiment a little. I succeeded to log in and to search an hashtag in the search bar which lead me to the following web page:

But I can not figure out how to like the photos in the feed, i tried to use a search with xpath and the following path:
     "//[@id="reactroot"]/section/main/article/div1/div/div/div1/div1/a/div"
But it didn't work, does anybody have an idea?

A: First of all, in your case it is recommended to use the official Instagram Api for Python (documentation here on github).
It would make your bot much simpler, more readable and most of all lighter and faster. So this is my first advice.
If you really need using Selenium I also recommend downloading Selenium IDE add-on for Chrome here since it can save you much time, believe me. You can find a nice tutorial on Youtube.
Now let's talk about possible solutions and them implementations. After some research I found that the xpath of the heart icon below left the post behaves like that:
The xpath of the icon of the first post is:
xpath=//button/span

The xpath of the icon of the second post is:
xpath=//article[2]/div[2]/section/span/button/span

The xpath of the icon of the third post is:
xpath=//article[3]/div[2]/section/span/button/span

And so on. The first number near "article" corresponds to the number of the post.

So you can manage to get the number of the post you desire and then click it:
def get_heart_icon_xpath(post_num):
    """
    Return heart icon xpath corresponding to n-post.
    """
    if post_num == 1:
      return 'xpath=//button/span'
    else:
      return f'xpath=//article[{post_num}]/div[2]/section/span/button/span'

try:
    # Get xpath of heart icon of the 19th post.
    my_xpath = get_heart_icon_xpath(19)
    heart_icon = driver.find_element_by_xpath(my_xpath)
    heart_icon.click()
    print("Task executed successfully")
except Exception:
    print("An error occurred")

Hope it helps. Let me know if find other issues.

A: i'm trying to do the same)
Here is a working method. Firstly, we find a class of posts(v1Nh3), then we catch link attribute(href).
posts = bot.find_elements_by_class_name('v1Nh3')
links = [elem.find_element_by_css_selector('a').get_attribute('href') for elem in posts]

A: I implemented a function that likes all the picture from an Instagram page. It could be used on the "Explore" page or simply on an user's profil page.
Here's how I did it.
First, to navigate to a profil page from Instagram's main page, I create a xPath for the "SearchBox" and a xPath to the element in the dropdown menu results corresponding to the index.
def search(self, keyword, index):
    """ Method that searches for a username and navigates to nth profile in the results where n corresponds to the index"""
    search_input = "//input[@placeholder=\"Search\"]"
    navigate_to = "(//div[@class=\"fuqBx\"]//descendant::a)[" + str(index) + "]"
    try:
        self.driver.find_element_by_xpath(search_input).send_keys(keyword)
        self.driver.find_element_by_xpath(navigate_to).click()
        print("Successfully searched for: " + keyword)
    except NoSuchElementException:
        print("Search failed")

Then I open the first picture:
def open_first_picture(self):
    """ Method that opens the first picture on an Instagram profile page """
    try:
        self.driver.find_element_by_xpath("(//div[@class=\"eLAPa\"]//parent::a)[1]").click()
    except NoSuchElementException:
        print("Profile has no picture")

Like each one of them:
def like_all_pictures(self):
    """ Method that likes every picture on an Instagram page."""
    # Open the first picture
    self.open_first_picture()
    # Create has_picture variable to keep track
    has_picture = True

    while has_picture:
        self.like()
        # Updating value of has_picture
        has_picture = self.has_next_picture()

    # Closing the picture pop up after having liked the last picture
    try:
        self.driver.find_element_by_xpath("//button[@class=\"ckWGn\"]").click()
        print("Liked all pictures of " + self.driver.current_url)
    except:
        # If driver fails to find the close button, it will navigate back to the main page
        print("Couldn't close the picture, navigating back to Instagram's main page.")
        self.driver.get("https://www.instagram.com/")

def like(self):
    """Method that finds all the like buttons and clicks on each one of them, if they are not already clicked (liked)."""
    unliked = self.driver.find_elements_by_xpath("//span[@class=\"glyphsSpriteHeart__outline__24__grey_9 u-__7\" and @aria-label=\"Like\"]//parent::button")
    liked = self.driver.find_elements_by_xpath("//span[@class=\"glyphsSpriteHeart__filled__24__red_5 u-__7\" and @aria-label=\"Unlike\"]")
    # If there are like buttons
    if liked:
        print("Picture has already been liked")
    elif unliked:
        try:
            for button in unliked:
                button.click()
        except StaleElementReferenceException: # We face this stale element reference exception when the element we are interacting is destroyed and then recreated again. When this happens the reference of the element in the DOM becomes stale. Hence we are not able to get the reference to the element.
            print("Failed to like picture: Element is no longer attached to the DOM")

This method checks if picture has a "Next" button to the next picture:
def has_next_picture(self):
    """ Helper method that finds if pictures has button \"Next\" to navigate to the next picture. If it does, it will navigate to the next picture."""
    next_button = "//a[text()=\"Next\"]"
    try:
        self.driver.find_element_by_xpath(next_button).click()
        return True
    except NoSuchElementException:
        print("User has no more pictures")
        return False

If you'd like to learn more feel free to have a look at my Github repo: https://github.com/mlej8/InstagramBot


text:
Q: Center Drawable and Text in EditText I want to make drawable and text center in my EditText. The text is centered but the drawable is not. I want something like this:
http://i.imgur.com/cacxR2C.jpg?1
Please help. This is what I have done so far
 <EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Username"
    android:layout_marginLeft="15dp"
    android:layout_marginRight="15dp"
    android:gravity="center_horizontal"
    android:drawableLeft="@drawable/lol2"
    />

When the user types in something in the EditText, the drawable should move itself to the left if the text is lenghty.

A: This worked for me:
<EditText
    android:id="@+id/searchET"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingStart="75dp"
    android:paddingEnd="75dp"
    android:inputType="text"
    android:singleLine="true"
    android:gravity="center"
    android:hint=" Username"
    android:drawableStart="@drawable/your_icon"
    android:background="@android:drawable/editbox_background"/>

The kicker here is that you wrap_content for the width, align the text however, center the view however you'd like, then add padding to each end of the edit text.
This shoves the drawable to the start of your text but still lets you expand your edit text background.

A: instead of

android:drawableLeft="@drawable/lol2"

try using

android:drawableStart="@drawable/lol2"

A: You can do something like this
<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:background="@android:drawable/editbox_background"
        >

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:hint="Username"
            android:background="@null"
            android:gravity="center"
            android:drawableLeft="@drawable/ic_launcher"
            />
    </RelativeLayout>

A: Basically gravity attribute is used to apply changes of aligning the contents of lay out so you can put the gravity to center to align contents in center and center_vertical to to align contents on left side and gravity to center_horizontal to put contents in horizontal center. i.e
android:gravity="center"


text:
Q: Async task only run when previous is completed For a unity project. Procedural terrain generation system that runs in generations. The output of each generation becomes the input of the next, so they must be run sequentially.
They are also slow enough that they need to run on another thread.
The below code works by generating a "sector" and storing it in a dictionary with its "generation" number as the key. It also stores a small initialization object with just the data required to initialize a given generation, so that I can destroy sectors to save memory and re instantiate them backwards down the chain.
Increment() finds the highest key, and generates a new sector with the previous one as its input.
Task.Run() does work to generate sectors without blocking the rest of the game. The problem is that it's possible to request a new sector before the previous one finished generating, etc.
What's the best pattern to prevent generation 3 being generated before generation 2 is finished?
public class WorldGeneratorAsync : MonoBehaviour
{
    public Dictionary<int, SectorController> SectorContollerDict = new Dictionary<int, SectorController>();
    public Dictionary<int, TerrainGraphInput> GraphInputDict = new Dictionary<int, TerrainGraphInput>();
    public int globalSeed;
    public TerrainGraph terrainGraph;

    async void Initialise()
    {
        DestroyAllSectors();
        await InstantiateSectorAsync(0);
    }

    async void Increment()
    {
        var highestGeneration = SectorContollerDict.Keys.Max();
        await InstantiateSectorAsync(highestGeneration+1);
    }

    async Task InstantiateSectorAsync(int generation)
    {
        if (generation == 0) // if we are first generation, init with dummy data
        {
            var inputData = new TerrainGraphInput(globalSeed, generation); // dummy data
            var outputData = await Task.Run(() =>terrainGraph.GetGraphOutput(inputData)); // slow function

            lock (SectorContollerDict)
            {
                SectorContollerDict[generation] = SectorController.New(outputData);
            }
            lock (GraphInputDict)
            {
                GraphInputDict[generation] = inputData;
            }
        }

        else // we take the init data from the previous generation
        {
            int adder = generation > 0 ? -1 : 1;
            TerrainGraphInput inputData;

            if (GraphInputDict.Keys.Contains(generation))
            {
                inputData = GraphInputDict[generation];
            }

            else if (SectorContollerDict.Keys.Contains(generation + adder))
            {
                var previousSectorController = SectorContollerDict[generation + adder];
                inputData = new TerrainGraphInput(
                    previousSectorController.sectorData,
                    previousSectorController.sectorData.EndSeeds,
                    generation,
                    globalSeed
                );
            }

            else
            {
                throw new NoValidInputException();
            }

            var outputData = await Task.Run(()=>terrainGraph.GetGraphOutput(inputData)); // slow function

            lock (SectorContollerDict)
            {
                SectorContollerDict[generation] = SectorController.New(outputData);
            }

            lock (GraphInputDict)
            {
                GraphInputDict[generation] = inputData;
            }
        }
    }

    private void DestroyAllSectors()
    {
        SectorContollerDict = new Dictionary<int, SectorController>();
        GraphInputDict = new Dictionary<int, TerrainGraphInput>();
        foreach (var sc in GameObject.FindObjectsOfType<SectorController>())
        {
            sc.DestroyMe();
        }
    }
}

A: Thanks to Orace - their idea worked. Simpler that I expected - just switch the dictionary of sectorControllers to tasks, and await the previous generation in the instantiation function.
public class WorldGeneratorAsync : MonoBehaviour
{
    public Dictionary<int, Task<SectorController>> TaskDict = new();
    // public Dictionary<int, SectorController> SectorContollerDict = new();
    public Dictionary<int, TerrainGraphInput> GraphInputDict = new();
    public int globalSeed;
    public TerrainGraph terrainGraph;

    async void Initialise()
    {
        DestroyAllSectors();
        TaskDict[0] = InstantiateSectorAsync(0);
    }

    async void Increment()
    {
        var highestGeneration = TaskDict.Keys.Max();
        int newGeneration = highestGeneration + 1;
        TaskDict[newGeneration] = InstantiateSectorAsync(newGeneration);
    }

    async Task<SectorController> InstantiateSectorAsync(int generation)
    {
        SectorController sc;

        if (generation == 0) // if we are first generation, init with dummy data
        {
            var inputData = new TerrainGraphInput(globalSeed, generation); // dummy data
            var outputData = await Task.Run(() =>terrainGraph.GetGraphOutput(inputData)); // slow function
            sc = SectorController.New(outputData);
            GraphInputDict[generation] = inputData;
        }
        else
        {
            int adder = generation > 0 ? -1 : 1;
            TerrainGraphInput inputData;

            if (GraphInputDict.Keys.Contains(generation))
            {
                inputData = GraphInputDict[generation];
            }

            else if (TaskDict.Keys.Contains(generation + adder))
            {
                // var previousSectorController = SectorContollerDict[generation + adder];
                var previousSectorController = await TaskDict[generation + adder]; // await previous generation
                inputData = new TerrainGraphInput(
                    previousSectorController.sectorData,
                    previousSectorController.sectorData.EndSeeds,
                    generation,
                    globalSeed
                );
            }

            else
            {
                throw new NoValidInputException();
            }

            var outputData = await Task.Run(()=>terrainGraph.GetGraphOutput(inputData)); // slow function
            sc = SectorController.New(outputData);
            GraphInputDict[generation] = inputData;
        }

        return sc;
    }

    private void DestroyAllSectors()
    {
        GraphInputDict = new Dictionary<int, TerrainGraphInput>();
        TaskDict = new();
        foreach (var sc in GameObject.FindObjectsOfType<SectorController>())
        {
            sc.DestroyMe();
        }
    }
}


text:
Q: How to delete from my query where row_num > 2 in MySql? I have this table in my database with the following schema:
nearbystops(nearbystopname, latitude, longitude, mainaddress), I have done the following query
SELECT
    nearbystopname,
    latitude,
    longitude,
    mainaddress,
    ROW_NUMBER() OVER (
        PARTITION BY
            nearbystopname,
            mainaddress
        ORDER BY
            nearbystopname,
            mainaddress
    ) row_num
    FROM
    DUSAgeocodeDB.nearbystops

which gives me the following:

My question is, how would I go by deleting the results where row_num > 2 and reflecting the changes into my database?
I have tried the following code:
with cte as (
SELECT
    nearbystopname,
    latitude,
    longitude,
    mainaddress,
    ROW_NUMBER() OVER (
        PARTITION BY
            nearbystopname,
            mainaddress
        ORDER BY
            nearbystopname,
            mainaddress
    ) row_num
    FROM
    DUSAgeocodeDB.nearbystops
    ) delete from cte where row_num > 1;

but it gives me the following error:

Error Code: 1146. Table 'dusageocodedb.cte' doesn't exist

Any help will be much appreciated!

A: Assuming you have a primary key on the table, then:
delete ns
    from DUSAgeocodeDB.nearbystops ns join
         (select nearbystopname, mainaddress, min(id) as min_id
          from DUSAgeocodeDB.nearbystops ns2
          group by nearbystopname, mainaddress
         ) ns2
         on ns2.nearbystopname = ns.nearbystopname and
            ns2.mainaddress = ns.mainaddress and
            ns.id > ns.id;

If you don't have a primary key, your best bet might be to repopulate the table:
create table temp_ns as
    select nearbystopname, latitude, longitude, mainaddress,
           row_number() over (partition by nearbystopname, mainaddress) as seqnum
    from DUSAgeocodeDB.nearbystops ns;

truncate table DUSAgeocodeDB.nearbystops ns;  -- SAVE first!!!

insert into DUSAgeocodeDB.nearbystops (nearbystopname, latitude, longitude, mainaddress)
    select nearbystopname, latitude, longitude, mainaddress
    from temp_ns
    where seqnum = 1;


text:
Q: Find the fraction of games that the soccer team wins. The question I am trying to answer is: A soccer team wins 60% of its games when playing at home, and 10% of its games when playing abroad. If the team plays home 30% of the time, what fraction of the games does it win?
To solve this, I tried to compute P(W|H), P(W|A), P(H), and P(A). It says in the problem that P(H)=.3, which implies that P(A)=1-P(H)-0.7.
For P(W|H), I used the formula P(W|H)=P(W∩H)/P(H)=0.6/0.3=2.
For P(W|A), I used the formula P(W|A)=P(W∩A)/P(A)=0.1/0.7=(1/7).
My intuition tells me that I should add 2 and (1/7), but then how do I get my answer to be of the form (games won)/(total games played)?

A: Let $W$ denote the event that the team wins.
Let $H$ and $A$ denote the events that the team plays the match at Home and Away respetively.
Then $P(H)=\frac{3}{10},P(A)=\frac{7}{10},P(W|H)=\frac{6}{10},P(W|A)=\frac{1}{10}$
Thus, $P(W)=P(W|H)P(H)+P(W|A)P(A)=(\frac{6}{10} \times\frac{3}{10}) +(\frac{1}{10} \times \frac{7}{10})=\frac{25}{100}=\frac{1}{4}$


text:
Q: Middleware for routes in vue I want to deny some routes for authorized users, like login page, register page, but I don't know how to make those middlewares
Routes
routes: [
{
  path: '/login',
  name: 'Login',
  component: Login
},
{
  path: '/register',
  name: 'Register',
  component: Register
}
]

Function that I use in components
computed: {
  isLoggedIn () {
    return this.$store.getters.isLoggedIn
  }
}

A: In your router you can do something like this.
All routes marked with meta: { requiresLogin: true} } will be checked in the BeforeEach method. Here we redirect them to the login page.
You can in principle halt the router and show a modal or whatever you like here.
Router
import Vue from 'vue'
import VueRouter from 'vue-router'

import App from '../views/App.vue'
import Login from '../views/login.vue'
import Register from '../views/registser.vue'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/', name: 'app', component: App, meta: { requiresLogin: true} },
    { path: '/login', name: 'login', component: Login },
    { path: '/register', name: 'register', component: Register },
  ]
})

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresLogin)) {
    if (**USER IS NOT LOGGED IN**) {
      next({
        path: '/login',
        query: {
          redirect: to.fullPath,
        },
      });
    } else {
      next();
    }
  } else {
    next();
  }
})

export default router

A: Create additional meta field requiresAuth in your routes to specify which route require logged user:
routes: [{
      path: '/',
      name: 'Dashboard',
      component: Dashboard,
      children: [{
        path: 'settings',
        name: 'Settings',
        component: Settings,
        meta: {
          requiresAuth: true
        }
      }],
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/login',
      name: 'Login',
      component: Login
    }
  ],

Then add middleware in main.js:
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth) {
    const authUser = JSON.parse(window.localStorage.getItem('authUser')) // your oauth key
    if (authUser && authUser.access_token) {
      next()
    } else {
      next({
        name: 'Login'
      })
    }
  }
  next()
})

new Vue({
  el: '#app',
  router,
  store,
  template: '<App/>',
  components: {
    App
  }
})


text:
Q: Restart app on PACKAGE_REPLACED not working I want my app to restart automatically after update.
Following is my manifest and broadcast receiver code:
...
    <receiver
        android:name="app.com.blynq.services.BootReceiver"
        android:theme="@android:style/Theme.Holo.Light.NoActionBar.Fullscreen"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
        <intent-filter>
            <action android:name="android.intent.action.SCREEN_ON" />
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>

        <intent-filter>
            <action android:name="android.intent.action.PACKAGE_REPLACED" />
            <data android:scheme="package" android:path="app.com.blynq.player" />
        </intent-filter>
    </receiver>
...

Service:
public class BootReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    String intentActionString = intent.getAction();
    if ("android.intent.action.BOOT_COMPLETED".equals(intentActionString) || "android.intent.action.PACKAGE_REPLACED".equals(intentActionString)) {
        Intent pushIntent = new Intent(context, RegisterActivity.class);
        pushIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(pushIntent);
    }
}

What am I missing here ?


text:
Q: Javascript to get the last paragraph text in HTML block This is fairly simple I'm sure but I'm having some trouble with it. I'm trying to use Sharepoint 2013 Client Side Rendering (CSR) to format a sharepoint field containing a long block of text to only show the last paragraph block (the idea is to have a "last update status" for tasks that reports whatever the last line of entry was).
So, given this block of html as an example:

    <meta name="generator"
    content="HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy-html5/tree/c63cc39" />
    <title></title>

        Current Status
        : Pending

Some update

Some Update 2

THIS IS THE TEXT I WANT TO GET

How can I use either regex or a javascript html parser to set a variable to contain "THIS IS THE TEXT I WANT TO GET"?
Thanks in advance! :)

A: By "the last paragraph block" do you mean the last "p" element? if so why not:

In jQuery:

A: You could forgo using JS altogether and do this using CSS. Stick this into your .

A: Here's some funky regex magic
document
// Get the parent node
.querySelector('.ExternalClass473CC6A801594594826FDFA0BFAD6B1E')
// Get the contents as text
.textContent
// Look for any character, then match all the way until there's a linebreak or its the end of the string.
.match(/\w.+(\n|$)/g)
// Get the last matching item
.slice(-1)

A: var textYouWantToGet = document.querySelector('p:last-child').innerText

A: It would be handy if the
 tag you wanted to assign to a variable had something like an id so JavaScript can identify it.
If you did that you could simply do : var text = document.querySelector("#id").value
Alternatively if this is not an option, you would have to seek it out among the
 tags yourself.
something like : var pTags = document.getElementByTagName("p");
               var theTextIwant = "";
               for(var i = 0; i < Ptags.length; i++){if(pTags[i] == "text i want;
                   theTextIwant = pTags[i];
                )}

A: OK so I spent the last day on this, but it looks like the simplest and most foolproof thing to do was this:
var bodyElements = doc.querySelectorAll("p");

//Find the last non-empty element
//TODO: Go back and try another element if all elements of the specified type are empty
var i = bodyElements.length;
var newBodyValue = "";
while (!(/\S/).test(newBodyValue) || i < 0) {
    i--;
    try {
        newBodyValue = bodyElements[i].innerText;
        if (!newBodyValue) {continue;}
    } catch (err) {
        continue;
    }
}

last-child selector didn't work because I need the last non-empty element period, not just the last per hierarchy. I later learned I could have easily used JQuery for this but I was trying to keep it pure to keep Sharepoint overhead minimal.
I had to add a bunch of extra stuff but here's the final CSR JSLink result. It takes a standard Sharepoint task list and modifies the description field so that it only shows whatever the last line entered was. This is useful for a particular summary view where I want the information as compact as possible.
https://gist.github.com/JustinGrote/4fd3b5e7bf0420c283a9
Thanks to all for your suggestions.
I know I probably didn't follow best practices on a lot of stuff, but I have only been using Javascript for about 10 hours total, so sue me :)


text:
Q: Having troubles rendering rectangle on button press I am trying to add a Rectangle in the panel by button press and remove it with another one. It should work but it doesn't render anything, and I absolutely don't know why.
Can someone explain what I am doing wrong and give me some nice tips what I can improve with my code?
public class GUI extends JPanel {

    public static boolean isRecVisible = false;

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

    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        super.paintComponent(g);
        g2d.drawRect(10, 10, 200, 200);
    }

    public static void createGui() {

        int frameWidth = 550;
        int frameHeight = 400;

        int buttonWidth1 = 250;
        int buttonHeight1 = 30;

        int buttonWidth2 = 500;
        int buttonHeight2 = 30;

        int displayWidth = frameWidth - 20;
        int displayHeight = frameHeight - 105;

        GUI drawRec = new GUI();

        JFrame f = new JFrame("Rectangle");
        JPanel p = new JPanel();
        JPanel display = new JPanel();
        JButton addRec = new JButton("Add Rectangle");
        JButton removeRec = new JButton("Remove Rectangle");
        JButton colorRec = new JButton("Color Rectangle");

        f.add(p);
        p.add(addRec);
        p.add(removeRec);
        p.add(colorRec);
        p.add(display);

        display.setBackground(Color.LIGHT_GRAY);

        f.setSize(frameWidth, frameHeight);
        f.setLocationRelativeTo(null);
        f.setResizable(false);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);

        display.setBounds(frameWidth / 2 - displayWidth / 2, 10, displayWidth, displayHeight);
        addRec.setBounds(frameWidth / 2 - buttonWidth1 / 2 - 250 / 2, frameHeight - 85, buttonWidth1, buttonHeight1);
        removeRec.setBounds(frameWidth / 2 - buttonWidth1 / 2 + 250 / 2, frameHeight - 85, buttonWidth1, buttonHeight1);
        colorRec.setBounds(frameWidth / 2 - buttonWidth2 / 2, frameHeight - 60, buttonWidth2, buttonHeight2);

        addRec.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (isRecVisible == false) {
                    isRecVisible = true;
                    display.add(drawRec);
                    display.repaint();
                    System.out.println("Rectangle has been drawn!");

                } else {
                    System.out.println("Rectangle has already been drawn!");
                    return;
                }
            }
        });

        removeRec.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (isRecVisible == true) {
                    isRecVisible = false;
                    System.out.println("Rectangle has been removed!");

                } else {
                    System.out.println("Rectangle has already been removed");
                    return;
                }
            }
        });
    }
}

A: display.add(drawRec);
display.repaint();

When you add (or remove) components to a visible frame then the basic logic is:
display.add(...);
display.revalidate();
display.repaint(); // sometimes needed

The revalidate() is the key method because it invokes the layout manager so the size/location of the component can be set.
However, that still won't fix the problem because your custom panel doesn't have a preferred size, so there is nothing to paint for your component.
You need to override the getPreferredSize() method of your custom panel to return the preferred size of your custom component. So in your case you might set the preferred size to be (220, 220) so the rectangle is centered in the panel.
Read the section from the Swing tutorial on Custom Painting for more information and complete working examples.
Note: the tutorial example will also show you how to better structure your code to make sure the GUI is created on the Event Dispatch Thread.

A: Rather than adding or removing components, it would make more sense here to add the custom painted panel on construction, and use the isRecVisible boolean as a flag to test for drawing the rectangle.
Something like shown here:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class GUI extends JPanel {

    public static boolean isRecVisible = false;

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

    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        super.paintComponent(g);
        if (isRecVisible) {
            g2d.drawRect(10, 10, 200, 200);
        }
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(600,400);
    }

    public static void createGui() {
        int frameWidth = 550;
        int frameHeight = 400;

        GUI drawRec = new GUI();
        drawRec.setBackground(Color.LIGHT_GRAY);

        JFrame f = new JFrame("Rectangle");
        JPanel p = new JPanel();
        JButton addRec = new JButton("Add Rectangle");
        JButton removeRec = new JButton("Remove Rectangle");
        JButton colorRec = new JButton("Color Rectangle");

        f.add(p, BorderLayout.PAGE_START);
        p.add(addRec);
        p.add(removeRec);
        p.add(colorRec);
        f.add(drawRec);

        f.setSize(frameWidth, frameHeight);
        f.setLocationRelativeTo(null);
        f.setResizable(false);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);

        addRec.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                isRecVisible = true;
                drawRec.repaint();
            }
        });

        removeRec.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                isRecVisible = false;
                drawRec.repaint();
            }
        });
    }
}


text:
Q: Automatic focus on next edittext for digit password entry From my app, I expect more like that implemented on IPhone with four digits for password entry, which means with masked dot. I'm already done with the correct entry. Using the concrete implementation for TextWatcher in addTextChangedListener, however, when I entered 4 wrong digits and the focus was returned back to the first one and every digit was cleared as well. In this case, the original soft keyboard for digit input switched back to the qwert one and any letter or digit entered became visible without masking with dot.
myEditText1.addTextChangedListener(new MyTextWatcher(mPasswordEditText){
       @Override
        public void afterTextChanged(Editable arg0) {
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            s = mPasswordEditText.getText();
            int cacheH = UnlockScreen.this.mPasswordEditText.getHeight();
            if(s.length() == 1){
                UnlockScreen.this.mPasswordEditText1.requestFocus();
                    mPasswordEditText.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    mPasswordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    mPasswordEditText.setMinHeight(cacheH);
            }
        }
});

But it didn't work well as expected.
XML layout is:
           <EditText
                    android:id="@+id/unlock_screen_password_edittext_1"
                    style="@style/passcodeStyle"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight=".20"
                    android:layout_marginRight="10dip"
                    android:digits="@string/digits_only"
                    android:gravity="center"
                    android:inputType="number"
                    android:password="true"
                    android:maxLength="1"/>

Any idea, folks?

A: I'm using setText(s.toString().replace(s.toString(), '.')); instead of mPasswordEditText.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);and                    mPasswordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
And set flags for textChange status in each edittext.
I'm not sure it's the best solution but for my app, this works fine and so far I've had no idea of a better way.


text:
Q: Suspend, hangs after GPU is used Problem
On normal occasions when xorg and compiz is running in my gpu, I
can Suspend peacefully. However if I run some intense (90% GPU
in use) training (via jupyter) related to pytorch, and subsequently
suspend after the processes are over, it refuses to sleep/wakeup.
I am positive GPU being full or not empty is causing the issue. I
don't know why "some process" possibly related to the GPU is not
Suspending. When I run jupyter and run 1+1 (or a simple process)
and Suspend, then also no issues.
Question
Kernlog shows me nothing "fishy". I have tried a bunch of online
remedies. Now at a dead end.
How do I identify what is happening? any ideas?
Other symptoms
It sort-of sleeps but I still hear some sound from the laptop when I
hit a key (it sounds as if it is booting up). And then blank screen
after that. Sometimes I get to go to the TTY but can't type anything.

My system

*

*Ubuntu 16.04

*Nvidia 1050 GeForce

*Acer nitro 5 8gb ram

What all I tried to rectify this issue?
Spent a good 5 full days understanding and searching and re-installing
etc... Now at a dead end.

*Checked the kern logs (pastebin link) but didn't see anything
"fishy". (at 02:08 I start sleeping and at 10:21 I hit hard
reset).
Here is a tiny exerpt:
Oct  2 02:08:06 eghx-nitro NetworkManager[8152]: <info>  [1601597286.6443] manager: sleep requested (sleeping: no  enabled: yes)
Oct  2 02:08:06 eghx-nitro NetworkManager[8152]: <info>  [1601597286.6443] manager: sleeping...
Oct  2 02:08:06 eghx-nitro NetworkManager[8152]: <info>  [1601597286.6447] manager: NetworkManager state is now ASLEEP
Oct  2 02:08:06 eghx-nitro NetworkManager[8152]: <info>  [1601597286.6453] device (wlp2s0): state change: activated -> deactivating (reason 'sleeping') [100 110 37]
Oct  2 02:08:06 eghx-nitro NetworkManager[8152]: <info>  [1601597286.8169] device (wlp2s0): state change: deactivating -> disconnected (reason 'sleeping') [110 30 37]
Oct  2 02:08:06 eghx-nitro NetworkManager[8152]: <info>  [1601597286.8356] dhcp4 (wlp2s0): canceled DHCP transaction, DHCP client pid 8328
Oct  2 02:08:06 eghx-nitro NetworkManager[8152]: <info>  [1601597286.8356] dhcp4 (wlp2s0): state changed bound -> done
Oct  2 02:08:06 eghx-nitro NetworkManager[8152]: <info>  [1601597286.8363] dns-mgr: Writing DNS information to /sbin/resolvconf
Oct  2 02:08:06 eghx-nitro kernel: [24100.153393] wlp2s0: deauthenticating from e8:cc:18:41:3c:15 by local choice (Reason: 3=DEAUTH_LEAVING)
Oct  2 02:08:07 eghx-nitro NetworkManager[8152]: <warn>  [1601597287.0509] sup-iface[0xb4a6f0,wlp2s0]: connection disconnected (reason -3)
Oct  2 02:08:07 eghx-nitro NetworkManager[8152]: <info>  [1601597287.0511] device (wlp2s0): supplicant interface state: completed -> disconnected
Oct  2 02:08:07 eghx-nitro NetworkManager[8152]: <info>  [1601597287.0525] device (wlp2s0): state change: disconnected -> unmanaged (reason 'sleeping') [30 10 37]
Oct  2 02:08:08 eghx-nitro kernel: [24101.983885] PM: suspend entry (deep)
Oct  2 02:08:09 eghx-nitro kernel: [24101.983888] PM: Syncing filesystems ... done.
Oct  2 10:21:32 eghx-nitro kernel: [24103.953554] Freezing user space
processes ... (elapsed 0.002 seconds) done.

*

*Based on Nvidia forum added the following to grub and updated.
 GRUB_CMDLINE_LINUX_DEFAULT="quiet acpi_rev_override=1
 acpi_osi=Linux scsi_mod.use_blk_mq=1 nouveau.modeset=0
 nouveau.runpm=0 mem_sleep_default=deep"

Added the following to iniramfs-tools/modules and updated.
 nvidia
 nvidia_modeset
 nvidia_uvm
 nvidia_drm

*Didn't change kernel as there was no evidence towards it. People
changed to 4.17. Mine is currently 4.15.

*

*4.17 but it didn't work

*Another user

*this guy

*Blind try: Trying different (Suspend)s
 systemctl suspend

 pm-suspend

*Tried downgrading the drivers to 384 from 430 with changing it at
additional drivers. This was not useful as this was not capable
of co-existing with pytorch=1.6.0

*Complete remove and re-install of nvdia-430 as per here:
purge, add-apt-repository ppa:graphics-drivers/ppa, update
and autoinstall.
This ended in the black screen of death. Recovered it with
noveau.modeset=0. Somehow GPU was not working anymore.

*At this point did a complete re-install of xserver,unity,
lightdm and nvidia-430 over tty terminal before login screen.
This recovered the system to it's previous state i.e., suspend
when GPU full hangs the system.


text:
Q: Count number of unique colours in image I am trying to count the number of unique colours in an image. I have some code that I think should work however when I run it on an image its saying a I have 252 different colours out of a possible 16,777,216. That seems wrong given the image is BGR so shouldn't their be much more different colours (thousands not hundreds?)?
def count_colours(src):
    unique, counts = np.unique(src, return_counts=True)
    print(counts.size)
    return counts.size

src = cv2.imread('../../images/di8.jpg')
src = imutils.resize(src, height=300)
count_colours(src) # outputs 252 different colours!? only?

Is that value correct? And if not how can I fix my function count_colours()?
Source image:

Edit: is this correct?
def count_colours(src):
    unique, counts = np.unique(src.reshape(-1, src.shape[-1]), axis=0, return_counts=True)
    return counts.size

A: If you look at the uniques you are getting back, I'm pretty sure you'll find they are scalars.
You need to use the axis keyword:
>>> import numpy as np
>>> from scipy.misc import face
>>>
>>> img = face()
>>> np.unique(img.reshape(-1, img.shape[-1]), axis=0, return_counts=True)
(array([[  0,   0,   5],
       [  0,   0,   7],
       [  0,   0,   9],
       ...,
       [255, 248, 255],
       [255, 249, 255],
       [255, 252, 255]], dtype=uint8), array([1, 2, 2, ..., 1, 1, 1]))

A: The comment by @ Edeki Okoh is correct. You need to find a way to take the color channels into account. There is probably a much cleaner solution but a hacky way to do this would be something like this. Each color channels has values from 0 to 255 so we add 1 in order to make sure that it gets multiplied. Blue will represent the last the digits, green the middle three ones and red the first three. Now every value is representing a unique color.
b,g,r = cv2.split(src)
shiftet_im = b + 1000 * (g + 1)  + 1000 * 1000 * (r + 1)

The resulting image should have one channel with each value representing a unique color combination.

A: I think you only counted for a single channel e.g R-value out of full RGB channel. that's why you have only 252 discrete values.
In theory R G B each can have 256 discrete states.
256*256*256 =16777216
means in total you can have 16777216 possibilities of colors.
My suggestion is to convert RGB uchar CV_8UC3  into a single 32bit data structure like CV_32FC1
Let
Given image as input
 # my test small sie text image. which I can count the number of the state by hand
import cv2
import numpy as np
image=cv2.imread('/home/usr/naneDownloads/vuQ9y.png' )# change here
b,g,r = cv2.split(image)
out_in_32U_2D =  np.int32(b) << 16 + np.int32(g) << 8 + np.int32(r)  #bit wise shift 8 for each channel.
out_in_32U_1D= out_in_32U_2D.reshape(-1) #convert to 1D
np.unique(out_in_32U_1D)
array([-2147483648, -2080374784, -1073741824, -1006632960,           0,
             14336,       22528,       30720,       58368,       91136,
            123904,      237568,      368640,      499712,      966656,
           1490944,     2015232,     3932160,     6029312,     8126464,
          15990784,    24379392,    32768000,    65011712,    67108864,
          98566144,   132120576,   264241152,   398458880,   532676608,
         536870912,   805306368,  1073741824,  1140850688,  1342177280,
        1610612736,  1879048192], dtype=int32)
len(np.unique(out_in_32U_1D))
37 # correct for my test wirting paper when compare when my manual counting

The code here should be able to provide you with what you needed


text:
Q: Adding a href link to a checkbox once selected So I currently have coded in HTML when a user clicks "Customize" a modal pops up with checkboxes. Once a checkbox is selected and the user clicks "Submit", what the user selected will show up on the page and the modal will vanish. What I'm trying to do is, have the selected content turn into a link (href) once selected. I've got it to where it makes the checkbox content a link in the modal but I don't want it there, I want it to convert into a link once it's been selected and the user clicks submit. The following is the code I currently have in HTML and JS

$('#youtube').change(function() {
  var chb = document.getElementsByClassName('chkbx');

  if (chb[0].checked) {
    console.log("YOUTUBE selected");
    $(this).next().html("YOUTUBE");
  }
});

Please select preferred websites:

    <button data-submit-button class="submit-button" onclick="getValue()">Submit</button>

    <input type="checkbox" class="chkbx" id="youtube" name="website" value="youtube"> YOUTUBE

A: You can only use next if you have something next
Otherwise use .after() or parent().append()

$('#youtube').on("click",function() {
  if (this.checked) {
    console.log("YOUTUBE selected");
    $(this).parent().next().html("YOUTUBE");
  }
});

Please select preferred websites:

    <button type="button" data-submit-button class="submit-button">Submit</button>

    <input type="checkbox" class="chkbx" id="youtube" name="website" value="youtube"> YOUTUBE
    This is the next

You can also use replaceWith if you want the checkbox to become a link
Here when submit is clicked

$('.submit-button').on("click",function() {
  const $check = $("#youtube")
  if ($check.is(":checked")) {
    console.log("YOUTUBE selected");
    $check.parent().replaceWith("YOUTUBE");
  }
});

Please select preferred websites:

    <button type="button" class="submit-button">Submit</button>

    <input type="checkbox" class="chkbx" id="youtube" name="website" value="youtube"> YOUTUBE


text:
Q: Use Magento's getUrl inside a function  public function getWelcome()
{
    if (empty($this->_data['welcome'])) {
        if (Mage::isInstalled() && Mage::getSingleton('customer/session')->isLoggedIn()) {
            $this->_data['welcome'] = $this->__('Welcome, %s!', $this->escapeHtml(Mage::getSingleton('customer/session')->getCustomer()->getName()));
        } else {
            $this->_data['welcome'] = $this->__('Welcome, Sign in or Register');
        }
    }

    return $this->_data['welcome'];
}

I want to know if I can use the function  Mage::getUrl('/whatever') inside this function.
More specifically, I need to use a link inside the
 else {
            $this->_data['welcome'] = $this->__('Welcome, Sign in or Register');
        }

Thanks.
EDIT
The solution:
$this->__('Welcome, Sign in or Register',
             Mage::getUrl('customer/account/login'),
             Mage::getUrl('customer/account/create')

);

A: The __() function works like sprintf(). You can use directives like this:
$this->__('Welcome, Sign in or Register',
    Mage::getUrl('customer/account/login'),
    Mage::getUrl('customer/account/create')
)

The neat part of this is the directives can be used in any order, you could translate the above to:
Please sign-up or, if you have an existing account,
login. To justify this example here is the register URL again;
<q>%2$s</q>.


text:
Q: Testing a regression network in caffe I am trying to count objects in an image using Alexnet.
I have currently images containing 1, 2, 3 or 4 objects per image. For initial checkup, I have 10 images per class. For example in training set I have:
image  label
image1  1
image2  1
image3  1
...
image39 4
image40 4

I used imagenet create script to create a lmdb file for this dataset. Which successfully converted my set of images to lmdb.
Alexnet, as an example is converted to a regression model for learning the number of objects in the image by introducing EucledeanLosslayer instead of Softmax Layer. As suggested by many. The rest of the network is the same.
However, despite doing all the above, when I run the model, I received only zeros as output during testing phase(shown below). It did not learn any thing. However, the training loss decreased continuously in each iteration.
I don't understand what mistakes I have made. Can anybody guide me why the predicted values are always 0? And how can I check the regressed values in testing phase, so that to check how many samples are correct and what's the value for each of my image?
The predicted and the actual label of the test dataset is given as :
I0928 17:52:45.585160 18302 solver.cpp:243] Iteration 1880, loss = 0.60498
I0928 17:52:45.585212 18302 solver.cpp:259]     Train net output #0: loss = 0.60498 (* 1 = 0.60498 loss)
I0928 17:52:45.585225 18302 solver.cpp:592] Iteration 1880, lr = 1e-06
I0928 17:52:48.397922 18302 solver.cpp:347] Iteration 1900, Testing net (#0)
I0928 17:52:48.499543 18302 accuracy_layer.cpp:88] Predicted_Value: 0 Actual Label: 1
I0928 17:52:48.499641 18302 accuracy_layer.cpp:88] Predicted_Value: 0 Actual Label: 2
I0928 17:52:48.499660 18302 accuracy_layer.cpp:88] Predicted_Value: 0 Actual Label: 3
I0928 17:52:48.499681 18302 accuracy_layer.cpp:88] Predicted_Value: 0 Actual Label: 4
...

Note: I also created hdf5 format files in-order to have floating labels, i.e. 1.0, 2.0, 3.0 and 4.0. However, when i changed data layer to HDF5 type, i can not crop the image for data-augmentation as being done in alexnet with lmdb layer, as well as normalization. I used the script given on "https://github.com/nikogamulin/caffe-utils/blob/master/hdf5/demo.m" for hdf5 data and followed his steps for using it in my model.
I have updated last layers as such:
layer {
   name: "fc8reg"
   type: "InnerProduct"
   bottom: "fc7"
   top: "fc8reg"
   param {
    lr_mult: 1
    decay_mult: 1
   }
   param {
     lr_mult: 2
     decay_mult: 0
   }
   inner_product_param {
   num_output: 1
   weight_filler {
       type: "gaussian"
       std: 0.01
   }
   bias_filler {
       type: "constant"
       value: 0
   }
   }
 }
 layer {
   name: "accuracy"
   type: "Accuracy"
   bottom: "fc8reg"
   bottom: "label"
   top: "accuracy"
   include {
     phase: TEST
   }
 }
 layer {
   name: "loss"
   type: "EuclideanLoss"
   bottom: "fc8reg"
   bottom: "label"
   top: "loss"
 }

A: Without judging whether your network diverged or not, the obvious mistake you have made is that you shouldn't use a Accuracy layer to test a regression network. It is only for  testing a classification network trained by a SoftmaxWithLoss Layer.
In fact, given an image for a network, the Accuracy layer in the network will always sort its input array(here it is bottom: "fc8reg") and choose the index of the maximal value in the array as the predicted label by default.
Since num_output == 1 in fc8reg layer, accuracy layer will always predict index 0 for the input image as its predicted label as you have seen.
At last, you can use a EuclideanLoss layer to test your regression network. This similar problem may also give you some hint.

If you are to print and calculate the regressed values after training, and count the accuracy of the regression network, you can simply write a RegressionAccuracy layer like this.
Or, if your target label only has 4 discrete values {1,2,3,4}, you can still train a classification network for your task.

A: In my opinion, everything is correct, but your network is not converging, which is not a rare hapenning. Your network is actually converging to zero outputs!
Maybe most of your samples have 0 as their label.
Also don't forget to include the loss layer only during TRAIN; otherwise, it will learn on test data as wel.


text:
Q: How to go about instantiating templates based on symbols missing in an object file? (This question is a bit obscure without a lot of motivation so please bear with me.)
For the sake of discussion let's assume I have two files, a.cpp and b.hpp. Suppose a.cpp has the declaration
template <typename T> void foo(T& t);

and somewhere in the code it has the commands:
foo<int>(1234);
foo<double>(12.34);

while b.hpp holds the actual (templated) definition and nothing else.
Now, a.cpp, compiled without including b.hpp will compile into an object file, a.o, which is expecting to be linked with other files containing the object code for foo<int> and foo<double>. In itself, b.hpp makes no instantiations of foo(), so it's useless to compile it alone.
However, if I were to determine which instantiations are necessary, and generate a.aux.cpp containing minimal code to instantiate exactly those templates needed for a.cpp, I would not have to manually ensure the instantiations are made.
So, how do I go about achieving this? I was thinking along the lines of doing
nm --undefined-only a.cpp | sed 's/^ *//;' | c++filt | grep foo

to get the signatures. Then I need to force their instantiation without actually causing any other side-effects... perhaps define a variable whose type is a pointer to foo<T> for each value of T I find.
Anyway, this all seems very kludgy and I was wondering whether some build-related tools do this for you. Or whether I should have another approach altogether.

A: I don't think there's anything you could use out of the box. You might try to write your own "needed instantiation extractor" with tools such as LibClang.
Also note that the only legal way to get an instantiation usable in other translation units is to request an explicit instantiation:
template void foo(int& t);


text:
Q: Trying to display JSON by sections in React JS The Problem:
This is how the App is supposed to render the contacts, organized by sections according to their first name letters - A,B,C... So far i couldn't figure a way to diplay them in this way from A to Z. Neither changing the JSON structure or in ReactJS solved it. Every attempt to add more properties in the JSON, faced the limitation of Array.map one time "scaning". Any help is appreciated!

This is the JSON behind it:
[
    {
        "id": 1,
        "fname": "Amanda",
        "lname": "Gonzales",
        "contact": "(31) 9 9580-2530",
    },
    {
        "id": 2,
        "fname": "Astrid",
        "lname": "Guzman",
        "contact": "(31) 9 9790-2530",
    },
    {
        "id": 3,
        "fname": "Aurora",
        "lname": "Muñoz",
        "contact": "(57) 9 9580-2530",
    },

]

And the React JS as well:
class ShowContactsList extends Component {
    render() {
        const mappedJSON = mockData.map((inputMap, index) => (
            <ContactListOneContact
                key={index}
                lname={inputMap.lname}
                fname={inputMap.fname}
                fname={inputMap.fname}
                contact={inputMap.contact}
            />
        ));
        return (

A

                {mappedJSON}

        )
    }
}

A: You could create a group by letter, for your contacts, and then you iterate over the letters and for each letter, iterate over the contacts
    export default class ShowContactsList extends Component {
      render() {
        const groupedByLetter = mockData.reduce((groups, contact) => {
          const letter = contact.fname[0].toUpperCase();
          const group = groups[letter] || [];
          group.push(contact);
          groups[letter] = group;
          return groups;
        }, {});

        return Object.entries(groupedByLetter).map(([letter, contacts]) => {
          return (

{letter}

              {contacts.map((inputMap, index) => (
                <ContactListOneContact
                  key={index}
                  lname={inputMap.lname}
                  fname={inputMap.fname}
                  contact={inputMap.contact}
                />
              ))}

          );
        });
      }
    }

Demo at https://codesandbox.io/s/twilight-cdn-e4tgs?file=/src/App.js