text:
Q: libgdx making a touch event I'm currently following this book to create my libgdx game..
 So far, i have these classes to create my game :

*

* AbstractGameScreen.java - that Implements libgdx's Screen

* AbstractGameObject.java - that extends libgdx's Actor

* GamePlay.java - which is my game screen

* GameController.java - where i init my game objects

* GameRenderer.java - when i render all my objects

* Assets.java - a class that organizes my game assets

* Ring.java - an object in my game

And here is my code..
AbstractGameScreen
public abstract class AbstractGameScreen implements Screen {
    protected Game game;

    public AbstractGameScreen(Game game){
        this.game = game;
    }

    public abstract void render(float deltaTime);
    public abstract void resize(int width, int height);
    public abstract void show();
    public abstract void hide();
    public abstract void pause();

    public void resume(String bg, String ring){
        Assets.instance.init(new AssetManager(), bg, ring);  // kosongin, jadinya default
    }

    public void dispose(){
        Assets.instance.dispose();
    }
}

AbstractGameObject
public abstract class AbstractGameObject extends Actor{ //implements EventListener{  //extends Sprite{
    public Vector2 position;
    public Vector2 dimension;
    public Vector2 origin;
    public Vector2 scale;
    public float rotation;

    public AbstractGameObject(){
        position = new Vector2();
        dimension = new Vector2(1, 1);
        origin = new Vector2();
        scale = new Vector2(1, 1);
        rotation = 0;

    }

    public void update (float deltaTime){

    }

    public abstract void render(SpriteBatch batch);
}

GamePlay
public class GamePlay extends AbstractGameScreen implements InputProcessor{

    private GameController gameController;
    private GameRenderer gameRenderer;
    private String dummyBg, dummyRing;
    private boolean paused;

    // for touch purposes
    private static final int appWidth = Constants.VIEWPORT_GUI_WIDTH_INT;
    private static final int appHeight = Constants.VIEWPORT_GUI_HEIGHT_INT;

    public GamePlay(Game game) {
        super(game);

        // still dummy.. nantinya ngambil dari database nya
        this.dummyBg = "bg-default";
        this.dummyRing = "ring-default";

        Gdx.input.setInputProcessor(this);
    }

    @Override
    public void render(float deltaTime) {
        if(!paused){
            gameController.update(deltaTime);
        }

        //Gdx.gl.glClearColor(0x64 / 255.0f, 0x95 / 255.0f,0xed / 255.0f, 0xff / 255.0f);
        //Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        // render game nya
        gameRenderer.render();
    }

    @Override
    public void resize(int width, int height) {
        gameRenderer.resize(width, height);
    }

    @Override
    public void show() {
        Assets.instance.init(new AssetManager(), "bg-default", "ring-default");
        Gdx.app.log("GamePlay", "After show() method");

        gameController = new GameController(game);
        gameRenderer = new GameRenderer(gameController);
        Gdx.input.setCatchBackKey(true);
    }

    @Override
    public void hide() {
        gameRenderer.dispose();
        Gdx.input.setCatchBackKey(false);
    }

    @Override
    public void dispose(){
        gameRenderer.dispose();
        Assets.instance.dispose();
    }

    @Override
    public void pause() {
        paused = true;
    }

    @Override
    public void resume() {
        super.resume(this.dummyBg, this.dummyRing);
        //Assets.instance.init(new AssetManager(), this.dummyBg, this.dummyRing);

        paused = false;
    }

    @Override
    public boolean keyDown(int keycode) {
        return false;
    }

    @Override
    public boolean keyUp(int keycode) {
        return false;
    }

    @Override
    public boolean keyTyped(char character) {
        return false;
    }

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {

        return true;
    }

    @Override
    public boolean touchUp(int screenX, int screenY, int pointer, int button) {

        return true;
    }

    // for touch purposes
    private float getCursorToModelX(int screenX, int cursorX) {
        return (((float)cursorX) * appWidth) / ((float)screenX);
    }

    private float getCursorToModelY(int screenY, int cursorY) {
        return ((float)(screenY - cursorY)) * appHeight / ((float)screenY) ;
    }

    @Override
    public boolean touchDragged(int screenX, int screenY, int pointer) {
        return false;
    }

    @Override
    public boolean mouseMoved(int screenX, int screenY) {
        return false;
    }

    @Override
    public boolean scrolled(int amount) {
        return false;
    }
}

GameController
public class GameController extends InputAdapter{
    // game objects
    public Array<Tiang> tiangs;
    public Array<Ring> rings;
    //private Game game;

    // game decorations
    public Background background;     public Sprite[] testSprite;
    private Game game;

    public GameController(Game game){
        this.game = game;
        init();
    }

    private void init(){
        // preparing variables
        rings = new Array<Ring>();
        tiangs = new Array<Tiang>();

        initObjects();
        initDecorations();
        initGui();
    }

    private void initObjects(){
        AbstractGameObject obj = null;
        obj = new Ring(1, "default");

        obj.addListener(new ClickListener(){
            @Override
            public void clicked(InputEvent event, float x, float y) {
                //super.clicked(event, x, y);
                Gdx.app.log("tag", "test clisk");
            }
        });

        rings.add((Ring)obj);
    }

    private void initDecorations(){

    }

    private void initGui(){

    }

    private void handleInput(float deltatime){

    }

    public void update(float deltaTime){
        //if(Gdx.input.isTouched()){
        //  Gdx.app.log("update", "screen touched");
        //}
    }
}

GameRenderer
public class GameRenderer implements Disposable{

    private OrthographicCamera camera;
    private GameController controller;
    private SpriteBatch batch;

    public GameRenderer(GameController controller){
        this.controller = controller;
        init();
    }

    private void init(){
        batch = new SpriteBatch();
        camera = new OrthographicCamera(Constants.VIEWPORT_WIDTH, Constants.VIEWPORT_HEIGHT);  //diambil dari class "Constants" (di package util)
        camera.position.set(0, 0, 0);
        camera.update();
    }

    public void resize(int width, int height){
        camera.viewportWidth = (Constants.VIEWPORT_HEIGHT / height) * width;
        camera.update();
    }

    public void render(){
        renderGui();
        renderDecorations();
        renderObjects();
    }

    private void renderGui(){

    }

    private void renderDecorations(){

    }

    private void renderObjects(){
        batch.setProjectionMatrix(camera.combined);
        batch.begin();

        for(Ring rings : controller.rings){
            rings.render(batch);
        }

        batch.end();
    }

    @Override
    public void dispose() {

    }
}

Assets
public class Assets implements Disposable, AssetErrorListener{
    public static final String TAG = Assets.class.getName();
    public static final Assets instance = new Assets();

    private AssetManager assetManager;

    // inner class objects
    public AssetTiang tiang;
    public AssetBackgroud bg;
    public AssetTombol tombol;
    public AssetTombolBg tombolBg;
    public AssetRing ring;

    //singleton pattern, buat mencegah instansiasi dari class yang lain
    private Assets(){}

    //public void init(AssetManager assetManager){
    public void init(AssetManager assetManager, String jenisBg, String jenisRing){
        this.assetManager = assetManager;
        assetManager.setErrorListener(this);

        //load texture atlas yang udah dibikin pake TexturePacker nya (liat ebook page 167)
        assetManager.load(Constants.TEXTURE_ATLAS_OBJECTS, TextureAtlas.class);
        assetManager.load(Constants.TEXTURE_ATLAS_DECORATION, TextureAtlas.class);
        assetManager.load(Constants.TEXTURE_ATLAS_GUI, TextureAtlas.class);

        // inner class objects
        tiang = new AssetTiang(atlasObject);
        bg = new AssetBackgroud(atlasDecoration, jenisBg);
        tombol = new AssetTombol(atlasGui);
        tombolBg = new AssetTombolBg(atlasDecoration);
        ring = new AssetRing(atlasObject, jenisRing);
    }

    @Override
    public void error(AssetDescriptor asset, Throwable throwable) {
        // TODO Auto-generated method stub

    }

    @Override
    public void dispose(){
        assetManager.dispose();
    }

    public class AssetRing{
        public final AtlasRegion ring;

        // jenis ring dimasukin disini, karena jenis ring bisa diganti-ganti sesuai yang dipilih
        public AssetRing(TextureAtlas atlas, String jenisRing){
            if(!jenisRing.equals("")){
                ring = atlas.findRegion(jenisRing);
            }
            else{
                ring = atlas.findRegion("ring-default");
            }
        }
    }
}

And finally, Ring (Object)
public class Ring extends AbstractGameObject{
    private TextureRegion ringOverLay;
    private float length;

    // jenis ring nya
    public String jenis;

    public Ring(float length, String jenis){
        init();

        setLength(length);
        setJenis(jenis);
    }

    // getters
    public float getLength(){
        return this.length;
    }

    public String getJenis(){
        return this.jenis;
    }

    public Vector2 getPosition(){
        return position;
    }

    // setters
    public void setLength(float length){
        this.length = length;
        dimension.set(5.0f, 1.0f);
    }

    public void setJenis(String jenis){
        this.jenis = jenis;
    }

    public void setPosition(float x, float y){
        position.set(x, y);
    }

    private void init(){
        ringOverLay = Assets.instance.ring.ring;  // Assets.instance.namaobjek.atlasregion

        origin.x = dimension.x/2;  // -dimension.x/2;
        origin.y = dimension.y/2;

        position.x = -5.0f;
        position.y = -2.5f;
    }

    @Override
    public void render(SpriteBatch batch) {
        TextureRegion reg = null;
        reg = ringOverLay;

        batch.draw(reg.getTexture(), position.x, position.y, origin.x, origin.y, dimension.x, dimension.y, scale.x, scale.y, rotation, reg.getRegionX(), reg.getRegionY(), reg.getRegionWidth(), reg.getRegionHeight(), false, false);
    }

}

So what's the problem? Okay, the problem is i cannot make the Ring (game object) become clickable.. the Ring is extending AbstractGameObject (which is Actor), and, in the GameController i've add a ClickListener to the Ring object, but the object still unclickable..
Please, anyone tell me what's my mistake?

A: You're using your Actor (in your case, the Ring) incorrectly: Actors are part of Scene2d, and as such must follow precise rules to work correctly.
To answer your question more specifically, Ring needs to be added to a Stage which itself is an InputProcessor. The Stage is responsible to distribute the input events (such as touch events) to the its Actors. Without defining a Stage your Actors will not respond to any input events.
Read up on Scene2d from the link above. This video tutorial is also helpful.


text:
Q: MySQL with Nodd js I am creating a rest api that uses mysql as data base. My confusion is that should i connect to database in every request and release the connection at the end of the operation. Or should i connect the database at the start of the server and make it globally available and forget about releasing the connection

A: I would caution that neither option is quite wise.
The advantage of creating one connection for each request is that those connections can interact with your database in parallel, this is great when you have a lot of requests coming through.
The disadvantage (and the reason you might just create one connection on startup and share it) is obviously the setup cost of establishing a new connection each time.
One option to look into is connection pooling https://en.wikipedia.org/wiki/Connection_pool.
At a high level you can establish a pool of open connections on startup. When you need to make a request remove one of those connections from the pool, use it, and return it when done.
There are a number of useful Node packages that implement this abstraction, you should be able to find one if you look.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Add a hyperlink to a list item pointing to a folder that is NOT on a server (Shared folder) I have modified my list to the point where I can now add hyperlinks to it, but it does not appear that I can simply add my link to the hyperlink field as I had thought.
I attempt to enter the address and a test string of text however unless it is a web address it give me the error

"The address is not valid. To fix this problem, enter an address that can be accessed from any location."
  I have tried using both forward and back slashes in the address line in the hopes that that would help - it didn't. It gives the same error when trying to add a link to my desktop as well.

I am using Sharepoint through Internet Explorer and I believe it is the 2010 version.

I also read through this but it didn't help terribly much as it appears that the user did not have the same error I am receiving:
File:// hyperlink to a shared drive
I'm quite unfamiliar with SharePoint so perhaps this is not the best way to go about doing this, but the end goal is to have on SharePoint a list of links to our finished optimization runs (stored on our shared folder) that can be sorted and filtered by their different parameters. Initially the attempt was to "attach" a shortcut file but that just resulted in it pulling the actual file which would have added up to a large amount (too large) of data being on SharePoint.

A: Instead of K:/ try file://K:/
Or even better, find out the real address of the fileshare that you've got mapped to the drive letter K. When you go to your Computer and you see the K drive listed under Network Locations, does it have a name like Something (\\contoso.com) (K:)? If it was named using the default values when mapping a drive, that would mean its file location is file://contoso.com/Something
Using the drive letter on its own may work depending on your patch level (it works in my environment) but it's dependent on every user having that drive letter mapped to the appropriate fileshare location on each of their devices. That's why using the actual file share name is preferable.

A: You need to use the file:// protocol handler, e.g.:
file://fileServerName/shareName
This does work in SharePoint 2010. You will not be able to use drive letters.


text:
Q: How to set factor order and colours in ggplot2 I am trying to assign colors to each of my 7 variables and set my variables in a specific order. However 'my_scale' in the geom_col code seems to override my factor order and puts them back in alphabetical order. They are ordered correctly when I run the script without the 'my_scale' line.
my_colors <- c("#1b9e77", "#d95f02", "#66A628", "#E81E89", "#7570b3", "#FFC000", "#0E85F2")
names(my_colors) <- levels(factor(c(levels(behavssec$Behaviour), levels(behavssec$Behaviour))))
my_scale <- scale_fill_manual(name = "Behaviour", values = my_colors)
behavssec$Behaviour <- factor(behavssec$Behaviour,levels = c("Burst","High energy swimming"   , "Medium energy swimming", "Low energy swimming", "Travel", "Ascending", "Descending"))

ggplot(behavssec, aes(fill=Behaviour, y=n, x= SharkID)) +
    geom_col(position = position_dodge2(width = 0.9, preserve = "single"))+
  theme_classic ()+ my_scale +
  theme (axis.text.x=  element_text( size = 12))+
theme (axis.text.y = element_text( size=16))+
  labs(x= "SharkID", y= "Time (second)")

Graph with my_scale - colors assigned to factor but in the wrong order:

Factors in the right order but without my assigned colors:

This is the data I am working with:
SharkID Behaviour   n
2   High energy swimming    2067
2   Medium energy swimming  3413
3   High energy swimming    16473
3   Medium energy swimming  15191
4   Burst   11
4   High energy swimming    825
4   Low energy swimming 24855
4   Medium energy swimming  465
5   High energy swimming    38
5   Low energy swimming 20063
5   Medium energy swimming  12
6   Burst   102
6   High energy swimming    21262
6   Medium energy swimming  6233
1   Ascending   1654
1   Burst   19
1   Descending  1211
1   Low energy swimming 5357
1   Travel  10685

A: You had the right idea. For scale_fill_manual the colors need to be supplied in a named vector. Slightly simplified example:
Code
my_colors <- c(
    "#1b9e77", "#d95f02", "#66A628", "#E81E89",
    "#7570b3", "#FFC000", "#0E85F2"
)
names(my_colors) <- levels(behavssec$Behaviour)

ggplot(behavssec, aes(x = SharkID, y = n, fill = Behaviour)) +
    geom_col(position = position_dodge2(width = 0.9, preserve = "single")) +
    scale_fill_manual(name = "Behaviour", values = my_colors)

Data
library(ggplot2)
behavssec <- structure(list(SharkID = c(2L, 2L, 3L, 3L, 4L, 4L, 4L, 4L, 5L,
5L, 5L, 6L, 6L, 6L, 1L, 1L, 1L, 1L, 1L), Behaviour = c("High energy swimming",
"Medium energy swimming", "High energy swimming", "Medium energy swimming",
"Burst", "High energy swimming", "Low energy swimming", "Medium energy swimming",
"High energy swimming", "Low energy swimming", "Medium energy swimming",
"Burst", "High energy swimming", "Medium energy swimming", "Ascending",
"Burst", "Descending", "Low energy swimming", "Travel"), n = c(2067L,
3413L, 16473L, 15191L, 11L, 825L, 24855L, 465L, 38L, 20063L,
12L, 102L, 21262L, 6233L, 1654L, 19L, 1211L, 5357L, 10685L)), class = "data.frame", row.names = c(NA,
-19L))

behavssec <- read.table(text = "
SharkID,Behaviour,n
2,High energy swimming,2067
2,Medium energy swimming,3413
3,High energy swimming,16473
3,Medium energy swimming,15191
4,Burst,11
4,High energy swimming,825
4,Low energy swimming,24855
4,Medium energy swimming,465
5,High energy swimming,38
5,Low energy swimming,20063
5,Medium energy swimming,12
6,Burst,102
6,High energy swimming,21262
6,Medium energy swimming,6233
1,Ascending,1654
1,Burst,19
1,Descending,1211
1,Low energy swimming,5357
1,Travel,10685
", header = TRUE, sep = ",")

behavssec$Behaviour <- factor(
    behavssec$Behaviour,
    levels = c(
        "Burst","High energy swimming",
        "Medium energy swimming",
        "Low energy swimming",
        "Travel",
        "Ascending",
        "Descending"
    )
)


text:
Q: Example for equality of Integral. Let $f,g$ be bounded real valued function defined on $[a,b] \subset \mathbb{R}$. My source says that:

Suppose that $f(x)< g(x)$ for all $x\in [a,b]$ and $f,g$ are Riemann Integrable on $[a,b]$.
Then $\int_a^b f \leq \int_a^b g$.

I do not understand why $\le$ is used instead of $<$.
Is this meant to imply that the equality case exists? If so, could you provide an example?
Thanks for your help.


text:
Q: Is it reasonable to assume/require the .NET framework these days? Background:
I have a project where I need to provide the user a download package with some sensitive data in it.  The data needs to be encrypted.  After they download it, they need to be able to view it (no editing required).   For this question, let's approximate the data as a series of static html files.  Because the data is sensitive, it needs to be encrypted any time it is on disk.
We are thinking of providing the user with a download option that would give them a zip file containing two files:

*

*A data file (we'd probably use an encrypted zip file behind the scenes) with the data they asked for

*An application to view the data that would appropriately prompt for a passphrase and handle decrypting the data and displaying it via an embedded web browser.

Additional details:

*

*Users are not under our control.  They are consumers.

*We are not worried about cross platform in this question.  This is just about Windows.  We will have a separate download for Mac users.

Get to the question already:
For that application we need to create, we're internally debating if it is reasonable for that app to be a .NET winforms application.  We want a single .exe, and we want the download to be reasonably small (e.g. 100k).

*

*Dare we use the .NET framework (we don't need to use a particularly recent version of .NET--2.0 would be fine)?

*Is it reasonable to assume that most consumers have .NET on their machines now due to Windows Update?

*Is it reasonable to ask the ones that don't have it to install it?

We know that not 100% of users will have .NET installed.  The real question is if it is reasonable to ask them to have it in this day and age.
P.S.  Does anyone know of any reliable statistics of what percentage of people actually do have .NET installed already?

A: I don't know if it's reasonable to ask them to have it or not.  However, I do know that customers are often unreasonable, so I don't see that it matters.  If you're dealing with a limited number of customers, ask them.  If you're dealing with more customers than you can reasonably talk to, or you're going to pick up customers over time, just make sure they see the requirement before buying.

A: What version of Windows are your users on?
If it's Windows Vista they'll have .NET 3 installed by default and if it's Windows 7 they'll have version 3.5. Source.
That doesn't help if they're on XP, but as Microsoft have just stopped support for SP2 they should be on SP3.
If you use something like "ClickOnce" (there are other installers available) you can make the relevant version of the .NET framework a prerequisite and it will download and install it for you - it's not included in your installer. If you are worried about the size of the download you could go to .NET 3.5 or 4 and make the Client Profile which is a much smaller download, though the .NET 4 version is more flexible.

A: A while back I read some posts from Paint.NET on the install process, and how to improve it.  Have a look at these two blog entries.  The first describes the awkwardness of installing the .NET Framework separately; the second describes how the author integrated it as part of the install.
The Paint.NET install experience — Part 1, version 3.xx  (the old bad way)
The Paint.NET install experience — Part 2, version 4.0  (the new good way)
So even if you're going to require the .NET Framework, and you're not sure whether the users will have it, you can at least integrate its installation with your app in a reasonably painless way.

A: Many corporate users are not on the latest version of Windows (Still on XP), but I think more home users have upgraded because of new hardware. Downloading and installing is a little bit of a pain. Is this file usually a one-time thing per client or will they continue to get files in the future?
What are your other options? Are password protected Acrobat files enough? It would be a lot easier to block: saving, printing, and copy and pasting.
Seems like you're reinventing the wheel, but I don't have all the specifics.

A: I did some research on the subject by tracking data on over 10000 installations accross the world for a desktop application targeting the .Net Framework 3.5 sp1. Only a bunch (about 10) did not have the proper framework installed. I removed the heavy .net framework  installation file from the installer, and did not notice any problem yet.
I highly suggest you to conduct the same study in your market and decide based on the results rather than on answers you could get on communities like this one.

A: By default, Windows XP doesn't include any version of the .NET framework.
Vista, and Server 2008 include .NET Framework 3.0, Windows 7 and Server 2008R2 include .NET 3.5, and Windows 2000 can't support anything above .NET 2.0.
With that in mind, it comes down to the OS spread in your target audience. I would list the requirement prominently on the download page and provide a link to Microsoft Update/Downloads section for the framework download, in addition to your application download.

A: Depends on your demographics...
If I wanted anyone[1] to be able to use it, I would finangle up a 32-bit app that would run on Win98 and W7.
That probably means C++/MFC stuff.
[1] Anyone with a machine younger than 12 years old that has an internet connection that is running Windows 98+.

A: .NET 4 is now part of Windows update (the KB was issued in July 2010). As long as the machine is current on their Windows updates, then you are pretty much guaranteed they have .NET 4.

A: Just make sure that the package you ship contains a dependency on the required version of the framework.  Then the package manager the user has will pull the necessary framework version and install it before your package.
Oh, the operating system you target has a very crippled package management system, which can't do this?  It should be a bad OS then.  Well, then you have only one option: require this framework installed and provide the link for user to do it.  I don't see how users benefit, if a noticeable part of what developers do is devoted to useless compatibility with "standard" OS tools (this time could be spent for fixing bugs and adding features instead).

A: If you know, that 100% of your customers don't have it, why did you code the application with .net?
You could have use Java and create a Web-Start Application.
But in fact, you can bundle the .net framework with the installer. If the Customer trust you to install your Application, he will install .net, too.


text:
Q: How to add admin_menu for regular users on wordpress plugin I am trying to add a custom submenu on my wordpress plugin using below code, but this is only available for admins how can i add a sub menu for regular users?
add_action('admin_menu')

A: Ok i manage to display it by changing the capability from manage_options to read referensing on this link https://codex.wordpress.org/Roles_and_Capabilities


text:
Q: How can I fix this to where the function will print out the results of the key_shift change into the output file? Thanks to the users here who already replied!  Now I am still having problems outputting the stream to the output file.  I don't think I should be using out_stream.put(ch); or out_stream << ch; .  I am missing something here for outputting the stream.
#include <iostream>
#include <cstdlib>
#include <fstream>

using namespace std;

void display_menu();     //Display the menu
void get_files(ifstream& in_stream, ofstream& out_stream);
void encrypt(ifstream &in_stream, ofstream &out_stream, int key_shift);       //Encrypts a file
int get_num_1_through_10(int number);   //Gets an integer numbered 1-10 and has the user re-enter integer if incorrrect

int main()
{
ifstream in_stream;   //declaring the input file path
ofstream out_stream;  //delcaring the output file path
string in_filename, out_filename;

int option;         //Declaration of user "option" choice
int key_shift;          //Declaration of user "shift key value" choice
do                  //Runs menu at least once
{
    display_menu();         //function call
    cin >> option;          //User inout for the option menu
    switch(option) {

        case 1:     cout << "Enter a value between 1 and 10 for the shift   key value: ";           //Prompts the user to choose a "shift key value" between   integers 1-10
                    cin >> key_shift;                                                                   //User input for the "shift key value"

                    get_num_1_through_10(key_shift);                                                    //Function call to get a number 1-10

                    cout << "You have chosen a shift key value of " << key_shift << endl;           //Prints to screen users "shift key value" choice
                    break;

        case 2:     cout << "Time to get the files set up!\n";

                    cout << "Beginning the encryption process...\n";

                    encrypt(in_stream, out_stream, key_shift);

                    in_stream.close();
                    out_stream.close();

                    break;

        case 3:     break;

        case 4:     cout << "Goodbye" << endl;                          //User chooses to quit the program
                    return 0;

        default:    cout << "Enter a choice 1-4" << endl;      //Alerts the   user of incorrect input
    }

} while (option != 4);    //While option is anything other than 1-4, quits
return 0;                 //Quits
}

void display_menu() {
cout << "1) Set the shift key value" << endl;
cout << "2) Encrypt a message" << endl;
cout << "3) Decrypt a message" << endl;
cout << "4) Quit" << endl;
cout << "Type in an option and hit enter: ";
}

int get_num_1_through_10(int number) {

if ( (number > 0) && (number < 11) ) {        //Excluding integers except integers 1-10

    return number;                          //If true, returns the users integer choice
}

else {                                                      //If false, returns user back to menu function
    cout << "Please input a number between 1 and 10\n";     //Reminds the user of incorrect integer input
    return main();                                          //Returns to main function
}
}

void encrypt(ifstream &in_stream, ofstream &out_stream, int key_shift) {

ifstream in_filename;
ofstream out_filename;
get_files(in_filename, out_filename);

char ch;

do {

 (in_stream.get(ch));

    while (ch != '\n') {
        ch = ch + key_shift;
    out_stream.put(ch);
    }
}
return;
}

void get_files(ifstream& in_stream, ofstream& out_stream) {

string in_filename, out_filename;
cout << "Enter the source file name: ";
cin >> in_filename;                         //User types in the file name to  receive data
cout << "Enter the destination file name: ";
cin >> out_filename;                        //User types in the file name to  output the data to

in_stream.open(in_filename.c_str());      //Opens the stream for input file
out_stream.open(out_filename.c_str());    //Opens the stream for out file

if ( in_stream.fail() || out_stream.fail() ) {       //If the input or  output fail
    cout << "Error opening input/output files\n";  //Alerts the user of  failure
    exit(1);                                       //Terminates
}

cout << "Files opening!" << endl;
}

A: Problem 1:
while (!in_stream.eof())

Will read past the end of the file and provide one extra reading before it tests that it's hit the end of the file. More here: Why is iostream::eof inside a loop condition considered wrong?
Solution:
Read, then test for a valid read (and not just for EOF because many things can go wrong), and then, if the read is valid, use the value read.
Problem 2:
in_stream.get(ch);
while (!in_stream.eof()) {
    while (ch != '\n') {
        ch = ch + key_shift;
    out_stream << ch;
    }
}

Nowhere in this loop is ch read. If the value is not read, it won't change, and you can be pretty sure the EOF is never going to be read.
Solution:
Read ch in the loop.
Something like
while (in_stream.get(ch)) {

    while (ch != '\n') {
        ch = ch + key_shift;
        out_stream << ch;
    }
}

Should kill both stones with one bird. while (in_stream.get(ch)) reads and then tests, only entering the body of the loop if the read is successful.


text:
Q: Can set-theoretic forcing exist without law of excluded middle? Of course the law of excluded middle is accepted by almost every mathematician except a few constructivists, but then I was wondering if set-theoretic forcing can exist without law of excluded middle. Of course some may say that the real question must be what will happen set theories (eg. ZF) without excluded middle, but then I will stick with my question.

A: Yes.  Consider Intuitionistic Zermelo set theory (IZ) and Intuitionistic Zermelo-Fraenkel set theory (IZF) as presented in chapter 8 of Bell's "Set Theory:  Boolean-valued models and Independence Proofs", third edition.  Forcing in these set theories would use Heyting-algebra-valued models as classical ZF would use Boolean-valued models (pp. 165-166).  Bell shows that the Law of Excluded Middle (LEM) holds in a Heyting-algebra-valued model if and only if the Heyting algebra in question is a boolean algebra.  Since the Axiom of Choice implies LEM, the Axiom of choice does not hold in any Heyting-algebra-valued model for which the Heyting algebra in question is not a boolean algebra (this last sentence is a paraphrase of a statement of Bell's found on pg. 166 of his book).


text:
Q: wordpress comments file hey guys!
So, I have this question:
I'm working with wordpress to make a blog but I'm having a little trouble with the source files for the comments. On the original wordpress theme (TWENTY TEN'S THEME) the generated html code is basically like this:

                John Doe

            says:

            26 de January de 2011 at 12:17

Adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nLorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nLorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

        Reply

so, what i need is to insert a new div between the div with the class 'comment-meta commentmetadata' and the div with class 'comment-body'.
I've already tryied to edit this in the 'comment-template.php' file but with no success (apparently this is not the right file).
Can anyone tell me which the right file is?
Regards! ;)

A: Wordpress allows you to specify a callback for the comment layout, in case of twentyten it's done like this:
wp_list_comments( array( 'callback' => 'twentyten_comment' ) );

The callback twentyten_comment is defined in functions.php.


text:
Q: How to use the 'count' parameter in tweepy's streaming API? I can use the streaming API just fine when I don't include the count parameter in filter() call, but when I try to specify how many tweets from my history I want to receive, my stream object returns None.
import tweepy
from tweepy.streaming import StreamListener, Stream

class Listener (StreamListener):
    def on_status(self, status):
        print '-' * 20
        print status.text
        return

def get_tweets(request):
    # if request.is_ajax():
    # All keys and secrets are declared here, but were removed for security reasons.

    auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
    auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
    api = tweepy.API(auth)
    listener = Listener()
    stream = Stream(auth, listener)
    stream.filter(follow=("14739093",), count=-5)

I also tried the following, to see what it was returning.
>>> something = stream.filter(follow=("14739093",), count=-5)
>>> print something
None

Thanks for your help!

A: Stream.filter always returns None, its job is just to pass the data on to the StreamListener.
Your problem is that Twitter only allows the count parameter for certain "roles".

Firehose, Links, Birddog and Shadow clients interested in capturing all statuses should maintain a current estimate of the number of statuses received per second and note the time that the last status was received. Upon a reconnect, the client can then estimate the appropriate backlog to request. Note that the count parameter is not allowed elsewhere, including track, sample and on the default access role.

This is the reason you're getting a 413 error when you try to use the count parameter -- you're on the "default access" role.


text:
Q: D3 Plot array of circles I've tried the circle plot example as the following:
  var x=20, y=20, r=50;
  var sampleSVG = d3.select("#viz")
  .append("svg")
  .attr("width", 800)
  .attr("height", 600);

  sampleSVG.append("circle")
  .style("stroke", "gray")
  .style("fill", "white")
  .attr("r",  r)
  .attr("cx", x)
  .attr("cy", y);

But  I want to figure out how to plot without a loop a sequence of circles from an array like:
  data = [
          [10,20,30],
          [20,30,15],
          [30,10,25]
         ];

A: Maybe this example could help?
var data = [
    [10,20,30],
    [20,30,15],
    [30,10,25]
];

var height = 300,
    width = 500;

var svg = d3.select('body').append('svg')
    .attr('height', height)
    .attr('width', width)
  .append('g')
    .attr('transform', 'translate(30, 30)');

// Bind each nested array to a group element.
// This will create 3 group elements, each of which will hold 3 circles.
var circleRow = svg.selectAll('.row')
    .data(data)
  .enter().append('g')
    .attr('transform', function(d, i) {
        return 'translate(30,' + i * 60 + ')';
    });

// For each group element 3 circle elements will be appended.
// This is done by binding each element in a nested array to a
// circle element.
circleRow.selectAll('.circle')
    .data(function(d, i) { return data[i]; })
  .enter().append('circle')
    .attr('r', function(d) { return d; })
    .attr('cx', function(d, i) { return i * 60; })
    .attr('cy', 0);

Live Fiddle


text:
Q: OpenGL extensions causing linker problems I'm trying to get the addresses for the VBO addon. In my stdafx.h I have the gl.h, glext.h and wglext.h
If I do:
    glGenBuffersARB =
        (PFNGLGENBUFFERSARBPROC)wglGetProcAddress("glGenBuffersARB");
    glGenBuffersARB(0,0);
in stdafx.cpp, this will compile.
but if I try to use glGenBuffersARB(0,0); in any of my other h or cpp files I get:
Error   11  fatal error LNK1169: one or more multiply defined symbols found C:\Users\Josh\Documents\Visual Studio 2008\Projects\Vectorizer Project\Release\Vectorizer Project.exe
Error   10  error LNK2005: _glGenBuffersARB already defined in OGLENGINE.obj    stdafx.obj

what is the proper way of doing this so I can use the vbo extension anywhere in my code?
Thanks

A:
_glGenBuffersARB already defined

You probably declared glGenBuffersARB as a global variable in a header (*.h) file, and forgot to add "extern".

what is the proper way of doing this so I can use the vbo extension anywhere in my code?

Use GLEE or GLEW.

A: You have a linking error that looks like you have more than one definition for glGenBuffersARB. As a first debugging step I would change it so that the name of you function pointer is not the same as the name of the function that you are getting the address of.
fp_glGenBuffersARB = (PFNGLGENBUFFERSARBPROC)wglGetProcAddress("glGenBuffersARB");

It may be that the function is already defined with the name glGenBuffersARB in a library that you are linking to.
You don't show what context you are calling wglGetProcAddress or what scope your variable glGenBuffersARB (or fp_glGenBuffersARB following my rename) has but you must ensure the there is only a single definition for it. You can forward declare it in a header file but you must just have a single definition.


text:
Q: how to trap the value error in python If any file is corrupted and cannot be open, the following code raise value error and stop opening of further files.
How can I print out the name of the file which raised value error, and make the program to run further to detect and print out next file which raise value error?
import glob
from PIL import Image
files = glob.glob('*.jpg')
for f in files:
    im = Image.open(f)
    print im

A: You can catch the exception with a try: / except: handler:
for f in files:
    try:
        im = Image.open(f)
    except IOError as e:
        print '{} failed to load: {}'.format(f, e)
    else:
        print im

The Python tutorial has a chapter devoted to error handling you might want to read.

A: You can use try/except bloks in here.
since PIL's Image.open method uses python standart library function open you can handle exceptions as open function do. In your case it will raise an IOError
for f in files:
    try:
        _f = Image.open(f)
    except IOError as e:
        print 'Can not open file: %r. Exception is: %r' % (f, e)
    else:
        # Do your operations in here
        print _f


text:
Q: How to change getElementbyID script to getElementsbyclassname? I have a script for a pop up booking tool I am trying to implement onto my site.
The script provided by the company is tied to a getElementbyID, but I need to be able to use the scirpt for several locations on a page, so I need to convert it.
Here is the script I am working with:

Can anyone help me create a script that allows for getElementsbyclassname or similar so I can use it easily across my site?
Thanks so much

A: I think this is a good way to do

  const id =
    document.getElementById('teachworks-booking-button').getAttribute("id");
    class =  document.getElementById('teachworks-booking-button').class=id;
    //if the id already have class then use this
    document.getElementById('teachworks-booking-button').classList.add(id);

A: getElementsByClassName implies accessing a collection, which means that you need to use a loop. I gave an example with method forEach().
Array.from(document.getElementsByClassName("teachworks-booking-button")).forEach(function (btn_current) {
    btn_current.onclick = function () {
        this.insertAdjacentHTML("afterend", "");
    };

    // event listener
    var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
    var eventer = window[eventMethod];
    var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
    eventer(
        messageEvent,
        function (e) {
            if (e.data == "close") {
                document.getElementById("booking-iframe").remove();
            }
        },
        false
    );
});


text:
Q: Running a shell command from Node.js without buffering output I'm trying to launch a shell command from Node.js, without redirecting that command's input and output -- just like shelling out to a command using a shell script, or using Ruby's system command. If the child process wants to write to STDOUT, I want that to go straight to the console (or get redirected, if my Node app's output was redirected).
Node doesn't seem to have any straightforward way to do this. It looks like the only way to run another process is with child_process, which always redirects the child process's input and output to pipes. I can write code to accept data from those pipes and write it to my process's STDOUT and STDERR, but if I do that, the APIs force me to sacrifice some flexibility.
I want two features:

*

*Shell syntax. I want to be able to pipe output between commands, or run Windows batch files.

*Unlimited output. If I'm shelling out to a compiler and it wants to generate megabytes of compiler warnings, I want them all to scroll across the screen (until the user gets sick of it and hits Ctrl+C).

It looks like Node wants to force me choose between those two features.

*

*If I want an unlimited amount of output, I can use child_process.spawn and then do child.stdout.on('data', function(data) { process.stdout.write(data); }); and the same thing for stderr, and it'll happily pipe data until the cows come home. Unfortunately, spawn doesn't support shell syntax.

*If I want shell syntax, I can use child_process.exec. But exec insists on buffering the child process's STDOUT and STDERR for me and giving them to me all at the end, and it limits the size of those buffers (configurable, 200K by default). I can still hook the on('data') events, if I want to see the output as it's generated, but exec will still add the data to its buffers too. When the amount of data exceeds the predefined buffer size, exec will terminate the child process.

(There's also child_process.execFile, which is the worst of both worlds from a flexibility standpoint: no shell syntax, but you still have to cap the amount of output you expect.)
Am I missing something? Is there any way to just shell out to a child process in Node, and not redirect its input and output? Something that supports shell syntax and doesn't crap out after a predefined amount of output, just like is available in shell scripts, Ruby, etc.?

A: You can inherit stdin/out/error streams via spawn argument so you don't need to pipe them manually:
var spawn = require('child_process').spawn;
spawn('ls', [], { stdio: 'inherit' });

Use shell for shell syntax - for bash it's -c parameter to read script from string:
var spawn = require('child_process').spawn;
var shellSyntaxCommand = 'ls -l | grep test | wc -c';
spawn('sh', ['-c', shellSyntaxCommand], { stdio: 'inherit' });

To summarise:
var spawn = require('child_process').spawn;
function shspawn(command) {
   spawn('sh', ['-c', command], { stdio: 'inherit' });
}

shspawn('ls -l | grep test | wc -c');

A: I haven't used it, but I've seen this library: https://github.com/polotek/procstreams
It you'd do this. The .out() automatically pipes to  the process's stdin/out.
var $p = require('procstreams');
$p('cat lines.txt').pipe('wc -l').out();

If doesn't support shell syntax, but that's pretty trivial I think.
var command_str = "cat lines.txt | wc -l";
var cmds = command_str.split(/\s?\|\s?/);
var cmd = $p(cmds.shift());
while(cmds.length) cmd = cmd.pipe(cmds.shift());
cmd
  .out()
  .on('exit', function() {
    // Do whatever
  });

A: You can replace exec by spawn and use the shell syntax simply with:
const {spawn} = require ('child_process');
const cmd = 'ls -l | grep test | wc -c';
const p = spawn (cmd, [], {shell: true});

p.stdout.on ('data', (data) => {
  console.log (data.toString ());
});

The magic is just {shell: true}.

A: There's an example in the node docs for the child_process module:
Example of detaching a long-running process and redirecting its output to a file:
 var fs = require('fs'),
     spawn = require('child_process').spawn,
     out = fs.openSync('./out.log', 'a'),
     err = fs.openSync('./out.log', 'a');

 var child = spawn('prg', [], {
   detached: true,
   stdio: [ 'ignore', out, err ]
 });

 child.unref();


text:
Q: Can't type ^ and ` I recently had problems with not being able to type in umlauts into the terminal which was resolved here.
Umlauts are working fine, but now I can't type in a ^ and a ` (Can't put it in code-tags as it is the code-encloser on this site). The strange thing is that this does only apply to some application of which the terminal is one (alongside with TeXStudio, KWrite and Kate).
In my Firefox browser and in LibreOffice (only tested in Calc so far) the keyboard works just as expected.
I did check for the keyboard layout but that is set correctly. The rest of the keyboard is also working as expected (I can even use ° which is on the same key as ^).
Therefore my question is if someone has any idea where this problem might come from and how I might be able to fix it.
I'm running Linux Mint 18.3 alongside the 4.10.0-38-generic kernel.
In case it is important: Here's the output of locale:
LANG=nds_DE.UTF-8
LANGUAGE=en_US
LC_CTYPE="nds_DE.UTF-8"
LC_NUMERIC="nds_DE.UTF-8"
LC_TIME="nds_DE.UTF-8"
LC_COLLATE="nds_DE.UTF-8"
LC_MONETARY="nds_DE.UTF-8"
LC_MESSAGES="nds_DE.UTF-8"
LC_PAPER="nds_DE.UTF-8"
LC_NAME="nds_DE.UTF-8"
LC_ADDRESS="nds_DE.UTF-8"
LC_TELEPHONE="nds_DE.UTF-8"
LC_MEASUREMENT="nds_DE.UTF-8"
LC_IDENTIFICATION="nds_DE.UTF-8"
LC_ALL=

A: I was able to work around this problem by using another keyboard layout variation: German (Macintosh, elimitate dead key).
This eliminates the dead keys completely though, so that I can't type any accented letters using dead keys.


text:
Q: Read the output of a process fluidly in Java In java, I am trying to read the output from a consoleprogram I wrote in C.
This program is continuously printing its current progress into stdout using printf().
If I run that program in a console, everything is fine, I am seeing the output.
I am now trying to run it from inside java, which also runs fine, the process is starting and calculating, but the whole output however will be read in huge blocks at once (There is no output for some seconds and then everything appears at once).
I assume there is some kind of a buffer in between that must be filled.
In order to draw a progressbar and work with other parameters the program is printing it is neccessary to read from the stdout fluidly and not everything at once.
I already read about this in Questions like Problem reading InputStream from Java Process (Runtime.getRuntime().exec() or ProcessBuilder), but this did not help me very much as I followed the tips in these questions.
Below is the code I am currently trying to use.
public static void main(String[] args)
{
    ProcessBuilder builder = new ProcessBuilder("render.exe", "1920", "1080", "10000", "0", "0", "1", "6", "test.png");
    try
    {
        final Process proc = builder.start();
        final Thread io = new Thread()
        {
            @Override
            public void run()
            {
                final InputStream read = proc.getInputStream();
                int c;
                try
                {
                    while((c = read.read()) != -1)
                        System.out.print((char)c);
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        };
        io.start();
        proc.waitFor();
    }
    catch (IOException | InterruptedException e)
    {
        e.printStackTrace();
    }

}

A: The C program probably detects that its stdout is not connected to an interactive console and buffers its output; you cannot change this from Java.
Assuming you use stdio, to make the C program produce output more fluidly you can add fflush(stdout) in appropriate places, or you can disable buffering with a call to setvbuf:
setvbuf(stdout, NULL, _IONBF, 0);


text:
Q: How to make Mathematica use the chain rule? Lets say I have the following PDE:
$$x^2 u_{xx}  - u_{yy} + u_y = 0$$
And I have the following change of variables:
$$ s(x,y) = x e^y \, \, \, , \, \, t(x,y) = x e^{-y}$$
How can I use Mathematica to compute $u_{xx}, u_{yy},u_y$ on terms of $u_{ss},u_{tt}, u_{ts},u_t,u_s$ using the definitions and the chain rule?

A: Just in case someone else need it (for example, quite possibly myself in the future), this is how I've done it
(Note: In the answer a different change of variables has been used)
s[x_, y_] := Log[x] + y
t[x_, y_] := Log[x] - y
Factor@D[u[s[x, y], t[x, y]], {x, 2}]
FullSimplify@D[u[s[x, y], t[x, y]], y]
Factor@D[u[s[x, y], t[x, y]], {y, 2}]
x^2 D[u[s[x, y], t[x, y]], {x, 2}] -
  Factor@D[u[s[x, y], t[x, y]], {y, 2}] +
  FullSimplify@D[u[s[x, y], t[x, y]], y] // FullSimplify

Which outputs the following:

Reading the output is quite anoying, but it was good enough for what I needed. (I'm sure it can be improved easily)

A: expr = x^2 D[u[x, y], {x, 2}] - D[u[x, y], {y, 2}] + D[u[x, y], y]

$Assumptions = {s > 0, t > 0}
expr /. u -> (u[# Exp[#2], # Exp[-#2]] &) /. {x -> Sqrt[s t],
                                              y -> Log[Sqrt[s/t]]} // Simplify

Second set of replacement rules is from:
Eliminate[s == x Exp[y] && t == x Exp[-y], x]
Eliminate[s == x Exp[y] && t == x Exp[-y], y]

E^(2 y) t == s
s t == x^2 && (s t)/x == x

I've forced $Assumptions so things like Sqrt[s^2] are reduced to s but keep them in mind. Sometimes it may be important.


text:
Q: Contacts see me Offline on WLM Althoung I'm online and chatting with them this problem appears just a few days ago , and still till this moment ,
my problem is that Contacts in my Windows Live Messenger (Version :14.0.8089.726 ) told me that I'm offline while I'm online , some of theme told me that I log in and out every moment while I'm still log in , after that they see me online again ,
so what is the problem exactly , and how can I get rid of it ?
Notice : I think problem started after they (Windows Live) make the feature that you can sign in from 2 messengers at same time .

A: I don't know if/how you solved this issue, but I think this might help someone else; I'm having the same problem with a fresh LiveID, so I guess it's a server problem.
I see that contacts I've added through the WLM interface appear as blocked.
My guess is, since there is no more a "blocked" status on WLM2011, they are then using the blocked flag for something else;
in particular, I think they are trying to link the profiles (along with their "social updates") to the WLM contacts. If you and your contact can't see online each other (you or him/her) try and see if one of you has a pending friend request on his/her live profile.
I think your contact appears to you as "blocked" when (s)he hasn't still accepted you on his/her live profile.
Once accepted, both of you log out and back in, and see if something has changed.
While the change (similar to what Facebook does, only on FB you accept the friend request once and for all) makes sense, it makes very little sense to do it like this.
HTH

A: *

*Did you try to check that you didn't make your status "Appear as Offline"?

*It could be a virus or  a piece of malware. Try to run a antivirus scan and a malware scan.

A: While i was searching about the problem i found that it happening alot for many WLM users, anyways i found this comment and it might help you:

I understand that you're still appearing offline to your contacts even you're online. I know this is quite inconvenient. Allow me to guide you in resolving this.
From our investigation, this issue usually happens when the Messenger cache folder of your account stored in your computer is corrupted. It is also possible your contacts are moved to your allow or block lists.
To resolve your issue, I will be giving to you the steps to delete the corrupted Messenger cache folder of your account stored in your computer. I have also included the steps to verify if those contacts that see you as offline are moved to allow or block lists.
Note: To fix the problem, please make sure that you and your friends follow these steps:
Step 1
- Here are the steps to delete Messenger cache folder:

*

*Right-click the Start button and then click Explore. In the window that opens, On the Tools menu beside Favorites and Help menu, click Folder Options. Click the View tab, and then make sure that Show Hidden files and folders option is selected.

Note: After you delete Messenger cache folder, it will regenerated a new and fresh copy of Messenger cache folder in your computer.
For Windows XP user, here are the steps:

*

*Click Start, click Run, copy and paste this message %USERPROFILE%\Application Data\Microsoft\ and then press Enter. Delete the IdentityCRL folder.

*Click Start, click Run, copy and paste this message %ALLUSERSPROFILE%\Application Data\Microsoft\ and then press Enter. Delete the IdentityCRL folder.

*Click Start, click Run, copy and paste this message %USERPROFILE%\Local Settings\Application Data\Microsoft\ and then press Enter. Delete the Windows Live Contacts folder.

*Click Start, click Run, copy and paste this message %USERPROFILE% and then press Enter. Delete the Contacts folder.

For Windows Vista users, here are the steps:

*

*Click Start, copy and paste this message in the Start Search box %USERPROFILE%\AppData\Local\Microsoft\ and then press Enter. Delete the Windows Live Contacts folder.

*Click Start, copy and paste this message in the Start Search box %userprofile% and the press Enter. Delete the Contacts folder.

*Sign in to Windows Live Messenger.

Step 2
- Try to sign in to Messenger and verify if the issue still persists.
If the issue still persists, it's possible that your contacts are move to your allow or block lists.
Here are the steps on how you'll appear online to you contacts once you performed completely these steps:
Here are the steps to re-add the contact that moved to Allow list:
1.Sign in to Windows Live Messenger.
2.On the Tools menu, click Options and then click Privacy.
3.From the Allow list, right-click the contact that was deleted previously and then click Add to Contacts.
4.Click OK.
Here are the steps to re-add the contact that moved to Block list:
1.Sign in to Windows Live Messenger.
2.On the Tools menu, click Options and then click Privacy.
3.From the Block list, right-click the contact that was previously block and deleted and then click Add to contacts and Move to allow list.
4.Click Apply, and then OK.

Link: http://www.vistax64.com/windows-live/213505-problem-windows-live-messenger-appearing-offline-2.html


text:
Q: Ionic android build failed after added AdMob Pro I just started to use ionic framework to build android apps. So I've run:
ionic start App blank
ionic platform add android
ionic build android
ionic run android

So far so good, I can test my app in my android phone with no problem. Now I want to add admob to my app. I decided to use the AdMobPro, so I did this:
ionic plugin add cordova-plugin-admobpro

The plugin added successfully. Without having implemented the admobpro code in my app.js, I tried to run ionic build android again just to make sure everything is ok, I got this error:
Running: /home/vagrant/app/android-quotes/platforms/android/gradlew cdvBuildDebug -b /home/vagrant/app/android-quotes/platforms/android/build.gradle -
Dorg.gradle.daemon=true

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'android'.
> Could not resolve all dependencies for configuration ':_debugCompile'.
   > Could not find any version that matches com.google.android.gms:play-services-ads:+.
     Searched in the following locations:
         https://repo1.maven.org/maven2/com/google/android/gms/play-services-ads/maven-metadata.xml
         https://repo1.maven.org/maven2/com/google/android/gms/play-services-ads/
     Required by:
         :android:unspecified

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 11.603 secs

/home/vagrant/app/android-quotes/platforms/android/cordova/node_modules/q/q.js:126
                    throw e;
                          ^
Error code 1 for command: /home/vagrant/app/android-quotes/platforms/android/gradlew with args: cdvBuildDebug,-b,/home/vagrant/app/android-quotes/plat
forms/android/build.gradle,-Dorg.gradle.daemon=true
ERROR building one of the platforms: Error: /home/vagrant/app/android-quotes/platforms/android/cordova/build: Command failed with exit code 1
You may not have the required environment or OS to build this project
Error: /home/vagrant/app/android-quotes/platforms/android/cordova/build: Command failed with exit code 1
    at ChildProcess.whenDone (/usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/cordova/superspawn.js:134:23)
    at ChildProcess.emit (events.js:110:17)
    at maybeClose (child_process.js:1015:16)
    at Process.ChildProcess._handle.onexit (child_process.js:1087:5)

Anyone has this error before?
Update 24/8/2015: I have ditch ionic-box and reinstall ionic directly in my windows machine, no more errors. It's a bit disappointed that I can't use ionic-box, but i guess this is the way I have to go.


text:
Q: HTML form with checkboxes and editable input boxes Let me try and describe what I am trying to accomplish:
I want to display a form using a table where each row has a checkbox, a unique identifier for the item in that row and a suggested quantity. The quantity is editable and the user can select a subset of the rows.
The form would submit the following:
For each selected row, the unique identifier and the quantity will be submitted to the server.
I can picture somehow using javascript to "activate" which rows get submitted, but I can't wrap my head around a solution for pairing up the UID + Qty pair.
Any suggestions are welcomed!
Thank you.

A: You can make a form like this:
<?php
$width = 10;
$height = 5;
echo '<form ...>';
echo '
';
for($i=0;$i<$height;$i++){
    echo "
";
    for($j=0;$j<$width;$j++){
    echo ';
    echo '<input type="checkbox" name="'.$i.'x'.$j.'" />';
    echo '<input type="text" name="'.$i.'x'.$j.'value" value="la valeur" />';
    echo '	';
    }
    echo '
';
    }
echo '
';
echo '<submit...>';
echo '</form>';

And then in the treatments part, you can make the two loop, verifying if the checkbox is checked and update the value if it is

A: If your server side language supports it, I would recommend using array syntax. e.g.

  <input type="checkbox" />

  NAME

  <input type="text" name="qty[5]" value="10" />

The server side language would then just need to run through the POSTed qty array, where the index is the UID, and the value is the Quantity. This model can be expanded like so:

  <input type="checkbox" />

  <input type="text" name="name[5]" value="Name" />

  <input type="text" name="qty[5]" value="10" />


text:
Q: Network Service needs to return a callback I have a Networking service that i want to use as a Service. It's a local Service since it's not valid anymore once the application process is dead and no Other applications need to access it.(or should...).
I was pondering if to use the IBinder interface with local reference to the class and decided not to, for the moment.
I have the following issues:

*

*if the service dies, and i know it can during request processing, it's an issue for me, first i've seen it, the process wont die until the net request returns (then the thread dies gracefully), unless kill -9 is used on the process... then i'm not sure what android does with the connections. I'm not sure what's the approach i should take here.(it will be true though even if this was a local thread and not a service...)

*if i want the service to listen on a callback and call it once the network processing is done, i'm in a problem, no instances can be passed on using Intents. So i need some other solutions, all the ones i though of sounds bad to me: A. use IBinder to get instance of the network service class then i can call one of it's methods and pass on an instance, this will work since they all run in the same process, BUT requires me to use Async way to get a Network instance which is not so suitable for me. B. Use static member in the Service i can access, then what to i need the service for ? C. use intent to send parameters only to the service, the service will compose a Request out of it and put it in the queue, then once done will send a response using intent which will encapsulate the response (which might be long!) and will also contain the name of the calling class as a string so all the Receivers will know if it's for them or not - BIG overhead of encapsulating data in Intent and search in all the receivers for the right one to get the response.

I don't want to use the service as a local running simple thread since i'm afraid if i'll run it in the root activity i will have to use static container so it will be visible in each activity and if the root will be destroyed for some reason it will take all the service with it, even if i start new task and the process is still alive...
Anyone got some nice ideas on how to approach this thing ?

A: Eventually i gave up on the service.
The reason to not use the service But to extend Application object and keep the networking class as a member of that Application object, it is started when the application is created, before any activity is created,and it is shut down before the application draws it's last breath. I know application onTerminate might not be called at all times, but if someone will call kill -9 or equivalent on my Application and the process will die killing the application with it, i'm all set as my Service will be destroyed anyway.
The reasons i gave up a service were:

*

*i have a way to keep a worker thread running during the application life cycle.

*Since i have and for future planning will have only one application it will still work in the future.

*Since It's not connected and started with any specific Activity it wont be affected by their death or by their creations.

*it has a context that will last through the lifecycle of the application so i CAN use it to broadcast events using intents.

*when the application dies my service dies with it. unless kill -9 and then the system will kill all threads related to the application, mine included, so i'm still good.

*Every activity can use getApplication() and cast to my Application object and get the service.

So no need to use binding and complicate my code with it, no need to think of how to start or end the service, if i'd made a service most chances i'll be starting it from the Application anyway (or the root activity), so i think for me and my app this is the best option.


text:
Q: Assembly.Load and Assembly.LoadFrom differences? My application loads assemblies it needs via the AppDomain.CurrentDomain.AssemblyResolve event. The assemblies are resources of the executing assembly.
private static Assembly OnResolveAssembly(object sender, ResolveEventArgs args)
{
    var executingAssembly = Assembly.GetExecutingAssembly();
    var assemblyName = new AssemblyName(args.Name);
    var resPath = assemblyName.Name + ".dll";

    using (var stream = executingAssembly.GetManifestResourceStream(resPath))
    {
        if (stream != null)
        {
            byte[] buffer = new byte[stream.Length];
            stream.Read(buffer, 0, buffer.Length);

            return Assembly.Load(buffer);
        }
    }

    return null;
}

In general this works fine but the assembly being loaded contains default styles for certain controls which won't get applied.
BUT if I don't load the assembly via Assembly.Load but save it to a file and load it via Assembly.LoadFrom everything just works fine.
What's the difference between those? Why doesn't it work when loading the assembly directly from memory - or why DOES it work when first saving it to disk and then loading it with Assembly.LoadFrom?
I'm very confused and I want to load the assemblies directly from memory without saving them first.

A: Assembly.Load and Assembly.LoadFrom uses different loading contexts. Assembly.Load loads assembly in the context of host assembly (default context). For correct loading all the dependant assemblies should be avaliable from host application path, GAC or should be loaded manually in advance.
Assembly.LoadFrom does't use host assembly context. It creates own loading context (load-from context) and able to automatically resolve dependant assemblies not present in the default context. These assemblies from a path that is not under the host application path.
It seems your default styles requires assemblies from a path that is not under the host application path.


text:
Q: Execute PHP Code via Ajax Call in drupal module I was trying to convert this into a Drupal module so that I can check PHP code instantly on my site for debugging purposes.  I saw this Firefox add on which allows you to execute PHP on the fly but admin log in is necessary, so far I did everything , have one form and set up ajax calls , but if I pass a string like:
preg_match($pat,$str,$matches);
print_r($matches);

How to execute this in backend?
EDIT
To load the form:
$items['localphp'] = array(
  'page callback' => 'executePHP',
  'access callback' => TRUE,
  'type' => MENU_CALLBACK,
);

function executePHP(){
  $output = drupal_get_form('executePHP_form');
  return $output;
}

Ajax callback function:
$items['runPHP'] = array(
  'page callback' => 'getResult',
  'access callback' => TRUE,
  'type' => MENU_CALLBACK,
);
function getResult(){
  $code = $_POST['code'];
  //I need help here how to execute $code i.e the php code and return back result
  echo $code;
}

JS function
function executePHP(baseurl){
  var code = $("#edit-code").val();
  $.ajax({
      type : "POST",
      url : baseurl+'runPHP',
      data : 'code='+code,
      async : true,
      cache : false,
      success : function (res) {
        $("#edit-result").html(res);
      },
      error : function (res) {
        alert("error");
      }
  });
  return false;
}

A: FYI, the Devel module has a feature that allows admins to run custom PHP code from their page.  The Devel module has a block with a ton of features useful for debugging.
For a custom module, without seeing any of your other code, I can tell you what I have done to achieve AJAX in a Drupal module:
In JavaScript make an AJAX request to a url on your site.  Add a menu item with the specified path inside of hook_menu() as 'type' => MENU_CALLBACK that points to a function in your module.  This function should do all the processing you need, then return the results to JavaScript to do what you want with it there.


text:
Q: Getting element with no attributes using Jsoup I have the following html, using Jsoup I'm trying to extract the text in the p section which does not have any attributes (the text "Some text 2" and not "Some text 1").

        Some text 1

        Some text 2

I tried using the following Jsoup expression:
div[id=intro] > p:not(:has(@*))

But it doesn't work.
Thanks for your help.

A: I think you can use the JSOUP CSS selector p:not([^]), which would select any p that does not match having an attribute starting with anything.
String html = "
"
        + "
"
        + "
"
        +   "Some text 1"
        + "
"
        + "
"
        +   "Some text A"
        + "
"
        + "
"
        +   "Some text B"
        + "
"
        +"
"
        +   "Some text 2"
        +"
"
        +"
 ";

Document doc = Jsoup.parse(html);
Elements els = doc.select("p:not([^])");
for (Element el:els){
    System.out.println(el.text());
}

the above example will only print out
Some text 2

because only this p element has no attributes.
Note that the selector p[^] will pick all p elements that do have an attribute.


text:
Q: convert pdf file into excel sheet Im new to .net,i have a pdf which contains three tables,(with the purchase details)my task is to extract all the 3 tables from the pdf and convert each into an excel sheet(three excel sheets)using c# code.,i google'd for 3days,all i could find was code to extract the text from pdf(but without any formatting),i cant purchase any third party tools,i need a way to atleast extract the text in proper table formats,then i will convert it to excel using interop,OR a code to directly convert to excel,whatever the solution is i need it urgently,pls help.

A: itextpdf has support for c# to extract information from pdf, however to answer whither we can extract table:

As described above: you can't get fields from a PDF that looks like a
  form, if the PDF isn't a form from a technical point of view; you
  can't get a table from a PDF that looks like a table, if the tabular
  structure (using tags) is missing inside the PDF.

Which i got from their support panel

A: I suggest you to look at xpdf.
It has a command line interface and you can obtain a text file from your pdf.
Most important, in case of columns, xpdf produces a well spaced text file so you can easily read your data using Substring() or, in the worst case, with regular expressions.
In the simplest case you can import directly the pdf output into Excel as text file with "fixed width fields".


text:
Q: iText converting incomplete Html file content to pdf using java I am trying to convert html file into pdf using iText lib(4.2.0). But the problem is it's not printing all the html content to pdf, its only partially printing some data. Here is the code to convert html to pdf.
InputStream il = new FileInputStream("/tmp/test.html");

      // step 1
      Document document = new Document();

      // step 2
      PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("/tmp/pdf.pdf"));

      writer.setInitialLeading(12.5f);

      // step 3
      document.open();

      HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);

      htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());

      // CSS
      CSSResolver cssResolver = new StyleAttrCSSResolver();
      InputStream csspathtest =new FileInputStream("/tmp/test.css");
      CssFile cssfiletest = XMLWorkerHelper.getCSS(csspathtest);
      cssResolver.addCss(cssfiletest);

      Pipeline<?> pipeline = new CssResolverPipeline(cssResolver,
                                                     new HtmlPipeline(htmlContext,
                                                                      new PdfWriterPipeline(
                                                                          document, writer)));

      XMLWorker worker = new XMLWorker(pipeline, true);
      XMLParser p = new XMLParser(worker);
      p.parse(il);

      // step
      document.close();

Here is the sample html file http://codepaste.net/65kmhp


text:
Q: Javascript not working on blackberry 5.0 devices I have a website created in hybrid css,html and javascript used. It works well on bb7.0 devices browser . But not on 5.0 devices browser.How can I check which devices support which javascripts or how can I test for the same.

A: Browser support was improved in OS 5.0 and completely re-written in OS 6.0, so my experience is that Browser experience on OS 6.0 is OK (screen size considered) anything prior to OS 6.0 is not so great experience and prior to OS 5.0, the experience can be pretty poor.
The User Agent can be used to determine the level of Browser, see this article for further information:
http://supportforums.blackberry.com/t5/Web-and-WebWorks-Development/How-to-detect-the-BlackBerry-Browser/ta-p/559862
Now with respect to JavaScript support, be aware that users can turn off JavaScript on the BB Browser options.  But the following link may help you decide what JavaScript options are available to you.  Sorry this is not an area of expertise:
JavaScript Information for OS 5.0 and below
Sorry I have not been able to find an equivalent for the later Browsers, but I think that is because it is fully supported.


text:
Q: Need to hook a method pre checkout in magento I have made a magento module, It has multiple methods, of which 1 method is ProcessOrderAction(), I want to call this method every time before i do final checkout, My config file is below.

<?xml version="1.0"?>
<config>
    <modules>
        <kodework_ongoing>
            <version>0.1.0</version>    <!-- Version number of your module -->
        </kodework_ongoing>
    </modules>
    <frontend>
        <routers>
            <mymodule>
                <use>standard</use>
                <args>
                    <module>kodework_ongoing</module>
                    <frontName>ongoing</frontName>
                </args>
            </mymodule>
        </routers>

    </frontend>

</config>

A: You could use the event checkout_cart_save_after to hook into via an observer. This event is fired after the after a cart save usually called after changes with cart items.
To use this you need to update your config.xml with a call to your observer class and your method.
<?xml version="1.0"?>
<config>
    <modules>
        <kodework_ongoing>
            <version>0.1.0</version>    <!-- Version number of your module -->
        </kodework_ongoing>
    </modules>
    <frontend>
        <routers>
            <mymodule>
                <use>standard</use>
                <args>
                    <module>kodework_ongoing</module>
                    <frontName>ongoing</frontName>
                </args>
            </mymodule>
        </routers>
        <!-- Hook into events start -->
        <events>
            <checkout_cart_save_after>
                <observers>
                    <kodework_ongoing>
                        <class>kodework_ongoing/observer</class> <!-- The observer class where with the ProcessOrderAction method -->
                        <method>ProcessOrderAction</method>
                    </kodework_ongoing>
                </observers>
            </checkout_cart_save_after>
        </events>
        <!-- Hook into events end -->
    </frontend>
</config>

As you can see you need an observer class app/code/local/Kodework/Ongoing/Model/Observer.php
<?php
class Kodework_Ongoing_Model_Observer
{
    public function ProcessOrderAction($observer)
    {
        $cart = $observer->getData('cart');
        $quote = $cart->getData('quote');
        $items = $quote->getAllVisibleItems();

       // More logic...
    }
}


text:
Q: como actualizar el valor de una variable dentro de una funcion en javascript basicamente estoy haciendo un formulario donde se puedan hacer retiros, depositos y consultar saldo, sin embargo no se como actualizar los valores dentro de una funcion, me explico al ejecutar la funcion depositar (que es parte de un onclick de un boton) la funcion se ejecuta y me muestra el nuevo saldo, sin embargo para ir a la funcion retirar o consultar saldo, me ejecuta de nuevo el saldo anterior sin ser actualizado por el deposito y si lo pongo fuera d ela funcion me dice que no está definido.
PD: tambien debo poner un contador de cuantas veces se ha depositado y retirado.
PD2: es una tarea de la u basica, asi que nada de frameworks ni nada extra, debe ser con lo basico de javascript, cualquier ayuda les agradezco mucho
function captura(){
let nombre= document.getElementById("nombre").value;
let identidad= document.getElementById("identidad").value;
let telefono= document.getElementById("telefono").value;
let email= document.getElementById("email").value;

console.log(nombre,identidad,email,telefono);

}

let miCuenta = new Cuenta;
function datos(){
    let nroCuenta= document.getElementById("numerodecuenta").value;
    let clave = document.getElementById("clave").value;

    if (nroCuenta==123 && clave == 1018120) {

        console.log(miCuenta.consultarSaldo(depositar(nuevoSaldo)));

  } else {

    console.log('Numero de cuenta o clave incorrecta');

  }
}

function depositar() {
  let nroCuenta= document.getElementById("numerodecuenta").value;
  let clave = document.getElementById("clave").value;

  if (nroCuenta==123 && clave == 1018120) {

    valorDeposito = document.getElementById("valordeposito").value;
    miCuenta.depositar(valorDeposito);
    console.log(miCuenta.consultarSaldo());
    nuevoSaldo= miCuenta.depositar(valorDeposito);
    miCuenta.consultarSaldo= nuevoSaldo;

} else {

  console.log('Numero de cuenta o clave incorrecta');

}

}

function retirar() {
    let valorRetiro = document.getElementById("valorretiro").value;
    miCuenta.depositar(valorRetiro);
    console.log(miCuenta.consultarSaldo());

}

y esta es la clase cuenta
class Cuenta
//propiedades de la clase cuenta
{
    #nroCuenta;
    #idcliente;
    #saldo;
    #telefono;
    #email

    saldo = this.#saldo;
    constructor ()
    {
        this.#nroCuenta = "123";
        this.#idcliente = "1018120";
        this.#saldo = 0,0;
        this.#email= "";
        this.#telefono="3151456879";
    }

    depositar( valorDeposito )
    {
        this.#saldo=this.#saldo + valorDeposito;

        return;
    }
    consultarSaldo()
    {
        return this.#saldo;
    }
    retirar( valorRetiro )
    {
        let respuesta;
        if (this.#saldo >= valorRetiro)
        {
        this.#saldo = this.#saldo - valorRetiro;
        respuesta = true;
        }
        else
        {
         respuesta = false;
        }
        return respuesta;
    }

}


text:
Q: Screen and Text blurry in Ubuntu 14.10 There is some issue with the display sometimes in ubuntu. This occurs if I leave it aside for few minutes and unlock the screen. Please check the screenshot
http://imgur.com/Fw0ibDU


text:
Q: TwitterSourceConnector must be subclass of SourceConnector Kafka Connect launching through docker-compose kafka-cluster with base from: landoop/fast-data-dev:lastest  where latest ends up being Kafka Connect Version 2.6.2-LO, also tried 2.6.2-LO. Both failed to successfully create and run the connector.
When vieweing connector status: http://localhost:8083/connectors/source-twitter-distributed/status
I see the trace below which I cannot understand since the connector comes bundled:
{
    "name": "source-twitter-distributed",
    "connector": {
        "state": "FAILED",
        "worker_id": "127.0.0.1:8083",
        "trace": "org.apache.kafka.connect.errors.ConnectException: Connector implementations must
be a subclass of either SourceConnector or SinkConnector
at org.apache.kafka.connect.runtime.WorkerConnector.initialize(WorkerConnector.java:162)\n\tat org.apache.kafka.connect.runtime.WorkerConnector.doRun(WorkerConnector.java:131)
at org.apache.kafka.connect.runtime.WorkerConnector.run(WorkerConnector.java:117)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)\n"
    },
    "tasks": [],
    "type": "unknown"
}

Any insights?

A: Wont select this as the official answer, but I believe it could be more related to landoop versions vs Connector.
Ended up changing landoop/fast-data-dev:latest to lensesio/fast-data-dev:2.5.1-L1, re-created all and now the connection and data is flowing as expected.


text:
Q: Find bug on below semaphore implementation using monitor In an interview was asked to identify bug in the below code , if there is any.
Below class implements semaphore with certain capacity.
    public class MySemaphore
    {
        private object _mutex = new object();
        private int _currAvail;

        public MySemaphore(int capacity)
        {
            _currAvail = capacity;
        }

        public void Wait()
        {
            lock (_mutex)
            {
                if (_currAvail == 0) Monitor.Wait(_mutex);
                _currAvail--;
            }
        }

        public void Signal()
        {
            lock (_mutex) {
                _currAvail++;
                Monitor.Pulse(_mutex);
            }
        }

    }

A: Problems with this Semaphore that I can see:

*

*capacity is actually just initial capacity, not a total capacity. Therefore one can just call Signal 1000 times and have 1000 additional capacity.

*integer overflow is not handled. If you put int.MaxValue as the initial capacity and then Signal, your current capacity will be at int.MinValue.

*the constructor doesn't check if the passed-in int is negative

A: Full disclosure: I don't use C#. I am not familiar with Monitor.Wait(o) and Monitor.Pulse(o), but I believe that  _currAvail could go negative if two or more threads are allowed to simultaneously call sema.Wait().
Suppose that thread A and thread C concurrently call sema.Wait() while thread B calls sema.Signal(). Here's what I think could happen:
currAvail  mutex   Thread A       Thread B        Thread C
---------  -----   -------------  --------------  --------------
    0      free    lock(mutex)         .               .
    0        A     Await Pulse()  Await mutex          .
    0      free      ''    ''     lock(mutex)          .
    0        B       ''    ''     currAvail++     Await mutex
    1        B       ''    ''     Pulse()          ''    ''

    1        B     Await mutex    release(mutex)   ''    ''
    1      free      ''    ''          .          lock(mutex)
    1        C       ''    ''          .          curAvail--
    0        C       ''    ''          .          release(mutex)
    0      free      ''    ''          .               .

    0      free    lock(mutex)         .               .
    0        A     currAvail--         .               .
   -1        A     release(mutex)      .               .
   -1      free          .             .               .

The fix is to re-check _currAvail after Monitor.Wait(_mutex) returns. I.e., call Monitor.Wait(_mutex) in a loop:
lock (_mutex) {
    while (_currAvail == 0) Monitor.Wait(_mutex);
    _currAvail--;
}


text:
Q: How to disable depth of field? Without a doubt, Unravel is one of the most graphically impressive 2D platformers. Unfortunately the game uses prominent depth of field effect (with film grain) that blurs the background , it is only possible to switch between "high" and "low" in the settings:

high

low (still noticeably blurred; enlarge the screenshot)

A: Reviewing this I can not see any options to reduce it beyond low.
I've freshly installed Unravel to see if it generates any additional config files where you could change something like
depth of field = 0.
However this doesn't appear to be the case and it looks like high and low are your only two options.


text:
Q: change numeric base of negative numbers How to convert a negative decimal number to a hexadecimal one?
I know how to convert positive numbers from one base to another.
The widows calculator returns a huge number something like FFFFFFFFFFFFCFC7 in hex for -12345 in dec.The value that I need to process further more is CFC7, but I don't know how to get it using C#.

A: Not exactly sure if that is what you need:
int i = -12345;
string test = i.ToString("X"); // test will hold: "FFFFCFC7"
int HexI = Convert.ToInt32(test, 16); // HexI will hold: -12345

A: Try this:
int decimalValue = -12345;
string hexVal = String.Format("{0:x2}", decimalValue);


text:
Q: MySQL string option with unlimited character count? I need to store huge amounts of text in a column of my MySQL database, but all of the types I've used so far are not big enough E.G. text, LongBlob, Longtext.
How can I store large amounts of characters in a column in a MySQL database, what type of column must I use?

A: if you can't shoehorn it into longtext, you can't do it.
That being said, I cannot imagine you'd really want to do that.  What sort of table is going to have multiple rows of 2GB chunks of text, and will be able to functionally use that for anything?


text:
Q: Creating shared library from header only using bazel I am trying create an .so file from the Google Differential Privacy framework to import it in another (non-Bazel) project.
The C code is only header files. For the build process they use bazel, so I am trying to stick with that.
I looked at various solutions on StackOverflow. Most of them suggested that this should work:
cc_binary(
name= "lib.so",
linkshared=1,
srcs=["header.h","src.c"],
deps=["//framwork:dependency1"],

)

However, this does not seem to work in my case. I assume this is due to the fact that I only have .h files for sources.
This is what I got:
    cc_binary(
    name= "lib.so",
    linkshared=1,
    srcs=[
       "header1.h",
       "header2.h",
       ...],
    deps=["//framwork:dependency1", ...],

)

When compiling with this an .so file is created but there are no symbols or code inside. Therefore, there seems to be a problem with the cc_binary rule I used.
Using linkstatic in cc_binary did not make any difference.
The gcc command executed by Bazel for the rule above looks something like this:
gcc -shared -o lib.so -Wl,-S -fuse,ld=gold -Wl,-no-as-needed -Wl,-z,relro,-z,now -Wl,--start-lib logging.pic.o -Wl,--end-lib -Wl,--start-lib hash.pic.o -Wl,--end-lib ... -pthread -pthread -pthread -lpthread -lm -lpthread -lm -lstdc++ -lm

Instead of the dots there are a lot more .pic.o files which are inserted with --start-lib and --end-lib. Somehow this command seems wrong but I don't know how to fix it.
Looking at the discussions on the Github page of the Bazel project, it seems that creating .so files seems to be one of the weak points of Bazel.
Does anyone have an idea what might go wrong here? Is using cc_shared_library a solution to this? If yes, how would I use it?
Thanks in advance!

A: It seems like what I was trying to do did not really make sense.
I found this post which talks about header-only libraries in CMake.
Since there are no c files, no object files can be created. Therefore, no .so file can be created.
As described in that other post I will try to create a .c file which simply includes all .h files to create a .so file.


text:
Q: Automapper v5 Ignore unmapped properties Previously when I used Automapper v3.x ignoring unmapped properties could be done by simply adding a .IgnoreUnmappedProperties() extension which looked like this
public static class AutoMapperExtensions
{

public static IMappingExpression<TSource, TDestination> IgnoreUnmappedProperties<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
    var typeMap = Mapper.FindTypeMapFor<TSource, TDestination>();
    if (typeMap != null)
    {
        foreach (var unmappedPropertyName in typeMap.GetUnmappedPropertyNames())
        {
            expression.ForMember(unmappedPropertyName, opt => opt.Ignore());
        }
    }

        return expression;
    }
}

How can this extension be rewritten to work with Version 5.x. I can of course add the following to each property.
.ForMember(dest => dest.LastUpdatedBy, opt => opt.Ignore())

or not call
Mapper.AssertConfigurationIsValid();

A: You can do that using the CreateMap method's memberList parameter to specify the validation that you want.
CreateMap<TSource, TDestination>(MemberList.None)

The MemberList.None should do the trick. You can also switch between the source or destination validations.
Automapper - Selecting members to validate


text:
Q: Qlikview Wildcard in a variable I have this string:
Sum (if(left(SeasonCalc,3) = '171', Fsgantal*ShoesMen))

SeasonCalc is a sales period for the year, i.e. the Season.
Fsgantal is the Number of shoes sold
ShoesMen is to only show the number of shoes sold that are Men's shoes.
The season is named like 17S1... 17S2... 18S1 etc.
What I want to do is to change the Season as the sales period changes and do that by using a Wildcard in the variable. Is this possible?
I know it's possible to use a variable to set the sales period, we do this already, but then I'd have to define *ShoesMen or *ShoesLadies etc. for every string.
Thanks!

A: Your question is not very clear, but following your example, I would guess that something like this could work :
Sum(if(WildMatch(SeasonCalc, '*S1'), Fsgantal*ShoesMen))

WildMatch will return true if it matches one of the a wildcard expression given as a parameter.

A: Wildcards can also be used in Set Analysis, also better performance :
Sum({<SeasonCalc={'*S1'}>}, Fsgantal*ShoesMen))


text:
Q: Keras callback AttributeError: 'ModelCheckpoint' object has no attribute '_implements_train_batch_hooks' I'm using Keras (with TensorFlow back-end) to implement a neural network and want to only save the model that minimises loss on the validation set during training. To do this, I instantiated a ModelCheckpoint and pass it when calling the fit method of the model. However, when I do this I get the following error: "AttributeError: 'ModelCheckpoint' object has no attribute '_implements_train_batch_hooks'". The closest thing I have found online for my problem is this post with a similar error, where the problem came from mixing modules from keras and tf.keras, however this is not my case as all my modules are imported from keras. I've been looking online and through the Keras documentation for a while and can't find anything that could explain this bug. Here are the parts of the code that seem the most relevant to the issue:
Imported modules:
from keras.models import Sequential
from keras.layers import Embedding, Conv1D, Dense, Dropout, GlobalMaxPool1D, Concatenate
from keras.callbacks import ModelCheckpoint

ModelCheckpoint instantiation, model compilation and call to fit method:
checkpoint = ModelCheckpoint('../model_best.h5', monitor='val_loss', verbose=1, save_best_only=True, mode='min')

model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

history = model.fit(x_train, y_train,
                    epochs = 10, batch_size = 64,
                    validation_data = (x_val, y_val),
                    callbacks = [checkpoint])

...and here is the full Traceback:
Traceback (most recent call last):

  File "/Users/thisuser/thisrepo/classifier.py", line 39, in <module>
    callbacks = [checkpoint])

  File "/Users/thisuser/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py", line 66, in _method_wrapper
    return method(self, *args, **kwargs)

  File "/Users/thisuser/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py", line 826, in fit
    steps=data_handler.inferred_steps)

  File "/Users/thisuser/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow/python/keras/callbacks.py", line 231, in __init__
    cb._implements_train_batch_hooks() for cb in self.callbacks)

  File "/Users/thisuser/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow/python/keras/callbacks.py", line 231, in <genexpr>
    cb._implements_train_batch_hooks() for cb in self.callbacks)

AttributeError: 'ModelCheckpoint' object has no attribute '_implements_train_batch_hooks'

The versions I'm using are:

*

*Python: 3.7.7

*Keras: 2.3.0-tf

Does anyone know what might be causing the issue? If needed I can modify my code slightly to give it all here, so that it is reproducible. Thanks in advance for your help!

A: I also encountered this problem recently.
What did I find out: recently the keras or tensorflow version was updated by developers and this cause the problem.
Solution: since the developers of keras require everyone to switch to the version tf.keras, you need to replace of your code import section.
From:
import keras

To:
import tensorflow.keras as keras

After that everything worked for me.

A: replace:
from keras.callbacks import ModelCheckpoint
to:
from tensorflow.keras.callbacks import ModelCheckpoint


text:
Q: How most iOS developers adapt different screen sizes? I wonder how other ios developers adapt application for supporting all different screen sizes. I personally used in every single view UIDevice API and Outlets for constraint.
But as time goes by, I became doubtful. Is it the way it is supposed to be?
What is the most efficient way to adjust my application for supporting all different screen sizes?
if UIDevice.current.userInterfaceIdiom == .pad {
  constraint1.constant = value
  constraint2.constant = value
  constraint3.constant = value
}

A: Your UI already adapts to different screen sizes if you're using auto layout constraints. I think your question is more about how to have different layouts for different screen sizes.
The problem with your approach is that your app may be used as multitasking in split view which means that your if statement is already predicting it wrong. Why? You see your app can be used in one of the layouts shown below.

But your are checking if your device is iPad which doesn't tell you much about what kind of layout your app is in.
Size classes here to rescue

Size classes are traits that are automatically assigned to content areas based on their size. The system defines two size classes, regular (denotes expansive space) and compact (denotes constrained space), which describe the height and width of a view.

More sophisticated solution will be to use size classes which gives you more options on how to arrange your views. So now you should go from this
if UIDevice.current.userInterfaceIdiom == .pad {
  constraint1.constant = value
  constraint2.constant = value
  constraint3.constant = value
}

to this
if traitCollection.horizontalSizeClass == .compact && traitCollection.verticalSizeClass == .regular {
  // Do something
} else {
  // Do something else
}

I hope I'd give you a general idea of how to start using size classes now is up to you to do further research. You can start in apple documentation with UITraitCollection class.
Resource: https://developer.apple.com/design/human-interface-guidelines/ios/visual-design/adaptivity-and-layout/


text:
Q: Background image for div not working Why is my background-image not working?
HTML

CSS
.container-fluid{
    background-image: url('G://etc/vvo/practice/img/bora1.jpg');
}

why drive G:? im practicing my coding during working hours and at home thats why the location is drive g

A: .container-fluid{
    background-image: url('../img/bora1.jpg');
}

If the image contains in your project the ".." is set the path to your image

A: Based from your comment, this might solve your problem. And just use a relative path, it is better and shorter.
.container-fluid{
   background-image: url('img/bora1.jpg');
}

A: Try doing this:
.container-fluid{
       background:url(../img/boral.jpg);
      }

A: I think you can give
.container-fluid{
   background-image: url('bora1.jpg');
}

if your image is in same folder as your html page.

A: just create an images folder into ur project and put ur image into that folder and then give the path to that folder like

it will be easy for u. and if ur have created a special class to that image then simply use it into


text:
Q: Finding the asymptotes of an integral I need to find the asymptote of $$\int\limits_{0}^{\infty} \frac{\ln(1 + \frac{x}{\sqrt{n}})}{x + x^3} dx$$
I've taken $b_{n} = n^{-1/2}$ which reduces the problem to finding,
$$\lim_{n\to\infty}\ \sqrt{n}\int\limits_{0}^{\infty} \frac{\ln(1 + \frac{x}{\sqrt{n}})}{x + x^3} dx$$ but now I'm stuck. Can I bring the limit inside the integral? Am I supposed to show that the limit is equal to 1 so that $\lim_{n\to\infty} \frac{a_n}{b_n} = 1$?

A: I would use squeezing, with the inequalities
$$
\frac{x}{x+1}<\ln(1+x)<x.
$$
Inserting and calculating, you will find that
$$
\frac{\sqrt{n}\pi-\ln n}{2+2n}\leq \int_0^{+\infty}\frac{\ln(1+x/\sqrt{n})}{x+x^3}\,dx\leq \frac{1}{\sqrt{n}}\frac{\pi}{2}.
$$
It follows that
$$
\lim_{n\to+\infty}\sqrt{n}\int_0^{+\infty}\frac{\ln(1+x/\sqrt{n})}{x+x^3}\,dx=\frac{\pi}{2}.
$$


text:
Q: Fail2Ban with DDWRT or router How can I use fail2ban with DDWRT or a router?
I love using fail2ban, but there is no info about using fail2ban in a linux base ddwrt / optware / entware and so on.

A: I tried to add to the WIKI, you might wanna add in:
Fail2Ban is not easy, but can be done cooly!
Right now, I use git but you can download the latest as well.
opkg install git git-http bash ca-bundle ca-certificates python

cd /opt
git clone https://github.com/fail2ban/fail2ban.git
cd fail2ban
mkdir -p /opt/log
mkdir -p /opt/run/fail2ban
mkdir -p /opt/lib/fail2ban/
cp /opt/fail2ban/config/jail.conf /opt/fail2ban/config/jail.local
cp /opt/fail2ban/config/fail2ban.conf /opt/fail2ban/config/fail2ban.local

Required modification for fail2ban.local
logtarget = /opt/log/fail2ban.log
socket = /opt/run/fail2ban/fail2ban.sock
pidfile = /opt/run/fail2ban/fail2ban.pid
dbfile = /opt/lib/fail2ban/fail2ban.sqlite3

Setup
There will be an info that /etc/fail2ban is not writable, but it is not a problems
cd /opt/fail2ban
setup.py install

Init script /opt/etc/init.d/fail2ban
#!/usr/bin/env bash
/opt/bin/python /opt/fail2ban/bin/fail2ban-server -c /opt/fail2ban/config/ $1

Startup command in like DDWRT
/opt/etc/init.d/fail2ban start

Shutdown command in like DDWRT command
/opt/etc/init.d/fail2ban stop
by Patrik aka p3x-robot / p3x / corifeus