text:
Q: Detect changed files How to detect changed files and move them to a folder named storage on my desktop is there any way I can do it with powershell/bat/vbscript without any third party tools?

A: The .NET framework has System.IO.FileSystemWatcher, which can be accessed from PowerShell (example).

A: This will print out newly created files in c:\win16. Note the double doubled backslashes in the folder path. Within 10 says to check every 10 seconds.
This copies new files in C:\Win16 to C:\Users\User\Desktop\Backup\. Note trailing backslash. You need to edit the paths.
All the Replaces and Splits are getting it a a plain file path turning two backslashes to one, removing quotes, and split discards the first part of the returned string.
Call it monitorfolder.vbs.
Set FSO = CreateObject("Scripting.FileSystemObject")
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
("SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE Targetinstance ISA 'CIM_DirectoryContainsFile' and TargetInstance.GroupComponent= 'Win32_Directory.Name=""c:\\\\Win16""'")
Do
    Set objLatestEvent = colMonitoredEvents.NextEvent
    FSO.MoveFile Replace(Replace(Split(objLatestEvent.TargetInstance.PartComponent, "=")(1), "\\", "\"), """", ""), "C:\Users\User\Desktop\Backup\"
Loop

To print it out to a console window
Shift+Right Click on the file - Copy As Path. Open Command Prompt as Administrator and
Right Click - Paste, then press Home key and prepend cscript //nologo  to the path to the vbs. Then press Ctrl+C to stop monitoring.
The output will look like this
C:\Windows\system32>cscript //nologo "C:\Users\User\Desktop\Bat+Vbs\monitorfolder.vbs"
"c:\Win16\file.txt"
"c:\Win16\Folder Property List.txt"
"c:\Win16\IHS.pdf"
"c:\Win16\nfs3.exe - Shortcut.lnk"

Note
When a file is modified or created Windows sets its Archive bit. XCopy can copy only files with the archive bit set and then clear the bit. This is how early MS-Dos backup programs worked. It only copies new of modified files since the last backup. See attrib /? and xcopy /?.

A: possible solution, run powershell script every like 10 minutes, look for created/modified files and move
Get-ChildItem -Recurse | ? { $_.CreationTime -gt $(get-date).AddMinutes(-10)} | % { Move-Item -Path $_.FullName -Destination $(Join-Path  -Path $([Environment]::GetFolderPath("Desktop")) -ChildPath source) }


text:
Q: How to speed up custom function How to speed up my custom function?
I have three list of numbers :
list1
list2
list3
And Pandas Dataframe like this:

id
inum
DESC_1
recs

id1
inum1
1
recs1

id2
inum2
2
recs2

id3
inum3
3
recs3

And my custom function:
def keep_inum(row):
    if len(row) != 0:
        if int(row['inum']) in list1:
            if row['DESC_1'] == 1:
                return row['recs']
            else:
                return ''
        elif int(row['inum']) in list2:
            if row['DESC_1'] == 2:
                return row['recs']
            else:
                return ''
        elif int(row['inum']) in list3:
            if row['DESC_1'] == 3:
                return row['recs']
            else:
                return ''
        else:
            return row['recs']
    else:
        pass

Apply func to DF:
df['recs'] = df.apply(keep_inum, axis = 1)

A: By not using a custom function at all:
import pandas as pd

df = pd.DataFrame(
    {
        "id": ["id1", "id2", "id3", "id4"],
        "inum": ["111", "222", "333", "331"],
        "DESC_1": [1, 4, 3, 3],
        "recs": ["recs1", "recs2", "recs3", "yes"],
    }
)

print(df)
print("---")

list1 = [111]
list2 = [222]
list3 = [333, 331]

# Cast inum to int in one go
df["inum_int"] = df["inum"].astype(int)
# Empty the recs where inum doesn't match desc
df.loc[df["inum_int"].isin(list1) & ~(df["DESC_1"] == 1), "recs"] = ""
df.loc[df["inum_int"].isin(list2) & ~(df["DESC_1"] == 2), "recs"] = ""
df.loc[df["inum_int"].isin(list3) & ~(df["DESC_1"] == 3), "recs"] = ""
df.drop(columns=["inum_int"], inplace=True)
print(df)

This outputs
    id inum  DESC_1   recs
0  id1  111       1  recs1
1  id2  222       4  recs2
2  id3  333       3  recs3
3  id4  331       3    yes
---
    id inum  DESC_1   recs
0  id1  111       1  recs1
1  id2  222       4
2  id3  333       3  recs3
3  id4  331       3    yes

redpajama_set_name: RedPajamaStackExchange


text:
Q: jquery mobile - navbars not changing color on click This small jquery mobile example works OK, except because the navbar is repeated, it takes two clicks to change the color.  Can I get around this with a .click event or maybe restructure the navbar's a bit.
<!DOCTYPE html>

    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.css" />

page1

page2

Page 1

page1

page2

Page 2


text:
Q: Android - Notification icon will not change How I can change the icon & largeIcon in my notification? I'm trying this code:
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        Notification notification = builder
            .setSmallIcon(android.R.drawable.stat_notify_more)
            .setWhen(System.currentTimeMillis())
            .setAutoCancel(true)
            .setContentTitle("title")
            .setContentText("text").build();

        notificationManager.notify(666, notification);

This works great, notification was displayed. But the notification are stil the same like application icon, not the "stat_notifi_more" from android drawable, why?
And also the STATUS BAR ICON (notification small icon at the top- left side next to battery, wifi and others) does not shows too!
Can someone help me with this?
Edit: I have lollipop 5.1.1 and android 24 (sdk)
EDIT2:
The notification icon (OK) (96x96px):

Status bar icon (24x24px) (NOT OK, default application icon):

real status bar icon:

Notification source:
// Using RemoteViews to bind custom layouts into Notification
            RemoteViews remoteViews = new RemoteViews(getPackageName(),
                    R.layout.notification_layout);

            // Set Notification Title
            String strtitle = "title";
            // Set Notification Text
            String strtext = "text";

            // Open NotificationView Class on Notification Click
            Intent intent = new Intent(this, MainActivity.class);
            // Send data to NotificationView Class
            intent.putExtra("title", strtitle);
            intent.putExtra("text", strtext);
            // Open NotificationView.java Activity
            PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);

            // Locate and set the Image into customnotificationtext.xml ImageViews
            remoteViews.setImageViewResource(R.id.imagenotileft, R.drawable.stacionar_xhdpi_green);

            // Locate and set the Text into customnotificationtext.xml TextViews
            remoteViews.setTextViewText(R.id.title, "title");
            remoteViews.setTextViewText(R.id.text, "content");

            NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.wall_black)
                    .setTicker("t")
                    .setContentIntent(pIntent)
                    .setContent(remoteViews);

            // Create Notification Manager
            NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            // Build Notification with Notification Manager
            notificationmanager.notify(0, builder.build());

xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/imagenotileft"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/imagenotileft" />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/title"
        android:layout_toRightOf="@+id/imagenotileft" />
</RelativeLayout>

A: Android notification will always show the application icon. You will need to create a custom notification layout for showing an icon other than application icon. Here, you can use whatever icon/design you want.
setSmallIcon() sets the notification icon that comes on the status bar and not in the notification tray. The drawable you assign here should be very small in dimensions. Check the expected sizes here. I believe your drawable is bigger than the expected size and hence, it is not able to render it. Hence, you are not able to see it in the status bar.
Edit:  The small icon in status bar will always be white, so your red and green color will not be shown. I think you are not able to see the green color is because of the translucent nature of the color. Even if your drawable has solid red or green, it will just appear as a white circle.
This SO Question has detailed information about it. Hence, my advice is that you just use default app icon for the small icon and use whatever custom icon you want for the notification in the notification tray.

A: If you are using Firebase Cloud Messaging:
to change the small icon when app is in the background you can do it from manifest:
        <meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@drawable/notification_icon"
        android:value="@string/default_notification_channel_id" />


text:
Q: Tried updating from 11.10 to 12.04, gets stuck at boot screen The update finished, upon restart I get stuck at this:

*

*and nothing afterwards. Before I attempt a complete reinstall, are there any other steps I can take?

If I do end up reinstalling, what is the best way to back up my files from the Windows side? As of right now, I cannot view them because Windows sees the folder as a protected recovery partition.

A: You cannot easily back up your files on Linux from Windows, as Windows can't read the ext4 filesystem.  You will need to boot into a LiveUSB / LiveCD environment and mount your Linux partition, and copy off data from your Linux partition to your Windows partition that you want to keep via the LiveUSB/LiveCD environment.
From there, if your upgrade failed and gets you stuck in a boot screen, I suggest a clean install of 12.04, then restore your files which you backed up afterwards.
This is just my suggestion, though, there may be better suggestions from others if you wait a bit more.


text:
Q: React funtion components store variable like a class member I'm quite new to react and I'm making a project. I need to a global hold a variable and update it ONCE when the component is created.
This object needs to be something like a hash map. Something like this:
const startState = [];
const comp = (props) => {
   const [someVar, setSomeVar] = useState({ id: "123" });
   ...
   //someVar is updated to a propper id

   somethingLikeAConstructor( () => {
      addToStartState( { someVar.id: {width: "123"} } );
   } );

};

This variable should store the initial state of all the created components on something like a hash map(So I can associate the corresponding components to right width values ) and it should be available to the other parts of the program.
But the width values are updated inside the component, I do not want the array to be updated when the values of the component is changed, I just want to store the starting values of each created component.
There needs to be only one variable that gets updated once when a component is created and it should be accessable globally.
So it must be something like a traditional class variable like in other OOP languages.
On another language I would do it like this:
class someClass{
public:
    static startValues = []
    constructor()
    {
       ... // calculate the width
       startValues.append(this.width);
    }
};

How can I achieve this effect on function components? And what type of variable I should use to get that id association effect?

A: You've said you want to have a global and have it updated each time a component is first mounted.
There are at least two ways to do that:

*

*useEffect

*useRef
useEffect is the usual solution and probably the one you want.
useEffect
When you use useEffect with an empty dependency array, it calls its callback when the component is mounted but not on subsequent re-renders:
useEffect(() => {
    // ...write to your global here...
}, []);

If you need to do something when the component is unmounted, you can return a callback to do that:
useEffect(() => {
    // ...write to your global here...
    return () => {
        // ...write your cleanup code here...
    };
}, []);

But, note that the useEffect callback is called just after the component is rendered and committed to the DOM, not before. Most of the time, this is what you want. In your case you've referred to element widths, so you'd be using refs to those elements, and those won't be filled in until the component is rendered and committed.
useRef
If you have an unusual situation where you need to do something the first time is a component is mounted before it's rendered and committed, you can do that with a ref via useRef:
const mountedRef = useRef(false);
if (!mountedRef.current) {
    mountedRef.current = true;
    // ...write to your global here...
}

There's no equivalent of the cleanup callback, but you can combine the useRef with the useEffect to get cleanup:
const mountedRef = useRef(false);
if (!mountedRef.current) {
    mountedRef.current = true;
    // ...write to your global here...
}
useEffect(() => {
    return () => {
        // ...do your cleanup here...
    };
}, []);


text:
Q: OracleAS 10g aborts request when downloading big excel file I am facing a problem with a servlet that generates a big excel file created with POI.
This servlet executes a code similar to this:
    // (...)
    // set headers and names
    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-disposition", "attachment;filename="
        + fileName + ".xlsx");

    workbook = new SXSSFWorkbook(flushLimit);
    workbook.setCompressTempFiles(true);

        while (resultSet.next()) {
            // add rows and cell to excel file
            //(...) about 3000000 rows
        }

        logger.info("Writing and closing to temp file");
        workbook.write(fileOutputStream);
        logger.info("Dispose Workbook");
        workbook.dispose();
        logger.info("Closing fileOutputStream");
        IOUtils.closeQuietly(fileOutputStream);

        logger.info("Passing file to servlet outputstream");
        fileInputStream=new FileInputStream(tempFileOutput);

        IOUtils.copy(fileInputStream, response.getOutputStream());

        logger.info("Closing fileInputStream");
        IOUtils.closeQuietly(fileInputStream);
        // delete temporal file
        try {
            tempFileOutput.delete();
        } catch (Exception e) {
            logger.error("Error trying to delete file");
        }

        // close servlet
        response.getOutputStream().flush();
        response.getOutputStream().close();

When servlet takes more than 10 minutes to generate the report and the file sizes is about 100mb it sometimes shows a web saying Internal problem(with no more information) or in other cases the page remains loading.
Despite, the excel file is generated correctly but the transmission was cancelled.
Is there a configuration prevent OAS aborts the connection?


text:
Q: Adding component.Why doesn't this work? The code below does exactly what I am trying to do, which is when I click a button add a component dynamically.
The thing is I want to make a function to add the component rather than the inline expression.But, it won't work.please somebody educate me.

<add-exercise :days="days" transition="fade" v-for="component in components" :exerciseplan_id="exerciseplan_id"></add-exercise>

<button v-if="components < 7" @click.prevent="components++">Add</button>
<button v-else="submit" transition="fade">Submit</button>

</template>

data() {

       return {

          components:1,

},
components:{ AddExercise },

the code that does not work
<button v-if="components < 7" @click.prevent="addComponent">Add</button>

methods: {
 addComponent: function(){
   return this.components++
}
}

A: The problem is with your method. You don't need to return, just run the action you want, like this:
methods: {
  addComponent: function(){
    this.components++;
  }
}


text: Q: send sms and notification without internet while the app requires internet to function? If my app require internet connection for authentication and am storing information that is supposed to send an SMS to client upon the time I specify reaches..can the app send the SMS without the internet connection??


text:
Q: Exchange - allow all users to see each others agenda I want to make a small script that all users can see each others agenda.
But the '$user.alias' is where i fail
I'm still learning Exchange scripting, at the moment I use Exchange 2010.
$mailboxen = get-mailbox | get-mailboxstatistics | where {$_.totalitemsize -ge 1mb}

foreach ($user in $mailboxen) {
Write-Host -ForegroundColor green "Setting permission for $($user.alias)..."
Set-MailboxFolderPermission -Identity "$($user.alias):\calendar" -User
Default -AccessRights Reviewer
}

A: This is what I use
$mailboxes = Get-Mailbox
$mailboxes | ForEach {Set-MailboxFolderPermission -Identity ([string]($_.PrimarySmtpAddress) + ":\Calendar") -User Default -AccessRights Reviewer}

With what you've used Get-MailboxStatistics doesn't return either the primarysmtp or the alias, so your variable $mailboxen won't contain it either.

A: Looks like you've joined two different scripts together as get-mailboxstatistics isn't needed:
$mailboxen = Get-Mailbox -ResultSize Unlimited

foreach ($user in $mailboxen) {
    Write-Host -ForegroundColor Green "Setting permission for $($user.alias)..."
    Set-MailboxFolderPermission -Identity "$($user.alias):\calendar" -User Default -AccessRights Reviewer
}


text:
Q: Classify ID column based on another column I can not figure this out. I have a data frame
id=c(1,2,3,4,2,6,1,1,6,5,4,2)
per=c(0.1,0.9,0.6,0.5,0.8,0.9,0.2,0.3,0.7,0.5,0.4,0.3)
df=data.frame(id=id,per=per)

I want to divide the "per" column in three conditions, lets say, between 0 and 0.3 (we assign a 3), 0.3 and 0.7 (we assign a 2), and 0.7 and 1 (we assign a 1).
My idea is to assign each unique id to the largest count of this division, i.e., if for id=1 there are more "per" in the 0.7-1 range, then that id corresponds to that division, i.e., id = 1 corresponds to "1". So the example would look like:
 id class
  1     3
  2     1
  3     2
  4     2
  5     2
  6     1

I found this
R- selecting a row based on characteristics of another column in that row
but I need the previous step, i.e., the classification, to reach that point.
Thank you!

A: You can easily achieve this using the cut function in R:
# specify cut, and labels
class <- cut(per, breaks = c(0, 0.3, 0.7, 1), labels = c(3, 2, 1))

#cbind with original data frame
df_new <- cbind(df, class)

#view
df_new

#     id  per   class
# 1   1   0.1     3
# 2   2   0.9     1
# 3   3   0.6     2

Hope this helps!
UPDATE:
# use dplyr package to summarise
(df_stats <- df_new %>% group_by(id,class) %>% summarise(count=n()))

For a given id, the higher the count, the higher the likelyhood that the id belongs to that corresponding class.

A: First assign the classes
cl <- cut(per, breaks = c(0, 0.3, 0.7, 1), labels = c(3, 2, 1), right=FALSE)

The parameter right=FALSE to handle edge cases as you specified in comments.
Then find number of classes for each id
chk <- table(id, cl)

Result is
> chk
   cl
id  3 2 1
  1 2 1 0
  2 0 1 2
  3 0 1 0
  4 0 2 0
  5 0 1 0
  6 0 0 2

Then find the column name with the highest value in a row. Assuming ties when there is same number of class in id are resolved by picking the last label (in this case, the lower number one)
output <- apply(chk, 1, function(x) names(rev(which(x==max(x))))[1])

Result is
> output
  1   2   3   4   5   6
"3" "1" "2" "2" "2" "1"


text:
Q: Printing Linux command line history without line numbers How can I print Linux command line history without including the line numbers? I want to send it all to a text file like this:
history >> history.txt

A: try the following if you don't want to write to a file
history -w /dev/stdout

A: First of all, the history is a feature of the shell, and doesn't really have anything to do with Linux, per se. Assuming you are using the bash shell, if you just use the history write option it doesn't add line numbers, anyway.
history -w history.txt

Will get you what you want.


text:
Q: I can load functions from dynamic library with linking this dl ,but I can not load it using 'dlsym' in the code without linking this dl I am using gcc/g++ on fedora 116, and my idea is:
c program -> load c++ dynamic library A -> load c++ dynamic library B

The c++ dynamic library B is third-party provided and I can not modify it.
When complinng c++ dynamic library A with linking c++ dynamic library B, A can find symbols in B. But when I load B functions in A code (not linking) using 'dlsym', A tells me
/path/to/B.so: undefined symbol: some_func

=============================
use nm -DC
0000000000014a80 T BinarySearch(int, int*, int)
0000000000007210 T CheckLicense()
0000000000009370 T GetEnd(stCha*, int&, int)
000000000000a970 T IC_Exit()
000000000000a740 T IC_Init(char const*)

the error report:
/path/to/some.so undefined symbol: IC_Init

the code in library A:
IC_API bool (* IC_Init)(const char *);
IC_Init = (IC_API bool (*)(const char *)) dlsym(dl_ic, "IC_Init");
if(IC_Init) {
    printf("function loaded");
}

in library A, it can load library B using dlopen:
void *dl_ic = dlopen(ic_lib_path, RTLD_LAZY);

A: Have you considered name mangling?  C++ identifiers are typically "mangled" to incorporate information on their namespace and arguments (which historically helped linkers differentiate overloaded functions).  You may want to make the function extern "C" to prevent mangling, or find its mangled name to use with dlsym (e.g. on Linx use nm on an object, or gcc -S -o /dev/tty ... | grep some_func on the source).


text:
Q: Data movement utility in db2 Why the not logged initially option during the data movement is faster than using the LOAD utility in DB2?
Not logged initially Method:
db2 alter table tablename activate not logged initially

db2 insert into table tablename select * from tbname

Load Utility:
db2 declare source cursor for select * from tablename

db2 load from source of cursor insert into tablename nonrecoverable

A: Based on your database size and performance question I am going to assume that you are using the Database Partitioning Feature (DPF) with DB2.
When you perform INSERT INTO ... SELECT, this occurs in parallel on all database partitions – each partition is working independently.  With logging turned off, this will be quite fast (albeit dangerous – if there is a problem, the not-logged-initially table will have to be dropped and recreated).
When you use LOAD FROM CURSOR, all of the database partitions execute the SELECT statement and return the rows to the coordinator partition, which then feeds them into the LOAD utility.  The LOAD utility then performs hash partitioning to send the data back to all of the database partitions again.  As you can imagine, with a large volume of data, shipping all of this data back and forth can be quite inefficient.


text:
Q: Revert to old object state in Java I'm just learning Java but I keep running into the same problem over and over again
How do i revert to an old state of some object efficiently?
public class Example {
    MyObject myLargeObject;

    public void someMethod(){
        MyObject myLargeMyObjectRecovery = myLargeObject;

        /**
         * Update and change myLargeObject
         */

        if(someCondition){
            //revert to previous state of myLargeObject
            myLargeObject = myLargeMyObjectRecovery;
        }
    }
}

The above is how I would like the code to work but it obviously doesn't since myLargeObject and myLargeObjectRecovery are references to the same object.
One solution is to create a copy constructor. This is fine for small objects but if I have a large object (in my project the object is a large 2D array meaning I would have to iterate over all of the entries), this way feels wrong.
This must be a very common problem in Java, how do others get around it?

A: Either deep copy, as you noted, or possibly serialization.  You could store a serialized string, and then reconstruct the object from it later.

A: The best solution depends on whether you have external references to your MyObject instance or not.
If you use the myLargeObject from the Example class only, you can use

*

*Serialize your object at the savepoint, and deserialize at the restore point (the serialized byte[] must be transient)

*Create a new instance with a Copy Constructor (doing deep copying) at the savepoint, and replace the reference at the restore point.

If you have access to the MyObject instance from outside, then it becomes a bit more interesting, you must introduce synchronization.

*

*All of your methods on MyObject must be synchronized (to avoid inconsistent read)

*You should have a synchronized void saveState() method which saves your state (either by serialization, or by copy constructor) (the latter is better)

*You should have a synchronized void restoreState(), where you internally restore your state (for copying fields you can use a common code fragment with the copy constructor)

In all cases it is recommended to close the transaction (kind of commit()) at some point, it means that when you get there, you can delete the saved state.
Also, it is very important, that if you have an underlying data structure, you should traverse the whole structure for it. Otherwise you may experience problems with the object references.
Be careful with JPA Entities or any externally-managed objects, it is unlikely that any of these methods will work with them.

A: If you assign a object to another, jvm refers to same object in the memory. Therefore, the changes on the object will be in the other objetc which references.
MyObject myLargeMyObjectRecovery = myLargeObject;

It is the same in your code. myLargeMyObjectRecovery and myLargeObject refer to same object in the memory.
If you want to exact copy of any object you can use Object.clone() method. this method will copy the object and return a object which is refer to another object whose fields and their valus same as the coppied object.
Since clone method is protected you can not access it direcly. you can implement a Prototype pattern depending on your requirements.
http://www.avajava.com/tutorials/lessons/prototype-pattern.html
public class MyObject{

//fields, getters, setters and other methods.

public MyObject doClone()
    {
        MyObject clonedObject = this.clone(); //you may need to override clone()depending on your requirements.
return clonedObject;
    }

    }

and call it in your code
MyObject myLargeMyObjectRecovery = myLargeObject.doClone();

A: The Memento Pattern addresses the design issue of the revert to previous state problem. This approach is useful when you need to capture one or multiple states of the object and be able to revert to them. Think of it as an N-step undo operation, just like in a text editor.
In the pattern you have a stateful object Originator, which is responsible for saving and restoring snapshots of it's state. The sate itself is saved in a wrapper class called Memento, which are stored in and accessed via the CareTaker.
In this approach the easiest idea is to deep-copy your objects. However this may be inefficient regarding performance and space, since you store whole objects and not the change-sets only.
Some object persistence libraries provide implementations of transactions and snapshots. Take a look at Prevayler, which is an object persistence library for java and an implementation of the prevalent system pattern. The library captures the changes to your objects in form of transactions and stores them in-memory. If you need a persistent storage of your POJOs, you can save snapshots of your objects on disk periodically and revert to them if needed.
You can find more on serializing POJOs in this SO question: Is there a object-change-tracking/versioning Java API out there?


text:
Q: Insert next line in For loop I'd like to have a next line inside my for loop, currently, what happens is that since it is inside a for loop, all the data is stored in an array and once I write it at the end of my code, it prints as one line.
fields = []
new_rows_list = []

file1 = open('CSV_sample_file.csv','rb')
reader = csv.reader(file1)

fields = reader.next()

for row in reader:
    for column in row:
        cellValue = column
        new_row = find_and_mask_cc(cellValue)
        new_rows_list.append(new_row)
file1.close()

file2 = open('CSV_sample_file2.csv', 'wb')
writer = csv.writer(file2)

writer.writerow(fields)
writer.writerow(new_rows_list)

file2.close()

What I am getting is this:
Created_User_ID__c,BRAND_Type__c,Migration_Remarks__c
EMSPDGBELNAS,test1,411111XXXXXX1111,EMSPDGCAJAPIN,test2,511111XXXXXX1111,EMSPDGNCRETES,test3,611111XXXXXX1111

My expected output is this:
Created_User_ID__c,BRAND_Type__c,Migration_Remarks__c
EMSPDGBELNAS,test1,411111XXXXXX1111
EMSPDGCAJAPIN,test2,511111XXXXXX111
EMSPDGNCRETES,test3,611111XXXXXX1111

A: You're appending all columns to the same list new_rows_list and writing it as one row with writer.writerow(new_rows_list).
You can make new_rows_list a list of lists and use writer.writerows for output instead:
...

for row in reader:
    new_row = []
    for column in row:
        cellValue = column
        new_row.append(find_and_mask_cc(cellValue))
    new_rows_list.append(new_row)
file1.close()

file2 = open('CSV_sample_file2.csv', 'wb')
writer = csv.writer(file2)

writer.writerow(fields)
writer.writerows(new_rows_list)

...

Alternatively, you can pass to writerows a generator expression that iterates through reader to write each row with columns converted by find_and_mask_cc to the output as you read it from the input, so it won't require reading the entire input into memory:
with open('CSV_sample_file.csv') as file1, open('CSV_sample_file2.csv', 'w', newline='') as file2:
    reader = csv.reader(file1)
    writer = csv.writer(file2)
    writer.writerow(next(reader))
    writer.writerows(map(find_and_mask_cc, row) for row in reader)

Demo: https://repl.it/repls/SatisfiedSardonicExponents


text:
Q: How many bytes does my function use? (C#) I would like to calculate how many bytes my function fills so that I can inject it into another process using CreateRemoteThread(). Once I know the number of bytes, I can write them into the remote process using the function's pointer. I have found an article online (see http://www.codeproject.com/KB/threads/winspy.aspx#section_3, chapter III) where they do the following in C++ :
// ThreadFunc
// Notice: - the code being injected;
//Return value: password length
static DWORD WINAPI ThreadFunc (INJDATA *pData)
{
//Code to be executed remotely
}
// This function marks the memory address after ThreadFunc.
static void AfterThreadFunc (void) {
}

Then they calculate the number of bytes ThreadFunc fills using :
const int cbCodeSize = ((LPBYTE) AfterThreadFunc - (LPBYTE) ThreadFunc);

Using cbCodeSize they  allocate memory in the remote process for the injected ThreadFunc and write a copy of ThreadFunc to the allocated memory:
pCodeRemote = (PDWORD) VirtualAllocEx( hProcess, 0, cbCodeSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE );
if (pCodeRemote == NULL)
__leave;
WriteProcessMemory( hProcess, pCodeRemote, &ThreadFunc, cbCodeSize, &dwNumBytesXferred );

I would like to do this in C#. :)
I have tried creating delegates, getting their pointers, and subtracting them like this:
    // Thread proc, to be used with Create*Thread
    public delegate int ThreadProc(InjectionData param);
    //Function pointer
    ThreadFuncDeleg = new ThreadProc(ThreadFunc);
    ThreadFuncPtr = Marshal.GetFunctionPointerForDelegate(ThreadFuncDeleg);
    //FunctionPointer
    AfterThreadFuncDeleg = new ThreadProc(AfterThreadFunc);
    IntPtr AfterThreadFuncDelegPtr= Marshal.GetFunctionPointerForDelegate(AfterThreadFuncDeleg);
    //Number of bytes
    int cbCodeSize = (AfterThreadFuncDelegPtr.ToInt32() - ThreadFuncPtr.ToInt32())*4 ;

It just does not seem right, as I get a static number no matter what I do with the code.
My question is, if possible, how does one calculate the number of bytes a function's code fills in C#?
Thank you in advance.

A: I don't think it is possible due dynamic optimization and code generation in .NET. You can try to measure IL-code length but when you try to measure machine-depended code length in general case it will fail.
By 'fail' I mean you can't get correct size that provide any meaning by using this technique dynamically.
Of course you can go with finding how NGEN, JIT compile works, pdb structure and try to measure. You can determine size of your code by exploring generated machine code in VS for example.
How to see the Assembly code generated by the JIT using Visual Studio

If you really need to determine size, start with NET Internals and Code Injection / NET Internals and Native Compiling but I can't imagine why you ever want it.

Be aware all internals about how JIT works exactly is subject to change so depending solution can be broken by any future version of .NET.

If you want to stick with IL: check Profiling Interfaces (CLR Profiling API), and a bit old articles:  Rewrite MSIL Code on the Fly with the .NET Framework Profiling API and No Code Can Hide from the Profiling API in the .NET Framework 2.0. There are also some topics about CLR Profiling API here on SO.

But simplest way to explore assembly is Reflection API, you want MethodBody there. So you can check Length of MethodBody.GetILAsByteArray and you'll find method length in IL-commands.


text:
Q: A Variable doesn't exist in the current context (I'm a beginner and just started learning C# in college/A-level, so my code is really inefficient).
Anyway, the code below is just a part of my "CinemaBookingSystem" and because my variable filmName is declared outside of my switch case, it says that "filmName" does not do not exist in this context. I tried using the "public static string filmname = "example";" method but that won't work because I'm declaring filmname more than once inside different if statements.
if (filmNum == 1)
    string filmName = "Teenage Horror Film";
if (filmNum == 2)
    ;
string filmName = "How I Live Now";
switch (filmNum)
{
    case 1:
    case 2:
        if (Age >= 15)
        {
            Console.WriteLine("What date do you want to watch the film? (Format : dd/mm/yyyy) :");
            DateTime dateChoice = DateTime.Parse(Console.ReadLine());
            DateTime now = DateTime.Now;
            DateTime limit = now.AddDays(7);
            if (dateChoice >= now && dateChoice <= limit)
            {
                Console.WriteLine("--------------------");
                Console.WriteLine("Aquinas Multiplex");
                Console.WriteLine("Film : {0}", filmName);
                Console.WriteLine("Date : {0}", dateChoice);
                Console.WriteLine("--------------------");
            }
            else
            {
                Console.WriteLine("Access denied - date is invalid");
            }
        }

        while (Age < 15)
        {
            Console.WriteLine("Access denied - You are too young");
        }
        break;
}

A: Kenny, since you declare variable filmName in condition statement it is not accessible in switch. You need to declare it before if:
string filmName = string.empty;
if (filmNum == 1) ;
        {
            filmName = "Teenage Horror Film";
        }
        if (filmNum == 2) ;
        {
            filmName = "How I Live Now";
        }

        switch (filmNum)
        {
            case 1: case 2:
                if (Age >= 15)
                {
                    Console.WriteLine("What date do you want to watch the film? (Format : dd/mm/yyyy) :");
                    DateTime dateChoice = DateTime.Parse(Console.ReadLine());
                    DateTime now = DateTime.Now;
                    DateTime limit = now.AddDays(7);
                    if (dateChoice >= now && dateChoice <= limit)
                    {
                        Console.WriteLine("--------------------");
                        Console.WriteLine("Aquinas Multiplex");
                        Console.WriteLine("Film : {0}", filmName);
                        Console.WriteLine("Date : {0}", dateChoice);
                        Console.WriteLine("--------------------");
                    }
                    else
                    {
                        Console.WriteLine("Access denied - date is invalid");
                    }
                }

                while (Age < 15)
                {
                    Console.WriteLine("Access denied - You are too young");
                }
                break;

        }
    }
}

A: You need to declare it outside of the if statements and just asign the value inside (make sure there is a default value in case neither if gets triggered).
Also you have semicolons right behind your if statements.


text:
Q: Executable not recognized in PowerShell. Possible issue with accented characters in path? I am trying to customize my PowerShell prompt in Windows Terminal using Oh My Posh.
I am following the docs but can't understand what I am missing. As instructed by the Oh My Posh docs, after the installation, I am adding the following to $PROFILE:
oh-my-posh --init --shell pwsh --config ~\AppData\Local\Programs\oh-my-posh\themes\paradox.omp.json | Invoke-Expression

I get the following error:
& : The term 'C:\Users\José Aniceto\AppData\Local\Programs\oh-my-posh\bin\oh-my-posh.exe' is not recognized as the
name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and try again.
At line:1 char:5
+ (@(&"C:\Users\José Aniceto\AppData\Local\Programs\oh-my-posh\bin\oh- ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\Users\José ...\oh-my-posh.exe:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Invoke-Expression : Cannot bind argument to parameter 'Command' because it is an empty string.
At line:1 char:158
+ ... sh --config="C:\Users\Jos[char]130]") -join "`n") | Invoke-Expression
+                                                         ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:String) [Invoke-Expression], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.Invo
   keExpressionCommand

If I navigate to the path, the executable is there. Seems to be a problem with the path. As you can see it has a special character (é) and a space.
How can I solve this? I have tried several things with encoding, inputting the characters as ASCII, etc. but nothing seems to work.


text:
Q: Managed package report(s) missing in production Got a problem: in our organization we have 1 production and 1 full sandbox. In both we have a same application with same version. Today users started to complain that they couldn't get access to one of the reports that is included to managed package. Tried to find the report in production through workbench including deleted items, also checked recycling bin - was not able to find the report. Meanwhile in sandbox the report's on the place, I see it in my "reports" tab. The applicaiton in prod and sandbox has same last modified date, which's almost half a year ago. Clicking "View Components" in production, I don't see the report, while doing the same in sandbox, I see the report. Also tried to copy Id from SB and paste it to production - see the error "Data Not Available".
Question is - how it could be, that managed package report is not visible (or deleted) in production, but visible in sandbox?
Added:
Sandbox package:

Production package:

A: The problem was in that a person moved the report to his private folder, thanks to Rahul Sharma for pointing out to this document. You could find in what folder it is stored following the link. The report will have different Id and will no longer be marked as a part of managed package.


text:
Q: how to write test cases using iframe in robot framework My html code is

Press ALT 0 for help

Press ALT 0 for help**
**

my scripts look like
select frame=//*[@id="cke_1_contents"]

A: Typically you should call the Select Frame keyword, giving it a locator for the frame. In your case it might look something like this:
Select frame   //iframe[@id="cke_1_contents"]


text:
Q: Product of metric outer measures The problem below has been asked recently already but, as a naive user, I got burned (well singed perhaps) because I asked the question in the wrong place.  So if this looks like a redundant question ... excuse me (as Steve Martin would say)!
Problem:  Show that the product of two metric outer measures (also known as Borel measures on a metric space) is again a metric outer measure.
Does anyone know if the problem is valid?
The hints given already on this forum work only for the separable case, but I don't have a solution to the general case.
I found the problem originally in the text by Munroe (Measure and Integration 1953). It seemed that the obvious approach would work so I added it without further thought to our book (Real Analysis, Bruckner/Bruckner/Thomson 1996). We received some valuable feedback from many sources, mostly from R. B. Burckel who pointed out among many other things that this problem was not straightforward and may be wrong. For the second 2008 edition I left the problem (since it is interesting) but included a footnote to indicate that there was some doubt.
Anybody have a definitive answer?
The problem appears as Exercise 6:1.5. in our 2nd edition. You can get a free PDF from the website classicalrealanalysis.com.
Hope to hear from someone (not, I hope, from someone assigned this problem because it appeared in our first edition--if so blame Munroe -- please).
Brian

A: Let $\kappa$ be real valued measurable with a witnessing probability measure $\mu$. Put discrete metric on $\kappa$. So $(\kappa, \mu)$ is a metric outer measure (being a total measure). Form the product $(\kappa^2 = \kappa \times \kappa, \nu = \mu \times \mu)$ in the sense of Defn 6.1 of OP. Let $A = \{(\alpha, \beta) : \alpha \leq \beta < \kappa\}$. Then for every $\mu \otimes \mu$-measurable set $W$, if $W \supseteq A$, then $(\mu \otimes \mu)(\kappa^2 \setminus W) = 0$ (Fubini's theorem). So $\nu(A) = 1$. Similarly, $\nu(\kappa^2 \setminus A) = 1$. So $(\kappa^2, \nu)$ is not a metric outer measure.
I will edit when I have a ZFC example.
Edit: Here's a sketch for the necessity of real valued measurable cardinals (rvm). Assume there is no rvm. Given $(X, \mu)$ where $X$ is metric and $\mu$ is a Borel probability measure on it, consider the subset $Y = \{x \in X : (\forall r > 0)(\mu(B(x, r)) > 0)\}$ (here, $B(X, r)$ is the open ball centered at $x$ of radius $r$). $Y$ is clearly separable. Also, $X \setminus Y$ is $\mu$-null (since otherwise there is an rvm). So $\mu$ is supported on a separable subspace of $X$ and we can argue as in the case of metric outer measures on separable metric spaces.


text:
Q: How to deal with "Cannot export init__init__: symbol not defined" I was to install the python package "wheezy.template" on my 64bit windows.
Here is what it shows after $pip install wheezy.template$.  How to solve it?
building 'wheezy.template.utils' extension

C:\anaconda\MinGW\bin\gcc.exe -DMS_WIN64 -mdll -O -Wall -IC:\Anaconda\include -IC:\Anaconda\PC -c src\wheezy\template\utils.c -o build\temp.win-amd64-2.7\Release\src\wheezy\template\utils.o

src\wheezy\template\utils.c: In function '__Pyx_RaiseArgtupleInvalid':

src\wheezy\template\utils.c:2100:18: warning: unknown conversion type character 'z' in format [-Wformat]

src\wheezy\template\utils.c:2100:18: warning: format '%s' expects argument of type 'char *', but argument 5 has type 'Py_ssize_t' [-Wformat]

src\wheezy\template\utils.c:2100:18: warning: unknown conversion type character 'z' in format [-Wformat]

src\wheezy\template\utils.c:2100:18: warning: too many arguments for format [-Wformat-extra-args]

writing build\temp.win-amd64-2.7\Release\src\wheezy\template\utils.def

C:\anaconda\MinGW\bin\gcc.exe -DMS_WIN64 -shared -s build\temp.win-amd64-2.7\Release\src\wheezy\template\utils.o build\temp.win-amd64-2.7\Release\src\wheezy\template\utils.def -LC:\Anaconda\libs -LC:\Anaconda\PCbuild\amd64 -lpython27 -lmsvcr90 -o build\lib.win-amd64-2.7\wheezy\template\utils.pyd

building 'wheezy.template.__init__' extension

C:\anaconda\MinGW\bin\gcc.exe -DMS_WIN64 -mdll -O -Wall -IC:\Anaconda\include -IC:\Anaconda\PC -c src\wheezy\template\__init__.c -o build\temp.win-amd64-2.7\Release\src\wheezy\template\__init__.o

writing build\temp.win-amd64-2.7\Release\src\wheezy\template\__init__.def

C:\anaconda\MinGW\bin\gcc.exe -DMS_WIN64 -shared -s build\temp.win-amd64-2.7\Release\src\wheezy\template\__init__.o build\temp.win-amd64-2.7\Release\src\wheezy\template\__init__.def -LC:\Anaconda\libs -LC:\Anaconda\PCbuild\amd64 -lpython27 -lmsvcr90 -o build\lib.win-amd64-2.7\wheezy\template\__init__.pyd

Cannot export init_init_: symbol not defined

collect2.exe: error: ld returned 1 exit status

error: command 'gcc' failed with exit status 1


text:
Q: How to read property file with custom separator using Spring I have a property file as below
Key1~~value1
Key2~~value2

How to read this custom separator property file using Spring.
Spring @PropertySource can read the property files with keys and values separated by = or :.

A: On the presumption that you are using a created properties file. You can use the setGlobalSeparator(String globalSeparator) method of PropertiesConfigurationLayout and change the separator to use ~~. Per the documentation, it will overwrite the existing configuration layout to set the new global separator.
Something like this:
PropertiesConfiguration propertiesConfig = new PropertiesConfiguration("test.properties");
PropertiesConfigurationLayout layout = new PropertiesConfigurationLayout(propertiesConfig);
layout.setGlobalSeparator("~~");
propertiesConfig.setLayout(layout);


text:
Q: Electric charge conservation in a superconductor In a superconductor, $U(1)$ gauge symmetry is spontaneously broken. But $U(1)$ gauge symmetry is responsible for conservation of electric charge. Then it appears to me that the electric charge conservation will be violated which is surely wrong. But I cannot understand how the electric charge remain conserved?
Weinberg says here that

The conservation of a current is usually a symptom of some symmetry of the underlying theory, and holds whether or not the symmetry is spontaneously broken.

A: Let me explain @ACuriousMind 's answer with some verbiage.
The short, regrettably oracular, answer is that the Fabri-Picasso theorem does not hold in a finite superconductor, since translational invariance fails at its boundaries. Really, I do appreciate this is aggressively obscure: will strive to explain.
First of all, if you have a chunk of warm superconducting material within an "observation sphere", you could assess the charge of the sphere's contents by Gauss's law. Lowering the material's temperature to a superconductor will not magically create or annihilate charge inside your sphere because somehow U(1) was broken, as you anticipated. In fact, there are (conserved) electric currents that can flow through the superconductor,
or course. That's why we love them! You don't even need to measure them directly, as it is precisely such cost-free current loops that arise to oppose and completely cancel an external magnetic field, by Lenz's law, and so exclude it from the bulk of the material, at least beyond a penetration length $\xi$.
So what about the "breaking" of the symmetry? (This is the best argument against using this term, to start with, instead of "hiding" or something less inflammatory.) The point is, as you might see in the WP article cited above, that the symmetry is still there, it's certainly not gone, and its current is conserved! It is just that the symmetry is realized in the nonlinear Nambu-Goldstone  mode ($\theta$) which manifests itself somewhat unconventionally, if not obscurely, $\delta \theta\propto \epsilon$.
Something terrible happens when one takes the space integral of the zeroth component of the current to yield infrared divergent answers, even though you could rehabilitate these answers by sticking them in a commutator with fields, in which case they produce the nonlinear transformations of the fields mentioned. A brief proof of this pathology is the F-P argument  of the Zen gambit above, but it requires translational invariance, luckily broken (explicitly) by the boundaries of the finite superconductor! The takeaway is that one may, humbly and carefully, talk about conserved charges and certainly conserved currents.
In a superconductor, you have in addition what we now call the Higgs mechanism. (This gem of an article by the late T Kibble, explains the above difficulties in defining Q in infinite, relativistic theories, which are not our concern here.) The London brothers, in 1935, discovered their eponymous phenomenological equation, $ \overrightarrow{J}= - \overrightarrow{A}/\xi^2$, so the London gauge $  \overrightarrow{\nabla}\cdot  \overrightarrow{A}=0$ is actually current conservation $ \overrightarrow{\nabla}\cdot  \overrightarrow{J}=0$.


text:
Q: Custom javascript is not allowed to run on Salesforce DOM Recently i have created an app which uses custom JavaScript in sidebar home page component using custom links, The app works perfectly and i also uploaded it to appexchange as managed released package and submitted it to review by salesforce.
Unfortunately review is negative saying Custom javascript is not allowed to run on Salesforce DOM. Below is details

1) Javascript in Salesforce DOM Vulnerability
Notes
Custom javascript is not allowed to run on Salesforce DOM.
Please check the requirement checklist for more information
https://developer.salesforce.com/page/Requirements_Checklist

Please guide how to resolve this.
**Custom Link Body:**
{!REQUIRESCRIPT('/soap/ajax/29.0/connection.js')}
{!REQUIRESCRIPT('/resource/customjavascript')}


text:
Q: Android - Error while writing file to external storage I was trying to create a simple .txt file in external storage, but I got nullPointerException, here is the code and error log, I'm not sure what I did wrong:
MainActivity:
package com.externalstoragedemo;

import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    TextView textView = (TextView)findViewById(R.id.textView);
    File dir;
    File file;
    String Text = "File has been created!";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if(isExternalStorageReadable() && isExternalStorageWriteable()){
            dir = new File (Environment.getExternalStorageDirectory().toString() + "/Documents");
            dir.mkdirs();

            file = new File(dir, "Simple.txt");
        }

        FileOutputStream fos = null;
        try{
            fos = new FileOutputStream(file);
            fos.write(Text.getBytes());
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(fos != null){
                try {
                    fos.close();
                    textView.setText(Text);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public boolean isExternalStorageReadable(){
        String state = Environment.getExternalStorageState();
        if(Environment.MEDIA_MOUNTED.equals(state) ||
                Environment.MEDIA_MOUNTED_READ_ONLY.equals(state))
        {
            return true;
        }else {
            return false;
        }
    }

    public boolean isExternalStorageWriteable(){
        String state = Environment.getExternalStorageState();
        if(Environment.MEDIA_MOUNTED.equals(state)){
            return true;
        }else{
            return false;
        }
    }

}

LayoutFile:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.externalstoragedemo.MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

ErrorLOG:

08-26 20:54:32.161 24298-24298/com.externalstoragedemo
  E/AndroidRuntime: FATAL EXCEPTION: main
                                                                           Process: com.externalstoragedemo, PID: 24298
                                                                           java.lang.RuntimeException: Unable to instantiate activity
  ComponentInfo{com.externalstoragedemo/com.externalstoragedemo.MainActivity}:
  java.lang.NullPointerException
                                                                               at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2174)
                                                                               at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2298)
                                                                               at android.app.ActivityThread.access$800(ActivityThread.java:144)
                                                                               at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                               at android.os.Looper.loop(Looper.java:212)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:5151)
                                                                               at java.lang.reflect.Method.invokeNative(Native Method)
                                                                               at java.lang.reflect.Method.invoke(Method.java:515)
                                                                               at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:684)
                                                                               at dalvik.system.NativeStart.main(Native Method)
                                                                            Caused by: java.lang.NullPointerException
                                                                               at
  android.support.v7.app.AppCompatDelegateImplBase.(AppCompatDelegateImplBase.java:120)
                                                                               at
  android.support.v7.app.AppCompatDelegateImplV9.(AppCompatDelegateImplV9.java:155)
                                                                               at
  android.support.v7.app.AppCompatDelegateImplV11.(AppCompatDelegateImplV11.java:31)
                                                                               at
  android.support.v7.app.AppCompatDelegateImplV14.(AppCompatDelegateImplV14.java:55)
                                                                               at
  android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:205)
                                                                               at
  android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:185)
                                                                               at
  android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:519)
                                                                               at
  android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
                                                                               at com.externalstoragedemo.MainActivity.(MainActivity.java:14)
                                                                               at java.lang.Class.newInstanceImpl(Native Method)
                                                                               at java.lang.Class.newInstance(Class.java:1208)
                                                                               at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
                                                                               at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2165)
                                                                               at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2298)
                                                                               at android.app.ActivityThread.access$800(ActivityThread.java:144)
                                                                               at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                               at android.os.Looper.loop(Looper.java:212)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:5151)
                                                                               at java.lang.reflect.Method.invokeNative(Native Method)
                                                                               at java.lang.reflect.Method.invoke(Method.java:515)
                                                                               at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:684)
                                                                               at dalvik.system.NativeStart.main(Native Method)

A: Pass this to the inside of the onCreate method:
TextView textview;
...
 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.textView);
...


text:
Q: Is set.seed consistent over different versions of R (and Ubuntu)? I am currently running R version 3.1.0 (on Ubuntu 12.04 LTS) and as both my R version and my operating system is getting rather old, I plan on updating both. However, I have a lot of simulations that rely on set.seed() and I would like them to still give me the same random numbers after updating both R and my operating system.
So my question is three-fold.

*

*Can I update R without changing which numbers are generated from each seed?

*Can I do the same for my operating system?

*If no to either 1) or 2), is there a way to change the seeds in my code in such a way that they are consistent with the olds seeds?

A: Cross-OS consistency: yes
If you installed R on two different operating systems without manually changing defaults or the RProfile, you should get the same results when using set.seed().
Consistency over versions of R: not necessarily
It used to be the case that set.seed() would give the same results across R versions, but that's no longer generally true thanks to a little-announced update in R 3.6.0. So you can get cross version consistency comparing results before R 3.6.0, but if you compare a post-3.6.0 use of set.seed() to a pre-3.6.0 use of set.seed(), you will get different results.
You can see that in the examples below:
R 3.2.0
> set.seed(1999)
> sample(LETTERS, 3)
[1] "T" "N" "L"

R 3.5.3
> set.seed(1999)
> sample(LETTERS, 3)
[1] "T" "N" "L"

R 3.6.0
set.seed(1999)
sample(LETTERS, 3)
[1] "D" "Z" "R"

The reason for the inconsistency is that in R 3.6.0, the default kind of under-the-hood random-number generator was changed. Now, in order to get the results from set.seed() to match, you have to first call the function RNGkind(sample.kind = "Rounding").
R 3.6.0
> RNGkind(sample.kind = "Rounding")
Warning message:
In RNGkind(sample.kind = "Rounding") : non-uniform 'Rounding' sampler used
> set.seed(1999)
> sample(Letters, 3)
[1] "T" "N" "L"

A: Having tested on several R versions (3.1.0, 3.3.1, 3.4.2) and two different machines (Windows 7 x64, Windows 10 x64), I got the same runif() random numbers with the same set.seed() independently of the R versions and the operating system. As far as I know, this suggests a yes for both questions 1 and 2.

A: As stated in accepted answer, the default algorithm for sampling changed from version 3.6.0 onwards:

sample.kind can be "Rounding" or "Rejection", or partial matches to these. The former was the default in versions prior to 3.6.0: it made sample noticeably non-uniform on large populations, and should only be used for reproduction of old results. See PR#17494 for a discussion.

In R versions 3.6.0 and later, you can keep consistency by using the older algorithm in a one liner:
set.seed(<seed_number_here>, sample.kind = "Rounding")

Notice that sample.kind option was added in 3.6.0 so you cannot use the newer, better method on older R versions (that is, set.seed(<seed_number_here>, sample.kind = "Rejection") does not work in R versions prior to 3.6.0).


text:
Q: How do I manually transform an IPv4 address into an IPv6 address? I would like to know if there is any manual method in transforming an IPv4 address to an IPv6 address without the use of an conversion calculator or tool. For example:
I have an IPv4 address and it is given as:
129.130.100.11
and when it is transformed the answer is given as:
0::FFFF:8182:640B
Are there any formula used to perform such transformation?
Any help would be nice.

A: For IPv6, the octets are usually represented as hexadecimal numbers, whereas IPv4 uses decimal.  So, an extremely simplified method is to first convert each of the decimal octets (8 bits) to hexadecimal:
129 becomes 81
130 becomes 82
100 becomes 64
11 becomes 0B

Then concatenate the results with a colon between the first two and the last two octets:
8182:640B

And add ::FFFF: to the front of the string:
::FFFF:8182:640B

There are however a few different formats for an IPv6 address.  I left these out above as you can see they all include some type of decimal-hexadecimal conversion and some simple string formatting.  Other alternatives include:

*

*6 to 4 address:

*

*2002:8182:640B:0:0:0:0:0

*2002:8182:640B::

*IPv4-mapped address:

*

*0:0:0:0:0:FFFF:129.130.100.11

*::FFFF:129.130.100.11

*::FFFF:8182:640B

*IPv4-compatibility address:

*

*0:0:0:0:0:0:129.130.100.11

*::129.130.100.11

*::8182:640B

A: While the other answer is correct as well, a valid IPv6 address may end with decimal rts as well, exactly in order to provide this sort of things.
You can just write
::FFFF:129.130.100.11

and you are done.


text:
Q: Get information profile user from Facebook in my Android class After reading some posts related with this subject I cannot solve my doubt.
In my app, I log in with Facebook (Registration.class) and app starts in MainActivity.class .
In this class, I want to get some information about user  like 'user_ID' to get image profile user and 'user_first_name', both are useful to put this information in the Navigation Drawer.
My problem is that I get this information in Registration.class with this code:
profileTracker = new ProfileTracker() {
            @Override
            protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
                // App code
                Log.i("PERFIL_NAME", Profile.getCurrentProfile().getFirstName());
                Log.i("PERFIL_FOTO", Profile.getCurrentProfile().getProfilePictureUri(100, 100).toString());
                Log.i("USER_ID", Profile.getCurrentProfile().getId());
            }
        };

but I do not know how I have to get it in MainActivity.class.
If I use this in the same way I get null. Also, I have tested with an Intent and it does not work because it is null too (I suppose that Intent is executed before than profileTracker()).
Moreover, I have tried some methods in MainActivity like:
public void putImageProfile() {
    URL imgUrl = null;
    try {
        imgUrl = new URL("http://graph.facebook.com/'user_ID'/picture?type=large");
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    InputStream in = null;
    try {
        in = (InputStream) imgUrl.getContent();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Bitmap  bitmap = BitmapFactory.decodeStream(in);
    img_profile.setImageBitmap(bitmap); //ImageView in NavDrawer
}

('user_ID' is my user ID profile Facebook written manually 1000098...) and it does not work well.
In conclusion, I want to get 'user_ID' and 'user_name' in MainActivity.class ... and after, to get the image profile with the 'user_ID'.
Thank so much.


text:
Q: Certificate chain validation using java, checking revokation and OCSP status I am new to the world of PKI , certificates in general. I am writing a service which needs to validate a chain of certiticates.
The general approach taken is as follows
a)  Generate a List of certificates from the data sent
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);

CertPathValidatorResult certPathValidatorResult = null;
try {

  CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
  List<X509Certificate> x509Certificates =
      (List<X509Certificate>) certificateFactory.generateCertificates(byteArrayInputStream);

  CertPath certPath = certificateFactory.generateCertPath(x509Certificates);

*Load the JDK keystore, with something like this
//Load the JDK's cacerts keystore file
String filename =
System.getProperty("java.home")
+ "/lib/security/cacerts".replace('/', File.separatorChar);
FileInputStream is = new FileInputStream(filename);
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
String password = "changeit";
keystore.load(is, password.toCharArray());

*
CertPathValidator certPathValidator = CertPathValidator.getInstance("PKIX");

PKIXParameters pkixParameters = new PKIXParameters(keystore);
//pkixParameters.setRevocationEnabled(false);

PKIXParameters certPathValidatorResult = certPathValidator.validate(certPath, pkixParameters);

*I am assuming if this is not a valid chain it would throw an exception. Would this validation check expired Certificates, Valid Public Key ?

*also I need to be able to find the the OCSP staus of a certificate or check if it is revoked>? How can this be done using the Cryptography API

*Is the use fo bouncy castle recommended over the API ? Does Bouncy castle have a way to check CRL and OCSP status of a certificate?
Thanks for all the pointers and help in advance. Appreciate it.
Best  Regards

A: *

*It's correct, you can use CertificateFactory to load certificates chain.

*If you want validate a chain of certiticates, you don't need a KeyStore. The certificates are validated with the certificate of autority who emit that certificate.
For example:

ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(chain.getBytes());
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
List<X509Certificate> x509Certificates = (List<X509Certificate>) certificateFactory.generateCertificates(byteArrayInputStream);
x509Certificates.get(1).verify(x509Certificates.get(0).getPublicKey());

*In this case you can use it to validate a certificate if you don't know the root ca.

*You can check the period with

x509Certificates.get(1).getNotBefore()

and
x509Certificates.get(1).getNotAfter()

*Is important validate the status of certificate.

*Yes BouncyCastle is great library for it.


text:
Q: How to add selected Items from a listbox into a table? I am still new to VBA and would appreciate some help.
I need to add the selected items from the listbox into a table, but every time I try the displayed table has no values in it.
Here is the code:
Private Sub BefehlX_Click()

    Dim db As Database
    Dim rs As Recordset
    Dim qdf As QueryDef
    Dim varItem As Variant
    Dim strCriteria As String
    Dim strSQL As String
    Dim lstBox As ListBox`

    DoCmd.SetWarnings (False)

    Set db = CurrentDb()
    Set rs = db.OpenRecordset("T_Auswertung", dbOpenDynaset)
    Set qdf = db.QueryDefs("Abfrage4")
    Set lstBox = Me!ListField1

    For Each varItem In lstBox.ItemsSelected
        strCriteria = strCriteria & ",'" & lstBox.ItemData(varItem) & "'"
        rs.AddNew

        'what should be placed here?`

        rs.Update
    Next varItem
    Set rs = Nothing

    If Len(strCriteria) = 0 Then
       MsgBox "Sie haben keine Queues gewählt!" _
             , vbExclamation, "Nichts zu finden!"
       Exit Sub
    End If
    strCriteria = Right(strCriteria, Len(strCriteria) - 1)

    DoCmd.SetWarnings (True)

End Sub

A: If you want to store all values in a single string split by ",", then move the rs.AddNew to outside the For cycle:
For Each varItem In lstBox.ItemsSelected
    strCriteria = strCriteria & ",'" & lstBox.ItemData(varItem) & "'"
Next varItem

'removes first ","
strCriteria = Right(strCriteria , Len(strCriteria ) - 1)

rs.AddNew
rs!NAME_OF_FIELD = strCriteria
rs.Update

If you want to store all values in separate registries (so ID = 1 has one itemselected, and ID = 2 has the next one, and so on) keep the add inside the For cycle:
For Each varItem In lstBox.ItemsSelected
    strCriteria =  lstBox.ItemData(varItem)
    rs.AddNew
    rs!NAME_OF_FIELD = strCriteria
    rs.Update
Next varItem


text:
Q: Did CREATE TABLE IF NOT EXISTS create the table? import sqlite3
connection = sqlite3.connect("...")
cursor = connection.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS ...")

How can I find out, after executing the CREATE TABLE IF NOT EXISTS, whether the table was created or already in place?

A: EDIT: Updated answer
It sounds like you don't know beforehand what tables might exist, what those tables have in them (if anything), or have a way to check beforehand if tables exist.
To check if a table was created after using the IF NOT EXISTS clause on a CREATE TABLE command, you could try one of these:

*

*Make the "new" table have at least one column name that is guaranteed to be different from the old table. After the CREATE TABLE command, you select the column guaranteed to be new.
CREATE TABLE newTable IF NOT EXISTS (column1 INTEGER, somethingUnique INTEGER)
SELECT somethingUnique FROM newTable
If you don't get back an error from selecting somethingUnique, then you know that you have created a new table, else the table already existed. If you end up creating a new table and do not want that somethingUnique column anymore, then you can just delete that column.

*Even if you don't want to make a somethingUnique column, there is the possibility that if the old table existed, it would have at least one row in it already. All you have to do is select anything from the table. If nothing returned, then you may or may not be dealing with your new table (so go back to suggestion 1). If something does get returned, then you know that you are dealing with an old table.
Old answer
One way to see if the table was created (or exists) is to go into a terminal, navigate to the directory where your database is, and then use sqlite commands.
$ sqlite3
sqlite> .open yourDatabase.db
sqlite> SELECT * FROM theTableYouWantedToCreate;

If the table does not exist, you would get back the following error:
Error: no such table: theTableYouWantedToCreate

If the table did exist, obviously it would return everything that is in the table. If nothing is in the table (since you just created it), sqlite will give you back another prompt, indicating that the table does indeed exist.

A: The only way to check is by removing the IF NOT EXISTS part of the query and checking for a sqlite3.OperationalError with a message of the form "table $tablename already exists". I wouldn't trust the error message to be stable, but Python apparently does not supply an error code along with the exception.
The safest thing to do would be to begin a transaction and query the sqlite_master table beforehand, create the table if there were no results, then commit the transaction.
Note that none of these solutions will work correctly if the table you are attempting to create has a different schema than the one that exists in the database; database migrations are more complicated and usually require case-by-case handling.


text:
Q: Delete rows where a row.cell has a specific string with VBA I have an Excel file with 390 rows. On the fifth column there are only two strings. It is either "YES" or "NO". So, I am trying to delete the rows, if the cell in the fifth column contains "NO" using VBA. I can do that by using filters and then use a macro to delete the hidden rows, but I want to find a way to do it in VBAs without using the filters. I want to learn it better and also keep the file for future use.
I have tried to use some scripts I found on stack, but they do not work. Most of them are for integers and not for strings. I have tried this one but it does not work:
Sub Delete_Rows_With_Specific_String_In_Cell()
  Dim myRow As Long
  Dim myCounter As Long
  myRow = 390
  For myCounter = myRow To 1 Step -1
    If Cells(myCounter, 5).Value = "NO" Then
        Rows(myCounter).Delete
    End If
  Next
End Sub

I tried putting a second For for the column but it did not work either. I would like to find a solution on what I have already written. I might be able to find other scripts on the internet, but I want to make it work based on this code.

A: http://analysistabs.com/vba/delete-row-if-cell-contains-string-excel-macro-example-code/
This solution works
Perhaps you're not inserting as a module?

A: Another way to delete rows, which may be a little quicker (I haven't tested so don't quote me on that) - figure out which rows need deleting first, union the ranges and delete them all in one go.
Sub Delete_Rows_With_Specific_String_In_Cell()

    Dim myRow As Long
    Dim myCounter As Long
    Dim rngDeletion As Range
    myRow = 390

    With ThisWorkbook.Worksheets("Sheet1")
        For myCounter = 1 To myRow
            If .Cells(myCounter, 5).Value = "NO" Then
                If rngDeletion Is Nothing Then
                    Set rngDeletion = .Rows(myCounter)
                Else
                    Set rngDeletion = Union(rngDeletion, .Rows(myCounter))
                End If
            End If
        Next
    End With

    rngDeletion.Delete

End Sub

Note:  I've used the With keyword in the code to ensure I'm referencing the correct sheet all the time.
See https://msdn.microsoft.com/en-us/library/wc500chb.aspx for an explanation of With... End With.


text:
Q: Inserting repeated records into Big Query with Java API/Dataflow - "Repeated field must be imported as a JSON array" I have data with repeated key-value (String,String) record pairs as one of the fields in a Big Query table schema.
I am trying to add these repeated records using the approach here: http://sookocheff.com/post/bigquery/creating-a-big-query-table-java-api/
The table schema created for the repeated record field looks like this:
TableFieldSchema column = new TableFieldSchema().setName("rawFields");
column.setType("RECORD");
List<TableFieldSchema> list = new ArrayList<>();
list.add(new TableFieldSchema().setName("key").setType("STRING"));
list.add(new TableFieldSchema().setName("value").setType("STRING"));
column.setFields(list);
column.setMode("REPEATED");

I am inserting data like this as part of a DoFn:
Map<String,String> record = ... // key-value pairs
List<TableRow> rawFields = new ArrayList<>();
record.forEach((k,v)->
    rawFields.add(new TableRow().set("key",k).set("value", v))
);
TableRow row = new TableRow();
// row has other fields, omitted here
row.set("rawFields", rawFields);

The DoFn is in my dataflow pipeline just before the BigQueryIO.Write:
.apply(BigQueryIO.Write
        .named("WriteLBLogLines")
        .to("xxx:yyy.zzz")
        .withSchema(mySchema)
        .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_APPEND)
        .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED));

When I try and run this through Dataflow I get the following error:
errorResult: JSON table encountered too many errors, giving up. Rows: 1; errors: 1., error: JSON table encountered too many errors, giving up. Rows: 1; errors: 1., error: JSON parsing error in row starting at position 0 at file: gs://xxxxxxxxxx/12271006010671464167/dax-tmp-2016-06-28_14_47_26-12271006010671462904-S04-1-303c4f638f6b411b/-shard-00002-of-00003-try-021aff4c448b3177-endshard.json. Repeated field must be imported as a JSON array. Field: rawFields.

What is wrong with my approach? It seems I am not using the right approach for inserting repeated records.

A: I've attempted to reproduce the problem with the following code, but it executes successfully.  Are there other aspects of the schema that could be at issue?
List<TableFieldSchema> fields = new ArrayList<>();
TableFieldSchema column = new TableFieldSchema().setName("rawFields");
column.setType("RECORD");
List<TableFieldSchema> list = new ArrayList<>();
list.add(new TableFieldSchema().setName("key").setType("STRING"));
list.add(new TableFieldSchema().setName("value").setType("STRING"));
column.setFields(list);
column.setMode("REPEATED");
fields.add(column);
TableSchema schema = new TableSchema().setFields(fields);

TableRow row = new TableRow();
List<TableRow> rawFields = new ArrayList<>();
rawFields.add(new TableRow().set("key","foo").set("value", "bar"));
row.set("rawFields", rawFields);

Pipeline p = Pipeline.create(options);
PCollection<TableRow> c =
    p.apply(Create.of(row, row).withCoder(TableRowJsonCoder.of()));
c.apply(BigQueryIO.Write.named("BigQuery-Write")
        .to(options.getOutput())
        .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED)
        .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_TRUNCATE)
        .withSchema(schema));
p.run();


text:
Q: Filtering objects with many to many relationships I have a two tables one for documents one for mapping to categories.
Documents
id | document_name
1  | somename.doc
2  | anothername.doc

Documents_to_categories
cat_id | doc_id
10     | 1
10     | 2
11     | 3
12     | 1

Some documents can map to multiple categories. What I want is to be able to select documents that belong in multiple categories, like in a filtering scheme.
Basically in the script I have an array of document id's that were a result from a search. I need to filter those documents down based on categories.
This is what something like what I'm aiming for (I know it doesn't work but for example).
SELECT *
 FROM Documents_to_categories A
 JOIN Documents B ON A.doc_id = B.id
WHERE B.id IN (6703,6614,2286)
  AND A.cat_id = :ID0
  AND A.cat_id = :ID1

Edit: Sorry for all those who answered, my first time posting, was unclear with question. Hopefully this is more clear on what I want.

A: select a.doc_id, count(*)
from Documents_to_categories A
where a.doc_id in (<doc_id list>)
and a.cat_id in (<cat_id list>)
group by doc_id
having count(*) = <cat_id list length>

will return a list of doc_ids that have an entry for every category in the cat_id list. Note that you also need to supply the length of the list for the having clause.
You can use this to retrieve all of the details required in an outer select, using the select above to populate an inlist for the doc_ids.
This ends up looking like :
select b.id, b.document_name, a,cat_id
from Documents_to_categories A,
Documents B
where a.doc_id = b.id
and b.id in (select mylist.doc_id from (
    select a.doc_id, count(*)
    from Documents_to_categories A
    where a.doc_id in (<doc_id list>)
    and a.cat_id in (<cat_id list>)
    group by doc_id
    having count(*) = <cat_id list length>

) as mylist )

A: Assuming you're passing in the list of document id's as a comma separated list, the simplest solution would be to use dynamic SQL:
L_CURSOR SYS_REFCURSOR;
L_QUERY  VARCHAR2(5000) DEFAULT 'SELECT d.document_name
                                   FROM DOCUMENTS d
                                   JOIN DOCUMENTS_TO_CATEGORIES c10 ON c10.doc_id = d.id
                                                                   AND c10.cat_id = 10
                                   JOIN DOCUMENTS_TO_CATEGORIES c12 ON c12.doc_id = d.id
                                                                   AND c12.cat_id = 12
                                  WHERE d.id IN (:document_list)'

BEGIN

  FOR I IN 0 .. (TRUNC(LENGTH(L_QUERY) / 255)) LOOP
    DBMS_OUTPUT.PUT_LINE(SUBSTR(L_QUERY, I * 255 + 1, 255));
  END LOOP;

  OPEN L_CURSOR FOR L_QUERY USING IN_DOCUMENT_LIST;
  RETURN L_CURSOR;

END;

What I want is to be able to select documents that belong in multiple categories, like in a filtering scheme. Ex: I want to filter by category 10 and 12, so only documents belonging to 10 and 12 return (in this case doc 1).

Using HAVING:
  SELECT d.document_name
    FROM DOCUMENTS d
    JOIN DOCUMENTS_TO_CATEGORIES dtc ON dtc.doc_id = d.id
   WHERE dtc.cat_id IN (10, 12)
GROUP BY d.document_name
  HAVING COUNT(DISTINCT dtc.cat_id) = 2

Using JOINs
SELECT d.document_name
  FROM DOCUMENTS d
  JOIN DOCUMENTS_TO_CATEGORIES c10 ON c10.doc_id = d.id
                                  AND c10.cat_id = 10
  JOIN DOCUMENTS_TO_CATEGORIES c12 ON c12.doc_id = d.id
                                  AND c12.cat_id = 12

A: To get the documents that ONLY appear in BOTH categories, you could use the ANSI SQL INTERSECT operator as follows:
SELECT Documents.document_name
FROM Documents
WHERE Documents.id IN
(
    SELECT Documents_to_categories.docid
    FROM Documents_to_categories
    WHERE Documents_to_categories.catid = 10
  INTERSECT
    SELECT Documents_to_categories.docid
    FROM Documents_to_categories
    WHERE Documents_to_categories.catid = 12
/*.. add additional filters */
)

A:
I want to filter by category 10 and
  12, so only documents belonging to 10
  and 12 return (in this case doc 1)

You need to generate SQL query from your app:
SELECT
  d.id,
  d.document_name
FROM
  Documents as d,
  Documents_to_categories dc1,
  Documents_to_categories dc2,
WHERE
  d.id = dc1.doc_id
  AND d.id = dc2.doc_id
  AND dc2.cat_id = 10
  AND dc1.cat_id = 12

This should work on all major database servers.

instead of selecting from a documents
  table, I want to select it from an
  array of document ID's.

Not sure what you mean. There is no array an entity in relational world (eg SQL). There is one which is called table or maybe set.

A: This gives you all documents that belong in at least one category, of which at least one category is either 10 or 12.
SELECT
  doc_id
FROM Documents_to_categories
WHERE doc_id IN (<your list of doc_ids>)
GROUP BY doc_id
HAVING COUNT(*) > 1
AND MAX(CASE WHEN cat_id IN (10, 12) THEN 1 ELSE 0 END) = 1;


text:
Q: Math cryptography module 11 I dont know why 3^-1 is equal to 4
 lambda  = (3 * 2^2 + 1)(2 * 7)^{-1}     mod 11
 = 2 * 3^-1  mod 11
 = 2 * 4  mod 11
 = 8

Why 3^-1 is equal to 4?

A: Inverse of  3 modulo 11 is 4, denoted by 3^(-1).

A: Modular exponentiation with a negative exponent follows different inverse rules:
Using Euler's theorem:
a^(-1) is equivalent to a^(m-2) mod m
so:
3^(-1) mod 11
3^(11-2) mod 11
3^9 mod 11
19683 mod 11
4
See Modular multiplicative inverse


text:
Q: python BaseHTTPRequestHandler returning json bad string I have a simple http server like so:
from http.server import BaseHTTPRequestHandler, HTTPServer

class S(BaseHTTPRequestHandler):
    def _set_headers(self):
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()

    def do_GET(self):
        self._set_headers()
        self.wfile.write(bytes("{\"result\": 200}", "utf-8"))

    def do_HEAD(self):
        self._set_headers()

    def do_POST(self):
        # Doesn't do anything with posted data
        self._set_headers()
        self.wfile.write(bytes("{\"result\": 200}", "utf-8"))

def run(server_class=HTTPServer, handler_class=S, port=8000):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print("Starting http server on port " + str(port))
    httpd.serve_forever()

if __name__ == "__main__":
    from sys import argv

    if len(argv) == 2:
        run(port=int(argv[1]))
    else:
        run()

When I make a GET request, I expect the json: {result: 200}, but instead I get bad string. What can I do to fix this? I've seen other examples where you can write python objects as json, but not really sure how to put it into this code.


text:
Q: Two jQuery plugin conflicting on the same page I have two jQuery Plugins working on the same file. One is jquery.autocomplete.js and the other is jquery.thumbnailScroller.js .
The problem is when I am using both on same file, autocomplete is not working at all an thumbnailScroller is working and but the same is working well without thumbnailScroller plugin.
Now, when I was browsing thru the js files, I got $.fn. in both files. But, I dont know is the problem because of this or anything else.
I had searched in google and stackoverflow also, but I failed to get the proper solution.
Please guide me

A: There are some ways for avoiding conflict in jquery.
I always do like this
var $k = jQuery.noConflict();

and use $k for every $ functions for any one plugin. Not do this in plugin js files. Do this for your implementation page, like,
$k("#id").autocomplete({...

Regards
iijb


text:
Q: why I can't run my median program, I really don't get it I really don't know that I have made two while loops, but when I ran it, it only showed first loop.
do_caculation = True
while(do_caculation):
        while(True):
                stat_number_count = 0
                stat_number_sum = 0
                stat_number_average = 0
                stat_number_maximum = 0
                stat_number_minimum = 0
                state_number_range = 0

                try:
                    stat_number_name= input("What is the name of the file: ")
                    stat_number = open(stat_number_name,"r")
                    raw = stat_number.readlines()
                    raws = []

                    for number in raw:
                        raws.append(int(number))

                    stat_number_count = sum(raws)
                    stat_number_sum = len(raws)
                    stat_number_maximum = max(raws)
                    stat_number_minimum = min(raws)

                    stat_number_range = stat_number_maximum - stat_number_minimum
                    stat_number_average = stat_number_count/stat_number_sum

                except Exception as error:
                    print("An error occurred reading", stat_number_name)

                else:
                    print("File name:", stat_number_name)
                    print("Sum:", stat_number_sum)
                    print("Count:", stat_number_count)
                    print("Average:", stat_number_average)
                    print("Maximum:", stat_number_maximum)
                    print("Minimum:", stat_number_minimum)
                    print("Range:", stat_number_range)

        while(True):
                def median(raws):
                    n = len(raws)
                if n < 1:
                        print ("XD")
                if n % 2 == 1:
                        SB = sorted(raws)[n//2]
                        print (SB)
                else:
                    print (sum(sorted(raws)[n//2-1:n//2+1])/2.0

A: You never exit the first while loop, so you never execute the second loop.
From this code it doesn't look like you really understand what a while loop does. The block of code inside the loop will continue to run until the condition you gave it is no longer true. You're using
while(True)

which can never possibly be false. Thus, the loop will always run unless broken by a break statement or an exception - and an exception isn't an option in this case, because if one occurs you're catching it and simply printing a String to the console.
You need to have some way to escape your while loop. I suggest removing it entirely - it doesn't seem necessary here. Or you can change the condition for the loop from True to something that might eventually be false. Or you can put a break statement inside the loop. Or a couple of other possibilities, but you see what I'm getting at.


text:
Q: Databinding generated in the wrong package I have several modules in my project and I've renamed one of them (including the packages). This module is an Android Library module with databinding enabled.
After the renaming, the ActivityBindingImpl file is generated in the old package.
The BR and DataBinderMapperImpl files are generated in the new package like this:
module
 -- java (generated)
 ---- old.package
 ------ ActivityBindingImpl
 ---- new.package
 ------ BR
 ------ DataBinderMappingImpl

Then I get the expected a build error:

ActivityBindingImpl.java:2: error: cannot find symbol import old.package.BR

The package in the Manifest file is correct.
I've tried to clean the project, invalidate Android Studio cache, disable/enable databinding as explained here but nothing worked.
Edit:
kapt {
    useBuildCache = false
}

Also didn't help :(

A: Adding kapt "com.android.databinding:compiler:3.1.4" to the build.gradle fixed the issue. Don't know why exactly.

A: Steps
Step 1.
buildFeatures {
    viewBinding false
}

Step 2.  Sync your project
Step 3. Clean and rebuild your project
Step 4.
 buildFeatures {
    viewBinding true
}

Step 5.  Again Sync your project
Step 6. Clean and rebuild your project
it's work for me!


text:
Q: can't run flutter project on chrome I created a sample flutter project and I want to see the result in chrome.
when I run main.dart on chrome I get a white blank page as result!
here is my flutter doctor:
Doctor summary (to see all details, run flutter doctor -v):
Flutter (Channel stable, 3.3.0, on Ubuntu 22.04.1 LTS 5.15.0-56-
generic,locale en_US.UTF-8)
Android toolchain - develop for Android devices
    cmdline-tools component is missing
    Run `path/to/sdkmanager --install "cmdline-tools;latest"`
    See https://developer.android.com/studio/command-line for more
    details.
Chrome - develop for the web
Linux toolchain - develop for Linux desktop
    clang++ is required for Linux development.
    It is likely available from your distribution (e.g.: apt
    install clang), or can be downloaded from
    https://releases.llvm.org/
CMake is required for Linux development.
    It is likely available from your distribution (e.g.: apt
    install cmake), or can be downloaded from
    https://cmake.org/download/
ninja is required for Linux development.
    It is likely available from your distribution (e.g.: apt
    install ninja-build), or can be downloaded from
    https://github.com/ninja-build/ninja/releases
pkg-config is required for Linux development.
    It is likely available from your distribution (e.g.: apt
    install pkg-config), or can be downloaded from
    https://www.freedesktop.org/wiki/Software/pkg-config/
Android Studio
    android-studio-dir =
    /home/mbunderline76/.local/share/JetBrains/Toolbox/apps/IDEA-
    U/ch-0
Unable to find bundled Java version.
IntelliJ IDEA Ultimate Edition (version 2022.3)
Connected device (2 available)
HTTP Host Availability
Doctor found issues in 3 categories.

any idea what is going on?
by the way i'm using Intellij Idea Ultimate

A: Fix these issues first.
Flutter command Line tools
Flutter Java Bundled Link
then again run flutter doctor to make sure these errors are gone.
then run flutter -v -d chrome run Or Pick " Chrome Web " in your Vscode or AndroidStudio.
Hope this works, Enjoy.


text:
Q: RaiseEvent (does not work) versus InvokeMember (works) I have a C# .NET web browser object that fetches a web page. There is an anchor element on this page. My C# is to click on this element.
The following did not work:
AnchorElement.RaiseEvent("onClick");

This worked:
AnchorElement.InvokeMember("click");

Would anyone have a guess as to why? Thanks!

A: I suspect your confusion is that the event you are trying to raise is called click. See here. Not onClick. onClick is a handler for the click event, not the event itself.
So you should be able to do:
AnchorElement.RaiseEvent("click");

InvokeMember works here because HTML elements happen to have a click method that is basically just a shortcut for RaiseEvent("click").


text:
Q: No error in code but when you debug, I get an error (Eclipse Luna) My code works perfectly fine. But when I tried debugging it since it's my first time on Luna Eclipse and wanted to learn how the debugging process worked, it gives me an error saying

*stopped,reason="end-stepping-range",frame={addr="0x00401479",func="main",args=[],file="..\src\Assignment1A.c",fullname="C:\Users\Sunghee\workspace2\Assignment1A\src\Assignment1A.c",line="37"},thread-id="1",stopped-threads="all"

I don't understand this, because it works perfectly fine when I run it. The error comes at my first if statement so at
printf("\n%d + %d =%d", num1, num2, ans);
if (num2 > 0) {
    printf("\n%d / %d = %d", num1, num2, num1 / num2);
    printf("\n%d %% %d = %d", num1, num2, num1 % num2);
}
else {
    printf("\n%d /%d is not allowed", num1, num2);
}

Can anyone tell me why? I already researched it but all the terms I don't understand kind of... didn't work for me :p THANKYOU!
It works in Eclipse when I run it. When I debug it line by line, the error occurs after that one line stated above.
The full code:
include
include
int main()
{
    int num1;       //First number to be input by user
    int num2;       //Second number to be input by user
    int ans;       //Variable to store math result
setbuf(stdout, 0);

printf("Please enter the first integer:\n");
scanf("%d", &num1);

printf("Please enter the second integer:\n");
scanf("%d", &num2);

ans = num1 + num2;
printf("\n%d + %d =%d", num1, num2, ans);
if (num2 > 0) {
    printf("\n%d / %d = %d", num1, num2, num1 / num2);
    printf("\n%d %% %d = %d", num1, num2, num1 % num2);
}

else {
    printf("\n%d /%d is not allowed", num1, num2);
    printf("\n%d %% %d is not allowed", num1, num2);
}

printf("\nThe average of %d and %d is %d", num1, num2, (num1+num2)/2);

return 0;

}
So if anyone can help, please do! As I said, there's no problem when I run it. But I want to know why there's an error when I debug it. For curiosity's sake :D

A: The following code works perfectly fine for me. I think it has something to do with the way you have initialized your variables. Request you to share the entire code if possible.
#include <stdio.h>

int main(void) {

    int num1 = 1,num2 =2,num3 = 3,ans =0;

    printf("\n%d + %d =%d", num1, num2, ans);
if (num2 > 0) {
    printf("\n%d / %d = %d", num1, num2, num1 / num2);
    printf("\n%d %% %d = %d", num1, num2, num1 % num2);
}
else {
    printf("\n%d /%d is not allowed", num1, num2);
}
    return 0;
}

Results
1 + 2 =0
1 / 2 = 0
1 % 2 = 1