text:
Q: Generate running count of a group based on two columns I would like to get a dataframe of the count of the total amount of items sold by day, but at the "end" of the day.
For example, I have the following data:
Item    Day Facility
Item_A  Day1    B
Item_B  Day1    A
Item_B  Day1    B
Item_C  Day2    B
Item_A  Day2    A
Item_C  Day2    C
Item_B  Day2    A
Item_B  Day2    A
Item_C  Day3    A

I would like a table which shows the total sold items at the end of the day + the previous days. I've included a dummy column because my data has additional columns which I don't need.
For example:
Item    Day Facility    Item_Total_Accumulative
Item_A  Day1    B   1
Item_B  Day1    A   2
Item_B  Day1    B   2
Item_C  Day2    B   2
Item_A  Day2    A   2
Item_C  Day2    C   2
Item_B  Day2    A   4
Item_B  Day2    A   4
Item_C  Day3    A   3

Thanks!!

A: You can use group_by() and mutate() (or count()) in order to calculate per day and per item, and for the calculation, I think the function cumsum() will be appropriated (cumulative sum).
As your variable Facility is not a numeric, I added a variable Value = 1, but using count() is a better way (same result than the commented line).
Then just make a left_join() with the previous result and you have what you are looking for.
library(dplyr)

 df %>%
  count(Item, Day) %>%
  group_by(Item) %>%
  mutate(Item_Total_Accumulative = cumsum(n)) %>%
  select(-n) %>%
  left_join(df,.)

#> Joining, by = c("Item", "Day")
#>     Item  Day Facility Item_Total_Accumulative
#> 1 Item_A Day1        B                       1
#> 2 Item_B Day1        A                       2
#> 3 Item_B Day1        B                       2
#> 4 Item_C Day2        B                       2
#> 5 Item_A Day2        A                       2
#> 6 Item_C Day2        C                       2
#> 7 Item_B Day2        A                       4
#> 8 Item_B Day2        A                       4
#> 9 Item_C Day3        A                       3

A: There should be an easier way but my quick doodle came out like this:
library(dplyr)
library(tidyr)

df %>%
  group_by(Day, Item) %>%
  count() %>%
  group_by(Item) %>%
  mutate(Item_Total_Accumulative=lag(n, default = 0) + n) %>%
  group_by(Day, Item, Item_Total_Accumulative) %>%
  expand(n=1:n) %>%
  select(-n)

#> # A tibble: 9 x 3
#> # Groups:   Day, Item, Item_Total_Accumulative [6]
#>   Day   Item   Item_Total_Accumulative
#>   <fct> <fct>                    <dbl>
#> 1 Day1  Item_A                       1
#> 2 Day1  Item_B                       2
#> 3 Day1  Item_B                       2
#> 4 Day2  Item_A                       2
#> 5 Day2  Item_B                       4
#> 6 Day2  Item_B                       4
#> 7 Day2  Item_C                       2
#> 8 Day2  Item_C                       2
#> 9 Day3  Item_C                       3

Created on 2019-06-05 by the reprex package (v0.3.0)


text:
Q: Three.js - Arranging cubes in a grid I would like to position cubes in a rectangular/square like grid. I'm having trouble trying to create some methodology in depending on what I pick through an HTML form input (checkboxes) to have it arrange left to right and up to down, a series of cubes, in a prearranged grid all on the same plane.
What measurement units is three.js in? Right now, I'm setting up my shapes using the built-in geometries, for instance.
var planeGeometry = new THREE.PlaneGeometry(4, 1, 1, 1);
The 4 and 1; I'm unsure what that measures up to in pixels, although I do see it rendered. I'm resorting to eyeballing it (guess and checking) every time so that it looks acceptable.

A: Without a fair bit of extra math THREE is not measured in pixels.
To make a simple grid (I leave optimizations, colors, etc for future refinements) try something like:
var hCount = from_my_web_form('horiz'),
    vCount = from_my_web_form('vert'),
    size = 1,
    spacing = 1.3;
var grid = new THREE.Object3d(); // just to hold them all together
for (var h=0; h<hCount; h+=1) {
    for (var v=0; v<vCount; v+=1) {
        var box = new THREE.Mesh(new THREE.BoxGeometry(size,size,size),
                      new THREE.MeshBasicMaterial());
        box.position.x = (h-hCount/2) * spacing;
        box.position.y = (v-vCount/2) * spacing;
        grid.add(box);
    }
}
scene.add(grid);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Liberty Farm while uploading .wlapp file it says Server is not reachable

My ServerFarm.xml File

<?xml version="1.0" encoding="UTF-8"?>
<Farm xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FarmSchema.xsd">
    <LibertyNode Hostname="192.168.0.98" ServerID ="server1_farm" AdminPass="demo" AdminUser="demo" JMXPortNumber="9443"   />
    <LibertyNode Hostname="192.168.0.149" ServerID ="server2_farm" AdminPass="admin" AdminUser="admin" JMXPortNumber="9443"   />
</Farm>

My server.xml File

<application id="worklight" name="worklight" location="project2.war" type="war">
   <application-bnd>
        <security-role name="worklightadmin">
            <user name="demo"/>
        </security-role>
    </application-bnd>
     <classloader delegation="parentLast">
        <privateLibrary id="worklightlib_worklight">
            <fileset dir="${shared.resource.dir}/worklight/lib" includes="worklight-jee-library.jar"/>
            <fileset dir="${wlp.install.dir}/lib" includes="com.ibm.ws.crypto.passwordutil_*.jar"/>
        </privateLibrary>
        <fileset dir="${wlp.install.dir}/lib" includes="com.ibm.ws.crypto.passwordutil_*.jar"/>
        </privateLibrary>
    </classloader>
</application>

com.worklight.common.util.jmx.LibertyFarmRuntimeMBeanHandler E Exception sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: signature check failed

Kindly advice.

A: It may be that you have incorrectly imported the certificate to the keystore. You may follow the instructions in the following post to resolve your issue: https://developer.ibm.com/answers/answers/211204/view.html

A: Everything i did well. i have miss to exchange the certificate in both servers.
well i have followed IBM MobileFirst 7.1 Configuring a server farm. Let try this like i think it will be hopeful for every one.


text:
Q: How to write a get function for a private char array in the class in both .h and .cpp? How to write a get function for a private character array in the class in both .h and .cpp? I don't know whether I should use char* for the type instead or something else.
I have tried using char[] getCharArray(); but it seems not acceptable.
// in .h
class Foo{
private:
   char charArray[32];
public:
   char getCharArray(); // How to write the get function?
};

// in .cpp
char Foo::getCharArray(){
// How to write the get function in .cpp?
}

A: Use an std::array and return a const reference to it. This provides read-only direct access:
#include <array>

class Foo {
public:
    const std::array<char, 32>& getCharArray() const
    {
        return charArray;
    }

private:
    std::array<char, 32> charArray{}; // The '{}' zero-initializes the array.
};

If code needs a const char* pointer to the array, use the data() member function of std::array:
void printFoo(const Foo& foo)
{
    printf("%s", foo.getCharArray().data());
}

A: Since the previous answer didn't actually answer the question....
class Foo{
private:
  char charArray[32];
public:
  const char* getCharArray() const { return charArray; }
};

A: For your question as asked
// in .h
class Foo
{
  private:
      char charArray[32];
  public:
     const char *getCharArray() const;
};

// in .cpp
//    include the header!
const char *Foo::getCharArray() const
{
     return charArray;
}

Bear in mind that the above returns a pointer to private data of the class Foo  (rather than a copy of the array).   The const qualifiers prevent the caller from (deliberately or accidentally) using the returned pointer to manipulate private data of class Foo.
However, your approach (using a raw array of char in a class) is considered a poor approach in C++.   It tends to be harder to use too.
A better approach would be to use a standard container rather than a raw array.
// in .h
#include <array>     //  C++11 and later
class Foo
{
  private:
      std::array<char, 32> charArray;
  public:
     std::array<char, 32> getCharArray() const;
};

// in .cpp
//   include the header!
std::array<char, 3> Foo::getCharArray() const
{
     return charArray;
}

In this approach, the caller of Foo::getCharArray() receives a COPY of the entire array, rather than a pointer or reference to private data of class Foo.    The caller can safely update the array it receives, and then later provide it back to class Foo  (e.g. via a setter).   Whereas, with using a pointer and a raw array, more gymnastics is needed to achieve a similar effect.
Optionally, a const reference to the std::array<char, 3> can be returned in the above, which can avoid some unnecessary copying of complete objects.

A: Something you can do that no one has mentioned is return a reference to the raw char array without needing std::array. I stole this idea from https://stackoverflow.com/a/34439639/10290252.
//.h file
class Foo{
private:
   char charArray[32];
public:
   char (&getCharArray())[32];
};

// .cpp file
char (&Foo::getCharArray())[32]{
   return charArray;
}

I want to stress however DO NOT DO THIS!!
Nikos C gave the correct answer and you should follow their example.


text:
Q: Visual Studio 2019 Professional IDE icons missing after installation My tech support gave me the VS 2019 professional exe. I ran the exe as an administrator but I don't see any of the VS IDE icons loaded. I am not sure whats the issue, can it be the VPN network that is preventing the download of the icons.
I also disconnected VPN and a fresh installation but no luck.
Please help me as I am stuck on this for past 2 days.

A: Please try using the Visual Studio Installer's "Repair" feature to ensure all components are installed correctly.
If that doesn't work, use the "Report a Problem" feature in VS itself to report the issue to Microsoft so someone can investigate.
https://learn.microsoft.com/en-us/visualstudio/ide/how-to-report-a-problem-with-visual-studio?view=vs-2022

A: I was able to get this working, issue was related to wrong OneDrive configured by the admin team, once he changed the OneDrive configuration everything is working as expected


text:
Q: expected vs observed proportion for more than two categories I show four colored cards to subjects asking them to choose one. Ideally all four colors should have equal probability of being chosen. But I notice that red is picked more frequently than others. Is there are test which can tell me if there is a real difference between expected and observed proportions?

A: Yes. If you have data of sufficiently many subjects, you can test whether the difference between the observed and expected outcome is significant.
You calculate the probability $P$ of the specific outcome with only the constraints that are relevant to the problem assuming a hypothesis $H$, which is in this case: The probability of picking red is $\frac14$.
If this probability is smaller than some value $\alpha$ (which is usually taken to be approximately $0.01$), then hypothesis $H$ is rejected.
Example: If you had 100 subjects pick cards and 30 picked red and 70 did not pick red (it doesn't matter what colors this were, since the hypothesis is about red).
Then the probability that at least 30 picked red given the hypothesis that the probability of picking a red card is $\frac14$, can be calculated using the cumulative binomial distribution: $$P =1-\mathrm{binomcdf}(N,p,k)=1-\mathrm{binomcdf}(100,\tfrac14,30)\approx 0.1495$$
Since $0.1495>0.01$, we accept the hypothesis $H$. You can repeat this with your own numbers.


text:
Q: How to avoid being friends multiple times I am stuck with the friendships model. I can be friends with an user multiple times. So I need a condition to avoid add to friend link .
My users_controller :
class UsersController < ApplicationController
    before_filter :authenticate_user!

  def index
        @users = User.all
  end
  def show
    @user = User.find(params[:id])
    @topics = @user.topics.paginate(page: params[:page])
    @friendship = @user.friendships.build(:friend_id => params[:friend_id])
    @friendships = @user.friendships.all

  end

my show.html.erb:

<%= @user.username %>

       <%= link_to "Arkadaşlarıma Ekle", friendships_path(:friend_id => @user), :method => :post,class: "btn btn-large btn-primary" %>

my friendships_controller :
class FriendshipsController < ApplicationController
    before_filter :authenticate_user!

    def create
        @friendship = current_user.friendships.build(:friend_id => params[:friend_id])
        if @friendship.save
            flash[:notice] = "Arkadaşlara eklendi."
            redirect_to root_url
        else
            flash[:error] = "Arkadaşlara Eklenemiyor."
            redirect_to root_url
        end
    end

    def destroy
        @friendship = current_user.friendships.find(params[:id])
        @friendship.destroy
        flash[:notice] = "Arkadaşlarımdan kaldırıldı."
        redirect_to current_user
    end
end

so I guess , I tried add this   method  in users_controller but still no solution for it. Can you help me to fix it?
def friend?(other_user)
   friendships.find_by_friend_id(other_user.id)
 end

and In before link
<% unless friend?(@user) %>
%= link_to "Arkadaşlarıma Ekle", friendships_path(:friend_id => @user), :method => :post,class: "btn btn-large btn-primary" %>
<%end %>

My user model :
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me, :username
  # attr_accessible :title, :body
  has_many :topics
  has_many :posts
  has_many :friendships
    has_many :friends, :through => :friendships
    has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id"
    has_many :inverse_friends, :through => :inverse_friendships, :source => :user
end

my Friendship model :
    class Friendship < ActiveRecord::Base
      attr_accessible :friend_id, :user_id
      belongs_to :user
        belongs_to :friend, :class_name => "User"
    validates :friend, :presence => true, :unless => :friend_is_self

def friend_is_self
  user_id == friend_id ? false : true
end
end

A: I think it is best to do such validations on the model level. use validate_uniqueness_of in your model and test for validity in your controller.

A: Your friend? method is returning the friendship or nil, not true or false as you would expect with a ? method.
Try
def friend?(other_user)
  # this assumes Friendship is a user, which probably isn't true
  # but I don't have your models but this should give you the right idea
  self.friendships.include other_user
end

A: I think the friend? method should be something similar as:
def friend?(other_user)
   current_user.friendships.find_by_friend_id(other_user.id)
end

since I guess friendship should be a table with user_id and friend_id, what we want to check is if this user has othter_user as a friend or not.


text:
Q: Issue with printing in IE8 I have one href link which prints my order details. Now on clicking this in firefox or chrome, order details are getting printed but the same is not happening in IE8.
Though in IE8, order details are getting printed but at the same time it reloads so my page goes to basket page as the current session has no pending orders to complete.
Actually one js file is there which checks the valid session but this js is not placed within the href but in the page, so I think in ie8 the page refreshes while I click the print href and this is causing the page to go basket page.
Please suggest how to get rid of this in IE8....


text:
Q: ParseException at FROM statement when updating SQL view using AND operator with CASE WHEN I am getting an error at the FROM sb.v_transactions t line after my CASE WHEN statements. I tried adding commas, parentheses, and am considering perhaps using CTE to create my output. Was wondering if anyone could help me figure out why I'm getting the error? I have a feeling it has something to do with how I'm using the AND operators.
%sql
UPDATE sb.transactions u
SET t.FranchiseStore = u.FranchiseStore
  AND t.LocationNumber = u.LocationNumber
  AND openflg = CASE openflg
    WHEN o.FiscYKey IS NULL THEN 1
    ELSE 0
    END
  AND closeflg_y = CASE closeflg_y
    WHEN c.FiscYKey IS NULL THEN 1
    ELSE 0
    END
  AND closeflg_p = CASE closeflg_p
    WHEN c.FiscYKey IS NULL THEN 1
    ELSE 0
    END
  AND closeflg_w = CASE closeflg_w
    WHEN c.FiscYKey IS NULL THEN 1
t.FiscWkKey THEN 1
    ELSE 0
    END

-- PARSE EXCEPTION ON THE FROM BELOW. WHY?
FROM sb.v_transactions t
LEFT JOIN sb.v_loc_opendates o
ON t.LocationNumber = o.LocationNumber
LEFT JOIN sb.v_loc_closedates c
ON t.LocationNumber = c.LocationNumber

WHERE t.LocationNumber = u.LocationNumber
AND t.DayDate = u.DayDate


text:
Q: Create Kali LIVE USB from Macbook with persistence I'm attempting to create a Kali LIVE USB with persistence from my Macbook.  I'm following these instructions from Kali  I can generate the USB and boot into the image.  Selecting "with persistence" does not persist.
Toward the middle of the page we have

Create and format an additional partition on the USB drive.
First, let's create the new partition in the empty space above our Kali
Live partitions.
end=7gb
read start _ < <(du -bcm kali-linux-2016.2-amd64.iso | tail -1); echo > $start
parted /dev/sdb mkpart primary $start $end
The parted command may advise you that it can't use the exact start values you specified; if so, accept the suggested value instead. If advised that the partition isn't placed at an optimal location, "ignore" it. When parted completes, the new partition should have been created at /dev/sdb3; again, this can be verified with the command "fdisk -l".

However, there is no "parted" command on OS X and the diskutil does not seem to support start and stop.  I would appreciate help in one of two options

*

*Please explain how to use diskutil to find the start and stop values.

*Alternatively, a complete instruction set, preferably not using third party, proprietary software.


text:
Q: How do I export a Java application in Eclipse? In Netbeans a simple click to clean/build creates a nice folder called dist/ in the project workspace and contains a runnable .jar, all in the background no repetitive popup menu.
Is there some sort of setting in Eclipse to make this same process faster and easier, even a hotkey to direct export using previously set settings would work?

A: It's not particularly hard in eclipse.

*

*Right click on the project name and select export.

*Open the Java section and select "Runnable Jar File", click "Next"

*Fill out the supplied form with the appropriate options.

That's about it.


text:
Q: Trick to getting initWithNibFile to be invoked? I've implemented a View Controller, and I'm trying to do some very basic initialization in initWithNibFile...which I understand to be the designated initializer for View Controller objects.
I've tried to put breakpoints on the code, and have put very simple NSLog statements into it as well.  Regardless...I'm not seeing it be executed (and the object i'm attempting to alloc/init inside the function is also not being allocated - so I'm about 99% sure I'm not hitting the code.
Is there something I need to do elsewhere to cause this method to be invoked?
I'm getting a clean build, no warnings or errors.  And the app successfully loads up the View, and I can invoke a ButtonClick method I've coded and connected to this same View Controller.
Any suggestions would be appreciated.
TC

A: I ended up moving my allocation logic to viewDidLoad, and that works fine.
Not sure why the initWithNibFile was not working...but I'll take the small victory !!!
Thanks for offering to look at the code bpapa.

A: You probably need initWithCoder:  It's what the SDK uses to read from nib files during startup.
initWithNibFile: is almost never called by the system.  Usually you call this manually.  The documentation is quite misleading on this point.
In any case, be careful doing too much initialization in the initWithXXXX methods.  The view's targets and actions aren't likely to be set up and connected yet.  viewDidLoad is almost always the right place to do viewController setup anyways.


text:
Q: Opacity/Brightness with Mouseover on an imagemap I have a picture with many people (~30) and I want to change the Opacity of specific areas when my mouse is above a face.
Id like to make that with Gimp (if possible?) and an imagemap.
What exactly I want:
I want to move my mouse over a face and the area AROUND the face (in a shape), im over, should be totally bright, which means the opacity should be changed. So the face in the middle is normal, and a small part around the face is brighter (or white).
I cant find anything in the internet, I just got some ideas but no clear idea how I should do it.
Probably with an opacity map? With slices? With div's?
Would be great if someone could help me or even have a code example!


text:
Q: How to check existing users and groups in kubernetes cluster? We can check the service accounts in Kubernetes Cluster. Likewise, Is it possible to check the existing users and groups of my Kubernetes cluster with Cluster Admin privileges. If yes then how ? If no then why ?
NOTE: I am using EKS

A: Posting this as a community wiki, feel free to edit and expand.

This won't answer everything, however there are some concepts and ideas.
In short words there's no easy way. It's not possible to do using kubernetes itself. Reason for this is:

All Kubernetes clusters have two categories of users: service accounts
managed by Kubernetes, and normal users.
It is assumed that a cluster-independent service manages normal users
in the following ways:

*

*an administrator distributing private keys

*a user store like Keystone or Google Accounts

*a file with a list of usernames and passwords

In this regard, Kubernetes does not have objects which represent normal
user accounts. Normal users cannot be added to a cluster through an
API call.

Source
More details and examples from another answer on SO

As for EKS part which is mentioned, it should be done using AWS IAM in connection to kubernetes RBAC. Below articles about setting up IAM roles in kubernetes cluster. Same way it will be possible to find which role has cluster admin permissions:

*

*Managing users or IAM roles for your cluster

*provide access to other IAM users and roles
If another tool is used for identity managing, it should be used (e.g. LDAP)


text: Q: Make Valid-Flags clearly distinguishable from Invalid-Flags Maybe it is just my eyes, but it is hard to scan your recent flags to tell what is Valid and what is Invalid. Can we highlight Valid in green or some other color to make it stand out?


text:
Q: Block Size in hadoop I am currently working on a four node multi cluster. Can anyone suggest me the appropriate block size for working on a 22GB input file?
Thanks in advance.
Here are my performance results:
64M  - 32 min.
128M - 19.4 min
256M - 15 min
Now, should I consider making it much larger to 1GB/2GB? Kindly explain if there are any issues if done so.
Edit:
 Also, if the performance increases with increasing block size for a 20GB input file why is the default block size 64MB or 128MB?
Kindly answer similar question over here

A: What is the split size that you are going to use for processing this file? If it's slightly more than the default block size, then i'd suggest you to change the block size to the split size value. This should increase the chances of data locality for mappers thereby improving the job throughput.
Split size is computed by input format.
    protected long computeSplitSize(long blockSize, long minSize,
                                  long maxSize) {
    return Math.max(minSize, Math.min(maxSize, blockSize));
  }

minSize and maxSize can be manipulated using the below configuration parameters,

mapreduce.input.fileinputformat.split.minsize
mapreduce.input.fileinputformat.split.maxsize

You can find the detailed data flow in the FileInputFormat class.

A: How heavy is the per-line processing?  If it were simply a kind of "grep" then you should be fine to increase the block size up to 1GB . Why not simply try it out? Your performance numbers indicate a positive result in increasing the block size already.
The consideration for smaller block sizes would be if each line requires significant ancillary processing.   But that is doubtful given your already established performance trends.


text:
Q: PHP QRCode Library: how to link to download SVG file? I have HTML links like this:

I need that the activated link downloads the SVG file.
getqr.php at this time shows the SVG onscreen
require_once('qrlib.php');
$theurl = "$_SERVER[REQUEST_URI]";
$urlarray = parse_url($theurl);
parse_str($urlarray['query'], $queryarray);
$theqrid = $queryarray['id'];
$dataText = 'http://dest.mysite.xyz/qr?id='.$theqrid;
echo QRcode::svg($dataText);

Whats needs to be different?

A: There are two options. Either handle the QR code image as an attachment in PHP (here I assume a PNG will be the result):
header('Content-Disposition: attachment; filename=qrcode.jpg');
header('Content-type: image/png');

require_once('qrlib.php');
$theurl = "$_SERVER[REQUEST_URI]";
$urlarray = parse_url($theurl);
parse_str($urlarray['query'], $queryarray);
$theqrid = $queryarray['id'];
$dataText = 'http://dest.mysite.xyz/qr?id='.$theqrid;
echo QRcode::svg($dataText);

or set the download attribute on the link:
QR code


text:
Q: The NavigationBar is not totally hidden I want to hide the NavigationBar and the stateBar to show fullScreen Image, but it seems that the navigationBar is not totally hidden:

The code is as below:
  [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
  [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackTranslucent];

The height of the part which is not hidden is the same as the stateBar. How to fix this problem? thanks!

A: Add the following to your Info.plist;
Status bar is initially hidden YES

A: Have you tried:
[[self navigationController] setNavigationBarHidden:YES animated:YES];

or:
self.wantsFullScreenLayout = YES;

?


text:
Q: Regular Expression to reject special characters except slahses? I have a RegularExpressionValidator to block all special characters.  Currently my expression is this:
ValidationExpression="^[0-9a-zA-Z ]+$"

However I would like to allow slashes: (/)
I'm new to regular expressions and not sure how to write them.  I've looked around online but don't see one to allow slashes.  Any help?

A: Simply place the characters that you want to match inside of your character class [].
ValidationExpression="^[a-zA-Z0-9/ ]+$"

Regular expression:
^                   # the beginning of the string

 [a-zA-Z0-9/ ]+     # any character of: 'a' to 'z', 'A' to 'Z',
                    # '0' to '9', '/', ' ' (1 or more times)

$                   # before an optional \n, and the end of the string

Since you stated you are new to regular expressions, I would begin with this Tutorial. For more information about characters inside of a character class, take a look at Character Classes or Character Sets


text:
Q: Angular JS code not working I copied this angularjs code from a book "ng-book". But it is not working at all..........................................................
<!DOCTYPE html>

    <title>Simple App</title>

        Hello

A: *

*Use $interval rather and setInterval.

*No need of $scope.$apply() when you use angular's $interval

*You need the ng-app defined

*The controller definition should be like in the snippet

Here is a working code snippet

var demoApp = angular.module('demoApp', []);
demoApp.controller('MyController', function($interval, $scope) {
  $scope.clock = new Date();
  var updateClock = function() {
    $scope.clock = new Date();
  };
  $interval(function() {
    updateClock();
  }, 1000);
  updateClock();
});

<!DOCTYPE html>

  <title>Simple App</title>

    Hello

A: What you are doing is not the most efficient way. For example you could use $interval and so on..
But since you are just starting with Angular, I've made the code working with minimal addition or modification so you can understand:

//addition-start
var app = angular.module('myApp', []);
app.controller("MyController", MyController);
//addition-end
function MyController($scope) {
  $scope.clock = new Date();
  var updateClock = function() {
    $scope.clock = new Date();
  };
  setInterval(function() {
    $scope.$apply(updateClock);
  }, 1000);
  updateClock();
};
<!DOCTYPE html>

  <title>Simple App</title>

    Hello

A: first read how to difine angular module and how it works.you didn't define module in html
<!DOCTYPE html>

        <title>Simple App</title>

            Hello

A: You forgot to define your module ng-app
<!DOCTYPE html>

    <title>Simple App</title>

        Hello {{clock}}

Doc
Difference between set-interval and $interval
ng-bind has one-way data binding ($scope --> view). It has a shortcut {{ val }} which displays the scope value $scope.val inserted into html where val is a variable name.


text:
Q: Custom Font (via Asset Pipeline) not Appearing on Heroku with Rails 5.2 I'm trying to get the Playlist font to work on my Rails app.  It's showing up on localhost but not on Heroku.
I added a fonts folder inside my assets folder, put the PlaylistCaps.otf and PlaylistScript.otf files in it, and added this line to my config/application.rb:
config.assets.paths << Rails.root.join("app","assets","fonts")

I have this in my application.scss file:
@font-face {
  font-family: "PlaylistScript";
  src: url(/assets/fonts/PlaylistScript.otf) format("opentype");
}

@font-face {
  font-family: "PlaylistCaps";
  src: url(/assets/fonts/PlaylistCaps.otf) format("opentype");
}

I've also tried having the source files on S3 and linking that in the src: url() but to no avail...
I checked to make sure Heroku precompiled my assets on deploy (I don't do it separately).
Can anyone help me figure this out?  My live site is currently displaying that awful boilerplate cursive.  I've consulted many SO posts (here, here, here) and some gists (like this) but can't find a working solution.
The live site is here if you want to poke around.
Update
I added a google font backup option in my scss to avoid the cursive default.  It still isn't showing the proper font, but at least it doesn't claw your eyes out with ugliness upon pageload:
$font-script: 'PlaylistScript', 'Arizonia', cursive;

A: You should use asset-path in your Rails sass files.
So instead of:
src: url(/assets/fonts/PlaylistCaps.otf) format("opentype");

Do:
src: asset-path(PlaylistCaps) format("opentype");

There's some documentation here: https://guides.rubyonrails.org/asset_pipeline.html#css-and-sass
When you do that, the correct asset paths should get generated. For example, you'll get "fingerprinted" URLs like this: https://www.thestaysanemom.com/assets/PlaylistScript-4a2ebf308b737499dcd1eef2a5cb0edf756089ea4eca0b811034ab41c4dbca8f.otf Which if you see will now download that font.

A: I never use offline fonts before, but i tried it just now and this works:
Delete the folder path and use asset-url instead of url:
@font-face {
  font-family: 'PlaylistScript';
  src: asset-url('PlaylistScript.otf');
}

@font-face {
  font-family: 'PlaylistCaps';
  src: asset-url('PlaylistCaps.otf');
}

Hope that helps.


text:
Q: check Relationship table on model, ruby on rails i have project with ruby on rails 3.2.14. i have 2 table named "countries" and "users". in "users" table have FK named "countries_id".
on model i have make table relation like:
in countries.rb i have set relationship like:
class Countries < ActiveRecord::Base
  self.primary_key = "id"
  has_many  :users,  :dependent => :destroy # plural
end

and in users.rb like:
class Users < ActiveRecord::Base
  self.primary_key = "id"

  belongs_to    :countries,
                :class_name => "Countries",
                :foreign_key => "countries_id"

end

and when i want to check plural relationship, it's didn't..
i type in rails console command like below
c=Countries.find_by_id(1)

and then when i type command  u=c.users , i have some error
the error:
c=Countries.find_by_id(1)
  Countries Load (0.3ms)  SELECT `countries`.* FROM `countries` WHERE `countries`.`id` = 1 LIMIT 1
 => #<Countries id: 1, code: "IND", name: "Indonesia", created_at: "2014-02-17 09:18:11", updated_at: "2014-02-17 09:18:11">
1.9.3-p484 :012 > u=c.users
NameError: uninitialized constant Countries::User
    from /home/vinra/.rvm/gems/ruby-1.9.3-p484@rails3.2/gems/activerecord-3.2.14/lib/active_record/inheritance.rb:111:in `compute_type'
    from /home/vinra/.rvm/gems/ruby-1.9.3-p484@rails3.2/gems/activerecord-3.2.14/lib/active_record/reflection.rb:172:in `klass'
    from /home/vinra/.rvm/gems/ruby-1.9.3-p484@rails3.2/gems/activerecord-3.2.14/lib/active_record/associations/association.rb:118:in `klass'
    from /home/vinra/.rvm/gems/ruby-1.9.3-p484@rails3.2/gems/activerecord-3.2.14/lib/active_record/associations/association.rb:171:in `find_target?'
    from /home/vinra/.rvm/gems/ruby-1.9.3-p484@rails3.2/gems/activerecord-3.2.14/lib/active_record/associations/collection_association.rb:334:in `load_target'
    from /home/vinra/.rvm/gems/ruby-1.9.3-p484@rails3.2/gems/activerecord-3.2.14/lib/active_record/associations/collection_proxy.rb:44:in `load_target'
    from /home/vinra/.rvm/gems/ruby-1.9.3-p484@rails3.2/gems/activerecord-3.2.14/lib/active_record/associations/collection_proxy.rb:87:in `method_missing'
    from /home/vinra/.rvm/gems/ruby-1.9.3-p484@rails3.2/gems/railties-3.2.14/lib/rails/commands/console.rb:47:in `start'
    from /home/vinra/.rvm/gems/ruby-1.9.3-p484@rails3.2/gems/railties-3.2.14/lib/rails/commands/console.rb:8:in `start'
    from /home/vinra/.rvm/gems/ruby-1.9.3-p484@rails3.2/gems/railties-3.2.14/lib/rails/commands.rb:41:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'
1.9.3-p484 :013 > ^C
1.9.3-p484 :013 >

i really hopping somebody knowing my problem,
anyway thank you,, sorry for my bad english :)

A: You should change a lot of things in your code:
app/models/country.rb
class Country < ActiveRecord::Base
    has_many :users, :dependent => :destroy
end

app/models/user.rb
class Users < ActiveRecord::Base
    belongs_to :country,
               :foreign_key => "countries_id"
end

And use it like this:
country = Country.find(1)
p country.users

A: The Problem is that Rails Active Record Models cant be Plural. You created the models with plural,so change them to singular or better way is to create them again with singular names.
Countries should be Country and Users should be User.
For more information on Naming Conventions,see This.
Hope it helps!


text:
Q: Facing issue when trying to generate excel with multiple list drop-downs in same sheet I am facing an issue when am trying to generate an excel with more than one Type_List dropdown using PHPExcel on Symfony 2.8.
I am using PHPExcel_Cell_DataValidation::TYPE_LIST to generate the columns of drop-down type. My code works fine when am generating only one column in the active sheet as a drop-down. However, when am trying to generate more than one columns as drop-down type in a sheet, am getting an unusable excel.
Here is a sample screenshot of the error am getting on opening the generated excel,

Here is the action code that I wrote,
//generating an excel using PHPexcel
public function generateExcel2Action(Request $request)
{
    $responseString = 'Initial Mem. '.(memory_get_peak_usage(true)/1024/1024).' MB
';
    $startTime = microtime(true);

    //make a new object
    $objPHPExcel = new PHPExcel();
    //set properties
    $objPHPExcel->getProperties()->setCreator("Ramit Mitra")
        ->setLastModifiedBy("Ramit Mitra")
        ->setTitle("Sample excel doc")
        ->setSubject("Office 2007 XLSX Test Document")
        ->setDescription("Test document for Office 2007 XLSX, generated using PHPExcel.")
        ->setKeywords("office 2007 openxml php")
        ->setCategory("Test result file");

    //Excel headers
    $objPHPExcel->setActiveSheetIndex(0);
    $objPHPExcel->getActiveSheet()->setCellValue('A1', 'Shipment Number');
    $objPHPExcel->getActiveSheet()->setCellValue('B1', 'Country');
    $objPHPExcel->getActiveSheet()->setCellValue('C1', 'Region');
    $objPHPExcel->getActiveSheet()->setCellValue('D1', 'Choose Storage Condition');
    $objPHPExcel->getActiveSheet()->setCellValue('E1', 'Choose Storage Area');
    $objPHPExcel->getActiveSheet()->setCellValue('F1', 'Choose Help Text');
    $objPHPExcel->getActiveSheet()->setCellValue('G1', 'Memory in use');

    //QUERY AND SET DATA
    $em = $this->getDoctrine()->getManager();
    //create all options
    $suSC = ['Cold', 'Hot', 'Normal'];
    $suSA = ['SM', 'LG', 'XS', 'XL'];
    $suHT = ['Text 1', 'Text 2', 'Text 3'];

    $i = 2;
    $allCountries = $em->getRepository('DemoBundle:Country')->findAll();
    foreach($allCountries as $key => $val) {
        //shpno
        $objPHPExcel->getActiveSheet()->setCellValue("A$i", 'SHP'.rand(10000,90000));
        //country
        $objPHPExcel->getActiveSheet()->setCellValue("B$i", $val->getName());
        //region
        $objPHPExcel->getActiveSheet()->setCellValue("C$i", $val->getRegion()->getName());
        //Choose Storage Condition
        $objValidation = $objPHPExcel->getActiveSheet()->getCell("D$i")->getDataValidation();
        $objValidation->setType(\PHPExcel_Cell_DataValidation::TYPE_LIST);
        $objValidation->setErrorStyle(\PHPExcel_Cell_DataValidation::STYLE_INFORMATION);
        $objValidation->setAllowBlank(false);
        $objValidation->setShowInputMessage(true);
        $objValidation->setShowDropDown(true);
        $objValidation->setPromptTitle('Pick Storage Condition');
        $objValidation->setPrompt('Please pick a value from the drop-down list.');
        $objValidation->setErrorTitle('Input error');
        $objValidation->setError('Value is not in list');
        $objValidation->setFormula1('"'.implode(',', $suSC).'"');
        unset($objValidation);
        //Choose Storage Area
        $objValidation1 = $objPHPExcel->getActiveSheet()->getCell("E$i")->getDataValidation();
        $objValidation1->setType(\PHPExcel_Cell_DataValidation::TYPE_LIST);
        $objValidation1->setErrorStyle(\PHPExcel_Cell_DataValidation::STYLE_INFORMATION);
        $objValidation1->setAllowBlank(false);
        $objValidation1->setShowInputMessage(true);
        $objValidation1->setShowDropDown(true);
        $objValidation1->setPromptTitle('Pick Storage Area');
        $objValidation1->setPrompt('Please pick a value from the drop-down list.');
        $objValidation1->setErrorTitle('Input error');
        $objValidation1->setError('Value is not in list');
        $objValidation1->setFormula1('"'.implode(',', $suSA).'"');
        unset($objValidation1);
        //Choose Help Text
        $objValidation2 = $objPHPExcel->getActiveSheet()->getCell("F$i")->getDataValidation();
        $objValidation2->setType(\PHPExcel_Cell_DataValidation::TYPE_LIST);
        $objValidation2->setErrorStyle(\PHPExcel_Cell_DataValidation::STYLE_INFORMATION);
        $objValidation2->setAllowBlank(false);
        $objValidation2->setShowInputMessage(true);
        $objValidation2->setShowDropDown(true);
        $objValidation2->setPromptTitle('Pick Help Text');
        $objValidation2->setPrompt('Please pick a value from the drop-down list.');
        $objValidation2->setErrorTitle('Input error');
        $objValidation2->setError('Value is not in list');
        $objValidation2->setFormula1('"'.implode(',', $suHT).'"');
        unset($objValidation2);
        //mem in use
        $objPHPExcel->getActiveSheet()->setCellValue("G$i", (memory_get_peak_usage(true)/1024/1024).' MB');
        $i++;
    }
    unset($allCountries);
    // create the writer
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    $file = $this->get('kernel')->getRootDir() . "\..\web" . $this->getRequest()->getBasePath()."/temp/test2.xlsx";
    $objWriter->save($file);
    unset($objWriter);
    $endTime = microtime(true) - $startTime;
    $responseString .= 'Final Mem. '.(memory_get_peak_usage(true)/1024/1024).' MB
'."File generated @ $file
Executed in :: $endTime";
    unset($startTime);
    unset($endTime);
    //send response
    return new Response($responseString);
}

Please provide a solution to this. I need to generate multiple columns in the same sheet as drop-downs.
Basic Env details:
Windows 7 OS,
PHP 7.1.1 on XAMPP
Symfony 2.8.26


text:
Q: How to limit number of permutations I have about 20 short strings that I want to permutate. I want only permutations that have len == 8.
I would like to avoid calculating every possible permutation, as seen below:
import itertools
p = itertools.permutations([s1, s2, s3, s4, s5, s6,...])
for i in p:
    s = ''.join(j for j in i)
    if len(s)==8:
        print(s)

But that's too slow right? How can I decrease the number of calculations? (to not spend processing and RAM).

A: The first, obvious thing to do is filter out any strings with length > 8:
newList = [i for i in [s1, s2, s3, s4, s5, s6, ...] if len(i) <= 8]

Then, you can use the second argument of itertools.permutations to set the number of items you want. If you have no empty strings in your list, you'll never need more than 8 items, so we can use 8 as the second argument:
p = itertools.permutations(newList, 8)

However, if any of your strings are longer than one character, this won't get you what you want, since it will only return permutations of exactly 8 items. One way to resolve this is to iterate through the various lengths:
pList = [itertools.permutations(newList, length) for length in range(1, 9)]

Yet here you end up with an enormous amount of permutations to filter through: P(20, 8) + P(20, 7) + ... P(20, 1) = roughly 5.5 billion, which is impractical to work with.
A different direction
Instead of using permutations, let's use combinations, of which there are far fewer ("only" 263,949). Recall that in combinations, the order of the combined items doesn't matter, while in permutations it does. Thus we can use the smaller set of combinations to filter for the length 8 that we want:
cList = (combo for length in range(1, 9)
    for combo in itertools.combinations(newList, length)
    if len(''.join(combo)) == 8)

Using () instead of [] will make this a generator rather than a list, to delay evaluation until we really need it. And now we are close!
We can get our final result by taking the permutations of the items in cList:
result = [''.join(perm) for combo in cList
    for perm in itertools.permutations(combo)]


text:
Q: How to specify a config file with path? I would like to setup one web.config file for my solution. How do I specify the path of the config file I am using?

A: Here is how you can specify new app setting in your web.config file.
<appSettings>
  <add key="LoggingDir" value="C:\\Logs\\"/>
  <add key="environment" value="test"/>
  <add key="smtp.server" value="incoming.ABank.com"/>
</appSettings>

And you can access in your code by
private static String logDirectory = ConfigurationManager.AppSettings["LoggingDir"].ToString();
private static String MailServer= ConfigurationManager.AppSettings["smtp.server"].ToString();

I prefer all my app or environmental settings in a separate file when I have lot of them. You can do that by
<appSettings configSource="env\ApplicationSettings.config"/>

and then write above <appSettings> </appSettings> section in ApplicationSettings.config file.

A: If you're creating an MVC application, then generally you can access your configuration file (web.config, in the root of the project) using ConfigurationManager:
string sConnectionString = ConfigurationManager.ConnectionStrings["SqlServer"].ConnectionString;

You could try loading a different configuration file using:
ConfigurationManager.OpenExeConfiguration()

Here's a link to the MSDN documentation for the ConfigurationManager class:
http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx - specifically, there's some information included there about the class's intended usage and operation.
Hope that helps,
Cheers!

A: Not knowing what your projets look like I'm going to go out on a limb here.
Just an FYI, in IIS there will be inheritance that may solve your issues, just be sure to setup your apps for debugging in IIS in the same folder structure.
If you have multiple libraries, you dont need config files for those libs (app.config), so what are you trying to to do eliminate multiple config files? Do you have multiple web sites? If you only have a single site and other class library projects, you won't beed other config files as they won't be used at runtime anyways. If you have multiple web sites, then consider inheritance.
10 things asp.net developers should know about web.config inheritance and overrides


text:
Q: How can you use an Apex class from the hello.apex script How can you use an Apex class from the hello.apex script in a newly created standard project with VS Code?
This is probably really simple, I thought I should use some 'using' or 'include' statement but I cannot find the information. This is what I did:
I am working from VS Code.
sfdx create project.
chosen: Standard.
In the directory scripts/apex I open the file hello.apex.
Log in to org, vscodeOrg.
sfdx Execute Anonymous Apex with Editor contents, this succeeds.
sfdx Create Apex Class, called NewClass with static function
right under the constructor I add a static method, the complete class code is now:
public with sharing class NewClass {
    public NewClass() {
    }
    public static void Test() {
        System.debug('call from apex class');
    }
}

The file is located in: ...\NewStandardProject\force-app\main\default\classes\NewClass.cls
Go back to hello.apex, execute still succeeds.
I add in the hello.apex file:
NewClass.Test();
Making the script code this:
string tempvar = 'Enter_your_name_here';
System.debug('Hello World!');
System.debug('My name is ' + tempvar);

NewClass.Test();

The editor gives me 'Intelligent code completion', so it seems my new class is known.
I try to execute again with 'Execute Anonymous Apex with Editor contents', it fails with this feed back:
Error: Variable does not exist: NewClass
If I replace the static call with e.g.
NewClass nc = new NewClass();
It gives the same error.
If I replace public with global in NewClass, that also does not help.
What am I doing wrong here?

A: Answering my own question then to make this complete:

*

*Install sfdx

*Install vs sfdx plug in

*Press Ctrl-Shift P to call the sfdx from vs code

*sfdx create project -> Standard

In the directory scripts/apex, open the file hello.apex
Log in to org, vscodeOrg (or if you have no standard org yet call  control shift p, sfdx create a default scratch org)
sfdx Execute Anonymous Apex with Editor contents, this succeeds
sfdx Create Apex Class, called NewClass with static function
right under the constructor I add a static method, the complete class code is now:
public with sharing class NewClass {
    public NewClass() {
    }
    public static void Test() {
        System.debug('call from apex class');
    }
}

In the left pain click on the file in the project directory and choose 'sfdx deploy source to org'.
(And that step as a developer customed to working with local executables, I forgot).
Add in the hello.apex file: NewClass.Test();
Making the code there:
// Use .apex files to store anonymous Apex.
// You can execute anonymous Apex in VS Code by selecting the
//     apex text and running the command:
//     SFDX: Execute Anonymous Apex with Currently Selected Text
// You can also execute the entire file by running the command:
//     SFDX: Execute Anonymous Apex with Editor Contents

string tempvar = 'Enter_your_name_here';
System.debug('Hello World!');
System.debug('My name is ' + tempvar);

NewClass.Test();

I try to execute again with 'Execute Anonymous Apex with Editor contents'.
In the output amongst a few other lines you should see: 'call from apex class'.


text:
Q: Nginx limit_req_zone ignores rate value I have a strange behavior my config looks something like this:
http {
    limit_req_zone $binary_remote_addr zone=nocachelimit:10m rate=120r/m;
}
...
location "/api" {
    {
        limit_req zone=nocachelimit burst=20;
    }
}

Regardless of what values i put into the rate, I even tried 1000r/s
I keep getting log entries for "normal" users that say:
 [warn] 16526#0: *4661 delaying request, excess: 1.000, by zone "nocachelimit"

The typical usecase is a Pageload that does not fall into the zone + 4-5 Ajax requests that will should be limited to the zone.
What could be the cause for this kind of behavior.

A: The rate determines how fast requests are processed.  If you set the rate to 120r/m, that means 1 request will get processed every 0.5 seconds.
If you get 5 requests all at once, it doesn't mean that they'll all go through.  They'll get queued up (up to your burst size), and get processed sequentially, 1 every 0.5 seconds.
You're getting that warning because things are going into the queue and getting delayed.  It does not mean that they're getting rejected.
If you don't want things getting delayed, then use the nodelay parameter:
location "/api" {
  limit_req zone=nocachelimit burst=20 nodelay;
}

For more details on exactly how this works, see https://www.nginx.com/blog/rate-limiting-nginx/


text:
Q: They are exception instead of compile error in Java.why? sorry for bad English.
Obviously, division by zero is always undefined. So why that is an exception at  run time?  Why that is not a compile error ? conclusion of division by zero not changed at run time. It is different from something like file not found exception which that will be determined after execution.
        System.out.println(1/0);

Another example :
        Person firstPerson = (Person) new Object();

compiler permit parent to child cast,but it throws exception at runtime.

A: Compilers usually only check for syntax errors, not semantic errors. And these are semantic errors. The syntax looks fine for both of your codelines. You divide two Integers, and cast an object to another type. Both are valid operations on syntactical level. The actual error is caused by the semantic (cant divide by 0 / the object you try to cast is no instance of a subtype of Person). And consider this code:
class AnObject{
     public AnObject(){
          divide7(0);
     }

     public int divide7(int i){
          return (7 / i);
     }
}

It divides 7 by 0, but if this was a compiletime error, compilers would be horribly inefficient, since they have to inspect the complete code everytime (every single path). And sometimes input is unknown (for example input from a server / the user).

A: The compiler doesn't check for exceptions in the program so often. This is usually because the programmer would know about any exception their program would throw (For example calling an undefined item and getting a thrown NullPointerException/IOException which they should catch to keep the program running)


text:
Q: MVC ViewModel Error - No parameterless constructor defined for this object I would like to know how can I use my ViewModel on the Create Action? I tried several examples I found here in the forum, but none solved my problem. I've been racking my brain for a few days, but can't figure out what is wrong.
Whenever I click the Create button I get the following error:
No parameterless constructor defined for this object.
@model MvcMusicStore.ViewModels.AlbumViewModel

@{
    ViewBag.Title = "Create";
}

Create

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Album</legend>

            @Html.LabelFor(model => model.AlbumItem.GenreId, "Genre")

            @Html.DropDownList("Genres", String.Empty)
            @Html.ValidationMessageFor(model => model.AlbumItem.GenreId)

            @Html.LabelFor(model => model.AlbumItem.ArtistId, "Artist")

            @Html.DropDownList("Artists", String.Empty)
            @Html.ValidationMessageFor(model => model.AlbumItem.ArtistId)

            @Html.LabelFor(model => model.AlbumItem.Title)

            @Html.EditorFor(model => model.AlbumItem.Title)
            @Html.ValidationMessageFor(model => model.AlbumItem.Title)

            @Html.LabelFor(model => model.AlbumItem.Price)

            @Html.EditorFor(model => model.AlbumItem.Price)
            @Html.ValidationMessageFor(model => model.AlbumItem.Price)

            @Html.LabelFor(model => model.AlbumItem.AlbumArtUrl)

            @Html.EditorFor(model => model.AlbumItem.AlbumArtUrl)
            @Html.ValidationMessageFor(model => model.AlbumItem.AlbumArtUrl)

            <input type="submit" value="Create" />

    </fieldset>
}

    @Html.ActionLink("Back to List", "Index")

Create.cshtml
    public class StoreManagerController : Controller
        {
            private MusicStoreDB db = new MusicStoreDB();

            //
            // GET: /StoreManager/Create

            public ActionResult Create()
            {
                var viewModel = new AlbumViewModel()
                {
                    Genres = new SelectList(db.Genres, "GenreId", "Name"),
                    Artists = new SelectList(db.Artists, "ArtistId", "Name")
                };
                return View(viewModel);
            }

            //
            // POST: /StoreManager/Create

            [HttpPost]
            public ActionResult Create(AlbumViewModel vm)
            {
                if (ModelState.IsValid)
                {
                    db.Albums.Add(vm.AlbumItem);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }

                vm.Genres = new SelectList(db.Genres, "GenreId", "Name", vm.AlbumItem.GenreId);
                vm.Artists = new SelectList(db.Artists, "ArtistId", "Name", vm.AlbumItem.ArtistId);
                return View(vm);
            }
}

StoreManager.cs - Snippet
public class AlbumViewModel
    {
        public AlbumViewModel()
        {
            //  nothing
        }

        public Album AlbumItem { get; set; }
        public SelectList Genres { get; set; }
        public SelectList Artists { get; set; }
    }

public class Album
    {
        public Album()
        {
            //  nothing
        }

        public virtual int AlbumId { get; set; }
        public virtual int GenreId { get; set; }
        public virtual int ArtistId { get; set; }
        public virtual string Title { get; set; }
        public virtual decimal Price { get; set; }
        public virtual string AlbumArtUrl { get; set; }
        public virtual Genre Genre { get; set; }
        public virtual Artist Artist { get; set; }
    }

public class Artist
    {
        public Artist()
        {
            // nothing
        }

        public virtual int ArtistId { get; set; }
        public virtual string Name { get; set; }
    }

public class Genre
    {
        public Genre()
        {
            // nothing
        }

        public virtual int GenreId { get; set; }
        public virtual string Name { get; set; }
        public virtual string Description { get; set; }
        public virtual List<Album> Albums { get; set; }
    }

A: If I had a nickel for every time I've seen this problem.  It's typically related to the naming of your model properties and how you use them in a DropDownList.  99.999% of the time it's because people are using Html.DropDownList() and naming it the same as their SelectList.  This is one reason you should use the strongly typed DropDownListFor.
In this case, your problem is that you have SelectLists named Genres and Artists, then in your view you have:
@Html.DropDownList("Genres", String.Empty)
@Html.DropDownList("Artists", String.Empty)

See, same name.
What you should do is change your Model to make the SelectLists be named GenreList and ArtistList.  Then, change your view to use strongly typed model.
@Html.DropDownListFor(m => m.AlbumItem.GenreID, Model.GenreList)
@Html.DropDownListFor(m => m.AlbumItem.ArtistID, Model.ArtistList)

The reason this happens is that you are posting a value called Genres to the controller.  The default model binder dutifully looks in the model to find something called Genres and instantiate it.  But, rather than an ID or string, it finds a SelectList named Genres, and when it tries to instantiate it, it finds there is no default constructor.
Thus your error.  SO is filled with questions asking about this same thing.

A: Similar to Erik Funkenbusch's answer I'd added a DropDownList to my form, however in my case it wasn't (and wasn't intended to be) submitted with the form as it was outside of the <form></form> tags:
@Html.DropDownList("myField", Model.MyField)

As the Model contained the field for display only, this also caused the No parameterless constructor defined for this object error because the field wasn't submitted at all.
In this case I fixed it by adding an exclude binding:
public ActionResult Foo(int id, int? page, [Bind(Exclude = "MyField")]MyModel model)

A: For me the problem was in the BeginForm() method itself. It looked like this:
@using (Html.BeginForm("MyAccount", "MyController", Model))

Copied and pasted in from another project's Login page, which doesn't have a dropdown.
Anyway, remove the Model from the parameter list and it all works just fine :)


text:
Q: which sqlite version is compatible for android 2.2 froyo Currently, my sqlite version isn't compatible for Android 2.2 froyo (Samsung galaxy ace) and encountering error message. Please let me know which sqlite version I need to use for Android 2.2 froyo.
private static class DatabaseHelper extends SQLiteOpenHelper {

DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {

    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                + newVersion);
    }
}

A: Using the emulators:
3-1.5-Cupcake: 3.5.9
4-1.6-Donut: 3.5.9
7-2.1-Eclair: 3.5.9
8-2.2-Froyo: 3.6.22
9-2.3.1-Gingerbread: 3.6.22
10-2.3.3-Gingerbread: 3.6.22
11-3.0-Honeycomb: 3.7.4
12-3.1-Honeycomb: 3.7.4
13-3.2-Honeycomb: 3.7.4

Copy from Here .


text:
Q: Is it possible to find the origin of a request in nestjs? Is it possible to block the requests hitting my server(API) and allow it to serve requests only from my ReactNative mobile app? If so how can it be done!?
Thanks in advance.


text:
Q: SlideToggle multiple elements independently I need some help with SlideToggle.
HTML:

Superior Double Room

Prices are per room
20 % VAT Included in price

Non-refundable
Full English breakfast $ 24.80

            + more info

                Max:

                Price:
                $ 55

                Rooms:
                01

            Book

Stylish and individually designed room featuring a satellite TV, mini bar and a 24-hour room service menu.

Room Facilities: Safety Deposit Box, Air Conditioning, Desk, Ironing Facilities, Seating Area, Heating, Shower, Bath, Hairdryer, Toilet, Bathroom, Pay-per-view Channels, TV, Telephone

Bed Size(s): 1 Double

Room Size:  16 square metres

Superior Double Room

Prices are per room
20 % VAT Included in price

Non-refundable
Full English breakfast $ 24.80

            + more info

                Max:

                Price:
                $ 55

                Rooms:
                01

            Book

Stylish and individually designed room featuring a satellite TV, mini bar and a 24-hour room service menu.

Room Facilities: Safety Deposit Box, Air Conditioning, Desk, Ironing Facilities, Seating Area, Heating, Shower, Bath, Hairdryer, Toilet, Bathroom, Pay-per-view Channels, TV, Telephone

Bed Size(s): 1 Double

Room Size:  16 square metres

Jquery:
$(document).ready(function () {
$(".more-information").slideUp();
        $(".more-info").click(function() {
        var txt = $(".more-information").is(':visible') ? '+ more info' : ' - less info';
        $(".more-info").text(txt);
        $(".more-information").slideToggle("slow");
    });
});

By clicking in "more-info" link I need to open "more-information" div. Now it toggles all at once, how can I achieve to toggle each independently?
Thank you.

A: Here you go" Fiddle
JavaScript:
$(document).ready(function () {
$(".more-information").slideUp();
$(".more-info").click(function() {
    var moreinformation = $(this).closest("li").find(".more-information");
        var txt = moreinformation.is(':visible') ? '+ more info' : ' - less info';
        $(this).text(txt);
        moreinformation.slideToggle("slow");
    });
});

Because roXon requested:
moreinformation.stop(true, true).slideToggle("slow");

Will prevent bad things happening when clicking the link multiple times in quick succession.


text:
Q: Dynamically Change Y Axis Size Based on Slicer I have a spreadsheet that has information on credit card applications. In Power BI, I have created calculations to calculate the number of applications (COUNT), and other calculated measures that give me the number of applications based on different filters (CALCULATE).
I then created a slicer that slices the data based on type of card. So say I have a line chart that shows the number of applications for males and females, I can then use the slicer to select different cards.
The trouble I'm running into, is that some cards have a lot more applicants than another. This can be difficult for display, as I set certain Y Axis ranges for the data labels to be clear. So if I have one line chart that the minimum is 100 and max is 500 for one card, if I click on another card in the slicer, then the Y axis size is still 100 - 500, which isn't great if another card  in the slicer pane only has 50 applicants.
Does anyone know of a creative way to dynamically change the Y Axis sizes, based on a slicer selection?


text:
Q: What is a TNS:listener in the Context of Oracle? Borderline ServerFault question, but figured I'd try here first since I've had luck with Oracle questions in the past.
I'm trying to connect to an oracle database from PHP, and I'm getting the following error.
ORA-12505: TNS:listener does not currently know of SID given in connect descriptor

This is the error that PHP reports, and the error that shows up in Oracle's listener.log.
My immediate problem is fixing this error.  The larger question I'd like answered is how does Oracle connection model work?
This is in a development environment that's running on my local windows machine and has been working up until now.  Unfortunately, the environment was handed to me (I didn't set it up) and the people who did set it up are unavailable to help me debug it.
If I was getting a similar error with MySQL or PostgreSQL (two systems I'm more familiar with), I'd check to ensure that a database process was running, and then attempt to connect manually to the database using the username/password/connection string.  Unfortunately, I'm not familiar with the Oracle tools on windows (other than SQL Developer) and I don't know what a TNS:listener or SID are in the context of Oracle (I have vague ideas, but vague ideas rarely help when you're debugging something like this)
Any general advice would be appreciated.
Updates per Comments:
There's a number of entires in my tnsnames.ora file, the relevant entry being
OBS2 =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = steel-ae39650)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = OBS2)
    )
  )

This is not reflected in the list of instances when I run
    LSNRCTL> services

So I think my next question is, how do I attempt to manually start up the OBS2 instance?

A: A TNS name is like an alias to your service instance. The TNS listener service acts as a sort of lookup service for you in this regard. It will fail with that error message if the actual service you're trying to connect to via a TNS name isn't valid.
You can then test out to see if the TNS listener sees the service correctly using the command line tool:
%>lsnrctl services

Which should output something like the following:
Service "myservice" has 1 instance(s).
  Instance "myinstance", status READY, has 1 handler(s) for this service...
    Handler(s):
      "D000" established:0 refused:0 current:0 max:1002 state:ready
         DISPATCHER <machine: LOCALHOST, pid: 12345>
         (ADDRESS=(PROTOCOL=tcp)(HOST=LOCALHOST)(PORT=6789))

Can you please post the relevant TNS entry (in the tnsnames.ora file)? It is located in ORAHOME\client or db\ADMIN\NETWORK. If you have both client and server, make sure both copies of the tnsnames.ora file have correct values, just to be safe.
Here's an example of a proper TNS name definition in tnsnames.ora called 'mydb':
myDbAlias =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 12345)(QUEUESIZE = 100))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = myservice)
    )
  )

A: Just wanted to add to this, as I recently had a similar connection issue that drove me nuts until I figured out what was happening.
First, the keywords SID and SERVICE_NAME are not exactly the same.  This was my first wrong assumption.  In many environments you can interchange SID and SERVICE_NAME, but not always, it depends.
That said, your error gives away the problem: you're specifying SID in a connection string instead of the SERVICE_NAME that tnsnames successfully uses.
So, if you are specifying the connect string in your code, try using SERVICE_NAME keyword in the connect string (*or, if you've already using SERVICE_NAME and cannot connect, try using SID keyword*).
Overly simplistic answer I know, but easy to try and may save someone some headaches.
Hope that helps.

A: Mike Atlas' answer is fairly comprehensive, but note that you can connect to 10g (or later) DBs which don't have a published tnsname using [//]host_name[:port][/service_name]
HTH
C.


text:
Q: PHP elseif not working.(Compare operators with integers) function ageIssue($age){
    if ($age > 10) {
        echo "Age is greater than 10";
    } elseif ($age>20) {
        echo "Age is greater than 20";
    } elseif($age>30) {
        echo "Age is greater than 30";
    }else {
        echo "Enter valid age";
    }
 }

 ageIssue(32);

What is the fault of this code? I need the answer "Age is greater than 30" but But always it says "Age is greater than 10". Help please....

A: Your code logic is wrong. If you want to handle with if else, you must do it like this:
function ageIssue($age){
    if ($age > 30 && $age < 40) {
        echo "Age is greater than 30";
    } elseif ($age>20) {
        echo "Age is greater than 20";
    } elseif($age>10) {
        echo "Age is greater than 10";
    }else {
        echo "Enter valid age";
    }
}

A: Your code executes up to the first true evaluation... break up your if statements to simplify your checks ... notice that I start with the least age.
Like below:

function ageIssue($age){

    $output = "Enter valid age";

    if ($age > 10) {
        $output = "Age is greater than 10";
    }

    if ($age > 20) {
        $output = "Age is greater than 20";
    }

    if($age > 30) {
        $output = "Age is greater than 30";
    }

    echo $output;

 }

 ageIssue(32);

A: You can start by testing value from largest to smallest if statements by

*

*Calling a returning method

function ageIssue($age){
    if ($age > 70) {
        return "Age is greater than 70";
    } if ($age>50) {
        return "Age is greater than 50 but less than 70";
    } if($age>30) {
        return "Age is greater than 30 but less than 50";
    }if($age>10){
        return "Age is greater than 10 but less than 30.";
    }
    if($age>=1){
      return "Age is between 1 and 10.";
    } else {
        return "Invalid Age enter";
    }
}

echo ageIssue(32);

A: You need to start from the largest as you check the age
    function ageIssue($age)
{
    if ($age > 70) {
        return "Age is greater than 70";
    } elseif ($age > 50) {
        return "Age is greater than 50 but less than 70";
    } elseif ($age > 30) {
        return "Age is greater than 30 but less than 50";
    } elseif ($age > 10) {
        return "Age is greater than 10 but less than 30.";
    } elseif ($age >= 1) {
        return "Age is between 1 and 10.";
    } else {
        return "Invalid Age enter";
    }
}

echo ageIssue(32);


text: Q: Import postgis layer from S3 link I have a postgis layer (layer.sql), which I am trying to add to my postgres database (mydatabase). The postgis layer is stored on S3 (https://s3.us.../layer.sql). I can add the layer to my database when it is stored on my local machine using psql mydatabase < ~/layer.sql but I'm failing to add the layer to my database, if I'm using the url. I tried psql mydatabase < https://s3.us.../layer.sql, which returns -bash: https://s3.us.../layer.sql: No such file or directory. Is there a different way command I can use when trying to add the layer with a url?


text:
Q: Stack at laravel query with relation I need your help.
I have this query but I am getting trouble
I have these two tables:
users
---------------------
 id | name | surname
---------------------

users_ratings
-------------------------------------
 id | user_id | customer_id | rating
-------------------------------------

Not every user has a rating.
I am trying to show on a view in Laravel every user and it's rating.
$users=User::where('role','=','4')->paginate(8);
$data = array();
foreach ($users as $user)
{
    $ratings = UserRating::where('user_id', $user->id)->get();
    $nr = UserRating::where('user_id',  $user->id)->count();
    $sum = 0;

        foreach ($ratings as $rate) {
            if ($rate->rating != "") {
                $rating = $rate->rating;
                $sum = $sum + $rating;

            }
        }

        if ($nr == 0) {
            $avg = 0;
        } else {
            $avg = ($sum / $nr);
        }

    }
    else {

        $avg=0;
    }
        $object = [
            'id' => $user->id,
            'rating' => number_format($avg, 3, '.', ','),
            'user'=>$user
        ];

        array_push($data, $object);

       return view('pages.users', ['data' => $data]);

Now I am showing in view:
@foreach($data as $d)
    {{$d->id}}
    {{$d->rating}]
    {{$d->user->name}}
@endforeach

I know that something is wrong here. It shows

"Trying to get property 'id' of non-object....

A: You should try this:
@foreach($data as $d)
{{$d['id']}}
{{$d['rating']}}

@endforeach

OR
@foreach($data as $key => $d)
    {{$d[$key]->id}}
    {{$d[$key]->rating}]
    {{$d[$key]->user->name}}
@endforeach

Updated Answer
@foreach($data as $key => $d)
  @foreach($d as $rsltDetails)
    {{$rsltDetails['id']}}
    {{$rsltDetails['rating']}}
  @endforeach
@endforeach

A: There are many things wrong here.
First, you have an n+1 query. You are fetching the users and inside the loop for each user, you are performing 2 additional queries.
$users = User::where('role','=','4')->paginate(8);

foreach ($users as $user) {
    $ratings = UserRating::where('user_id', $user->id)->get();
    $nr = UserRating::where('user_id',  $user->id)->count();
    $sum = 0;
    ...
}

Solution:
This code will execute only two queries.
// I am assuming the relation name between User and UserRating is ratings
$users = User::with('ratings')->where('role','=','4')->paginate(8);

return view('pages.users', compact('users));

In your view, you can easily print the values
@foreach($users as $user)
    {{ $user->id }}
    {{ number_format($user->ratings->avg('rating'), 3, '.', ',') }}
    {{ user->name }}
@endforeach

A: Doing it that way is not a scalable solution and you will face the N+1 problem.
I would suggest the following.
First, in your App\User model, define your relationship with App\UserRating:
use App\UserRating;

public function ratings()
{
    return $this->hasMany(UserRating::class);
}

Then, define your inverse relationship in App\UserRating
use App\User;

public function user()
{
    return $this->belongsTo(User::class);
}

Finally, you could simplify your loop like this:
$users = User::where('role','=','4')
    ->with('ratings') // eager-load ratings
    ->paginate(8);

$results = [];

foreach($users as $user) {
    // To access ratings you would do
    // foreach($user->ratings as $rating) { }

    // To get the count you would do
    // $user->ratings->count();
}

In your blade file, you could just do this:
@foreach($users as $user)
    {{ $user->id }}
    {{ number_format($user->ratings->avg('rating'), 3, '.', ',') }}
@endforeach

Doing it this way will solve your N+1 problem and leverages Laravel's Collections to make everything a little bit cleaner as well :)


text:
Q: Table-Valued Parameter as Output parameter for stored procedure Is it possibile to Table-Valued parameter be used as output param for stored procedure ?
Here is, what I want to do in code
/*First I create MY type */
CREATE TYPE typ_test AS TABLE
(
     id int not null
    ,name varchar(50) not null
    ,value varchar(50) not null
    PRIMARY KEY (id)
)
GO

--Now I want to create stored procedu whic is going to send output type I created,
--But it looks like it is inpossible, at least in SQL2008
create  PROCEDURE [dbo].sp_test
         @od datetime
        ,@do datetime
        ,@poruka varchar(Max) output
        ,@iznos money output
        ,@racun_stavke  dbo.typ_test   READONLY --Can I Change READONLY with OUTPUT ?
AS
BEGIN
    SET NOCOUNT ON;

    /*FILL MY OUTPUT PARAMS AS I LIKE */

    end

A: No, unfortunately table value parameters are read-only and input only. This topic in general is covered very well in How to Share Data between Stored Procedures, which presents all the alternatives. My recommendation would be to use a #temp table.

A: This is an older post, but it was near the top when I was searching for "Table-Valued Parameter as Output parameter for stored procedure".  While it is my understanding that you cannot pass a table-valued parameter as an output parameter, I would imagine the goal is to use that table-valued output parameter as a table-valued input parameter in another procedure.  I will show an example for how I made this work.
First, create some data to work with:
create table tbl1
(
id int,
fname varchar(10),
gender varchar(10)
);
create table tbl2
(
id int,
lname varchar(10)
);
insert into tbl1
values
(1,'bob'  ,'m'),
(2,'tom'  ,'m'),
(3,'sally','f')
;
insert into tbl2
values
(1,'jones'   ),
(2,'johnson' ),
(3,'smith'   )
;

Next, create a stored procedure to capture some of the data.  Normally, this would be where you are trying to create a table-valued output parameter.
create procedure usp_OUTPUT1
 @gender varchar(10)
as
Begin
    select id from tbl1 where gender = @gender
End

Additionally, you will want to create a data type (table type) where the data from the first stored procedure can be passed as the input parameter for the next stored procedure.
create type tblType as Table (id int)

Next, create the second stored procedure that will accept the table-valued parameter.
create procedure usp_OUTPUT2
@tblType tblType readonly  --referencing the type created and specify readonly
as
begin
 select lname from tbl2 where id in (select id from @tblType)
end

Granted, this is not a true table-valued output parameter, but it will likely produce results similar to what you would be looking for. Declare your table-valued parameter, fill it with data by executing the stored procedure into it, then use it as the input variable for the next procedure.
Declare @tblType tblType
insert into @tblType execute usp_OUTPUT1 'm'
execute usp_OUTPUT2 @tblType

A: in addition to the nicely put answer by remus including the link he provided
How to Share Data between Stored Procedures
there are situations where you get the following error messages when saving the results of a stored procedure to a table:
An INSERT EXEC statement cannot be nested.
The current transaction cannot be committed and cannot support operations that write to the log file. Roll back the transaction
and when this happens on my own stored procedures that I develop for my own use
for example a tool to tell me from a login all the AD groups it belongs to and all their permissions in all databases in a server
I create a temp table outside the procedure and pass its name as a parameter
--===============
-- this way below it works, by passing a temp table as a parameter
--===============

                if OBJECT_ID('tempdb.dbo.#my_table') IS NOT NULL
                   DROP TABLE #my_table

                CREATE TABLE #my_table(
                    db nvarchar(128)   COLLATE Latin1_General_CI_AS  NULL,
                   permission_type nvarchar(128)   COLLATE Latin1_General_CI_AS  NULL,
                    login_  nvarchar(128)   COLLATE Latin1_General_CI_AS  NULL,
                    role_  nvarchar(128)   COLLATE Latin1_General_CI_AS  NULL,
                    Obj    nvarchar(517)   COLLATE Latin1_General_CI_AS  NULL,
                    Permission nvarchar(128)   COLLATE Latin1_General_CI_AS  NULL,
                    script nvarchar(1008)  COLLATE Latin1_General_CI_AS  NULL
                )

                exec sp_GetLoginDBPermissionsX
                    @Login='my_loginname',
                    @debug=0,
                    @where_to_save ='#my_table'

                select *
                from #my_table

and inside the procedure, after all the calculations, when I am returning the final data (below an example)
I check whether we are outputting to a table or just back to the screen and create the script dynamically.
            select @sql = case when @where_to_save IS not null then
            '
            insert into ' + @where_to_save + '(db,Permission_Type,login_,role_,obj,Permission,script) '
            else '' end +
'
        SELECT
            J.db,
            J.Permission_Type,
            J.login_,
            J.role_,
            J.Obj,
            J.Permission,
            J.script
        FROM #tablewithpermissions J
        WHERE J.login_ IN ( SELECT  L1.LOGIN_FROM COLLATE Latin1_General_CI_AS FROM #logins L1)
           OR J.role_ IN  ( SELECT  L1.LOGIN_FROM COLLATE Latin1_General_CI_AS FROM #logins L1)
       ORDER BY J.DB, J.[permission_order]
'
        --print(@sql)

        EXEC(@SQL)

After that you have either the info you need on the screen, or if you have passed a temp table as a parameter, it will have the data now.
this is one solution I found, but I only use it for my own works DBA otherwise this will be considered high risk for Sql Injection.

A: A table could be converted to JSON (SQL Server 2016 or later) and passed as an nvarchar parameter out:
CREATE PROCEDURE test
  @json nvarchar(max) output
AS
BEGIN
  SET NOCOUNT ON;

  --Create table variable
  declare @t1 as table ([value] nvarchar(max), [ordinal] int);

  --Fill table
  INSERT INTO @t1 ([value], [ordinal])
  SELECT 'abc', 1 UNION
  SELECT 'def', 2;

  --Convert table to JSON
  set @json  = (SELECT * FROM @t1 FOR JSON PATH);
END

[{"value":"abc","ordinal":1},{"value":"def","ordinal":2}]
Then to convert it back to a table, specify the column names as JSON keys:
declare @json nvarchar(max);

exec test @json output;

--Convert JSON to table
SELECT * FROM OPENJSON(@json)
WITH ([value] nvarchar(max) '$.value', [ordinal] int '$.ordinal');


text:
Q: tkinter движение объекта за мышкой Пытаюсь сделать чтобы объект двигался в сторону мышки, но не выходил за границы, но что-то явно я не то написал.
from tkinter import *

def MouseMove(event):
    side = canvas.bbox(square)
    x1,y1,x2,y2 = side
    pos_x = x1 + (x2 - x1) / 2 + event.x
    pos_y = y1 + (y2 - y1) / 2 + event.y
    if 0 <= pos_x <= 50 and 0 <= pos_y <= 50:
        canvas.move(square,event.x,event.y)
    window.after(10,MouseMove)

window = Tk()
window.geometry('800x600')

canvas = Canvas(window, width=50, height=50)
square = canvas.create_rectangle(10,10,20,20, fill="red")
canvas.place(x=200, y=50)

window.bind('<Motion>', MouseMove)

window.mainloop()

мне нужно чтобы объект двигался (стремился в сторону курсора) в пределах canvas, но отслеживалось все за пределами canvas

A: У вас возникает ошибка, т.к. в строке window.after(10,MouseMove) вы не передаете обязательный аргумент event для функции MouseMove. Чтобы исправить это, добавьте аргумент: window.after(10, MouseMove, event).
Но вам тут в принципе не нужен after. Он нужен был бы, если бы движение вашей фигуры не зависело бы от движения мыши (если была бы просто анимация). В вашем случае из строки window.bind('<Motion>', MouseMove) следует, что при движении курсора функция MouseMove и так будет вызываться.
Чтобы фигура не выходила за пределы канваса, вы можете двигать её только при движении курсора внутри канваса, а не внутри всего окна window. Для этого привязывайте функцию к канвасу, а не к окну: canvas.bind('<Motion>', MouseMove)
move перемещает элемент на канвасе не к определенной координате, а на передаваемое расстояние x, y. Поэтому логику функцииMouseMove вам надо переписать.
Вот так может выглядеть ваш код:
from tkinter import *

def MouseMove(event):
    x1, y1, x2, y2 = canvas.bbox(square)
    canvas.move(square, event.x - x2, event.y - y2)

window = Tk()
window.geometry('800x600')

canvas = Canvas(window, width=500, height=500, bg='white')
square = canvas.create_rectangle(10, 10, 20, 20, fill="red")
canvas.place(x=200, y=50)
canvas.bind('<Motion>', MouseMove)

window.mainloop()


text:
Q: AWS STS assume role "unable to locate credentials" in docker container I am trying to fetch aws credentials using aws sts. The below code works fine in Pycharm, but when i run it in docker container i am getting "unable to locate credentials."
def assumed_role_session(role_arn):
    try:
        base_session = boto3.session.Session()._session.profile
        sts_client = boto3.client('sts').assume_role(RoleArn=role_arn, RoleSessionName=base_session)
        credentials = sts_client['Credentials']
        return credentials
    except Exception as e:
        return None

assumed_role_session('arn:aws:iam::{AWS_ACCOUNT_NUMBER}:role/{AWS_ROLE_NAME}')

A: When running the python app in docker container, the boto3 lib will try to fetch the credentials from the docker container env, not the local PC env. So, you will need to check if the credentials have been configured correctly via the Dockerfile / docker-compose yml file.
Besides, Boto3 will search for credentials in a particular order. (check https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html) Please make sure that the credential configuration you are going to use always has the 1st priority.


text:
Q: Get Window Service list over network I want to get all windows services that installed on other machine through network
I'm using C#.
This is my code
ServiceController[] svDetail = ServiceController.GetServices("192.168.1.2");

I have an Exception here. This is Exception message
Cannot open Service Control Manager on computer . This operation might require other privileges.

How can I get services over network?


text:
Q: R merge two dataframes with same columns without replacing values I have the following two columns:
e_2020_certified_Machines_Per_Jurisdiction_count_per_state:

And e_2016_certified_Machines_Per_Jurisdiction_count_per_state:

I would like to merge these two dataframes together so that it looks like this: (Sample data)

I have tried numerous things including:
1: Using the select function;
2: Merging the dataframes
3: Creating a new dataframe and inserting the data through the SQLDF package
I either get duplicated data, data that is overwritten or dataframes where 2020 gets replaced in its entirety by 2016 etc.
Help would be greatly appreciated. I've been at this for a few hours now.
I'm very sorry if this is a duplicate, I couldn't find a question similar to this on stackoverflow which actually solved the problem.
If I manage to find the answer in the meantime I'll make sure to post it as well.
Thank you very much and have a nice day!

A: Solution:
Thanks to @GregorThomas for providing the answer.
This problem was solved with the following command:
merge(data1, data2, all = TRUE)


text:
Q: How can I optimize images uploaded using Paperclip & Rails? Does anyone know how to optimize image size through paperclip?
In my Graphic model I have the following:
has_attached_file :graphic,
                    :styles => {
                      :home       => ['120x90',:jpg],
                      :thumb      => ['70x70',:jpg]
                    }

By optimize I mean, reduce the filesize of each of :home & :thumb graphics once paperclip creates them, Google's speed test tells me that I should be able to reduce these by 70 - 90%.
I think I can do this by creating a perclip processor, but not really sure where to start.
Kind of stumped on this one, any help / hints much appreciated!
(Rails 2.3)

A: There's a gem that allows you to do this easily with Paperclip:
https://github.com/janfoeh/paperclip-optimizer

A: And this gem to image compression processor for Paperclip:
https://github.com/emrekutlu/paperclip-compression

A: Check out the quality option. I've read that 75 is the best setting for balancing quality and the resulting size of the image.
has_attached_file :photo,
                :styles => {
                  :small => {
                    :geometry => '38x38#',
                    :quality => 40,
                    :format => 'JPG'
                  },
                  :medium => {
                    :geometry => '92x92#',
                    :quality => 50
                  }


text:
Q: how to get all possible combinations of words in an array? We are given N different types of stickers. Each sticker has a lowercase English word on it.
You would like to spell out the given target string by cutting individual letters from your collection of stickers and rearranging them.
You can use each sticker more than once if you want, and you have infinite quantities of each sticker.
What is the minimum number of stickers that you need to spell out the target? If the task is impossible, return -1.
Input:
["with", "example", "science"]"thehat"
Output:
3
Explanation:
We can use 2 "with" stickers, and 1 "example" sticker.
After cutting and rearrange the letters of those stickers, we can form the target "thehat".
Also, this is the minimum number of stickers necessary to form the target string.
this is my code....
class Solution {
public:
    int max(int a ,int b)
    {
        if(a>b){return a;}
        else return b;
    }
    int minStickers(vector<string>& stickers, string target)
    {
        int l=target.length();int c2=0;
        int count=0;int c1=0;
        string t1=target;
        string s;
        for(int i=0;i<stickers.size();i++)
        {
            c1=0;
            s=stickers[i];
            for(int j=0;j<s.length();j++)
            {
              count =0;
                for(int k=0;k<target.length();k++)
                {
                    if(s[j]==target[k]){count+=1;target.erase(k,1);k=-1;}
                    cout<<target<<" ";
                }
                if(count>0){c1=max(c1,count);}
            }
             cout<<c1<<" ";

            c2=c2+c1;
        }
        if(target.length()==0){return c2;}
        return -1;
    }
};

the first test case works,but this doesnt work...  ["these","guess","about","garden","him"]
  "atomher"
  My output: 4
  Expected: 3
I'm getting number of words but not the minimum number of words....can u help me out


text:
Q: Using Microsoft.Web.Administration from Powershell - it's connecting to my IISExpress instance instead of my main one? I'm trying to manage my IIS instance through PowerShell.
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Web.Administration") | Out-Null
            $Iis = [Microsoft.Web.Administration.ServerManager]::OpenRemote($WebServer)
            $IisApp = $Iis.sites[$SiteName].Applications["/$WebApplicationName"]
            if(-not $IisApp)
            {
                $IisApp = $Iis.sites[$SiteName].Applications.Add("/$WebApplicationName", $WebApplicationFolder)
            }

This fails because it finds the wrong IIS instance on the target machine sometimes.  How do I tell Microsoft.Web.Administration to use the real IIS and not IIS Express?
I've also tried fetching the latest Microsoft.Web.Administration through NuGet and it does no better. I've pulled down the assembly into a shared Nuget location (c:\nuget\packages\) and instead I load the assembly from there
add-type -Path "C:\nuget\packages\Microsoft.Web.Administration\lib\netstandard1.5\Microsoft.Web.Administration.dll"

and confirmed that ServerManager is coming from the correct assembly and it's no different.
I've uninstalled IIS Express from my machine and it works on my machine, but I can't uninstall IIS Express from every machine I wish to target.
How do I tell Microsoft.Web.Administration to focus on real IIS instead of IIS Express?
If IIS Express is installed, everything fails. If IIS Express is not installed, everything is fine.
Help?

A: Loading the Microsoft.Web.Administration from C:\Windows\System32\inetsrv fixed it.  Remote invocation using OpenRemote doesn't work, so I had to use Invoke-SqlCommand to administer on remote machine.


text:
Q: the specified module 'pswindowsupdate' was not loaded because no valid module file was found in any module directory Window updates are always saying checking for updates and process is running without any update install. Hence, I am trying to install window updates using the Windows PowerShell button. However, I have found the error below when I used the following command in Powershell:
Import-Module PSWindowsUpdate

the specified module 'pswindowsupdate' was not loaded because no valid
  module file was found in any module directory

Can anyone help ?

A: I had this same issue with the Security & Compliance PowerShell when I ran:
Import-Module ExchangeOnlineManagement

Looking into it further I discovered that you can use the "Find-Module" cmdlet to search and install it:
Find-Module -Name ExchangeOnlineManagement | Install-Module

In your situation you'll want to execute the following:
Find-Module -Name PSWindowsUpdate | Install-Module

Reference: https://learn.microsoft.com/en-us/powershell/module/powershellget/install-module?view=powershell-7.3#example-1-find-and-install-a-module

A: Yes,
I have downloaded the "PSWindowupdate.zip" from here. https://gallery.technet.microsoft.com/scriptcenter/2d191bcd-3308-4edd-9de2-88dff796b0bc to %USERPROFILE%\Documents\WindowsPowerShell\Modules which fixed the issue.


text:
Q: There are two MOTD's shown when I login to my server using SSH I wanted to change the MOTD that is shown when you login to a computer on a TTY, which seems to work, but somehow, it doesn't just show the MOTD in /etc/motd and /etc/update-motd.d/, but also another message.
This is shown when I login to my server:
sam@laptop:~$ ssh <user>@<server>
Welcome to Ubuntu 12.04.2 LTS (GNU/Linux 2.6.32-042stab068.8 i686)

 * Documentation:  https://help.ubuntu.com/
No mail.
Last login: Thu Feb 21 19:20:55 2013 from <ip>
Welcome to Ubuntu 12.04.2 LTS (GNU/Linux 2.6.32-042stab068.8 i686)

 * Documentation:  https://help.ubuntu.com/

<user>@<server>:~$

My update-motd.d contains two files, 00-header and 10-help-text.
00-header contains the following:
[ -r /etc/lsb-release ] && . /etc/lsb-release

if [ -z "$DISTRIB_DESCRIPTION" ] && [ -x /usr/bin/lsb_release ]; then
        # Fall back to using the very slow lsb_release utility
        DISTRIB_DESCRIPTION=$(lsb_release -s -d)
fi

printf "Welcome to %s (%s %s %s)\n" "$DISTRIB_DESCRIPTION" "$(uname -o)" "$(uname -r)"     "$(uname -m)"

And 10-help-text contains this:
[ -r /etc/lsb-release ] && . /etc/lsb-release

if [ -z "$DISTRIB_RELEASE" ] && [ -x /usr/bin/lsb_release ]; then
    # Fall back to using the very slow lsb_release utility
    DISTRIB_RELEASE=$(lsb_release -sr)
fi

URL="https://help.ubuntu.com/"
if uname -r | grep -qs "\-server"; then
    URL="https://help.ubuntu.com/$DISTRIB_RELEASE/serverguide/C"
fi

printf "\n * Documentation:  %s\n" "$URL"

This would make up for the portion of the MOTD up until No mail.. But where is the rest coming from?

A: The MOTD can either be printed by sshd, or by PAM. It's possible that both are doing it.
Check your /etc/ssh/sshd_config for the following:
PrintMotd yes

If that line isn't present it may be defaulting to yes (although Debian/Ubuntu change the default to no).
Check your PAM configuration in /etc/pam.d/ for the following:
session    optional     pam_motd.so

Try disabling these one at a time to see what changes.

A: If you are using Ubuntu, you might try to:
sudo nano /etc/ssh/sshd_config

and check to see of PrintMotd and UsePam are both set to true, that was the case for me.
Note: Following the above, you can do sudo service ssh restart and you should see just one Motd on login.

A: After testing on Debian 8:
It is this option in /etc/pam.d/login prints another motd
session    optional   pam_exec.so type=open_session stdout /bin/uname -snrvm

A: On Ubuntu 22.04 server, I had this happen by installing the update-motd package. Uninstalling it did not help.
It seems the pam at-login-time dynamic functionality creates /run/motd.dynamic and update-motd creates /run/motd, and then both gets printed at ssh login.
The solution for me was to uninstall update-motd and remove /run/motd:
sudo apt remove --purge update-motd
sudo rm -f /run/motd


text:
Q: d3 text elements not rendering inside circle I'm trying to add texts to svg circles.  I've read other posts about using the grouping "g" tag, and I've tried that, but my text still isn't rendering.  I see the text element exists in the console though.
Here's the relevant code:
 var node = svg
    .selectAll(".node")
    .data(data.nodes)
    .enter()
    .append("g")
    .attr("class", "node")
    .call(
      d3
        .drag()
        .on("start", dragstarted)
        .on("drag", dragged)
        .on("end", dragended)
    );
  node
    .append("circle")
    .attr("r", (d) => {
      return d.type === "application" ? 50 : 20;
    })
    .attr("fill", (d) => {
      return d.type === "application" ? "red" : "blue";
    });

  node
    .append("text")
    .attr("dx", 12)
    .attr("dy", ".35em")
    .text(function (d) {
      return d.name;
    });

  force.on("tick", function () {
    link
      .attr("x1", function (d) {
        return d.source.x;
      })
      .attr("y1", function (d) {
        return d.source.y;
      })
      .attr("x2", function (d) {
        return d.target.x;
      })
      .attr("y2", function (d) {
        return d.target.y;
      });
    node.attr("transform", function (d) {
      return "translate(" + d.x + "," + d.y + ")";
    });
  });

  function dragstarted(d) {
    if (!d3.event.active) force.alphaTarget(0.3).restart();
    d.fx = d.x;
    d.fy = d.y;
  }

  function dragged(d) {
    d.fx = d3.event.x;
    d.fy = d3.event.y;
  }

  function dragended(d) {
    if (!d3.event.active) force.alphaTarget(0);
    d.fx = null;
    d.fy = null;
  }

Added correct code based on accepted answer.
Why is this still not rendering?

A: One way you can solve this is to bind your data to the group elements first and then append circles and text individually. So your code becomes:
var node = svg
  .selectAll("g")
  .data(data.nodes)
  .enter().append("g")
  .attr("class", "nodes");

node
  .append("circle")
// all circle-related code

node
  .append("text")
// all text related code, including x and y

Only two (AFAIK) svg elements allow other elements to be nested within them: g and text. When you call append on the selection of circles, you're appending a text element as a child of circle - which it doesn't support.


text:
Q: Class derived from shape I a wpf I want to create a class which derives from Rectangle class in order to override the onRender method. However the class is sealed so I tried to implement the inheritance using the Shape class. This is attainable but it does not contain the properties RadiusX and RadiusY. What can be done to have all the properties of the Rectangle class? How should be then the constructor written including the properties Fill, Width, Height, RadiusX, RadiusY?
Is there any other way to override the method onRender without creating a new class?


text:
Q: customizing x and y axis in corrplot I am interested in modifying a correlation table I made with corrplot.

I would like to modify it so all the numeric categories are on the X-axis and the letters are on the y-axis. Is there anyway to tell it which categories I want on each axis? Below is my R code.
library(corrplot)
blinded <- read_excel("corralation.xlsx", sheet = "blinded")
corr <- cor(blinded, method = "pearson")

cor.mtest <- function(mat, ...) {
  mat <- as.matrix(mat)
  n <- ncol(mat)
  p.mat<- matrix(NA, n, n)
  diag(p.mat) <- 0
  for (i in 1:(n - 1)) {
    for (j in (i + 1):n) {
      tmp <- cor.test(mat[, i], mat[, j], ...)
      p.mat[i, j] <- p.mat[j, i] <- tmp$p.value
    }
  }
  colnames(p.mat) <- rownames(p.mat) <- colnames(mat)
  p.mat
}

p.mat <- cor.mtest(corr)
head(p.mat[, 1:5])

col <- colorRampPalette(c("#EFFF00", "#228B22"))
corrplot(corr, method="color", col=col(200),
         type="upper", order="hclust",
         addCoef.col = "black",
         tl.col="black", tl.srt=45,
         p.mat = p.mat, sig.level = 0.01, insig = "blank",
         diag=FALSE)


text:
Q: Rotation to a given direction in opengl I'm starting to confuse math.
I want to make a rotation that translates the direction of the y axis to a given direction.
So I want to make a function that has a direction for input, and makes a call to glRotatef(). After the function anything I draw should point to the given direction instead of upwards.
glRotatef has 4 parameters: angle, x, y, z

A: Basically, you want to align the world y axis with a (unit-length) direction d.  In order to compose a rotation matrix with glRotatef, you need an axis a = [a_x, a_y, a_z] and an angle omega.
The rotation axis that takes y into d is perpendicular to both y and d, thus can be computed via the vector cross product:
a = cross(y, d);

the angle of rotation omega is simply the angle between the vectors y and d, thus can be computed from the dot product:
omega = acos(dot(y, d));

Now you can build your rotation matrix with:
glRotatef(omega, a_x, a_y, a_z);

Be careful that omega needs to be in degrees and not radians.  Also check the direction of rotation.