text:
Q: How can I make Visual Studio copy the required .dll files into the release folder? I'm using Visual Studio 2012 with C++, developing a Qt application.
I'm able to compile it and debug it, but, somehow, no .dll file is in the Debug or Release folder. I've tried some of other posts solutions, but none worked.
So, how can I make Visual Studio copy the required .dll files into the release folder?
I think it should be an option somewhere. I'm just starting to think about copying it handmade.

A: Too much bad advice, a DLL cannot be a resource.  Windows demands that code is stored in a separate executable file with a proper PE32 header.  Which permits it to create a memory-mapped file to map the file content into memory, allowing the code to be shared by multiple processes and keeping it out of the paging file.  And to relocate the code when the DLL's base address is already in use.
Simply use Project + Properties, Build events, Post-Build Event to xcopy the DLLs.  Arbitrarily, if you stored the needed DLLs in the "dlls" subdirectory of your project then this command will get them copied, only when necessary:
 xcopy /d /y "$(ProjectDir)dlls\*.*" "$(OutDir)"

Use it both in the Debug and Release configuration so you'll debug exactly what you'll ship.

A: Add your .dll files as resources to your project. In this way your .dll files will be in a resources folder in you project.
Try Add Item... -> New Item... and add a resource (.qrc) file to the project and add the .dll files to that.


text:
Q: How can i make function that makes my player move in Pygame I'm trying to make space invaders in Pygame. I am trying to make the player move I saw few tutorials and that suppose to work but nothing happening when I am pressing the button.
this is the code:
import pygame

pygame.init()

WIN = pygame.display.set_mode((800, 600))
WIDTH, HEIGHT = 800, 600
VEL = 3
FPS = 60
WHITE_COLOR = (255, 255, 255)
pygame.display.set_caption("Space Invaders")
ufo_icon = pygame.image.load('ufo.png')
player = pygame.image.load('space-invaders.png')
player = pygame.transform.scale(player, (60, 60))
playerX = 400 - player.get_width()/2
playerY = 300
pygame.display.set_icon(ufo_icon)

def player_movement(playerX , keys):
    if keys[pygame.K_LEFT]:
        playerX += VEL

def draw_window(player, playerX, playerY):
    WIN.fill((WHITE_COLOR))
    WIN.blit(player, (playerX, playerY + 100))
    pygame.display.update()

def main():
    run = True
    while run:
        for event in pygame.event.get():

            if event.type == pygame.QUIT:
                run = False

            keys = pygame.key.get_pressed()
        player_movement(playerX, keys)
        draw_window(player, playerX, playerY)

main()

A: Python has no concept of in-out parameters. You need to return the new value from the function:
def player_movement(playerX , keys):
    if keys[pygame.K_LEFT]:
        playerX -= VEL
    if keys[pygame.K_RIGHT]:
        playerX += VEL
    return playerX

def main():
    playerX = 400 - player.get_width()/2
    playerY = 300
    run = True
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

        keys = pygame.key.get_pressed()
        playerX = player_movement(playerX, keys)
        draw_window(player, playerX, playerY)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is Twitter session response null? I have a custom button for twitter login. When I authorise in twitter using this button, I get back twitterSessionResult. But the response property of this object is null.
How can I get twitter id and email?
    twitterButton = (FancyButton) findViewById(R.id.twitter_login_button);
    twitterButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            twitterAuthClient.authorize(WelcomeActivity.this, new com.twitter.sdk.android.core.Callback<TwitterSession>() {

                @Override
                public void success(Result<TwitterSession> twitterSessionResult) {
                    Log.w("LOG", ""+ twitterSessionResult.response); // LOG: null
                }

                @Override
                public void failure(TwitterException e) {
                    e.printStackTrace();
                }
            });

        }
    });

A: Found answer here: https://stackoverflow.com/a/29982457/3400881 . I need twitterSessionResult.data, not twitterSessionResult.response .


text:
Q: Cloud Firestore whereNotEqual Does Firestore support something like whereNotEqual?
For example, I need to get exact documents where key "xyz" is missing.
In Firebase realtime db, we could get it by calling *.equalTo(null).
Thanks.

A: Firestore does not support a direct equivalent of !=. The supported query operators are <, <=, ==, >, or >= so there's no "whereNotEqual".
You can test if a field exists at all, because all filters and order bys implicitly create a filter on whether or not a field exists. For example, in the Android SDK:
collection.orderBy("name")

would return only those rows that contain a "name" field.
As with explicit comparison there's no way to invert this query to return those rows where a value does not exist.
There are a few work-arounds. The most direct replacement is to explicitly store null then query collection.whereEqualTo("name", null). This is somewhat annoying though because if you don't populate this from the outset you have to backfill existing data once you want to do this. If you can't upgrade all your clients you'll need to deploy a function to keep this field populated.
Another possibility is to observe that usually missing fields indicate that a document is only partially assembled perhaps because it goes through some state machine or is a sort of union of two non-overlapping types. If you explicitly record the state or type as a discriminant you can query on that rather than field non-presence. This works really well when there are only two states/types but gets messy if there are many states.

A: Cloud Firestore now supports whereNotEqualTo in database queries.
Keep in mind if you have more than one field in your query you may have to create a composite index in Cloud Firestore.


text:
Q: Is the induction correct in this proof of $R/(I_1\cdots I_k) \cong R/I_1 \times \cdots \times R/I_k$? From Algebra, Chapter $0$ by Aluffi:

In the second line of the proof, he writes assume the statement is known for fewer ideals, but then says we have to prove it for the case of two ideals.
It seems like something is incorrect here.
Isn't the induction hypothesis already assuming that $R \to \big(R/(I_1 \cdots I_{k-1})\big) \times R/I_k$ is surjective?

A: The proof is completely fine. By induction hypothesis we assume that $R \rightarrow R/I_1 \times \dots \times R/I_{k-1}$ is surjective if the the ideals $I_j$ and $I_l$ are pairwise coprime for all $1 \leq j \neq l \leq k - 1$. Now we consider the map $R \rightarrow R/I_1 \times \dots \times R/I_{k-1} \times R/I_k \cong R/I_1 \cdots I_{k-1} \times R/I_k$. Thus we deal with the two ideals $I_1 \cdots I_{k-1}$ and $I_k$ (which are coprime under the assumption that $I_j$ and $I_l$ are pairwise coprime for all $1 \leq j \neq l \leq k$) and their quotients which means we have to show it for the case of two ideals.


text:
Q: ITunes 12.8.1.2 does not recognize devices nor see backups Running Yosemite 10.10.5 on MacBook Air (early 2014), with Safari v. 10.1.2, iTunes 12.8.1.2, iTunes updated dec 14 2018.
Devices (iPhone, iPad) do not register in iTunes. Are seen in USB device tree in System Information.
In iTunes, preferences, Devices: backups are blank - contains at least 10 for 5 different devices ....
Safari 'cannot be opened because of a problem' (no window comes up).
ITunes 12.8. will not install: 'Newer version already installed'.
ITunes will not delete:'required by OSX'. Timemachine backup will not restore...
I need device connectivity, their backups and this OSX.
Any suggestions ?
Berthe
Dec 17: new iTunes build in App store appeared, it fixes Safari and Photo-connect to device. ITunes not tested yet, but I expect it, too, is fine....

A: Appears to be issues relating to the new MobileDevice.framework on Yosemite (I'm aware that the problem is slightly different, but the issues seem related.) I'd recommend upgrading macOS  if you can (it's good practice anyways), and if not, downgrading iTunes or waiting to see if Apple releases a fix.


text:
Q: How to Install and run python and database over busybox I purchased a a WiFi server terminal which runs Busybox and only comes with a http web implementation which pops up once you connect to the WiFi. I'd like to support for SQL (or some variation) and python so i can build in some new web functions over it. Can anyone help break down steps i should take to achieve this? I have no background installing linux packages.
Thanks in advance.


text:
Q: Incorrect date when trying to insert in database using jdbc, SimpleDateFormat I'm trying to insert "2016-07-24" into the Oracle database using the JDBC, SimpleDateFormat class. In the database it should be saved as  "24-JUL-16", instead it is inserting "24-JUL-24"
which is an incorrect format. Below is my code. Please let me know what should be changed for the SimpleDateFormat.
I suspect if it is because I haven't declared the
 public static final SimpleDateFormat transDate = new SimpleDateFormat(
            "yyyy-MM-dd");

as transient.
import java.sql.Connection;
import java.sql.SQLException;
import com.myjdbc.database.DBConnection;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;

public class DateInserter {
    private static final String PROCEDURE_FOO = "{call P_PROCESS_FOO(?,?,?)}";
    public static transient final SimpleDateFormat transBusinessDate = new SimpleDateFormat(
            "yyyy-MM-dd");
    public static final SimpleDateFormat transDate = new SimpleDateFormat(
            "yyyy-MM-dd");

    public static void callProcedure() throws SQLException {
        Connection con = null;
        CallableStatement stmt = null;
        ResultSet jdbcRs = null;
        try {
            con = DBConnection.getConnection();
            stmt = con.prepareCall(PROCEDURE_FOO);
            stmt.setString("P_TRANS_ID", "A1221");
            stmt.setDate("P_TRANS_BUSNS_DATE", new java.sql.Date(
                    transBusinessDate.parse("2016-07-31").getTime()));
            stmt.setDate("P_TRANS_DT",
                    new java.sql.Date(transDate.parse("2016-07-30").getTime()));
            stmt.execute();
            jdbcRs = (java.sql.ResultSet) stmt.getObject("P_TRANS_DATA");

        } catch (Exception e) {
            System.out.println("JDBC Exception " + e);
        }
    }
}


text:
Q: Keycloak - Get all Users mapped to roles I know keycloak has exposed below api,
<dependency>
    <groupId>org.keycloak</groupId>
    <artifactId>keycloak-services</artifactId>
    <version>2.0.0.Final</version>
</dependency>

With complete documentation here. I cannot find the required api here to fetch all users with specific role mapped to them.
Problem Statement - I need to pick all users from keycloak server who have a specific role. I need to send email to all users with role mapped to them.

A: This should be now possible with the updated rest endpoint.
Set<UserRepresentation> usersOfRole = realmResource.roles().get(roleName).getRoleUserMembers();

A: Here is another interesting query, which would also display other useful fields.
SELECT kr_role.REALM_ID 'Realm', cl.CLIENT_ID 'Realm Client',
    kr_role.NAME 'Role Name',
    kr_role.DESCRIPTION 'Role Description',
    user_ent.USERNAME 'Domain ID', user_ent.EMAIL 'Email'
  FROM keycloak_role kr_role, user_role_mapping role_map,
    user_entity user_ent, client cl
  WHERE role_map.USER_ID = user_ent.ID
  AND kr_role.ID = role_map.ROLE_ID
  AND kr_role.CLIENT = cl.ID
  AND cl.REALM_ID = '<realm_name>'
  AND cl.CLIENT_ID = '<client_name>'
  ORDER BY 1, 2, 3;

A: Based on the documentation it appears to be this API:
GET /{realm}/clients/{id}/roles/{role-name}/users

It is there for a while. In this older version however it was not possible to get more than 100 users this way. It was fixed later and pagination possibility was added.

A: There is an outstanding feature request asking for this function via the API.
In the meantime if your requirement is once-off you could obtain the user names (or email addresses) by interrogating the database joining KEYCLOAK_ROLE to USER_ROLE_MAPPING to USER_ENTITY
Something like:
SELECT username
FROM keycloak_role kr
   JOIN user_role_mapping rm ON kr.id = rm.role_id
   JOIN user_entity ue ON rm.user_id = ue.id
WHERE kr.name = 'your_role_name';

A: If anyone is still searching for a Postgres Query to find information regarding users/roles/groups in keycloak database, I came up with this one lately.
It uses two CTEs to have the groups and roles straight (recursing for groups in groups, because they can nest in arbitrary depth and fetching composite roles with their parents) and a simple UNION for group and direct assignments.
Please note the WHERE clause, where you can limit the realm and different aspects. You can search for

*

*all roles from a specific user (just matching username)

*all users, that have a particular role assigned (matching role_name)

*everything coming from a specific group (I sometimes use it without the username column in the projection to just see, what roles a group has. Please note the prefix in the group column)

-- flat out GROUPS in GROUPS
WITH RECURSIVE groups AS (
    SELECT
        g.id,
        g.id AS parent_group,
        g.name,
        g.name AS parent_name,
        g.realm_id,
        1 AS iter
    FROM
        keycloak_group g
    UNION
    SELECT
        groups.id,
        parents.parent_group,
        groups.name,
        parents.name,
        groups.realm_id,
        groups.iter + 1
    FROM
        groups
        INNER JOIN keycloak_group parents ON groups.parent_group = parents.id
),
-- Collect roles and composite roles
roles AS (
    SELECT
        r.id,
        r.name AS role_name,
        null AS base_role,
        c.client_id
    FROM
        keycloak_role r
        LEFT JOIN client c ON r.client = c.id
    UNION
    SELECT
        r.id,
        r2.name,
        r.name,
        c.client_id
    FROM
        keycloak_role r
        JOIN composite_role cr ON r.id = cr.composite
        JOIN keycloak_role r2 ON r2.id = cr.child_role
        LEFT JOIN client c ON r.client = c.id
)
SELECT DISTINCT
    username,
    role_name,
    base_role,  -- for composite roles
    client_id,
    source,
    realm_name
FROM
    (
        -- Roles from Groups
        SELECT
            ue.username,
            roles.role_name,
            roles.base_role,
            roles.client_id,
            ue.realm_id,
            'group ' || g.name AS source,
            realm.name AS realm_name
        FROM
            user_entity ue
            JOIN realm ON ue.realm_id = realm.id
            JOIN user_group_membership ugm ON ue.id = ugm.user_id
            JOIN groups g ON g.id = ugm.group_id
            JOIN group_role_mapping grm ON g.parent_group = grm.group_id
            JOIN roles roles ON roles.id = grm.role_id
        UNION
        -- direct role assignments on User
        SELECT
            ue.username,
            roles.role_name,
            roles.base_role,
            roles.client_id,
            ue.realm_id,
            'direct',
           realm.name
        FROM
            user_entity ue
            JOIN realm ON ue.realm_id = realm.id
            JOIN user_role_mapping urm ON ue.id = urm.user_id
            JOIN roles roles ON roles.id = urm.role_id
    ) AS a
WHERE
    realm_name = 'realm_name'
    AND (
        -- username = 'username'
        role_name IN ('roleName')
        -- source = 'group GROUPNAME'
    )
ORDER BY
    username,
    role_name
;

This query works from keycloak 9 to 16.1.1 (the last jboss/keycloak version I got from docker hub).

A: SELECT username,
       kr.NAME,
       kr.REALM_ID
FROM KEYCLOAK_ROLE kr
JOIN USER_ROLE_MAPPING rm ON kr.id = rm.role_id
JOIN USER_ENTITY ue ON rm.user_id = ue.id
ORDER BY USERNAME,
         NAME,
         REALM_ID;


text:
Q: MacBook Pro hard disk failure. How to recover and clean install? I have a MacBook pro, 2009, 13 inch, Original Snow leopard OS.
Recently, I was experiencing that my MacBook some times froze or restarted automatically! I didn't care, and one day it did not start!
When booting, it does not proceed the first gray page, and circle keeps rotating, until after few minutes the circle changes to a NO Entry sign.
I used Opt key while starting the MacBook and booted into Bootcamp. It works fine, I have been using Bootcamp windows for 2-3 weeks now, and just twice I got the Blue Death Screen, out of sudden!
I got the opportunity to back up all my files.
I used Opt-Cmd-P-R combination and reset the NVRAM.
Also I pressed the D key while starting and made a Apple Hardware Test. The result was recognition of the following problem:
4HDD/11/40000004:SATA(0,0)

*

*Can some one please let me know what my problem is?
If my hard disk is busted, how comes it works (almost) problem-less in bootcamp?
Can the problem somehow be solved? For example if it is a bad sector on my hard disk, by isolating that area or so?

*I tried to boot from MacBook DVDs and try to clean install the OS again, but when I restart and press and hold C key, (while the OSX DVD which came by my laptop is inserted), nothing happens! I hear the noise that it tries to read the DVD, and that's it...it just goes on for ages and nothing happens (stuck to gray initial boot page).
How can I have a clean installation of my OSX?

*Does my computer (Snow Leopard, MacBook Pro mid 2009), have a recovery hidden partition? How can I access that?
Your helpful comments are highly appreciated.
Thanks.

A: I'm sorry to tell you that your hard drive is dead (or at least is on the way out), and will need to be replaced. If you're not too confident, you can call Apple Care who should be able to recommend a local shop who can sell you a replacement hard drive and install it for you.
Alternatively, it's quite easy to replace the hard drive yourself. If you google it you'll see there's loads of articles and videos on how to do it (here's a good one to get you started). Apple even has instructions on how to change the hard drive in the macbook pro manual, which is definitely worth a read before you crack it open.

A: @cybergeek654
A common problem with the 13" early generation of the macbook pro.  More than likely this is simply a hard drive CABLE which is a 14$ replacement at an apple store.  Quick easy repair, and can usually be done while you wait.  9 out of 10 repairs for this issue were remedied by replacing the cable, and in turn we were able to save all of the data as the HD was not replaced.  Best of luck.

A: I just replaced the hard drive in my MacBook Pro 13" 2009 and same problem again.
New out of box hard drive. Formatted and cloned. Booted first time great. Second time can't edit anything or trash or open some program's.
Could be a cable problem. As there should not be anything wrong with the new hard drive.


text:
Q: how to compare the list of numbers to a predefined value and output the index of that value I have 2 lists, A= [ 18.0, 25.6, 35.6, 36.6,2.0] and B=[ root, init, top, cpu, mem] both are of length 5.
I want to compare the elements of A are greater than 30.0 or not.
And want to output all the elements which are greater than 30 in A.
Also output the index of those elements along with the entry at same index number in B
I am new to python and hence want to learn how to compare elements of list to a number..
If i am using
For i in A:
       If i > 30
      print A[i]

But its showing me syntax error.
Please help me with the code.

A: for i in range(0, len(A)):
    if A[i] > 30:
        print("Value" + str(A[i]) + " Index " + str(i) + " Table B Value " + str(B[i]) )

A: This can be one lined:
pairs = {key: value for key, value in zip(A,B) if key > 30.0}
print(pairs)

This is called a dict comperhension, you may read more about it on : Python Data Structures

A: enumerate  the ziped lists.
a = [ 18.0, 25.6, 35.6, 36.6,2.0]
b = ["root", "init", "top", "cpu", "mem"]
for i, pair in enumerate(zip(a, b)):
    if pair[0] > 30.0:
        print("i={}, a={}, b={}".format(i, pair[0], pair[1]))

Output:
i=2, a=35.6, b=top
i=3, a=36.6, b=cpu

A: A = [18.0, 25.6, 35.6, 36.6, 2.0]
B = ['root', 'init', 'top', 'cpu', 'mem']
zipped = zip(A, B)

i = 0
for k, v in zipped:
    if k > 30.0:
         print("index: {}, valueFromA: {}, valueFromB: {}".format(i, k, v))
    i += 1

Output:
index: 2, valueFromA: 35.6, valueFromB: top
index: 3, valueFromA: 36.6, valueFromB: cpu


text:
Q: What are PIP alternative in arachne-pnr? While going through the router.cc the file of arcahne-pnr, I am unable to understand, how are the programmable interconnect pins PIPs routed? Does it seem PLL is representing the PIPs in the code? Could somebody help to make me clear, what corresponds to PIP in arachne-pnr?
Thanks

A: They are called switches in the chip database, although I think the router expands this to its own structure.
Certainly nothing to do with PLL (phased locked loops) which are a clocking primitive.


text:
Q: How to create a file with text, date, and file content in command line I'm looking to create an alais in IOS Terminal that will create a file with a comment at the top of the file and append another file to the end
Output I would like
\#2Thu Dec  3 14:39:41 MST 2015
--fileContents--

Attempt
echo # > x.txt; date >> x.txt; cat file.txt >>> x.txt;

But the results put the # and the date on separate lines... How would I do it with keeping them on the same line

A: I've found that adding ` around date inside of an echo executes the statement.
Resolution
echo # `date` > x.txt; cat file.txt >> x.txt;


text:
Q: Run external program in parent Window without system() How can I run an external Program within the parent Window without using system()?
Current Operating System: Windows 10
I tried using
ShellExecute(NULL, "open", target.c_str(), NULL, NULL, SW_SHOW);

But it will run it in a new window instead of the parent Window.
(Target program is a Console Program. If Program has a GUI, open new window Instead)
What exactly I want:
system("C:/Users/ELEMENT/source/repos/apath/aprogram.exe arg1 arg2");

But without using system();
I don't want to use system(); is because I want to learn if there's any other way to do it.
Please help!

A: I suggest you to use CreateProcess function:

Creates a new process and its primary thread. The new process runs in
the security context of the calling process.

You can set the dwCreationFlags to CREATE_NO_WINDOW to prevent the process to create a new window.
#include <windows.h>
#include <stdio.h>
#include <tchar.h>

void _tmain(int argc, TCHAR* argv[])
{
    STARTUPINFOA si;
    PROCESS_INFORMATION pi;

    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    ZeroMemory(&pi, sizeof(pi));

    const LPCSTR program_path = "C:/Users/ELEMENT/source/repos/apath/aprogram.exe";
    const LPCSTR cmdline = " arg1 arg2";

    // Start the child process.
    if (!CreateProcessA(program_path,   // No module name (use command line)
        const_cast<char*>(cmdline),        // Command line
        NULL,           // Process handle not inheritable
        NULL,           // Thread handle not inheritable
        FALSE,          // Set handle inheritance to FALSE
        CREATE_NO_WINDOW,              // The process is a console application that is being run without a console window.
        NULL,           // Use parent's environment block
        NULL,           // Use parent's starting directory
        &si,            // Pointer to STARTUPINFO structure
        &pi)           // Pointer to PROCESS_INFORMATION structure
        )
    {
        printf("CreateProcess failed (%d).\n", GetLastError());
        return;
    }

    // Wait until child process exits.
    WaitForSingleObject(pi.hProcess, INFINITE);

    // Close process and thread handles.
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);
}


text:
Q: My IIS redirect rule is not working via web.config I have a redirect rule that I am trying to create using web.config. I am trying to redirect
from the below page:
https://example.org/content/content.php?PrintMe=0&PgName=gothedistance
to this page:
https://example.org/gothedistance
My url redirect rule looks like the below:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Redirect" stopProcessing="true">
                <match url="content.php$" />
                <conditions>
                <add input="{QUERY_STRING}" pattern="PrintMe=0&PgName=gothedistance" />
            </conditions>
            <action type="Redirect" url="gothedistance" redirectType="Permanent" appendQueryString="false" />
            </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>


text:
Q: How to Deploy an Image with the Application in Google App Engine Using Python Whenever I deploy my application, it deploys correctly except the backgroud image I used in main.css does not appear. If I change it to a background color, it works but background image does not work for whatever reason. When I test run by using Browse, it works but once I change the Application name in app.yaml, the Browse does not work but the Deployment works but it doesn't show the background image. How can I get the back ground image to show?
Code in main.CSS:
body {
  font-family: Comic Sans, Helvetica, sans-serif;
  background-image: url(../stylesheets/goku-wallpaper-2.jpg);
  background-repeat:repeat-x;
}

Code in app.yaml:
application: guestbooksky
version: 1
runtime: python27
api_version: 1
threadsafe: true

handlers:
- url: /stylesheets
  static_dir: stylesheets

- url: /.*
  script: helloworld.app

libraries:
- name: jinja2
  version: latest

A: probably:
background-image: url(/stylesheets/goku-wallpaper-2.jpg);

if the image file is in the path of:
/stylesheets/


text:
Q: problem parsing with XMLReader (using ReadSubTree) Im trying to build a simple XML to Controls parser in my CF application.
In the code below the string im trying to parse looks like this:
"<Panel>Text1Text2</Panel>"

The result i want with this code would be a Panel with two labels.
But the problem is when the first Label is parsed the subreader.Read() returns false in the ParsePanelElementh method, and so it falls out of while statement.
Since im new into XMLReader i must be missing something very simple.
Any help would be apreciated !
peace.
static class XMLParser
{
    public static Control Parse(string aXmlString)
    {
        XmlReader reader = XmlReader.Create(new StringReader(aXmlString));
        return ParseXML(reader);
    }

    public static Control ParseXML(XmlReader reader)
    {
        using (reader)
        {
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    if (reader.LocalName == "Panel")
                    {
                        return ParsePanelElement(reader);
                    }

                    if (reader.LocalName == "Label")
                    {
                        return ParseLabelElement(reader);
                    }
                }
            }
        }
        return null;
    }

    private static Control ParsePanelElement(XmlReader reader)
    {
        var myPanel = new Panel();
        XmlReader subReader = reader.ReadSubtree();
        while (subReader.Read())
        {
            Control subControl = ParseXML(subReader);
            if (subControl != null)
            {
                myPanel.Controls.Add(subControl);
            };
        }
        return myPanel;
    }

    private static Control ParseLabelElement(XmlReader reader)
    {
        reader.Read();
        var myString = reader.Value as string;
        var myLabel = new Label();
        myLabel.Text = myString;
        return myLabel;
    }
}

A: The problem is that the reader reads twice, once in ParsePanelElement and once in ParseXML. This way you parse the panel, skip the first label and eventually add the second label.
[EDIT May 3rd 2010]
This code works under Visual Studio 9. (I have moved the using clause)
   static class Program
   {
      ///
      /// The main entry point for the application.
      ///
      [STAThread]
      static void Main()
      {
         Control Test = XMLParser.Parse("<Panel>Text1Text2</Panel>");
         for (Int32 i = 0; i < Test.Controls.Count; i++)
         {
            System.Diagnostics.Debug.WriteLine("Control " + i + ": " + Test.Controls[i].GetType().FullName + " [TEXT = " + Test.Controls[i].Text + "]");
         }
      }

      static class XMLParser
      {
         public static Control Parse(string aXmlString)
         {
            Control result = null;
            using (StringReader strReader = new StringReader(aXmlString))
            {
               using (XmlReader reader = XmlReader.Create(strReader))
               {
                  result = ParseXML(reader);
               }
            }
            return result;
         }

         public static Control ParseXML(XmlReader reader)
         {
            while (reader.Read())
            {
               if (reader.NodeType == XmlNodeType.Element)
               {
                  if (reader.LocalName == "Panel")
                  {
                     return ParsePanelElement(reader);
                  }

                  if (reader.LocalName == "Label")
                  {
                     return ParseLabelElement(reader);
                  }
               }
            }
            return null;
         }

         private static Control ParsePanelElement(XmlReader reader)
         {
            var myPanel = new Panel();
            using (XmlReader subReader = reader.ReadSubtree())
            {
               while (subReader.Read())
               {
                  Control subControl = ParseXML(subReader);
                  if (subControl != null)
                  {
                     myPanel.Controls.Add(subControl);
                  };
               }
            }
            return myPanel;
         }

         private static Control ParseLabelElement(XmlReader reader)
         {
            reader.Read();
            var myString = reader.Value as string;
            var myLabel = new Label();
            myLabel.Text = myString;
            return myLabel;
         }
      }
   }


text:
Q: Detect redirection within iframe I need to detect when my iframe did not get served the content it requested but instead got redirected to the login page.
Does the iframe even handle the redirection or is this done by the browser?
What led me to believe so: the load event only gets fired once + even afterwards it's src property is still set to the original URL.

A: Assuming same origin you have these two ways given this test:
function isFramed() {try {return window.self !== window.top;} catch (e) {return true;};

This
if (isFramed) window.open(location.href,"_top");

or
if (isFramed) parent.doSomethingWhenLoginIsFramed();

Alternatively look at postMessage


text:
Q: Mysterious incompatibility between tally marks and IPA package For a series of lecture notes, I am using a code found in a different trend to make automatic tally marks. The code works fine as long as the package tipa is not loaded. Like in the example below
\documentclass{article}

\usepackage[utf8]{inputenc}
\usepackage[misc]{ifsym}
\usepackage{amsmath,amssymb}

\newcounter{TallyCount}

\newcommand{\tally}[1]{%
  \setcounter{TallyCount}{#1}%
  \loop\ifnum\theTallyCount>4\relax
  \StrokeFive\:\addtocounter{TallyCount}{-5}%
  \repeat
  \ifcase\theTallyCount\or\StrokeOne\or\StrokeTwo
         \or\StrokeThree\or\StrokeFour
         \else{Error}\fi\unskip}

%\usepackage{tipa}

\begin{document}

\tally{23}

\end{document}

However, as soon as I uncomment the package tipa, it gives me this error:
./Untitled.tex:22: Argument of \addtocounter has an extra }.
<inserted text>
                  \par l.22 \tally{23}

 ?

I need to use the tipa package, for I write the pronunciation of some technical words. Is there any chance this can be fixed somehow?

A: tipa apparently redefines \: for its own purposes, you could use \> or \medspace (which are the same thing)


text:
Q: Throwing exceptions in application configuration providers Simple question: What is the best/common practice regarding to throwing errors for application configuration providers?
Given is a simple key/value-based configuration source:
class Configuration
    string GetValue(key);
    void SetValue(key, value);

Or more extended, with the ability to add/remove key/value elements
class Configuration
    string GetValue(key);
    void SetValue(key, value);
    void AddKeyValuePair(string key, string value);
    void RemoveKeyValuePair(string key);

Not throwing exceptions on methods like GetValue() has the benefit of not interrupting the application flow and making code easier to read because of a lack of exception handling etc. It also allows to use null-conditional operators (maybe monads) or null-coalescing operators for e.g. setting defaults:
var value = configuration.GetValue("myKey") ?? "Hello World";

Return null simply tells the user: 'Whoops, got nothing to return since nothing is set/there'.
However..
If I'd avoid throwing exceptions, what would happen if I try to add a key/value pair which is already available? Or set the value with a key that isn't there in the underlying storage? Or removing a key/value pair that isn't available? Would it be obvious for the user that simply nothing happens when we tries to remove a none-existing key pair?
What is the prefered approach for application configuration?

A: It sounds like you are on the verge of Railway Oriented Programming.
As with most things there is no Right Way To Do It, only trade-offs. Exceptions are costly when thrown, but they are fairly standard practice in C#. Conversely, returning a pass/fail means you have to check the return value (if you care about it failing).
Using Exceptions, they will have to wrap calls to your code in try/catch blocks (which I never find fun). If you were going to avoid using exceptions for expected failures (key not found), I would change the API to make the return value explicit as to whether or not the configuration was changed. And make the methods clear as to expected preconditions (key present or not). That way, the caller can pick a method which allows them to ignore the return value. Or else they can explicitly handle the case where their requested change could not be performed.
Here is an example class with more explicit methods and return values.
class Configuration
    string GetValue(string key); // presence expected, null means not there
    bool ChangeExistingValue(string key, string value); // only change if present
    bool AddNewKeyValuePair(string key, string value); // add only if not present
    void AddOrUpdateValue(string key, string value); // obvious use
    bool RemoveKeyValuePair(string key); // obviously presence is expected

When called, I can choose the method I need (C#):
// don't want to add the value if it's not already there
// return value of false is ignored
config.ChangeExistingValue("asdf", "fdsa");

// -- vs --

// there is a problem if this value is not there
if (!config.ChangeExistingValue("asdf", "fdsa"))
    throw new SomeException(...);

// -- vs --

// I don't care about before, just put it in there now
config.AddOrUpdateValue("asdf", "fdsa");

A: First and foremost: What is a configuration for?
A configuration allows the user to change the behaviour of our application to influence the behavior of your application in some way or the other. Your application behaves in a certain, sane way but the user wants to customize the behaviour.
That said the perspective for your answers is the following:

If I'd avoid throwing exceptions, what would happen if I try to add a key/value pair which is already available?

Your application has a sane default behaviour. If the user decides to overwrite it, this is okay. If the user changes his mind, he should be able to do so without hassle as long as your application is in a sane state.

Or set the value with a key that isn't there in the underlying storage?

If your configutation should only accept certain values, and you should let your users know that.

Or removing a key/value pair that isn't available?

The purose of this action is, that you do not want a customized behaviour and instead want to rely on the defaults. You should handle this case gracefully and accept it in case of you would allow the set-operation in other cases let your user know that this configuration value isn't allowed.

Would it be obvious for the user that simply nothing happens when we tries to remove a none-existing key pair?

No. But would he care?
In case the user wants to get a value, which isn't explicitely set, return the (sane) default.
Regarding exceptions:
Exceptions are just that: exceptional behavior in case you could not handle the situation. Think of a Samurai - accomplish your mission or die trying.
Setting not allowed options is exceptional so it would be okay to throw an exception.


text:
Q: why so many "duplicated" (i386 + x86_64) packages installed? I did a fresh install of a 64bit laptop (where previously i had ubuntu 10.04 64bit) I now notice that everytime i install a package from the reppos, i get lots of duplicate libs both in 32bit and 64bit, why?
I only have the official ubuntu reppos and installed OpenShot video editor and Flash and a few other things like CompizConfig Settings Manager and Gnome Tweak Tool...
I now magically have 122 duplicated libs in 2 different architectures, why?
dpkg -l|grep ":i386"|wc -l
If i inspect this list i find both 64bit and 32bit in my system... This is really a waste of space and then which one is used by the apps? 32 or 64?
It is really confusing...

A: I would say those are dependencies for some 32bit tools you are using. Its not a waste of space because they are needed, not everything will work with 64bit so those packages are need to make sure all runs smoothly.

A: Because flashplugin-installer:amd64 depends flashplugin-downloader:i386. And for working multiarch needs more i386 packages.
Just remove flashplugin-installer, flashplugin-downloader:i386 and other i386 packages and install adobe-flashplugin:amd64.
But if you want install skype there is only i386 package in Ubuntu 11.10 Oneiric Ocelot now. And it depends many i386 packages.


text:
Q: Are there any problems with this symlink traversal code for Windows? In my efforts to resolve Python issue 1578269, I've been working on trying to resolve the target of a symlink in a robust way. I started by using GetFinalPathNameByHandle as recommended here on stackoverflow and by Microsoft, but it turns out that technique fails when the target is in use (such as with pagefile.sys).
So, I've written a new routine to accomplish this using CreateFile and DeviceIoControl (as it appears this is what Explorer does). The relevant code from jaraco.windows.filesystem is included below.
The question is, is there a better technique for reliably resolving symlinks in Windows? Can you identify any issues with this implementation?
 def relpath(path, start=os.path.curdir):
  """
  Like os.path.relpath, but actually honors the start path
  if supplied. See http://bugs.python.org/issue7195
  """
  return os.path.normpath(os.path.join(start, path))

 def trace_symlink_target(link):
  """
  Given a file that is known to be a symlink, trace it to its ultimate
  target.

  Raises TargetNotPresent when the target cannot be determined.
  Raises ValueError when the specified link is not a symlink.
  """

  if not is_symlink(link):
   raise ValueError("link must point to a symlink on the system")
  while is_symlink(link):
   orig = os.path.dirname(link)
   link = _trace_symlink_immediate_target(link)
   link = relpath(link, orig)
  return link

 def _trace_symlink_immediate_target(link):
  handle = CreateFile(
   link,
   0,
   FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
   None,
   OPEN_EXISTING,
   FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS,
   None,
   )

  res = DeviceIoControl(handle, FSCTL_GET_REPARSE_POINT, None, 10240)

  bytes = create_string_buffer(res)
  p_rdb = cast(bytes, POINTER(REPARSE_DATA_BUFFER))
  rdb = p_rdb.contents
  if not rdb.tag == IO_REPARSE_TAG_SYMLINK:
   raise RuntimeError("Expected IO_REPARSE_TAG_SYMLINK, but got %d" % rdb.tag)
  return rdb.get_print_name()

A: Unfortunately I can't test with Vista until next week, but GetFinalPathNameByHandle should work, even for files in use - what's the problem you noticed?
In your code above, you forget to close the file handle.


text:
Q: Excluding 0s from a contingency table made from subset data in R I'm new to stack overflow so please let me know if you need more information.
I'm was workking with a dataset which contained two options for the variable "colour" and then two each for "shade". I subsetted the data thus:
blue <- subset(data1, colour=="B")

which seemed to work and only colour "B" and shade "sky" and "navy" remained when I typed in "blue"
I then wanted to create a contingency table from this subset which I did thus:
table1 <-table(blue$shade, blue$Response)

where response is a Y/N.
However at this point I ran into problems as the red shades reappeared with 0s in my contingency table
               Y    N
Sky            35   8
Navy           36   12
Scarlet        0    0
Maroon         0    0

Can anyone advise on how to remove these 0 values aside from "fix"ing the table and manually deleting the relevant parts?
Many thanks

A: We can use droplevels to remove the unused levels
blue <- droplevels(blue)

and then do the table
table(blue$shade, blue$Response)


text:
Q: Singularity of a matrix times its transpose If $A$ is a $k \times n$ matrix of rank $k$, where A can be broken down into $UDV^T$ as per singular value decomposition, why is $AA^T$ non-singular?

A: $D$ is a $k \times n$ diagonal matrix where each row is non-zero. Its $(i,i)$-th entry, $d_i$ is positive.
$DD^T$ is a $k \times k$ matrix where each row is non-zero, its $(i,i)$-th entry, $d_i^2$ is positive. and hence it is nonsingular.
$$AA^T=UDV^TVD^TU^T=UDD^TU^T$$
Since $U$ is nonsingular, $DD^T$ and $U^T$ are nonsingular, $AA^T$ is nonsingular.

A: Since you are using transpose ($T$) rather than Hermitian conjugate, we're working over the reals.
Since $A$ has full row rank, it is surjective.
$\text{Ker}(A^T) = (\text{Ran}(A))^\perp = \{0\}$.
For any nonzero vector $x \in \mathbb R^k$, $x^T A A^T x = \|A^T x\|^2 > 0$,
so $A A^T x \ne 0$. Thus $\text{ker}(A A^T) = \{0\}$, so $A A^T$ is nonsingular.


text:
Q: Print (or output to file) table of number of steps for Euclid's algorithm I'd like to print (or send to a file in a human-readable format like below) arbitrary size square tables where each table cell contains the number of steps required to solve Euclid's algorithm for the two integers in the row/column headings like this (table written by hand, but I think the numbers are all correct):
  1  2  3  4  5  6
1 1  1  1  1  1  1
2 1  1  2  1  2  1
3 1  2  1  2  3  1
4 1  1  2  1  2  2
5 1  2  3  2  1  2
6 1  1  1  2  2  1

The script would ideally allow me to choose the start integer (1 as above or 11 as below or something else arbitrary) and end integer (6 as above or 16 as below or something else arbitrary and larger than the start integer), so that I could do this too:
   11 12 13 14 15 16
11  1  2  3  4  4  3
12  2  1  2  2  2  2
13  3  2  1  2  3  3
14  4  2  2  1  2  2
15  4  2  3  2  1  2
16  3  2  3  2  2  1

I realize that the table is symmetric about the diagonal and so only half of the table contains unique information, and that the diagonal itself is always a 1-step algorithm.
See this and for a graphical representation of what I'm after, but I'd like to know the actual number of steps for any two integers which the image doesn't show me.
I have the algorithms (there's probably better implementations, but I think these work):
The step counter:
def gcd(a,b):
    """Step counter."""
    if b > a:
        x = a
        a = b
        b = x
    counter = 0
    while b:
        c = a % b
        a = b
        b = c
        counter += 1
    return counter

The list builder:
def gcd_steps(n):
    """List builder."""
    print("Table of size", n - 1, "x", n - 1)
    list_of_steps = []
    for i in range(1, n):
        for j in range(1, n):
            list_of_steps.append(gcd(i,j))
    print(list_of_steps)
    return list_of_steps

but I'm totally hung up on how to write the table. I thought about a double nested for loop with i and j and stuff, but I'm new to Python and haven't a clue about the best way (or any way) to go about writing the table. I don't need special formatting like something to offset the row/column heads from the table cells as I can do that by eye, but just getting everything to line up so that I can read it easily is proving too difficult for me at my current skill level, I'm afraid. I'm thinking that it probably makes sense to print/output within the two nested for loops as I'm calculating the numbers I need which is why the list builder has some print statements as well as returning the list, but I don't know how to work the print magic to do what I'm after.

A: Try this. The programs computes data row by row and prints each row when it's available,
in order to limit memory usage.
import sys, os

def gcd(a,b):
   k = 0
   if b > a:
      a, b = b, a
   while b > 0:
      a, b = b, a%b
      k += 1
   return k

def printgcd(name, a, b):
   f = open(name, "wt")
   s = ""
   for i in range(a, b + 1):
      s = "{}\t{}".format(s, i)
   f.write("{}\n".format(s))
   for i in range(a, b + 1):
      s = "{}".format(i)
      for j in range (a, b + 1):
         s = "{}\t{}".format(s, gcd(i, j))
      f.write("{}\n".format(s))
   f.close()

printgcd("gcd-1-6.txt", 1, 6)

The preceding won't return a list with all computed values, since they are destroyed on purpose. It's easy to do however. Here is a solution with a hash table
def printgcd2(name, a, b):
   f = open(name, "wt")
   s = ""
   h = { }
   for i in range(a, b + 1):
      s = "{}\t{}".format(s, i)
   f.write("{}\n".format(s))
   for i in range(a, b + 1):
      s = "{}".format(i)
      for j in range (a, b + 1):
         k = gcd(i, j)
         s = "{}\t{}".format(s, k)
         h[i, j] = k
      f.write("{}\n".format(s))
   f.close()
   return h

And here is another with a list of lists
def printgcd3(name, a, b):
   f = open(name, "wt")
   s = ""
   u = [ ]
   for i in range(a, b + 1):
      s = "{}\t{}".format(s, i)
   f.write("{}\n".format(s))
   for i in range(a, b + 1):
      v = [ ]
      s = "{}".format(i)
      for j in range (a, b + 1):
         k = gcd(i, j)
         s = "{}\t{}".format(s, k)
         v.append(k)
      f.write("{}\n".format(s))
      u.append(v)
   f.close()
   return u


text:
Q: Bash: capture ping's intermediary statistics on SIGQUIT to variable I have this:
 ping -q xxx.xxx.xxx.xxx & disown; pingpid=$!
 for run in {1..3}; do
 sleep 5
 stats+=$(kill -SIGQUIT $pingpid)
 done
 kill $pingpid

So basically I launch ping in background with -q option (to show just stats), get its PID and then execute a for loop in which I want to store the intermediary stats of ping on each kill -SIGQUIT $pingpid in a variable... that's 3 lines of stats, 5 seconds apart.
I can see the intermediary stats being printed to stdout but when I check the $stats variable, I find it empty. I also tried with stderr redirection to stdout but I still can't get the variable to have the stats stored in it.

A: The output that you're trying to capture is coming from the ping process (on it's standard error to be precise), not the kill process. You need to capture its output with a redirection when you launch it. Try this:
stats=""
{
        read pingpid
        for run in {1..3}; do
                sleep 5
                kill -quit $pingpid
                read line
                stats+="$line"$'\n'
        done
} < <(ping -q xx.xx.xx.xx 2>&1 >/dev/null & echo $!)

kill $pingpid
stats=${stats%$'\n'}  # Remove the extra newline
echo "$stats"

The ordering of the redirection in the ping command, 2>&1 >/dev/null, redirects standard out to /dev/null while standard error is redirected to the input of the loop.

A: What are you actually trying to accomplish here?  It seems like you should actually be running ping with a timeout, or a limited number of packets (amounts to the same thing in the end).
for run in 1 2 3; do
    ping -c 5 -q 12.34.56.78 | tail -n 2
done

The regular output from ping is somewhat more verbose than the single line you get when you send it a SIGQUIT, so we need two lines of output.  Perhaps you want to pipe to some simple Awk script to normalize the output to make it fit your needs, or perhaps transform it to a properly machine-readable format.


text:
Q: how to implement Cron jobs(shedulded tasks) for a servlet in Appengine Application I start developing Google Appengine Java Application..for that I am using Servlet, jsp and EClipse helios IDE.
In my Application, I want to create a servlet, that will execute for Particular time interval(every 5 minutes) and the the get values are stored in datastore.....
How to do this...Also i go through about Scheduling tasks here.But I didn't understand how to implement in my project using Eclipse....
Please help me.....

A: You just need to create a servlet that will handle requests to the URL you specify in your cron config.  Your cron.xml gets saved in the same location as your appengine-web.xml.

A: cron job in AppEngine uses http GET, so just any servlet that handles doGet() will suffice.
suppose your servlet is mapped to /mytask in web.xml, then in cron.xml,
<cron>
    <url>/mytask</url>
    <description>describe your task here</description>
    <schedule>every 1 minutes</schedule>
</cron>

this instructs appengine to issue a httpGet at URL /mytask every minute.


text:
Q: Memory optimization: declare multiple string variables VS use in place I have to code a class with heavy memory allocation considerations.
This class have strings all over the place like so
var data = GetPropertyValue<GSData>(response.BaseData, "scriptData");

Just like "scriptData" there are over 10 strings declared "in place"
Another programmer made some public const string for a few of these strings that where needed outside the class.
I was wondering if I should create private const string for the rest of the "in place" strings that are repeated in multiple times in the class.
My questions are:

*

*What the difference in memory consumption will be?

*What about reserving memory using const against using "in place"?

I need to understand what the compiler does when there are strings like "textA" defined in several places in a class (over multiple methods), what happens in memory when the program run, and so on.
Thanks!


text:
Q: How to open a spec runner in a browser In this tutorial it says:
"Opening the spec runner in a web browser will give the expected outcome:"

But does not mention how to do it. How can I do it?
Example code:
var My = {
  sqrt: function(x) {
    if (x < ) throw new Error("sqrt can't work on negative number");
      return Math.exp(Math.log(x)/2);
  }
};

Test code:
describe("sqrt", function() {
  it("should compute the square root of 4 as 2", function() {
    expect(My.sqrt(4)).toEqual(2);
  });
});

A: There should be a SpecRunner.html file that references jasmine, your code, and your spec files. Looks something like this:
<!DOCTYPE HTML>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>Jasmine Spec Runner v2.0.2</title>

  <link rel="shortcut icon" type="image/png" href="libs/jasmine-2.0.2/jasmine_favicon.png">
  <link rel="stylesheet" type="text/css" href="libs/jasmine-2.0.2/jasmine.css">

  <script type="text/javascript" src="libs/jasmine-2.0.2/jasmine.js"></script>
  <script type="text/javascript" src="libs/jasmine-2.0.2/jasmine-html.js"></script>
  <script type="text/javascript" src="libs/jasmine-2.0.2/boot.js"></script>

  <script type="text/javascript" src="libs/jquery-1.11.1.min.js"></script>
  <script type="text/javascript" src="libs/jasmine-jquery.js"></script>

  <!-- include source files here... -->
  <script type="text/javascript" src=""></script>

  <!-- include spec files here... -->
  <script type="text/javascript" src=""></script>

</head>

<body>
</body>
</html>


text:
Q: Java bufferedimage not loading I have this image that I want to load but it always gives me an input= null exception.
This is the first bit of code:
Entity e = new Entity("images/meganium.png");

Here is the part that loads the image:
image = null;
    try{
        path = this.getClass().getResource(fileName);
        System.out.println(path);
        image = ImageIO.read(path);
    }catch(IOException e){
        System.out.println("Dun goofed in " + "SPrites");
    }

The structure is like this:
com/blah/bleh/Main
com/blah/bleh/images
com/blah/bleh/foo/bar/Loader Class

Stack trace:
java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(ImageIO.java:1362)
at net.ofn.nyc.javagentleman.src.graphic.Sprite.<init>(Sprite.java:31)
at net.ofn.nyc.javagentleman.src.ent.Entity.<init>(Entity.java:21)
at net.ofn.nyc.javagentleman.JavaGentleman.<init>(JavaGentleman.java:27null)
at net.ofn.nyc.javagentleman.JavaGentleman.main(JavaGentleman.java:23)

A: Do you have 2 separate directories, one named images the other named Images (capital 'I')?  Keep it consistent.  Your file system may not distinguish between the two, but Java does.

A: You're using a relative path for the image resource. With Class.getResource(), relative paths are resolved against the package containing the class, so if the class loading the images is in package com.blah.bleh.foo.bar, then it will be looking for the image at /com/blah/bleh/foo/bar/images/meganium.png. getResource() returns null if it can't find the given resource and hence your IllegalArgumentException.


text:
Q: Primary Identity Column of table gets random value in sql server 2012 CREATE TABLE [dbo].[tbl_Person](
[PersonID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NULL,
[Address] [varchar](50) NULL,
[Phone] [varchar](50) NULL,
 CONSTRAINT [PK_tbl_Person] PRIMARY KEY CLUSTERED
(
    [PersonID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
    ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

) ON [PRIMARY]

In this table when inserting value from application using stored procedure with query
INSERT INTO [dbo].[tbl_PersonName]
       ([Name])
 VALUES
       ('name')

the 'PersonID' column got unusual value. The value jumps randomly like, from 1896 to 11896 and again jumps from 11905 to 21905. i worry if such jumps occurs the range could be insufficient and the data seems quite unorganized. I wonder if those unused value would be reused or not? After inserting some data what should i do to re managed the sequence? i am worried with the issue, this didn't happen in 2010 though i used the same pattern of code as in 2012. help me!

A: That is because you are trying to insert a new column to your primary key column.
If you have a table lets say with 1000 rows and you delete the record at 797 position. Then when you will insert a new row to your table then the value will be inserted at 1001 position not at 797.

I wonder if those unused value would be reused or not?

No the values will not be reused. As whenever you delete a column from the table and then try to insert the value again in the table then the value will be inserted to a new position.
EDIT:-
Also you may find this helpful.
Microsoft added sequences in SQL Server 2012

By default when you create a SEQUENCE you can either supply CACHE
  size. Caching is used to increase performance for applications that
  use sequence objects by minimizing the number of disk IOs that are
  required to generate sequence numbers.

To fix this issue, you need to make sure, you add a NO CACHE option in sequence creation / properties like this.
CREATE SEQUENCE TEST_Sequence
    AS INT
    START WITH 1
    INCREMENT BY 1
    MINVALUE 0
    NO MAXVALUE
   NO CACHE

However if you want the same old behavior then you may use trace flag 272
Since the trace flag 272 option worked for OP. Here are the steps to add trace flag 272:-

*

*Open "SQL Server Configuration Manager"

*Click "SQL Server Services" on the left pane

*Right-click on your SQL Server instance name on the right pane

*Click "Properties"

*Click "Startup Parameters"

*On the "specify a startup parameter" textbox type "-T272"

*Click "Add"

*Confirm the changes


text:
Q: Getting CORS error in Http request using ionic4 Getting error in API calling

ERROR => Access to XMLHttpRequest at 'localhost:3003/graphql' from origin 'http://localhost:8101' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

apollo: Apollo,
    httpLink: HttpLink
  ) {
    apollo.create({
      link: httpLink.create({ uri: 'localhost:3003/graphql}),
      cache: new InMemoryCache()
    });

CORS-enabled for all origins (Node Api)

A: As error refers only supported for protocol schemes: http.... which certainly means you've just forgotten to put the https or http on the request in your code
So please note localhost:3003/graphql must change to either http://localhost:3003/graphql or https://localhost:3003/graphql
apollo: Apollo,
    httpLink: HttpLink
  ) {
    apollo.create({
      link: httpLink.create({ uri: 'http://localhost:3003/graphql'}),
      cache: new InMemoryCache()
    });


text:
Q: how to access package in public folder from node_modules folder in nodejs? i have MEAN stack application.
In public folder i have AngularJs application.
Structure

Here in index.html i am trying to access a package, which is present in node_modules.
Can any please tell me how to access this?

A: As @31Py said, you can reference using ../node_modules/path/to/the/package
OR
It's always better to create separate dependencies in package.json file for public folder(front end code).
This helps you to organize both the code separate, while bundling front end, running task runners(grunt, gulp) and you would know which packages are for front end.
In index.html referencing the node modules will be /node_modules/path/to/the/package
Some reference Links with comments in the section.

*

*Separating Frontend & Backend Dependencies with Gulp/Yarn

*Separating package.json for frontend and backend with shared code


text:
Q: Insert statement crashes because of trigger The error I get is this "The INSERT statement conflicted with the FOREIGN KEY constraint "FK_vacation_users". The conflict occurred in database "TestAtt", table "dbo.users", column 'userID'."
I'm trying to insert into users with this:
INSERT into users (firstName, lastName, userName, password, team, fingerID, type, isActive) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}')",
firstNameAddBox.Text, lastNameAddBox.Text, userNameAddBox.Text, passwordAddBox.Text,
teamAddUserCombo.Text, fingerIdAddBox.Text, userTypeAddCombo.SelectedValue, isActiveCheck.Checked);

My users table looks like this:
CREATE TABLE
    users
    (
        userID INT NOT NULL IDENTITY,
        userName NVARCHAR(50) COLLATE Romanian_CI_AS NOT NULL,
        password NVARCHAR(100) COLLATE Romanian_CI_AS NOT NULL,
        firstName NVARCHAR(50) COLLATE Romanian_CI_AS NOT NULL,
        lastName NVARCHAR(50) COLLATE Romanian_CI_AS NOT NULL,
        team TINYINT NOT NULL,
        type TINYINT NOT NULL,
        fingerID SMALLINT NOT NULL,
        isActive BIT DEFAULT 1 NOT NULL,
        CONSTRAINT PK_users PRIMARY KEY (userID),
        CONSTRAINT FK_users_userType FOREIGN KEY (type) REFERENCES userType (typeID),
        CONSTRAINT users_idx UNIQUE (fingerID)
    );

The vacation table looks like this:
CREATE TABLE
    vacation
    (
        ID INT NOT NULL IDENTITY,
        userID INT NOT NULL,
        vacation TINYINT DEFAULT 0 NOT NULL,
        extraDays TINYINT DEFAULT 0 NOT NULL,
        PRIMARY KEY (ID),
        CONSTRAINT FK_vacation_users FOREIGN KEY (ID) REFERENCES users (userID)
    );

And this is the trigger:
ALTER TRIGGER "dbo"."newUserTrigger"
  on "dbo"."users"
  AFTER INSERT
  as
begin
DECLARE @newUserID int
SELECT @newUserID = (SELECT userID FROM Inserted)
INSERT INTO vacation (userID) VALUES (@newUserID)
end;

So if I disable the trigger the insert works but with the trigger on it seems it wont insert the userID in the vacation table also.

A: I think your foreign key is incorrect, the column that's referencing users is userID, not ID:
 CONSTRAINT FK_vacation_users FOREIGN KEY (userID) REFERENCES users (userID)

But your trigger is also broken because inserted can contain multiple (or no) rows. So it should be:
ALTER TRIGGER "dbo"."newUserTrigger"
  on "dbo"."users"
  AFTER INSERT
  as
begin
INSERT INTO vacation (userID) SELECT userID from Inserted
end;

A: Here's the problem:
CONSTRAINT FK_vacation_users FOREIGN KEY (ID) REFERENCES users (userID)

This is saying that the ID column in vacation must have a matching value in userId in users. I think (ID) should be (userID). It should work OK then.

A: CONSTRAINT FK_vacation_users FOREIGN KEY (ID) REFERENCES users (userID)

should be
CONSTRAINT FK_vacation_users FOREIGN KEY (userID) REFERENCES users (ID)


text:
Q: Angular how to build the requestBody in http calls? Imagine i have multiple input fields:

projectName, customerName, employeeName

The user can fetch data from an API depending on which values he input on this fields.
If he enters some values, the RequestBody will maybe look like this:
{
    "projectName": "Opel Travel",
    "customerName": "",
    "employeeName": "",
}

How should i build the requestBody when the user types nothing into the fields, to get all data without filtering for values?
variant1:
{
    "projectName": "",
    "customerName": "",
    "employeeName": "",
}

The API dont return any data, so i guess this approach is wrong.
variant2:
{

}

with this approach i get all data.
What is best practice to build the request body? The Goal is, to get all data if user inputs nothing otherwise filter for his inputs.

A: Well, it also depends upon how you handled null cases while inserting the data.  And filtering through parameters has nothing much to do on the front-end side.
If any parameter (input field) is "" in the request, you should manage to convert the empty string to null or 0 depending on how you sent the data while inserting into the databases.
Let suppose you sent this object to save in the databases
{
    "projectName": "Opel Travel",
    "customerName": "",
    "employeeName": "",
}

"customerName" and "employeeName" should be saved as null as they contain no value.


text:
Q: Should the web.xml file be under version control? In the past, I've only developed Java applications.  This is my first time attempting an actual web app on my own, so pardon the painfully rookie question.
Should I add the WEB-INF/web.xml file to version control?  It appears to be a generated file, so my instinct is to add it to the ignore list, but I thought I'd ask and make sure.
Thanks!

A: Your IDE has probably generated a sample web.xml file, which you will edit as your application expands. If this is the case, then it is definitely something you want to keep in source control.
As has been said in other answers, if you are actually using some web.xml generating tool, then keep that tool's configuration in source control, and fire the tool up during your build process.

A: On a more general point, anything that is considered "source" should be kept in source control. This includes:

*

*Code (excluding generated code)

*Configuration files (excluding generated config)

*Run scripts

*Database schema definitions and objects (stored procedures, triggers, etc)

*IDE configurations for compiler settings, formatting, etc

*Scheduling definition files

*Environment source files

If it's required for your application to work, and you don't generate it as part of your build process, put it in source control.

A: Generally, web.xml should be under version control. And it is not usually generated.
If you are using some "clever" utility to generate the web.xml, then don't put it in version control. But:

*

*your build process should include the generation as well - your app won't run without this file

*I'd advise against web.xml generation. At minimum there should be a template web.xml to which the generator appends.

A: it should be. it is where you do configure your web application.

A: If the file can be regenerated completely based on information which is present in your source control system, then No.   Otherwise Yes.
If you can regenerate it, then better document or automate how.


text:
Q: Connect turtles who are within a certain radius I use the nw extension in NetLogo to create a network.
My aim is the following:

*

*Check if any turtles are close by

*If any turtles are close by (I tried with next 3 patches, but that might change), connect to them + there is an upper limit of possible links

I tried (and, I think, succeeded) to implement the approach, described here. Which means that the upper limit works. However, I am not able to only link to the turtles close by. I also need something to catch the error if no turtle is close by. I tried to use the in-radius command but for some reasons, it doesn't do what I want.
extensions [nw]

breed [ AT1s AT1]

turtles-own [ friends ]

to setup
  ca
  create-AT1s 20 [
   setxy random-xcor random-ycor
   set friends 3
   set color green
   get-radius-friends friends AT1s
  ]
end

to get-radius-friends [ x AgentT]
  let lonely AgentT with [count my-links < x]
  let candidates other AgentT with [ any? AgentT in-radius 3 AND count my-links < x ]
   let new-links x - count my-links
    if new-links > 0 AND any? AgentT in-radius 3
    [ let chosen n-of min (list new-links count other candidates) other candidates
      create-links-with chosen [ hide-link ]
      set candidates other candidates
      ask chosen [ if my-links = x [ set candidates other candidates ] ]
    ]
end

I also found the neighbors and the distance commands but these only consider the immediate surroundings which isn't what I need.

A: Actually, that's not the best question to pull from if you want to spatially restrict the turtles. And there's a serious problem with having the connection within the turtle creation block because there are no potential friends for the turtles created first. Unless you have a very large number of turtles, you probably don't need to worry about efficiency.
I also think the variable 'x' is unnecessary because you have the variable 'friends' available (which appears to be the number of links you want the turtle to have). And there is a new reporter up-to-n-of which makes the whole list and min unnecessary.
I think this does what you want. You may want to test is without the hide-link so you can see what it does.
breed [ AT1s AT1]

turtles-own [ friends ]

    to setup
      clear-all
      create-AT1s 100
      [ setxy random-xcor random-ycor
        set friends 3
        set color green
      ]
      get-radius-friends 10 AT1s
    end

    to get-radius-friends [ #radius #breed ]
      let linkers turtles with [breed = #breed ]
      ask linkers
      [ let new-links friends - count my-links
        if new-links > 0
        [ let candidates other linkers with [ count my-links < friends ] in-radius #radius
          let chosen up-to-n-of new-links candidates
          create-links-with chosen [ hide-link ]
        ]
      ]
    end


text:
Q: Why does nuxt give me this error with vue-chartjs? I get this error while trying to make vue-chartjs work
 WARN  in ./node_modules/vue-chartjs/es/BaseCharts.js

"export 'default' (imported as 'Chart') was not found in 'chart.js'

And also this in devtools:
TypeError: chart_js__WEBPACK_IMPORTED_MODULE_0__.default is not a constructor

Steps to recreate:

*

*Create nuxt app with: $ yarn create nuxt-app <project_name>

*Add vue-chartjs with $ yarn add vue-chartjs chart.js

*Add following code which should work according to vue-chartjs docs

~/components/BarChart.js
import { Bar } from 'vue-chartjs'

export default {
  extends: Bar,
  props: ['data', 'options'],
  mounted() {
    this.renderChart(this.data, this.options)
  },
}

~/pages/index.vue
<template>

      <bar-chart
        :data="barChartData"
        :options="barChartOptions"
        :height="200"
      />

</template>

I am also using tailwindcss in the project and other nuxt project options were Axios, Git, ESlint, Prettier.

A: yarn add vue-chartjs chart.js@2.9.4

if you are using yarn

A: Chart.js has a new release version with 3.0.x. I think, vue-chartjs does not support it yet.
You can downgrade chart.js and try again.
ChartJS [3.0.1 - Published 2 days ago]
https://www.npmjs.com/package/chart.js?activeTab=readme
And there is a vue-chartjs issue about 22 hours ago.
https://github.com/apertureless/vue-chartjs/issues/695

A: chart.js version above 3.0.0 is not compatible, you need to downgrade chart.js
npm install chart.js@2.9.4
This has solved my issue

A: maybe its a bit late but I have to give the answer,
what you need is to change the version of both libraries
npm install chart.js@2.7.1 vue-chartjs@3.4.0 --save

it works fine in vue2


text:
Q: Grub menu at boot time... "holding shift" not working I read here at this thread that holding Shift during boot can bring up the GRUB menu. However I try holding one or the other Shift keys, tapping, tapping then holding, nothing works. Am I missing something? How does one access the GRUB menu during boot time?
No dual boot here, just standard Lubuntu 14.04 install.

A: I had the same problem. The system would boot directly and my monitor would be in out-of-range mode. I pressed ↑ repeatedly until I thought GRUB was waiting for a command, then I pressed ↓, Enter, ↓ to select recovery mode.
It took a few tries or randomness, but when I entered recovery mode the display came back. I then:

*

*Selected root for a root prompt

*Ran mount -o rw,remount / to mount the filesystem in read-write mode

*Ran vi /etc/default/grub

*Removed # from GRUB_TERMINAL=console

*Saved the file

*Ran update-grub to update GRUB

*Ran exit to return to the menu and continue booting

GRUB would show up, the monitor would work, and then I could log in.

A: I also cannot access the GRUB menu by any manner of pressing shift or esc on my Asus X205TA. To get the GRUB menu to display at boot, I had to modify the /etc/default/grub file. See this page.
To get the GRUB menu to display every time (until I change it back) I used nano to edit the file in the terminal. Type:
sudo nano /etc/default/grub

find the line that says GRUB_HIDDEN_TIMEOUT=0 or GRUB_TIMEOUT_STYLE=hidden
put # at the start of this line to comment it out
#GRUB_HIDDEN_TIMEOUT=0

or
#GRUB_TIMEOUT_STYLE=hidden

and make sure GRUB_TIMEOUT=10 or some other number bigger than zero. When done exit nano saving changes and run
sudo update-grub

A: I am answering this question in hope that it will help someone else in the Future.
Usually you are right in trying to get to Grub with Shift! But Grub usually explicitly prohibits using the Shift key if you have "Fastboot" enabled:
if [ "\${fastboot}" = "1" ]; then
  # timeout_style=menu + timeout=0 avoids the countdown code keypress check
  set timeout_style=menu
  set timeout=0

Taken from /etc/grub.d/12_menu_auto_hide
But the other people who answered in here are right aswell, but I think for a different problem. If the Grub menu does not start automatically on start up, you can try fiddeling with your /etc/default/grub file.
Open it with sudo rights:
sudo nano /etc/default/grub

And there you should see two entries of importance to us:
GRUB_TIMEOUT= "some number, probably 0 or 5"
GRUB_TIMEOUT_STYLE= hidden/menu/countdown

GRUB_TIMEOUT tells us how long Grub will wait for Input until it loads the default OS.

*

*0 will instantly choose the default OS

*-1 will wait on user input indefinitely

GRUB_TIMEOUT_STYLE tells you how the Grub menu is shown, if at all

*

*hidden= Hides grub unless you press Shift in time

*menu= Will show Grub

*countdown= Will not show grub, but an actual Countdown
on screen

Hope that helped
(more info on the other entries in /etc/default/grub Ubuntu Wiki

A: I have an X200MA. To enter the GRUB menu, you press Esc while booting. Choose Ubuntu to boot normally.
You may have problems if you installed Ubuntu not in UEFI mode. I did not test it that way.

A: There are three issues that make getting into the grub menu difficult on some systems.

*

*The timing of when to hit a key to abort the hidden menu feature is tricky

*Holding down the shift key doesn't always work because some bioses will think the key is stuck and clear it or give an error on stuck key

*Some video cards will not be initialized yet when the menu should come up, and the screen will be black, causing you to miss it

The first two problems can be bypassed by using capslock instead of shift.
The trick is to press caps lock during boot and watch the capslock light.  When it goes out, hit capslock again to turn it back on, and keep doing that until either you get the grub menu or you realize you've missed the timing again.
Once you've gotten past the hidden menu and gotten the grub menu, you need to turn off capslock and then interact with the menu before the menu timeout occurs and it selects the default item.
If you have a system with timing issues or video card initialization issues with grub, I strongly recommend you use one of the other answers here to permanently disable the hidden menu feature and/or force text console mode, as appropriate.  You will need to either boot successfully to do this -- either normally, via rescue options in the grub menu, or by booting the Ubuntu install media and invoking rescue mode from there.
When I'm installing ubuntu on a machine that has known problems like this, I'll use the "try ubuntu before installing" option and before it finishes, edit /etc/default/grub to disable hidden menu.   This can be done during install or before rebooting at the end.  Make sure update-grub gets rerun after you make that edit, either as part of the install or manually.


text:
Q: Proxy URL to different port via Lighttpd I cannot seem to proxy a URL to another port on same hostname. I have user interface (Angular 5) running on somehost:8080 and the rest of the web application on somehost.com (port 80). I'd like to proxy http://somehost.com/xxx to http://somehost.com:8080. Not sure if my configuration is correct or in the right place.
$HTTP["host"] =~ "somehost\.com$" {

        $HTTP["url"] =~ "(^/xxx/)" {
          proxy.server  = ( "" => ("" => ( "host" => "somehost.com", "port" => 8080 )))
        }

        url.rewrite-if-not-file = (
                "^/(.*)" => "/index.php/$1",
        )

}

A: From your question it looks like you want to serve http://somehost.com/xxx/file from http://somehost.com:8080/file. In that case your config is wrong, because it is trying to serve http://somehost.com:8080/xxx/file instead. You need to add a url.rewrite-once:
  url.rewrite-once = ( "^/xxx/(.*)$" => "/$1" )
  proxy.server  = ( "" => ( # proxy all file extensions / prefixes
    "" => # optional label to identify requests in logs
      ( "host" => "somehost",
        "port" => 8080
      )
    )
  )

Depending on your version of lighttpd, you might or might not be able to call url.rewrite-once from within a $HTTP["url"] match.
Also make sure that you have loaded the mod_proxy and mod_rewrite modules  with:
server.modules += ( "mod_proxy" )
server.modules += ("mod_rewrite")

More info on proxy.server: https://redmine.lighttpd.net/projects/1/wiki/Docs_ModProxy
More info on url.rewrite-once: https://redmine.lighttpd.net/projects/1/wiki/docs_modrewrite#urlrewrite-repeat


text:
Q: Sending parameters to local HTML file I'm fetching an URL address from XML file. That URL links to an HTML file,
the html builds itself (using javascript) according to a parameter that I'm sending to him.
One example line from the XML is:
<Module Id="1" URL="../../Modules/MessageComposer/module.htm" SRC="email.png" />

I would like to set this line to:
<Module Id="1" URL="../../Modules/MessageComposer/module.htm?UID=1" SRC="email.png" />

And I want to aks if this will work?
Thanks in advance.

A: A local file won't query anything unless you use a local server to fetch your URLs.
So if you want a local file to react on parameters passed to it's URL, for example in HTML you can parse window.location.search with JavaScript and do something with it.
If you want to locally trigger a query, use a simple local server as LAMP/WAMP.

Get your parameters:

var params = window.location.search.slice(1).split("&");

With each get name and value:
for(var p=0; p<params.length; p++) {
  var nv = params[p].split("=");
  var name = nv[0], value = nv[1];
  // What you want to do with name and value...
}

Generating an HTML anchor with XSL:

<xsl:for-each select="//Module">
  <xsl:element name="a">
    <xsl:attribute name="href"><xsl:value-of select="URL"/></xsl:attribute>
    <xsl:value-of select="URL"/>
  </xsl:element name="a">
</xsl:for-each>


text:
Q: Vuejs and google maps: Cannot create new object of Polyline class So, I want the user to be able to draw a freehand polygon on click of a button. I have it implemented in plain JS and now want to use it in vue (using vue-cli).
I am using this plugin for vue: https://github.com/xkjyeah/vue-google-maps/blob/vue2/API.md
Here is the code I am using:

var self = this;
// calls another method which disables map controls
self.disableMap();
// below line is fine
console.log(self.$refs.map.$mapObject);
// event handler is being called
self.$refs.map.$mapObject.addListener('mousedown', function() {
  // the below line results in undefined
  console.log(self.$refs.$polylineObject);
  let poly = new(self.$refs.map.$polylineObject)({
    map: self.$refs.map,
    clickable: false
  });
})

Any help greatly appreciated.


text:
Q: problem with text using svg2tikz I'm a new user of the extension svg2tikz.
I created a figure in Inkscape and exported it to TeX. When I export a the .svg file from inkscape to TikZ, the text is not located where it is in the .svf file.
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{tikz}
\usepackage{blindtext}

\begin{document}

\definecolor{c0000ff}{RGB}{0,0,255}

\begin{figure}
    \centering
\begin{tikzpicture}[y=0.80pt, x=0.80pt, yscale=-1.000000, xscale=1.000000, inner sep=0pt, outer sep=0pt]
\begin{scope}[shift={(-130.00729,-79.00466)}]
    \path[draw=black,fill=c0000ff,miter limit=4.00,fill opacity=0.098,line
      width=1.600pt,rounded corners=0.0000cm] (131.0073,80.0047) rectangle
      (502.2522,423.5963);
    \path[shift={(65.33081,-189.77046)},fill=black,line join=miter,line
      cap=butt,line width=0.800pt] (0.0000,0.0000) node[above right] (flowRoot4138)
      {TEXT};
\end{scope}
\end{tikzpicture}
    \caption{Caption}
\end{figure}

\end{document}

So you have any idea how to solve this problem.
Thank you.


text:
Q: Laravel 5 file downloads invalid When using Response::download to download files, I noticed that images and other binary files were being transferred incorrectly.
Changing the Content-Type header didn't change anything, nor did explicitly disallowing cache or forcing the content's length.
What may be the cause of this problem?

A: The solution to this problem can be found here:
http://simpledeveloper.com/how-to-fix-laravel-response-image-download-in-laravel/
The cause of the issue was due to Laravel/Symfony not properly cleaning the output buffer for some reason, so the solution is this:
$response = Response::download($path, ...);
ob_end_clean();

return $response;


text:
Q: Error: protocol error: bad line length character: erro Tried to push to my GitHub URL and it gives me this weird error. I don't see anyone else having this error.  I can pull from my git directory but not push.

A: It's known, that there can be different reasons for such a problem (some answers are already linked), but in our case its text was just the same, and it was caused by lack of RAM:
fatal: protocol error: bad line length character: Erro
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.


text:
Q: How insert data from a temporary table into partitioned table in oracle/sql using merge statement I have to write a merge statement to insert data from temporary table to a partitioned table and i'm getting below error:-
Error report -
SQL Error: ORA-14400: inserted partition key does not map to any partition

*

*I have to do it session wise and as a result, have to use a temporary table which can not be partitioned.

A: if your inserts datasets into the partioned table, oracle want to place it
into the correct partionen. You must create for the complete period of time
partitions like in example for MONTHY partition:
ALTER TABLE sales ADD
PARTITION sales_q1_2007 VALUES LESS THAN (TO_DATE('01-APR-2007','dd-MON-yyyy')),
PARTITION sales_q2_2007 VALUES LESS THAN (TO_DATE('01-JUL-2007','dd-MON-yyyy')),
PARTITION sales_q3_2007 VALUES LESS THAN (TO_DATE('01-OCT-2007','dd-MON-yyyy')),
PARTITION sales_q4_2007 VALUES LESS THAN (TO_DATE('01-JAN-2008','dd-MON-yyyy'))
;

If you have done this, you can insert the data ass needed.
Good luck,


text:
Q: Is the Cartesian product of two open sets open? Just a quick question: If you have two sets $A,B \subset \mathbb{R}$ that are open, that is, for every $p \in A$, there exists an $\varepsilon > 0$ such that $B(p;\varepsilon) \subset A$, is the Cartesian Product of these sets also open?
I am trying to think of a proof, but I am stuck rather quickly. So far I have this:
Proof: Let $A$, $B \subset \mathbb{R}$ be open sets. Let $C = A \times B$. Since $A$ is open, there exists an $\varepsilon > 0$ such that for all $p \in A$, $B(p;\varepsilon ) \subset A$. Since $B$ is open, there exists an $\varepsilon ' > 0$ such that for all $q \in B$, $B(q;\varepsilon ') \subset B$.
In other words, we can make a ball around a point in the $x$ or $y$ direction, but can we also make a ball in both at the same time?
Some guidance would be lovely.
Thanks in advance!

A: Yes, the product of two open sets is open. Generally, that is immediate from the definition of the product topology, but in the situation here, the task is to show that the topology induced by the usual Euclidean metric on $\mathbb{R}^d$ (here, $d = 2$) is at least as fine as the product topology (the converse, that every open ball around a point contains the product of open balls around the coordinates, then shows that the two topologies are identical).
If we have $B(p;\varepsilon) \subset A$ and $B(q;\varepsilon') \subset B$, then $B(p;\varepsilon)\times B(q;\varepsilon') \subset A\times B$. Since the coordinate projections don't increase distance,
$$\lvert x_i-y_i\rvert \leqslant \sqrt{\sum_{j=1}^d \lvert x_j - y_j\rvert^2} = \lVert x-y\rVert,$$
it follows that $B((p,q);\min \{\varepsilon,\,\varepsilon'\}) \subset B(p;\varepsilon)\times B(q;\varepsilon')$, and the product of the two open sets $A$ and $B$ is recognised as open.
The converse, that every open ball in the Euclidean metric contains the product of open balls in the coordinate spaces, follows from
$$\lvert x_i-y_i\rvert < \varepsilon/\sqrt{d} \text{ for all } i \Rightarrow \lVert x-y\rVert = \sqrt{\sum_{j=1}^d \lvert x_j-y_j\rvert^2} < \sqrt{\sum_{j=1}^d \varepsilon^2/d} = \varepsilon.$$


text:
Q: Spring reactive WebSocketHandler mono does not reach doFinally block I am trying to handle closing web socket session in WebSocketHandler. My intuition was to do it in this way:
webSocketClient.execute(
    URI.create("some-ws-endpoint")
) { session: WebSocketSession ->
    session.receive()
        .doOnEach { action(it) }
        .then()
        .doFinally { session.close() }
}

but I cannot reach doFinally block from Mono<Void> returned by webSocketClient.execute. My full test code for this case is:
fun test() = runBlocking {
        val webSocketClient: WebSocketClient = StandardWebSocketClient()

        val subscription = webSocketClient.execute(
            URI.create("some-ws-endpoint")
        ) { session: WebSocketSession ->
            session.receive()
                .doOnEach { println("Message: $it") }
                .then()
                .doFinally { println("finally") }
        }.subscribe()

        delay(20000)

        subscription.dispose()

        delay(5000)
    }

from which I have Messages printed, but finally is never shown on my console. From the other hand when I tried to do it on plain reactor-core components, everything works just fine:
runBlocking {
    val publisher: Flux<Long> = Flux.interval(Duration.ofSeconds(1))

    val subscription = publisher
        .doOnEach { println("Value: $it") }
        .then()
        .doFinally { println("in doFinally") }
        .subscribe()

    delay(5_000)

    subscription.dispose()

    delay(1_000)
}

I am new to both WebSockets and Project Reactor, so maybe I am doing some basic mistake. Does anyone see what is wrong with my code?


text:
Q: Generic constraints in C#, T is the same TSomethingElse, right? I often see:
public interface IFoo<TWidget> where TWidget : ISomethingElse { }

In this case, TWidget is the same as using the generic T, correct? I'm finding this surprisingly hard to google or find in the specs. I'm 99% sure that T + any other characters is the same as saying just T, but wanted to be absolutely sure.

A: The name of the generic type parameter can by any valid identifier name.
In most documentation you would indeed find T where you put TWidget.
From MSDN:

Do name generic type parameters with descriptive names, unless a single letter name is completely self explanatory and a descriptive name would not add value.

A: In this case TWidget is generic, but not because it is T+something. Although it is recommended to name it T+something, it can be anything you want, as long as it syntactically correct type identifier name.

A: As you suspect, it's perfectly legal to put any identifier where you usually see T.
You'll often see more descriptive names when there are constraints put on the generic type, usually indicating what the constraint might be. It's also helpful to have a longer identifier when you have multiple generic type parameters, so you can easily remember which one is which.

A: The Type parameter can be names anything but the standard way of doing it is to use T and then go through the alphabet as more generic types are required.
So you might have public interface IFoo<T, U> where T : ISomethingElse { }
But you could just as easily use public interface IFoo<Banana, Spiggot>. It really doesn't matter


text:
Q: JavaScript-Change Navigation Style On Scroll I want the active section to be highlighted when scrolling the page.
But i am getting error: "Uncaught DOMException: Failed to execute 'querySelector' on 'Document': The provided selector is empty."
Why? How to solve this?
js:
window.addEventListener('scroll', event=>{
    let navigationLinks = document.querySelectorAll('nav ul li a');
    let fromTop = window.scrollY;

    navigationLinks.forEach(link=>{
        let section = document.querySelector(link.hash);
        if (section.offsetTop <=fromTop &&
            section.offsetTop + section.offsetHeight > fromTop
        ){
            link.classList.add('active');
        } else{link.classList.remove('active');}
    })
});

html:

Home

About

Contact

css:
nav a.active{
    color: darkcyan;
    border-bottom: 2px solid darkgoldenrod;
}

A: The error you give is caused by the first link.
The href is # so the link.hash property will be ""
Both document.querySelector("") and document.querySelector("#") raise an error.
The solution is to add a check if the hash is not empty.
if (link.hash != "" && link.hash != "#") {

Note that the Home link will always stay active since it doesn't have a corresponding
 element

window.addEventListener('scroll', event => {
  let navigationLinks = document.querySelectorAll('nav ul li a');
  let fromTop = window.scrollY;

  navigationLinks.forEach(link => {
    if (link.hash != "" && link.hash != "#") {
      let section = document.querySelector(link.hash);
      if (section.offsetTop <= fromTop &&
        section.offsetTop + section.offsetHeight > fromTop
      ) {
        link.classList.add('active');
      } else {
        link.classList.remove('active');
      }
    }

  })
});
nav a.active {
  color: darkcyan;
  border-bottom: 2px solid darkgoldenrod;
}

/* for demonstration purposes */

nav {
  position: fixed;
  top: 0;
}

#about,
#contact {
  height: 100vh;
}

Home

About

Contact

About

Contact


text:
Q: MariaDB Cluster vs Percona Cluster for MySQL What are the advantages and and disadvantages between the two? I've only been able to find information on these two implementations without any specifics on clusters.
I'm currently implementing a Percona Cluster but my only concern currently is with MYISAM databases for replication. I run several wordpress databases in INNODB on these servers but when I need to migrate databases from other systems, they are sometimes fully or partially MYISAM which has caused some problems with my setup lately.
Is moving from a Percona Cluster to a MariaDB Cluster a better choice?

A: Both platforms use the same mechanism for replication: Galera.  On the page at that link, you'll notice there are images featuring both PXC and MariaDB Cluster.
Galera library provides transactional replication.  MyISAM doesn't do transactions, so the problems you may be having now are very likely related and would not be any different on the alternate platform.

Currently replication works only with InnoDB storage engine. Any writes to tables of other types, including system (mysql.*) tables, are not replicated. However, DDL statements are replicated in statement level, and changes to mysql.* tables will get replicated that way. So, you can safely issue: CREATE USER..., but issuing: INSERT INTO mysql.user..., will not be replicated.
— http://www.percona.com/doc/percona-xtradb-cluster/limitation.html
Currently MariaDB Galera Cluster only supports the InnoDB/XtraDB storage engine.
— https://mariadb.com/kb/en/getting-started-with-mariadb-galera-cluster/

And, of course, PXC uses XtraDB, Percona's compatible replacement for InnoDB (it has "XtraDB" right in the name), and MariaDB also uses Percona's XtraDB instead of Oracle's InnoDB, although, for compatibility on both systems, the storage engine still calls itself InnoDB.
Since the two systems share a signficant amount of code and are all intended to be essentially drop-in replacements for one another, the decision of which platform to use is largely a matter of opinion.  I personally prefer vendor "x" which might mean I'd personally recommend you use MariaDB and also might mean I'd personally recommend sticking with PXC, but I need not actually actually tell you my preference, since it doesn't matter -- it's based largely on opinions and impressions and documentation and personalities and not on any kind of valuable evidence.
Your best solution for migrating MyISAM is probably going to be to modify the dumpfiles to ENGINE=InnoDB (and any other changes that necessitates) or staging them on a standalone server, then converting and exporting them as fully-InnoDB before trying to import them to your cluster.
If the MyISAM issue is your only concern, or even just your primary concern, then MariaDB Cluster and PXC are essentially identical in that regard -- they don't support it, for a very sensible reason -- it's not feasible to do so.

A: I work for Percona, so I'm biased.  I'd say that while on the surface they are similar products, PXC has had many more releases, we're doing a ton more QA, and are doing much more to contribute back to Codership than Maria so far.
However, MyISAM support is going to be the same on either, and I'm sorry to say that if MyISAM is a design requirement for you, you're likely not going to be happy on any Galera product.  Galera is simply never going to really support a non-transactional engine like MyISAM like it does with Innodb and I'd agree with Michael that migrating away from MyISAM is your best choice if you are moving to Galera.


text:
Q: Git from local to FTP (not working copy) What's the best way to push (publish) my local repository to both bitbucket and my shared host (hostgator)?
I'm using Windows with Git.
Actually, i can git push to bitbucket and works. But I would like to publish in my FTP (shared host), but I think great to publish only the files, not the .git folder, in other words, the working copy (clone).
Actually i access the ssh via git bash, and hit git clone ... but this is'not a good/better way (I think).
So I saw this link: http://github.com/resmo/git-ftp and also http://github.com/ezyang/git-ftp
but i would like to know if exists better way to do this without have to install python or other softwaer like cygwin.
My projects are little (about 3mb), so isn't necessary to send only the changed files. can be all the files.
I have looked at many links about this, and I tried other ways, but maybe there are a good and simple way to do this... because this I came to stackoverflow to ask for your all help.

A: You have several different options:
1)  Create a script locally which does a git push to bitbucket, a git checkout-index -a -f --prefix=/destination/path/ to a local directory and then ftp's that local directory up to your ftp server.
2)  Create a new remote which points to a bare repository on the ftp server, and then create a post-receive hook which does the git checkout-index -a -f --prefix=/destination/path/ on the ftp server.  Once this is setup you'd do a git push and git push ftp (which could be aliased to one command if desired)
3)  Use git archive to point to a remote repository:  git archive --format=tar --remote=ssh://remote_server/remote_repository master | (cd /path/to/dir/ && tar -xf -)  Obviously, you'd want to create an alias for this command.


text:
Q: Post-fork connection to Cassandra under gunicorn I'm developing a Flask microservice to expose some data from a Cassandra database. It is served with gunicorn being called from the command line.  I'm confused regarding as to where and how to connect to the database under gunicorn, particularly when considering how to mock or bypass the need of the database when doing unit testing.
My first attempt was to connect at app creation time, as follows:
def create_app():
    app = Flask(__name__)

    app.debug = True

    cluster = Cluster([os.environ['CASSANDRA_HOST']])
    app.cassandra = cluster.connect(os.environ['CASSANDRA_KEYSPACE'])

    return app

thinking that it will make a single "global" connection reducing overhead for each individual request. This clearly fails unit testing as it'll try to connect which is not the point of a unit testing in an isolated environment of a CI pipeline.
Then, checking some slides from Cassandra people it says that for Flask under gunicorn we should use @app.before_first_request and that as a general rule should connect "post-fork". I'm not sure what "post-fork" means in this context.
Anyhow, doing:
@app.before_first_request
def before_request():
    app.cluster = Cluster([os.environ['CASSANDRA_HOST']])
    app.cassandra = app.cluster.connect(os.environ['CASSANDRA_KEYSPACE'])

also works, but still have the same problem with the isolated unit testing.
By reading through this post, I guess that I'm not having issues with the connection itself as I'm creating one Cassandra session per Flask instance that is spawned by gunicorn post-fork.
Then my question would reduce to which strategy to follow to be able to unit test the endpoints without having to explicitly reach for the database.

A: The general idea is to have one Cluster/Session per process, created on fork and held for the process lifetime. Most servers offer a post-fork 'hook' for setting up resources like this.
The Gunicorn hook is documented here
uWSGI analog is reference in the driver FAQ.


text:
Q: Ubuntu :generate apk android studio 3.3 I am in the process of creating an android app. I use Ubuntu 14.04 as an OS and android studio 3.3 as an IDE. I want to generate the apk, i follow the following steps:

Build > Generate signed BUndle or Apk > Apk > add the keystore.js >
  choose V1 and V2 and release > finish

The gradle file contains the following information

keyAlias 'key'
            keyPassword '1234565789'
            storeFile file('/home/development/Android/KeyStore/app.jks')
            storePassword '123456789'

After that, the following error appear when i click my apk:

The file
  '/home/development/Android/App/app/release/app-release.apk' is not
  marked as executable.  If this was downloaded or copied from an
  untrusted source, it may be dangerous to run.  For more details, read
  about the executable bit.


text:
Q: Is it better to access a public field of an object multiple times or cache it in a variable? I encountered this piece of code today and it made me wonder:
Is it better to access a public field of an object multiple times in a row or does it make more sense to cache it in a local variable?
void AddName(Class object) {
    if (object.name != null && !list.Contains(object.name)) {
        list.Add(object.name);
    }
}

or
void AddName(Class object) {
    string name = object.name;

    if (name != null && !list.Contains(name)) {
        list.Add(name);
    }
}

I was wondering if in C#, accessing public fields multiple times is better or worse than caching to a local variable and allocate memory every single time the method is called.
Thank you for your answers!

A: The compiler can't optimize the first example but you won't notice a difference between the two variants. There's no measurable difference in performance and both variants consumes the same memory.
It is much more important for you (and your team) to design the code in a way that it is easy and quick to understand.