text:
Q: How do I manage an unmanaged Eclipse formatting profile? Our project has an "Unmanaged profile" and save-time autoformatting. I'd like to be able to modify the settings for this unmanaged profile and be able to check them back in to version control.
Eclipse's help documents are quite unhelpful ("You are not allowed to change such a profile, only the creator (manager) of the profile can change it.").

A: I'm not sure if this will allow you to check your profile back in to version control, but the following process will allow you to edit your profile on any computer that has the source checked out.
To edit your profile, you have to recreate the profile in Eclipse, which you can easily do as follows:

*

*Create a new profile by clicking "New..."

*Give the new profile the same name as your existing unmanaged profile.

*Before clicking OK, make sure you selected your unmanaged profile in "Initialize settings with the following profile" drop down list.

This will let you recreate the profile, and allow you to modify it in Eclipse, as normal.
Note: This process works with Eclipse Indigo

A: The problem is that a managed profile is actually stored in your workspace not your project.  Settings are pushed into your project when you make project specific changes such as selecting a different profile.  But the settings in the project are a different format to those in in the profile (in the workspace).
At present eclipse does not have the ability to perform this in reverse. That is it can't take settings from your project folder to create a profile in the workspace. Effectively an "Unmanaged Profile" is a profile to which you have lost the source code.
The simplest way I've found to reverse-engineer the profile is to generate an XML profile file that can be imported (under the formatter settings --> import button).
To reverse-engineer the the settings from a project; I wrote the following program. It reads the settings from a project folder and writes them out as an XML file:
import java.io.*;

public class ExtractFormatter {

    public static void main( String args[] ) throws IOException {
        if (args.length < 2)
            throw new RuntimeException("No arguements specified; expected <project folder> <output file>");

        File inFile = new File(args[0]);
        File outFile = new File(args[1]);

        BufferedReader reader = new BufferedReader(new FileReader(new File(inFile,
                ".settings/org.eclipse.jdt.core.prefs")));
        PrintWriter writer = new PrintWriter(outFile);
        writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>");

        // Retain the date from the file as a comment
        String line = reader.readLine();
        writer.println("<!-- Exported from " + inFile + " -->");
        writer.println("<!-- " + line + " -->");

        writer.println("<profiles version=\"12\">");
        writer.println("<profile kind=\"CodeFormatterProfile\" name=\"" + inFile.getName()
                + "\" version=\"12\">\")");

        // Now read every setting for the formatter and write it out as an XML tag.
        for (line = reader.readLine(); line != null; line = reader.readLine()) {
            if (line.startsWith("org.eclipse.jdt.core.formatter.")) {
                String[] parts = line.split("=", 2);
                writer.println("<setting id=\"" + parts[0] + "\" value=\"" + parts[1] + "\" />");
            }
        }

        writer.println("</profile>");
        writer.println("</profiles>");

        reader.close();
        writer.close();
    }
}

A: Eclipse should put a .settings folder in your project dir when you have an unmanaged profile. The only way I've found to change the settings so far is to go into the .settings folder within the project and hand edit the .prefs files in there.


text:
Q: Getting lift sources from maven repository I'm trying to learn how to use lift. I can create project skeleton by running maven commands (I had zero maven experience before) from Starting with Lift. It successfully downloads needed dependencies and everything works fine, however it does not download sources - I'd like to see how lift works from inside.
Looks like it downloads dependencies from here and there are compiled .jar files as well as sources - there are lift-mapper-1.0.jar and lift-mapper-1.0-sources.jar, but only lift-mapper-1.0.jar is downloaded to my local repository. I could download sources manually, but there are more than just few folders there. So, is there a way to tell it to Maven to download dependencies with sources?

A: The maven-dependency-plugin has a sources goal that will obtain the sources for all dependencies that are available. Simply run mvn dependency:sources to obtain the sources.
If you are using Eclipse, the m2eclipse plugin handles source resolution and attachment for you. You can set it to automatically obtain sources in the Maven preferences. Window > Preferences...->Maven, then enable Download Artifact Sources.
You can also manually invoke "Download Sources" action from the Maven popup menu on any jars (including those that are not managed with Maven). Then plugin will use Maven repository indexes to lookup the corresponding Maven artifact and download its sources.

redpajama_set_name: RedPajamaStackExchange


text:
Q: React.CSSProperties shows parsing error when used to insert css variables into App I am trying to use these variables in my scss file so that I can change my theme in the future directly from here. But it shows me parsing error, which was not there in the previous projects.
This is a React CRA project with typescript.
//App.tsx
import React from "react";
import "./App.scss";

const lightTheme = {
    "--primary": "#27AE60",
    "--text-primary": "#000000",
    "--background-primary": "#ffffff",
    "--background-secindary": "#fafafa",
} as React.CSSProperties;

const App = () => {
    return

;
};

export default App;

I can now use them as -
//App.scss
body {
color: var(--primary);
}

My package.json file -
{
    "name": "management-portal",
    "version": "0.1.0",
    "private": true,
    "dependencies": {
        "@testing-library/jest-dom": "^5.11.4",
        "@testing-library/react": "^11.1.0",
        "@testing-library/user-event": "^12.1.10",
        "@types/jest": "^26.0.15",
        "@types/node": "^12.0.0",
        "@types/react": "^16.9.53",
        "@types/react-dom": "^16.9.8",
        "react": "^17.0.1",
        "react-dom": "^17.0.1",
        "react-router-dom": "^5.2.0",
        "react-scripts": "4.0.1",
        "sass": "^1.32.5",
        "typescript": "^4.0.3",
        "web-vitals": "^0.2.4"
    },
    "scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "test": "react-scripts test",
        "eject": "react-scripts eject"
    },
    "browserslist": {
        "production": [
            ">0.2%",
            "not dead",
            "not op_mini all"
        ],
        "development": [
            "last 1 chrome version",
            "last 1 firefox version",
            "last 1 safari version"
        ]
    }
}

But it is throwing me this error ...
  Line 9:3:  Parsing error: Unexpected token, expected ";"

   7 |  "--background-primary": "#ffffff",
   8 |  "--background-secindary": "#fafafa",
>  9 | } as React.CSSProperties;
     |   ^
  10 |
  11 | const App = () => {
  12 |  return

;

Although I expect the following result -
Expected result in browser
I have got a workaround for the error, which works fine. But I am not able to find my mistake in my earlier code. Here it is -
import React from "react";
import "./App.scss";

const lightTheme: any = {
    "--primary": "#27AE60",
    "--text-primary": "#000000",
    "--background-primary": "#ffffff",
    "--background-secindary": "#fafafa",
};

const App = () => {
    return

;
};

export default App;

A: I successfully cloned your repo and found out what was the cause of the above error.
You are missing eslintConfig property in package.json:
{
  "name": "management-portal",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "@types/jest": "^26.0.15",
    "@types/node": "^12.0.0",
    "@types/react": "^16.9.53",
    "@types/react-dom": "^16.9.8",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.1",
    "sass": "^1.32.5",
    "typescript": "^4.0.3",
    "web-vitals": "^0.2.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": { <----- This one
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Potentially you will need to add this yarn add -D eslint-config-react-app
It's a small fix, but this property is generated by CRA cli. Not sure why you are missing it since you used that command (Maybe your app was ejected or you are adding Typescript to your app ad hoc).


text:
Q: beginner needs help with sql and php Im making a simple forum for my site but im having some problems
it wont print the posts. and i get no error very weird. It prints the thread title.
$id = isset($_GET['t']) ? intval($_GET['t']) : 0;
$query = "SELECT * FROM threads t INNER JOIN posts p ON p.tid = t.id WHERE t.id = $id";
$result = mysql_query($query);

// see if thread exists
if (!mysql_num_rows($result)) {
    echo "The requested thread does not exist.";
    return false;
}

// Fetch the rows
$row = mysql_fetch_assoc($result);

// Print title
echo '
'.htmlspecialchars($row['title']).'
';
// Print posts
while ($row2 = mysql_fetch_assoc($result)) {
    echo $row2['message'];
}

The Tables:
CREATE TABLE IF NOT EXISTS `threads` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
)

INSERT INTO `threads` (`id`, `title`) VALUES
(1, 'My first thread!');

CREATE TABLE IF NOT EXISTS `posts` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`tid` int(10) unsigned NOT NULL DEFAULT '0',
`message` text NOT NULL,
PRIMARY KEY (`id`)
)

INSERT INTO `posts` (`id`, `tid`, `message`) VALUES
(1, 1, 'This is my first post in my first thread :)');

A: Check if your queries and db connections succeed. You're not doing that, so right now if the query fails, it'll do so silently and you're stuck in the dark:
$result = mysql_query($query) or die(mysql_error());

Something like that during development will save you a ton of hair and time.

A: the first message is in $row try this
// Fetch the rows
$row = mysql_fetch_assoc($result);

// Print title
echo '
'.htmlspecialchars($row['title']).'
';
echo $row['message'];
// Print posts
while ($row2 = mysql_fetch_assoc($result)) {
    if($row['title'] == $row2['title'])
        echo $row2['message'];
    else
        //start a new title

A: You probably want something like this:
$query = "SELECT * FROM threads t INNER JOIN posts p ON p.tid = t.id WHERE t.id = $id ORDER BY `tid` ASC";
$result = mysql_query($query);

if (!mysql_num_rows($result)) {
    echo "The requested thread does not exist.";
    return false;
}

$lastTID = null;
while ($row = mysql_fetch_assoc($result)) {
    if ($lastTID != $row['tid']) {
        echo '
'.htmlspecialchars($row['title']).'
';
        $lastTID = $row['tid'];
    }

    echo $row['message'];
}

Note the ORDER BY clause and the $lastTID bit.


text:
Q: MouseOver issue with ComboBox Item image in WPF I have a ComboBox item including an image and text. When I'm running my application the image  disappears in a MouseOver case as shown in the figure on the link below:
http://postimg.org/image/wcdfgwp7t/f4518372/
I have added the image on the background property for the ComboBox item. I want the Item to display my image in this case, how do I handle this ?.
My XAML code:
<ComboBox x:Name="comboBox1"  HorizontalAlignment="Left" Margin="66,150,0,0" VerticalAlignment="Top" Width="84" Text="Valg Enhed">
        <ComboBoxItem Content="Stk" FontSize="16" RenderTransformOrigin="0.5,0.5">
            <ComboBoxItem.Background>
                <ImageBrush ImageSource="apple_green.png" Stretch="Uniform">
                    <ImageBrush.RelativeTransform>
                        <TransformGroup>
                            <ScaleTransform CenterY="0.5" CenterX="0.65" ScaleY="1" ScaleX="-1"/>
                            <SkewTransform AngleY="0" AngleX="0" CenterY="0.5" CenterX="0.65"/>
                            <RotateTransform Angle="0" CenterY="0.5" CenterX="0.65"/>
                            <TranslateTransform/>
                        </TransformGroup>
                    </ImageBrush.RelativeTransform>
                </ImageBrush>
            </ComboBoxItem.Background>
        </ComboBoxItem>
    </ComboBox>

Thanks in advance

A: Actually you are setting the ComboboxItem's background with an RelativeTransform , that is causing the problem here.
You could simply do this,
  <ComboBox x:Name="comboBox1"  HorizontalAlignment="Left" Margin="66,150,0,0" VerticalAlignment="Top" Width="84" Text="Valg Enhed">
            <ComboBoxItem Name="Stk">
                <StackPanel Orientation="Horizontal">
                    <Label Content="Stk " Width="50"/>
                    <Image Source="apple_green.png" Width="16" Height="14"  />
                </StackPanel>
            </ComboBoxItem>
        </ComboBox>

With binding:
XAML:
<ComboBox Name="cmb1" SelectedValue="{Binding comboItem}"
      ItemsSource="{Binding Comboboxitems}" Margin="176,216,0,181" SelectionChanged="cmb1_SelectionChanged">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Height="20" Text="{Binding Label}" Width="100" />
                    <Image Height="20" Source="{Binding Image}" Width="100" Stretch="Fill" />
                </StackPanel>
            </DataTemplate>
        </ComboBox.ItemTemplate>
 </ComboBox>

Model:
 public class comboItem
    {
        public ImageSource Image { get; set; }
        public string Label { get; set; }

        public comboItem(ImageSource image, string label)
        {
            Image = image;
            Label = label;

        }
    }

ViewModel:
 public class ViewModel : INotifyPropertyChanged
    {
        public ViewModel()
        {
            List<comboItem> list = new List<comboItem>();
            list.Add(new comboItem(new BitmapImage(new Uri("/WpfApplication1;component/Images/FT-C2HB.JPEG", UriKind.Relative)), "Stk"));
            list.Add(new comboItem(new BitmapImage(new Uri("//WpfApplication1//Images//FT-C2HB.JPEG", UriKind.Relative)), "abc"));
            _comboboxitems = new CollectionView(list);
        }
        private readonly CollectionView _comboboxitems;
        private comboItem _comboitem;

        public CollectionView Comboboxitems
        {
            get { return _comboboxitems; }
        }

        public comboItem Comboitem
        {
            get { return _comboitem; }
            set
            {
                if (_comboitem == value) return;
                _comboitem = value;
                OnPropertyChanged("Comboitem");
            }
        }
        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        public event PropertyChangedEventHandler PropertyChanged;
    }

Mainpage.cs:
public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new ViewModel();
        }


text:
Q: Same traces implies equivalent representation. Let $D_{12}=\left<a,b:a^6=b^2=1, b^{-1}ab=a^{-1}\right>$
$, A= \begin{pmatrix}e^{i\pi/3}& 0 \\ 0 & e^{-i\pi/3} \end{pmatrix}, $ $B=\begin{pmatrix}0& 1\\ 1 & 0 \end{pmatrix},$ $C=\begin{pmatrix}\frac{1}{2}& \frac{\sqrt 3}{2} \\ \frac{-\sqrt 3}{2} & \frac{1}{2} \end{pmatrix}$ and $D=\begin{pmatrix}1& 0 \\ 0 & -1 \end{pmatrix}.$
Prove that the following representations $\rho_k:D_{12} \to GL(2,\mathbb{C}) \ (k=1,2)$ given by:
$\rho_1 :a^rb^s\to A^rB^s , \  \rho_2:a^rb^s\to C^rD^s$
are equivalent.
Attempt: I manage to find $T$ that diagonalises $C$ and it turns out (coincidentally?) that $T^{-1}CT=A$ and $T^{-1}DT=B.$
I read that it suffices to check the representations have the same traces on all elements. Could someone explain to me why it is so? Thank you.


text:
Q: How to turn off NVIDIA 1060 card when it is not needed? I have a Lenovo Legion Y720 laptop with an Intel CPU plus an NVIDIA GTX 1060 6G. I know it is possible to have the NVIDIA turned off (unpowered) when not gaming, to save battery life, and to have it turned on automatically when gaming and other uses when graphical performance is needed.
Currently my NVIDIA is always turned on. If I click the little arrow in the tray of the task bar and hover over NVIDIA Activity icon, it is partially green and says 1 display, 0 programs.
I have a friend who has a laptop with a similar Intel + NVIDIA configuration, and that icon is grey on his PC; hovering over it shows Inactive. When he starts Minecraft, it turns green and active.
I've tried searching the web, but can't find a solution; most of what I find are people trying to force the NVIDIA graphics to run all the time, which is opposite of what I want.
So how do I ensure that Intel's graphics display adapter is used when it is adequate, and that NVIDIA is powered off and not consuming energy except when needed?

A: There is an option in Nvidia Control Panel to control which applications run on which graphics card.  To access these settings right click on your desktop and select Nvidia Control Panel.  On the left side of the under 3D settings, select Manage 3D settings.
Here you can either change your global settings and set your preferred graphics processor to the on board graphics chip or your Nvidia Card or you can go to program settings and change the settings on a per-program basis.
I'm not currently on my PC with two graphics cards to check through the process, but I use this method to ensure I am only using my Nvidia card for gaming applications.
Check out this post on TechAdvisor for reference.
Hope this helps!


text:
Q: MySQL CASE WHEN numb IS NULL ignore record WHERE numb IS NOT NULL I have these data in a table:
numb    m   value
8070    1   7.63
NULL    1   7.64
NULL    1   7.65
8070    2   7.939
8070    2   7.935
8070    2   7.941
NULL    3   7.62
8070    4   7.92
8070    4   7.935

I need MIN(value) and MAX(value) for each m, and if there is a value without numb (NULL), then the ones with a numb should be ignored.
So I should be getting the following results:
numb    m   value
NULL    1   7.64
NULL    1   7.65
8070    2   7.935
8070    2   7.941
NULL    3   7.62
8070    4   7.92
8070    4   7.935

I've tried quite a lot of different things, but nothing seems to work, and I have no more ideas how to find relevant info. Can you please point me to the right direction?
UPDATE:
to get the number of values it looks like this:
COALESCE(
IF(
  COUNT(
    CASE
      WHEN m IN (2, 4)
      THEN value
      ELSE
      CASE
        WHEN m IN (1, 3) AND numb IS NULL
        THEN value
      END
    END
  ) = 0,
  NULL,
  COUNT(
    CASE
      WHEN m IN (2, 4)
      THEN value
      ELSE
      CASE
        WHEN m IN (1, 3) AND numb IS NULL
        THEN value
      END
    END
  )
),
COUNT(
  CASE
    WHEN m IN (1, 3)
    AND numb IS NOT NULL
    THEN value
  END
)
) AS cnt

A: This query should give you the results you want. It has two levels of nested derived tables. The first:
SELECT m,
       MIN(CASE WHEN numb IS NULL THEN value END) AS min_null,
       MAX(CASE WHEN numb IS NULL THEN value END) AS max_null,
       MIN(CASE WHEN numb IS NOT NULL THEN value END) AS min_normal,
       MAX(CASE WHEN numb IS NOT NULL THEN value END) AS max_normal
FROM numbers
GROUP BY m;

computes the minimum and maximum values for each value of m, dependent on whether numb was a number or NULL. In the next level,
SELECT m,
       COALESCE(min_null, min_normal) AS min_value,
       COALESCE(max_null, max_normal) AS max_value
FROM (... query 1...)

we use compute the appropriate minimum and maximum values to use (if there was a NULL value, we use that, otherwise we use the one associated with numeric values of numb). Finally we JOIN the numbers table to the result of query 2 to find the appropriate values of numb for each value of m:
SELECT n.numb, n.m, n.value
FROM numbers n
JOIN (... query 2 ...) num ON num.m = n.m AND (num.min_value = n.value OR num.max_value = n.value)
ORDER BY n.m, n.value

Output:
numb    m   value
null    1   7.64
null    1   7.65
8070    2   7.935
8070    2   7.941
null    3   7.62
8070    4   7.92
8070    4   7.935

Demo on dbfiddle
The full query:
SELECT n.numb, n.m, n.value
FROM numbers n
JOIN (SELECT m,
             COALESCE(min_null, min_normal) AS min_value,
             COALESCE(max_null, max_normal) AS max_value
      FROM (SELECT m,
                   MIN(CASE WHEN numb IS NULL THEN value END) AS min_null,
                   MAX(CASE WHEN numb IS NULL THEN value END) AS max_null,
                   MIN(CASE WHEN numb IS NOT NULL THEN value END) AS min_normal,
                   MAX(CASE WHEN numb IS NOT NULL THEN value END) AS max_normal
            FROM numbers
            GROUP BY m) n) num ON num.m = n.m AND (num.min_value = n.value OR num.max_value = n.value)
ORDER BY n.m, n.value


text:
Q: Could Gambit rescue Rogue from Toad without injuring her? If Rogue (Before gaining Ms. Marvel's powers) was slimed by Toad, and Gambit found her with the slime hardened to her face, would he be able to use his powers to charge the slime with kinetic energy and break it without causing Rogue harm?

A: As Marvel Universe explains, Rogue's near-invulnerability is a power she gained from Ms. Marvel.

After permanently absorbing the powers of Ms. Marvel, Rogue possessed an amalgamated mutant human/alien Kree physiology that granted her a degree of immunity to poisons, and a virtually indestructible body.

As such, without Ms. Marvel's powers, an explosion to her face would harm her (assuming she has not temporarily absorbed anyone else's defensive or healing powers).

A: Yes, as long as Gambit was smart about it. For example, if he made skin contact with her FIRST (hands, neck, etc.), he would transfer his immunity to his own powers. However, no skin contact, no more Rogue.


text:
Q: Better way to check element between getPageSource and webelement - selenium java At first I used driver.findElement(By.xpath("//div[@class='xxx']")) to find but I think it's too slow.
I think I'll use getPageSource after that use indexOf() to search from the text.
Which one is better?

A: *

*I do not know why you think driver.findElement(By.xpath("//div[@class='xxx']")) is too slow. In my opinion, it is fast enough and I think findElement is better.

*If you apply Page Object Model or Screen Play, you must find element by the way driver.findElement(By.xpath("//div[@class='xxx']")) do.

*Page Object Model tutorial: https://www.guru99.com/page-object-model-pom-page-factory-in-selenium-ultimate-guide.html

A: I think you should use driver.findElement(By.xpath("//div[@class='xxx']")) and its faster as well. You can use chropath tool to find the web elements on web page .You can find this tool in extensions of chrome browser.


text:
Q: How to retrieve id sent from a link_to in rails I am trying to to edit a form through a reveal-modal. So i have multiple posts.
When I click the link 'Edit' it will reveal a div and display a form inside that is repopulated with the information. However, I don't know how to pass the post id into the form it will know which post to edit.
If i try to render the partial form I get this error:

undefined method `model_name' for Post::ActiveRecord_Relation:Class

All my information are on a controller view that is called Dashboard

controllers/dashboards_controller.rb
class DashboardsController < ApplicationController

def index
    @profile = Profile.find(current_user)
    @profileAll = Profile.all
    @post = Post.all
end

def show

end

def edit
    @profile =Profile.find(current_user)
    @post = @profile.post.find(params[:id])
end

end

controllers/posts_controller.rb
class PostsController < ApplicationController

def create
    @profile = Profile.find(current_user)
    @post = @profile.post.create(post_params)
    redirect_to dashboards_path(current_user)
end

def destroy
    @post =Profile.find(params[:profile_id])
    @post = profile.post.find(params[:id])
    @post.destroy
    redirect_to dashboards_path(current_user)

end

def show
    @profile =Profile.find(current_user)
    @post = @profile.post.find(params[:id])
end

def edit
    @profile =Profile.find(current_user)
    @post = @profile.post.find(params[:id])
end

def update
    @post = profile.post.find(params[:id])

    if @post.update(post_params)
        redirect_to dashboards_path(current_user)
    else
        render 'edit'
    end
end

private
    def post_params
        params.require(:post).permit(:title, :content)
    end
end

posts/_form2.html.erb
<%= form_for @post do |f| %>
<% if @post.errors.any? %>

<%= pluralize(@post.errors.count, "error") %> prohibited
  this post from being saved:

<% @post.errors.full_messages.each do |msg| %>

<%= msg %>

<% end %>

<% end %>

<%= f.label :title %>

<%= f.text_field :title %>

 <%= f.label :content %>

 <%= f.text_area :content %>

<%= f.submit %>

<% end %>

routes.rb
Rails.application.routes.draw do

get 'homepages/index'
 resources 'dashboards' do
  resources 'posts'
end
#get 'users/sign_in'
resources 'profiles' do
 resources 'posts'
end

devise_for :users, :controller => {:registrations => "users/registrations"}

devise_scope :user do
 root :to => 'devise/sessions#new'
end
end

Dashboards/index.html.erb
 <% @post.each do |post| %>

 <%= @profileAll.find(post.profile_id).name  %>

<%= post.title %>

<%= post.content %>

 <%# link_to "Edit",  edit_dashboard_post_path(current_user,[post.profile, post]) %>
 <%= link_to "Edit", {id: @post},'data-reveal-id' => 'edit-post' %>

 <% end %>

   <%= render 'posts/form2'  %>

  ×

A: Well, it simply does not work that way. First, you have in your controller @post = Post.all and within your _form2.html.erb you want to render form for a collection. That should be:
# index.html.erb

   <%= render :partial => 'posts/form2', collection: @posts  %>

  ×

#dashboard controller:
def index
    #...
    @posts = Post.all
end

_form2.html.erb:
Every @post object instance has to be replaced with form2. Read more here: http://api.rubyonrails.org/classes/ActionView/PartialRenderer.html about rendering a collection.
However, consider a case when you have hundreds of posts. Then, for each post, a partial is rendered. That would be very inefficient so instead, consider an asynchronous request which will load only one post the user requested.


text:
Q: Why does child div overflow its parent div? I've stared at this for some time now and to no avail can I come up with a solution that keeps the liquidy of the website.
What I am trying to accomplish for the #right-content to fill all available space height wise inside of its parent which is the #bottom-container. so it maintains its liquidy.
But giving it a min-height:100% makes it overflow the parent.
Live example can be found at the following link
Live Example
a static example of what im trying to acomplish.
Static Example

A: try the following css on #mCSB_1,
#mCSB_1
{
    position: relative;
    height: 500px;
    max-width: 100%;
    overflow: hidden;
}

A: You need to set a float on #left-content. Add this to your css:
#left-content {
float:left;
width:700px;
}

and remove inline-block from the #right content:
#right-content {
margin-left:750px;
display:block
min-width:250px;
}

This will maintain a liquid format to the right-container.

A: Your CSS is a main problem
Following CSS is from the URL what your want to achieve
#right-content {
display: inline-block;
width: 38%;
font-size: 14pt;
font-family: Verdana;
max-height: 600px;
vertical-align: top;
padding: 5px;
float: right;
margin-right: 25px;
overflow: hidden;
}

And Following CSS is form What your have
#right-content {
display: inline-block;
width: 36%;
font-family: Verdana;
height: 99.99%;
vertical-align: top;
padding: 5px;
}

Hope this will give you some clue to proceed
EDIT - 1
Main Problem with CSS is max-height. You will need to specify the correct height for your Parent DIV. If you want the resolution based dynamic CSS, you will need to update your height using JS. for hint check this
jQuery Screen Resolution Height Adjustment


text:
Q: How to convert Buffer to base64 image in Node js I am getting data from my SQL database like this:
const mysql = require("mysql");

const connection = mysql.createConnection({
    host: "localhost",
    user: "root",
    database: "database",
    password : ''
  });
  //connection.release();
  connection.connect(function(err) {
    if (err) console.log(err);
  });

  connection.query("SELECT image FROM table WHERE id=(SELECT max(id) FROM table);", function (err, result, fields) {
    if (err) console.log(err);
    console.log(result);
  });

/*Output:
[
  RowDataPacket {
    image: <Buffer 64 61 74 61 3a 69 6d 61 67 65 2f 6f 63 74 65 74 2d 73 74 72 65 61 6d 3b 62 61 73 65 36 34 2c 69 56 42 4f 52 77 30 4b 47 67 6f 41 41 41 41 4e 53 55 68 ... 27941 more bytes>
  }
]
*/

How can I convert result to a base64 image in Node.js? For Example:
'data:image/png;base64,iVBORw0KGgoAAAANS'

A: Since you're receiving a Buffer back as output, Buffer.toString('base64') will convert the raw binary data in the buffer to a base64 representation of the data.
Buffer.toString() can also take other encodings, you can read more about the other supported encodings in the docs.
So for your above code you would use this to get your image as base64
const dataImagePrefix = `data:image/png;base64,`
const query = 'SELECT image FROM table WHERE id=(SELECT max(id) FROM table)'

connection.query(query, (err, result, fields) => {
  if (err) {
    console.log(err)

    // Exit after handling error
    return
  }

  // Return all results and for each result row
  // convert to a base64 string with the dataImagePrefix prepended to each
  return results.map(result => `${dataImagePrefix}${result.image.toString('base64')}`)
})

A: You can do it very simple,

const generateImageFromBuffer = buffer => {
  let _buffer = new Buffer.from(buffer, 'base64');
  return _buffer.toString('base64');
};


text:
Q: Magento invoice link to pdf in transactional email I remember myself asking this question before and closing it again. Maybe it could not be done.....
We are investingating this option because it helps us in not sending a 1-2MB attachment to our customers.
But only after today when investigating  mywebstore.com/sales/guest/form I found something that could be helpful to access an order, without logging in ...
{{store url=""}}/sales/guest/print/order_id/{{var order.id}}/

Investigating now.
If any other mehtods exist I am interested.


text:
Q: Installing multiple packages in Ansible I have this task in Ansible:
- name: Install mongodb
  yum:
    name:
    - "mongodb-org-{{ mongodb_version }}"
    - "mongodb-org-server-{{ mongodb_version }}"
    - "mongodb-org-mongos-{{ mongodb_version }}"
    - "mongodb-org-shell-{{ mongodb_version }}"
    - "mongodb-org-tools-{{ mongodb_version }}"
    state: present
  notify: Restart mongodb

Is there a way I can indicate the version without having to use a loop like this? What is a more "elegant" way of writing this?
- name: Install mongodb
  yum:
    name: "{{ item }}-{{ mongodb_version }}"
    state: present
    loop:
    - mongodb-org-server
    - mongodb-org-mongos
    - mongodb-org-shell
    - mongodb-org-tools
  notify: Restart mongodb

A: Some people have mentioned syntax that allows passing a list, but you don't need to special-case your code for apt or yum. Here is the command that uses the generic package manager module:
- name: Install packages
  become: yes
  package:
    name:
      - tmux
      - rsync
      - zsh
      - rsync
      - wget
    state: present

(Or state: latest.) This feature is only documented for Ansible 2.9, so it may be new.

A: I think this is best way, but as the package names should not be hard coded, it is preferred to keep in vars/main.yml
e.g
mongodb_version: 5
packages:
  - "mongodb-org-shell-{{ mongodb_version }}"
  - "mongodb-org-server-{{ mongodb_version }}"

Call this inside your playbook as
- name: Install mongodb packages
  yum: name={{ item }}
       state=latest
  with_items: "{{ packages}}"

A: Now yum module direct accept array of packages like this
  vars:
    pkgs:
      - screen
      - rubygems
      - ksh
      - strace

  tasks:
  - name: Install pre-requisite packages
    yum: name={{ pkgs }} state=installed

A: To my surprise I didn't find the simplest solution in all the answers, so here it is. Referring to the question title Installing multiple packages in Ansible this is (using the yum module):
- name: Install MongoDB
  yum:
    name:
      - mongodb-org-server
      - mongodb-org-mongos
      - mongodb-org-shell
      - mongodb-org-tools
    state: latest
    update_cache: true

Or with the apt module:
- name: Install MongoDB
  apt:
    pkg:
      - mongodb-org-server
      - mongodb-org-mongos
      - mongodb-org-shell
      - mongodb-org-tools
    state: latest
    update_cache: true

Both modules support inline lists!
The second part of your question is how to integrate specific version numbers into the package lists. No problem - simply remove the state: latest (since using specific version numbers together with state: latest would raise errors) and add the version numbers to the package names using a preceding = like this:
- name: Install MongoDB
  yum:
    name:
      - mongodb-org-server=1:3.6.3-0centos1.1
      - mongodb-org-mongos=1:3.6.3-0centos1.1
      - mongodb-org-shell=1:3.6.3-0centos1.1
      - mongodb-org-tools=1:3.6.3-0centos1.1
    update_cache: true

You could also optimize further and template the version numbers. In this case don't forget to add quotation marks :)

A: Make this into an Ansible Role called mongo, resulting in the directory structure:
playbook.yml
roles
|-- mongo
|  |-- defaults
|  |    |-- main.yml
|  |
|  |-- tasks
|  |    |-- main.yml
|  |
|  |-- handlers
|  |    |-- main.yml

Add the required MongoDB packages and version into the default variables file roles/mongo/defaults/main.yml:
mongo_version: 4.0
mongo_packages:
- mongodb-org-server
- mongodb-org-mongos
- mongodb-org-shell
- mongodb-org-tools

Re-write the task in the roles/mongo/tasks/main.yml file:
- name: Install mongodb
  yum:
    name: "{{ item }}-{{ mongo_version }}"
    state: present
  with_items: "{{ mongo_packages }}"
  notify: Restart mongodb

Add your handler logic to restart MongoDB in the file roles/mongo/handlers/main.yml.
Write a Playbook called playbook.yml that calls the role.
---
- hosts: all
  roles:
  - mongo

A: A more elegant way, which doesn't keep re-checking each and every package if installed every time the script is run is to use something like this:
In vars/main.yml or similar:
  packages_to_install:
    - mongodb-org-server
    - mongodb-org-mongos
    - mongodb-org-shell
    - mongodb-org-tools

In tasks/main.yml or similar:
  - name: "Get installed packages"
    yum:
      list: "installed"
    register: installed_packages

  - name: "Install missing packages"
    package:
      state: "present"
      name: "{{ item }}"
    with_items: "{{ packages_to_install | difference(installed_packages | json_query('results[*].name')) }}"

Essentially this checks what is already installed and only installs missing packages. Counter-intuitively this is faster. You can also use dnf instead of yum.


text:
Q: PHP How to generate image from Base64? Hello I used to store my images as data. It looked something like "‰PNG IHDRÂæÉ0†". I was able to generate images from this data using the following code:
include_once "mysql_connect.php";
if(isset($_GET['id'])){
$id = mysql_real_escape_string($_GET['id']);
$query = mysql_query("SELECT * FROM `entree` WHERE `realID` = '$id'");

while($row = mysql_fetch_assoc($query)){
    $imageData = $row["thumbXL"];
    $imageType = $row["imageext"];
}

if($imageType == "image/png"){
    header("content-type: image/png");
}else if($imageType == "image/jpeg"){
    header("content-type: image/jpeg");
}else{}

if(!($imageData == null)){
echo $imageData;
}else{
}

}else{

}

That code was in a file called generateThumbnailXL.php and I would put that in the src of the images and the image would be generated perfectly. I switched to using Base64 image data recently and I just put the base64 data into the src and the image is generated perfectly. The problem is when someone shares my article on Facebook, the thumbnail doesn't show up because Facebook doesn't like using Base64. I need some way of converting base64 into something like "‰PNG IHDRÂæÉ0†" and then echo it out like the way the above code did. How can I do this? I researched on Google and found little help, nothing that will work for me.

A: Let say you have something like this :-
<?php

// $imgData contains base64 encoded data of image
$imgData = <<< EOFILE
R0lGODlhogBxAPcAA......0zEREAA7
EOFILE;

header("Content-type: image/png");
echo base64_decode($imgData);
exit();

and you will see image .


text:
Q: Positional Destructing Functions I'm new to clojure and I'm trying to understand as much as possible but the documentations are so vague
when you have a function
(fn [_ {:keys [kind]}] kind)

my understanding is that the function takes a vector map but only wants access to a key as specified by the second param {:keys..... correct?
Then how many parameters do I pass to this function? 1 or 2?
is it a vector? {:kind 1 :dog 2} or the vector key value (:kind {....})?

A: Your function expects two parameters (has arity 2.) The first parameter's name is _ (underscore,) which conventionally denotes a variable which is not used. (It is a valid variable name, and it becomes bound, but by convention it is not used, so it denotes a placeholder.)
The second parameter is destructured - {:keys [kind]}, which means that the expected value is a map, and as a result of destructuring a variable named kind will be bound to the value of key :kind of the actual parameter (or nil if there is no such key.)
So your function expects two parameters, the first is ignored, the second must be a map with a key :kind (maybe other keys as well, but they are ignored.)
((fn [_ {:keys [kind]}] kind) :foo {:kind :bar, :color :green})
=> :bar

P.S. I have looked at your question again, and I realised where your confusion may be coming from. The syntax [_ {:kind [kind]}] looks like a vector that includes a map at the second position. That's correct, but not everywhere in Clojure a vector notation means you can stick a vector there. Clojure users square brackets for a list of formal parameters of a function - it is part of a common pattern in Clojure of using vector literals everywhere a sequence may be expected. It is in fact very convenient, compared to other Lisps where you need to carefully use quotes in many places to avoid interpreting your lists as function application forms. But that's a digression, the important point is in fn (and defn) the square brackets denote parameter list and do not mean that the parameter is a vector.

A: Let's give the function a name:
(defn splot [_ {:keys [kind]}] kind)

This is shorthand for
(defn splot [_ {kind :kind}] kind)

*

*a function of two (positional) arguments:

*

*_, conventionally unused, and

*an anonymous map, which has its :kind entry bound to local kind;

*which then returns whatever is bound to kind.
Bindings that fail return nil.
For examples:
(splot "..." 6)            ;nil
(splot "..." {})           ;nil
(splot "..." {:kind 77})   ;77

A: It's fairly straightforward to see what a given function syntax does by trying it in the repl.
+user=> ((fn [_ {:keys [kind]}] kind) (:kind {}))
ArityException Wrong number of args (1) passed to: user/eval1/fn--3  clojure.lang.AFn.throwArity (AFn.java:429)
+user=> ((fn [_ {:keys [kind]}] kind) nil (:kind {}))
nil
+user=> ((fn [_ {:keys [kind]}] kind) nil {:kind 1})
1

the {:keys []} destructuring syntax is described pretty comprehensively in the official docs, and describes a shorthand to bind values that come from a hashmap. In Clojure {} is a hashmap, and [] is a vector, and these are not interchangeable. (:foo m) invokes get to look up the value under the key :foo in m. (let [{:keys [foo]} {:foo "bar"}] ...) and (let [foo (:foo {:foo "bar"})] ...) are equivalent.


text:
Q: How to get all .mp3 files(from both media card and device memory) in j2me? Is there anyway to get all .mp3 file listing in j2me like android.
and if not what is the best way to get all mp3 files.
thanks.

A: import java.io.IOException;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.microedition.io.Connector;
import javax.microedition.io.file.*;

/**
 * @author crazywizard
 */
public class RootMIDlet extends MIDlet implements CommandListener{
    private List list;
    private Command exitCommand;
    private Hashtable allowed_types;

    public RootMIDlet(){
        /* Construct MIDlet */
        //Define the file types of interest here
        allowed_types = new Hashtable();
        allowed_types.put("mp3", "audio/mp3");
    }

    public void startApp() {
        list = new List("My Files", List.IMPLICIT);
        exitCommand = new Command("Exit", Command.EXIT, 0);
        list.addCommand(exitCommand);
        list.setCommandListener(this);
        Display.getDisplay(this).setCurrent(list);
        getRootList();
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }

    public void getRootList(){
        //Get ALL available filesystem mounts
        Enumeration drives = FileSystemRegistry.listRoots();
        while(drives.hasMoreElements()){
            //Iterate through the drives
            String driveString = drives.nextElement().toString();
            list.append("Searching "+driveString, null);
            getFileList("file:///"+driveString);
        }
    }//--End of getRootList()

    public void getFileList(String path){
        try {
            //Open path
            FileConnection fc = (FileConnection)Connector.open(path, Connector.READ);
            //Get list of ALL files and dirs
            Enumeration filelist = fc.list();   //Get Hidden files as well --fc.list("*", true);
            while(filelist.hasMoreElements()){
                String filename = (String)filelist.nextElement();
                FileConnection fc1 = (FileConnection)Connector.open(path+filename, Connector.READ);
                //Check for dirs
                if(fc1.isDirectory()){
                    //Apply recursion here
                    getFileList("file://"+fc1.getPath()+filename);  //Note use of *double // instead of triple ///. Adjust accordingly according to phone platform
                }else{
                    //Filter for only allowed types == .mp3
                    String file_type = getFileType(filename).toLowerCase();
                    if(!allowed_types.containsKey(file_type)){
                        //Do Nothing and Pass
                        continue;
                    }
                    list.append(fc1.getPath()+filename, null);
                }
            }
            //Clean resources
            fc.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
            Display.getDisplay(this).setCurrent(new Alert("Error", ioe.toString(), null, AlertType.ERROR));
        } catch (Exception ex) {
            ex.printStackTrace();
            Display.getDisplay(this).setCurrent(new Alert("Error", ex.toString(), null, AlertType.ERROR));
        }
    }

    /* Helper Method */
    private String getFileType(String fileName){
        //Get file extension from fileName
        char ch = '.';
        int index = fileName.lastIndexOf((int)ch);
        return fileName.substring(index+1);
    }//--End of getFileType(String)

    public void commandAction(Command c, Displayable d) {
        if(c == exitCommand){
            notifyDestroyed();
        }
    }
}


text:
Q: How to redirect app in Android Emulator to development notebook? I develop a multiplatform (browser, Android, later iOS) and multiplayer word game and mostly do it on my old Macbook Air, but also sometimes on a Windows 7 PC:

While developing the HTML5 part of my game it was very comfortable to run the browser at my Macbook and make it connect to localhost, where the development version of my game backend was running: Jetty + PostgreSQL.
However now I have completed the browser part of my game and have switched to Android development.
Unfortunately, I haven't found a good way to redirect HTTP and WebSocket connections from my app running in Android Emulator to the "development backend" running at the same Macbook. And thus I have to use my "production backend" for testing (which is uncomfortable and requires good internet connectivity).
Please share your tricks and strategies for doing such a development, I am sure most of you had to work on an Android app + some HTTP script.
I was thinking of using dnsmasq (through "brew"), but haven't found a good way yet.

A: I have found a simple solution to my problem, which would even work while on a plane (with no connectivity) -
The address http://10.0.2.2 entered in Android Emulator would point to my notebook as described in the doc Set Up Android Emulator Networking:

Alternatively I got suggestions to take a look at adb reverse or ngrok


text:
Q: Add wordpress 'slug' as category class I want to stylize each of my categories with background colors to make them unique.
How can i do it with a function? tried milion codes, none worked.
Example:
https://fmportugal.net/downloads/rb-versailles
I want fm 2020 to have a color, and Downloads another diferent one, and Novas ligas e expansões too.
maybe the theme was overiding some of my earlier tries.


text:
Q: Maven 2.2 Eclipse Target is not a supported Maven Home I've a problem to link Maven 2.2 installed in disk with eclipse (I'm not able to uncheck the embedded version).
enter image description here
Thank you in advance for your help!

A: I had to use ECLIPSE LUNA and Maven 2.2.1 was accepted.


text:
Q: recaptcha in Matrix i need one help , i have been trying to do registration process using recaptcha (i am using matrix public server which requires recaptcha
However whenever i send my recaptcha response to server
it does not get accepted , which secret_key does server use to validate token?
i am following https://matrix.org/docs/spec/client_server/r0.3.0#post-matrix-client-r0-register


text:
Q: How to stop Rails app crashing due to form_tag I have an issue with my Rails App which just doesn't make sense. I have a form_tag so that the user can select a date, which is then passed to the controller. All I need it to do is reload the page with the selected date in the URL as params. This same code works elsewhere in my application, but in this instance it crashes the app.
The app completely freezes in both development and production (Heroku). I cannot figure out why.
Here is the form:
      <%= form_tag new_reservation_path, method: :get do %>
        <%= date_field_tag 'reservation_date', params[:reservation_date], class: "button-standard", style: "display: inline-block;", placeholder: "DD-MM-YYYY" %>

        <%= hidden_field_tag(:room, params[:room]) %>
        <%= submit_tag 'next', class: "button-standard", style: "display: inline-block;" %>

      <% end %>```


text:
Q: android studio generating builds in old paths after refactoring project I did a refactoring and changed the package name of my app in android studio. Also, made the change in the manifest and change the project folder name.
I replaced the filenames with 'oldname' and 'newname' to make things clearer
But no Class.forName does not find the classes anymore
Class target = Class.forName("LoginScreen");
Intent goTo = new Intent(WelcomeScreen.this, target);
startActivity(goTo);

Above code yields
04-13 14:03:08.375 5264-5264/? I/art: Not late-enabling -Xcheck:jni (already on)
04-13 14:03:08.613 5264-5264/com.example.ce.oldname W/System: ClassLoader referenced unknown path: /data/app/com.example.ce.oldname-2/lib/x86
04-13 14:03:08.992 5264-5270/com.example.ce.oldname W/art: Suspending all threads took: 8.440ms
04-13 14:03:09.036 5264-5292/com.example.ce.oldname D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
04-13 14:03:09.142 5264-5292/com.example.ce.oldname I/OpenGLRenderer: Initialized EGL, version 1.4
04-13 14:03:09.178 5264-5292/com.example.ce.oldname W/EGL_emulation: eglSurfaceAttrib not implemented
04-13 14:03:09.179 5264-5292/com.example.ce.oldname W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xabf6a0c0, error=EGL_SUCCESS
04-13 14:03:10.047 5264-5289/com.example.ce.oldname W/System.err: java.lang.ClassNotFoundException: LoginScreen
04-13 14:03:10.048 5264-5289/com.example.ce.oldname W/System.err:     at java.lang.Class.classForName(Native Method)
04-13 14:03:10.048 5264-5289/com.example.ce.oldname W/System.err:     at java.lang.Class.forName(Class.java:324)
04-13 14:03:10.048 5264-5289/com.example.ce.oldname W/System.err:     at java.lang.Class.forName(Class.java:285)
04-13 14:03:10.048 5264-5289/com.example.ce.oldname W/System.err:     at com.example.ce.newname.WelcomeScreen$1.run(WelcomeScreen.java:36)
04-13 14:03:10.048 5264-5289/com.example.ce.oldname W/System.err: Caused by: java.lang.ClassNotFoundException: Didn't find class "LoginScreen" on path: DexPathList[[zip file "/data/app/com.example.ce.oldname-2/base.apk"],nativeLibraryDirectories=[/data/app/com.example.ce.oldname-2/lib/x86, /vendor/lib, /system/lib]]
04-13 14:03:10.048 5264-5289/com.example.ce.oldname W/System.err:     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
04-13 14:03:10.048 5264-5289/com.example.ce.oldname W/System.err:     at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
04-13 14:03:10.048 5264-5289/com.example.ce.oldname W/System.err:     at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
04-13 14:03:10.048 5264-5289/com.example.ce.oldname W/System.err:   ... 4 more
04-13 14:03:10.048 5264-5289/com.example.ce.oldname W/System.err:   Suppressed: java.lang.ClassNotFoundException: LoginScreen
04-13 14:03:10.048 5264-5289/com.example.ce.oldname W/System.err:     at java.lang.Class.classForName(Native Method)
04-13 14:03:10.048 5264-5289/com.example.ce.oldname W/System.err:     at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
04-13 14:03:10.049 5264-5289/com.example.ce.oldname W/System.err:     at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
04-13 14:03:10.049 5264-5289/com.example.ce.oldname W/System.err:     at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
04-13 14:03:10.049 5264-5289/com.example.ce.oldname W/System.err:       ... 5 more
04-13 14:03:10.049 5264-5289/com.example.ce.oldname W/System.err:   Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available
04-13 14:03:10.049 5264-5289/com.example.ce.oldname I/System.out: DEBUG:Menu
04-13 14:05:39.594 5264-5270/com.example.ce.oldname W/art: Suspending all threads took: 7.819ms
04-13 14:06:04.120 5264-5270/com.example.ce.oldname W/art: Suspending all threads took: 11.536ms

When installing the app on the emulator I get below print which shows that it is still using a path with oldname to generate the build.
Installing APK:
C:\Users\CE\AndroidStudioProjects\newname\app\build\outputs\apk\app-
debug.apk

Uploading file to: /data/local/tmp/com.example.ce.oldname
Installing com.example.ce.oldname
DEVICE SHELL COMMAND: pm install -r "/data/local/tmp/com.example.ce.oldname"
pkg: /data/local/tmp/com.example.ce.oldname

How does Android Studio decide to set this path and how can I change it so that the app works under the new name?


text:
Q: How to display a two column ListView in Android? I have an android application that shows a grid view that shows:
1
2
3
4
GridView gridview=(GridView)findViewById(R.id.GridView_test);
DataBaseHelper dbhelper=new DataBaseHelper(this);
ArrayList<String> test=new ArrayList<String>(5);
backlinksadapter.add("1");
backlinksadapter.add("2");
backlinksadapter.add("3");
backlinksadapter.add("4");
ArrayAdapter mAdapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, test);
gridview.setAdapter(mAdapter);

By the moment is working, but i would like to show foreach line of the grid, 2 columns with the values of a 2 dimensional array (something like the GridView in ASP.Net - as datasource -).
I would like to show:
1 | Person 1
2 | Person 2
3 | Person 3
4 | Person 4
Any idea?

A: If you can't find an existing adapter that has those properties, you can create your own custom adapter and have it map to your view.
The Hello, GridView tutorial shows how to do this.

A: Does it have to be a grid view?  Will a ListView work?
I wrote a ListView and ListActivity that displays two items in each row.  I started with the SDK supplied simple_list_item_2.xml layout that lists two items per row but places one on top of the other (two lines) with the second line using a smaller font.  What I wanted was both items on the same line, one to the right and one to the left.
First I copied the simple_list_item_2.xml into my project's res/layout directory under a new name and changed the property android:mode="twoLine" to "oneLine" while still keeping the view element name as "TwoLineListItem".  I then replaced the two inner  elements with ones that did what I wanted.
In the code to initialize the list, I created a MatrixCursor and filled it with the desired data.  To support two items, each row in the MatrixCursor requires three columns, one being a primary key, "_id", and the other two columns being the items that I wanted to be displayed.  I was then able to use a SimpleCursorAdapter to fill in and control the ListView.
My Layout XML File:
 <?xml version="1.0" encoding="utf-8"?>
  <TwoLineListItem
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:paddingTop="2dip"
     android:paddingBottom="2dip"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:minHeight="?android:attr/listPreferredItemHeight"
     android:mode="oneLine"
  >
<TextView
    android:id="@android:id/text1"
    android:gravity="left"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="6dip"
    android:layout_marginTop="6dip"
    android:textAppearance="?android:attr/textAppearanceLarge"
/>
<TextView
    android:id="@android:id/text2"
    android:gravity="right"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="6dip"
    android:layout_marginTop="6dip"
    android:layout_marginRight="6dip"
    android:layout_toRightOf="@android:id/text1"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:textColor="@color/MainFontColor"
/>
</TwoLineListItem>

Note that I used "left" and "right" android:gravity values to make the left side item left justified and the right side item right justified.  You will need different gravity values for your layout plus you will need properties to control the size of the left side item that I did not need.
The method in my ListActivity class that initialized the ListView:
private void initListView()
{
    final String   AuthorName    = "Author: ";
    final String   CopyrightName = "CopyRight: ";
    final String   PriceName     = "Price: ";

    final String[] matrix  = { "_id", "name", "value" };
    final String[] columns = { "name", "value" };
    final int[]    layouts = { android.R.id.text1, android.R.id.text2 };

    MatrixCursor  cursor = new MatrixCursor(matrix);

    DecimalFormat formatter = new DecimalFormat("##,##0.00");

    cursor.addRow(new Object[] { key++, AuthorName, mAuthor });
    cursor.addRow(new Object[] { key++, CopyrightName, mCopyright });
    cursor.addRow(new Object[] { key++, PriceName,
            "$" + formatter.format(mPrice) });

    SimpleCursorAdapter data =
        new SimpleCursorAdapter(this,
                R.layout.viewlist_two_items,
                cursor,
                columns,
                layouts);

    setListAdapter( data );

}   // end of initListView()

The parameter to the MatrixCursor constructor is an array of strings that define the order and the names of the columns in the cursor. Important: Make sure to add an "_id" column, without it the MatrixColumn will throw an exception and fail to work!
The three variables, mAuthor, mCopyright and mPrice, are three data members in my ListAdaptor class and they are initialized elsewhere.  In my actual code, mAuthor is actually built in this method from a list of author names.  The author names are concatenated into a single string using "\n" as separators between the names.  This causes the multiple author names to appear on different lines in the same TextView.
The SimpleCursorAdapter ctor parameters are the ID of the View to use for each List row, the cursor containing the data, an array of strings where each element is the name of the column from the cursor (in the order to get them) and a corresponding array of View IDs for the View to use for each item in the List row.

A: JRL is right, you should write your own custom adapter which will let you control what will be displayed in each row. You might find this helpful. A more advanced example can be found here http://developerlife.com/tutorials/?p=327.
If you don't want/have to use a list a TableLayout could display your data as well. But that would be the manual approach since you'd have to fill each cell.
Best of success.

A: Why not create a class, whose toString() returns str(id) + " | " + personName, and use it as a template class instead of the String object?

A: You can simply add this in your XML
   android:numColumns="2"


text:
Q: swapoff from inside kernel code kernel newbie here...
I'm trying to do a swapoff from inside kernel code (on a swap device at a known location, suitable for hardcoding). I found the syscall sys_swapoff, which looks fairly straigtforward, so I tried just doing:
sys_swapoff("/path/to/swap/device");

but that doesn't work (it returns error no -14). Using ghetto-style debugging via printk, I've determined that it's erroring out on this codeblock in sys_swapoff:
    pathname = getname(specialfile);
    err = PTR_ERR(pathname);
    if (IS_ERR(pathname))
            goto out;

So apparently it doesn't like something about the pathname I'm giving it. I thought maybe it was because I was passing it a string literal instead of an allocated buffer, so I tried kmallocing a buffer, strcpying the path into it, and passing it that, but that made no difference. What am I doing wrong? Is there a better way to do a swapoff from inside kernel code other than using the syscall?

A: Are you specifying the path to the specific numbered partition (e.g. sda1 vs sda) as part of your path? Can you provide the specific value you used?
Actually, if you're trying to do this inside kernel code --  sys_swapoff expects the parameter being passed in to be from userspace, so you probably need to decompose sys_swapoff and do some of that work yourself in your code.

A: There's existing code in the TuxOnIce patch set (widely used for hibernation support in various Linux distros) that enables / disables swap when needed, i.e. when creating a hibernation image and/or resuming.
What this code does (check kernel/power/tuxonice_swap.c in the patch sources) is exactly the same as you do - sys_swapoff(swapfilename); - and it's functional. So there's nothing wrong with the invocation from kernel space as such.
How sure are you about your device pathname ? Have you instrumented sys_swapon() and sys_swapoff() so that they print what is actually passed when you manually on the command line issue swapon / swapoff commands ? udev & friends and/or the usage of initramfs sometimes result in device pathnames that aren't universally valid.
Edit:
Since you just stated in a comment you're attempting /dev/block/... - that might well be your cause; the path is an artifact, just after boot these device nodes exist directly in /dev/ (like /dev/mmcblk0 becomes /dev/block/mmcblk0 later). Try /dev/zram0 and see what happens.


text:
Q: Get and replace second last digit in integer -javascript I want to increment the second last digit of the integer by 1. I used below code but always changing the last digit. Please help
For Example, I want to change 26925131 to 26925141.
function increment_last(v) {
    return v.replace(/[0-9]+(?!.*[0-9])/, function(match) {
       return parseInt(match, 10)+1;
    });
 }

A: You need to add 10 instead 1, and no need of regex match
  function increment_last(v) {
          return v+10;

     }

A: You could take the second last digit for changing.
It works by looking for a character which is followed by another character and end of string (positive lookahead).

function inc(number) {
    return +number.toString().replace(/.(?=.$)/, v => (+v + 1) % 10);
}

var value = 26925131;

console.log(inc(value));


text:
Q: Lookup Values in Power Pivot tables with DAX i am trying to create a calculated column in Excel which should contain values from related tables. I tried looking into the Lookup function but this looks too complicated for my knowledge.
I have an Incident table where i want to have a calculated Column named closdBy. In this column i want to put the name of the operator that closed the incident. Every incident has many mutation entries which are stored in a Mutations table. This Mutations table has 1 statusID which comes from another related table named Status
In the calculated Field closedBy i want the calculated column to display the Name of the operator whose name matches the statusID Closed The name of the operator comes from the Operator table.
Anyone can help me with this ? Would appreciate it a lot.

POWER BI Example: https://ufile.io/z0g4x
Excel Example: https://ufile.io/6adju

A: required result in incident table (download PowerBI file) :

I have made some modification in relationship between table incident and mutation
created a column in mutation table
ID_Closed = IF(Mutation[statusID]="{CLO}",Mutation[ID],CONCATENATE(Mutation[ID],Mutation[statusID]))

Hoping this will help!

A: This is how my table looks like. The mutation table can have the same value for status (see {CLO} but I want to have the field Closed By and Resolved by in the Incident table to display the most recent Operator.
I have here an adjusted PowerBi file with more data:
https://ufile.io/20u0v


text:
Q: How to Prevent id duplication of dynamic div I am trying to create divs dynamically my method is working but I am having issue in id duplication. In this scenario I am restricted to creating only 4 extra divs. Below is my code.
Html code where divs are to be appeneded:

Html button code to add divs:
<button id="bedTypeAdder" class="btn btn-sm btn-outline-success">Add more</button>

Jquery code for dynamic div creation:
 //bed type adder
         var bedTypeCounter=0;// too keep track on the number of divs created
         $("#bedTypeAdder").click(function(event) {
            event.preventDefault();
            bedTypeCounter++;
            if(bedTypeCounter<5)
            {
                $('#bedTypeContainer').append('
 \

 \
                        <select id="" class="form-select" id="validationCustom13" required> \
                            <option selected disabled value="">Choose...</option> \
                            <option>...</option> \
                        </select> \

Please select a valid Option.
 \

 \

 \
                        <input id="" type="number" step="1" min="1" max="30" class="form-control max-limiter" id="validationCustom15" required> \

Looks good!
 \

 \

   \
                        <button id="btDynamicRowRemover'+bedTypeCounter+'" class="btn btn-outline-danger btDynamicRowRemoverClass">Remove</button>    \

  \

');
            }
            if(bedTypeCounter == 5)
            {
                alert("Max number of beds Reached but dont worry you can add extra beds");
                $('#bedTypeAdder').hide();
            }
        });

Jquery Code to remove div:
 $(document).on('click', '.btDynamicRowRemoverClass', function(event){
             event.preventDefault();
            var idSelector = $(this).attr("id");
            if(idSelector == 'btDynamicRowRemover2'){
                $('#btDynamicRow2').remove();
                $('#bedTypeAdder').show();
                bedTypeCounter--;
            }

         });

The issue I am facing here is like if I remove an id in this scenario the second row and add another div the id gets duplicated and I need the counter so I do not create more than 4 divs.

A: You can make your life easier by not using IDs. There's no need. Just use jQuery's $(selector).length to get the number. I also made your block of code actual HTML that sits on the page and gets cloned. Alot easier to manage rather than escaping line breaks with an inline script. Finally, to remove, just use $(this).closest(selector).remove()
You mention in a comment that you need ids to send values to the database. If you like, show how you're doing that and I can suggest an alternative. There's really no need for the IDs - they will just trip over each other.

//bed type adder
var bedTypeCounter = 0; // too keep track on the number of divs created
$("#bedTypeAdder").click(function(event) {
  event.preventDefault();
  bedTypeCounter = $('.bed-thing').length;
  if (bedTypeCounter < 5) {
    let clone = $('#template').clone().addClass('bed-thing').removeAttr('id')
    $('#bedTypeContainer').append(clone);
  }
  if (bedTypeCounter == 5) {
    alert("Max number of beds Reached but dont worry you can add extra beds");
    $('#bedTypeAdder').hide();
  }
});

$(document).on('click', '.btDynamicRowRemoverClass', function(event) {
  event.preventDefault();
  $(this).closest('.bed-thing').remove();
});
.bed-thing {
  padding: 10px;
  border-bottom: 1px solid #ddd;
  margin-bottom: 10px;
}

#template {
  display: none;
}

Html button code to add divs:

<button id="bedTypeAdder" class="btn btn-sm btn-outline-success">Add more</button>

    <select id="" class="form-select" id="validationCustom13" required>
      <option selected disabled value="">Choose...</option>
      <option>...</option>
    </select>

Please select a valid Option.

    <input id="" type="number" step="1" min="1" max="30" class="form-control max-limiter" id="validationCustom15" required>

Looks good!

    <button id="btDynamicRowRemover' + bedTypeCounter + '" class="btn btn-outline-danger btDynamicRowRemoverClass">Remove</button>

A: add another variable like
 var bedId = 0 ;

and update your code like this
  event.preventDefault();
  bedTypeCounter++;
  bedId++;

appended html

note : dont do
$(document).on('click', '.btDynamicRowRemoverClass', function(event){
bedId --
})


text:
Q: Cannot start Apache Tomcat 6 from IntelliJ IDEA 12.1.4 Ultimate (Windows 7) I need to debug a web application for Tomcat6 in IntelliJ IDEA.
When I try to run my web application, I get two errors:

*

*Address localhost:1099 is already in use

*Unable to open debugger port: java.net.SocketException
Launching the Apache Tomcat 6 service manually works fine.
What should I do in order to be able to debug web applications in Apache Tomcat 6 from Intellij IDEA?

A: If you had the web application up and running before, there may be an old debug server that did not close down properly running in the background. See this post about how to find what process that uses port 1099. If it proves to be a java process, kill it.
How can you find out which process is listening on a port on Windows?
(If you use the GUI sw suggested in the link above, you may kill the process(es) by marking all java processes that uses port 1099, right click and press "End Process...")

A: Following the below steps work:-

*

*Open command prompt and type the command netstat -ano

*You will see a list of active TCP connections with PID as the last column

*See the second column listing the local addresses and find the one using port 1099 from it and you'll get its PID

*Now open your Task Manager, click the Process tab and get the PID column to display [either by right clicking on the heading row and selecting PID OR click View, and then click Select Columns and select PID.]

*Now find the PID we got from Step3 and end the process.

Now you are good to go :)

A: I face this issue all the time. Here's how to fix it
LINUX
Open a terminal instance.
fuser 1099/tcp

This should return you a process ID.
1099/tcp:            31596

where 31596 is the process ID. Now you can either use the process ID to kill it or just bash the following -
fuser -k 1099/tcp

WINDOWS
Open a command prompt instance.
netstat -aon | find "1099"

This will return you an instance of the process.
output:
TCP    0.0.0.0:1099       0.0.0.0:0       LISTENING       15776

Here 15776 is the process ID. To kill this, enter -
taskkill /F /PID 15776

Cheers!

A: As said before, there's an old debug server running in the background.
My solution was to close the Java process that was left open from the Windows Task Manager.
Please verify that you can close this process before doing so!

A: You can change the JMX port (1099 per default) in the Run/Debug Configuration dialog. Just try a different port number (i.e. 9099).

A: Change your http port to 8080(default for tomcat) and debug port to something that is not being used currently by any processes. You can use anything that is upwards of 1024, but since you are getting an error on 1099, try something that is greater that 6000.
Debugger setting can be found here

A: There might be other program or server running at the background. First close other server running in the background and then restart your server.

A: I found this answer helpful:
How can you find out which process is listening on a port on Windows?
I opened the resource monitor and looked for what was using the ports. Then opened task manager and ended those processes

A: What worked for me was. I assumed I would need to have the "Apache Tomcat" service running under "Services" [Windows + R >> services.msc]
I went and stopped the Tomcat service here. Then I came to my Java application and ran it in Intellij, which allowed me to run it.
Hope this helps!

A: Just close all other unnecessary servers while using InteliJ.
I stopped my WAMP in order to remove this error "Port is already in use".


text:
Q: Is a nonempty intersection of a collection of closed sets closed? My intuition is yes, but how would you prove it? Would the nonempty intersection of a collection of closed sets always be closed?

A: We use the following proposition*:

If $\{ U_i : i \in \mathcal{A}\}$ is any collection of open subsets of $M$, then $\displaystyle\bigcup_{i \in \mathcal{A}} U_i$ is open.

We will also use one of De Morgan's Laws:

Let $M$ be a set, $\{B_i : i \in \mathcal{A}\}$ a collection of subsets of $M$. Then $\displaystyle\bigcup_{i \in \mathcal{A}}(M \setminus B_i) = M \setminus \displaystyle\bigcap_{i \in \mathcal{A}} B_i$

The trick to dealing with closed sets is to take their complement so that we instead deal with open sets.
We want to show that:

If $\{ F_i : i \in \mathcal{A}\}$ is any collection of closed subsets of $M$, then $\displaystyle\bigcap_{i \in \mathcal{A}} F_i$ is closed.

Since $F_i$ is closed, we have that $M \setminus F_i$ is open.
So $\displaystyle\bigcup_{i \in \mathcal{A}}(M \setminus F_i)$ is open by the proposition.
By De Morgan's Laws, $\displaystyle\bigcup_{i \in \mathcal{A}}(M \setminus F_i) = M \setminus \Bigg(\displaystyle\bigcap_{i \in \mathcal{A}}F_i\Bigg)$.
Hence, by definition $\displaystyle\bigcap_{i \in \mathcal{A}}F_i$ is closed.
*EDIT: I've just realised that this is tagged general-topology in a recent edit, in which case the proposition is true by definition and isn't actually a proposition at all. However, for a metric space we can actually prove it.

A: This is correct and easy to prove.
The proof is from ProofWiki:
Theorem

Let $T = \left({S, \tau}\right)$ be a topological space. Then the intersection of an arbitrary number of closed sets of $T$ (either finitely or infinitely many) is itself closed.

Proof
Let $I$ be an indexing set (either finite or infinite).
Let $\displaystyle \bigcap_{i \mathop \in I} V_i$ be the intersection of a indexed family of closed sets of $T$ indexed by $I$.
Then from De Morgan's laws: Difference with Intersection:
$\displaystyle S \setminus \bigcap_{i \mathop \in I} V_i = \bigcup_{i \mathop \in I} \left({S \setminus V_i}\right)$
By definition of closed set, each of $S \setminus V_i$ are by definition open in $T$.
We have that $\displaystyle \bigcup_{i \mathop \in I} \left({S \setminus V_i}\right)$ is the union of a indexed family of open sets of $T$ indexed by $I$.
Therefore, by definition of a topology, $\displaystyle \bigcup_{i \mathop \in I} \left({S \setminus V_i}\right) = S \setminus \bigcap_{i \mathop \in I} V_i$ is likewise open in $T$.
Then by definition of closed set, $\displaystyle \bigcap_{i \mathop \in I} V_i$ is closed in $T$. $\blacksquare$


text:
Q: How can I filter on different exceptions using only the keyboard? In the exception chooser (CTRL+ALT+E) in Visual Studio, how can I navigate this screen using the keyboard? So far TAB hasn't gotten me very far. Thanks for you time.

A: You can use Tab to navigate through the buttons on the right side and eventually into the main pane.  When the main pane is selected, the OK button is highlit in blue, but doesn't have the line of dots surrounding it.
Once in the main part, you can navigate around the options using the arrow keys, and you can select/deselect options using Alt+T


text:
Q: How to get old function from a file in old commit let's say that i have file called getData as the following
class getData{
   public function retriveData() {
     echo 'data retrived';
   }
   public function checkData() {
    echo 'data checked'
   }
}

then i edit it to be like this
class getData{
      public function retriveData() {
      echo 'data retrived';
     }
}

then i commit the last change and after while i want to get checkData() back what is the best method to do that without damage any of my project files and make my file back to previous form

A: You can "checkout" a file from a previous commit by runnning:
git checkout abc123 -- path/to/file/to/restore

Where abc123 is the commit hash where the file was in the state you wanted it to be in.
You can also swap the commit ID with HEAD~1 where the 1 represents the number of commits to go back from.
Update; As per @Roman Valeri, the newer, equivalent syntax would be:
git restore —source=abc123 — path/to/file


text:
Q: CSRF-Prevention for XHR-Requests I did just learn about the details of CSRF-prevention. In our application, all "writing" requests are done using XHR. Not a single form is actually submitted in the whole page, everything is done via XHR.
For this scenario, Wikipedia suggests Cookie-to-Header Token. There, some random value is stored in a cookie during login (or at some other point in time). When making an XHR-request, this value is then copied to a custom http-header (e.g. "X-csrf-token="), which is then checked by the server.
Now I am wondering, if the random value is actually necessary at all in this scenario. I think it should be enough to just set a custom header like "X-anti-csrf=true". Seems a lot more stable than dragging a random value around. But does this open any security issues?

A: It depends on how many risky assumptions you want to make.

*

*you have properly configured your CORS headers,

*and the user's browser respects them,

*so there is no way a malicious site can send an XHR to your domain,

*which is the only way to send custom headers with a request

If you believe in all that, sure, a fixed custom header will work.
If you remove any of the assumptions, then your method fails.
If you make the header impossible to guess, then you don't need to make those assumptions. You're still relying on the assumption that the value of that header can't be intercepted and duplicated by a third party (there's TLS for that).


text:
Q: MySQL query is slow? Today I have a problem in my SQL query, my request take most 30 seconds, so I get an error in my php.
My SQL query:
SELECT v.ID
     , v.TITLE
     , v.THUMB
  FROM video v
  JOIN join_video_date d
    ON d.ID_VIDEO = v.ID
  JOIN join_video_category c
    ON c.ID_VIDEO = v.ID
 WHERE c.ID_CATEGORY = $ID
 ORDER
    BY d.DATE DESC
 LIMIT $PAGE,24

This query take 24 video of category ordered by date, but this query is slow.
I have indexes all tables, example of table "join_video_date"
join_video_date (ID, ID_VIDEO, DATE)

Index:
PRIMARY -> ID
ID_VIDEO -> ID_VIDEO
DATE -> DATE

A: This is your query:
SELECT v.ID, v.TITLE, v.THUMB
FROM video v JOIN
     join_video_date d
     ON d.ID_VIDEO = v.ID JOIN
     join_video_category c
     ON c.ID_VIDEO = v.ID
 WHERE c.ID_CATEGORY = $ID
 ORDER BY d.DATE DESC
 LIMIT $PAGE,24;

The first thing to try is indexes: join_video_category(ID_CATEGORY, ID_VIDEO), join_video_date(ID_VIDEO, DATE).  I assume video(id) has an index.
Your query suggests that a video could have multiple categories and multiple dates.  If so, the query is probably not doing what you want anyway.  One way to prevent this is to move the condition on categories to the WHERE clause:
SELECT v.ID, v.TITLE, v.THUMB
FROM video v JOIN
     join_video_date d
     ON d.ID_VIDEO = v.ID
 WHERE v.id IN (SELECT c.ID_VIDEO
                FROM join_video_category c
                WHERE c.ID_CATEGORY = $ID
               )
 ORDER BY d.DATE DESC
 LIMIT $PAGE,24;


text:
Q: how can I add spaces after ." but not after just a " in ruby? I do the following to add spaces after proper end-of-sentence punctuation:
string = '"something is wrong."     but then, "why?"  '
new_string = string.squeeze(" ").gsub(/([.?!"]) */,'\1  ')
puts new_string
=> "  something is wrong.  "  but then, "  why?  "

My desired result is this:
"something is wrong."  but then, "why?"

If something is after " to not add spaces unless it's ." in which case, add the same two spaces I would after a regular  .

A: On the example string you give, I can get the desired result with
2.2.0 (main):0 > puts string.squeeze.strip
"something is wrong." but then, "why?"


text:
Q: My discord python bot's shop cause it to freeze I have been making a discord economy bot and it has a shop.
When I try and buy an item from my shop in the bot, the bot does not respond with anything and I won't recognise any other commands. The bot also gives me an error in the command prompt. This error is in the picture. Any help given is great.
https://i.stack.imgur.com/SsBwA.png
My code:
mainshop = [{"name":"Airbus A320","price":400,"description":"test description"}]

@client.command()
async def shop(ctx):
    em = discord.Embed(title = "Dealership")

    for item in mainshop:
        name = item["name"]
        price = item["price"]
        desc = item["description"]
        em.add_field(name = name, value = f"${price} | {desc}")

    await ctx.send(embed =em)

@client.command()
async def buy(ctx,item,amount = 1):
    await open_account(ctx.author)

    res = await buy_this(ctx.author,item,amount)

    if not res[0]:
        if res[1]==1:
            await ctx.send("That item does not exisit!")
            return
        if res [1]==2:
            await ctx.send(f"You do not have enough money!")
            return

    await ctx.send(f"you just bought {amount} {item}")

async def buy_this(user,item_name,amount):
    item_name - item_name.lower()
    name_ = None
    for item in mainshop:
        name = item["name"].lower()
        if name == item_name:
            name_ = name_
            price = item["price"]
            break

    if name_ ==None:
        return [False,1]

    cost = price*amount

    users = await get_bank_data()

    bal = await update_bank(user)

    if bal[0]<cost:
        return [False,2]

    try:
        index = 0
        t = None
        for thing in users[str(user.id)]["bag"]:
            n = thing["item"]
            if n == item_name:
                old_amt = thing["amount"]
                new_amt = old_amt + amount
                users[str(user.id)]["bag"][index]["amount"] = new_amt
                t = 1
                break
            index+=1
        if t == None:
            obj = {"item":item_name , "amount" : amount}
            users[str(user.id)]["bag"].append(obj)
    except:
        obj = {"item":item_name , "amount" : amount}
        users[str(user.id)]["bag"] =[obj]

    with open("bank.json","w") as f:
        json.dump(users,f)

    await update_bank(user,cost*-1,"Wallet")

    return [True,"Worked"]```

A: you have a typing mistake in buy_this function.
item_name - item_name.lower()

You need to put '=' instead of '-', like this:
item_name = item_name.lower()


text:
Q: Как получить логарифм по заданному основанию для списка? Как записать математическое выражение в питоне, выдается ошибка. Нужно чтобы log(...) по основанию 1+x**2, для различных x.
import numpy as np

x = [1, 10, 100, 1000]
print("Входные значения x: \n", x)
y = np.log(1 / np.e ** np.sin(x + 1) / (5 / 4) + (1 / x ** 15)) / np.log(1 + x ** 2)
print(y)

Получаю ошибку:

TypeError: can only concatenate list (not "int") to list

A: Ошибка в выражении x + 1:

$ python
Python 3.10.0 (default, Oct 16 2021, 12:17:56) [GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
@>>> x = [1, 10, 100, 1000]
@>>> x + 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "int") to list

Исправить можно переведя список в массив numpy:

@>>> import numpy as np
@>>> x = np.array(x)
@>>> x + 1
array([   2,   11,  101, 1001])

Целиком исправленная программа:
import numpy as np

x = np.array([1, 10, 100, 1000])
print("Входные значения x: \n", x)
y = np.log(1 / np.e ** np.sin(x + 1) / (5 / 4) + (1 / x ** 15)) / np.log(1 + x ** 2)
print(y)

A: Как вариант через math
import math

x = [1, 10, 100, 1000]

print("Входные значения x: \n", x)

def logs(x1):
    base = (1 + x1 ** 2)
    ex = 1 / math.e ** math.sin(x1 + 1) / (5 / 4) + (1 / x1 ** 15)
    return math.log(ex, base)

print([logs(i) for i in x])

>>> [0.40299028466113235, 0.16832640716567754, -0.0733047836576131, -0.08274280283465775]


text:
Q: Moving data to another sheet and specific cell not working as anticipated I have my data all on one sheet ("PBT"). There are different ranges of data that need to go to different sheets. My current code will move the data to the sheet I want; however, it starts putting the data into A4 and then puts the next row into A3, A2, and then deletes anything else. I'd like it to go down from A4 and I'm not sure what I am doing wrong.
Here is the code:
Sub Move_Data()
'Moves data to set worksheets
Dim Firstrow As Long
Dim Lastrow As Long
Dim Lrow As Long
Dim CalcMode As Long
Dim ViewMode As Long

With Application
    CalcMode = .Calculation
    .Calculation = xlCalculationManual
    .ScreenUpdating = False
End With

'We use the ActiveSheet but you can replace this with
'Sheets("MySheet")if you want
With Sheets("PBT")

    'We select the sheet so we can change the window view
    .Select

    'If you are in Page Break Preview Or Page Layout view go
    'back to normal view, we do this for speed
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView

    'Turn off Page Breaks, we do this for speed
    .DisplayPageBreaks = False

    'Set the first and last row to loop through
    Firstrow = .UsedRange.Cells(1).Row
    Lastrow = .UsedRange.Rows(.UsedRange.Rows.Count).Row

    'We loop from Lastrow to Firstrow (bottom to top)
    For Lrow = Lastrow To Firstrow Step -1

        'We check the values in the A column in this example
        With .Cells(Lrow, "A")

            If Not IsError(.Value) Then

                If Right(.Value, 7) >= 30001 And Right(.Value, 7) <= 32500 Then .EntireRow.Cut Sheets("WTH").Range("A4").End(xlUp).Offset(1)
                'in Column A, case sensitive.

            End If

        End With

    Next Lrow

End With

ActiveWindow.View = ViewMode
With Application
    .ScreenUpdating = True
    .Calculation = CalcMode
End With

End Sub

A: Try This.  Your For Loop was going backwards from the last row to the first row.  I took out the Step - 1 to make it increase instead of decrease and I flipped around the Firstrow and Lastrow so it starts on the first row and stops on the Lastrow.
Initial State of Sheet1:  (Sheet2 is blank)

State of Sheet1 after code:

State of Sheet2 after code:

 Sub Move_Data()
'Moves data to set worksheets
Dim Firstrow As Long
Dim Lastrow As Long
Dim Lrow As Long
Dim CalcMode As Long
Dim ViewMode As Long
Dim num_of_entries As Integer
With Application
    CalcMode = .Calculation
    .Calculation = xlCalculationManual
    .ScreenUpdating = False
End With
num_of_entries = 0
'We use the ActiveSheet but you can replace this with
'Sheets("MySheet")if you want
With Sheets("Sheet1")

    'We select the sheet so we can change the window view

    'If you are in Page Break Preview Or Page Layout view go
    'back to normal view, we do this for speed

    'Turn off Page Breaks, we do this for speed

    'Set the first and last row to loop through
    Firstrow = .UsedRange.Cells(1).Row
    Lastrow = .UsedRange.Rows(.UsedRange.Rows.Count).Row

    'We loop from Lastrow to Firstrow (bottom to top)
    For Lrow = Firstrow To Lastrow

        'We check the values in the A column in this example
        With .Cells(Lrow, "A")

            If Not IsError(.Value) Then

                If Right(.Value, 7) >= 30001 And Right(.Value, 7) <= 32500 Then

                    .EntireRow.Cut Sheets("Sheet2").Range("A4").Offset(num_of_entries)
                    num_of_entries = num_of_entries + 1
                'in Column A, case sensitive.
                End If
            End If

        End With

    Next Lrow

End With

'ActiveWindow.View = ViewMode
With Application
    .ScreenUpdating = True
    .Calculation = CalcMode
End With

End Sub

A: Here is a version of the code that could solve some issues.
1. Go forward through the loop so you know where the write the values in the other sheet
2. By going forward you have to make sure to stay on the same row whenever you cut a row out, and not to go beyond the end of the now shorter list.
I marked the lines I changed with ***** in the comments.
Sub Move_Data()
'Moves data to set worksheets
'**** We dont need Firstrow anymore
'**** Dim Firstrow As Long
'**** Use Targetrow for driving where the move should be to
Dim TargetRow as Long
Dim Lastrow As Long
Dim Lrow As Long
Dim CalcMode As Long
Dim ViewMode As Long

With Application
    CalcMode = .Calculation
    .Calculation = xlCalculationManual
    .ScreenUpdating = False
End With

'We use the ActiveSheet but you can replace this with
'Sheets("MySheet")if you want
With Sheets("PBT")

    'We select the sheet so we can change the window view
    .Select

    'If you are in Page Break Preview Or Page Layout view go
    'back to normal view, we do this for speed
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView

    'Turn off Page Breaks, we do this for speed
    .DisplayPageBreaks = False

    'Set the first and last row to loop through
    '**** Assign to Lrow as we will use While loop
    Lrow = .UsedRange.Cells(1).Row
    Lastrow = .UsedRange.Rows(.UsedRange.Rows.Count).Row
    '**** New variable for reference in target sheet
    TargetRow = 5

    ' ***** We loop forward now
    Do While Lrow <= Lastrow
        'We check the values in the A column in this example
        With .Cells(Lrow, "A")
            If Not IsError(.Value) Then
                If Right(.Value, 7) >= 30001 And Right(.Value, 7) <= 32500 Then
                   'in Column A, case sensitive.
                   ' **** Use Target Row to determine destination range
                   .EntireRow.Cut Sheets("WTH").Range("A" & TargetRow)
                   ' **** increment the target row for next move.
                   TargetRow = TargetRow + 1
                   ' **** As we removed one row, our last row is one less now
                   Lastrow = Lastrow - 1
                   ' *** Counter the increment to the row, as we have the new
                   ' *** row already at the position where we cut one away
                   Lrow = Lrow - 1
                End If
            End If
            ' **** Increment
            Lrow = Lrow + 1
        End With
    '****
    Loop

End With

ActiveWindow.View = ViewMode
With Application
    .ScreenUpdating = True
    .Calculation = CalcMode
End With

End Sub


text:
Q: JQuery Ajax returns Source code I'm using JQuery Ajax on my website. I've tested it on our test server it worked perfectly, but when I tried to put it on our productive server the Ajax just returns the source code of the website itself.
JS File:
$(document).ready(function () {
    $('#sshin').keyup(function () {
        var query = $(this).val();
        console.log(query);
        if (query != '') {
            $.ajax({
                url: "search.php",
                method: "POST",
                data: {
                    query: query
                },
                success: function (data) {

                    console.log(data);

                }
            });
        }
    });

    $(document).on('click', 'article', function () {
        var text = $('#sshin').val();
        text = text.substring(0, text.lastIndexOf(',') + 1);
        text += $(this).text();

        var uniq = text.match(/\b\w+\b/g).filter(function (el, idx, a) {
            return idx === a.lastIndexOf(el);
        });

        text = uniq.join(',');

        $('#sshin').val(text);
        $('#sshout').fadeOut();
    });
});

PHP File:
<?php
  if(isset($_POST["query"])){
     $query = $_POST["query"];
     return '

1

2

';
  }
?>

Any idea why it returns something different than it should?

A: This method once worked for me, hope it might help. Let me know.
 this->output->set_content_type('application/json');
        return $this->output->set_output(json_encode('

1

2

'));


text:
Q: Percentile for a Given Z-Score Disclaimer: Statistical math person I am not...
I'm a programmer that has been tasked with finding the percentile a child will fall in depending on their weight and age according to the CDC.
The CDC site with the data is:
http://www.cdc.gov/growthcharts/percentile_data_files.htm
I am using the Weight-for-age data from the CDC and I beleive I can obtain the correct z-score for a child given their weight for age. Now that I have a z-score...what do I do? How can I turn that Z-Score into a percentile? From what I've researched it sounds like I need a standard normal table find the percentile, but can I use any standard normal table I find? How exactly do I get the corresponding percentile for a given Z-Score? I am even on the right track?
EDIT:
I would like to get childs specific percentile for their weight if possible. The data tables provided by the cdc give percentages in increments (ie: 3, 5, 10), but I would like to know if a child falls into the 2nd percentile. I just don't know if getting an exact percentile is possible.

A: If you follow the instructions on the page you linked to find the z-score using the LMS parameters, then you can use any standard normal table (they should all be the same) to find the percentile. Since you're programming, you should look to see if your programming language has a "Normal quantile" or "Normal inverse cdf" function (qnorm in R), which does the calculation for you so you don't need a table.
The 3rd, 5th, etc. percentiles that are also included in the files you can download are unnecessary and you can just ignore them. The LMS method will give you an "exact" percentile (up to the error of the distribution fitting, but there's nothing you can do about that--it's baked into the data).


text:
Q: JetBrains rider: how to attach to processes running as root Just wondering what's the best way to attach to a process running under root account. I've thought about running rider from the cmd with sudo, but it's not a good idea because it looses all my regular user's settings and keys.
Thanks.


text:
Q: GlassFish JAX-RS Jackson custom JSON serialization I have a JAX-RS resource and I'd like to use a custom JSON serializer for java.util.Calendar attribute using the @JsonSerialize(using=MySerializer.class).
import java.util.Calendar;
import org.codehaus.jackson.map.annotate.JsonSerialize;

public class FooBar {

    @JsonSerialize(using=MySerializer.class)
    private Calendar calendar;

    public FooBar() {
        calendar = Calendar.getInstance();
    }

    public Calendar getCalendar() {
        return calendar;
    }
}

MySerializer.java:
import java.io.IOException;
import java.util.Calendar;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;

public class MySerializer
    extends JsonSerializer<Calendar>
{

    @Override
    public void serialize(Calendar c, JsonGenerator jg, SerializerProvider sp)
        throws IOException, JsonProcessingException
    {
        jg.writeString("fooBar Calendar time: " + c.getTime());
    }

}

I made a simple project in NetBeans 7.1 and it works well.
When I use it in an other project with different deployment (EAR with multiple WARs and EJB JARs) then I receive
javax.ws.rs.WebApplicationException: com.sun.jersey.api.MessageException: A message body writer for Java class
com.example.FooBar and MIME media type application/json was not found

But if I put into the web.xml the init-parameter
<init-param>
   <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
   <param-value>true</param-value>
</init-param>

json serialization works,
but the @JsonSerialize annotation does not work.
On the other hand the Netbeans project does't need POJOMappingFeature.
What could be the difference between these two applications?
What makes a difference where one application needs POJOMappingFeature and the other one don't?

A: Regarding the @JsonSerialize failure: If you have a getter of a field, you need to annotate the getter method with @JsonSerialize and not the field itself! It seems the getter method has a preference over the field on serialization. So the working code is:
import java.util.Calendar;
import org.codehaus.jackson.map.annotate.JsonSerialize;

public class FooBar {

    private Calendar calendar;

    public FooBar() {
        calendar = Calendar.getInstance();
    }

    @JsonSerialize(using=MySerializer.class)
    public Calendar getCalendar() {
        return calendar;
    }
}

A: Finally I found out the difference.
If I put jackson-jaxrs.jar into the WEB-INF/lib of WAR, then no POJOMappingFeature is required in web.xml, it can automatically serialize POJOs.
If you don't have this jar, then you need the following entry in web.xml:
<servlet>
    <servlet-name>ServletAdaptor</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
      <param-value>true</param-value>
    </init-param>
    ...
</servlet>


text:
Q: lua - garry's mod - attempt to call global 'Player' (a table value) When trying start Garry's Mod server i get an error:

[ERROR]
gamemodes/darkrp/gamemode/modules/base/sv_gamemode_functions.lua:227:
attempt to call global 'Player' (a table value)

*

*unknown - gamemodes/darkrp/gamemode/modules/base/sv_gamemode_functions.lua:227

sv_gamemode_functions.lua:217-230

function GM:EntityRemoved(ent)
self.Sandbox.EntityRemoved(self, ent)
if ent:IsVehicle() then
    local found = ent:CPPIGetOwner()
    if IsValid(found) then
        found.Vehicles = found.Vehicles or 1
        found.Vehicles = found.Vehicles - 1
    end
end
local owner = ent.Getowning_ent and ent:Getowning_ent() or Player(ent.SID or 0)
if ent.DarkRPItem and IsValid(owner) then owner:removeCustomEntity(ent.DarkRPItem) end
if ent.isKeysOwnable and ent:isKeysOwnable() then ent:removeDoorData() end end

please help.

A: change this line
local owner = ent.Getowning_ent and ent:Getowning_ent() or Player(ent.SID or 0)

to
local owner = ent :GetOwner()

https://wiki.facepunch.com/gmod/Entity:GetOwner
https://wiki.facepunch.com/gmod/Player:UserID

A: The problem is not in this part of code.
Something overrode Player global variable with a table.
You need to find why this happened.
If after the fix Player won't work, try Entity(ent.SID or 0), maybe it's a EntityIndex not UserID.
Entity:GetOwner (as Doyousketch2 suggested) won't help you because it's used for parenting not ownability.


text:
Q: Obtain Vilucha without having to fight the dark aeon? I have the HD Remaster version.  I am trying to go back to Besaid to get Vilucha to use with the Blitzball games. I realize they added Dark Aeons, but at this stage in the game they are too hard to defeat. Is there anyway I can get Vilucha without having to fight Dark Valefor?

A: I'm afraid not.  Entering Besaid triggers the cutscene, and forces you to fight Dark Valefor.  There's no way around that.  So come looking for a fight, and bring your best weaponry.
If Wakka's been levelled enough, a perfect Attack Reels with a Break Damage Limit weapon can drop it without any issue.  Otherwise, you're in it for the long haul.  It has 800,000 HP, and will require a team of heavily levelled members in order for them to survive.  Break HP Limit and Auto Phoenix on one person can help you take him, and give you the edge when someone drops.

A: If you're still having difficulty with the dark aeon I recommend using Yojimbo's special Zanmato. Save at the closest save point and grand summon him with Yuna (if speeds an issue equip someone with first strike and swap them for Yuna once the battle begins.) If you give a million gil you're likely to get it, but the odds of him using it depends on how often and well you use him after you've gotten him. Good luck