text:
Q: TableViewer how to set caret position for the cell with Editing Support and remove FULL_SELECTION I have a TableViewer with last column which has EditingSupport to edit the cell's value. The viewer has style set to FULL_SELECTION.
Once I click on the cell, the text value is fully selected:

I can start editing, it will clear off the current value "max value" and start new value.
However, If i want to move the mouse to a specific position to edit, I need to give a delay of a sec or so. If I click too fast right after the first click to select, the cell will be deselected.
Is there any way to avoid that? Can I make the cell not fully selected ? or always have the caret to the end of the text ? Thanks!

A: I assume you are using TextCellEditor as the cell editor.
Create your own class extending TextCellEditor and override the doSetFocus class to be something like:
@Override
protected void doSetFocus()
{
  super.doSetFocus();

  if (text != null) {
     text.setSelection(0, 0);
   }
}

A: to remove full selection and set caret to end of text, override doSetFocus and set text.setSelection( text.getText().length() );
to ignore double click event, override getDoubleClickTimeout to return 0


text:
Q: Mapping to POCOs with top-level dictionary from Postgres jsonb column I have a .NET Core 3.1 application using EF Core and a Postgres database. In the database I have one jsonb column that I now want to map to a well-defined set of classes in EF Core.
The content of the jsonb column looks like the following:
{
    "entry1": {
        "name": "entry1",
        "contents": {
            "entry1.1": {
                "name": "entry1.1"
            },
            "entry1.2": {
                "name": "entry1.2",
                "contents": {
                    "entry1.2.1": {
                        "name": "entry1.2.1"
                    }
                }
            }
        }
    }
}

At the top level it is a dictionary mapping strings to entries. Each entry has a name and can have contents, which is again a dictionary mapping strings to entries.
public class Entry
{
    public string name { get; set; }
    public Dictionary<string, Entry> contents { get; set; }
}

The jsonb column itself is defined on a table like this:
public class MyTable {
    [Column(TypeName = "jsonb")]
    public Dictionary<string, Entry> Entries { get; set; }
}

The problem with this now is that it simply doesn't work. When I fetch an entry from the database with EF Core, the "Entries" property does contain indeed a dictionary with a single key "entry1", but the value of that key is an empty Entry object (name and contents are both null).
The Npgsql documentation on mapping jsonb columns to POCOs doesn't explain how to handle dictionaries in this case. I couldn't find any examples with a top-level dictionary in the jsonb column, so I'm not entirely sure I'm doing this right.
How can I wire this up correctly so that my jsonb column gets mapped to a dictionary of Entry objects?

A: The following seems to work well:
class Program
{
    static void Main(string[] args)
    {
        using (var createCtx = new BlogContext())
        {
            createCtx.Database.EnsureDeleted();
            createCtx.Database.EnsureCreated();

            createCtx.Blogs.Add(new Blog
            {
                Entries = new Dictionary<string, Entry>
                {
                    { "bla", new Entry { Foo = "foo1" }}
                }
            });

            createCtx.SaveChanges();
        }

        using var ctx = new BlogContext();

        var results = ctx.Blogs.Single();
        Console.WriteLine(results.Entries["bla"].Foo);
    }
}

public class BlogContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    static ILoggerFactory ContextLoggerFactory
        => LoggerFactory.Create(b => b.AddConsole().AddFilter("", LogLevel.Information));

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseNpgsql(@"Host=localhost;Database=test;Username=npgsql_tests;Password=npgsql_tests")
            .EnableSensitiveDataLogging()
            .UseLoggerFactory(ContextLoggerFactory);
}

public class Blog
{
    public int Id { get; set; }
    [Column(TypeName = "jsonb")]
    public Dictionary<string, Entry> Entries { get; set; }
}

public class Entry
{
    public string Foo { get; set; }
}

In the database:
test=# select * from "Blogs"
test-# ;
 Id | Name |         Entries
----+------+--------------------------
  1 |      | {"bla": {"Foo": "foo1"}}
(1 row)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Failed sending email with java program via smtp and ssl I am just trying to send an email form java code. But I am getting exception like this:
"java.lang.RuntimeException: javax.mail.MessagingException:
 Could not connect to SMTP host:smtp.gmail.com, port: 465, response: -1."

I have set the following properties:
mail.smtp.host
mail.smtp.socketFactory.port
mail.smtp.auth
mail.smtp.port

What is the reason for this exception?
Please help me. Thanks in advance.

A: You could probably try this example to sort it out problem -
Java send mail through gmail

A: Looks like you haven't found the JavaMail FAQ.  These entries might help:

*

*How do I debug problems connecting to my mail server?

*How do I configure JavaMail to work through my proxy server?


text:
Q: Animating osmdroid overlays I have tried to pass drawables with animations to the marker overlay built into the bonus pack to no success. Has anyone figured out how to animate a marker overlay, I was looking to create the sonar ping style my location thats built into apple maps. I would also like to make one fade in and out for a set amount of time.
From what I can tell is to do this would be to override the draw method and keep track of the last value, then use an post delayed handler to act as the timer and keep forcing the map to refresh which will redraw the markers. This seems a bit of overhead, but it appears how the my location overlay currently works, in that every time the location is updated it redraws the map to show the new marker location or compass direction if its moving.

A: Yes it's possible (have pretty much what you described in closed source app), but you have to do the leg work your self.
You'll need an async task that fires on some cycle that adds line to an osm overlay. On each iteration, clear the view, then add in a new circle (or whatever) with a larger diameter until your target radius has been reached.


text:
Q: Result matrix where each entry is a vector of varying size in Matlab I have a 128 X 8192 matrix. I have split it into cell arrays of size 1X64 each using :
C = mat2cell(input_matrix, repmat(1,[1 128]), repmat(64,[1 128]));
Now I need to pass each of these cell arrays to an function say 'fn_X'. This function returns an array of varying sizes. I need the output for each of the cell arrays passed to be stored in a result matrix. I used the following code :
for(irl = 1 : 128)
        for(jrl = 1 : 128)
            Output_matrix(irl,jrl) = fn_X(C{irl,jrl});
         end
end

This gave me an error 'Subscripted assignment dimension mismatch.'
I then tried it in a column matrix using the following code :
king = 1;
    for(irl = 1 : 128)
        for(jrl = 1 : 128)
            Output_matrix(king) = fn_X(C{irl,jrl});
            king = king + 1;
        end
    end

This gave me an error 'In an assignment  A(I) = B, the number of elements in B and I must be the same.'
I also tried using cell array assignment using the following code :
king = 1;
for(irl = 1 : 128)
    for(jrl = 1 : 128)
        Output_matrix(king) = fn_X(C{irl,jrl});
        king = king + 1;
    end
end

This gave an error 'Cell contents assignment to a non-cell array object.'
Any suggestions on how I can handle this?

A: The problem on your code is that should use curly brackets on the left side of the assignment:
king = 1;
for irl = 1 : 128
    for jrl = 1 : 128
        Output_matrix{king} = fn_X(C{irl,jrl});
        king = king + 1;
    end
end

But this likely not the right way to do this. This is not the "style" of the language, the way that makes sense is to vectorize which will probably require fn_X handle this itself.
Alternatively, you can also do it with the much simpler (and often faster):
Output_matrix = cellfun (@fn_X, C, "UniformOutput", false);


text:
Q: Accessing an IIS Website from a mobile phone that is connected via usb cable directly with the windows machine You may find this question very odd but these days we have all sorts of windows and mobile phone apps. Although googling it didn't help but I thought may be someone somewhere knows the answer.
Is it possible to access an IIS hosted website on a mobile phone. Mobile phone is connected to the windows machine via usb cable. If it is possible then what is the procedure please.
IIS Website is written in asp.net mvc 4 razor with c#.
Unfortunately the network does not have a wifi so connecting to the windows machine via wifi is out of the question.
I am administrator of my windows machine.
At the moment, it is also not possible to host the website on the server and make it available over the internet.
My phone is latest android.
In simple words, I have a website that is hosted on IIS and the phone is connected to the machine via usb and I want to browse the website from my phone.

A: Some ideas from the top of my head:

*

*If your mobile phone has internet access and you can access your network router (or you can ask your admin to do this for you) than you could just simply forward a port to your PC and connect from internet to your router with appropriate port. Please look into your router manual for more details

*You can also buy cheap usb wifi key that you can use with your PC as set up direct connection with your phone

*Depending on your mobile phone OS you can actually share internet connection (so probably at the same time give your phone access to your local PC) by using 3rd party software and some hacks - this is one for Android but requires rooted OS http://www.howtogeek.com/117118/how-to-connect-your-android-to-your-pcs-internet-connection-over-usb/
Good luck! :-)


text:
Q: Content inside iframe redirects but not the whole page So I have a column which has this code inside:

and the this is a line inside "sidebar.html" :
example

(keep in mind that this is a part of a table)
when I click on the word "example" it does actually redirect to where it should but thats only visible inside the iframe
I want to redirect the WHOLE page instead to www.example.com

A: Just only add "parent." before window.location:
example

A: You can use
window.top.location.href = "http://www.newurl.com";
to change the URL of the parent page.
A simple redirect will only work inside the iframe.


text:
Q: Help installing package? I asked this question so most of the details are there. But, to sum up: I've added a PPA (maybe it isn't technically a PPA but it acts as such) to my sources.list.d directory and run sudo apt-get update
For some reason though, I still can't get my system to find the package.
Would greatly appreciate any help.
$ dpkg --print-architecture
amd64

$ dpkg --print-foreign-architectures
i386

$ sudo apt-get update
[sudo] password for ramy:
Hit:1 http://us.archive.ubuntu.com/ubuntu focal InRelease
Get:2 http://us.archive.ubuntu.com/ubuntu focal-updates InRelease [114 kB]
Get:3 http://security.ubuntu.com/ubuntu focal-security InRelease [114 kB]
Get:4 http://us.archive.ubuntu.com/ubuntu focal-backports InRelease [101 kB]
Hit:5 https://apt.releases.hashicorp.com focal InRelease
Hit:6 http://ppa.launchpad.net/forkotov02/ppa/ubuntu focal InRelease
Hit:7 https://apt.stellar.org focal InRelease
Get:8 http://us.archive.ubuntu.com/ubuntu focal-updates/main amd64 DEP-11 Metadata [274 kB]
Get:9 http://security.ubuntu.com/ubuntu focal-security/main amd64 DEP-11 Metadata [24.4 kB]
Get:10 http://us.archive.ubuntu.com/ubuntu focal-updates/universe amd64 DEP-11 Metadata [323 kB]
Get:11 http://security.ubuntu.com/ubuntu focal-security/universe amd64 DEP-11 Metadata [58.3 kB]
Get:12 http://security.ubuntu.com/ubuntu focal-security/multiverse amd64 DEP-11 Metadata [2,464 B]
Get:13 http://us.archive.ubuntu.com/ubuntu focal-updates/multiverse amd64 DEP-11 Metadata [2,468 B]
Get:14 http://us.archive.ubuntu.com/ubuntu focal-backports/universe amd64 DEP-11 Metadata [1,768 B]
Get:15 https://dl.cloudsmith.io/public/balena/etcher/deb/ubuntu focal InRelease [5,054 B]
Fetched 1,020 kB in 1s (772 kB/s)
Reading package lists... Done

To install the package I followed this guide. It instructs me to run do two things. First
Download and install the public signing key with
wget -qO - https://apt.stellar.org/SDF.asc | sudo apt-key add -

and [Save the repository definition to /etc/apt/sources.list.d/SDF.list] 4 with echo "deb https://apt.stellar.org $(lsb_release -cs) stable" | sudo tee -a /etc/apt/sources.list.d/SDF.list
echo "deb https://apt.stellar.org $(lsb_release -cs) stable" | sudo tee -a /etc/apt/sources.list.d/SDF.list

The two commands above show the following output:
:~$ wget -qO - https://apt.stellar.org/SDF.asc | sudo apt-key add -
OK
:~$ echo "deb https://apt.stellar.org $(lsb_release -cs) stable" | sudo tee -a /etc/apt/sources.list.d/SDF.list
deb https://apt.stellar.org focal stable


text:
Q: Audio Play Error in Corona Sdk I´m with this error in my simulator:
main.lua:24: audio.loadSound() failed to create sound '1.wav'
The sound is correctly wirte
here´s my code:

(i already change the name and local of my sound and didn´t work)
and i have this other code here:

and he´s working perfectly
Can You Help Me pls?
(I´m Brazilian so sorry for my english)

A: Try this

*

*Cross-platform .wav files must be 16-bit uncompressed,

*audio.loadSound() — loads an entire sound into memory. It should be used for shorter audio files that may be used repeatedly throughout the app,

*read more https://docs.coronalabs.com/guide/media/audioSystem/index.html

*check localization of 1.wav file

Hope this help
ldurniat

A: Maybe you did not specify the correct path? For example if it was in the "Sounds" folder you would need:
x = audio.loadSound("Sounds/1.wav")


text:
Q: Twitch OAuth access_token instead of Bearer token Twitch has New API and V5 API, and I want to use exactly the V5 API since that's API gives a little bit more info about channel. And when I'm use assess_token from browser dev tools, API is working.

But when I'm using assess_token got by Omniauth authorization, API is not working and errors like {"error":"Gone","status":410,"message":"It's time to kick ass and serve v3... and I'm all outta v3. See https://dev.twitch.tv/docs"} are constantly appeared. The docs said the V5 API is still working (though deprecated).

Helix and Kraken APIs has different types of tokens (Bearer and OAuth)

How can I get exactly the OAuth access_token to be able to work with V5 API after user authentication?
Token from browser dev tools is working as with the New API and with the V5 API but token got from Omniauth is working only with New API.
SOLVED
Access token might be used for both New API and V5 API. For using V5 API just need to add Accept header with application/vnd.twitchtv.v5+json into request.


text:
Q: How to log into my new spring boot application? I'm learning Spring boot and while I can run my project, when I try to access it, hoping for a blank page, I get a login/password prompt and, though I've defined a few values on my application.properties file, I always get an error.
pom.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>b.c.g</groupId>
    <artifactId>app</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>appName</name>
    <description>appDescription</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jersey</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mobile</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-social-facebook</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-social-twitter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.restdocs</groupId>
            <artifactId>spring-restdocs-mockmvc</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

application.properties is:
spring.datasource.url = jdbc:mysql://localhost:3306/app
spring.datasource.name=app
spring.datasource.username=app
spring.datasource.password=appPassword
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database=mysql
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect

security.user.name=master
security.user.password=abc123

And, finally, my main class is:
@Configuration
@EnableAutoConfiguration
@ComponentScan
@Controller
public class AppNameApplication {

    @ResponseBody
    @RequestMapping(value = "/")
    public String entry() {
        return "AppName";
    }

    public static void main(String[] args) {
        SpringApplication.run(AppNameApplication.class, args);
    }
}

Though I'm a seasoned Spring user, I'm learning Spring boot to add to my development skills.
The error I get on the browser is:

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing
  this as a fallback. Tue Aug 09 13:33:59 BRT 2016 There was an
  unexpected error (type=Unauthorized, status=401). Bad credentials

I know there's nothing much going on now, but is this the expected behavior? Shouldn't I be, at least, able to login?

A: I'll post this answer as a more detailed "comment", since I can't comment with nice details.
In your pom.xml you have added the Spring Security starter:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

This means that Spring will enable security to access your endpoint, hence your unauthorized error. Spring Security's default behavior is to lock down your entire application.
So, you have to configure spring security accordingly to enable your access.
As detailed in this link https://spring.io/guides/gs/securing-web/
You have to create a WebSecurity configurer, below the example:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }
}

Before getting involved with Spring Security, you could first remove the security starter and try accessing your endpoints. Once you confirm that your API works as expected, then you can start playing with Security. Likewise, I'd suggest you to start from scratch with no starters and adding them one by one meanwhile you learn instead of adding everything in one shoot.


text:
Q: "gcc": executable file not found in %PATH% when using mongo-go-driver I want to use mongodb driver.But I get the following error:

go.mongodb.org/mongo-driver/vendor/github.com/DataDog/zstd
  exec: "gcc": executable file not found in %PATH%

A: The issue is that your library depends on gcc to run.
1. Linux/Containers
If you are running in a container, you can try two options:

*

*you can build your app without CGO with the following command:

RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o yourBinary

*You can try to install gcc into your container. If it is an alpine based container, run

RUN apk update && apk add --no-cache gcc

You could also need musl-dev package, but you should try without it first.
2. Windows
Since MacOS and most Linux distros come with GCC, I guess you could be using Windows. In this case, you need to install MinGW.

A: I know this is old but I ran into this problem too, About Alexey answer, on windows, you should install MinGW and add the path to win environment. You should follow this. In case MinGW did not work, you can install this one which worked perfectly for me on windows.

A: and for whom uses WSL?
my wls is like this:
# github.com/mattn/go-sqlite3
cgo: C compiler "gcc" not found: exec: "gcc": executable file not found in $PATH


text:
Q: Python pyodbc cursor.execute(query) not working on a .exe compilation I'm trying to create an alert with Python that connects to a SQL database, executes a SELECT, and based on the results, sends an alert via SMTP. I got it all down, it works when executing the Python script from Visual Studio. But if I compile it to .exe with pyinstaller (which I need to execute from the Windows Task Scheduler on a server that does not have Python installed) and try to run it, it stops on the line that executes the query. Here is the code:
for BM in servers:
        try:
            server = BM[0]
            db = BM[1]

            conn = pyodbc.connect('driver={%s};server=%s;database=%s;uid=%s;pwd=%s' % ( driver, server, db, user, password ) )
            log.write("Conectado" + '\n')

            cursor = conn.cursor()
            log.write("Cursor creado" + '\n')

            try:
                cursor.execute(query)
                log.write("Query ejecutada" + '\n')

            except pyodbc.Error as ex:
                log.write(ex + '\n')

        except pyodbc.Error as ex:
            log.write(ex + '\n')

The line that stops the script is cursor.execute(query). And "query" is a simple SELECT * FROM table, no conditions.
How can I make this work?


text:
Q: SwiftUI and Combine - Update variable in view model when another changes I am currently building a small one view app to help learn some more SwiftUI.
The app is a simple app to calculate values in a ratio. I have 4 main variables at the moment, the left and right side of the ratio, and the first and second value that will be calculated in ratio.
Initially I had each of these stored as @State properties:
@State var leftSide = Double()
@State var rightSide = Double()
@State var value1 = Double()
@State var value2 = Double()

In the app there are 4 sliders that allow each variable to be changed independently of each other. What I want to now allow to happen is that changing the variable value1 will also update value2 according to the ratio the user has set. To achieve this I believe I need to use Combine however I have not got much experience with the framework.
To begin with I moved the variables to an ObservableObject class:
final class UserData: ObservableObject {
    @Published var leftSide = Double()
    @Published var rightSide = Double()
    @Published var value1 = Double()
    @Published var value2 = Double()
}

I updated my main view with @ObservedObject var userData = UserData() so I could access the variables in my view and this works fine
Now I want to update the value1 and value2 variables when the other changes. From the reading I have done I think I need to use a subscriber but I cannot find anything on how to set this up with they @Published property. Have I gone about this in the correct way or is there a better way to do this?

A:
I have 4 main variables at the moment, the left and right side of the
  ratio, and the first and second value that will be calculated in ratio

so, why you don't declare it as computed variables?
final class UserData: ObservableObject {
    @Published var leftSide = 0.0
    @Published var rightSide = 0.0
    var value: Double {
        // perform the calculation here
        ...
    }
}

If you like to change value independently (bind it to SwiftUI component), and modify the value in case leftSide or rightSide are modified, use willSet or even didSet
final class UserData: ObservableObject {
    @Published var leftSide = 0.0 {
        willSet {
           // update value
            value = f(newValue)
        }
        didSet {
           // update value
           value = f(oldValue)
        }
    }
    @Published var rightSide = 0.0
    @Published var value = 0.0
    func f(_ v: Double)->Double {
        ......
    }
}


text:
Q: Uncaught ReferenceError: bootstrap is not defined but still loaded In my Laravel 8 project I am trying to display a Toast via the following code:
app blade layout:

            Bootstrap
            11 mins ago
            <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>

            Hello, world! This is a toast message.

@if(Session::has('message'))

@endif

I use webpack via laravel-mix v6.0.43.
app.js:
import "bootstrap";

webpack.mix.js:
const mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel applications. By default, we are compiling the CSS
 | file for the application as well as bundling up all the JS files.
 |
 */

 mix.js('resources/js/app.js', 'public/js')
    .sass("resources/scss/app.scss", "public/css");

package.json:
{
    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "mix",
        "watch": "mix watch",
        "watch-poll": "mix watch -- --watch-options-poll=1000",
        "hot": "mix watch --hot",
        "prod": "npm run production",
        "production": "mix --production"
    },
    "devDependencies": {
        "@popperjs/core": "^2.11.5",
        "axios": "^0.21",
        "bootstrap": "^5.1.3",
        "laravel-mix": "^6.0.43",
        "lodash": "^4.17.19",
        "postcss": "^8.1.14",
        "resolve-url-loader": "^5.0.0",
        "sass": "^1.50.0",
        "sass-loader": "^12.6.0"
    }
}

npm run dev

> dev
> npm run development

> development
> mix

● Mix █████████████████████████ emitting (95%)
 emit

✔ Mix
  Compiled successfully in 4.55s

   Laravel Mix v6.0.43

✔ Compiled Successfully in 4516ms
┌────────────────────────────────────────────────────────────────────┬─────────┐
│                                                               File │ Size    │
├────────────────────────────────────────────────────────────────────┼─────────┤
│                                                         /js/app.js │ 299 KiB │
│                                                        css/app.css │ 201 KiB │
└────────────────────────────────────────────────────────────────────┴─────────┘
webpack compiled successfully

Dropdown and Modal via the data-bs-toggle="modal" attribute works perfectly and the app.js file contains all Bootstrap plugins..
I get the error message Uncaught ReferenceError: bootstrap is not defined even though Bootstrap is loaded.

A: Try to run this command again
npm run dev

i hope it was useful


text:
Q: has_one and belongs to form I'm rather new to rails and I'm stuck with this has_one and belongs_to form. I'm trying to create a team that has two speakers (from class 'User') through a form ,in the following manner:
class Team<ActiveRecord::Base

belongs_to :league
belongs_to :seed
has_many :speakers do
def user(level="1")
    find_by(level: level).user
end

end
    end
my user model looks like this :
class User < ActiveRecord::Base

belongs_to :team

end

user model:
    class User

speaker model:
class Speaker < ActiveRecord::Base
    belongs_to :team
    belongs_to :user
end

my issue is (i think ) primarily in my controllers and form.controller looks like:
class TeamsController<ApplicationController

def new
    @seed=Seed.find_by_id(params[:seed_id])
    @league=current_admin.league
    @team=current_admin.league.teams.build(:seed_id=>@seed,:approved=>false)
    @usernames= @mca.connections.connected.each do |x| x.user end
end

def create
    @league=current_admin.league
    @team = @league.teams.build(team_params)

  if @team.save
    flash[:notice] = "Team Request Sent!."
    redirect_to '/'
  else
    flash[:error] = "Unable to request team."
    redirect_to :back
  end

end
form looks like:

        <%= form_for @team do |f| %>
            <%= f.hidden_field :seed_id, :value => @seed.id %>
            <%= f.hidden_field :league_id, :value => @league.id %>

                    <%= f.collection_select :speaker, @usernames,:user,:fullname, multiple:true %>

                <%= f.submit "Create" , class:"btn btn-primary" %>

        <% end %>

I would really appreciate some help because it keeps throwing the following error:
NoMethodError in TeamsController#create
undefined method `each' for "2":String

A: The surface issue you have is that you're passing a string when Rails is expecting an object:

User(#69980837338020) expected, got String(#69980808947560)

This means you should be sending @user rather than "username" etc.
The error will likely be on this line:
@team = @league.teams.build team_params

... which means that you're passing :speaker (which Rails needs as an object) when you should be passing the speaker_id foreign key. Yury Lebedev's answer explains how to do this.

There is a deeper issue.
I don't see how each User can only belong to a Team:
class AddFieldsToUser < ActiveRecord::Migration
  def change
    add_column :users, :speaker_id, :integer
    add_column :users, :speaker2_id, :integer
  end
end

For this to work, your users can only be a member of one team.
Whilst this might work for a smaller scale product, I personally feel it to be an incorrect schema setup.
If anything, you'd expect the team to have speaker_1 and speaker_2, which would mean those two options being stored in the teams database (not user).
I think this is the cause of your problem (you're trying to set the speaker_1 and speaker_2 params when they don't exist in the teams db).
-
I would recommend the following:
#app/models/user.rb
class User < ActiveRecord::Base
   has_many :speaking_engagements, class_name: "Speaker"
   has_many :teams, through: :speaking_engagements
end

#app/models/speaker.rb
class Speaker < ActiveRecord::Base
   #columns team_id | user_id | level | created_at | updated_at
   belongs_to :team
   belongs_to :user
end

#app/models/team.rb
class Team < ActiveRecord::Base
   has_many :speakers do
      def user(level="1")
         find_by(level: level).user
      end
   end
end

This will give you the ability to call:
@team = Team.find params[:id]
@speakers = @team.speakers

@user.speaking_engagements.where(team: @team)

To save it, you'll be able to use the following:
#app/controllers/teams_controller.rb
class TeamsController < ApplicationController
   def new
      ...
       @team = current_admin.league.teams.build seed: @seed, approved: false
   end

   def create
       @league = current_admin.league
       @team = @league.teams.build team_params

       if @team.save
         ...
   end

   private

   def team_params
       params.require(:team).permit(:name, :speakers) #-> not sure about "speakers"
   end
end

This should allow you to define the following:
#app/views/teams/new.html.erb
<%= form_for @team do |f| %>
   <%= f.collection_select :speakers, @usernames, :id, :name, multiple: true %>
   <%= f.submit %>
<% end %>


text:
Q: How do I set the charts Y axis to be dynamic with maximum value set at 125? I have a charts populated in asp.net C#. I have multiple charts and each can range from 0 - 125.
which look like this if I do not set the maximum which one of it, the chart maximum will go to 140 if my series range max is 125.:

Thus I would like to set the maximum of Y axis to 125 however not staticly setting it for all charts. which mean I would like to make it dynamic still like the second chart image with the maximum set as 125.
Please advice thanks.

A: // Maximum value in Series, you may have to change YValues[0] to the appropriate
// index for your type of chart (so that it measures the top of your markers)
double maxValue = chart.Series[0].Points.Max(x => x.YValues[0])

// yAxisMax calculated as max value in series + 10 then rounded up to nearest 10
// but capped at 125 below. You could change this to perhaps
// maxValue * 1.1 to always get a 10 % extra above, anything goes
double yAxisMax = Math.Ceiling((maxValue + 10) / 10) * 10;

if (yAxisMax > 125)
    yAxisMax = 125;

chart.ChartAreas[0].AxisY.Minimum = 0;
chart.ChartAreas[0].AxisY.Maximum = yAxisMax;
chart.ChartAreas[0].AxisY.Interval = 5;


text:
Q: Displaying message multiple times I have following code.
<fieldset id="test">
    (2) Open Sub-tasks

                Location/Problem
                Assignment
                Due Date

                Bathroom, Plumbing
                Johnny Fixalot
                03/14/2017

                Mark Complete

                Delete

               Location/Problem
               Assignment
               Due Date

                Bathroom, Plumbing
                Johnny Fixalot
                03/14/2017

                Mark Complete

                Delete

</fieldset>

As per this code, its displaying 2 tasks with options Mark Complete and Delete respectively. When any option is selected that particular "li" gets selected class. I am trying to validate whether any options selected or not and trying to display an error message.
My trial code is-
$('ul.multi-list').each(function(){
 if($('li.sub_task_complete.selected').length == 0){
    $('fieldset#test').addClass('error');
    $('fieldset#test .table-holder').after('Please select an option for completing or deleting sub task.');
 }
});

Its displaying the message 4/5 times. I want to display a message after each table holder only once if it's not selected.
Note: There can be multiple fieldsets with ul.multi-list class hence sub_task_complete class of li is only the distinguishing factor.

A: Ah, after your comment on my first answer I get what you're doing. In this case you want to use .closest. Pretty sure this does what you're after.
// Iterate through the lists individually
$('ul.multi-list').each(function(){
    // Set the errors variable for this list to 0
    var errors= 0;
    // Iterate through the li's in this list
    // Increment errors if any of the tasks are missing .selected
  $(this).find('li').each(function(){
   if(!$(this).hasClass("selected")){
    errors++;
        }
    })

    // Check if this list has 2 errors meaning neither
    // li has .selected and add the error class and message to
    //this list only
  if( errors ==2 ) {
    $(this).closest('.table-holder').addClass('error');
    $(this).closest('.table-holder').after('Please select an option for completing or deleting sub task.');
  }
});

Fiddle: https://jsfiddle.net/4qprwk3y/

A: Instead of iterate through all li option you can use inbuilt jQuery function like this to achieve your goal:
if($('li').filter('.selected').length == 0)
{
e.preventDefault();
alert('please select atleast one option');
}

Here you can see an example


text:
Q: save json file in cache error I need yo download Json of about 30 MB and save it before to make a percentual of download. So I've implemented this code:
 private void downloadAirports()
{
    final OkHttpClient mOkHttpClient = new OkHttpClient();

    final Request mRequest = new Request.Builder().url(SERVICE_ENDPOINT).build();

    Observable.create(new Observable.OnSubscribe<String>()
    {
        @Override
        public void call(Subscriber<? super String> subscriber)
        {
            try {
                InputStream inputStream;
                Response response = mOkHttpClient.newCall(mRequest).execute();
                if (response.isSuccessful())
                {
                   inputStream = response.body().byteStream();
                   long len = response.body().contentLength();

                    Log.d("str",String.valueOf(len));

                    String progress = "0";
                    subscriber.onNext(progress);

                    final int bufferSize = 1024;
                    flag = false;
                    final byte[] buffer = new byte[bufferSize];
                    final StringBuilder out = new StringBuilder();
                    Reader in = new InputStreamReader(inputStream, "UTF-8");
                    ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();

                    long total = 0;
                    airp = new ArrayList<AirportObject>();
                    int count =0;

                    /*while ((count = inputStream.read(data)) != -1)
                    {
                        total += count;
                        progress = String.valueOf(total * 100 / len);
                        subscriber.onNext(progress);
                    }*/

                while(!flag)
                    {
                        count = inputStream.read(buffer);

                        if (count == -1)
                        {
                            progress = "100";
                            subscriber.onNext(progress);
                            flag = true;

                        }
                        else
                        {
                            byteOutStream.write(buffer);
                            total += count;
                            progress = String.valueOf(total * 100 / len);
                            subscriber.onNext(progress);
                        }
                    }

    //                        byte[] res = byteOutStream.toByteArray();

                    File jsonFile = new File(getActivity().getCacheDir(), FILE_NAME);
                    FileOutputStream outStream = new FileOutputStream(jsonFile);
                    byteOutStream.writeTo(outStream);

                    byteOutStream.flush();
                    inputStream.close();
                    byteOutStream.close();
                    Log.d("length", String.valueOf(jsonFile.length()));
                    Log.d("str",String.valueOf(len));

                    //write the whole data into the file
                   /* for(int i = 0; i < res.length; i++)
                    {
                        outStream.write(res[i]);
                    }*/

                    Gson gson = new Gson();

                    JsonReader reader = new JsonReader(new FileReader(jsonFile));

                    airp = new ArrayList<>();

                    reader.beginArray();

                    while (reader.hasNext())
                    {

                          AirportObject airport = gson.fromJson(reader, AirportObject.class);
                          airp.add(airport);

                    }

                    reader.endArray();
                    reader.close();

                }

                 subscriber.onCompleted();
               }
             catch (IOException e)
             {
                e.printStackTrace();
             }

        }
    }).subscribeOn(Schedulers.newThread())
            .subscribe(new Subscriber<String>() {

                public void onCompleted()
                {
                    Log.wtf("on complete","On complete");
                }

                @Override
                public void onError(Throwable e)
                {
                    e.printStackTrace();
                }

                @Override
                public void onNext(final String progress) {

                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                     Log.d("%",progress);
                                }
                        });

                }
            });
}

but I've this problem: if I use the code I've put in the comments (byte array and the for cycle) it is so slow but it works, and if I use the code I've post down, I give this error when I print the log of the size of file:
D/length: 25767936
D/str: 24672558

where lenght is the dimension of the file I've created in the cache, str is the dimension of the download. So I give some error in Gson with this bug of MalformedJson.
How could I fix this error?

A: According to OP, this line:
count = inputStream.read(buffer);

should be:
count = inputStream.read(buffer,0,count);


text:
Q: Load XpsDocument from a .XPS file into existing FixedDocument I'm trying to load a XPS file from disk and print it as part of a FixedDocument or FixedDocumentSequence of in memory documents I've created. They need to be printed as one sequence because they're duplexed.
Here's my best attempt so far:
// create my memory FixedDocument (a packing slip)
DocumentReference mainDocRef = GetMainDoc();  // created in memory

// load XPS document from file (to print on the back)
XpsDocument xpsDoc = new XpsDocument("flyer.xps", FileAccess.Read);
var docSequenceFromFile = xpsDoc.GetFixedDocumentSequence();
var xpsDocRef = docSequenceFromFile.References.First();

// try to combine together
FixedDocumentSequence documentSequence = new FixedDocumentSequence();
documentSequence.References.Add(mainDocRef);
documentSequence.References.Add(xpsDocRef);     // THROWS EXCEPTION

// print
XpsDocumentWriter xps = PrintQueue.CreateXpsDocumentWriter(printQueue);
xps.Write(documentSequence, ticket);

I always end up with the exception :

InvalidOperationException : Additional information: Specified element is already the logical child of another element. Disconnect it first.

I've tried several ways to do this, but keep ending up with errors like this
How can I load an XpsDocument and print it as a second page in a FixedDocumentSequence I've created in memory?

A: Simon_Weaver,
As I dont exactly know what is being returned by the GetMainDoc() method I have excluded that and just commented out the mainDocRef refrences however this seems trivial as your issue is adding the loaded xps file to your documentSequence and the mainDocRef is somewhat irrelevant to the question (please correct me if I am wrong).
Now the problem as stated is that the xpsDoc is loaded to another element (document) and we must detach it as the exception states. However the ability to do so is protected by an internal method. This being said the easiest way is just enumerate through all the pages of the document and create a new page from the source of the page being enumerated to a new document.
The final code looks something like.. (code commented)
//DocumentReference mainDocRef = GetMainDoc();  // created in memory. commented as I dont have a reference to what this object contains.

//create our new document reference to add the pages to
DocumentReference newDocReference = new DocumentReference();

// load XPS document from file (to print on the back)
using (XpsDocument xpsDoc = new XpsDocument(@"flyer.xps", FileAccess.Read))
{
    var docSequenceFromFile = xpsDoc.GetFixedDocumentSequence();
    var xpsDocRef = docSequenceFromFile.References.First();

    //get the fixed document to enumerate
    FixedDocument xpsFixedDoc = xpsDocRef.GetDocument(false);

    //get the fixed document to add to
    FixedDocument newFixedDoc = new FixedDocument();

    //set the new document reference
    newDocReference.SetDocument(newFixedDoc);

    //enumerate each page of the fixed document
    foreach (PageContent page in xpsFixedDoc.Pages)
    {
        PageContent newPageContent = new PageContent();
        newPageContent.Source = page.Source;
        ((IUriContext)newPageContent).BaseUri = ((IUriContext)page).BaseUri;
        newPageContent.GetPageRoot(true);
        newFixedDoc.Pages.Add(newPageContent);
    }
}

// try to combine together.
FixedDocumentSequence documentSequence = new FixedDocumentSequence();

//documentSequence.References.Add(mainDocRef); <<-- commented out, re-add after tests

//add the new document reference
documentSequence.References.Add(newDocReference);

// print
XpsDocumentWriter xps = PrintQueue.CreateXpsDocumentWriter(printQueue);
xps.Write(documentSequence, ticket);

mainDocRef = null;
newDocReference = null;

Now one thing to note is XpsDocument and PrintQueue inherit from IDisposable. (Dont need to tell you what to do there).
Now there could still be problems with the GetMainDoc() but as the reference to this method is not posted I cant test any errors here. Let me know how it goes.
Cheers. Nico


text:
Q: Javaee asyncContext object creating a new thread after dispatching I have the following code:
@WebServlet(urlPatterns="/Servlet1", asyncSupported=true)
public class Servlet1 extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Servlet1 doGet ..");
        AsyncContext ac =  request.startAsync();
        System.out.println(request.isAsyncStarted());
        ac.dispatch("/Servlet2");
        System.out.println("Servlet1 doGet after dispatch ..");
}

}

@WebServlet("/Servlet2")
public class Servlet2 extends HttpServlet {
    private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Servlet2 doGet ..");
}

}

Notice the following output:
Servlet1 doGet ..
true
Servlet1 doGet after dispatch ..
Servlet2 doGet ..

Notice the last 2 output lines?
I was expecting (just like a forward request dispatcher)
Servlet2 doGet
Servlet1 doGet after dispatch ..

Seems like ac.dispatch has created a new thread.
Any idea on this?
Thanks.

A: The behavior is described in the javadoc

This method returns immediately after passing the request and response
  objects to a container managed thread, on which the dispatch operation
  will be performed. If this method is called before the
  container-initiated dispatch that called startAsync has returned to
  the container, the dispatch operation will be delayed until after the
  container-initiated dispatch has returned to the container.

This makes sense, since you are in an asynchronous context.


text:
Q: React Checkbox Depends on Parent State In my parent component, I have a regular component that renders checked based off state and it can call a function:
<input
    name='shiftOne'
    type='checkbox'
    onChange={() => this.onCheck('shiftOne')}
    checked={this.state.shiftBools['shiftOne']}
/>

This works fine except for a warning in the console saying that I am switching from controlling and uncontrolling, but it doesn't break anything.
Trying to do the React way, I seperate this Checkbox out into it's function:
function Checkbox (props) {
  return (
    <div>
      <label>
        <input
          type='checkbox'
          name={props.name}
          checked={props.checked}
          onChange={() => props.handleCheckChange(props.name)}
        />
        {props.text}
      </label>
    </div>
  )
}
export default Checkbox

And then I render it in my Root App Component:
<Checkbox
    checked={this.state.shiftBools.shiftOne}
    name={'shiftOne'}
    onChange={() => this.handleCheckChange('shiftOne')}
    text={shiftOne[0] + ' ' + shiftTwo[1]}
/>

When I use the Checkbox functional component, it's on change doesn't work, it just always stays checked. Also, it doesn't even call the function in the onChange. I tried to console.log inside it and it's not called:
 handleCheckChange = () => {
    console.log(1)
    this.setState({
      shiftBools: {
        ...this.state.shiftBools,
        shiftOne: this.state.shiftOne
      }
    })
  }

I am trying to think more in React and just using the input in the parent class works fine, I'm just not sure why the functional component isn't working. All the data is in my parent state and whether the checkbox is checked or not depends on the data I have in that state.
* EDIT *
I changed the functional component to a Class component:
class Checkbox extends Component {
  constructor(props) {
    super(props);

    this.handler = this.handler.bind(this);
  }

  handler() {
    this.props.onCheck(this.props.name);
  }

  render() {
    return (
      <label>
        <input
          type="checkbox"
          name={this.props.name}
          checked={this.props.checked}
          onChange={this.handler}
        />
        {this.props.text}
      </label>
    );
  }
}

Now I deal with the parent function through a handler function. I also binded the parent function, as I wasn't before:
this.onCheck = this.onCheck.bind(this);

Now my checkbox is rendered in the parent function like so:
<Checkbox
  name={"shiftOne"}
  checked={this.state.shiftBools.shiftOne}
  onCheck={this.onCheck}
/>

This post helped me: How do I define methods in stateless components?
although my question was a little vague. Thanks for all your help.

A: You need to change the way you are calling onChange handler
Change
onChange={() => props.handleCheckChange(props.name)}

To
onChange={props.handleCheckChange(props.name)}

also, change the way of passing handler down has props to Checkbox component
<Checkbox
    checked={this.state.shiftBools.shiftOne}
    name={'shiftOne'}
    onChange={this.handleCheckChange('shiftOne')}
    text={shiftOne[0] + ' ' + shiftTwo[1]}
/>


text:
Q: Having images centred in columns I have three ToggleButton elements, each of which is a 50x70px image. I want these images centred in columns across the page (i.e. there are three columns, each of which takes up 1/3rd of the page's width, and each of which has an image centred horizontally inside it), but if I use a LinearLayout or TableLayout the images get stretched to become 33% of the page's width each. What should I be doing?
        <LinearLayout android:orientation="horizontal"
        android:id="@+id/buttonTable" android:layout_width="fill_parent"
        android:layout_below="@+id/tv_people" android:layout_height="wrap_content"
        android:layout_weight="1">
        <ToggleButton android:id="@+id/person1Button"
            android:gravity="center_horizontal" android:layout_weight="1"
            android:layout_width="51px" android:layout_height="68px"
            android:background="@drawable/person1_button" android:textOn=""
            android:textOff=""></ToggleButton>

        <ToggleButton android:id="@+id/person2Button"
            android:gravity="center_horizontal" android:layout_weight="1"
            android:layout_width="51px" android:layout_height="68px"
            android:background="@drawable/person2_button" android:textOn=""
            android:textOff=""></ToggleButton>

        <ToggleButton android:id="@+id/person3Button"
            android:gravity="center_horizontal" android:layout_weight="1"
            android:layout_width="51px" android:layout_height="68px"
            android:background="@drawable/person3_button" android:textOn=""
            android:textOff=""></ToggleButton>
    </LinearLayout>

A: The buttons are scaled to 1/3 of the screen just because android:layout_weight="1" has higher priority than android:layout_width="51px". To avoid this you can try to include each ToggleButton to its own LinearLayout. Like the following:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:id="@+id/buttonTable"
    android:layout_width="fill_parent"
    android:layout_below="@+id/tv_people"
    android:layout_height="wrap_content">
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:layout_weight="1">
        <ToggleButton android:id="@+id/person1Button"
            android:layout_width="51px"
            android:layout_height="68px"
            android:textOn=""
            android:textOff=""/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:layout_weight="1">
        <ToggleButton android:id="@+id/person2Button"
            android:layout_width="51px"
            android:layout_height="68px"
            android:textOn=""
            android:textOff=""/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:layout_weight="1">
        <ToggleButton android:id="@+id/person3Button"
            android:layout_width="51px"
            android:layout_height="68px"
            android:textOn=""
            android:textOff=""/>
    </LinearLayout>
</LinearLayout>

A: This layout code worked for me... (Note: this is your code)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent" android:gravity="center_horizontal"
  android:layout_height="wrap_content" android:orientation="horizontal">
        <ToggleButton android:id="@+id/person1Button"
            android:gravity="center_horizontal" android:layout_weight="1"
            android:layout_width="51px" android:layout_height="68px"
            android:textOn=""
            android:textOff=""></ToggleButton>

        <ToggleButton android:id="@+id/person2Button"
            android:gravity="center_horizontal" android:layout_weight="1"
            android:layout_width="51px" android:layout_height="68px"
            android:textOn=""
            android:textOff=""></ToggleButton>

        <ToggleButton android:id="@+id/person3Button"
            android:gravity="center_horizontal" android:layout_weight="1"
            android:layout_width="51px" android:layout_height="68px"
            android:textOn=""
            android:textOff=""></ToggleButton>
</LinearLayout>

It shows 3 toggle buttons at the top and shows them evenly spaced at the top which each took up 1/3 of the screen.
This most likely means that the scale of this layout is not related to why its streching.


text:
Q: Making a UIView landscape I have created an iPhone app, which is a tab bar application and only in portrait orientation.
From one tab  I am presenting a modal view which contain UIImage view.
Can I make landscape orientation only to that view while rotating iPhone to 90 degree?

A: yes , you can.
There are a few settings, code part which need to make it.
Depends also for which version, hopefully aren't targeting all supported by xcode, because it is horrible. Better choose only one, like the lastest iOS.


text:
Q: Elastic search relevance score In a project I'm involved with, Elastic Search is used to contain a couple of million items from a marketplace.
Users can search these items and currently the results returned are sorted by a relevance score based on the number of word occurences.
However the creation time of the items are also highly relevant - so a search for "bike" should return a list of items containing "bike" ordered by how new the item is (newer is more relevant).
I have no hands on with this myself (i'm more frontend than backend) so just need some guidance as to how this can be done? I read something about boosting scores but am unsure on whether that can be used.

A: Try to use the following structure:
"sort" : [
    {
        "YourValue" : {
            "order" : "desc"
        }
    }, {
        "_score" : { }
    }
]


text:
Q: Call SQL Stored Procedure with input "'abc','xyz'" I want to call:
EXEC [MyProcedure] @@param=' ';
                           |.| =  'string1','string2','string3','string4'
             This is one string: |---------------------------------------|

How can I achieve this? Using ''' didn't work for me.
--- This doesn't work:
EXEC [MyProcedure] @@param=''''string1','string2','string3','string4'''';
EXEC [MyProcedure] @@param='''string1','string2','string3','string4''';

A: You need to double up the single quotes inside the string:
EXEC [MyProcedure] @@param='''string1'',''string2'',''string3'',''string4''';


text:
Q: Is it possible to represent the derivative operator as an integral transform? Apparently, the Schwartz kernel theorem states that all linear operators can be represented as integral transforms (but only if you use generalized functions such as the dirac delta as kernels.) Representing the derivative operator as an integral transform would be really useful because then when defining strange and new generalizations of integrals one could automatically derive an appropriate generalization of derivatives to fit.

A: Yes, you can - but (somewhat disappointingly) the integral kernel for the derivative is just
$$
k(x,y) = -\delta^\prime(x-y)
$$ where $\delta^\prime$ is the derivative of the delta distribution, defined in the distributional sense i.e.
$$
\langle \delta^\prime(x-y),\varphi(y)\rangle = -\langle \delta(x-y),\varphi^\prime(y)\rangle = -\varphi^\prime(x)
$$
This is occasionally useful for manipulating expressions symbolically.  Also look into the single and double layer potential which express a similar idea for directional derivatives across surfaces and is a very useful concept in PDE.


text:
Q: How can I get the content on my page to update after a select option click? I have a feed. In that feed is a list of "posts". The feed can be updated with posts from different cities by selecting a new city from a list of select options. I use the Onymos service for my backend In my header I have interpolated the name of the default city in a title which is "new york". In the constructor I call a service I made that is set to populate the feed with new york posts on page load and update the feed on new city select.
I have the code working just fine that populates the feed with "new york" posts on load and changes the header title on new city selection. I can't however get the feed to update to show the posts from the newly selected city.
I've tried putting a page window.location.reload in different places but that either causes a crash and no page rendering or a glitchy select list that doesn't work.
HTML
<ion-header >
   <ion-navbar id="navbar" class="toolbar-background">

  <ion-toolbar>

        <ion-title id="title">
MyTitle{{selectedCity}}
</ion-title>
        <ion-buttons end>

<ion-icon id="icon" name="heart">Change City</ion-icon>

                <ion-select id="select" [(ngModel)]="selectedCity" (ionChange)="changeCity(selectedCity)" >
                        <ion-option value="New York">New York</ion-option>
                        <ion-option value="Philadelphia">Philadelphia</ion-option>
                        <ion-option value="Boston">Boston</ion-option>
                        <ion-option value="L.A.">L.A.</ion-option>
                        <ion-option value="San Francisco">San Francisco</ion-option>

               </ion-select>

         </ion-buttons>

      </ion-toolbar>
       </ion-navbar>

   </ion-header>

  <ion-content id="content">

     <ion-card id="card" *ngFor="let event of listOfEvents" >

       //Code for post info goes here on this card

    </ion-card>

</ion-content >

myService.TS
import { Injectable } from '@angular/core';

declare var OnymosUtil:any;

@Injectable()
export class getPosts {
constructor(){}

     listOfEvents: Array<any> = [];

     newCity: string;

/*Below is the service that gets the posts to populate the feed. I thought I could pass it a variable that could determine reload or not*/

getPosts(selectedCity,reloadPg){

   /*should there be a page refresh here?  */

if(reloadPg == true){
window.location.reload();
}

this.newCity = selectedCity;

let that = this;

    OnymosUtil.getData(

        '/events/' + this.newCity ,

        function successCallback (listOfEventsObject) {

                for (var x in listOfEventsObject) {

                   that.listOfEvents.push(listOfEventsObject[x]);
                }

        },

        function failureCallback (error) {
            alert(error);
        },

        {

            orderByField:'createdTime',
        });

    }//end getPosts

mainTS.
import { Component } from '@angular/core';
import { NavController, ModalController } from 'ionic-angular';
import { LoadingController } from 'ionic-angular';
import { getPosts } from '../../services/getPosts.service';

 declare var OnymosUtil:any;

@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
  providers: [getPosts]
})
export class Home {

     listOfEvents: Array<any> = [];

     selectedCity: string = 'New York';

     reloadPg: boolean;

 constructor (public navCtrl: NavController, public modalCtrl: ModalController, public loading: LoadingController, public getPostSrvc: getPosts) {

getPostSrvc.getPosts(this.selectedCity); /*this populates the feed with the default city's posts from New York*/

this.listOfEvents = getPostSrvc.listOfEvents;

}// end of constructor

/*here is where I tried to use a reload:*/

changeCity(selectedCity){

this.reloadPg = true;

           this.getPostSrvc.getPosts(selectedCity, this.reloadPg);

      };

}//close class

A: Here's a basic example on how to update the list. Granted the events are hard coded, but the idea remains the same.
import {Component, NgModule, VERSION, onInit} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

const events = [
  {
    city: 'New York',
    events: [
      {
        title: 'Comedy in Broadway',
        description: 'Get ready to pee your pants laughing'
      },
      {
        title: 'Puertorican Day Parad',
        description: 'Lots of traffic, loud music, great party!'
      }
    ]
  },
  {
    city: 'Chicago',
    events: [
      {
        title: 'Al Capone Memorial',
        description: 'Go back to the days of prohibition and how the gangsters ruled the city'
      },
      {
        title: 'White Sox vs Bears',
        description: 'Which is worse?'
      }
    ]
  }
];

@Component({
  selector: 'my-app',
  template: `

City: {{ currentEvent.city }}

 {{ e.title }}

            {{ e.description }}

      <button (click)="changeCity('Chicago')">View Chicago Events</button>
      <button (click)="changeCity('New York')">View New York Events</button>

  `,
})
export class App implements OnInit{
  name:string;
  currentEvent;
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }

  ngOnInit() {
    this.currentEvent = events.filter(event => event.city === 'New York')[0];
    console.log(this.currentEvent);
  }

  changeCity(city) {
    this.currentEvent = events.filter(event => event.city === city)[0];
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

Working Plnkr
In your case, instead of using .filter you would get the data from the service.
EDIT WITH SERVICE
*app.service.ts**
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class AppService {
  constructor(private http: Http) {}

  getAllEvents(): Promise<any>{
    return this.http.get('dummy_data.json').toPromise();
  }

  getEventsForCity(city): Promise<Array<any>> {
    let data = [];
    return new Promise((resolve, reject) => {
      this.getAllEvents().then(events => {
        events = events.json();
        data = events.filter(event => event.city === city)[0];
        if(!data) {
          return reject();
        }
        console.log(data);
        resolve(data):
      });
    });
  }
}

app.ts
//our root app component
import {Component, NgModule, VERSION, onInit} from '@angular/core'
import { HttpModule } from '@angular/http';
import {BrowserModule} from '@angular/platform-browser'
import { AppService } from './app.service';

@Component({
  selector: 'my-app',
  template: `

City: {{ currentEvent.city }}

 {{ e.title }}

            {{ e.description }}

      <button (click)="changeCity('Chicago')">View Chicago Events</button>
      <button (click)="changeCity('New York')">View New York Events</button>

  `,
})
export class App implements OnInit{
  currentEvent = {
    currentCity: '',
    events: []
  };
  constructor(private appSvc: AppService) {

  }

  ngOnInit() {
    this.appSvc.getAllEvents()
      .then(events => {
        events = events.json();
        this.currentEvent = events.filter(event => event.city === 'New York')[0];
      });
  }

  changeCity(city) {
    this.appSvc.getEventsForCity(city).then(events => this.currentEvent = events);
  }
}

@NgModule({
  imports: [ BrowserModule, HttpModule ],
  declarations: [ App ],
  bootstrap: [ App ],
  providers: [ AppService ]
})
export class AppModule {}

Service Plunkr


text:
Q: Hardware-level detection of USB3.0 vs USB2.0 I'm designing a USB battery charger, and I'm trying to use simple hardware (ICs are fine, just nothing that I have to upload firmware onto preferrably) to detect whether or not the USB socket I'm plugging the device into is USB3.0 or USB2.0, so I can safely determine how much current I can draw. I'm using a BQ2439RSER chip to determine if the socket I'm plugged into is a Standard Downstream Port, Charging Downstream Port, or a Dedicated Charging port. However, I'm running into trouble coming up with a simple way to check whether or not the host port is USB3.0 or USB2.0.
My initial thought was to check for pullups/pulldowns on any of the extra USB3 pins not present on a USB2 socket, however in all of the schematics I've looked at, the superspeed differential pairs have blocking capacitors on them (see page 11 of this datasheet http://www.ti.com/lit/an/slla329/slla329.pdf). My next though was to just check to see if the GND_DRAIN pin was connected to the common USB GND pin, but this post (USB3 with fewer wires) says that GND_DRAIN and GND are not necessarily going to be the same.
I don't need any of the RX/TX pairs to work or transmit data, I'm only interested in identifying maximum allowable current, and drawing it. I'm aware that some devices will limit me to 100mA, but in my experience these seem to be few and far between these days, so I'm willing to test the prototype without enumeration (worst case scenario I'll ad an FT232R host controller to take care of that later, but I'm trying to keep this as simple as possible).
Thanks for the help

A: Normally, the port capability is determined by device after connecting and configuring the USB interface. And then control the charger accordingly. But if the device you design does not have any USB, just a charger with a USB3 cable, you can use Rx-detect capability of the USB3 Tx channel, see section 6-11 of USB3.0 specifications.
Essentially you need to provide 45-Ohm termination on Tx -> Rx wires. The host will apply a pulse to Tx-/Tx+ wires, and watch for RC response time. This pulse might be difficult to detect however on Rx side. If the host detects the termination, it will start sending LFPS differential signals, Polling.LFPS, which are bursts at 10-50MHz and 1us in duration, repeated every 10us until timeout of 360ms, since your device will not respond. You should be able to detect this activity. Or maybe just any differential activity on Tx lines will give you a hint if the host port is USB3 or USB2.
Actually, you may want just to detect the Rx-detect activity without providing the termination, just a high-impedance single-ended receiver will do, since the host must periodically check for presence of Rx termination.


text:
Q: Is it OK to replace a 750 ohm 5W ceramic resistor with a 750 ohm 10W ceramic resistor One of four (4) 750 ohm 5w ceramic resistors in a subwoofer's power amp section seems to be open. I want to replace it with a compatible ceramic resistor.
Questions:

*

*Will the 10W one generate more heat?

*Is it OK to mix one 10W resistor with three (existing) 5W resistors? (All 750 ohms and 5% tolerance.)
[They are in the immediate proximity of transistors]
............................................................
Added on 2/2/17:
I think I was overlooking the importance of derating factors operating temperature range differences when resistors are used in audio amplifiers because audio amplifiers can get hot.

A: Is it OK to replace a 750 ohm 5W ceramic resistor with a 750 ohm 10W ceramic resistor?
Yes.
Will the 10W one generate more heat?
No.
Is it OK to mix one 10W resistor with three (existing) 5W resistors? (All 750 ohms and 5% tolerance.)
Yes.

A: *

*No more or less heat as total energy, but the 5W unit very likely runs hotter because its cooling is designed to be less effective due the smaller rating

*No problems in circuit's function because Ohm's law is the same. Mechanical problems can occur. I've seen, how heavier parts make mechanical resonance frequencies lower and their sheer mass is more tiring to the solder joints. If not mounted with glue or a proper clamp, it's well possible that the bigger parts rip themselves off sooner.


text:
Q: About topological conjugacy The Smale horseshoe map $f$ is desribed in this page: What's the point of a Horseshoe map?
A striking feature of this system is the stability of its dynamics: given any diffeomorphism $g$ sufficiently $C¹$-close to $f$, then there exist a homoemorphism $h$ such that $f∘h=h∘g$. This is the topological conjugacy.
My question is: Why the map $g$ should be of class $C¹$. Why this definition does not works with for example $C⁰$ or a discontinuous map $g$ considered as a small variation of the map $f$.


text:
Q: Is there a topological space which is star compact but not star countable? A topological space $X$ is said to be star compact if whenever $\mathscr{U}$ is an open cover of $X$, there is a compact subspace $K$ of $X$ such that $X = \operatorname{St}(K,\mathscr{U})$.
A topological space $X$ is said to be star countable if whenever $\mathscr{U}$ is an open cover of $X$, there is a countable subspace $K$ of $X$ such that $X = \operatorname{St}(K,\mathscr{U})$.
We know that there are some topological spaces which are star countable but not star compact. However I don't know whether star compact implies star countable. Is there a topological space which is star compact but not star countable?
Added: $St(K, \mathscr{U})=\cup\{u\in \mathscr{U}: u \cap K \neq \emptyset\}$

A: Let $X=\Big(\beta\omega_1\times(\omega_2+1)\Big)\setminus\Big((\beta\omega_1\setminus \omega_1)\times\{\omega_2\}\Big)$ as a subspace of $\beta\omega_1\times(\omega_2+1)$; I claim that $X$ is star compact.
Let $\mathscr{U}$ be an open cover of $X$. For each $\xi\in\omega_1$ there are $U_\xi\in\mathscr{U}$ and $\alpha_n\in\omega_2$ such that $$\langle \xi,\omega_2\rangle\in \{\xi\}\times(\alpha_n,\omega_2]\subseteq U_\xi\;.$$ Let $\alpha=\sup_\xi\alpha_\xi<\omega_2$, and let $K=\beta\omega_1\times\{\alpha+1\}$; $K$ is compact, and $$\omega_1\times \{\omega_2\}\subseteq \operatorname{st}(K,\mathscr{U})\;,$$ since $U_\xi\subseteq \operatorname{st}(K,\mathscr{U})$ for each $\xi\in\omega_1$. The ordinal space $\omega_2$ is countably compact, so $\beta\omega_1\times\omega_2$ is countably compact and therefore star finite, and there is a finite $F\subseteq \beta\omega_1\times\omega_2$ such that $\beta\omega_1\times\omega_2\subseteq\operatorname{st}(F,\mathscr{U})$. But then $K\cup F$ is compact, and $\operatorname{st}(K\cup F,\mathscr{U})=X$, as desired.
However, $X$ is not star countable. To see this, let $$\mathscr{U}=\{\beta\omega_1\times\omega_2\}\cup\Big\{\{\xi\}\times(\omega_2+1):\xi\in\omega_1\Big\}\;;$$ $\mathscr{U}$ is certainly an open cover of $X$, but if $C$ is any countable subset of $X$, we can choose $\xi\in\omega_1$ such that $C\cap\big(\{\xi\}\times (\omega_2+1)\big)=\varnothing$, and then $\langle \xi,\omega_2\rangle\notin\operatorname{st}(C,\mathscr{U})$.
This is a modification of Example 2.1 of Yan-Kui Song, On $\mathcal{K}$-Starcompact Spaces, Bull. Malays. Math. Soc. (2) 30(1) (2007), 59-64, which is available as a PDF here.


text:
Q: Symfony 3 OneUp Flysystem error: There is no extension able to load the configuration for "oneup_flysystem" According to the configuration of Flysystem i have put the following settings on my config.yml:
oneup_flysystem:
    adapters:
        acme.flysystem_adapter:
            awss3v3:
                client: acme.s3_client
                bucket: "%s3_bucket_name%"
                prefix: "symfotest_"

And I have provided the following settings on services.yml:
acme.s3_client:
        class: Aws\S3\S3Client
        arguments:
            -
                version: 'latest' # or 'latest'
                region: "%s3_region%" # 'eu-central-1' for example
                credentials:
                    key: "%s3_key%"
                    secret: "%s3_secret%"

End I have set the following enviromental variables via SetEnv:
SetEnv SYMFONY_S3_BUCKET_NAME   symphotest
SetEnv SYMFONY_S3_REGION    eu_west_1
SetEnv SYMFONY_S3_KEY       akey
SetEnv SYMFONY_S3_SECRET    asuperseccret

But I get the following error on my error.log:

[Wed Jul 06 21:11:56.424801 2016] [:error] [pid 21876] [client
  127.0.0.1:60488] PHP Fatal error:  Uncaught Symfony\Component\DependencyInjection\Exception\InvalidArgumentException:
  There is no extension able to load the configuration for
  "oneup_flysystem" (in
  /home/pcmagas/Kwdikas/web/apps/symphotest/app/config/config.yml).
  Looked for namespace "oneup_flysystem", found "framework", "security",
  "twig", "monolog", "swiftmailer", "doctrine", "sensio_framework_extra"
  in
  /home/pcmagas/Kwdikas/web/apps/symphotest/vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php:368\nStack
  trace:\n#0
  /home/pcmagas/Kwdikas/web/apps/symphotest/vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php(338):
  Symfony\Component\DependencyInjection\Loader\YamlFileLoader->validate(Array,
  '/home/pcmagas/K...')\n#1
  /home/pcmagas/Kwdikas/web/apps/symphotest/vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php(44):
  Symfony\Component\DependencyInjection\Loader\YamlFileLoader->loadFile('/home/pcmagas/K...')\n#2
  /home/pcmagas/Kwdikas/we in
  /home/pcmagas/Kwdikas/web/apps/symphotest/vendor/symfony/symfony/src/Symfony/Component/Config/Loader/FileLoader.php
  on line 118

Do you have any Idea hos is this fixed?

A: This happens when the OneUpBundle is not registered in the AppKernel. Add the corresponding bundle class to the other bundles in the registerBundles method and you should be golden.
For more information look here


text:
Q: Ionic 2 - Infinite Scroll on Large Screens I have a page with infinite scroll at the bottom and it is working well but the issue is that the app is meant for browsers also. On browsers, the first paginated result taking almost 50% of the page, and hence the infinite scroll is not working unless I resize down the browser and make it scroll down.
How can I fix this issue?


text:
Q: Javascript Newbie: if statements I'm practicing some JS by writing a little program that prompts our user to enter a date to determine whether the date will be a leap year or not.
I'm using if statements and Number.isInteger(userInput) to determine whether their input is valid or not.
My problem is that I can get most dates to work but as the rule applies to leap years, years that can be divided by 100 must also be able to be divived by 400 in order for the year to be recognized as a leap year.
With my current code, every year that is divisible by 4 is a valid year and I'm quite stumped.

    <button onclick="leapYear()">Check for leap year</button>

A: I had the wrong if's the entire time...thanks for reading though.

    <button onclick="leapYear()">Check for leap year</button>


text:
Q: How can I read a directory in Perl with one statement? I'm writing a script that looks for certain files in a directory and processes them.  I keep on writing the following:
opendir DIR, $dir;
@files = readdir DIR;
closedir DIR;

While I could (and in fact should) wrap this in a function, I was wondering if there's a more elegant way to do this?

A: Another way would be to use a do block:
my @files = do {
    opendir my $d, '/your/dir/';
    readdir $d;
};

Its more elegant because my $d is local to block (unlike your DIR global) and closedir isn't needed because the filehandle is automatically closed when $d went out of scope.
/I3az/

A: Most elegant is to use a function someone else has already written.
use File::Slurp;

@files = read_dir $dir;  # . and .. are removed by default

A: I like to use File::Find for this kind of thing.

A: No one has suggested glob yet? OK, here goes:
@files = glob("$dir/*");

Or if you need files that begin with a dot, too:
@files = glob("$dir/{.,}*")

A: glob is the simplest solution.  I do not know what you think the first three lines belong in a subroutine, unless you are opening the files more than once