text:
Q: Dynamically initializing JButtons with unique ImageIcons This is my first attempt at using a GUI layout in Java. I am trying to create a simple memory card game, where the user flips over two cards, and tries to get a match, and if there's no match they flip back over, if there's a match they stay flipped until you get all the matches. I might have made it hard on myself though in that I made the whole game dynamic to the constructor variables that define the number of columns and rows of cards. I thought this was better than hard-coding a certain value in, but now I'm having trouble putting the images in my img folder onto my cards.
I understand that variables of variables are not permitted in Java & this is really hard for me to adapt to as a ColdFusion developer. Can you help me think of ways to accomplish this this the proper way in Java?
Here is a simplified version of my code.
import javax.swing.JFrame;

public class MemoryApp
{
    public static void main(String args[])
    {
        //Creates a new game with 3 columns and 4 rows
        final CardGame myGame = new CardGame(3, 4);

        javax.swing.SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowGUI(myGame.getCols(), myGame.getRows());
            }
        });
    }

    private static void createAndShowGUI(int c, int r) {
        //Create and set up the window.
        Window frame = new Window("GridLayoutDemo", c, r);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Set up the content pane.
        frame.addComponentsToPane(frame.getContentPane());
        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }
}

Card game class:
public class CardGame
{
    private int cols, rows;

    public CardGame(int c, int r)
    {
        cols = c;
        rows = r;
    }

    public int getCols(){
        return cols;
    }

    public int getRows(){
        return rows;
    }
}

The window with the grid layout:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSeparator;

public class Window extends JFrame
{
    private int cols, rows;
    GridLayout windowGrid = new GridLayout(1,1);

    public Window(String t, int c, int r)
    {
        super(t);
        cols = c;
        rows = r;
        windowGrid.setColumns(c);
        windowGrid.setRows(r);
    }

    public void addComponentsToPane(final Container pane)
    {
        final JPanel compsToExperiment = new JPanel();
        compsToExperiment.setLayout(windowGrid);
        JPanel controls = new JPanel();
        controls.setLayout(new GridLayout(cols,rows));

        int countCard = (cols * rows) / 2;

        /**
         * Add buttons to experiment with Grid Layout.
         * This is where I'd like to be able to loop through
         * countCard and create the required number of buttons
         * as well as put images on the buttons like so:
         *
         * ImageIcon image1 = new ImageIcon(getClass().getResource("card1.png"));
         *  through
         * ImageIcon image1 = new ImageIcon(getClass().getResource("card" & cardCount & ".png"));
         *
         * Below is how I would attempt this in ColdFusion- I know
         * the variable of variables syntax is invalid, it is just
         * to show you what I mean.
         */

        // for(int i = 0; i < countCard; i++;)
        // {
        //      compsToExperiment.add(new JButton("../img/card" & i & ".png"));
        //      ImageIcon variables["image" & i] = new ImageIcon(getClass().getResource("card" & i & ".png"));
        //      imageButton.setIcon(variables["image" & i]);

        //      etc. with ButtonClickEventHandler, haven't gotten that far yet
        // }

        pane.add(compsToExperiment, BorderLayout.NORTH);
        pane.add(new JSeparator(), BorderLayout.CENTER);
    }
}

A: Based on the code commented-out code that you posted so far, one approach could be like this:
public class Window extends JFrame
{
    ...

    // A java.util.List that stores all the buttons, so
    // that their icons may be changed later
    private List<JButton> buttons = new ArrayList<JButton>();

    // A java.util.List that stores all the ImageIcons that
    // may be placed on the buttons
    private List<ImageIcon> imageIcons = new ArrayList<ImageIcon>();

    public void addComponentsToPane(final Container pane)
    {
        ...

        for(int i = 0; i < countCard; i++;)
        {
            // String concatenation is done with "+" in Java, not with "&"
            String fileName = "card" + i + ".png";

            // Create the icon and the button containing the icon
            ImageIcon imageIcon = new ImageIcon(getClass().getResource(fileName));
            JButton button = new JButton(imageIcon);

            // Add the button to the main panel
            compsToExperiment.add(button);

            // Store the button and the icon in the lists
            // for later retrieval
            imageIcons.add(imageIcon);
            buttons.add(button);

            // Attach an ActionListener to the button that will
            // be informed when the button was clicked.
            button.addActionListener(createActionListener(i));
        }
    }

    private ActionListener createActionListener(final int cardIndex)
    {
        return new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                clickedCardButton(cardIndex);
            }
        };
    }

    private void clickedCardButton(int cardIndex)
    {
        System.out.println("Pressed button for card "+cardIndex);

        // Here you can change the icons of the buttons or so...
        JButton button = buttons.get(cardIndex);
        ImageIcon imageIcon = imageIcons.get(cardIndex);
        ....
    }

You mentioned that this is your first attempt to build a GUI with Java. So I assume that this is only intended for "practicing". If your intention was to build a "real application", you should rather consider some Model-View-Controller (MVC) approach for this.


text:
Q: Cannot get second image animation to work - whats going on? I want to create a quick picture/movie viewer - for a birthday celebration.
First I want to show some pictures - then a movie - and then some pictures again. The first picture animation shows up fine, movie starts fine and catching AVPlayerItemDidPlayToEndTimeNotification just fine to launch pictures again, - but second animation never starts - I cannot work this out ?? - DoShow1 is not working - please advice anybody out there ??
- (void)DoShow
    {
        NSArray *imageNames = @[@"1.jpg", @"2.jpg", @"3.png", @"4.png",
                                @"5.png", @"6.png",@"7.png", @"8.png",
                                @"9.png", @"10.png", @"11.png",@"12.png",
                                @"13.png"];

        NSMutableArray *images = [[NSMutableArray alloc] init];
        for (int i = 0; i < imageNames.count; i++) {
            [images addObject:[UIImage imageNamed:[imageNames objectAtIndex:i]]];
        }

        _imageview.animationImages = images;
        _imageview.animationDuration = 10;
        _imageview.animationRepeatCount = 1;

        [_imageview startAnimating];

        [self performSelector:@selector(playmovie) withObject:nil afterDelay: 10];
    }

    - (void)DoShow1
        {

        NSArray *imageNames = @[@"14.jpg", @"16.jpg", @"18.jpg", @"19.jpg",
                                @"20.jpg", @"22.jpg",@"23.jpg", @"24.jpg"];

            NSMutableArray *images = [[NSMutableArray alloc] init];
            for (int i = 0; i < imageNames.count; i++) {
                [images addObject:[UIImage imageNamed:[imageNames objectAtIndex:i]]];
            }

            _imageview2.animationImages = images;
            _imageview2.animationDuration = 2;
            _imageview2.animationRepeatCount = 100;

            [_imageview2 startAnimating];
    }

    - (void) playmovie
    {

        MyMusicPlayerManager *sharedManager = [MyMusicPlayerManager sharedManager];
        [sharedManager ChkPaused];

        NSBundle *Bundle = [NSBundle mainBundle];
        NSString *moviePath = [Bundle pathForResource:@"stine_ane" ofType:@"mp4"];
        NSLog(@"String is %@", moviePath);
        NSURL *url = [NSURL fileURLWithPath:moviePath];

        AVPlayerItem *video = [[AVPlayerItem alloc] initWithURL:url];
        AVQueuePlayer *queue = [[AVQueuePlayer alloc] initWithItems:@[video]];
        video = [[AVPlayerItem alloc] initWithURL:url];

        [queue insertItem:video afterItem:nil];

        self.avmovieplayer =  [[AVPlayerViewController alloc] init];

        self.avmovieplayer.player = queue;

        [self presentViewController:self.avmovieplayer animated:YES completion:nil];

        self.avmovieplayer.player.actionAtItemEnd = AVPlayerActionAtItemEndNone;

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(myMovieFinishedCallback:)
                                                     name:AVPlayerItemDidPlayToEndTimeNotification
                                                   object:[avmovieplayer.player currentItem]];

        [self.avmovieplayer setShowsPlaybackControls:YES];
        [self.avmovieplayer.player play];

    }

    - (void)myMovieFinishedCallback:(NSNotification *)notification {
        [self dismissViewControllerAnimated:YES completion:Nil];

        [self DoShow1];
    }

    - (IBAction)DoStart:(id)sender {
        [self DoShow];
    }

A:     [self dismissViewControllerAnimated:YES completion:Nil];
    [self DoShow1];

this is probably calling in succession and animation doesnt start at the same time the view is being dismissed.

try it in the completion handler which is called after the view is
  dismissed

[self dismissViewControllerAnimated:YES completion:^{
        [self DoShow1];
    }];

redpajama_set_name: RedPajamaStackExchange


text:
Q: Real time process communication in game development If you make a game architecture that splits up system components (IE, rendering, physics, logic, input, scripting, etc) into different threads, how do you handle cases where real-time communication is necessary?
For example, if a script wants to draw a box on the screen, it would ideally do this when the rendering component issues a "FrameDrawn" event so that the box would be drawn on top of the screen, at the end of each frame draw. How is this possible if the scripting component and the rendering component are on different threads from each other?

A: Typically the rendering thread is the only one to ever draw things to the screen. However, since threads can communicate, it's possible for say the scripting thread to tell the rendering thread "Hey, I want to draw a box next frame."
The way our project handles thread communication is in one of two ways. For something that is dynamically edited - lists of objects, moving vehicles, et cetera, we create a mutex that locks the data when it is being changed. If the renderer wants to draw it, but the update thread is deleting that object, the renderer will have to wait. For other things, like the ui, we just have global flags that are written by the ui thread, and read by the renderer, so no mutex is required.

A: What most games will have is a massive pile of data and several threads referring to some subset of that data as needed. Communication between threads is rarely explicit and more commonly is implicit, done through a change in the data caused by one thread and noticed later by a second thread. The changes are protected by mutexes, semaphores, or other low-level synchronisation primitives.
For your drawing example, the scripting thread would change some data in the GUI component and the rendering thread, next time it renders the GUI, would see that new data and draw the box accordingly.
Bear in mind however that most game developers don't thread things quite so much as is in your example, partly because it's difficult to do that effectively with a model that shares so much data and relies on low level locking for correctness. Ideally more game developers would move towards a model that shares less data but that is difficult due to the soft-real-time presentation response requirements.

A: What you're asking for isn't really possible, which is why the general rule is to only have one UI thread. If another thread wants to show something on the screen, it should send a message to the UI thread which will show the message when it is rendering.


text:
Q: compare values in 2 excel sheets I am looking for a formula to look at any value in Column D on Sheet1 and compare it with any value in Column D on Sheet2 and if there is a match put TRUE in Column H in the row of the match of Sheet2. The Data does not match per cell# such as D3 Sheet1 = D3 Sheet2. It might be D3 Sheet1 = D2487 Sheet2.

A: Good morning man I think I have the solution for your problem:
Click here to see the imageIn the first cell of column H where you want to compare the values you'll write this


text:
Q: use jquery in React and get jquery_1.default(...).resizable is not a function I am using jquery with React. and when I want to use $(.myclass).resizable(). I got an error:use jquery in React and get jquery_1.default(...).resizable is not a function.
here is the demo:
https://stackblitz.com/edit/react-modal-rnd-2?file=rnd.js
import React from 'react';
import { render } from 'react-dom';
import { Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap';
import $ from 'jquery';

export default class RND extends React.Component {
  constructor() {
    super();

    $('.modal-content').resizable({
      //alsoResize: ".modal-dialog",
      minHeight: 300,
      minWidth: 300
    });
    $('.modal-dialog').draggable();

    $('#myModal').on('show.bs.modal', function() {
      $(this)
        .find('.modal-body')
        .css({
          'max-height': '100%'
        });
    });
  }

  modalClose = () => {
    this.setState({
      modalShow: false
    });
  };

  onStart = () => {
    console.log('here');
  };

  render() {
    return (
      <Modal
        isOpen={this.state.showModal}
        toggle={() => {
          this.setState({ showModal: false });
          this.modalClose();
        }}
        style={{
          minWidth: '30rem',
          border: '0.1rem solid green'
        }}
      >
        <ModalHeader
          className="modal-header bg-primary modal-title text-white"
          toggle={() => {
            this.setState({ showModal: false });
            this.modalClose();
          }}
        >

 Header

        </ModalHeader>
        <ModalBody>

              Body data

        </ModalBody>
      </Modal>
    );
  }
}

what I want is to make the popup modal resizable and draggable.it also works for me if there is a way to achieve it without jquery.

A: I've found a solution.
step1:
npm i jquery-ui
step2:
add these sources in jsx file
import 'jquery-ui/themes/base/resizable.css';
import 'jquery-ui/themes/base/draggable.css';

require('jquery-ui/ui/version');
require('jquery-ui/ui/plugin');
require('jquery-ui/ui/widget');
require('jquery-ui/ui/widgets/mouse');
require('jquery-ui/ui/widgets/resizable');
require('jquery-ui/ui/widgets/draggable');

and then you can use jquery-ui function.


text:
Q: Tweet on user profile using Twit package I am trying to create a tweet to the user profile using twit package. This is the code I am using. By using this code I am able to tweet to my profile because I have access_token and access_token_secret. My question is If I want to tweet to some other people's profile. What is the procedure to do it I am not able to understand? I am using passport library to get the user details.
var Twit = require('twit');

var T = new Twit({
  consumer_key: '************',
  consumer_secret: '**********',
  access_token: '******************',
  access_token_secret: '******************',
  timeout_ms: 60 * 1000,
  strictSSL: true,
})

T.post('statuses/update', {status: 'hello world! '}, function(err, data, response) {
  console.log('post on ',data);
})

Below down is my passport authentication code
'use strict';

require('dotenv').config();

const path = require('path');
const express = require('express');
const passport = require('passport');
const { Strategy } = require('passport-twitter');
const { TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, SESSION_SECRET } =  process.env;
const port = process.env.PORT || 3000;
const app = express();
const routes = require('./routes');

passport.use(new Strategy({
    consumerKey: TWITTER_CONSUMER_KEY,
    consumerSecret: TWITTER_CONSUMER_SECRET,
    callbackURL: '/return'
  },
  (token, tokenSecret, profile, cb) => {
    console.log(token);
    console.log(tokenSecret);
    console.log(profile);
        return cb(null, profile);
}));

passport.serializeUser((user, cb) => {
  cb(null, user);
});

passport.deserializeUser((obj, cb) => {
  cb(null, obj);
});

app.set('view engine', 'ejs');

app.use('/public', express.static(path.join(__dirname, 'public')));

app.use(require('express-session')({ secret: SESSION_SECRET, resave: true, saveUninitialized: true }));

app.use(passport.initialize());
app.use(passport.session());
app.use('/', routes);

app.listen(port);

another file
'use strict';

const express = require('express');
const passport = require('passport');
const router = express.Router();

router.get('/', (req, res, next) => {
    const { user } = req;
    console.log('user details', req.user);
    // res.render('home', { user });
});

router.get('/login/twitter', passport.authenticate('twitter'));

router.get('/logout', (req, res, next) => {
  req.logout();
  res.redirect('/');
});

router.get('/return',
  passport.authenticate('twitter', { failureRedirect: '/' }),
  (req, res, next) => {
    res.redirect('/');
});

module.exports = router;

A: Got the answer following these steps.  https://developer.twitter.com/en/docs/basics/authentication/oauth-1-0a


text:
Q: How do I make a pygame trivia question appear in the entry widget I'm trying to create a trivia game using pygame. The first trivia question appears on the entry widget. However, I want the second question to appear in the entry widget once the first question has been answered correctly.
Also If at any point the player selects a wrong answer I want the game to exit/end.
Apologies for the long line of code. I would have loved to put the question and answer in a text file instead of coding them directly inside python, but I obviously don't know how to do go about it.
from tkinter import *
import tkinter as tk
import pygame as py
from PIL import ImageTk, Image
import time, random, sys
from pygame.locals import *

py.init()
py.mixer.init()
root=Tk()
root.title("Who Wants To Be A Millionaire")
root.geometry=('1352x625+0+0')
root.configure(background ='black')
abc= Frame(root, bg = 'black')
abc.grid()

abc1= Frame(root, bg = 'black', bd=20, width=900, height=600)
abc1.grid(row=0, column=0)
abc2= Frame(root, bg = 'black', bd=20, width=452, height=600)
abc2.grid(row=0, column=1)

abc1a= Frame(abc1, bg = 'black', bd=20, width=900, padx=110, height=200)
abc1a.grid(row=0, column=0)
abc1b= Frame(abc1, bg = 'black', bd=20, width=900, height=200)
abc1b.grid(row=1, column=0)
abc1c= Frame(abc1, bg = 'black', bd=20, width=900, height=200)
abc1c.grid(row=2, column=0)

#===========================================Trivia Questions==============================================

question1 = StringVar()
question2 = StringVar()
question3 = StringVar()
question4 = StringVar()
question5 = StringVar()
question6 = StringVar()
question7 = StringVar()
question8 = StringVar()
question9 = StringVar()
question10 = StringVar()
question11 = StringVar()
question12 = StringVar()
question13 = StringVar()
question14 = StringVar()
question15 = StringVar()

choice1 = StringVar()
choice2 = StringVar()
choice3 = StringVar()
choice4 = StringVar()

question1.set("What's the capital of Nigeria")
choice1.set('Mongoria')
choice2.set('Cairo')
choice3.set('Accra')
choice4.set('Abuja')

question2.set(" Which one of the color can be found in US National Flag")
choice1.set("Green")
choice2.set('Red')
choice3.set('Orange')
choice4.set('Yelow')

question3.set("What is 5000 x 110")
choice1.set("55,110")
choice2.set('56,100')
choice3.set('50,000')
choice4.set('55,000')

question4.set("Whitney Houston died in which year")
choice1.set("2013")
choice2.set('2010')
choice3.set('2012')
choice4.set('2011')

question5.set("How many countries are there in Africa")
choice1.set("32")
choice2.set('43')
choice3.set('45')
choice4.set('30')

#===========================================Text-Labels-Button==============================================
textQues= Entry(abc1c, font= ('arial',18, 'bold'), bg='black',fg='white', bd= 2, width=50, justify= CENTER,textvariable= question1)
textQues.grid(row=0, column=0, columnspan=10, pady=4)

label_option1= Label(abc1c, font= ('arial',14, 'bold'), text='A: ', bg='black',fg='white', bd= 5, justify = CENTER)
label_option1.grid(row=2, column=0, pady=4, sticky=W)
text_option1= Button(abc1c, font= ('arial',14, 'bold'), bg='blue',fg='white', bd= 5, width=17, height= 2, justify = CENTER, textvariable=choice1)
text_option1.grid(row=2, column=1, pady=4)

label_option2= Label(abc1c, font= ('arial',14, 'bold'), text='B: ', bg='black',fg='white', bd= 5, justify = CENTER)
label_option2.grid(row=2, column=2, pady=3, sticky=W)
text_option2= Button(abc1c, font= ('arial',14, 'bold'), bg='blue',fg='white', bd= 5, width=17, height= 2, justify = CENTER, textvariable=choice2)
text_option2.grid(row=2, column=3, pady=4)

label_option3= Label(abc1c, font= ('arial',14, 'bold'), text='C:', bg='black',fg='white', bd= 5, justify = CENTER)
label_option3.grid(row=3, column=0, pady=4, sticky=W)
text_option3= Button(abc1c, font= ('arial',14, 'bold'), bg='blue',fg='white', bd= 5, width=17, height= 2, justify = CENTER, textvariable=choice3)
text_option3.grid(row=3, column=1, pady=4)

label_option4= Label(abc1c, font= ('arial',14, 'bold'), text='D: ', bg='black',fg='white', bd= 5, justify = CENTER)
label_option4.grid(row=3, column=2, pady=4, sticky=W)
text_option4= Button(abc1c, font= ('arial',14, 'bold'), bg='blue',fg='white', bd= 5, width=17, height= 2, justify = CENTER, textvariable= choice4)
text_option4.grid(row=3, column=3, pady=4)

raytxt=Label(abc2,font=('Cambri', 12, 'italic'), text='Built by: Raymond French ', bg='black', fg='white', bd= 5, justify= CENTER)
raytxt.grid(row=1, column=0)

root.mainloop()

A: You should keep quetion, choices and correct answer on list. Later you can read data from file
This way don't have to create so many widgets. You can create widgets without text and use function which put/replace question and choices in widgets.
When you click answer it should run function which check if selected answer is correct. And then you can run again function which replace text in widget.
I create minimal working example only with important elements. And now code is much shorter.
import tkinter as tk

def set_question(number):
    global correct_answer

    row = all_questions[number]

    question.set(row[0])

    choice_a.set(row[1])
    choice_b.set(row[2])
    choice_c.set(row[3])
    choice_d.set(row[4])

    correct_answer = row[5]

def selected(selected_number):
    global current_question

    if selected_number != correct_answer:
        print('Game Over')
        root.destroy()
    else:
        current_question += 1
        if current_question >= len(all_questions):
            current_question = 0
        set_question(current_question)

all_questions = [
    #[question, choice_a, choice_b, choice_c, choice_d, correct_answer],
    ["What's the capital of Nigeria", 'Mongoria', 'Cairo', 'Accra', 'Abuja', 4],
    ["Which one of the color can be found in US National Flag", "Green", 'Red', 'Orange', 'Yelow', 2],
    ["What year is today", "2017", '2018', '2019', '2020', 3],
]

current_question = 0

root = tk.Tk()

top_frame = tk.Frame(root)
top_frame.grid(row=2, column=0)

question = tk.StringVar()
choice_a = tk.StringVar()
choice_b = tk.StringVar()
choice_c = tk.StringVar()
choice_d = tk.StringVar()

# create Widgets for question and choices but without text
textQues = tk.Entry(top_frame, textvariable=question)
textQues.grid(row=0, column=0, columnspan=10)

label_option1 = tk.Label(top_frame, text='A:')
label_option1.grid(row=2, column=0)
text_option1 = tk.Button(top_frame, textvariable=choice_a, command=lambda:selected(1))
text_option1.grid(row=2, column=1)

label_option2 = tk.Label(top_frame, text='B:')
label_option2.grid(row=2, column=2)
text_option2 = tk.Button(top_frame, textvariable=choice_b, command=lambda:selected(2))
text_option2.grid(row=2, column=3)

label_option3 = tk.Label(top_frame, text='C:')
label_option3.grid(row=3, column=0)
text_option3 = tk.Button(top_frame, textvariable=choice_c, command=lambda:selected(3))
text_option3.grid(row=3, column=1)

label_option4 = tk.Label(top_frame, text='D:')
label_option4.grid(row=3, column=2)
text_option4 = tk.Button(top_frame, textvariable=choice_d, command=lambda:selected(4))
text_option4.grid(row=3, column=3)

# put first question in Widgets
set_question(current_question)

root.mainloop()

BTW: and use variable's names which means something - ie. top_frame instead of abc


text:
Q: Got 'Cannot find module' error when I tried to import certain JS file I am currently learning JS and this is codes from practice.
(which is from YDKJSY)
This is a publication.js
function printDetails(title,author,pubDate) {
    console.log(`
    Title: ${ title }
    By: ${ author }
    ${ pubDate } `
    );
}
export function create(title,author,pubDate) {
    var publicAPI = {
        print() {
            printDetails(title,author,pubDate);
        }
     };
return publicAPI;
}

And this blogpost.js import publication.js
import { create as createPub } from "publication.js";
function printDetails(pub,URL) {
    pub.print(); console.log(URL);
}
export function create(title,author,pubDate,URL) {
    var pub = createPub(title,author,pubDate);
var publicAPI = { print() { printDetails(pub,URL);
        }
    };
return publicAPI;
}

And finally main.js import blogpost.js
import { create as newBlogPost } from "blogpost.js";
var forAgainstLet = newBlogPost(
    "For and against let",
    "Kyle Simpson",
    "October 27, 2014",
    "https://davidwalsh.name/for-and-against-let"
);

I converted these code by babel and got converted codes.
PS C:\users\leepc\babel> npm run build
> babel@1.0.0 build C:\users\leepc\babel
> babel ./public/src -d ./public/lib -w

public\src\blogpost.js -> public\lib\blogpost.js
public\src\main.js -> public\lib\main.js
public\src\publication.js -> public\lib\publication.js

but when I do npm run build and tried to run main.js I got this,
PS C:\users\leepc\babel\public\lib> node main.js
internal/modules/cjs/loader.js:984
  throw err;
  ^

Error: Cannot find module 'blogpost.js'
Require stack:
    at Module.require
(internal/modules/cjs/loader.js:1043:19)
    at require (internal/modules/cjs/helpers.js:77:18)
    at Object.<anonymous>
(C:\users\leepc\babel\public\lib\main.js:3:17)
    at Module._compile
(internal/modules/cjs/loader.js:1157:30)    3:17)
    at Object.Module._extensions..js
(internal/modules/cjs/loader.js:117
7:10)
    at Module.load (internal/modules/cjs/loader.js:1001:32)
    at Function.Module._load
(internal/modules/cjs/loader.js:900:14)

    at Function.executeUserEntryPoint [as runMain]
(internal/modules/run
_main.js:74:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
'C:\\users\\leepc\\babel\\public\\lib\\main.js' ]

}

I checked whether I forgot any installment.
PS C:\users\leepc\babel> npm ls --depth=0
babel@1.0.0 C:\users\leepc\babel
+-- @babel/core@7.8.4
+-- babel-cli@6.26.0
+-- babel-preset-env@1.7.0
`-- babel-preset-es2015@6.24.1

Lastley, about .babelrc
{
  "presets": ["env"]
}

and package.json build,
{
    ...
    "build": "babel ./public/src -d ./public/lib -w"
  }

I used node.js preset, but it got weird errors so I just left if with "env".
Sorry for a messy and long code, but I have been trouble for this problem these days and can't get to further studying.
Please let me know is there any other information I have to post and edit in this question.
edit:
is this maybe becasue I put all of this files in a same folder?
should I have to put these in a certain different folder?
This is a picture of my practice project folder

A: please try to have your modules relative to your file for importing. Usually, the imports with no paths are for node_modules.
import { create as newBlogPost } from "./blogpost.js";
// or wherever your blogpost.js is relative to your main.js
...

A: Okay it turns out, I should combine both of answers above.
First, I have to check whether my import plugin is right or wrong.
So I just re-installed it.
npm install babel-plugin-import --save-dev

Make sure not to forget put plugin opitions. In my cases, I use this in .babelrc
{
    "presets": ["es2015"],
    "plugins": [["import", { "libraryName": "antd" }]]
}

this "plugins": [["import", { "libraryName": "antd" }] line means import js modulary.
And also next stuff, I have to make import path to be corrected.
import { create as newBlogPost } from "blogpost.js";

change this to
import { create as newBlogPost } from "./blogpost.js";

By doing this, now I can get a result that I wanted so far.
PS C:\Users\leePC\babel\public\lib> node main.js

    Title: For and against let
    By: Kyle Simpson
    October 27, 2014

So majorly,
1. Check whether I missed some plugins or packages ( in my cases, I forgot import package )
2. Make sure to check your import path
Thank you for help guys.

A: Have you followed the setup steps from https://www.npmjs.com/package/babel-plugin-import ?
npm install babel-plugin-import --save-dev

In .babelrc
{
  "plugins": [["import", options]]
}


text:
Q: JAVASCRIPT/Chrome: How to Get Extension of Page Given
google.com

How can I get .com and save it to a variable. I was thinking of using regex to split google.com into google and ".com", but I don't know the regex to do this.
It might help to know that I got the hostname from using window.location.hostname
Thank you!

A: You can split the location by ., and the last value in the array will be the extension.  Something like this would work:
var extension=location.hostname.split(".");
extension=extension[extension.length-1];

console.log(extension)

JS Fiddle Example: https://jsfiddle.net/igor_9000/yvy0zrat/
Hope that helps!

A: You could use a substring and lastIndexof:
var str =  window.location.hostname;
var ending = str.substring(str.lastIndexOf(".")+1);

https://jsfiddle.net/06r86q0n/
Mostly the same as the other answer, but neither helps with double domains like ".co.uk"

A: Do not use split, its a bit slower than slice:
var last = location.hostname
var t = last.slice(last.lastIndexOf("."));

console.log(t) // .com, .net etc...

Fiddle: https://jsfiddle.net/1qu0rffb/

A: If you are looking to create a regex statement that will only grab the .com then I would use something like:
/(.com)/ as your Regex statement
so your code would look like something like this:
var regexMatch = /(.com)/; as a regular expression literal
or
var regexMatch = new RegExp(".com"); as constructor function of the RegExp object.


text:
Q: React native scroll Text horizontal How to create a text scrolling bar in react native?
Like that of news scroll. Is it possible without using Animation library?

A: If you want a user-controlled scroll you have a component for this - ScrollView

Here's a link to the official documentation - https://facebook.github.io/react-native/docs/scrollview.html

If you want it to scroll automatically you need you use ScrollView with the Animated library or use ScrollView's scrollTo function.


text:
Q: MySQL InnoDB table shows a negative number of rows in phpMyAdmin I just converted a MyISAM table to InnoDB with around 1.4 million rows.  When I converted it to InnoDB, it now shows -1.4 million rows.  The table still works as expected, but why does it shows negative in the rows column?

A: If you look closely, you'll notice it's not a negative sign, it's a tilde, which means "approximately".
InnoDB tables do not store the exact count of rows in the table, so you are being shown approximately how many rows are in the table.
If you use the COUNT(*) function you can retrieve the exact number of rows.

A: I think that could be a bug of phpmyadmin ...
What version are you using?
If you do a SELECT COUNT(*) FROM table from MySQL command prompt, what number is displayed?


text:
Q: SonarQube: Create HTML reports without run sonar:sonar command In Sonar, we just download the sonar setup and if need, change the db credentials and run the command on maven project sonar:sonar, our coding stats and bugs are are analyzed by sonar and make the good html reports. But for this we need to run sonar:sonar command. Like findbugs, its possible to integrate with maven and create reports and time of maven:install .In this LINK at 4th step explain. Is also possible with sonar for make the report on maven:install command?

A: Like you can see on the SonarQube documentation, we strongly advise you to first run mvn clean install and then mvn sonar:sonar separately - otherwise you can have some side effects.
However, if you want to have all this in a single run, this is a Maven-related question. You just have to bind the "sonar" goal to the "install" phase in your POM, with something like:
...
<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>sonar-maven-plugin</artifactId>
            <executions>
                <execution>
                    <phase>install</phase>
                    <goals>
                        <goal>sonar</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
...


text:
Q: rsync cannot delete non-empty directory When syncing my remote backup I get the error rsync cannot delete non-empty directory.
I know the cause: I have excluded some files and when rsync tries to delete a remote directory because it doesn't exists locally, it can't since it is not empty. Without the exclusion the directory would be emptied.
I also know I could get rid of the problem by using --delete-excluded, but that is not want I want.
I would like to skip uploading certain files (because they are too big for my upload speed), but I want to keep those I have already uploaded some time ago if they exist locally. If they do not exist locally, they should be deleted. --delete-excluded would delete them all on the remote side.
That also means that if a directory doesn't exists anymore locally, it should be deleted even if it contains excluded files.
Is it possible to setup rsync to accomplish this?

A: Use the p modifier:

A  p  indicates  that  a  rule is perishable, meaning that it is
  ignored in directories that are being deleted.  For
                instance, the -C option's default rules that exclude things like "CVS" and "*.o" are marked as perishable, and  will
                not prevent a directory that was removed on the source from being deleted on the destination.

For example, I use the -F option, which "tells rsync to look for per-directory .rsync-filter files that have been sprinkled through  the  hierarchy  and use their rules to filter the files in the transfer."
My .rsync-filter contains lines like these to filter out these "droppings" that Macs leave behind them:
-p .DS_Store
-p ._*

If using exclude instead of just -, add a comma. For example :
exclude,p .DS_Store
exclude,p Thumbs.db

A: You can use modifiers of include/exclude pattern, add -s on the pattern you used. It tell rsync that exclude rule only for send-side.
-n : only check what will delete on desc, don't delete
pattern: *.sh
desc: /home/kg/tmp
aim:
want to delete file end of .sh on desc, but if you do this, you can't delete on the desc:
rsync -rvz --exclude *.sh --delete -n conkg kg@192.168.31.202:/home/kg/tmp
should change to : please add -n when you test
test: rsync -rvz --exclude-from del.txt -n --delete  conkg kg@192.168.31.202:/home/kg/tmp
real delete: rsync -rvz --exclude-from del.txt  --delete  conkg kg@192.168.31.202:/home/kg/tmp
cat del.txt
-s*.sh
or:
rsync -rvz --exclude -s*.sh --delete  conkg kg@192.168.31.202:/home/kg/tmp

A: You could force deletion with this option:
 --force                 force deletion of directories even if not empty

A: just use the '--max-size=xx' and '--delete' options of rsync. It will do everything automatically and meet all your requirements.


text:
Q: How to find the maximum Eulerian sub-graph in an un-directed given graph? Given the next graph:

How do i find the maximum Eulerian sub-graph?
The correct answer should be this one (sub-graph with blue edges):

is there any algorithm to archive this? at least for small graphs like this one.


text:
Q: Centre text horizontal and vertical in element i'm trying to center some text vertically and horizontal in my #modal element:
#modal
{
background: gray;
    color: white;
    white-space: nowrap;
    width: 427px;
    height: 999px;
}

http://jsfiddle.net/4js3runn/

    CENTRE THIS

A: see the jsfiddle code :
http://jsfiddle.net/4js3runn/1/
#modal {
    background: none repeat scroll 0 0 gray;
    color: white;
    float: left;
    height: 100vh;

    position: relative;
    width: 100%;
}
.center {
    background-color: #444;
    height: 30px;
    left: 50%;
    line-height: 30px;
    margin-left: -56px;
    margin-top: -15px;
    position: absolute;
    text-align: center;
    top: 50%;
    width: 112px;
}

CENTRE THIS


text:
Q: Checking indexes were also restored... Postgres I made a backup of a whole PostgreSQL database that has indexes on several of its tables. I restored some of those tables using a cmd like:
pg_restore -h localhost -p 5432 -U jckusr -d mydb4test -t mytable2restore dbbackupdump.pgdmp

How can I be sure that the respective indexes were also restored? I did not exclude indexes during the backup process.


text:
Q: Importing a sample from an already imported library in android In android studios, I have successfully imported a library called ChatKit(https://github.com/stfalcon-studio/ChatKit). The creators of the library were kind enough to include a fully working sample within the library. Instead of recreating the process I want to import the sample from the library into my project but android studios is not allowing me to do so.
In my main activity, I can add :
import com.stfalcon.chatkit.dialogs.DialogsList;

But when cannot add:
import com.stfalcon.chatkit.sample.ChatSamplesListAdapter;

So I'm curious what other people have done to import a sample from an already imported library.
Thank you.

A:
import com.stfalcon.chatkit.sample.ChatSamplesListAdapter;

It happens because this class is not included in the library.
It is a sample file used as sample.
As you can see it is just a simple RecyclerView.Adapter then you can copy it in your project or you can use a own adapter.


text:
Q: Cannot create Multiple Ids but yet I only have one As you see I am creating a new class with one primary key I droped the db to recreate it but
public class CustomerContracts
{
    [Key, Column("ItemId")]  //This change the name of the column when you are using migration.  If you have a form created already, you have to change the connection in the for to aim the new column name.

    public int ItemId { get; set; }

    public string Description { get; set; }

    public string CustomerRef { get; set; }

    public int ContractTypeId { get; set; }

    public DateTime StartDate { get; set; }

    public DateTime EndDate { get; set; }

    public bool isActive { get; set; }
    [DecimalPrecision(18, 2)]
    public decimal Price { get; set; }

}

But I am receiving the following error when I try to update the database.

Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
  Applying explicit migrations: [201804260855058_firstmigration].
  Applying explicit migration: 201804260855058_firstmigration.
  System.Data.SqlClient.SqlException (0x80131904): Multiple identity columns specified for table 'CustomerContracts'. Only one identity column per table is allowed.
     at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)
     at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)
     at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
     at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
     at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
     at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
     at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
     at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext1 c)
     at System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func3 operation, TInterceptionContext interceptionContext, Action3 executing, Action3 executed)
     at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
     at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
     at System.Data.Entity.Migrations.DbMigrator.ExecuteSql(MigrationStatement migrationStatement, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
     at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ExecuteSql(MigrationStatement migrationStatement, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
     at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable1 migrationStatements, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
     at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinTransaction(IEnumerable1 migrationStatements, DbTransaction transaction, DbInterceptionContext interceptionContext)
     at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinNewTransaction(IEnumerable1 migrationStatements, DbConnection connection, DbInterceptionContext interceptionContext)
     at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable1 migrationStatements, DbConnection connection, DbInterceptionContext interceptionContext)
     at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable1 migrationStatements, DbConnection connection)
     at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClass32.<ExecuteStatements>b__30()
     at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
     at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func1 operation)
     at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)
     at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable1 migrationStatements, DbTransaction existingTransaction)
     at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable1 migrationStatements)
     at System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteStatements(IEnumerable1 migrationStatements)
     at System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, VersionedModel targetModel, IEnumerable1 operations, IEnumerable1 systemOperations, Boolean downgrading, Boolean auto)
     at System.Data.Entity.Migrations.DbMigrator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
     at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
     at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable1 pendingMigrations, String targetMigrationId, String lastMigrationId)
     at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
     at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
     at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClasse.b__d()
     at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
     at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
     at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
     at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
     at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore()
     at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()
  ClientConnectionId:8aa18649-614e-4be4-a46d-fb780984d59f
  Error Number:2744,State:2,Class:16
  Multiple identity columns specified for table 'CustomerContracts'. Only one identity column per table is allowed.

Why would I be getting this error. As you can see, I am using only one key nor am I renaming it (it's a new table as I dropped the db).  Any help be appreciated.
Here is my migration I deleted the folder after i deleted the db and yet its still putting info into up and down.
 public partial class firstmigration : DbMigration
    {
        public override void Up()
        {
            DropPrimaryKey("dbo.CustomerContracts");
            AddColumn("dbo.CustomerContracts", "ItemId", c => c.Int(nullable: false, identity: true));
            AddPrimaryKey("dbo.CustomerContracts", "ItemId");
            DropColumn("dbo.CustomerContracts", "TeamId");
        }

        public override void Down()
        {
            AddColumn("dbo.CustomerContracts", "TeamId", c => c.Int(nullable: false, identity: true));
            DropPrimaryKey("dbo.CustomerContracts");
            DropColumn("dbo.CustomerContracts", "ItemId");
            AddPrimaryKey("dbo.CustomerContracts", "TeamId");
        }
    }

A: Try this:
public override void Up()
{
    DropPrimaryKey("dbo.CustomerContracts");
    DropColumn("dbo.CustomerContracts", "TeamId"); // Drop this first
    AddColumn("dbo.CustomerContracts", "ItemId", c => c.Int(nullable: false, identity: true));
    AddPrimaryKey("dbo.CustomerContracts", "ItemId");
}


text:
Q: Don't work ide-haskell for atomeditor I tried to install atom.
I go to Properties->packages and then find ide-haskell and then install them. But it doesn't work. On the main page of ide-haskell author wrote that in ~/.atom/config.scon should be section named "ide-haskell", but i can't find it. What i missed? What I should do to run ide-haskell?
My OS Ubuntu 14.04


text:
Q: Corrugated tracks in PCB I've noticed that on some PCBs, there are some undulating tracks.
An example can be seen on the Compute Module IO for Raspberry Pi Compute Module 4 (CM4).

Apparently, these are high frequency tracks.
What is the function of these ripples? How do I calculate these ripples for the design of my boards containing high frequency communications?
I would like to know more about it, so I can research it.
I am developing a board containing the CM4. So maybe I have to use that kind of trail.
Thank you
Edit:
As I understand it, the main function of corrugation is to make all tracks with a certain function have the same length.
We must add the corrugation where the problem starts. If we don't, the differential impedance designed for the board fails.

A: High speed differential tracks must be equal path length end to end in order to prevent propagation skew in differences , in this case on the other side. This is often done for DDR memory.
But this example would have sub-optimal crosstalk with the same gap pair and adjacent tracks, but may be a non-issue for synchronous data.
It could also be overkill for a difference in path length of 20 picoseconds.


text:
Q: Gradient of Distance Function to a Hypersurface If $S\subset \mathbb{R}^n$ is a compact smooth hypersurface and $d(x)=dist(x,S)$, I know from the tubular neighborhood theorem that $d$ is smooth in a neighborhood of $S$.
A material I'm reading is using that $Dd(x)=N(\pi(x))$, where $N$ is a normal field to S (Gauss map) and $\pi$ is the projection onto the surface, that is, $\pi(x)$ is the nearest point to $x$ in the surface. This result seems intuitevely clear, but I haven't been able to prove it.
Can somebody provide a proof or a reference that proves this claim? Any help is appreaciated.


text:
Q: How to draw an image? How can I make this kind of graph by tikz?

A: \documentclass{article}

\usepackage{tikz}
\usetikzlibrary{shapes.arrows}

\newcommand{\arr}[2]{
    \draw[->] #1 -- #2;
    \filldraw #1 circle(0.5pt);
}
\newcommand{\carr}[5]{
    \draw[->,rotate around={#5}] #1 arc[x radius=#4cm, y radius =#4cm, start angle=#2, end angle=#3];
    \filldraw #1 circle(0.5pt);
}

\begin{document}

\begin{center}
\includegraphics[scale=0.5]{graph.PNG}
\end{center}

\begin{center}

\begin{tikzpicture}[>=latex]
%Graph 1, system 1
\draw[dashed] (2.8,6.04)--(2.8,5.5);
\arr{(2.8,5.5-0.4*0)}{(2.8,5.5-0.4*1)}
\arr{(2.8,5.5-0.4*1)}{(2.8,5.5-0.4*2)}
\arr{(2.8,5.5-0.4*2)}{(2.8,5.5-0.4*3)}
\arr{(2.8,5.5-0.4*3)}{(2.8,5.5-0.4*4)}
\arr{(2.8,5.5-0.4*4)}{(2.8,5.5-0.4*5)}
\arr{(2.8,5.5-0.4*5)}{(2.8,5.5-0.4*6)}
\draw[dashed] (2.8,5.5-0.4*6)--(2.8,2.5);
\filldraw (2.8,3.1) circle(0.5pt);
%system 2
\arr{(2.3,5.15)}{(2.8,4.7)}
\arr{(2.3,5.7)}{(2.3,5.15)}
\arr{(1.8,5.3)}{(2.3,5.15)}
%system 3
\arr{(2.3,4.35)}{(2.8,3.9)}
%system 4
\arr{(3.3,3.65)}{(2.8,3.5)}
\arr{(3.3,4.25)}{(3.3,3.65)}
\arr{(3.8,3.95)}{(3.3,3.65)}
%system 5
\arr{(3.3,4.5)}{(2.8,4.3)}
\arr{(3.8,4.8)}{(3.3,4.5)}
\arr{(4.2,5.3)}{(3.8,4.8)}
\arr{(4,5.7)}{(4.2,5.3)}
\draw[dashed] (4,5.7)--(3.76,6.18);
\arr{(3.2,5)}{(3.3,4.5)}
\arr{(3.25,5.5)}{(3.2,5)}
%Graph 2, system 1
\arr{(5,4.5)}{(5.5,4.2)}
\arr{(5.4,3.59)}{(5.5,4.2)}
\arr{(5.5,4.2)}{(6,4.5)}
\draw[dashed] (5.4,3.59)--(5.3,2.98);
%system 2
\arr{(6,4.5)}{(6.5,4)}
\arr{(6.5,4)}{(7.3,4)}
\arr{(7.3,4)}{(7.5,4.65)}
\arr{(7.5,4.65)}{(6.8,5)}
\arr{(6,4.5)}{(6.8,5)}
%system 3
\arr{(6.8,5.5)}{(6.8,5)}
\arr{(6.4,6.02)}{(6.8,5.5)}
\arr{(7.2,6.02)}{(6.8,5.5)}
\filldraw (6.8,5) circle(0.5pt);
%system 4
\arr{(6.4,3.5)}{(6.5,4)}
\arr{(6,3)}{(6.4,3.5)}
\arr{(6.5,3)}{(6.4,3.5)}
%system 5
\arr{(7.5,3.5)}{(7.3,4)}
\arr{(7.3,3)}{(7.5,3.5)}
\arr{(8,3.3)}{(7.5,3.5)}
%system 6
\arr{(8.5,5)}{(8,4.7)}
\arr{(8,4.7)}{(7.5,4.65)}
\arr{(8,5.2)}{(7.5,4.65)}
\arr{(8,5.8)}{(8,5.2)}
\draw[dashed] (8,5.8)--(8,6.1);
%Graph 3, system 1
\arr{(9.5,4)}{(9.7,4.5)}
\arr{(9.7,4.5)}{(10.3,4.8)}
\arr{(10.3,4.8)}{(11,4.4)}
\arr{(11,4.4)}{(10.8,3.7)}
\arr{(10.8,3.7)}{(10,3.5)}
\arr{(10,3.5)}{(9.5,4)}
%Graph 4, system 1
\carr{(12,4)}{100}{-360+100}{0.25}{30:(12,4)}
%system 2
\arr{(13,5.5)}{(13,5)}
\arr{(13,5)}{(13,4.5)}
\arr{(13,4.5)}{(13,4)}
\filldraw (13,4) circle(0.5pt);
\draw[dashed] (13,4)--(13,3.5);
%system 3
\arr{(13.8,5.5)}{(13.8,5)}
\arr{(13.8,5)}{(13.8,4.5)}
\arr{(13.8,4.5)}{(13.8,4)}
\arr{(13.8,4)}{(13.8,3.5)}
\carr{(13.8,3.5)}{100}{-360+100}{0.25}{0:(13.8,3.5)}
\draw[dashed] (13.8,5.5)--(13.8,6);
%system 3
\arr{(14.5,5.5)}{(14.5,5)}
\arr{(14.5,5)}{(14.5,4.5)}
\arr{(14.5,4.5)}{(14.5,4)}
\arr{(14.5,4)}{(14.5,3.5)}
\filldraw (14.5,3.5) circle(0.5pt);
\draw[dashed] (14.5,5.5)--(14.5,6);
\draw[dashed] (14.5,3.5)--(14.5,3);
\end{tikzpicture}
\end{center}

\end{document}


text:
Q: Gpio under linux olimex I am using olimex 3188 board and am trying to access gpios. When I attempt : ls -l /sys/class/gpio I get :
export
gpiochip160
gpiochip192
gpiochip224
gpiochip256
unexport

cat /sys/class/gpio/gpiochip160/ngpio returns 32
cat /sys/class/gpio/gpiochip160/label returns gpio0
cat /sys/class/gpio/gpiochip192/label returns gpio1
and so on until gpio3
I have read and understood what each block consists of, but for example I want to access pin : GPIO0_B4. Where does this pin belong?


text:
Q: Is text file or sqlite data manageable when submitted to the AppStore? I have an iPhone app that loads data from 100 different text files. I would like to know if I am able to update and manage those text files when they are in the AppStore. Something like that I have a user named John, but I want to change his name. Can I do this when the app is in the AppStore?
Also, is data in sqlite databases manageable when submitted ?

A: That depends on where the files are being loaded from. If they're resources built into the app, then no, you can't change anything without resubmitting the app. But you can, of course, change files that your app loads from a server.
A common way to deal with this kind of situation is to include the most up-to-date files you have in your app, but build in the ability to retrieve newer versions from your server. Then, as you make changes and post them on your server, your app will update itself.

A: Well, that depends. You cannot change any part of the app bundle when it is on the App Store without resubmitting a new version and having it go through the review process. You can however have your app download files from a server and use those in your app. Then just update the files on your server to be whatever you like.


text:
Q: Why is my Sequelize query so slow? (nested-joins using findAll) I'm seeing an issue where my query is exponentially slower as I include more of the DayAvailability nested associations on the Schedule model. The goal is to serialize the User instance to include all associated instances.
Here is the table structure:
// User model

const User = sequelize.define('user', {
    id: {
      type: DataTypes.UUID,
      primaryKey: true
    }
}, {});
});

User.associate = function (models) {
  User.hasOne(models.Schedule);
};

// Schedule model

const Schedule = sequelize.define('schedule', {
  id: {
    type: DataTypes.UUID,
    primaryKey: true
  },
  userId: DataTypes.UUID
}, {
  hooks: {
    async afterCreate(instance, options) {
      await instance.createMonday();
      await instance.createTuesday();
      await instance.createWednesday();
      await instance.createThursday();
      await instance.createFriday();
      await instance.createSaturday();
      await instance.createSunday();
    }
  }
});

Schedule.associate = function(models) {
  Schedule.belongsTo(models.User);
  Schedule.hasOne(models.DayAvailability, { as: 'Monday', foreignKey: 'scheduleId' });
  Schedule.hasOne(models.DayAvailability, { as: 'Tuesday', foreignKey: 'scheduleId' });
  Schedule.hasOne(models.DayAvailability, { as: 'Wednesday', foreignKey: 'scheduleId' });
  Schedule.hasOne(models.DayAvailability, { as: 'Thursday', foreignKey: 'scheduleId' });
  Schedule.hasOne(models.DayAvailability, { as: 'Friday', foreignKey: 'scheduleId' });
  Schedule.hasOne(models.DayAvailability, { as: 'Saturday', foreignKey: 'scheduleId' });
  Schedule.hasOne(models.DayAvailability, { as: 'Sunday', foreignKey: 'scheduleId' });
};

// DayAvailability model

const DayAvailability = sequelize.define('day_availability', {
  id: {
    type: DataTypes.UUID,
    primaryKey: true
  },
  scheduleId: DataTypes.UUID
}, {});

DayAvailability.associate = function(models) {
  DayAvailability.belongsTo(models.Schedule);
};

(omitting other fields for brevity)
This setup does indeed work as intended. I can get a User instance with the nested Schedule instance included, however including the DayAvailability instances nested inside the Schedule instance causes a ridiculously slow query. If I omit some of the DayAvailability instance associations from the query, it's not as slow.
// User controller

const include = { model: Schedule, include: [
    { association: 'Monday' },  // only Monday - ~0.1 sec
    { association: 'Tuesday' },  // include Tues - ~0.5 sec
    { association: 'Wednesday' },  // include Wed - ~1.5 sec
    { association: 'Thursday' },   // include Thurs - 2+ sec
    { association: 'Friday' },
    { association: 'Saturday' },
    { association: 'Sunday' }   // include all - times out
]};

await User.findOne({
  where: { id: '123' },
  include
});

Any ideas as to why this query is so incredibly slow? Is it no good to include nested associations like this?
Thanks for your help.

Edit:  here is the SQL query that gets generated from the above Sequelize function. Other fields from the models are included in the SQL query as a heads up.
https://gist.github.com/FilmCoder/0afba42ffefb8f1e483699eb7ca2ac3b

A: I can give a little more information.  The DayAvailability record may expand in the future with more columns to include more information, such as a time range for when a person is available, which time zone they are in, their track record for how open they are on that day, etc...
And there will be 7 DayAvailability records per schedule, as the "Schedule" represents one week, and DayAvailability a single day of that week.
We're wondering if we're doing something fundamentally wrong with foreign keys and there's a way to make this work efficiently within a relational database.
I would have made this a comment, but for some reason stack overflow won't let me.


text:
Q: How to query first 5 projects for each person I have a dataset of around 50k records. The important fields are "date", "name" and "project ID". My challenge is I need to pull the first 5 projects for each person. There are around 500 people in the dataset. I know how to get the earilest projects, or the earliest projects for a specific individual, but I don't know how to get all the data for the earliest projects for all individuals. Any suggestions?
My desired output would be something like this:
NAME, DATE, PROJECT_ID
sally, 12/2/2020, 12432
sally, 12/6/2020, 13433
sally, 12/16/2020, 14453
sally, 1/8/2021, 14468
sally, 2/6/2021, 15496
jimmy, 11/15/2020, 24531
jimmy, 3/21/2021, 42322
jimmy, 5/13/2021, 44332

...
I'm using SQL in Google Big Query. I haven't gotten far because the logic is baffling me. And as you may be able to tell, my sql skills are elementary at best - but I'm trying! :)

A: You can use the ROW_NUMBER function with the PARTITION BY clause as a subquery, like so, and get only records with a row number <= 5 as it's ordering by date, this will get the first 5 records for each user, if you needed the 5 most recent records for each user, you would do ORDER BY DATE DESC, yourtable would be the name of your actual database table:
--Partitioning by Name is not consistent if more than one user
--shares the same name, if you have a user id which you can use to
--partition it would be better, but the following will get you moving
--in the right direction.
SELECT NAME, DATE, PROJECT_ID
FROM
(
    SELECT NAME, DATE, PROJECT_ID, ROW_NUMBER ()
    OVER (PARTITION BY Name ORDER BY DATE) AS rownum
    FROM yourtable
)
where rownum <= 5

More information on the ROW_NUMBER function: bigquery-row-number-function


text:
Q: How to calculate distance and time between two locations Here's a sample of some data
  Tag.ID TimeStep.coa        Latitude.coa Longitude.coa
   <chr>  <dttm>                     <dbl>         <dbl>
 1 1657   2017-08-17 12:00:00         72.4         -81.1
 2 1657   2017-08-17 18:00:00         72.3         -81.1
 3 1658   2017-08-14 18:00:00         72.3         -81.2
 4 1658   2017-08-15 00:00:00         72.3         -81.3
 5 1659   2017-08-14 18:00:00         72.3         -81.1
 6 1659   2017-08-15 00:00:00         72.3         -81.2
 7 1660   2017-08-20 18:00:00         72.3         -81.1
 8 1660   2017-08-21 00:00:00         72.3         -81.2
 9 1660   2017-08-21 06:00:00         72.3         -81.2
10 1660   2017-08-21 12:00:00         72.3         -81.3
11 1661   2017-08-28 12:00:00         72.4         -81.1
12 1661   2017-08-28 18:00:00         72.3         -81.1
13 1661   2017-08-29 06:00:00         72.3         -81.2
14 1661   2017-08-29 12:00:00         72.3         -81.2
15 1661   2017-08-30 06:00:00         72.3         -81.2
16 1661   2017-08-30 18:00:00         72.3         -81.2
17 1661   2017-08-31 00:00:00         72.3         -81.2
18 1661   2017-08-31 06:00:00         72.3         -81.2
19 1661   2017-08-31 12:00:00         72.3         -81.2
20 1661   2017-08-31 18:00:00         72.4         -81.1

I'm looking for a method to obtain distances travelled for each ID. I will be using the ComputeDistance function within VTrack package (could use a different function though). The function looks like this:
ComputeDistance( Lat1, Lat2, Lon1, Lon2)

This calculates a straight line distance between lat/lon coordinates.
I eventually want a dataframe with four columns Tag.ID, Timestep1, Timestep2, and distance. Here's an example:
Tag.ID   Timestep1            Timestep2               Distance
1657     2017-08-17 12:00:00  2017-08-17 18:00:00     ComputeDistance(72.4,72.3,-81.1,-81.1)
1658     2017-08-14 18:00:00  2017-08-15 00:00:00   ComputeDistance(72.3,72.3,-81.2,-81.3)
1659     2017-08-14 18:00:00  2017-08-15 00:00:00  ComputeDistance(72.3,72.3,-81.1,-81.2)
1660    2017-08-20 18:00:00   2017-08-21 00:00:00  ComputeDistance(72.3,72.3,-81.1,-81.2)
1660   2017-08-21 00:00:00   2017-08-21 06:00:00  ComputeDistance(72.3,72.3,=81.1,-81.2

And so on
EDIT:
This is the code I used (thanks AntoniosK). COASpeeds2 is exactly the same as the sample df above:
test <- COASpeeds2 %>%
  group_by(Tag.ID) %>%
  mutate(Timestep1 = TimeStep.coa,
         Timestep2 = lead(TimeStep.coa),
         Distance = ComputeDistance(Latitude.coa, lead(Latitude.coa),
                                    Longitude.coa, lead(Longitude.coa))) %>%

  ungroup() %>%
  na.omit() %>%
  select(Tag.ID, Timestep1, Timestep2, Distance)

This is the df I'm getting.
   Tag.ID Timestep1           Timestep2           Distance
   <fct>  <dttm>              <dttm>                 <dbl>
 1 1657   2017-08-17 12:00:00 2017-08-17 18:00:00    2.76
 2 1657   2017-08-17 18:00:00 2017-08-14 18:00:00    1.40
 3 1658   2017-08-14 18:00:00 2017-08-15 00:00:00    6.51
 4 1658   2017-08-15 00:00:00 2017-08-14 18:00:00   10.5
 5 1659   2017-08-14 18:00:00 2017-08-15 00:00:00    7.51
 6 1659   2017-08-15 00:00:00 2017-08-20 18:00:00    7.55
 7 1660   2017-08-20 18:00:00 2017-08-21 00:00:00    3.69
 8 1660   2017-08-21 00:00:00 2017-08-21 06:00:00    4.32
 9 1660   2017-08-21 06:00:00 2017-08-21 12:00:00    3.26
10 1660   2017-08-21 12:00:00 2017-08-28 12:00:00   10.5
11 1661   2017-08-28 12:00:00 2017-08-28 18:00:00    1.60
12 1661   2017-08-28 18:00:00 2017-08-29 06:00:00    1.94
13 1661   2017-08-29 06:00:00 2017-08-29 12:00:00    5.22
14 1661   2017-08-29 12:00:00 2017-08-30 06:00:00    0.759
15 1661   2017-08-30 06:00:00 2017-08-30 18:00:00    1.94
16 1661   2017-08-30 18:00:00 2017-08-31 00:00:00    0.342
17 1661   2017-08-31 00:00:00 2017-08-31 06:00:00    0.281
18 1661   2017-08-31 06:00:00 2017-08-31 12:00:00    4.21
19 1661   2017-08-31 12:00:00 2017-08-31 18:00:00    8.77

A: library(tidyverse)
library(VTrack)

# example data
dt = read.table(text = "
Tag.ID TimeStep.coa        Latitude.coa Longitude.coa
 1 1657   2017-08-17_12:00:00         72.4         -81.1
 2 1657   2017-08-17_18:00:00         72.3         -81.1
 3 1658   2017-08-14_18:00:00         72.3         -81.2
 4 1658   2017-08-15_00:00:00         72.3         -81.3
 5 1659   2017-08-14_18:00:00         72.3         -81.1
 6 1659   2017-08-15_00:00:00         72.3         -81.2
 7 1660   2017-08-20_18:00:00         72.3         -81.1
 8 1660   2017-08-21_00:00:00         72.3         -81.2
 9 1660   2017-08-21_06:00:00         72.3         -81.2
10 1660   2017-08-21_12:00:00         72.3         -81.3
", header=T)

dt %>%
  group_by(Tag.ID) %>%
  mutate(Timestep1 = TimeStep.coa,
         Timestep2 = lead(TimeStep.coa),
         Distance = ComputeDistance(Latitude.coa, lead(Latitude.coa),
                                    Longitude.coa, lead(Longitude.coa))) %>%
  ungroup() %>%
  na.omit() %>%
  select(Tag.ID, Timestep1, Timestep2, Distance)

As a result you get this:
# # A tibble: 6 x 4
#     Tag.ID Timestep1           Timestep2             Distance
#     <int> <fct>               <fct>                    <dbl>
# 1   1657 2017-08-17_12:00:00 2017-08-17_18:00:00 11.1
# 2   1658 2017-08-14_18:00:00 2017-08-15_00:00:00  3.38
# 3   1659 2017-08-14_18:00:00 2017-08-15_00:00:00  3.38
# 4   1660 2017-08-20_18:00:00 2017-08-21_00:00:00  3.38
# 5   1660 2017-08-21_00:00:00 2017-08-21_06:00:00  0.0000949
# 6   1660 2017-08-21_06:00:00 2017-08-21_12:00:00  3.38

A: Assuming the start and ending points are in order and have a matching pair.
Here is another option:
#identify the start and end of each trip
df$leg<-rep(c("Start", "End"), nrow(df)/2)
#label each trip
df$trip <- rep(1:(nrow(df)/2), each=2)

#change the shape
library(tidyr)
output<-pivot_wider(df, id_cols = c(Tag.ID, trip),
            names_from = leg,
            values_from = c(TimeStep.coa, Latitude.coa, Longitude.coa))

#calcuate distance (use your package of choice)
library(geosphere)
output$distance<-distGeo(output[ ,c("Longitude.coa_Start", "Latitude.coa_Start")],
                         output[ ,c("Longitude.coa_End", "Latitude.coa_End")])

# #remove undesired columns
# output <- output[, -c(5, 6, 7, 8)]
output

> output[, -c(5, 6, 7, 8)]
# A tibble: 10 x 5
   Tag.ID  trip TimeStep.coa_Start  TimeStep.coa_End    distance
    <int> <int> <fct>               <fct>                  <dbl>
 1   1657     1 2017-08-17 12:00:00 2017-08-17 18:00:00   11159.
 2   1658     2 2017-08-14 18:00:00 2017-08-15 00:00:00    3395.
 3   1659     3 2017-08-14 18:00:00 2017-08-15 00:00:00    3395.
 4   1660     4 2017-08-20 18:00:00 2017-08-21 00:00:00    3395.
 5   1660     5 2017-08-21 06:00:00 2017-08-21 12:00:00    3395.
 6   1661     6 2017-08-28 12:00:00 2017-08-28 18:00:00   11159.
 7   1661     7 2017-08-29 06:00:00 2017-08-29 12:00:00       0
 8   1661     8 2017-08-30 06:00:00 2017-08-30 18:00:00       0
 9   1661     9 2017-08-31 00:00:00 2017-08-31 06:00:00       0
10   1661    10 2017-08-31 12:00:00 2017-08-31 18:00:00   11661.

A: You could use geosphere::distGeo in a by approach.
library(geosphere)
do.call(rbind.data.frame, by(dat, dat$Tag.ID, function(s) {
  t.diff <- (s$TimeStep.coa[length(s$TimeStep.coa)] - s$TimeStep.coa[1])
  d.diff <- sum(mapply(function(x, y)
    distGeo(s[x, 3:4], s[y, 3:4]), x=1:(nrow(s)-1), y=2:nrow(s)))/1e3
  `colnames<-`(cbind(t.diff, d.diff), c("hours", "km"))
}))
#      hours        km
# 1657  6.00  1.727882
# 1658  6.00 11.166785
# 1659  6.00 11.166726
# 1660 18.00 22.333511
# 1661  3.25 24.192753

Data:
dat <- structure(list(Tag.ID = c(1657L, 1657L, 1658L, 1658L, 1659L,
1659L, 1660L, 1660L, 1660L, 1660L, 1661L, 1661L, 1661L, 1661L,
1661L, 1661L, 1661L, 1661L, 1661L, 1661L), TimeStep.coa = structure(c(1502964000,
1502985600, 1502726400, 1502748000, 1502726400, 1502748000, 1503244800,
1503266400, 1503288000, 1503309600, 1503914400, 1503936000, 1503979200,
1504000800, 1504065600, 1504108800, 1504130400, 1504152000, 1504173600,
1504195200), class = c("POSIXct", "POSIXt"), tzone = ""), Latitude.coa = c(72.4,
72.3, 72.3, 72.3, 72.3, 72.3, 72.3, 72.3, 72.3, 72.3, 72.4, 72.3,
72.3, 72.3, 72.3, 72.3, 72.3, 72.3, 72.3, 72.4), Longitude.coa = c(-81.1,
-81.1, -81.2, -81.3, -81.1, -81.2, -81.1, -81.2, -81.2, -81.3,
-81.1, -81.1, -81.2, -81.2, -81.2, -81.2, -81.2, -81.2, -81.2,
-81.1)), row.names = c(NA, -20L), class = "data.frame")


text:
Q: Multiple pattern for one action I am working on MVC 5 routing.  I want to use just 1 mapping  for different URLs;
For example, If the user write  as Prodcut,Producto and Urun like below:

www.blabla.com/Product/1
www.blabla.com/Urun/1
www.blabla.com/Producto/1

...then will send this request same Action of Product.
Is this possible to make a defination like below code?
routes.MapRoute(
            "Page",
            "Product/{id} | Producto/{id} | Urun/{id}", //This row not working
            defaults: new { controller = "Product", action = "ShowProduct" , id = UrlParameter.Optional},
            constraints: new { id = @"^[a-zA-Z0-9ğüşöçİĞÜŞÖÇ_-.]+$" }
        );

A: Better is create multiple route but you can play with constraints
    routes.MapRoute(
        "Page",
        "{name}/{id},
        defaults: new {
           controller = "Product",
           action = "ShowProduct",
           id = UrlParameter.Optional
        },
        constraints: new {
           id = @"^[a-zA-Z0-9ğüşöçİĞÜŞÖÇ_-.]+$",
           name = "Product|Producto|Urun"
        }
    );


text:
Q: Error of "cannot determine size of graphics" I know this topic is covered elsewhere in this forum, so I would not ask if I was not desperate and had tried everything I could already.
I have a large PhD thesis with over a hundred images in it written in lyx. When I try to export to pdf, for three particular images I keep getting the error "cannot determine the size of graphics"
To try to remove this error I have tried the following:

*

*Specifying the scale graphics % in the lyx graphics dialogue box.

*Manually specifying the exact width and height of the graphics, in cm, in the lyx graphics dialogue box.

*Deleting the original .bmp files and re-exporting the images as .bmp files from the graph creation software I am using (Sigmaplot in case anyone knows it.)

*Converting .bmp files to .jpg files, and when that did not work, converting to .png files, which did not work either.
These three files look to me to be very similar to other files which I have exported from the same graph creation software, but I am not receiving any errors for those. So at this stage I am completely out of ideas.
Any help would be greatly appreciated. Also I am not a programmer and don't understand coding very well, so assume you are responding to a complete dummy when it comes to latex etc.


text:
Q: Getting Barcode Scanner MT2000 to Move to Next Focus I am trying to move to the next focus of an application by transmit a TAB or ENTER character to the host from my Motorola MT2070 Barcode Scanner.
I have tried using the SendLabel method as follows
       string barcode = "Hello";
       int count = 1;

        SendBarcode(new LabelData(barcode + "\t" + count.ToString(), Options.BarcodeType));
        count++;
    }

    private bool SendBarcode(LabelData label)
        {
        RESULTCODE result = RESULTCODE.E_OK;
        try
        {
            result = Program.ScannerServicesClient.SendLabel(label, 10000);
        }
        catch
        {
            result = RESULTCODE.E_HOST_NOT_READY;
        }
        if (result != RESULTCODE.E_OK)
        {
            MsgBox.Error(listForm, Properties.Resources.StrErrorCouldntSendBarcode);
        }
        return result == RESULTCODE.E_OK;
    }

Unfortunately the "\t" does not translate into an actual TAB keystroke in Keyboard mode.
When scanning in NOTEPAD the 5 spaces of the tab show up, but it doesn't work to move the focus to the next field as hitting TAB does in Excel or other applications.
What should I be transmitting in place of the \t?
Thanks!

A: I assume this won't work, because it is not a normal/manual input from your keyboard. It is a value passed from a barcode to the text-property of your field. So you have to handle this different.


text:
Q: Access 2010 -- Same report, different record sources Ok, So I am Tracking certain Items by region of the world and I have create a system of Tables and Join Query's to a report. The Report summarizes all the data for 2012, it has a sub report inside the main report for each region of the world. When 2013 is done I want to be able to copy the exact report and just change the control sources for the report and sub reports, as all the queries and tables that will be built in 2013 have the same fields so the data should transfer easily. Now lets say I want it so this is user friendly, is there a way that I can use Vba code to generate the next report and change the control sources based on what a user selects in a Form? As this would allow a person not familiar with access to generate reports with ease. Thanks in advance.

A: If you are as good as I think you are, the 2012 report (and I am including sub-reports) uses queries that filter records by date -- limiting the returns to the year 2012.  For 2013, you will run the same report, but the criterion for filtering will be the year 2013.  This is easily handled with parameter queries, and VBA will indeed make it simple.
If you can show us a bit more, such as one of the base queries, then you hopefully can learn more about the specific approach.
Additional Information:
A good how-to is available here.  I believe it's not too hard, using parameter queries and VBA (or VBA's QueryDef object), to simplify the user's action to just choosing from a list of years on a form.  If you get a start on this approach, post what you have and maybe I can offer more help.  (Sorry for the long time replying.)


text:
Q: DataSource.InsertParameters.Add("UserId", UserGUID.ToString()); Object reference not set to an instance of an object error I have been following the tutorial to create additional fields in the Create User Wizard here:
https://web.archive.org/web/20211020103243/https://www.4guysfromrolla.com/articles/070506-1.aspx#postadlink
I am getting an error of Object reference not set to an instance of an object on my line DataSource.InsertParameters.Add("UserId", UserGUID.ToString());
My ASP Code is this:
    <asp:CreateUserWizard ID="CreateUserWizard1" runat="server" oncreateduser="CreateUserWizard1_CreatedUser">
    <WizardSteps>
        <asp:CreateUserWizardStep ID="CreateUserWizardStep1" runat="server">
            <ContentTemplate>

                            Sign Up for Your New Account

                            <asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">User Name:</asp:Label>

                            <asp:TextBox ID="UserName" runat="server"></asp:TextBox>
                            <asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName"
                                ErrorMessage="User Name is required." ToolTip="User Name is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>

                            <asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label>

                            <asp:TextBox ID="Password" runat="server" TextMode="Password"></asp:TextBox>
                            <asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ControlToValidate="Password"
                                ErrorMessage="Password is required." ToolTip="Password is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>

                            <asp:Label ID="ConfirmPasswordLabel" runat="server" AssociatedControlID="ConfirmPassword">Confirm Password:</asp:Label>

                            <asp:TextBox ID="ConfirmPassword" runat="server" TextMode="Password"></asp:TextBox>
                            <asp:RequiredFieldValidator ID="ConfirmPasswordRequired" runat="server" ControlToValidate="ConfirmPassword"
                                ErrorMessage="Confirm Password is required." ToolTip="Confirm Password is required."
                                ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>

                            <asp:CompareValidator ID="PasswordCompare" runat="server" ControlToCompare="Password"
                                ControlToValidate="ConfirmPassword" Display="Dynamic" ErrorMessage="The Password and Confirmation Password must match."
                                ValidationGroup="CreateUserWizard1"></asp:CompareValidator>

                            <asp:Label ID="EmailLabel" runat="server" AssociatedControlID="Email">E-mail:</asp:Label>

                            <asp:TextBox ID="Email" runat="server"></asp:TextBox>
                            <asp:RequiredFieldValidator ID="EmailRequired" runat="server" ControlToValidate="Email"
                                ErrorMessage="E-mail is required." ToolTip="E-mail is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>

                            <asp:Label ID="ManagerFirstNameLabel" runat="server" AssociatedControlID="ManagerFirstName">First Name:</asp:Label>

                            <asp:TextBox ID="ManagerFirstName" runat="server"></asp:TextBox>
                            <asp:RequiredFieldValidator ID="ManagerFirstNameRequired" runat="server" ControlToValidate="ManagerFirstName"
                                ErrorMessage="First Name is required." ToolTip="First Name is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>

                            <asp:Label ID="ManagerSurnameLabel" runat="server" AssociatedControlID="ManagerSurname">Surname:</asp:Label>

                            <asp:TextBox ID="ManagerSurname" runat="server"></asp:TextBox>
                            <asp:RequiredFieldValidator ID="ManagerSurnamRequired" runat="server" ControlToValidate="ManagerSurname"
                                ErrorMessage="Surname is required." ToolTip="Surname is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>

                            <asp:Label ID="TeamNameLabel" runat="server" AssociatedControlID="TeamName">Team Name:</asp:Label>

                            <asp:TextBox ID="TeamName" runat="server"></asp:TextBox>
                            <asp:RequiredFieldValidator ID="TeamNameRequired" runat="server" ControlToValidate="TeamName"
                                ErrorMessage="Team Name is required." ToolTip="Team Name is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>

                            <asp:Label ID="TeamStadiumLabel" runat="server" AssociatedControlID="TeamStadium">Team Stadium Name:</asp:Label>

                            <asp:TextBox ID="TeamStadium" runat="server"></asp:TextBox>
                            <asp:RequiredFieldValidator ID="TeamStadiumRequired" runat="server" ControlToValidate="TeamStadium"
                                ErrorMessage="Team Stadium Name is required." ToolTip="Team Stadium Name is required."
                                ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>

                            <asp:Label ID="RecieveReminderLabel" runat="server" AssociatedControlID="RecieveReminder">Recieve Reminder Email:</asp:Label>

                            <asp:CheckBox ID="RecieveReminder" runat="server" />

                            <asp:Label ID="RecieveSummaryLabel" runat="server" AssociatedControlID="RecieveSummary">Recieve Summary Email:</asp:Label>

                            <asp:CheckBox ID="RecieveSummary" runat="server" />

                            <asp:Literal ID="ErrorMessage" runat="server" EnableViewState="False"></asp:Literal>

                            <asp:Literal ID="Literal1" runat="server" EnableViewState="False"></asp:Literal>

            </ContentTemplate>
        </asp:CreateUserWizardStep>
        <asp:CompleteWizardStep ID="CompleteWizardStep1" runat="server" />
    </WizardSteps>
</asp:CreateUserWizard>

<asp:SqlDataSource ID="InsertAdditionalUserDetails" runat="server" ConnectionString="<%$ ConnectionStrings:RaiseFantasyLeagueConnectionString %>"
    InsertCommand="INSERT INTO [UserDetails] ([UserId], [ManagerFirstName], [ManagerSurname], [TeamName], [TeamStadium], [RecieveReminder], [RecieveSummary]) VALUES (@UserId, @ManagerFirstName, @ManagerSurname, @TeamName, @TeamStadium, @RecieveReminder, @RecieveSummary)" ProviderName="System.Data.SqlClient">
    <InsertParameters>
        <asp:ControlParameter Name="ManagerFirstName" Type="String" ControlID="ManagerFirstName" PropertyName="Text" />
        <asp:ControlParameter Name="ManagerSurname" Type="String" ControlID="ManagerSurname" PropertyName="Text" />
        <asp:ControlParameter Name="TeamName" Type="String" ControlID="TeamName" PropertyName="Text" />
        <asp:ControlParameter Name="TeamStadium" Type="String" ControlID="TeamStadium" PropertyName="Text" />
        <asp:ControlParameter Name= "RecieveReminder" Type="Boolean" ControlID="RecieveReminder" PropertyName="Checked" />
        <asp:ControlParameter Name= "RecieveSummary" Type="Boolean" ControlID="RecieveSummary" PropertyName="Checked" />
    </InsertParameters>
</asp:SqlDataSource>

and C# code is this
        protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
    {
        TextBox UserNameTextBox = (TextBox)CreateUserWizardStep1.ContentTemplateContainer.FindControl("UserName");
        SqlDataSource DataSource = (SqlDataSource)CreateUserWizardStep1.ContentTemplateContainer.FindControl("InsertAdditionalUserDetails");

        MembershipUser User = Membership.GetUser(UserNameTextBox.Text);

        if (User != null)
        {
            object UserGUID = User.ProviderUserKey;
            DataSource.InsertParameters.Add("UserId", UserGUID.ToString());
            DataSource.Insert();
        }
    }

Any help would be appreciated !

A: Your "DataSource" or "UserGUID" is NULL.

A: this error you are getting because you are trying to convert object to string. Try this it might help you
instead of object use var
var user

A: I think this will solve your problem
protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
{
    MembershipUser User = Membership.GetUser(CreateUserWizard1.UserName);
    object userGUID = User.ProviderUserKey;
    TextBox firstname = (TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("FirstName");
    TextBox lastname = (TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("LastName");
    TextBox companyname = (TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("CompanyName");
    TextBox address1 = (TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Address1");
    TextBox address2 = (TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Address2");
    TextBox city = (TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("City");
    DropDownList state = (DropDownList)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("State");
    TextBox zip = (TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Zip");
    TextBox phone_number = (TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Phone");
    TextBox email_address = (TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Email");

    SqlDataSource1.InsertParameters.Add("userid", userGUID.ToString());
    SqlDataSource1.InsertParameters.Add("firstname", firstname.Text);
    SqlDataSource1.InsertParameters.Add("lastname", lastname.Text);
    SqlDataSource1.InsertParameters.Add("companyname", companyname.Text);
    SqlDataSource1.InsertParameters.Add("address1", address1.Text);
    SqlDataSource1.InsertParameters.Add("address2", address2.Text);
    SqlDataSource1.InsertParameters.Add("city", city.Text);
    SqlDataSource1.InsertParameters.Add("state", state.SelectedValue);
    SqlDataSource1.InsertParameters.Add("zip", zip.Text);
    SqlDataSource1.InsertParameters.Add("phone_number", phone_number.Text);
    SqlDataSource1.InsertParameters.Add("email_address", email_address.Text);
    SqlDataSource1.Insert();
}


text:
Q: Is there a way to load static language files and also be able to load additional language resource on-demand using ngx-translator? My application has static JSON files for most translations, but some run time data also has translations and I'd like to load that translation data on-demand using ngx-translator.
Is there a way to load static files and also be able to load additional data on-demand?


text:
Q: sms BroadcastReceiver doesn't receive SMS after app killed OR device restart on MI devices only My SMS receiving code works good on all devices except Xiomi Redmi devices
On Xiomi Redmi devices, my app(Broadcast Receiver) not able to receive SMS when app gets killed by swiping from recent app list OR after device restart until I start the app manually.
(Tested on Mi Marshmallow and MI Lollipop devices).
This issue happens only on MI devices. App works good on other devices like Samsung, HTC, Sony, Motorola, Micromax etc.
my code in manifest:
 <uses-permission android:name="android.permission.SEND_SMS" />
 <uses-permission android:name="android.permission.RECEIVE_SMS" />
 <receiver
        android:name=".receiver.SMSBroadcastReceiver"
        android:enabled="true"
        android:priority="999">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
  </receiver>

Broadcast Receiver:
public class SMSBroadcastReceiver extends BroadcastReceiver {

 public void onReceive(Context context, Intent intent) {
    if (Constants.SMS_RECEIVED_ACTION.equals(intent.getAction())) {
        mContext = context.getApplicationContext();
        mIntent = intent;
        sendIntent();
    } else {
        LogUtil.e(TAG, "Intent action: " + intent.getAction());
    }
 }
}

A: Xiomi Redmi devices, app restrictions are more stringent than any other ROM, due to these restrictions many of the app notifications are not meeting the timeline and delivers the notifications only after some certain period of time. The reasons may be of different ranges, starting from Google's cloud messaging to advanced battery modes, that enable apps to sleep instead of getting the notifications.To Resolve this issue Read this document carefully
 http://en.miui.com/forum.php?mod=viewthread&tid=268224&page=1

A: Finally got the solution(workaround actually)
1. First check if MI device
if (!TextUtils.isEmpty(getMiUiVersionProperty())) {
// its a MI device
}
public String getMiUiVersionProperty() {
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(Runtime.getRuntime().exec("getprop ro.miui.ui.version.name").getInputStream()), 1024);
        String line = reader.readLine();
        reader.close();
        return line;
    } catch (IOException e) {}
}

2. Show a dialog to user to enable Autostartfor your application
e.g.
3. Then navigate user to 'Autostart' screen directly to enable it for your app
public void openMiuiAutoStartPermissionActivity(Context context) {
        Intent intent = new Intent("miui.intent.action.APP_PERM_EDITOR");
        String ROM = getMiUiVersionProperty();
        if (TextUtils.equals(ROM, "V5")) {
            PackageInfo pInfo = null;
            try {
                pInfo = context.getPackageManager().getPackageInfo(                                                      context.getPackageName(), 0);
            } catch (NameNotFoundException e) {
                e.printStackTrace();
            }
            intent.setClassName("com.android.settings",    "com.miui.securitycenter. permission.AppPermissionsEditor");
            intent.putExtra("extra_package_uid", pInfo.applicationInfo.uid);
        } else if (TextUtils.equals(ROM, "V6") || TextUtils.equals(ROM, "V7") || TextUtils.equals(ROM, "V8")) {
            intent.setClassName( "com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity");
            intent.putExtra( "extra_pkgname", context.getPackageName());
        } else {
            intent.setClassName( "com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity");
            intent.putExtra( "extra_pkgname", context.getPackageName());
        }
        if (isIntentAvailable(context, intent) && (context instanceof Activity)) {
            ((Activity) context).startActivityForResult(intent, AUTO_START_ENABLE_REQUEST);
        }
    }


text:
Q: Background sticky concurrent mark sweep GC freed and app crashes - android When sending some data to server, the below method rises more,
I/art﹕ Background sticky concurrent mark sweep GC freed 45388(3MB) AllocSpace objects, 17(292KB) LOS objects, 14% free, 10MB/11MB, paused 20.543ms total 209.212ms
I/art﹕ Background partial concurrent mark sweep GC freed 66026(4MB) AllocSpace objects, 27(616KB) LOS objects, 28% free, 9MB/13MB, paused 2.454ms total 246.055ms
I/art﹕ Background sticky concurrent mark sweep GC freed 42923(3MB) AllocSpace objects, 14(236KB) LOS objects, 20% free, 11MB/13MB, paused 3.247ms total 143.983ms
W/art﹕ Suspending all threads took: 7.054ms

MyClass.Java
private static synchronized void saveToServer(final MyClass myclass) throws JSONException {
User currentUser = MainActivity.getUser();
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("name", myclass.getname());
// …. other params.put(....)
try {
HttpClientUtils.postRequestWithCallback(SAVE_URL, params, SignatureType.SIG_SEC, new HttpClientUtils.CustomCallbackListener(){
@Override
public void onSuccess(JSONObject jsonObject) {
myclass.setSaved(true);
}
});
}catch (Exception e){
}
}


text:
Q: Easiest way to change directory into its own logical volume in LVM2 I have a dir called /mydir on logical volume /dev/vg1/lv_root ( / )
var is on its own logical volume, so is opt and /usr.. If I have free space in the volume group, what is the easiest way to change /mydir to make /mydir the mountpoint for a new logical volume in the vol group called /dev/vg1/lv_mydir ?  Cent 6 EXT4 file system.
Edit:  I havent created the new logical volume yet.

A: Just mount your /dev/vg1/lv_mydir to /mydir.
mount -t ext4 /dev/vg1/lv_mydir /mydir

As Adrian pointed out i assumed a lot, so yes if you have any files residing in current directory you will have to preserve them somewhere and then copy to the new mount. Also on the new LV you will need to create ext4 partition before mounting it.


text:
Q: Transparent ViewController I'm pushing a UIViewController with
[otherController presentViewController: newController animated: NO completion: nil];

Then nib for newController has the base view, a smaller view and a text field and some buttons in the smaller view. I want the base view to be transparent gray, so I can see the view of the view controller beneath it, while making it obvious to the user that that other view is disabled.
I've tried setting the Alpha value low (which alpha-ed my other controls), setting the view background to a transparent black, and unsetting the Opaque flag. None of those work. I just get an opaque light gray background.
Here's my view controller:
@interface MyEditQueryViewController : UIViewController

@property (nonatomic, strong) id<MyEditQueryDelegate> delegate;
@property (nonatomic, strong) IBOutlet UITextField* textField;
@property (nonatomic, strong) IBOutlet UIView* editView;
@property (nonatomic, strong) IBOutlet UIButton* cancelButton;
@property (nonatomic, strong) IBOutlet UIButton* saveButton;
@property (nonatomic, strong) NSString* defaultText;
@property (nonatomic) CGFloat verticalOffset;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil;
- (id)initWithDefaultText:(NSString*)defaultText orign:(CGPoint)origin;

- (IBAction)cancelTapped:(id)sender;
- (IBAction)saveTapped:(id)sender;
@end

Is there a way to make that view translucent?

A: On iPhone, the only way to accomplish this (outside of UIAlertView and UIActionSheet) is by presenting a UIView as a subview on the UIViewController that will serve as the background view.  The UIView you present can take up the full screen and use a transparent/translucent view for most of it's view to accomplish the dimming effect.

On iPad, in addition to UIAlertView and UIActionSheet, you can also modally present views that are not full screen.  These have their own view controllers.  To do this, you need to set the UIModalPresentationStyle to one of the following:

*

*UIModalPresentationPageSheet

*UIModalPresentationFormSheet
However, both of these options are a little limiting (in my opinion) in terms of how you can size them and where you can place them, so if you want full customization, you'll have to do it the same way I explained for iPhone, by presenting a separate UIView on the UIViewController that serves as the background view.

Other than the UIModalPresentationPageSheet and UIModalPresentationFormSheet options for the iPad, setting a transparent/translucent background for a view controller will assume a white background behind the back-most layer you can set the color of.

It should also be noted that UIAlertView and UIActionSheet are intended (by Apple) to be used as is and should not be subclassed, whereas you can subclass UIView all you want to get whatever look you desire.

A: This kind of thing is easy when using a custom RootViewController to manage its own container views. The root view controller can then define its own navigation system or delegate to a standard UIKit component.
This also has the advantage of being able to use domain-specific language - method names that model your specific app in the Root VC's interface - for example [rootViewController presentMenuItem:menuItem].
I have an example of an app using a root view controller here.
And here's another code snippet (from another app) that presents an overlay with a semi-transparent background:
- (void)presentOverlayViewController:(UIViewController*)viewController
{
    LogDebug(@"Presenting overlay view controller: %@", viewController);
    if (_overlayViewController)
    {
        [self dismissOverlayViewController];
    }

    [self.view setUserInteractionEnabled:NO];
    [self.view bringSubviewToFront:_tintView];
    [_tintView setAlpha:0.0];
    [self.view bringSubviewToFront:_overlayViewContainer];
    _overlayViewController = viewController;

    CGSize screenSize = [[UIScreen mainScreen] currentSize];

    [viewController willMoveToParentViewController:self];
    [_overlayViewContainer addSubview:viewController.view];
    [_overlayViewController.view setPosition:(CGPoint) {(screenSize.width / 2) - (_overlayViewController.view.frame.size.width / 2),
            (screenSize.height / 2) - (_overlayViewController.view.frame.size.height / 2)}];

    __weak UIView* overlayViewContainer = _overlayViewContainer;
    __weak UIView* view = self.view;
    __weak UIView* tintView = _tintView;
    [UIView transitionWithView:self.view duration:0.60 options:UIViewAnimationOptionCurveEaseInOut animations:^
    {
        [tintView setAlpha:0.7];
        CGRect newFrame = overlayViewContainer.frame;
        newFrame.origin.y -= screenSize.height;
        [overlayViewContainer setUserInteractionEnabled:YES];
        overlayViewContainer.frame = newFrame;
    } completion:^(BOOL complete)
    {
        [viewController didMoveToParentViewController:self];
        [view setUserInteractionEnabled:YES];
    }];
}

This approach will work on either iOS or iPad, and can in fact be written to work on both.
Edit:
If you haven't got a custom root view controller set right down as the rootVC on UIWindow, you can still do this by adding the same methods on the VC that will be presenting the semi-transparent overlay.
Edit2:
Please note the addition of:
 [viewController willMoveToParentViewController:self];
 [viewController didMoveToParentViewController:self];

. . which are required, as pointed out by Jesse Rusak


text:
Q: Reasons to use BinaryFormatter instead of protobuf-net So in many benchmarks I've seen, protobuf-net comes well ahead of BinaryFormatter:
 - http://theburningmonk.com/2011/08/performance-test-binaryformatter-vs-protobuf-net/
 - https://code.google.com/p/protobuf-net/wiki/Performance
Which leads me to the question: Why would you want to use BinaryFormatter if protobuf-net is available?
I have read something about BinaryFormatter storing type metadata, something that protobuf does not do. Can you give me an example scenario where I would want type metadata to be stored?

A: I'm currently struggling with protobuf-net to serialize objects of type Dictionary<string, object>. What I've read is that it's not possible, so I guess that's a scenario where one would prefer BinaryFormatter.


text:
Q: Get Two Signed APK From Same Android Project I have an app which includes ads with package name com.test1
I got one signed apk from this and I also want another one with package name com.test1.test2 which will be paid version (directs to google play store).
How can I get second signed apk without using same keystore?

A: If a package is different then you can choose different Keystore files while generating a new apk.


text:
Q: Reading Specific Part Of A Text File I've found a few similar questions to this but not relating to XCode.
I am creating an app where clicking a button generates a randomised quote and displays it in a label.
What I'd like to do is have a text file with all of the quotes, then have my app randomly select a quote from that file.
The problem is that my code at present reads the entire contents of the file.
    textHIYP = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
textHIYP.editable = NO;
[self.view addSubview:textHIYP];

textHIYP.text = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Quotes" ofType:@"txt"] encoding:NSUTF8StringEncoding error:nil];

The only other way I can think of doing it is to have an arc4random() code that randomises which file it locates, with each file containing a single quote...but as I want to have over a hundred quotes, this seems less than ideal.
Any suggestions as to how to read a particular line of a text file?
Thanks heaps in advance!

A: You could read the whole file into an NSString, then split it into an array with componentsSeparatedByString:@"\n", keep that it memory, and return a random element of the array when needed. If there are just hundreds (and not, say, millions) of lines, the additional memory used should not be an issue.

A: You're imitating the behavior of the old fortune program, so adopt its tactic, too. The database of quotes is a set of files with quotes separated by lines containing only a special character:
Cabbage crates coming over the briny!
%
Top hole, squiffy!
%
Next we have number four, "crunchy frog".
%
Lemon curry?
%

For each of those quote files, a companion file is generated (using the strfile utility) that stores the offset and length of each quote. To pick a quote, you load just the (relatively small) index file into memory, choose an element at random, then use that offset and length to seek and read a single quote from the appropriate quote file.
Here's a Python implementation of fortune on GitHub. The original C code should be floating around somewhere too.