text:
Q: Ubuntu only Boots after Booting Windows and Restarting I have been trying to get Ubuntu 16.04 to work on my computer alongside Windows 10. I followed the instructions for how to install it (I used the option to "install alongside Windows").
The Problem
The problem is really bizarre: When I first suspended Ubuntu and then tried to start up the computer again, it completely froze and I had to hard-reset the computer. Once I rebooted Ubuntu, it just loops forever with a blank screen and the "Ubuntu drum sound", occasionally blinking the login screen every once in a while.
My Attempts at Fixing it
There is one weird "fix" to this that I figured out; if I boot Windows 10, restart from there, and then choose to boot Ubuntu after the restart, then everything works smoothly. There seems to be something wrong connected to "booting the computer from after being turned off".
Another "fix" I had to do before discovering the above was to reinstall Ubuntu, in which case it works normally until I try to suspend it again.
My Question
Does anyone know what might be causing this? It is rather annoying to have to boot Windows, restart it and boot Ubuntu everytime I want to use it, let alone have to reinstall it.
In case this is helpful: I tried to install to Ubuntu 18.04 instead, but I receive similar problems -- the system breaks after trying to suspend, locking me at login.
Thanks in advance!

Here are the contents of /etc/default/grub:
# If you change this file, run 'update-grub' afterwards to update
# /boot/grub/grub.cfg.
# For full documentation of the options in this file, see:
#   info -f grub -n 'Simple configuration'

GRUB_DEFAULT=0
#GRUB_HIDDEN_TIMEOUT=0
GRUB_HIDDEN_TIMEOUT_QUIET=true
GRUB_TIMEOUT=10
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"
GRUB_CMDLINE_LINUX=""

# Uncomment to enable BadRAM filtering, modify to suit your needs
# This works with Linux (no patch required) and with any kernel that obtains
# the memory map information from GRUB (GNU Mach, kernel of FreeBSD ...)
#GRUB_BADRAM="0x01234567,0xfefefefe,0x89abcdef,0xefefefef"

# Uncomment to disable graphical terminal (grub-pc only)
#GRUB_TERMINAL=console

# The resolution used on graphical terminal
# note that you can use only modes which your graphic card supports via VBE
# you can see them in real GRUB with the command `vbeinfo'
#GRUB_GFXMODE=640x480

# Uncomment if you don't want GRUB to pass "root=UUID=xxx" parameter to Linux
#GRUB_DISABLE_LINUX_UUID=true

# Uncomment to disable generation of recovery mode menu entries
#GRUB_DISABLE_RECOVERY="true"

# Uncomment to get a beep at grub start
#GRUB_INIT_TUNE="480 440 1"

A: your graphics card might be causing this.
try to enter into ubuntu with "nomodeset"

*

*when you see the grub, highlight to "Ubuntu" and press e to edit the kernal parameters.

*go to the line starting with "linux" and find the string ro quiet splash

*add the text nomodeset in between "ro quiet splash". now it should look like this ro nomodeset quiet splash

*press Ctrl+x or F10 to boot.

*Once you enter into Ubuntu.. try to install the rite drivers for your graphics card.


text:
Q: does MSMQ have "lock until expire" functionality similar to Amazon SQS? I've been using AWS SQS, which has a nice feature that when a message is claimed from the queue it locks for a period of time. During this lock if it is processed successfully the message is marked as completed. If the processing fails (and no response is received from the message processor), after a period of time the lock expires and the message is available for another processor to pick up.
Now I have a requirement to use queues outside of SQS (mostly for latency reasons, but potentially for cost reasons too). I'm really looking for a queue provider that has the same characteristic. MSMQ would be the obvious choice for me, since it's already installed and we use it elsewhere, but I can't find any functionality that handles failed messages in the same way.
Does MSMQ allow for this, or is there an easy way to replicate it?
Alternatively, is there another lightweight, open-source messaging service that does?

A: MSMQ does this already. If you read a message within a transaction and the transaction aborts then the message will reappear in the queue.

redpajama_set_name: RedPajamaStackExchange


text:
Q: В чем причина пустого пространства между блоками На сайте есть пустое пространство, могу устранить его отрицательным маржин для футера, но все же, в чем причина то?!
Причина найдена, може кому поможет в будущем. Часто причинй есть неучтенный margin где то в верстке. В моем случае я проверил все, ничего подобного не было. Причину нашел посредством инструмента "Edit as HTML" в браузере Google Chrome. Я нашел какой то символ, который в обычном коде не отображался. Увидеть его удалось только через данный инструмент http://pastenow.ru/d154f781f9024c23940a49d7ef074da8
В шаблоне он отображался так http://pastenow.ru/0a4f2c0c8df2b01a192085247a09404d в конце.
Для тех, кто будет в будущем искать ответ на подобный вопрос: важно помнить что проблема обязательно связана с чем то, это точно не мистика)


text:
Q: Balancer is down after stopping config servers I had an urgent issue to solve in admin DB
I stopped all config servers, and made changes in the primary one.
After restarting all other servers - balancer working only on the server where I did changes, the other two have:
balancer:
        Currently enabled:  yes
        Currently running:  no
Also rs.status() returns:
configsvr> rs.status()
{
        "info" : "configsvr",
        "ok" : 0,
        "errmsg" : "not running with --replSet",
        "code" : 76
}

Need some help to fix it
Should I restart all config servers with some options, or need to build replication from the beginning?

A: First: balancer is running ONLY at config server replica sets PRIMARY, never on SECONDARY.
Second: (as) your error message says that, that node where you gave rs.statatus() command is not started in replica set mode, more like maintenance mode. i.e. started without --replSet or replication.replSetName config parameter and maybe also without "sharding.clusterRole: configsvr" parameter.
You can check what where starting parameters, by just reading mongod.log file. There is (at startup) list of parameters what that mongod used when it was started.


text:
Q: i would like enhanced that code by loading textures from image and using textures in the scene I'm french and newbie in open and webgl...nobody's perfect:)
I try to enhanced a code from Evan Wallace to make a little game.
But I try to load textures from images to texturing object with no success...
An idea?
Thank you
here's the code:
function loadImage(url, callback) {
  var image = new Image();
  image.src = url;
  image.onload = callback;
  return image;
  }

  function loadImages(urls, callback) {
  var images = [];
  var imagesToLoad = urls.length;

  // Called each time an image finished
  // loading.
  var onImageLoad = function() {
  --imagesToLoad;
  // If all the images are loaded call the callback.
  if (imagesToLoad == 0) {
  callback(images);
  }
  };

  for (var ii = 0; ii < imagesToLoad; ++ii) {
  var image = loadImage(urls[ii], onImageLoad);
  images.push(image);
  }
  }

  if (gl) {
  loadImages([
  "178.jpg",
  "football.png",
  ], PathTracer);
  }

  function PathTracer(images) {

 var vertices = [
-1, -1,
-1, +1,
+1, -1,
+1, +1
];

// create vertex buffer
this.vertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);

// create framebuffer
this.framebuffer = gl.createFramebuffer();

 // create textures
 var type = gl.getExtension('OES_texture_float') ? gl.FLOAT :      gl.UNSIGNED_BYTE;
 this.textures = [];
 for(var i = 0; i < 3; i++) {
  this.textures.push(gl.createTexture());
  gl.bindTexture(gl.TEXTURE_2D, this.textures[i]);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, 512, 512, 0, gl.RGB, type, null);
  if (i == 2){
  //gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE,   images); nothing append
 //gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA,   gl.UNSIGNED_BYTE,new Uint8Array([0, 255, 255, 0])); with that screen blinking
 }
}
 gl.bindTexture(gl.TEXTURE_2D, null);

  // create render shader
  this.renderProgram = compileShader(renderVertexSource,     renderFragmentSource);
 this.renderVertexAttribute = gl.getAttribLocation(this.renderProgram,    'vertex');
 gl.enableVertexAttribArray(this.renderVertexAttribute);

 // objects and shader will be filled in when setObjects() is called
 this.objects = [];
 this.sampleCount = 0;
 this.tracerProgram = null;
 }


text:
Q: why is my list cannot be convert into zip list? python i have 2 list that i got from input in my html
i want to ouput that 2 list together
but when i use zip(lista, listb)
no output shown
         {% for proc, ope in procslist %}

            {{proc.id}}
            {{proc.name}}
            {{proc.setcost}} / {{proc.proccost}}
            {{proc.id}}
            {{proc.id}}
            {{proc.id}}
            {{proc.settime}}

              <input type="hidden" name="opetimelist" value="{{proc.id}}" id="">
              <input type="text" name="opetime-{{proc.id}}" id="" value="{{ope}}"
              style="width: 80%;">

          {% endfor %}

and this is my views.py
        proc = ''
        choosenproc = request.POST.get('choosenproc')
        if choosenproc:
            proc = Proc.objects.get(Q(name__icontains=choosenproc) | Q(id__icontains=choosenproc))

            flag = False
            if proc:
                if selectedproc != []:
                    for product in selectedproc:
                        if product.id == proc.id:
                            flag = True
                            break
                if flag == False:
                    selectedproc.append(proc)

        opetimelist = request.POST.getlist('opetimelist')
        opetimevalue = [request.POST['opetime-{}'.format(o)] for o in opetimelist]

        procslist = zip(selectedproc, opetimevalue)

the result it no ouput
how to fix this?


text:
Q: Browser request hanging when running the latest Docker ColdFusion image I installed the Docker release of ColdFusion with the following command:
docker pull eaps-docker-coldfusion.bintray.io/cf/coldfusion:latest

I then created a compose file:
version: "3.7"
services:
  coldfusion:
    image: eaps-docker-coldfusion.bintray.io/cf/coldfusion:latest
    ports:
      - "8500:8500"
    networks:
      coldfusion:
    hostname: coldfusion
    volumes:
      - "~/dev/docker/projects/coldfusion/volumes/app:/app"
      - "~/dev/docker/projects/coldfusion/volumes/logs:/opt/coldfusion/cfusion/logs"
    environment:
      acceptEULA: "YES"
      password: "ColdFusion123"
      enableSecureProfile: "false"
      HOST_USER_ID: ${CURRENT_UID}
      HOST_GROUP_ID: ${CURRENT_GID}
    deploy:
      replicas: 1
      restart_policy:
        condition: any
        delay: 5s
        max_attempts: 3
        window: 10s
    healthcheck:
      test: curl --fail http://localhost:8500 || exit 1
      interval: 1m
      timeout: 3s
      retries: 3
networks:
  coldfusion:
    name: coldfusion
  common:
    external: true
    name: common

and started it with the command:
docker stack deploy --compose-file docker-compose-dev.yml coldfusion

The log shows:
stephane@stephane-pc:~/dev/docker/projects/coldfusion$ docker service logs -f coldfusion_coldfusion
coldfusion_coldfusion.1.rlhixv3jctvm@stephane-pc    | Updating webroot to /app
coldfusion_coldfusion.1.rlhixv3jctvm@stephane-pc    | Configuring virtual directories
coldfusion_coldfusion.1.rlhixv3jctvm@stephane-pc    | Updating password
coldfusion_coldfusion.1.rlhixv3jctvm@stephane-pc    | Skipping language updation
coldfusion_coldfusion.1.rlhixv3jctvm@stephane-pc    | Serial Key: Not Provided
coldfusion_coldfusion.1.rlhixv3jctvm@stephane-pc    | Previous Serial Key: Not Provided
coldfusion_coldfusion.1.rlhixv3jctvm@stephane-pc    | Starting ColdFusion
coldfusion_coldfusion.1.rlhixv3jctvm@stephane-pc    | Starting ColdFusion 2018 server ...
coldfusion_coldfusion.1.rlhixv3jctvm@stephane-pc    | The ColdFusion 2018 server is starting up and will be available shortly.
coldfusion_coldfusion.1.rlhixv3jctvm@stephane-pc    | ======================================================================
coldfusion_coldfusion.1.rlhixv3jctvm@stephane-pc    | ColdFusion 2018 server has been started.
coldfusion_coldfusion.1.rlhixv3jctvm@stephane-pc    | ColdFusion 2018 will write logs to /opt/coldfusion/cfusion/bin/../logs/coldfusion-out.log
coldfusion_coldfusion.1.rlhixv3jctvm@stephane-pc    | ======================================================================
coldfusion_coldfusion.1.rlhixv3jctvm@stephane-pc    | [000] Checking server startup status...
coldfusion_coldfusion.1.rlhixv3jctvm@stephane-pc    |   % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
coldfusion_coldfusion.1.rlhixv3jctvm@stephane-pc    |                                  Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:--  0:00:01 --:--:--     0
coldfusion_coldfusion.1.rlhixv3jctvm@stephane-pc    | External Addons: Disabled
coldfusion_coldfusion.1.rlhixv3jctvm@stephane-pc    | External Session Storage: Disabled
coldfusion_coldfusion.1.rlhixv3jctvm@stephane-pc    | Skipping setup script invocation
coldfusion_coldfusion.1.rlhixv3jctvm@stephane-pc    | Secure Profile: Disabled
coldfusion_coldfusion.1.rlhixv3jctvm@stephane-pc    | Cleaning up setup directories

But it hangs when typing the http://localhost:8500/ request in the browser.
The log remains empty:
tail -f volumes/logs/coldfusion-out.log

I created an index.cfm page in the /app directory:
hi
<cfset firstName = "World">

Hello <cfoutput>#firstName#</cfoutput>!

This CFML tutorial was designed for
<cfif firstName eq "World">
  you!
<cfelse>
  the world to see.
</cfif>

UPDATE: A 200 response comes back fine when using 127.0.0.1 instead of localhost
Opening the firewall ports does not change anything to the issue:
stephane@stephane-pc:~$ sudo ufw allow from 127.0.0.0 to any port 8500;
Rules updated
stephane@stephane-pc:~$ sudo ufw allow from any to any port 8500;
Rules updated
Rules updated (v6)

My host /etc/hosts file contains the line:
127.0.0.1       localhost

The nmap command responds:
stephane@stephane-pc:~/dev/docker/projects/coldfusion$ nmap -p 8500 localhost
Starting Nmap 7.80 ( https://nmap.org ) at 2020-09-08 12:09 CEST
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00038s latency).

PORT     STATE SERVICE
8500/tcp open  fmtp

Nmap done: 1 IP address (1 host up) scanned in 0.22 seconds

A: Your docker compose file shows
hostname: coldfusion

so shouldn't it be available at http://coldfusion:8500?
If it's docker compose v3, it should be
services:
  dns:
    hostname: 'your-domain'


text:
Q: What are Telegram Client Messaging limits? From here I know that Telegram limits BOT messages like this:
> 1msg/second per chat
> 30msg/second different chats
Happens that I'am not using the python-telegram-bot API, I'am using a normal client through telethon's library. I'am getting Flood\Spam error from Telegram when trying to send messages in that cadence. BTW, I'am using delayQueue Class to control the messages limits like this:
dqueue = DelayQueue(burst_limit=29, time_limit_ms=1014)
dqueue(client.send_message,inputPeerUser,msg)

Already asked directly to telegram's support, but got no answer. Does someone know what are the limits to normal clients?

A:
There is a limit of 30 msg/sec.

Also,a bot can use the API requests for a limited no. of times
I get this error when I usually test the bot.During testing,there would be a lot of scenarios to test.So,I would be sending a huge amount of requests.
I get an error like this, {error_code:429,description:Too many requests try after (some_time)}
Idk the exact limit.
To avoid this:
You should not flood the telegram server with requests


text:
Q: I update my Angular 5 to 8 and I got an error on toastr I updated my angular 5 to 8
When I start (ng server), I have this error on console
Uncaught TypeError: core_1.style is not a function
at Object../node_modules/ng2-toastr/src/toast-container.component.js (toast-container.component.js:118)
at __webpack_require__ (bootstrap:84)
at Object../node_modules/ng2-toastr/src/toast-manager.js (toast-manager.js:4)
at __webpack_require__ (bootstrap:84)
at Object../node_modules/ng2-toastr/ng2-toastr.js (ng2-toastr.js:5)
at __webpack_require__ (bootstrap:84)
at Module../src/app/app.module.ts (app.error-handle.ts:6)
at __webpack_require__ (bootstrap:84)
at Module../src/main.ts (main.ts:1)
at __webpack_require__ (bootstrap:84)
at Object.0 (main.ts:12)
at __webpack_require__ (bootstrap:84)
at checkDeferredModules (bootstrap:45)
at Array.webpackJsonpCallback [as push] (bootstrap:32)
at main.js:1

I already did this commands:
npm i ng2
npm i ng2-toastr

Angular Version

A: It probaly is using @ViewChild or @ContentChild, these have breaking changes in Angular 8. Since the package has not been updated for 2 years, you should probaly look for another library.


text:
Q: How to trigger event on specific date automatically to reset count in java? I am trying to update count of button clicks on every button click. I am using spring boot and angular as frontend.I managed to do that programatically count button clicks and save in database. But I need to reset those count to zero on day 1 of every month.
How can I do that?
/** On what day of each month should the count be reset? 1..28 */
static final int DAY_OF_MONTH_TO_RESET_COUNT = 1;
/** In what time zone should above day-of-month be interpreted? */
static final ZoneId timeZone = ZoneId.of("Asia/Pontianak");

public static void resetIfDue() {
    // substitute reset_date from DB here
    LocalDate lastResetDate = LocalDate.of(2020, Month.SEPTEMBER, 24);

    LocalDate nextResetDate = lastResetDate.plusMonths(1)
                                .withDayOfMonth(DAY_OF_MONTH_TO_RESET_COUNT);
    LocalDate today = LocalDate.now(timeZone);
    // "not after today" means today or before today
    if (! nextResetDate.isAfter(today)) {
        System.out.println("Reset the count and update the reset_date in the database");
        updateClickCounts();

    }
}

here I got this function on which date I have to reset the count. It will call updateClickCounts() function which contains update query. But I want to trigger event to call resetIfDue() on day 1 of every month automatically. How can I do that? I am new to event triggers thats why I do not understand How it works.

A: You can use cron for it, here simple example.

A: You can make use of the spring cron as below:
/** On what day of each month should the count be reset? 1..28 */
static final int DAY_OF_MONTH_TO_RESET_COUNT = 1;
/** In what time zone should above day-of-month be interpreted? */
static final ZoneId timeZone = ZoneId.of("Asia/Pontianak");

@Scheduled(cron="0 0 0 1 1/1 *")
public static void resetIfDue() {
    // substitute reset_date from DB here
    LocalDate lastResetDate = LocalDate.of(2020, Month.SEPTEMBER, 24);

    LocalDate nextResetDate = lastResetDate.plusMonths(1)
                                .withDayOfMonth(DAY_OF_MONTH_TO_RESET_COUNT);
    LocalDate today = LocalDate.now(timeZone);
    // "not after today" means today or before today
    if (! nextResetDate.isAfter(today)) {
        System.out.println("Reset the count and update the reset_date in the database");
        updateClickCounts();

    }
}

Add @EnableScheduling annotation in the spring boot main class.


text:
Q: UITextview selected text I've an UITabBarController. In my UIViewController a UItextView where I can select the text but when I change the View, text is kept selected. I've tried to add that code but doesn't work:
var range:NSRange = textView.selectedRange
range.length = 0
range.location = NSNotFound

A: Did you try setting textView.selectedTextRange = nil?
Edit: Depending on your requirements, could you set this in viewWillDisappear or viewWillAppear so it is deselected when you either leave or come back to your view controller?
Similar to: How do I deselect text in UITextView?


text:
Q: Using templates for 2D/3D point Is it worth to write classes representing 1D, 2D, 3D points using templates
template <class T>
class Point2D
{

protected:

    T X, Y;

public:

    Point2D(const T x, const T y) : hot smileyx), Y(y)) {}
    ...
};

template <class T>
class Point3D : public Point2D<T>
{
    protected:
    T Z;

public:

    Point3D(const T x, const T y, const T z) : Point2D<T>(x,y), Z(z) {}
...
};

...or using this approach:
class Point2D
{

protected:

    double X, Y;

public:

    Point2D(const double x, const double y) : X(x), Y(y)) {}
    ...
};

class Point3D : public Point2D
{
    protected:
    double Z;

public:

   Point3D(const double x, const double y, const double z) : Point2D(x,y), Z(z) {}
...
};

We understand the coordinates as continuous variables, so it makes sense to express them using double values. A similar situation arises when working with matrices. However in this case templates are widely used...
This class is not only for single use, but it will be part of the library... And my second part of the question. How some "measure" functions should be implemented?
template <class T>
T getDist(const Point2D <T> * p1, const Point2D<T> *p2)
{
....
}

or
double  getDist(const Point2D <T> * p1, const Point2D<T> *p2)
{
....
}

Is it reasonable to write such function in general or for some specific type?

A: Why repeat yourself? Most of the content of those classes and functions will be the same.
Something like this works much better:
template <std::size_T N, typename T>
class Point
{
public:
    Point()
    {
        std::fill_n(mData, N, T());
    }

    explicit Point(const T& pX) :
    mData[0](pX)
    {
        // or some variant (enable_if also works)
        static_assert(N == 1, "X constructor only usable in 1D");
    }

    explicit Point(const T& pX, const T& pY) :
    mData[0](pX),
    mData[1](pY),
    {
        static_assert(N == 2, "XY constructor only usable in 2D");
    }

    // incomplete, left as exercise for reader. :P

private:
    T mData[N];
};

And you just use loops for the functions:
template <std::size_T N, typename T>
T getDist(const Point<N, T>& pFirst, const Point<N, T>& pSecond)
{
    // generic, compiler will unroll loops
}

A: Based on my experience, I'd avoid like the plague creating a class hierarchy where a 3D point IS-A 2D point.  It makes it far too easy for 3D points to unintentionally and silently be treated as 2D points.  Better to keep coordinates of different dimensionality distinct types (as per GMan's answer) and require explicit coercion between types.
My current favourite implementation of this sort of thing is provided by Eigen.  Even if it's license (LGPL) limits it's use to you, I'd suggest taking a look at it's elegantly templated vector and matrix types and learning from them.

A: It looks OK to me, provided that all functions are implemented correctly and efficiently. For distance measurement:
template <class T>
T getDist(const Point3D <T>& p1, const Point3D<T>& p2);

signature should be used. Distances can be in 3D also.

A: I've run into this situation, and had cause to allow different types for the X and Y values, where X was sometimes integral but Y always had higher precision (float or double depending on usage).  Might be worth considering that upfront.

A: Some consideration should also be made on how the class will be used. You mentioned matrices. If you plan on solving systems using that class or anything else incolving matrix inversions (or other similar matrix operations) representing a matrix as a bunch of integers would be outlandish.
If you plan to use it as simply a table of sorts (or are only going to be adding/subtracting and multiplying the matrices) then you could template the class because a matrix full of integers would not provide weird (and incorrect) results for those operations.


text:
Q: Play Framework with LaTex
Possible Duplicate:
Latex directives in template are causing `error in unicode escape`

Im trying to add Latex to a view in a play application.
Can you point me some directions?
Thanks


text:
Q: Windows 10 keeps BSODing (UNEXPECTED _STORE_EXCEPTION)even after resetting the pc I tired nearly every possible ways for this solution like booting windows 10 again through USB,resetting, removing dual boot etc.
Note: My PC shows "Harddisk Problem Detected" also so I doubt this might be the culprit. If yes, how do I fix this(Without changing the harddisk)?.

A: Test if it's the hard disk by installing an OS (e.g. Ubuntu) on a USB flash drive and running (not just booting) from it.

*

*If the PC runs from the flash drive without BSOD, you know it's not a hardware issue.

*Mount the HDD in the PC. Check its SMART status. Since SMART status is just an indicator, you can perform more thorough testing with Smartmontools.
Note that if there is an issue with the HDD, the faster you can install another and salvage data, the better. Disk drives often go from "a bit flaky" to completely unmountable in a short time.


text:
Q: Image rotation issue in blackberry cascades I have an app where users can take and save their profile pic. I'm using https://github.com/RileyGB/BlackBerry10-Samples/tree/master/WebImageViewSample sample from github to load image from url to my view and it works fine. The  problem is when I save the profile pic from ios and view the profile pic in blackberry it appears 90 degree rotated left. But the same url loads fine in ios and android. Below is the link of a sample image taken from iOS that loads correctly ios and android but shifts left to 90 degrees in blackberry. It works fine for other images that is taken from blackberry or android. Is there anyway to fix this? Any help is appreciated
http://oi57.tinypic.com/2hzj2c4.jpg
Below is a sample code of loading this image in qml
Page {
    Container {
        layout: DockLayout {
        }
        WebImageView {
            id: webViewImage
            url: "http://oi57.tinypic.com/2hzj2c4.jpg"
            horizontalAlignment: HorizontalAlignment.Center
            verticalAlignment: VerticalAlignment.Center
            visible: (webViewImage.loading == 1.0)
        }
        ProgressIndicator {
            value: webViewImage.loading
            verticalAlignment: VerticalAlignment.Center
            horizontalAlignment: HorizontalAlignment.Center
            visible: (webViewImage.loading < 1.0)
        }
    }

    actions: [
        ActionItem {
            title: "Clear Cache"
            ActionBar.placement: ActionBarPlacement.OnBar
            onTriggered: {
                webViewImage.clearCache();
                webViewImage.url = "http://oi57.tinypic.com/2hzj2c4.jpg";
            }
        }
    ]
}

A: I was able to fix this issue by adding EXIF library and adding an additional function in the webimageview class
QByteArray WebImageView::getRotateImage(QByteArray imageFile)
{
    //Load the image using QImage.
    // A transform will be used to rotate the image according to device and exif orientation.
       QTransform transform;
    QImage image;
    image.loadFromData((unsigned char*)imageFile.data(),imageFile.length(),"JPG");

    ExifData *exifData = 0;
    ExifEntry *exifEntry = 0;
    int exifOrientation = 1;

    // Since the image will loose its exif data when its opened in a QImage
    // it has to be manually rotated according to the exif orientation.
    exifData = exif_data_new_from_data((unsigned char*)imageFile.data(),(unsigned int)imageFile.size());

    // Locate the orientation exif information.
    if (exifData != NULL) {

        for (int i = 0; i < EXIF_IFD_COUNT; i++) {
            exifEntry = exif_content_get_entry(exifData->ifd[i], EXIF_TAG_ORIENTATION);
            // If the entry corresponds to the orientation it will be a non zero pointer.
            if (exifEntry) {
                exifOrientation = exif_get_short(exifEntry->data, exif_data_get_byte_order(exifData));
                break;
            }
        }
    }
    // It's a bit tricky to get the correct orientation of the image. A combination of
    // the way the the device is oriented and what the actual exif data says has to be used
    // in order to rotate it in the correct way.
    switch(exifOrientation) {
        case 1:
            // 0 degree rotation
            return imageFile;
            break;
        case 3:
            // 180 degree rotation
            transform.rotate(180);
            break;
        case 6:
            // 90 degree rotation
            transform.rotate(90);
            break;
        case 8:
            // 270 degree rotation
            transform.rotate(270);
            break;
        default:
            // Other orientations are mirrored orientations, do nothing.
            break;
    }

    // Perform the rotation of the image before its saved.
    image = image.transformed(transform);

    QImage img =image;
    QByteArray arr;
    QBuffer buf(&arr);
    buf.open(QIODevice::WriteOnly);
    img.save(&buf, "PNG");
    buf.close();
    return arr;

}


text:
Q: transfer db from one heroku app to another faster Is there a faster way to transfer my production database to a test app?
Currently I'm doing a heroku db:pull to my local machine then heroku db:push --app testapp but this is becoming time consuming.  I have some seed data but it is not nearly as accurate as simply testing with my real-world data.  And since they're both stored on a neighboring AWS cloud, there must be a faster way to move the data?
I thought about using a heroku bundle, but I noticed the animate command is gone?
bundles:animate <bundle>     # animate a bundle into a new app

A: It's quite common to migrate databases between staging, testing and production environments for Rails Apps. And heroku db:pull/push is painfully slow. The best way I have found so far is using Heroku PG Backups add-on and it's free. I followed following steps to migrate
production database to staging server:
1) Create the backup for the production-app db
heroku pg:backups capture --app production-app

This will generate b001 backup file from the main database (usually production db in database.yml)
2) To view all the backups (OPTIONAL)
heroku pg:backups --app production-app

3) Now use the pg:backups restore command to populate staging server database from the last backup file on production server
heroku pg:backups restore $(heroku pg:backups public-url --app production-app) DATABASE_URL --app staging-app

Remember that restore is a destructive operation, it will delete existing data before replacing it with the contents of the backup file.

A: So things are even easier now .. checkout the transfer command as part of pgbackups
heroku pgbackups:transfer HEROKU_POSTGRESQL_PINK sushi-staging::HEROKU_POSTGRESQL_OLIVE -a sushi

https://devcenter.heroku.com/articles/upgrading-heroku-postgres-databases#4b-alternative-transfer-data-between-applications
This has worked beautifully for me taking production code back to my staging site.

A: Update for mid-2015...
The pgbackups add-on has been deprecated. No more pgbackups:transfer. pg:copy is ideal for this scenario.
To copy a database from yourapp (example db name: HEROKU_POSTGRESQL_PINK_URL to yourapp_staging (example db name: HEROKU_POSTGRESQL_WHITE_URL)
# turn off the web dynos in staging
heroku maintenance:on -a yourapp-staging

# if you have non-web-dynos, do them too
heroku ps:scale worker=0 -a yourapp-staging

# backup the staging database if you are paranoid like me (optional)
heroku pg:backups capture -a yourapp-staging

# execute the copy to splat over the top of the staging database
heroku pg:copy yourapp::HEROKU_POSTGRESQL_PINK_URL HEROKU_POSTGRESQL_WHITE_URL -a yourapp-staging

Then when it's complete, turn staging back on:
# this is if you have workers, change '1' to whatever
heroku ps:scale worker=1 -a yourapp-staging

heroku maintenance:off -a yourapp-staging

Reminder: you can use heroku pg:info -a yourapp-staging (and yourapp) to get the database constants.
(source: https://devcenter.heroku.com/articles/upgrading-heroku-postgres-databases#upgrade-with-pg-copy-default)

A: The correct answer has changed again as of March 11, 2015.
heroku pg:backups restore $(heroku pg:backups public-url --app myapp-production) DATABASE_URL --app myapp-staging

Note specifically that the argument is now public-url.
https://blog.heroku.com/archives/2015/3/11/pgbackups-levels-up

A: psql -h test_host -c 'drop database test_db_name; create database test_db_name;'

pg_dump -h production_host production_db_name | psql -h test_host test_db_name`

This can be done on production_host or on test_host — will work both ways.

A: Have not tested this, but it might work.
Do this to get the URL of your source database:
heroku console "ENV['DATABASE_URL']" --app mysourceapp

Then try executing db:push with that.
heroku db:push database_url_from_before --app mytargetapp

This might not work if Heroku doesn't allow access to the DB machines from outside their network, which is probably the case. You could, perhaps, try using taps (gem that heroku db commands use internally) from within your app code somewhere (maybe a rake task). This would be even faster than the above approach because everything stays completely within AWS.
Edit:
Here's an (admittedly hacky) way to do what I described above:
Grab the database URL as in the first code snippet above. Then from a rake task (you could do it on console but you risk running into the 30 second timeout limit on console commands), execute a shell command to taps (couldn't easily determine whether it's possible to use taps directly from Ruby; all docs show use of the CLI):
`taps pull database_url_from_source_app #{ENV['DATABASE_URL']}`

The backticks are important; this is how Ruby denotes a shell command, which taps is. Hopefully the taps command is accessible from the app. This avoids the problem of accessing the database machine from outside Heroku, since you're running this command from within your app.

A: Heroku enables you to fork existing applications in production. Use heroku fork to copy an existing application, including add-ons, config vars, and Heroku Postgres data.
Follow the instructions on Heroku: https://devcenter.heroku.com/articles/fork-app

A: Update for mid-2016...
Heroku now have a --fast flag when creating forks, however they will be up to 30 hours out-of-date.
$ heroku addons:create heroku-postgresql:standard-4 --fork HEROKU_POSTGRESQL_CHARCOAL --fast --app sushi
https://devcenter.heroku.com/articles/heroku-postgres-fork#fork-fast-option


text:
Q: Trouble with CultureInfo for Norway I am currently dealing with globalization in my app.  Part of it is working with CultureInfo and RegionInfo.  There is one issue that really puzzles me.  Maybe someone can shade some light on this:
var ci1 = new CultureInfo("de");      // Correct, gives a neutral CultureInfo
var ci2 = new CultureInfo("de-CH");   // Correct, gives a specific CultureInfo
var ci3 = new CultureInfo("fr-CH");   // Correct, gives a specific CultureInfo
var ci4 = new CultureInfo("no");      // Correct, gives a neutral CultureInfo
var ci5 = new CultureInfo("nb-NO");   // Correct, gives a specific  CultureInfo
var ci6 = new CultureInfo("nn-NO");   // Correct, gives a specific  CultureInfo
var ci7 = new CultureInfo("ch");      // Failure!  Can't create a neutral Swiss culture.

The point here is, that Norway and Swizerland are both multilingual countries, but in contrast to Norway I am not able to create a neutral Swiss CultureInfo.
Is that because of historical reasons or is this simply a bug in Microsofts implementation?
EDIT:
It seems that this is some kind of 'political' issue, not a technical.  So I would like to rephrase my question:  Any good ideas how to deal with this issue technically?  Simply ignore "CultureInfo("no")"?  Interestingly enough "CultureInfo("no")" delivers a parent "CultureInfo.TwoLetterISOLanguageName" of 'nb'.
So, for me it is quite confusing.  Any good ideas?

A: A neutral culture is a culture that is associated with a language but not with a country/region.  See:  http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo(v=vs.71).aspx
You are trying to create a language culture with ch, but there is no swiss language.  You use de-CH for german (language) - switzerland (country).  Similarly, you use it-CH or fr-CH for italian and french (languages) in switzerland.
And, as MPelletier points out, there is no canadian language, but in the canadian region, they speak fr(ench) or en(glish).

A: "no" has different behavior from "ch", because "no" is a language, norwegian, while "ch" does not refer to any language.
While it's correct that Norway is a multilingual country the official languages in Norway are; Norwegian, Sami and Kven.  With Sami and Kven recognised as minority languages.  Neither "nb" or "nn" refers to languages that have offical recognizion in Norway, because neither bokmål or nynorsk are languages.
The confusion stems from two facts.  Norwegian, unlike most languages, has two offical written norms, Bokmål and Nynorsk.  In ISO 639 Norwegian is considered a macro language for the two norms and ISO 639 assigns a separate language code to the two written norms, ie. "nb" and "nn".  And the language code for Norwegian "no" coincides with the country code for Norway "NO".

A: According to ISO language standard there is
nno nn Norwegian Nynorsk;
nob nb Bokmål, Norwegian;
nor no Norwegian
From Wikipedia "https://en.wikipedia.org/wiki/Norwegian_language"
Nynorsk and Bokmål provide standards for how to write Norwegian, but not for how to speak the language. There is no officially sanctioned standard of spoken Norwegian, and most Norwegians speak their own dialects in all circumstances. Thus, unlike in many other countries, the use of any Norwegian dialect, whether it coincides with the written norms or not, is accepted as correct spoken Norwegian.
no is spoken Norwegian
nn and nb are written forms
on a website if you see no-no you can assume it is nb-no.


text:
Q: How to implement a semaphore So I've created a program, trying to display the dangers of using shared variables, so I have 3 classes the main called DangersOfSharedVariables and an Incrementer and Decrementer class.
So the idea is to have two threads running at once, both calling their respected methods, so the Decrementer class will call the decrementShared() method in the main and the Incrementer class will call the incrementShared() method in the main.
Here's the main method:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package dangersofsharedvariables;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 */
public class DangersOfSharedVariables {

    /**
     * @param args the command line arguments
     */
    private static int sharedValue =0;
    private static int numberOfCycles = 2000000000;

    public static void main(String[] args) {
        // TODO code application logic here
        Incrementer in = new Incrementer(numberOfCycles);
        Decrementer de = new Decrementer(numberOfCycles);
        Semaphore sem = new Semaphore(1);

        in.start();
        try {
            in.join();
        } catch (InterruptedException ex) {}
        de.start();
        try {
            de.join();
        } catch (InterruptedException ex) {}
        System.out.println(sharedValue);
    }

    public void decrementShared(){
        sharedValue -=10;
    }

    public void incrementShared(){
        sharedValue +=10;
    }

}

Here's the Incrementer class
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package dangersofsharedvariables;

/**
 *
 *
 */
public class Incrementer extends Thread {

    private int numberOfIncrements;

    public Incrementer(int numberOfIncrements) {
        this.numberOfIncrements = numberOfIncrements;

    }

    @Override
    public void run() {
        DangersOfSharedVariables in = new   DangersOfSharedVariables();
        for(int i = 0; i < numberOfIncrements; i++){
            in.incrementShared();
        }
    }
}

Decrementer Class:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package dangersofsharedvariables;

/**
 *
 *
 */
public class Decrementer extends Thread {
    private int numberOfDecrements;
    public Decrementer(int numberOfDecrements){
        this.numberOfDecrements = numberOfDecrements;

    }

    @Override
    public void run(){
        DangersOfSharedVariables d = new DangersOfSharedVariables();
        for(int i = 0; i < numberOfDecrements; i++){
            d.decrementShared();
        }
    }
}

I was googling and a more secure way to do this would be with the use of a Sempaphore class. So I took it upon myself to play around with a semaphore template I found, but am unsure as to how i'd implement it.
Semaphore Class:
package dangersofsharedvariables;

public class Semaphore {

    // *************************************************************
    // Class properties.
    // Allow for both counting or mutex semaphores.
    private int count;

    // *************************************************************
    // Constructor
    public Semaphore(int n) {
        count = n;
    }

    // *************************************************************
    // Public class methods.
    // Only the standard up and down operators are allowed.
    public synchronized void down() {

        while (count == 0) {

            try {
                wait(); // Blocking call.
            } catch (InterruptedException exception) {
                exception.printStackTrace();
            }
        }
        count--;
    }

    public synchronized void up() {
        count++;
        notify();
    }

}

A: Based on your query, following is a brief description about semephore data structures. Semaphores are useful in solving a variety of synchronised problems. The concept has been introduced by Dijkstra(1968) where he introduced the idea of semaphores as part of the operating system in order to synchronise processes with each other and with hardware.
The structure of a typical semaphore involves 4 stages:

*

*Non-critical region

*Entry protocol

*Critical region

*Exit protocol

The non-critical region is any code which can be carried out concurrently by 2-n threads.
The entry protocol is the code which must be executed by a process prior to entering a critical region. It is designed to prevent the process from entering the critical region if another process is already using shared resources.
The critical region is the section of code in which a shared resource is being accessed.
The exit protocol is the code that the process must execute immediately on completion of its critical region.
Semaphores can be put to different uses:

*

*for mutual exclusive access to a single shared resource, in which case the semaphore is called a binary semaphore

*to protect access to multiple instances of a resource (a counting semaphore)

*to synchronise two processes (a blocking semaphore)

The versatility of the semaphore mechanism is achieved through correct initialisation.
For demonstration purposes please consult example below which showcases the most simple binary semaphore implementation:
Semaphore:
package BinarySemaphore;

public class Semaphore{
    private static Semaphore semaphore;
    private static int resource = 1;

    private Semaphore(){}

    public synchronized void increment(){
        while(isAvailable()){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        resource += 1;

        report();

        this.notifyAll();
    }

    public synchronized void decrement(){
        while(!isAvailable()){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        resource -= 1;

        report();

        this.notifyAll();
    }

    public synchronized final static boolean isAvailable(){
        return resource == 1 ? true : false;
    }

    public synchronized final static void report(){
        System.out.println("Resource value: " + resource);
    }

    public final static Semaphore getInstance(){
        if(semaphore == null){
            semaphore = new Semaphore();
        }
        return semaphore;
    }
}

Incrementer:
package semaphore;

import BinarySemaphore.Semaphore;

public class Incrementer implements Runnable{
    private static Semaphore semaphore = null;

public Incrementer(Semaphore s){
    semaphore = s;
}

@Override
public void run() {
    for(int i = 0; i < 10; i++){
        System.out.println("Incrementing...");
        semaphore.increment();
    }
}

}
Decrementer:
package semaphore;

import BinarySemaphore.Semaphore;

public class Decrementer implements Runnable{
    private static Semaphore semaphore = null;

    public Decrementer(Semaphore s) {
        semaphore = s;
    }

    @Override
    public void run() {
        for(int i = 0; i < 10; i++){
            System.out.println("Decrementing...");
            semaphore.decrement();
        }
    }
}

Main:
package semaphore;

import BinarySemaphore.Semaphore;

public class Main {
    public static void main(String[] args){
        Thread iIncrement = new Thread(new Incrementer(Semaphore.getInstance()));
        Thread iDecrement = new Thread(new Decrementer(Semaphore.getInstance()));

        iIncrement.start();
        iDecrement.start();
    }
}

Output:
Decrementing...
Incrementing...
Resource value: 0
Decrementing...
Resource value: 1
Incrementing...
Resource value: 0
Decrementing...
Resource value: 1
Incrementing...
Resource value: 0
Decrementing...
Resource value: 1
Incrementing...
Resource value: 0
Decrementing...
Resource value: 1
Incrementing...
Resource value: 0
Decrementing...
Resource value: 1
Incrementing...
Resource value: 0
Decrementing...
Resource value: 1
Incrementing...
Resource value: 0
Decrementing...
Resource value: 1
Incrementing...
Resource value: 0
Decrementing...
Resource value: 1
Incrementing...
Resource value: 0
Decrementing...
Resource value: 1
Incrementing...
Resource value: 0
Resource value: 1

A: The name for what you want is "mutex" which is short for "Mutual Exclusion".  A mutex is a block of code that can only be executed by one thread at a time.
The Java language statement synchronized (foo) { ... } implements mutual exclusion.  foo is an expression that yields up some object (sometimes called the lock object), and ... are the statements to be protected.  The Java language guarantees that no two threads will be allowed to synchronize the same lock object at the same time.

Semaphore can be used to provide mutual exclusion, but it is more cumbersome, and it's antiquated.
Semaphore was invented before computers had hardware primitives for thread synchronization.  It was supposed to be the "primitive" operation upon which other synchronization constructs (e.g., mutexes) could be built.
Today, the Java implementation of Semaphore actually is built on top of the same hardware primitives as the synchronized statement.


text:
Q: C# How can I send a break to another sub routine? I have a loop running that will process 1000's of records, currently once the loop is running it can't be stopped and the user must wait until it is finished. How can I stop the loop when someone clicks a 'Cancel' button? How do I break into that other routine?
Thanks

A: You can run it in its own thread and abort the thread. Just beware that that might leave the operation in a bad state.
Instead, you should create an exit flag that the thread checks at safepoints. If it's marked for exiting, the thread will stop as soon as it's safe for it to do so.

A: You can just use the BackgroundWorker component.
It's event-based and is very easy to utilize. Looks very appropriate for what you are describing.
It has nice support for cancellation signaling as well as progress reporting too.
And a lot of code examples you can lookup on google.

Set the WorkerSupportsCancellation property so it is true.
backgroundworker1.WorkerSupportsCancellation = true;

Do it before you start the worker.
Then, in the loop, you can poll the CancellationPending property:
if (backgroundWorker1.CancellationPending) return;

Just an example, but you should get the idea.

A: thanks for the replies. It is a backgroundworker but when I use backgroundworker1.cancelAsync(); I get the exception:

"This BackgroundWorker states that it doesn't support cancellation.
  Modify WorkerSupportsCancellation to state that it does support
  cancellation"

How do I go about altering this? This is inherited code, sorry!

A: As Mark said you need to implement some kind of co-operative synchronization.  People often gravitate to wanting to use Thread.Abort here ... but that is a bad idea.
There are a number of questions that address this, for example see: "Is there a good method in C# for throwing an exception on a given thread."

A: You can add a cancel button which sets a boolean flag
Inside the loop add "Application.DoEvents" at key points and then check the boolean flag. If the flag has been tripped, preform your cleanup and exit the loop.

A: Set the WorkerSupportsCancellation property on your BackgroundWorker to true :-)
You've also got to check the CancellationPending property inside your loop to see if you should be aborting processing. The MSDN article that chakrit linked has a nice block of sample code
Edit: D'oh, you got me by a few seconds there chakrit :)


text:
Q: Wordpress - Getting parent page name dynamically on parent page-specific menu item that links to child page that shares the same child page name? Hopefully that question makes sense. This is essentially what I need:
I have a menu item that shows up on every parent page (that have different names), but will link to a child page that shares the same name. For example:
Parent Page:
http://website.com/parent-1/
Menu Item Link --> http://website.com/parent-1/overview
Parent Page:
http://website.com/parent-2/
Menu Item Link --> http://website.com/parent-2/overview
So essentially what I'm looking for is for the menu item to get the parent name dynamically when the user visits the page:
http://website.com/%parent%/overview/

A: There's not really enough information to answer your question properly. Are you wanting to do this in PHP or Javascript or something else?
You can get the current url in javascript with
window.location.href

In php with
$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]

Specifically in wordpress
global $wp;
home_url( $wp->request )

All the answers are already out there if you search for them...

A: I think that you are using the wrong tag please ask this question under Wordpress oriented tag


text:
Q: can not assign variable with return value of function I'm trying to assign a numerical value to my var gameid with the function initGame(red, black options).
unfortunately gameid will always return undefined.
async function startPendingRoom (red, black) {
    var gameid = initGame (red, black, returnPendingRoomIfExists (red).options);
    removePendingRoomIfExists (red);
    removePendingRoomIfExists (black);

    io.to (red).emit ('startOnlineGameRES', { gameid : gameid });
    io.to (black).emit ('startOnlineGameRES' , {  gameid : gameid });

    console.log (red," vs. ", black, " gameid: ", gameid);
    updatePendingRoomsCLIENT ();
}

function initGame (red, black, options, gameid) {
    dbCon.connect(function(err) { if (err) throw err;
        dbCon.query("INSERT INTO options "
            +"VALUES ("
            +"0 ,"
            + options.malusSize + ", "
            + options.sequenceSize +", "
            + options.throwOnWaste +", "
            + options.throwOnMalus +", "
            + "'"+options.variant+"'" +", "
            + options.turnsTimed +", "
            + options.timePerTurn +", "
            + options.roundsTimed +", "
            + options.timePerRound +", "
            + (options.roomName     != "" ? "'"+options.roomName+"'"     : "null" )+", "
            + (options.roomPassword != "" ? "'"+options.roomPassword+"'" : "null" )+");",
        function (err, option) { if (err) throw err;
            dbCon.query("INSERT INTO games "
                +"VALUES ("
                +"0 ,"
                + option.insertId + ", "
                + "'"+red+"'" + ", "
                + "'"+black+"'" +");",
            function (err, game) { if (err) throw err;
                return game.insertId;
            });
        });
    });

}

A: Try this

function initGame (red, black, options, gameid) {
    return new Promise((resolve) => {
      dbCon.connect(function(err) { if (err) throw err;
        dbCon.query("INSERT INTO options "
            +"VALUES ("
            +"0 ,"
            + options.malusSize + ", "
            + options.sequenceSize +", "
            + options.throwOnWaste +", "
            + options.throwOnMalus +", "
            + "'"+options.variant+"'" +", "
            + options.turnsTimed +", "
            + options.timePerTurn +", "
            + options.roundsTimed +", "
            + options.timePerRound +", "
            + (options.roomName     != "" ? "'"+options.roomName+"'"     : "null" )+", "
            + (options.roomPassword != "" ? "'"+options.roomPassword+"'" : "null" )+");",
          function (err, option) {
              if (err) throw err;
              dbCon.query("INSERT INTO games "
                  +"VALUES ("
                  +"0 ,"
                  + option.insertId + ", "
                  + "'"+red+"'" + ", "
                  + "'"+black+"'" +");",
              function (err, game) {
                  if (err) throw err;
                  resolve(game.insertId);
              });
          });
      });
    })
}

const gameId = await initGame(...);


text:
Q: How to create variables that depend on other variables like %time %date% in batch file? Lets say if I have to print time and date three times, I have to write
echo %date% %time%
echo %date% %time%
echo %date% %time%

The above code prints three different times, if I assign %date% %time% to a variable (to avoid writing them each time) then it is printing constant value three times,
set a=%date%_%time%
echo %a%
echo %a%
echo %a%

I however want to create the %a% variable once, and still echo the actual date and time as they change.

A: It's possible with delayed expansion:
@echo off
setlocal enabledelayedexpansion
set  "a=^!time^!"
echo %a%
timeout 2 >nul
echo %a%

Often call is used for a second layer of parsing to avoid delayed expansion (like in aschipfl's answer), but to use it exactly like any other variable, delayed expansion is the only way to do it.
If for any reason you have to have delayed expansion disabled or want it to work directly on command line, the call method is a good alternative, when you don't mind to type the additional call command.

A: What about this in a batch file:
set "a=%%date%% %%time%%"

call echo %a%
> nul timeout 1
call echo %a%
> nul timeout 1
call echo %a%

In command prompt it looks like this:
>>> set "a=%^date% %^time%"
>>> call echo %a%
>>> call echo %a%
>>> call echo %a%

A: I am assuming you want to set a once, but still show the actual changes in the date and time?
@echo off
setlocal enabledelayedexpansion
for %%i in (1,1,3) do (
        set a=!date!_!time!
        timeout /t 1 > nul
        echo !a!
)

I have used timeout to simply show the difference in time because it runs so quick, it will display the same time as it runs within milliseconds.
Alternatively, call a label:
@echo off
for %%i in (1,1,3) do (
call :timeloop
)
goto :eof
:timeloop
set a=%date%_%time%
timeout /t 1 > nul
echo %a%

you can call the label witihout a loop as well:
@echo off
echo do something
call :timeloop
echo do something else
call :timeloop
goto :eof
:timeloop
set a=%date%_%time%
timeout /t 1 > nul
echo %a%

A: You may use this as an alternative:
@echo off

call :printdate
REM here I wait 2 seconds to test different timestamp values
timeout 2 1>NUL
call :printdate

pause
exit /B 0

:printdate
echo The timestamp is: %DATE%-%TIME%
goto :eof

Output:
The timestamp is: 17/08/2018-13:40:10,37
The timestamp is: 17/08/2018-13:40:12,16

If you want to pass a parameter, use this:
@echo off

call :printdate "The OLD timestamp is: "
REM here I wait 2 seconds to test different timestamp values
timeout 2 1>NUL
call :printdate "The NEW timestamp is: "

pause
exit /B 0

:printdate
echo %~1 %DATE%-%TIME%
goto :eof

Output:
The OLD timestamp is:  17/08/2018-13:54:46,24
The NEW timestamp is:  17/08/2018-13:54:48,14


text:
Q: Linking census shapefiles with geocoded addresses using QGIS I'm trying to merge a census shapefile of New Orleans with a health outcomes dataset by address with QGIS. I have geocoded the addresses and added them as a layer in QGIS but don't know on which variable within the street level city shapefile to merge them.  The dataset has long/lat but the shapefile does not.

A: What you are trying to achieve is called a spatial join. You want to join the attributes of the database to the census shapefile, which holds the geographic/spatial data.
Since you are working with a Census Data Shapefile, I am assuming that it is either a County or Tract Polygon layer. And since you talked about geocoding your health outcomes database, I am assuming you are working with point data for that layer. If you can indeed see the points of your geocoded database points in QGIS (aka they have sufficient spatial information to be displayed) and you want to join them based upon location in relation to polygon layer (census) then you can do as evv_gis suggested above and do Join attributes by location. A regular Spatial Join by Attribute is usually implemented when you have a linking key or column that is shared between the two separate tables that the join is based upon. The Spatial Join by Location is used when no linking key exists and only the geographic location of one in relation to the other can be used to join data to the table.
It isn't clear from your question which way you want the join to go, either the points onto the polygons or vice versa. So based upon your intent, you would decide which way to go.
The scale and lat long coordinates may be slightly different because they are different vector formats, one point and the other polygon. Check out an example of this polygon dataset that is different than just simple latitude, longitude.


text:
Q: NetBeans "Go To Declaration" (F12) work-around in mis-configured JavaServer Faces (JSF) Is there a "shortcut key" work-around (e.g. macro, plugin, etc.) to navigate into a Java method from a JSF page in NetBeans (v. 7.4)?
Context (less relevant):
Problem: JSF navigation features, esp. "Go To Declaration," in my slightly mis-configured NetBeans environment are mostly broken.  I'm gonna lose my mind if I have to keep copying method name > find symbol > paste method name > get matches > look back at parent classes/interfaces > scroll to match > select match.
Config Fail: Won't fix IDE/env configuration (to enable JSF navigation) for now.  Initial attempts failed (plus DevLead asked me not to touch it).  It's some combination of NetBeans/J2EE/JSF/PriceFaces/Gradle/GlassFish.
Analogous Work-Around: Within Visual Studio, macros that match strings to "Go to Implementation" (when declarations bring you to interface)
Psychology: Sequences of learned repetitive fine-motor movements (e.g. a longer sequence of UI navigation commands) are part of "implicit procedural memory."  Mine is very weak.


text:
Q: Is there an example function using the Google Drive API to read comments from google sheets? I want to read comments from multiple google sheets using scripts and store text in another google sheet.
I know there is a .getNote() method and not a .getComment() method but I have read on a few posts there is a way to read the comments using Google Drive API but have not seen an example.


text:
Q: How to select all tables from the database? Good afternoon, whatever your timezone is ..
My question is,
 Is there a way to select all tables? just like how we select all columns?
Something like
 Dim cmdsql As String = "SELECT * FROM  *"

Situation:
I have 4 tables inside the database ("which I would not know the names if my client changes it") So I need a better way how to do those.

I wanna SELECT all the columns, FROM all the tables store it in a dataset, so I can iterate
  if it matches the search criteria.

EDIT: This is my search code by the way.
SearchDataset.Clear()
lstSearchResults.Items.Clear()
btnSearch.Enabled = False
Dim cmdsql As String = "SELECT * FROM *" '- This variable holds the SQL command.
            '-----------------------------------------
            ' Connect to the current connection string
            '----------------------------------------
            SYSTEM_MainClient.dbcon.Open()

            '-----------------------------------------
            ' Setup the Where Clause
            '----------------------------------------

            If cboSearchBy.Text = "StudentID" Then
                SearchAdapter = New OleDb.OleDbDataAdapter(cmdsql + " WHERE " + cboSearchBy.Text + " = " + txtSearchbox.Text, SYSTEM_MainClient.dbcon)
            ElseIf cboSearchBy.Text = "Age" Then
                SearchAdapter = New OleDb.OleDbDataAdapter(cmdsql + " WHERE " + cboSearchBy.Text + " = " + txtSearchbox.Text, SYSTEM_MainClient.dbcon)
            Else
                SearchAdapter = New OleDb.OleDbDataAdapter(cmdsql + " WHERE " + cboSearchBy.Text + " like '" + txtSearchbox.Text + "'", SYSTEM_MainClient.dbcon)
            End If
            SearchAdapter.Fill(SearchDataset, "SearchResults")
            SYSTEM_MainClient.dbcon.Close()
            If SearchDataset.Tables("SearchResults").Rows.Count > 0 Then
                For i = 0 To SearchDataset.Tables("SearchResults").Rows.Count - 1
                    lstSearchResults.Items.Add(SearchDataset.Tables("SearchResults").Rows(i).Item("Last_Name").ToString + ", " + SearchDataset.Tables("SearchResults").Rows(i).Item("First_Name").ToString)
                Next
            Else
                SYSTEM_MainClient.ShowInformation("No records matched with the search '" + txtSearchbox.Text + "'.", "Database Search")
                txtSearchbox.Clear()
            End If
            btnSearch.Enabled = True

Basically what I want to happen, select all from all tables, and fill it in the dataset and iterate inside the dataset if there are matching result names based on the search criteria with my where clause.

A: Here this Is the code to select all the tables from the ms access database
SELECT MSysObjects.Name AS table_name FROM MSysObjects
 WHERE (((Left([Name],1))<>"~") AND ((Left([Name],4))<>"MSys") AND ((MSysObjects.Type) In (1,4,6)))
order by MSysObjects.Name

Making some alteration to this query will help to select columns of table


text:
Q: Modifying cat command to number paragraphs and display last paragraph only I have a text file for which I need to do three things:

*

*Modify the "cat" command to highlight keywords whilst showing the complete contents of the file. SOLUTION FOUND

*Modify the "cat" command to automatically number the paragraphs. These are separated by a single blank line.

*Modify the "cat" command to display the final paragraph only.

The tricky part is that all of these need to be done by modifying the cat command.
I've seen many forum posts explaining that cat is not meant for this - and I can entirely see why. However, the challenge is that I have to use cat!

A: You really need to use cat?
cat -n  thefile | tail -n1

What do you mean with "Highlight keywords whilst showing the complete contents of the file."
What keywords you want to highlight?
What is the purpose to number all the paragraphs but to show only the last one?  (NOTE: the command that i write will do exactly this, cat -n to number the paragraphs, and tail -n1 to show only the last paragraph.)

A: Good luck with teaching gcse computing coursework ;) It doesn't specify to use cat in the question, at least in the one on the question sheet!
I just did
perl -00pe 's/^/$. /' textfile

for 7ii
and
perl -00pe 's/^/$. /' jamestextfile | tail -n1

for 7iii
The important thing in question 7 is using pipe and stuff.

A: I found the question and the comments interesting, so I had a deeper look into it. According the comments given I understand that the question is more about "How to modify the output of the cat command?", maybe just by using command switches and if possible. Just a note, the question would be easier to understand if a sample input is given and the expected output is shown.
It is assumed the following TEST_FILE is given:
This is the first (1) paragraph. This is the second (2) sentence. This is the third (3) sentence.\n The fourth (4) sentence of the first (1) paragraph is the second (2) line of the first (1) paragraph.

This is the second (2) paragraph. This is the second (2) sentence of the second (2) paragraph. This is the third (3) sentence of the second (2) paragraph.

This is the third (3) paragraph. This is the second (2) sentence. This is the third (3) sentence of the second (3) paragraph.

This is the fourth (4) paragraph. This is the second (2) sentence of the fourth (4) paragraph. This is the third (3) sentence.

This is the fifth (5) paragraph. This is the second (2) sentence. This is the third (3) sentence.\n The fourth (4) sentence of the fifth (5) paragraph is the second (2) line of the fifth (5) paragraph.

The paragraphs are not separated by a single blank line (as it was requested), but it is good to learn how some of the commands are working.
Suppress repeated empty output lines:
cat -s TEST_FILE
This is the first (1) paragraph. ...

This is the second (2) paragraph. ...

This is the third (3) paragraph. ...

This is the fourth (4) paragraph. ...

This is the fifth (5) paragraph. ...

Additionally number all output lines:
cat -s -n TEST_FILE
     1 This is the first (1) paragraph. ...
     2
     3 This is the second (2) paragraph. ...
     4
     5 This is the third (3) paragraph. ...
     6
     7 This is the fourth (4) paragraph. ...
     8
     9 This is the fifth (5) paragraph. ...

And number nonempty output lines only:
cat -s -n -b TEST_FILE
     1 This is the first (1) paragraph. ...

     2 This is the second (2) paragraph. ...

     3 This is the third (3) paragraph. ...

     4 This is the fourth (4) paragraph. ...

     5 This is the fifth (5) paragraph. ...

According your "SOLUTION FOUND" it seems to be agreed to use pipe and a second command to modify the output of the cat command. At least for your third requirement it would be necessary.
Therefore you could achieve the same result with number lines nl (but only if the the empty lines are really empty and do not contain white spaces):
cat TEST_FILE | nl
     1  This is the first (1) paragraph. ...

     2  This is the second (2) paragraph. ...

     3  This is the third (3) paragraph. ...

     4  This is the fourth (4) paragraph. ...

     5  This is the fifth (5) paragraph. ...

It would then be possible to Remove blank lines with grep also:
cat -s -n -b TEST_FILE | grep .

In case of lines with whitespaces it would be necessary to remove them first:
grep -v -e '^[[:space:]]*$' TEST_FILE | nl

To Echo newline in Bash you can use:
echo -e $(cat -s TEST_FILE | tail -1)
echo -e $(cat -s -n -b TEST_FILE | tail -1)

You could also show certain lines numbers only. But this is already leaving the scope of the question.


text:
Q: Create Dockerfile for mongoDB 4.2 with authentication how would you script the Dockerfile to create admin user for mongoDB 4.2 ?
Is there a one line command to create admin users not using an interactive subshell ? (didn't see any in mongoDB documentation)
Thanks for your help.
Passing MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD does not work anymore (removed from Docker hub mongo image documentation).
The mongo Docker hub documentation only shows interactive shell admin user creation.
> mongo admin
executes mongo interactive shell but how do you write a shell script to enter commands in that subshell from the top level shell ?
FROM mongo

RUN mongo admin ???? db.createUser({ user: 'jsmith', pwd: 'some-initial-password', roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] });

The docker build process should display:

Successfully added user: {
      "user" : "jsmith",
      "roles" : [
          {
              "role" : "userAdminAnyDatabase",
              "db" : "admin"
          }
      ]
  }

A: OK, here's the way to add authetication via the Dockerfile.

*

*create a init.js file:

db = new Mongo().getDB("admin");

// create admin user

db.createUser({
  user: "admin",
  pwd: "password",
  roles: [
    {
      role: "clusterAdmin",
      db: "admin"
    }
  ]
});

// create non admin user

db.createUser({
  user: "toto",
  pwd: "123",
  roles: [
    {
      role: "readWrite",
      db: "tube"
    }
  ]
});

*

*create the Dockerfile:

FROM mongo

# init.js will be executed when the mongo instance runs

COPY ./init.js ./docker-entrypoint-initdb.d

*

*build your docker image

docker build -t mongoAuth .

*

*run the container (attached mode to see the logs)

docker run --name mongoContainer -p 27017:27017 mongoAuth
What I was missing was that I didn't set the database on which to create the users (admin database) by using:
db = new Mongo().getDB("admin");


text:
Q: On HTML Canvas, certain overlapping colors are creating unwanted shadows I am playing with various colors on canvas and just noticed that certain overlapping colors (e.g. red on blue) create shadows, as shown in the image below:

If you notice, there's about 0.5px wide shadow on the right side of the red circle.
I have the following code:
<canvas width="1000" height="1000"></canvas>

const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');

// BG
ctx.fillStyle = '#1c4c72'; ctx.fillRect(0, 0, 1000, 1000);

// Circle red
ctx.beginPath(); ctx.arc(500, 500, 250, 0, 2 * Math.PI); ctx.fillStyle = '#9a1500'; ctx.fill();

// Circle white
ctx.beginPath(); ctx.arc(500, 500, 150, 0, 2 * Math.PI); ctx.fillStyle = '#ffffff'; ctx.fill();

Is there a remedy for this or is this something to learn to live with? Thanks for any ideas.
Tested on Firefox and Chrome on Windows, latest versions.


text:
Q: Loading an javascript image object from a server file I am developing a mobile application that has this scenario:  A user goes to one screen where they supply indexing meta data for an image.  From this first screen they can go to a second screen where they select and upload the actual image to go with the meta data.  Once selected, they go back to the first screen where they can then upload both the image and the meta data to a separate web service.  Now, once the image has been selected and the user is back on the first screen, they may want to look at or change the image (that they previously selected) before actually submitting it to the web service.  So I need to provide a way for the user to go back to the second screen and see the image they previously uploaded (without having to select it again).  Clear so far?
In my ASP.Net MVC mobile application code I am caching the uploaded image to the server in a temporary file path on the server.  Now I want to take that saved file and load it into a javascript image object so it can be displayed to the user when they go back to the second screen.  How can this be done?

A: When you upload it to the server, the server can respond with a URL that can be used to retrieve the uploaded image. Capture that response and use it to set the src attribute of a new client-side Image object.


text:
Q: C# editor class view Is there a way of making the C# editor in Visual studio 2010 behave like the visual basic editor where the left combo box lets you pick an object and the right one shows only its events/methods like VB?
I am working on a form with alot of controls and methods (Devexpress Ribbon Form) and all the controls, their methods, the forms methods are appearing in the right combo box and navigating to form methods is really cumbersome now,
or is there something built in within visual studio that I can use to navigate quickly between methods?

A: Tools -> Options -> C# -> General
Check the Navigation bar checkbox under the Display group


text:
Q: Error import shapeFile shp2pgsql-gui I'm trying to import a shapefile to my PostGIS database but I can not, give a look:
Importing with configuration: 12mie250gc_sir, public, geom, / home/samuelribeiro/Desktop/MALHA_DIGITAL/ac/12MIE250GC_SIR, mode = c, dump = 1, simple = 0, geography = 0, index = 1, shape = 1, srid = 4326
Shapefile type: PolygonM
PostGIS type: MULTIPOLYGONM [3]
Failed SQL begins: "SET TO UTF8 CLIENT_ENCODING;
STANDARD_CONFORMING_STRINGS SET TO ON;
BEGIN;
CREATE TABLE "public". "12mie250gc_sir" (gid serial,
"id" float8
"nm_micro" varchar (100),
"cd_geocodu" varchar (2));
ALTER TABLE "public". "12mie250gc_sir" ADD PRIMARY KEY (gid);
SE "
Failed in pgui_exec (): ERROR: function AddGeometryColumn (unknown, unknown, unknown, unknown, unknown, integer) is not unique
LINE 9: SELECT AddGeometryColumn ('public', '12mie250gc_sir ',' geom ', '4 ...
                ^
HINT: Could not choose a best candidate function. You might need to add explicit type casts.

Shapefile import failed.

A: Looks like you're loading into a database that either (a) has a version of PostGIS installed that doesn't match the loader or (b) has no PostGIS installed at all. Run "select postgis_full_version()" in your target database and see if it's the version you expect.

A: You can try the opensource ogr2ogr-tool to import the shapefile:
command would be something like this:
ogr2ogr -f "ESRI Shapefile" mydata.shp PG:"host=myhost user=myloginname dbname=mydbname password=mypassword" "mytable"

Information can be found in this cheatsheet


text:
Q: how to route com port data to usb port (for exporting gps data) My dell laptop has an internal GPS card that outputs NMEA GPS info over COM 4. I want to capture the COM4 traffic and send it to a USB port, then connect the USB port to a NMEA compatible  device (a VHF radio).  I will be using .NET to capture the data and route it to the USB port, unless there is already a utility/driver that does this.
So I have a few issues:

*

*I think it should be fairly straight forward to capture the COM port data, and so the problem is sending it to a USB port - which leads to my next problem

*NEMA devices use 2 wires, I suppose this will correspond to the data + and data - of the USB, so I think I could wire that up myself.
So... what is required to relay COM data to an USB port using .NET
and...  will my plan for wiring the USB cable work (electrically, I mean)
Do it sound like I'm on the right track?  I wonder if a utility like this already exists, it seems like a common need, convert hardware generated com port data to usb.
Any advice welcome!

A: With USB you do not have direct access to the tx/rx wires of the physical port like you do with a COM port.  Your device would need to actually support USB.  It is possible to buy a USB->serial dongle which would present itself as another COM port.  Then it would be fairly trivial to copy the data from one COM port to another.

A: It would help to know what model your VHF radio is. Usually VHF radios receive NMEA input through a serial port on the radio, but it's often not labelled as such, with names like "ground" and "nmea in". The USB is sometimes for outputting NMEA (and creates a virtual serial port on your laptop) or for controlling the radio using your laptop with custom software that came with the radio.
If your radio actually has the standard NMEA input lines, and your laptop has a real COM4 port then you need to connect the correct wires from the COM port to your radio - http://en.wikipedia.org/wiki/Com_port tells you which wire is which for your laptop, and you want to connect latop:tx to radio:NMEA in and laptop:rx to radio:NMEA out. And make sure the baud rates are the same for the two devices (4800 used to be default for NMEA, but it can be 9600 or 36400 or even higher these days).
But the COM4 GPS port on your laptop is probably a virtual port. In this case you need to redirect it to a real port if you have one (e.g. COM1), or buy a "USB to serial converter" (search for that phrase on google) and redirect COM4 to that. Then the wiring job is the same. But redirecting is going to be tricky - there is software out there.
And if your radio genuinely expects to receive NMEA over USB, then either it should come with software that asks you which serial port you want it to connect to - so then you select COM4 (this is by far the simplest scenario). Or it might create its own virtual serial port when you plug in the USB cable. You're probably running Windows, so check on the Device Manager in Control Panel under Ports (COM &LPT) when you plug it in to see if a new serial port appears, and what it's COM number is. And then you need some software to connect the two virtual ports together.
As for all the redirect and virtual port software that I mention - theres com0com which is freeware, and eltima.com who sell serial port software. You might be able to find other stuff out there. Or you have to learn about low level serial port driver programming, which is likely to be tricky. Good luck.


text:
Q: regex to match looping data in a file I have data in file in which records are like given below
X00
X01
NNN---Loop - 1
LLL
LLL
LLL
 .
 .
 .
LLL (99th time)
NNN---Loop - 2
LLL
LLL
LLL
LLL
NNN---Loop - 3
LLL
T01
T00

And in data as you can see loops are there.
So it means
NNN--(can occur one time in one loop)
LLL--(Can occur 99 times in a loop)

And this loop should occur at least one time and Max limit is n times.
First two and last two records are going to be static.
So, I'm trying to match this data with regular expression. Tried google but not able to write this much complex regex for this loop type of data.
Any suggestion please ?
Thanks

A: Have You Tried the expression:
X01\nX02\n(N{3}(\nL{3}){1,99}\n){1,3}T01\nT02

Explanations:

*

*X01\nX02\n is for your beginning constant values.

*(N{3}(\nL{3}){1,99}if for your loop and inner values.

*Next {1,3} is the range of number of loops. I have used 3, you can changed it.

*T01\nT02 for your last constant values.

You can justify the answer in Regex101


text:
Q: R object reference counting I am debugging a large R package. It is creating several objects but not cleaning the memory. Is there a way to do reference counting in R, checking which object has been accessed how many times. This will give me a rough idea of objects that are created but never used in later parts of the code. FYI, most of these objects are data.table

A: Reference counting is a mechanism to determine how many R objects are pointing to the same underlying SEXPREC (C structure of R objects). For example in
a <- 1:5
b <- a

a and b point to the same SEXPREC and if one of both is modified, the SEXPREC needs to be copied to not change the value of the other object. However, if the reference count of an object is not increased, this does not mean that it is not relevant for the computations. For example in
a <- 1:5
b <- a+1

a is relevant, but both a and b will have a low reference count because they are pointing to different SEXPREC. Hence, reference counting of R cannot be used to check if objects are created but never used.
Just for fun, one could use lexical scoping to count how many times an R object was access:
obj <- function(x){
    n <- 0
    get <- function() {n <<- n+1; x}
    count <- function() n
    list(get=get, count=count)
}

Then create a new R object with
a <- obj(1:10)

and access it with
a$get()
 [1]  1  2  3  4  5  6  7  8  9 10

One can count how many times the object was accessed.
a$count()
[1] 1
max(a$get())
[1] 10
a$count()
[1] 2

If the object has count 0, it was created but never used.
b <- obj(2)
b$count()
[1] 0


text:
Q: ASP.NET MVC: Menu in the view not updating even after updating sitemap I am using sitemap to show the menu in the web application(ASP.NET MVC)
I updated sitemap and ran the web application again, but the changes are not seen in the view. I tried "hard reload" and "empty cache and hard reload" in the chrome browser and nothing worked.
How can I see the sitemap changes?

A: While you can use the sitemap and master pages in MVC, using the default _Layout.cshtml in Shared folder inside Views is much simpler and easier to use.
In the beginning when I switched from ASP.Net Web Forms to ASP.Net MVC, I also tried to stick to sitemap and master pages, however, soon I found out that _Layout.cshtml is not too difficult at all. You can still control access by allowing specific users and roles.

A: I could fix this by killing the IIS Express(How do I start/stop IISExpress Server ?) and running the web application again.


text:
Q: How to connect database by using username and password in .net c# I'm new to .net c#, hope this question is not sound silly. How can I connect to the database in web.config by using the username and password??
Example:
Following is the connection strings that I used to connect to the database. How could I write/set so that I can set the username (username = test) and password (password = abc123) for this connection strings and so that it will allows me to access to the database?
  <connectionStrings>
    <add name="aConnectionString" connectionString="Data Source=AAA-LLLL-SQL-00;Initial Catalog=Database_Name;Connect Timeout=1;Integrated Security=True;" providerName="System.Data.SqlClient"/>
  </connectionStrings>

A: Try something like this.
<connectionStrings>
     <add name="aConnectionString" connectionString="Data
 Source=AAA-LLLL-SQL-00;Initial Catalog=Database_Name;User Id=myUsername;Password=myPassword"
 providerName="System.Data.SqlClient"/>
</connectionStrings>

A: Use this to pull your connection string from the web.config.
http://msdn.microsoft.com/en-us/library/ms178411.aspx
Then you will use the .net Sql Provider to create a connection.
using(SqlConnection con = new SqlConnection(connectionstring))
{

   con.Open();
   // Perform operations here

}

A: Are you trying from IIS?
Then you need to grant your App Pools account access to SQL Server.
CREATE LOGIN [IIS APPPOOL\ASP.NET v4.0] FROM WINDOWS WITH DEFAULT_DATABASE=[AAA-LLLL-SQL-00], DEFAULT_LANGUAGE=[us_english]
GO

A: Reference for ADO and ADO.NET connection strings http://www.sqlstrings.com/

A: <connectionStrings>
   <add name="aConnectionString" connectionString="Data Source=AAA-LLLL-SQL-00;Initial Catalog=Database_Name; User Id=your username; Password=pwd;" providerName="System.Data.SqlClient"/>
</connectionStrings>

A:     <connectionStrings>
       <add name="aConnectionString" connectionString="Server={ip};Database= {databasename}; User Id={username}; Password={password}"/>
</connectionStrings>

This should work replace {...} with your values.


text:
Q: Sending data to Activity without startActivityForResult How can I send data to another Activity that did not startActivityForResult?
I Override the onActivityResult method in order to perform logic as soon as a result returns from another Activity. Specifically, from my EditItemActivity
Process:
Within my MainActivity,

when I click on an item in the ListView, I am redirected to another Activity called ToDoDetailActivity

When I click the Edit button I am redirector to another Activity called EditItemActivity"

As soon as I make my changes and press the Edit button on the EditItemActivity, I return back to the MainActivity
data = new Intent(EditItemActivity.this, MainActivity.class);
data.putExtra(EDITTEXT_VALUE, etValue);
setResult(123, data);
startActivity(data);

Within my MainActivity, I want to UPDATE the item I just edited with this logic within my onActivityResult method. However, I don't see any logs in LogCat meaning I do not believe this method is being used and therefore no logic is performed
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null) {
            return;
        }
        if (resultCode == 123) {
            String editedItemValue = data.getStringExtra(EditItemActivity.EDITTEXT_VALUE);
            todoItems.remove(editedPosition);
            aToDoAdapter.insert(editedItemValue, editedPosition);
            aToDoAdapter.notifyDataSetChanged();
        }
    }

A: In your code:
data = new Intent(EditItemActivity.this, MainActivity.class);
data.putExtra(EDITTEXT_VALUE, etValue);
setResult(123, data);
startActivity(data);

When you execute startActivity with MainActivity.class it is launching a new Activity so you are not going to find a result in "onActivityResult" method.  It is because you are not returning to the main activity after finishing in a "child" activity.
What I have done in the past is use broadcast event to notify the "MainActivity" about updating the view.
Hope that helps.

A: We can use BroadcastReceiver or use database to store the result of your edit in EditItemActivity then update that result in onResume method of MainActivity


text:
Q: java.lang.NullPointerException while executing multithreaded database application Creating a multi-threaded application which creates multiple threads and queries same table of the database
Given the input xml file with format:
<transliteration>
<element>
    <source>about us</source>
</element>
</transliteration>

Application reads multiple files and creates multiple threads one for each xml file and output will be another xml file with format
<transliteration>
<element>
    <source>about us</source>
        <target/>
</element>
</transliteration>

below is the run method of the thread
public void run() {

        MultipleDatabaseThread th = new MultipleDatabaseThread();
        Map<String,String> map = new HashMap<String,String>();

        try
        {
            Document doc = loadXmlContentToMemory(this.inputString);

            XPathExpression expr = null;
            XPathFactory xFactory = XPathFactory.newInstance();
            XPath xPath = xFactory.newXPath();
            expr = xPath.compile("/transliteration/element//source");
            Object result = expr.evaluate(doc, XPathConstants.NODESET);
            NodeList nodes = (NodeList) result;
            String sourceString = "";
            if(nodes.getLength() > 0)
            {
                for (int i=0; i<nodes.getLength();i++)
                {
                    //System.out.println("Name: "+nodes.item(i).getNodeName() +" Local Name: "+nodes.item(i).getLocalName() +" Value: "+nodes.item(i).getTextContent());
                    sourceString = nodes.item(i).getTextContent();
                    map = th.getCompleteStringTransliterate(sourceString, this.language);

                    if(map.get(sourceString) == null || map.get(sourceString).equals("") || map.get(sourceString).equals(sourceString))
                    {
                        map.clear();
                        map = th.getRecordsFromDatabase(sourceString, language);

                        Element abc = doc.createElement("target");

                        String targetString = "";

                        String[] tokens = sourceString.trim().split("\\s+");

                        for(int itr=0; itr < tokens.length; itr++)
                        {
                            targetString = targetString+" "+map.get(tokens[itr]);
                        }

                        abc.setTextContent(targetString.trim());
                        nodes.item(i).getParentNode().appendChild(abc);
                    }
                    else
                    {
                       Element abc = doc.createElement("target");
                       abc.setTextContent(map.get(sourceString));
                       nodes.item(i).getParentNode().appendChild(abc);
                    }
                }
            }

            try
            {

                expr = xPath.compile("/transliteration/element//target");
                result = expr.evaluate(doc, XPathConstants.NODESET);
            }catch(XPathExpressionException ex)
            {   }

            NodeList nodesList = (NodeList) result;

            for(int i =0;i<nodesList.getLength();i++)
            {
                System.out.println("Node Name: "+nodesList.item(i).getNodeName()+" Node Value: "+nodesList.item(i).getTextContent());
            }

            try
            {
                Transformer transformer = TransformerFactory.newInstance().newTransformer();
                StreamResult strResult = new StreamResult(new File(this.inputString+"_out.xml"));
                if(doc != null && strResult != null)
                {
                    DOMSource source = new  DOMSource(doc);
                    transformer.transform(source, strResult);
                }
            }
            catch(TransformerException ex)
            {
               System.out.println(""+ex);
            }
            catch(TransformerFactoryConfigurationError ex)
            {
               System.out.println(""+ex);
            }

        }catch(IOException ex)
        {
            ex.printStackTrace(System.out);
        }
        catch(DOMException ex)
        {
            ex.printStackTrace(System.out);
        }
        catch(ParserConfigurationException ex)
        {
            ex.printStackTrace(System.out);
        }
        catch(SAXException ex)
        {
            ex.printStackTrace(System.out);
        }
        catch(XPathExpressionException ex)
        {
            ex.printStackTrace(System.out);
        }
        catch(InterruptedException ex)
        {
            ex.printStackTrace(System.out);
        }

    }

*

*loadXmlContentToMemory** function takes filename as a input and loads
xml content in the Document.

*getCompleteStringTransliterate** is a function of
MulltipleDatabaseThread class which returns a map variable which
contain source and its traget string in it.

*getRecordsFromDatabase** is anoher function in same class which
splits source string and gets its target string again returns map
variable
public class MultipleDatabaseThread {
public Map<String,String> getCompleteStringTranslate(String inputString, String language) throws InterruptedException
{
    Map<String,String> map = new HashMap<String,String>();

    synchronized(OutputRecords.getMap())
    {
       //long startTime = System.currentTimeMillis();

       OutputRecords.clearOutputStream();
       Thread thCompleteString = new DatabaseThread(inputString, language);
       thCompleteString.start();
       thCompleteString.join();

       map = OutputRecords.getRecords();
       //System.out.println("Complete String Time Taken:: "+(System.currentTimeMillis()-startTime));
       return map;
    }
}

public Map<String,String> getRecordsFromDatabase(String inputString, String language) throws  InterruptedException
{
    String[] tokens = inputString.split("\\s+");

    Map<String,String> map = new HashMap<String,String>();

    Thread[] databaseThreads = new Thread[tokens.length];

    synchronized(OutputRecords.getMap())
    {
        //long startTime = System.currentTimeMillis();

        OutputRecords.clearOutputStream();
        for(int index=0; index < tokens.length; index++)
        {
            databaseThreads[index] = new DatabaseThread(tokens[index],language);
            databaseThreads[index].start();
        }
        for(int index = 0 ; index < tokens.length; index++)
        {
                databaseThreads[index].join();
        }

        map = OutputRecords.getRecords();
        //System.out.println("Tokens Time Taken:: "+(System.currentTimeMillis()-startTime));

        return map;

    }
}

}
both these functions uses a static/shared map variable in OutputRecord class and generates multiple threads which actually gives call to database and populates shared map variable and return that variable
but on execution of this program its giving
Exception in thread "Thread-0" java.lang.NullPointerException
    at transliterationthreading.ExecuteOuterThread.run(ExecuteOuterThread.java:66)

on line
if(map.get(sourceString) == null || map.get(sourceString).equals("") || map.get(sourceString).equals(sourceString))

So one thread gets terminated and then other gets executed completely and generates output file. I am not getting the problem can anyone gve some suggestion in solving this problem.
Thanks

A: I woud suspect that the map content changes during evaluation of the line
if(map.get(sourceString) == null || map.get(sourceString).equals("") || map.get(sourceString).equals(sourceString))

This way your null checks succeed but the new value you get from the map could be null. Map is not synchronized!
Change this line to
String sourceStringValue = map.get(sourceString);
if(sourceStringValue == null || sourceStringValue.equals("") || map.get(sourceString).equals(sourceString))

A: Thanks all for your Efforts
I tried solving this problem using a different approach by not using the static shared map and using ExecutorService and Callable Interface approach
here is my code
try
        {
            doc = loadXmlContentToMemory(this.inputString);
            expr = xPath.compile("/transliteration/element//source");
            result = expr.evaluate(doc, XPathConstants.NODESET);

        }catch(ParserConfigurationException ex)
        {
            System.out.println("loadXmlError: "+ex.toString());
        }
        catch(IOException ex)
        {
            System.out.println("loadXmlError: "+ex.toString());
        }
        catch(SAXException ex)
        {
            System.out.println("loadXmlError: "+ex.toString());
        }
        catch(XPathExpressionException ex)
        {
            System.out.println("loadXmlError: "+ex.toString());
        }

        NodeList nodes = (NodeList) result;
        String sourceString = "";

        if(nodes.getLength() >0)
        {
            Map<String,String> fileMap = new HashMap<String,String>();
            ExecutorService executor = Executors.newFixedThreadPool(NTHREADS);

            for(int index =0; index <nodes.getLength(); index++)
            {
                sourceString = nodes.item(index).getTextContent();
                Callable<Map<String,String>> worker = new MultipleDatabaseCallable(sourceString,language);
                Future<Map<String,String>> map = executor.submit(worker);

                try
                {
                    //System.out.println(""+Thread.currentThread().getName()+"SourceString:: "+sourceString+"Map: "+map.get().get(sourceString));
                      fileMap.putAll(map.get());
                }catch(InterruptedException ex)
                {
                    System.out.println("future read: "+ex.toString());
                }
                catch(ExecutionException ex)
                {
                    System.out.println("future read: "+ex.toString());
                }
            }

            executor.shutdown();
            // Wait until all threads are finish
            while (!executor.isTerminated()) {

            }
            ExecutorService tokenExecutor = Executors.newFixedThreadPool(NTHREADS);
            for(int i =0 ;i<nodes.getLength();i++)
            {
                sourceString = nodes.item(i).getTextContent();
                if(fileMap.get(sourceString) == null || fileMap.get(sourceString).equals("") || fileMap.get(sourceString).equals(sourceString))
                {
                    fileMap.remove(sourceString);
                    Callable<Map<String,String>> worker = new MultipleTokenCallable(sourceString,language);
                    Future<Map<String,String>> map = tokenExecutor.submit(worker);

                    try
                    {
                        fileMap.putAll(map.get());
                    }
                    catch(InterruptedException ex)
                    {
                        System.out.println("Tokenized put Interupted exception: "+ex.toString());
                    }
                    catch(ExecutionException ex)
                    {
                        System.out.println("Tokenized put Execution exception: "+ex.toString());
                        ex.printStackTrace(System.out);
                    }

                    Element targetElement = doc.createElement("target");
                    String targetString = "";

                    String[] tokens = sourceString.trim().split("\\s+");

                    for(int itr=0; itr < tokens.length; itr++)
                    {
                        targetString = targetString+" "+fileMap.get(tokens[itr]);
                    }
                    targetElement.setTextContent(targetString.trim());
                    nodes.item(i).getParentNode().appendChild(targetElement);
                    //System.out.println(""+Thread.currentThread().getName()+" Target:  "+targetString+" Source:  "+sourceString);
                }
                else
                {
                    Element abc = doc.createElement("target");
                    abc.setTextContent(fileMap.get(sourceString));
                    nodes.item(i).getParentNode().appendChild(abc);
                }
            }

            tokenExecutor.shutdown();
            // Wait until all threads are finish
            while (!tokenExecutor.isTerminated()) {

            }
            try
            {
                Transformer transformer = TransformerFactory.newInstance().newTransformer();
                StreamResult strResult = new StreamResult(new File(this.inputString+"_out.xml"));
                if(doc != null && strResult != null)
                {
                    DOMSource source = new  DOMSource(doc);
                    transformer.transform(source, strResult);
                }
            }
            catch(TransformerException ex)
            {
               System.out.println(""+ex);
            }
            catch(TransformerFactoryConfigurationError ex)
            {
               System.out.println(""+ex);
            }

        }

since multiple threads gets generated using this and all threads try to connect to the  database at same time, this might give too many connections error, if number of concurrent threads increases. So you need to maintain a Connection Pool to overcome that problem