text:
Q: Async does wait for data to be returned in a redux-thunk function I've being trying populate my redux store with data that comes from my mongo-db realm database.
Whenever I run the function below it will execute fine but the problem is data will be delayed and ends up not reaching my redux store.
My thunk function:
export const addItemsTest = createAsyncThunk(
  "addItems",
  async (config: any) => {
    try {
      return await Realm.open(config).then(async (projectRealm) => {
        let syncItems = await projectRealm.objects("Item");
        await syncItems.addListener((x, changes) => {
          x.map(async (b) => {
            console.log(b);
            return b;
          });
        });
      });
    } catch (error) {
      console.log(error);
      throw error;
    }
  }
);

and my redux reducer:
  extraReducers: (builder) => {
      builder.addCase(addItemsTest.fulfilled, (state, { payload }: any) => {
        try {
          console.log("from add Items");
          console.log(payload);
          state.push(payload);
        } catch (error) {
            console.log(error)
         }
      });
  }

Expected Results:
My redux store should have these data once addItemsTest return something:
[{
itemCode: 1,
itemDescription: 'Soccer Ball',
itemPrice: '35',
partition: 'partitionValue',
},
{
itemCode: 2,
itemDescription: 'Base Ball',
itemPrice: '60',
partition: 'partitionValue',
}
]

Actual Results:

A: Mixed Syntaxes
You are combining await/async and Promise.then() syntax in a very confusing way.  It is not an error to mix the two syntaxes, but I do not recommend it.  Stick to just await/async
Void Return
Your action actually does not return any value right now because your inner then function doesn't return anything.  The only return is inside of the then is in the x.map callback.  await syncItems is the returned value for the mapper, not for your function.
Right now, here's what your thunk does:

*

*open a connection

*get items from realm

*add a listener to those items which logs the changes

*returns a Promise which resolves to void
Solution
I believe what you want is this:
export const addItemsTest = createAsyncThunk(
  "addItems",
  async (config: any) => {
    try {
      const projectRealm = await Realm.open(config);
      const syncItems = await projectRealm.objects("Item");
      console.log(syncItems);
      return syncItems;
    } catch (error) {
      console.log(error);
      throw error;
    }
  }
);

Without the logging, it can be simplified to:
export const addItemsTest = createAsyncThunk(
  "addItems",
  async (config: any) => {
    const projectRealm = await Realm.open(config);
    return await projectRealm.objects("Item");
  }
);

You don't need to catch errors because the createAsyncThunk will handle errors by dispatching an error action.
Edit: Listening To Changes
It seems that your intention is to  sync your redux store with changes in your Realm collection.  So you want to add a listener to the collection that calls dispatch with some action to process the changes.
Here I am assuming that this action takes an array with all of the items in your collection.  Something like this:
const processItems = createAction("processItems", (items: Item[]) => ({
  payload: items
}));

Replacing the entire array in your state is the easiest approach.  It will lead to some unnecessary re-renders when you replace item objects with identical versions, but that's not a big deal.
Alternatively, you could pass specific properties of the changes such as insertions and handle them in your reducer on a case-by-case basis.
In order to add a listener that dispatches processItems, we need access to two variables: the realm config and the redux dispatch.  You can do this in your component or by calling an "init" action.  I don't think there's really much difference.   You could do something in your reducer in response to the "init" action if you wanted.
Here's a function to add the listener.  The Realm.Results object is "array-like" but not exactly an array so we use [...x] to cast it to an array.
FYI this function may throw errors.  This is good if using in createAsyncThunk, but in a component we would want to catch those errors.
const loadCollection = async (config: Realm.Configuration, dispatch: Dispatch): Promise<void> => {
  const projectRealm = await Realm.open(config);
  const collection = await projectRealm.objects<Item>("Item");
  collection.addListener((x, changes) => {
    dispatch(processItems([...x]));
  });
}

Adding the listener through an intermediate addListener action creator:
export const addListener = createAsyncThunk(
  "init",
  async (config: Realm.Configuration, { dispatch }) => {
    return await loadCollection(config, dispatch);
  }
);

// is config a prop or an imported global variable?
const InitComponent = ({config}: {config: Realm.Configuration}) => {
  const dispatch = useDispatch();

  useEffect( () => {
    dispatch(addListener(config));
  }, [config, dispatch]);

  /* ... */
}

Adding the listener directly:
const EffectComponent = ({config}: {config: Realm.Configuration}) => {
  const dispatch = useDispatch();

  useEffect( () => {
    // async action in a useEffect need to be defined and then called
    const addListener = async () => {
      try {
        loadCollection(config, dispatch);
      } catch (e) {
        console.error(e);
      }
    }

    addListener();

  }, [config, dispatch]);

  /* ... */
}


text:
Q: Removable Singularity with bound on derivative Here is a question from a practice exam:
Suppose $g(z)$ is a holomorphic function everywhere except the origin.  Also suppose
$$
|g'(z)|\leq \frac{1}{|z|^{3/2}} \quad \text{ for } 0<|z|\leq 1
$$
Prove that $z=0$ is a removable singularity.

A: Since $|g'(z)z^2|<\sqrt{|z|}$, $0$ is a removable singularity of $g'(z)z^2$. And $g'(z)z^2\to 0$ as $z\to 0$, so $0$ is a zero of $g'(z)z^2$. Therefore $0$ is a removable singularity of $g'(z)z$. Let $g(z)=\dots+a_{-1}z^{-1}+a_0+a_1z+\dots$, since $0$ is a removable singularity of $zg'(z)$, we have $\dots+a_{-1}z^{-1}=0$, we are done.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP I need to get the numerical value="" and what the user sees So I'm using a form with the POST method and I have no trouble getting the value="" of the option chosen by the user. Got my math working and everything, no problem. Then I'm going over everything and realized that I need to show the user their Dilution Ratio, for example 1:1, based on what they chose.
<select name="yourDilution" id="yourDilution">
<option value=""></option>
<option value="2">1:1</option>
<option value="3">1:2</option>
<option value="4">1:3</option>
<option value="5">1:4</option>

So how do I get that done?
Thank you for your time.
Oh and please no .js, that language and I aren't currently on speaking terms.

A: You have a couple options:
1 - Pass the value you need
You can simply pass '1:1' as the value and make your form handler based on this so that it is available for outputting later.
<option value="1:1">1:1</option>

2 - Use logical values
You could also simply pass the defining part of the ratio. If all the ratios are 1:x then pass the value of x and know that the resulting ratio will alway be 1:x
<option value="1">1:1</option>

Then in your form handler
$display = "1:".$_POST['yourDilution'];

3 - Use value like an ID
Re-define the value and display value relationship in your form handler with a switch statement
switch($_POST['yourDilution']){
 case 2:
     $display = "1:1";
 break;
  //etc ...
}

Personally, I like Option 2 since it's simple and allows you to pass the least amount of data and requires less work if the form values change. Hope this helps.

A: You can simply handle this with using a array example,
<?php
// Here you put your options value that you want to show the user
$array = ["1:1","1:2","1:3"];
// Here you get the selection value of the user
$postValue = 2; // in your case $_POST['yourDilution']

// here you show it to the user
print_r($array[$postValue]);

?>


text:
Q: Automatically Populating TextBoxes of a software from another vendor from my DB? I have a software which I will be using. The software has a number of textboxes and I cannot get an access to the code. How can I automatically populate these textboxes through my own databases?
So for example I have a win form of another vendor which has textfield of:

*

*First Name

*Last Name

*Address

Now I want to populate these textboxes from my own database. Is there anyway to do it?
Thank You!

A: without know what software and whether it supports an API,  my suggestion would be to contact the manufacturer of the product first. If that fails then you have to consider using reflection and code injection. That may not be allowed in your license. Check carefully.

A: If the assembly is in .NET, and the form and its fields are public, you can just reference the assembly in your program, new up the form in question, and set its fields, then call whatever behavior you need. If the assembly is unmanaged, but registered for COM, you can do much the same thing.
If the program hides its internals and doesn't play well via COM, you'll have to get creative with GDI and other unmanaged hooks. You can get the handle of the window and interrogate its children to find the fields you need, then set their values. This is extremely messy to do in an unmanaged way, so I would encourage you to explore any other option you have.


text:
Q: Symfony and Doctrine - displaying data from database in controller method This is my code. I want to set default value from database in the form. I want to set value in form which i create in this method.
public function updateBlogAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();
        $data = $em->getRepository('AppBundle:Blog\Post')->find($id);

        $blogs = new Post();

        $form = $this->createFormBuilder($blogs)
                ->add('title', TextType::class, array('attr'=>array( 'class'=>'form-control','placeholder'=>'Blog title')))
                ->add('description', TextareaType::class, array('attr'=>array('class'=>'form-control','placeholder'=>'Blog description')))
                ->add('submit',SubmitType::class, array('label'=>'Add Blog', 'attr'=> array('class'=>'btn btn-primary pull-right')))
                ->getForm();

        $form->handleRequest($request);

        if( $form->isSubmitted() && $form->isValid() ){
            $data->setTitle($blogs);
            $em->flush();

            return $this->redirectToRoute('blog');
        }

        return $this->render('blog/update_blog.html.twig', array(
            'form'  =>  $form->createView()
        ));
    }

A: It is as easy as
$em = $this->getDoctrine()->getManager();
$blogs= $em->getRepository('AppBundle:Blog\Post')->find($id);

$form = $this->createFormBuilder($blogs)
/* ... */


text:
Q: Change a SF Symbol size inside a UIButton I am declaring a Button like this :
let menuButton = UIButton()

After that I am trying to change it's parameter and set his position on the view with the help of LBTATools (a pod) with this function:
fileprivate func setMenuButtonUI() {
        menuButton.setImage(UIImage(systemName: "line.horizontal.3.decrease.circle.fill"), for: .normal)
        view.addSubview(menuButton)
        menuButton.anchor(top: view.safeAreaLayoutGuide.topAnchor, leading: view.leadingAnchor, bottom: nil, trailing: nil, padding: .init(top: 20, left: 60, bottom: 0, right: 0), size: .init(width: 40, height: 40))
        menuButton.setupShadow(opacity: 1, radius: 5, offset: .zero, color: .darkGray)
        menuButton.tintColor = .red
    }

Everything is working well, I get the right color, position and even size.
Only problem is it's size, I cannot change it with all the usual methods like menuButton.imageView?.contentMode = .scaleAspectFit etc..
Probably it comes from the fact that it is a SF Symbol and not a normal image.
The help of someone would be really appreciated.
Thanks

A: Objective C:
UIImageSymbolConfiguration * configuration = [UIImageSymbolConfiguration configurationWithPointSize:30 weight:UIImageSymbolWeightBold scale:UIImageSymbolScaleLarge];
UIImage * image = [UIImage systemImageNamed:@"" withConfiguration:configuration];
[_btn setImage:image forState:UIControlStateNormal];

A: You can do it using SymbolConfiguration like in the sample code below:
let largeConfig = UIImage.SymbolConfiguration(pointSize: 140, weight: .bold, scale: .large)

let largeBoldDoc = UIImage(systemName: "doc.circle.fill", withConfiguration: largeConfig)

button.setImage(largeBoldDoc, for: .normal)

A: The iOS 15 and Swift 5 solution would be:
var config = UIButton.Configuration.plain() // Change style with e.g. `.filled()`
config.title = "Title of the UIButton"
config.image = UIImage(systemName: "line.horizontal.3.decrease.circle.fill",
                                   withConfiguration: UIImage.SymbolConfiguration(scale: .small)) // Change the scale here
config.imagePadding = 4 // Padding between image and title

let menuButton = UIButton()
menuButton.configuration = config


text:
Q: Can a private base class member variable be modified in a derived class? Is there a way to set a private member variable of a base class to a value in the constructor of a derived class?
I understand that's what getter and setter methods are for and what making the variable protected or public is for, but assuming you can't modify the base class, is there any alternate way to set it?

A: No. It's private. That is the whole point of private.
From the clarifications in the comments - the base class does give you a way to do it via its constructor, so you can use that.
// Assuming MyBaseclass has a 1 int constructor to set the
// private member, then something like this works.
//
MySubclass(int x) : MyBaseclass(x) {}

A:
I understand that's what getter and setter methods are for and what making the variable protected or public is for, but assuming you can't modify the base class, is there any alternate way to set it?

Sure. The alternative way instead of using setter functions in the derived class constructor body, is to use an appropriate constructor from your derived class to call an initializing constructor of the base class (as you state it exists in your comment):
class Base {
public:
    Base(int x, int y) : x_(x), y_(y) {}
private:
    int x_;
    int y_;
};

class Derived : public Base {
public:
    Derived() : Base(15,42) {}
           // ^^^^^^^^^^^^^
}:

See more details about the member initializer list.

A: Yes, we can do so by calling a getter function from the base class. Here is an example:
#include<iostream>
using namespace std;

class A{
    int x;
public:
    void setx(int x1) {
        x = x1;
    }

    int getx() {
        return x;
    }

};

class B: public A {

};

int main() {
    B b;
    b.setx(1000);
    cout << b.getx();
    return 0;
}


text:
Q: Batch convert xlsx to csv, all sheets with a pattern, if they have data, in linux I need to convert a lot of XLSX files to CSV, but each file has tabs, which must be converted to individual files if they have data in them.
In addition, I need to convert only those tabs that follow a pattern in their name, for example, "Tab1".
So far, I have managed to batch convert the files, although it only prints the first tab, using the ssconvert utility:
find. -name '* .xlsx' -exec ssconvert -T Gnumeric_stf: stf_csv {} \;

But when I try to add the tabs flag (-S) or the flag to include those tabs with a pattern (-I), I only get the following message:
find. -name '* .xlsx' -exec ssconvert -S -I tab1 -T Gnumeric_stf: stf_csv {} \;

An output file name or an explicit export type is required.

How do I do this correctly?

A: I just found the solution, I leave it here in case someone finds it useful. In the end I created a small script that performs the actions:
#!/bin/bash

for i in *.xlsx; do
    nombre=${i:0:${#i}-5};
    name="$nombre-%n-%s.csv";
    ssconvert --export-type=Gnumeric_stf:stf_csv --export-file-per-sheet $i $name;
done
echo "Finish!"


text:
Q: How to connect to a remote system using ftp command? I have to transfer files from machine to another(both windows platform) and for that purpose i am trying out with ftp commands. So, i am opening command prompt and typing the following:
C:\WINDOWS\system32> ftp
ftp> open sample.com
ftp> username

Now when i enter username it throws me error as "Not connected".I am not getting what am i doing wrong. The user name is absolutely correct.Please suggest how do i connect to remote system using ftp commands.

A: It seems that the "open" command failed and you are not really connected to the ftp server.
Here is what a good connection looks like:
C:\>ftp
ftp> open ftp.microsoft.com
Connected to ftp.microsoft.akadns.net.
220 Microsoft FTP Service
User (ftp.microsoft.akadns.net:(none)): anonymous
331 Anonymous access allowed, send identity (e-mail name) as password.
Password:
230-Welcome to FTP.MICROSOFT.COM. Also visit http://www.microsoft.com/downloads.
230 User logged in.
ftp>

Here the username is "anonymous" and I provided that at the "User" prompt.
You can do this in another way:
C:\>ftp
ftp> open ftp.microsoft.com
Connected to ftp.microsoft.akadns.net.
220 Microsoft FTP Service
User (ftp.microsoft.akadns.net:(none)):
501 Invalid number of parameters.
Login failed.
ftp> user anonymous
331 Anonymous access allowed, send identity (e-mail name) as password.
Password:
230-Welcome to FTP.MICROSOFT.COM. Also visit http://www.microsoft.com/downloads.
230 User logged in.
ftp>

Here I did not enter the username but used the "user" command provided by the ftp client to provide the username "anonymous"
None of these look like what you are experiencing. Could this be because you have removed some of the information in the interest of confidentiality? If so, that makes it difficult to help.
Also, it would help to read up on some help on using FTP command.
Here is one I found off google that I think would walk you through FTP commands: FTP and SFTP Beginners Guide with 10 Examples


text:
Q: Segmentation fault, listing contents of a directory I am getting segmentation fault upon the end of a while loop(I am not sure if the error appears after termination or before).
I have checked that dirlist_next_entry successfully returns DIRLIST_END after
end of directory stream is reached. I don't understand what causes the fault as the loop should successfully terminate after end of stream is reached
#include "DirEntry.h"
#include <cstdio>

int main(int argc, char* argv[]){
    if(argc != 2){
        printf("Directory not specified\n");
        return -1;
    }
    DirListError error;
    DirEntry result;
    handle hfile = dirlist_start_find(argv[1], &error);
    while( dirlist_next_entry(hfile, &result) != DIRLIST_END){
        printf("%s  %lld\n", result.entry, result.size);
    }
    dirlist_end_find(hfile);

}

Here is the definition of  dirlist_next_entry:
DirListError dirlist_next_entry(handle h, DirEntry* result){
    DIR* dirp = (DIR*)h;
    dirent* dr;
    if((dr = readdir(dirp)) == NULL){
        return DIRLIST_END;
    }

        strcpy(result->entry, dr->d_name);
    if(dr->d_type == DT_DIR){
        result->is_directory = 1;
    }
    else if(dr->d_type == DT_REG){
        result->is_directory = 0;
        struct stat* buf;
        stat(result->entry, buf);
        result->size = buf->st_size;
    }

    return DIRLIST_OK;
}

Direntry.h is just a header with a couple of declarations:
#ifndef  DIRENTRY_H
#define DIRENTRY_H

const int MAX_PATH_LENGTH = 1024;
typedef void* handle;

struct DirEntry{
    char entry[MAX_PATH_LENGTH + 1];
    int is_directory;
    long long size;
};

enum DirListError{
    DIRLIST_OK,
    DIRECTORY_NOT_FOUND,
    INCORRECT_DIRECTORY_NAME,
    DIRLIST_END,
};

handle dirlist_start_find(const char* dir, DirListError* error);
DirListError dirlist_next_entry(handle h, DirEntry* result);
void dirlist_end_find(handle h);
#endif

A: I believe that the d_name field of dirent* is not null terminated. So strcpy() on this may lead to a segmentation fault later on. If this is the case you should use strncpy()

A: This is most likely overwriting random memory:
struct stat* buf;
stat(result->entry, buf);

It should be:
struct stat buf;
stat(result->entry, &buf);


text:
Q: De-cluttering ASP.NET javascript I'm just getting into ASP.NET Been avoiding it for years as I'm a desktop application advocate.
Anyway, I was wondering if there's a way to stop the generated html being so cluttered with javascript. Is there a way to make the generated script go into a referenced js file rather that inline with the page.

A: Look into ASP.NET MVC - it is an alternative to WebForms and tends to have less clutter.

A: Are you sure you're using code-behind?
When you add a new page, make sure you check "Place code in a separate file", otherwise all your server-side code will be on the page (even tough it won't show up for the end-user)
If you're using code-behind but it still has a lot of javascript code in the page (maybe you're using ajax?) I'd suggest you don't use the .NET ajax controls, just do all the ajax by hand, using jQuery or Prototype. It's fast and it'll be as lightweight as it can be.

A: Check out ClientScriptManager.RegisterClientScriptInclude.


text:
Q: What is the proper way to stop awaited tasks when object goes out of scope? My application has two distinct states, each of them having independent set of resources, but only one of them can be active at a time.
The state is represented by a class which holds managed references to various services. For simplicity let's just assume this:
class FirstApplicationState {
  ServiceA FooService { get; }
  ServiceB BarService { get; }
}

// Some 'global' object holds reference to State
Application.State = new FirstApplicationState();

The ServiceA class during execution launches a delayed-execution task.
class ServiceA {
  CancellationTokenSource tsc;

  private async Task TriggerDelayedActionAsync() {
    try {
       tsc = new CancellationTokenSource();
       await Task.Delay(TimeSpan.FromMinutes(1),tsc.Token);
    }
    catch(TaskCancelledException) {
      Log.Info("Task cancelled");
      return;
    }
    finally { /*dispose tsc*/ }

    await RunVeryLongTaskAsync();
  }
}

The task should no longer execute if the FirstApplicationState is no longer the active state of the application. If the state will go out of scope and the entire hierarchy will be marked to be colleced by invoking Application.State = null while the Task.Delay() method is being awaited, the instance of ServiceA won't be marked for GC collection, and the await will finally execute, invoking the RunVeryLongTaskAsync method, which will load some resources and potentially throw an exception.
To avoid it, the natural solution would be to just introduce some Deinitialize() method to services and  run a deinitialization process which will properly trigger all cancellation tokens before the Application allows for marking state for GC collection, although it seems like requiring tracking cancellation tokens for all potential tasks.
I'm wondering if there is some other mechanism, which would let me cancel all tasks once object executing them goes out of scope? While not relying on it for proper state cleanup, maybe I can check if any tasks on entire hierarchy of objects are still running for debugging purposes? I'm also considering using double-source cancellation tokens which would allow me for some higher level cancellation like described in Microsoft's docs, but I'm not sure how common of a practice is this as I haven't encountered similar solutions before.

A: If you want to list tasks for debugging purposes, you can use
TaskScheduler.GetScheduledTasks (You can get the default scheduler from Scheduler.ThreadPool)
Or implement your own TaskScheduler and use it in a TaskFactory

A:
The task should no longer execute if the FirstApplicationState is no longer the active state of the application.

The easiest way to check this is to have the method itself check if it is still supposed to run. If you only need to check once at a particular point, that is what I would recommend.

the instance of ServiceA won't be marked for GC collection... maybe I can check if any tasks on entire hierarchy of objects are still running for debugging purposes?

There actually is no "hierarchy". The problem is that tasks exist in memory linked in the opposite way of what you need. The task returned from TriggerDelayedActionAsync does not reference the task returned from Task.Delay at all. The opposite is actually true. The timer acts as a GC root, referencing the task returned from Task.Delay, which has a continuation for TriggerDelayedActionAsync, which references the task returned from TriggerDelayedActionAsync.

To avoid it, the natural solution would be to ... trigger all cancellation tokens... although it seems like requiring tracking cancellation tokens for all potential tasks.

Yes. If you need to only check once (e.g., before the long task begins), then you can get away with a single check at that time. But if you need to be able to cancel at any time, then a CancellationToken would be an appropriate solution. Linked cancellation tokens may also be necessary, as you noted.
There's nothing built-in for this; you'll have to add those cancellation tokens everywhere if you need to support that.


text:
Q: Pass by reference - "hack" in java not working anymore? I tried to simulate pass-by-ref in java by passing an array of size 1 that contains the value to a corresponding method.
The source:
    public static void test(String... a) {
    a[0] = new String("bar");
}

public static void main(String[] args) throws Exception {

    String a = "foo";
    test(a);
    System.out.println(a);
}

The value is still "foo" - why?
I use JDK version 15.0.1.

A: First, the new String is pointless. Don't do that.
public static void test(String... a) {
    a[0] = "bar";
}

Second, in order to pass an array by reference, you must pass an array. Like,
public static void main(String[] args) throws Exception {
    String[] a = {"foo"};
    test(a);
    System.out.println(a[0]);
}

Outputs
bar

A: This
public static void main(String[] args) throws Exception {
    String a = "foo";
    test(a);
    System.out.println(a);
}

is effectively the same as this:
public static void main(String[] args) throws Exception {
    String a = "foo";
    String[] temp = { a };
    test(temp);
    System.out.println(a);
}

and thus 'a' is not changed.


text:
Q: Importing list of source files into an Eclipse project We have a topdirectory containing code for lots of different projects. I would like to create an Eclipse CDT-project that contains only the source needed to work on and compile a specific project. I used SlickEdit before, and there I could just import a list of sources and headers. Is it possible to achieve something similar in Eclipse?

A: In Eclipse, you can selectively import certain directories to be included in the project.
You can create an eclipse project somewhere else in your drive, and then create links only to the folders that you want in your original location (these are called "linked resources" in Eclipse)
You can also use the linked resource strategy for an entire project (I mean an Eclipse project, not your top-level project).
For example, if your folder hierarchy is as follows:
/top-level
/top-level/projectA
/top-level/projectA/subProjectA
/top-level/projectB

You can create an eclipse workspace at location /my-workspace, create a project called subProjectA and have it linked to /top-level/projectA/subProjectA. You can do the same for projectB and they will appear in your Eclipse workspace as if they are side-by-side in a flat hierarchy.

A: So far as I know, you can not do that. What you can do is import these source files into another project, which means these file will be copied to that created project.

A: Traditionally, Eclipse assumes that the .project file is at the top-level directory of your project's sources and all the source code below it is included in the project. However, I think that you should be able to use linked folders so that you have a Eclipse project directory which is basically empty but for a .project file and a linked folder which points to your source tree. I do not think however that you can explicitly list the files to include in the project.
EDIT: if you do find a solution to this, please let me know.

A: In Eclipse Helios (3.6)
In eclipse project, righ-mouse-click "New ..." > "Folder".
A dialog box appears.
Click "Advanced" button...
Click "Link to alternate Location" radio button.
Click "Browse"
Select the folder you want to link to.
For a refinement , see "Help" > "Help Contents" (a new window appears)
"Workbench User Guide" > "What's New"
Search for "Virtual folders"


text:
Q: Unit Testing with django-pipeline I have problems unit testing views of an application that uses django-pipeline? Whenever I perform a client.get() on any URL, it produces the following exception:

ValueError: The file 'css/bootstrap.css' could not be found with <pipeline.storage.PipelineCachedStorage object at 0x10d544950>.

The fact that it is bootstrap.css is of course not important, but that I'm unable to execute view rendering due to this exception.
Any guide / tips are welcome!

A: I ran into a similar problem. However, setting
STATICFILES_STORAGE='pipeline.storage.NonPackagingPipelineStorage'

when running the tests only partly solved my issue. I also had to disable the pipeline completely if you want to run LiverServerTestCase tests without having to calling 'collecstatic' before running the tests:
PIPELINE_ENABLED=False

Since django 1.4 it's fairly easy to modify settings for tests - there is a handy decorator that works for methods or TestCase classes:
https://docs.djangoproject.com/en/1.6/topics/testing/tools/#overriding-settings
e.g.
from django.test.utils import override_settings

@override_settings(STATICFILES_STORAGE='pipeline.storage.NonPackagingPipelineStorage', PIPELINE_ENABLED=False)
class BaseTestCase(LiveServerTestCase):
    """
    A base test case for Selenium
    """

    def setUp(self):
        ...

However this produced inconsistent results as @jrothenbuhler describes in his answer. Regardless, this is less than ideal if you are running integration tests - you should mimic production as much as possible to catch any potential issues. It appears django 1.7 has a solution for this in the form of a new test case "StaticLiveServerTestCase". From the docs:
https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#django.contrib.staticfiles.testing.StaticLiveServerCase

This unittest TestCase subclass extends
  django.test.LiveServerTestCase.
Just like its parent, you can use it to write tests that involve
  running the code under test and consuming it with testing tools
  through HTTP (e.g. Selenium, PhantomJS, etc.), because of which it's
  needed that the static assets are also published.

I haven't tested this, but sounds promising. For now I'm doing what @jrothenbuhler in his solution using a custom test runner, which doesn't require you to run collectstatic. If you really, really wanted it to run collectstatic you could do something like this:
from django.conf import settings
from django.test.simple import DjangoTestSuiteRunner
from django.core.management import call_command

class CustomTestRunner(DjangoTestSuiteRunner):
    """
    Custom test runner to get around pipeline and static file issues
    """

    def setup_test_environment(self):
        super(CustomTestRunner, self).setup_test_environment()
        settings.STATICFILES_STORAGE = 'pipeline.storage.NonPackagingPipelineStorage'
        call_command('collectstatic', interactive=False)

In settings.py
TEST_RUNNER = 'path.to.CustomTestRunner'

A: I've been running into the same problem. I tackled it using a custom test runner:
from django.conf import settings
from django.test.simple import DjangoTestSuiteRunner

from pipeline.conf import settings as pipeline_settings

class PipelineOverrideRunner(DjangoTestSuiteRunner):

    def setup_test_environment(self):
        '''Override STATICFILES_STORAGE and pipeline DEBUG.'''
        super(PipelineOverrideRunner, self).setup_test_environment()
        settings.STATICFILES_STORAGE = 'pipeline.storage.PipelineFinderStorage'
        pipeline_settings.DEBUG = True

Then in your settings.py:
TEST_RUNNER = 'path.to.PipelineOverrideRunner'

Setting pipeline's DEBUG setting to True ensures that the static files are not packaged. This prevents the need to run collectstatic before running the tests. Note that it's pipeline's DEBUG setting, not Django's, which is overridden here. The reason for this is that you want Django's DEBUG to be False when testing to best simulate the production environment.
Setting STATICFILES_STORAGE to PipelineFinderStorage makes it so that the static files are found when Django's DEBUG setting is set to False, as it is when running tests.
The reason I decided to override these settings in a custom test runner instead of in a custom TestCase is because certain things, such as the django.contrib.staticfiles.storage.staticfiles_storage object, get set up once based on these and other settings. When using a custom TestCase, I was running into problems where tests would pass and fail inconsistently depending on whether the override happened to be in effect when modules such as django.contrib.staticfiles.storage were loaded.

A: I ran into the same problem. I managed to get around it by using a different STATIC_FILES_STORAGE when I'm testing:
STATICFILES_STORAGE = 'pipeline.storage.NonPackagingPipelineStorage'

I have separate settings files for production and testing, so I just put it in my test version, but if you don't, you could probably wrap it in if DEBUG.
--EDIT
It took a little more effort, because this can only present during the unittesting. To address that, I used the snippet at http://djangosnippets.org/snippets/1011/ and created a UITestCase class:
class UITestCase(SettingsTestCase):
    '''
    UITestCase handles setting the Pipeline settings correctly.
    '''
    def __init__(self, *args, **kwargs):
        super(UITestCase, self).__init__(*args, **kwargs)

    def setUp(self):
        self.settings_manager.set(
            STATICFILES_STORAGE='pipeline.storage.NonPackagingPipelineStorage')

Now all of my tests that need to render UI that incude compressed_css tags use UITestCase instead of django.test.TestCase.

A: I ran into the same problem, and it turned out to be because I had
TEST_RUNNER = 'djcelery.contrib.test_runner.CeleryTestSuiteRunner'

I don't understand how, but it must somehow have interacted with Pipeline. Once I removed that setting, the problem went away.
I still needed to force Celery to be eager during testing, so I used override_settings for the tests that needed it:
from django.test.utils import override_settings

…

class RegisterTestCase(TestCase):

    @override_settings(CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,
                       CELERY_ALWAYS_EAGER=True,
                       BROKER_BACKEND='memory')
    def test_new(self):
        …

A: Same here. Refers to this issues: https://github.com/cyberdelia/django-pipeline/issues/277
As I use py.test, I put this in conftest.py as a workaround:
import pytest
from django.conf import settings

def pytest_configure():
    # workaround to avoid django pipeline issue
    # refers to
    settings.STATICFILES_STORAGE = 'pipeline.storage.PipelineStorage'

A: i've tried @jrothenbuhler workaround and it helps at first..
but then, for some reason it starts fail again with same error
after hours of debugging i've figured out that the only things that helps is to set
STATICFILES_STORAGE = 'pipeline.storage.NonPackagingPipelineStorage'
directly in settings...
dunno why, but it works.


text:
Q: SQL Server Always on, delay in replicating data to secondary I have 2 SQL Server databases, one is Primary where all the write operations is done connected to Main app, and secondary database is connected to reporting app, data between 2 databases is synced via Always On group. The issue I am facing here is, all the data gets replicated soon, but when secondary database is having to many transaction (i.e if more number of users are accessing my report tool) then data replication gets delayed between primary and secondary database up to 3mins, 8mins and sometimes 20 mins as well. what is the for fix this issue?
Note: SQL Server is installed in a very good infrastructure with good RAM & HD.
I got to hear few solutions as, by applying locks in queries of reporting app, and query optimization and applying indexes might help, but my doubt is that, this will increase the query performance, but my issue is in data replication from primary to secondary database.
Can someone please help me.


text:
Q: Why does Thread.isInterrupted () always return false? I found the method of JavaDoc:
Returns:
true if this thread has been interrupted; false otherwise.
I think something wrong with my understanding of the method. Further, I may misunderstand the concept 'interrupt' in Thread.
Any explanation is welcome! Thank you!
Code snippet:
In thread definition:
public void run() {
        try {
            //Do something
        } catch (InterruptedException e) {
            System.out.println(isInterrupted());//Always false
            return;
        }
    }

invoke:
theThread.interrupt();

A: Adding to cdhowie's answer, one standard pattern is to let the Thread handle interruption. This is useful with Executors, when the running code doesn't "own" the Thread and should not get in the way of interruption (unless you really know what you're doing)
public void run() {
    try {
        //Do something
    } catch (InterruptedException e) {
        // Do whatever local clean up you need to
        ...
        // Then let the owning Thread know it's been interrupted, so it too can clean up
        Thread.currentThread().interrupt(); //
    }
}

A: This behaviour is typically documented in methods that throw that exception.  For example, the javadoc for Object.wait() says:

"InterruptedException - if any thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown."

Indeed, the javadoc for the exception itself says this:

"Occasionally a method may wish to test whether the current thread has been interrupted, and if so, to immediately throw this exception. The following code can be used to achieve this effect:
if (Thread.interrupted())  // Clears interrupted status!
     throw new InterruptedException();

Note how they emphasize that the flag should be cleared before the exception is thrown.

Why was it designed to work like this?  You'd have to ask the designers, but I expect they figured that an exception handler should handle the situation, and that there should therefore be no need for the flag to still be set at that point.  (If the handler doesn't fully handle the situation it can either rethrow the exception, or call Thread.getCurrentThread.interrupt() to set the flag again.)

A: Once the exception is thrown, the thread is no longer in an interrupted state.

A: You would check isInterrupted() in your own code, for example from a loop. If the thread has been interrupted you can then throw InterruptedException to stop executing.
In your example if you caught InterruptedException you can be sure that it was interrupted and you don't have to check that method.


text:
Q: CUDA C v. Thrust, am I missing something? I just started learning CUDA programming. I was trundling through some simple CUDA C examples and everything was going swimmingly. Then! Suddenly! Thrust! I consider myself versed on C++ functors and was taken aback at the difference between CUDA C and Thrust
I find it hard to believe that
__global__ void square(float *a, int N) {
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    if (idx < N) {
        a[idx] = a[idx] * a[idx];
    }
}

int main(int argc, char** argv) {

float *aHost, *aDevice;

const int N = 10;
size_t size = N * sizeof(float);

aHost = (float*)malloc(size);
cudaMalloc((void**)&aDevice, size);

for (int i = 0; i < N; i++) {
    aHost[i] = (float)i;
}

cudaMemcpy(aDevice, aHost, size, cudaMemcpyHostToDevice);

int block = 4;
int nBlock = N/block + (N % block == 0 ? 0:1);

square<<<nBlock, block>>>(aDevice, N);

cudaMemcpy(aHost, aDevice, size, cudaMemcpyDeviceToHost);

for (int i = 0; i < N; i++) {
    printf("%d, %f\n", i, aHost[i]);
}

free(aHost);
cudaFree(aDevice);
}

is equvalent to
template <typename T>
    struct square {
    __host__ __device__ T operator()(const T& x) const {
        return x * x;
    }
};

int main(int argc, char** argv) {
    const int N = 10;
    thrust::device_vector<float> dVec(N);
    thrust::sequence(dVec.begin(), dVec.end());
    thrust::transform(dVec.begin(), dVec.end(), dVec.begin(), square<float>());
    thrust::copy(dVec.begin(), dVec.end(), std::ostream_iterator<float>(std::cout, "\n"));
}

Am I missing something? Is the above code being run on the GPU? Thrust is a great tool, but I'm skeptical that it takes care of all the heavy C-style memory management.

*

*Is the Thrust code being executed on the GPU? How can I tell?

*How did Thrust eliminate the bizarre syntax of evoking a kernel?

*Is Thrust actually evoking a kernel?

*Does Thrust automatically handle the thread index computation?

Thanks for your time. Sorry if these are silly questions, but I find it incredulous that the examples I've seen transition instantly from what can be described as a Model T to a M3.

A: Roughly: yes, of course. Thrust is a library, so as all of them are born to make it easier. Its great point is avoiding all explicit CUDA code, which looks strange for rest of programmers, providing a friendly C++-like interface.
Thrust uses GPU, but not just GPU. It makes same operations you make if you write your own code, i.e., C/C++ code for allocating memory, copying, set grid and block sizes... and then invokes GPU for executing kernel.
It is a good choice for those who don't want to get inside low level CUDA stuff but to take advantage of GPU parallelism in a simple (but frequent) problem, like vector operations.


text:
Q: Something like print END << END; in C++? Is there anyway to do something like PHP's
print << END
yadayadayada
END;

in C++? (multi-line, unescaped, easy-to-cut-and-paste stream insertion)

A: In C++, it's not usually considered code style to put large amounts of data into source code so there isn't a fancy language way to do it.
It is usually more flexible to put the text into an external file (such as a text file), then it isn't bound into the compiled executable.
If you do want the text to be bound into the executable then (depending on your platform) you can often use some form of resource support, or an assembler with an 'incbin' style directive to give name to a data area with the text that you want.
Alternatively, you can use an external utility (such as xxd -i) to compiler a named C style array from a given input file. The generated file can then be compiled with the rest of the source code.

A: Yes.  http://en.cppreference.com/w/cpp/language/string_literal
const char* s1 = R"foo(
Hello
World
)foo";
//same as
const char* s2 = "\nHello\nWorld\n";

Whether or not it's best-practice, C++11 does pretty well exactly what you want.

A: C++11 has raw string literals:
// this doesn't have '\n', but '\\' and 'n'
R"(yada"yadayada\n)"

And if you need those parens, you can do that, too, using whatever you want for an end token:
// the following will be "(yada)(yada)(yada)"
R"END((yada)(yada)(yada))END"

it also works with embedded new lines:
// the following will be "\n(yada)\n(yada)\n(yada)\n"
R"END(
(yada)
(yada)
(yada)
)END"

A: This answer is now out of date for modern C++ - see sbi's answer for the modern way.
This is the best you can do:
std::cout <<
    "This is a\n"
    "multiline\n"
    "string.\n";

Not as convenient as a proper heredoc, but not terrible.

A: You can do like this:
std::cout << "First line\n"
"second line\n"
"third line\n" ;

And that's the best you can do with C++.

A: There is not such thing as a HEREDOC in C++.
You can do
cout <<
"yadayadayada"
"yadayadayada"
<< endl;

That is the best you can get. But you still has to escape special chars like \,",'.
The way would it be to include the text as an ressource into the executable or load it from an external file.

A: A slash at the end of a line means the next line is a continuation of the string.  This leads you to an alternate syntax that you may or may not prefer over other suggestions:
std::cout << "\
This is a\n\
multiline\n\
string.\
";

The advantages: you don't have to wrap each line in quotes; when importing text from some other source you only have to edit one end of each line, not both ends (more macro friendly); and you can see exactly how the resulting string will look, including leading spaces.
The disadvantages: you still have to explicitly include \n for newlines, and I don't like losing the ability to indent my code nice and pretty.  HEREDOC syntax also suffers from this feature, so perhaps that won't bother you.
Personally, this isn't a syntax I like.

A: If I understand you correctly, I believe you want this:
#include <iostream>
...
std::cout << std::endl << "yadayadayada" << std::endl;


text:
Q: How fit scrollview properly to screen I have question about scrollview. I look up on the internet but I couldn't fit any solution for it. I am using a windowed activity in my application. I use it without a problem until I add a scrollview. Scrollview isn't fit screen properly.
Here is the my activity code.
class ExtendedMedicineInfoActivity : Activity() {
private lateinit var binding: ActivityExtendedMedicineInfoBinding
var medicineUsageData = MedicineUsageData()
var gson = Gson()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityExtendedMedicineInfoBinding.inflate(layoutInflater)
    val view = binding.root
    setContentView(view)

    medicineUsageData = gson.fromJson(intent.getStringExtra("medicineData"), MedicineUsageData::class.java)

    val displayMetrics = DisplayMetrics()
    windowManager.defaultDisplay.getMetrics(displayMetrics)
    val width = displayMetrics.widthPixels
    val height = displayMetrics.heightPixels
    window.setLayout((width * .8).toInt(), (height * .8).toInt())
    val params = window.attributes
    params.gravity = Gravity.CENTER
    params.x = 0
    params.y = -20
    window.attributes = params
    setFields()
}

private fun setFields() {
    binding.expireDateEditText.setText(medicineUsageData.expireDate)
    binding.barcodeNumEditText.setText(medicineUsageData.barcodeNum)
    binding.companyNameEditText.setText(medicineUsageData.companyName)
    binding.drugSubstanceEditText.setText(medicineUsageData.drugSubstance)
    binding.medicineNameEditText.setText(medicineUsageData.productName)
    binding.partyNumEditText.setText(medicineUsageData.partyNum)
    binding.serialNumEditText.setText(medicineUsageData.serialNum)
}
}

This code doesn't produce any errors. I use it for my other windowed activities too. But this is the first time I try to add a scrollview to it.
Here is the xml code for this activity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:gravity="center"
    android:orientation="vertical"
    android:background="@drawable/popup_medicine_list"
    tools:context=".ExtendedMedicineInfoActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:text="@string/medicine_information"
        android:textSize="32sp" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

    <GridLayout
        android:id="@+id/grid_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:clipToPadding="false"

        android:columnCount="1"
        android:padding="16dp">

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/medicine_name_text_input"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="4dp"
            android:hint="@string/medicine_name">

            <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/medicine_name_edit_text"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:focusable="false"
                android:cursorVisible="false"
                android:textColor="@color/black" />
        </com.google.android.material.textfield.TextInputLayout>

        <Space />

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/expire_date_text_input"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="4dp"
            android:hint="@string/expire_date">

            <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/expire_date_edit_text"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:focusable="false"
                android:cursorVisible="false"
                android:textColor="@color/black" />
        </com.google.android.material.textfield.TextInputLayout>

        <Space />

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/company_name_text_input"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="4dp"
            android:hint="@string/company_name">

            <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/company_name_edit_text"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:focusable="false"
                android:cursorVisible="false"
                android:textColor="@color/black" />
        </com.google.android.material.textfield.TextInputLayout>

        <Space />

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/barcode_num_text_input"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="4dp"
            android:hint="@string/barcode_number">

            <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/barcode_num_edit_text"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:focusable="false"
                android:cursorVisible="false"
                android:textColor="@color/black" />
        </com.google.android.material.textfield.TextInputLayout>

        <Space />

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/drug_substance_text_input"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="4dp"
            android:hint="@string/drug_substance">

            <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/drug_substance_edit_text"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:focusable="false"
                android:cursorVisible="false"
                android:textColor="@color/black" />
        </com.google.android.material.textfield.TextInputLayout>

        <Space />

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/party_num_text_input"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="4dp"
            android:hint="@string/party_number">

            <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/party_num_edit_text"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:focusable="false"
                android:cursorVisible="false"
                android:textColor="@color/black" />
        </com.google.android.material.textfield.TextInputLayout>

        <Space />

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/serial_num_text_input"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="4dp"
            android:hint="@string/serial_number">

            <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/serial_num_edit_text"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:focusable="false"
                android:cursorVisible="false"
                android:textColor="@color/black" />
        </com.google.android.material.textfield.TextInputLayout>

    </GridLayout>

    </ScrollView>

    <com.google.android.material.button.MaterialButton
        android:id="@+id/delete_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/delete" />

</LinearLayout>

This code build and works without error. But this is the result.

As you can see there is another element at the top but it doesn't show.

And there is redundant space under it.
I can fix upper problem by adding android:layout_marginTop="56dp" to inner GridLayout. But I know it isn't the best solution. Screen size can change or something else. And even if I add this line it doesn't fix my down side redundant space problem.
Can anyone help me with this problem. Thanks in advance.

A: I figure it out. When I change my code values my problem is solved.
Here is the code which I changed.
window.setLayout((width * .8).toInt(), (height * .8).toInt())
val params = window.attributes
params.gravity = Gravity.CENTER
params.x = 0
params.y = -20

I changed it to this:
window.setLayout((width * .8).toInt(), (height * .9).toInt())
val params = window.attributes
params.gravity = Gravity.CENTER
params.x = 0
params.y = 100


text:
Q: PHP Dom Is there any way an element can create an element I realize that createElement() is a DOMDocument method.
If I have methods to which an element is passed, in this case, for a subsequent
element::parent::insertBefore(new_element, element)

is there a way given only the element to refer to the DomDocument so that the element can be created, an equivalent of
element::document::createElement()

or do I always need to pass the it as an additional parameter?

A: You can use:
$element->ownerDocument->createElement(...)

inherited from \DOMNode
Reference: https://php.net/manual/class.domnode.php#domnode.props.ownerdocument


text:
Q: Transfer gitlab repo to another drive Why?
I am going to have a big (>150gb) repository, that will fulfill main drive, so /var/opt/gitlab/git-data is not going to be enough. I want to move existing repository (and wiki) from /var/opt/gitlab/git-data/repositories/mygroup/myproject to /mnt/big-repos/git-data/mygroup/myproject
Info

*

*GitLab Community Edition 11.3.6

/etc/gitlab/gitlab.rb:
git_data_dirs({
   "alternative" => {
     "path" => "/mnt/big-repos/git-data"
    },
   "default" => {
     "path" => "/var/opt/gitlab/git-data"
    }
 })

What I've tried?
1.
sudo -u git mkdir /mnt/big-repos/git-data/mygroup

sudo -u git mv /var/opt/gitlab/git-data/repositories/mygroup/myproject.*  /mnt/big-repos/git-data/mygroup

rm -rf /var/opt/gitlab/git-data/repositories/mygroup/myproject.*

gitlab-ctl reconfigure
gitlab-ctl restart

Not working, cuz it keeps spawning everything in old direcory.
2.
sudo -u git mkdir /mnt/big-repos/git-data/mygroup

sudo rsync -av /var/opt/gitlab/git-data/repositories/mygroup/myproject.*  /mnt/big-repos/git-data/mygroup

rm -rf /var/opt/gitlab/git-data/repositories/mygroup/myproject.*

gitlab-ctl reconfigure
gitlab-ctl restart

Same here. help


text:
Q: Reference ENUM by index I need to implement a lookup table scenario. I COULD do it with a hash table. So
$fruit = @{
    0 = 'Apple'
    1 = 'Pear'
    2 = 'Kiwi'
}

$fruit[1]

But it feels to me like an ENUM is the right native data type. however, while I can get the index of a specific enum name, I can't seem to get the name by referencing the value/index. This DOESN'T work.
Enum Fruit {
    Apple
    Pear
    Kiwi
}

[fruit]::1

Am I just completely not understanding ENUMs? Because it seems to me that looking up the index with [fruit]::'Pear'.value__ is the opposite of what I would want to do.
For context, I want to have an ENUM that provides the corresponding strings for the integer I get back from
(Get-WmiObject -class:Win32_ComputerSystem -computerName:. -nameSpace:'root\CIMV2').PCSystemType

And ultimately I want to localize those ENUMs in a PSD1 file, so my French users get 'Portable' when PCSystemType is 2, while English speaking users would get 'Mobile'. Note, I am not actually sure that 'Portable" is correct. I need to get a friend to do the localization, but you get the point.
Anyway, is there a direct route, given the index, to get to the name? Or is the only option to coerce the enum to an array or hash table, at which point there is no reason to use an enum?
EDIT: @andy-arismendi answered the :: question here. It's calling a static method of the [fruit] type, which isn't what we want. And since it's a .NET type I guess is also needs to .NET way to reference an index, which doesn't need use [#] like PowerShell? More to learn! ;)

A: using the enum as [fruit]1 will work


text:
Q: Why the datatable header missing after click filter button in Laravel I want to filter the data and managed to do it. However, when I clicked filter, my datatable headers are missing but I couldnt figure out what the problem is.
My blade is:

                                ID
                                First Name
                                Last Name

Filter function:
$('#filter').click(function(){
      var table = $('#table_data').DataTable();
      var name= $('#name').val();
      var age= $('#age').val();
      var gender= $('#gender').val();

      if( $.fn.DataTable.isDataTable('#table_data')){
            table.destroy();
            $('#table_data').empty();
            var dataTable = $('#table_data').DataTable({
            processing: false,
            serverSide: false,
            ajax:{
            url:'/filter-result',
            data:{name:name, age:age,gender:gender}
            },

            columns: [
                  {
                      data:'id',
                      name:'id'
                  },
                  {
                      data:'First_name',
                      name:'First_name'
                  },
                  {
                      data:'Last_name',
                      name:'Last_name'
                  }

              ]

          });

          }
    });

What is the reasons the header missing after clicked?


text:
Q: Zend Framework Disapatcher error so suddnly is about a week I work for an application and now, yesterday i receive this error and than so suddnly has disappeared and I continued to work! now i receive again this error but without any change!
how can i solve it?
thanks

Warning:  include_once(/www/zendsvr/htdocs/TassiWeb/application/controllers/LoginController.php) [function.include-once]: failed to open stream: Too many open files in /usr/local/zendsvr/share/ZendFramework/library/Zend/Controller/Dispatcher/Standard.php on line 344

Warning:  include_once() [function.include]: Failed opening '/www/zendsvr/htdocs/TassiWeb/application/controllers/LoginController.php' for inclusion (include_path='/www/zendsvr/htdocs/TassiWeb/application/../library:/www/zendsvr/htdocs/TassiWeb/library:.:/usr/local/zendsvr/share/ZendFramework/library:/usr/local/zendsvr/share/pear') in /usr/local/zendsvr/share/ZendFramework/library/Zend/Controller/Dispatcher/Standard.php on line 344

Warning:  include_once(/www/zendsvr/htdocs/TassiWeb/application/controllers/ErrorController.php) [function.include-once]: failed to open stream: Too many open files in /usr/local/zendsvr/share/ZendFramework/library/Zend/Controller/Dispatcher/Standard.php on line 344

Warning:  include_once() [function.include]: Failed opening '/www/zendsvr/htdocs/TassiWeb/application/controllers/ErrorController.php' for inclusion (include_path='/www/zendsvr/htdocs/TassiWeb/application/../library:/www/zendsvr/htdocs/TassiWeb/library:.:/usr/local/zendsvr/share/ZendFramework/library:/usr/local/zendsvr/share/pear') in /usr/local/zendsvr/share/ZendFramework/library/Zend/Controller/Dispatcher/Standard.php on line 344

Fatal error:  Uncaught exception 'Zend_Controller_Dispatcher_Exception' with message 'Invalid controller class ("ErrorController")' in /usr/local/zendsvr/share/ZendFramework/library/Zend/Controller/Dispatcher/Standard.php:352
Stack trace:
/usr/local/zendsvr/share/ZendFramework/library/Zend/Controller/Dispatcher/Standard.php(262): Zend_Controller_Dispatcher_Standard->loadClass('ErrorController')
/usr/local/zendsvr/share/ZendFramework/library/Zend/Controller/Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
 /usr/local/zendsvr/share/ZendFramework/library/Zend/Application/Bootstrap/Bootstrap.php(97): Zend_Controller_Front->dispatch()
/usr/local/zendsvr/share/ZendFramework/library/Zend/Application.php(366): Zend_Application_Bootstrap_Bootstrap->run()
/www/zendsvr/htdocs/TassiWeb/public/index.php(26): Zend_Application->run()
{main}
  thrown in /usr/local/zendsvr/share/ZendFramework/library/Zend/Controller/Dispatcher/Standard.php on line 352

A: Zend needs a lot of files open. But the 'too many open files' issue is connected with recursion; particularly a loop of files where A includes B includes C includes A (for instance.)
With Zend you shouldn't need to manually include files for the most part, since it uses auto-loading. In that week's time I'm thinking you may have introduced an accidental recursion.
Remove that recursion (or make sure the includes are include_once/require_once) and you will address the issue.

A: I had a similar 'too many files' open error and it ended up being that I was extending the wrong Bootstrap class in my module. I was using Zend_Application_Bootstrap_Bootstrap instead of Zend_Application_Module_Bootstrap. So check if you have more than one implementation of Zend_Application_Bootstrap_Bootstrap. Hope that applies to your situation.


text:
Q: JavaFX Images not showing when running Jar Everything is perfect when building/running jar with the IDE however when I use ANT to build project no images show. They were defined using scene builder and document relative path.
e.g. "@../resources/pic.png"
I have tried everything I saw online but still nothing (I was working on it for 5hours). Any help would be appreciated as I am out of ideas.


text:
Q: In Android how do you use a selector on a ListView to change the background color that will allow the text to appear as well? I'm currently using an android:listSelector in order to change the color of the background of a selected item in my list.  This works well, but when the color changes, you can no longer read the text that was displaying for that list item.  What am I doing wrong?  How can I get the selected item in my list to change color while not covering the text for that item?
What I want is for the background color to change from gray to orange (when it is selected) like it is currently doing, but I would also like for my text to display during the color change to orange.
This is my activity_main.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"
    android:background="@drawable/gray_lines" >

    <ImageView
        android:id="@+id/header"
        android:layout_width="wrap_content"
        android:layout_height="45dp"
        android:scaleType="fitXY"
        android:src="@drawable/logo_header" />

    <!-- Footer aligned to bottom -->
    <ImageView
        android:id="@+id/footer"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:layout_alignParentBottom="true"
        android:scaleType="fitXY"
        android:src="@drawable/orange" />

    <TextView
        android:id="@+id/footerText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_marginBottom="5dp"
        android:layout_marginLeft="14dp"
        android:onClick="contactPressed"
        android:text="@string/footerText" />

    <ListView
        android:id="@+id/mainMenuList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/header"
        android:layout_above="@id/footer"
        android:listSelector="@drawable/item"
        android:drawSelectorOnTop="true"
        android:divider="#000000"
        android:dividerHeight="0.1dp" />

</RelativeLayout>

This is my list_item.xml which is used to populate the contents of each item in the listView.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/gray" >

    <ImageView
        android:id="@+id/img"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_marginRight="15dp"
        android:layout_marginTop="20dp"
        android:layout_alignParentRight="true" />

    <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:layout_marginTop="17dp"
        android:layout_marginLeft="15dp"
        android:textSize="23sp" />

</RelativeLayout>

and this finally is my selector xml (labeled item.xml)
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_enabled="false" android:state_focused="true"
        android:drawable="@drawable/orange" />
  <item android:state_pressed="true"
        android:drawable="@drawable/orange" />
  <item android:state_focused="true"
        android:drawable="@drawable/orange" />
</selector>

Thanks!

A: Create a sub folder in res called color. Use that folder to create new color selectors.
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true" android:color="pressed_color"/>
    <item android:color="default_color"/>

</selector>

From there, use the TextView:textColor attribute and apply the selector.
android:textColor="@color/your_selector"

Edit
First, remove the line android:drawSelectorOnTop="true" from your ListView. This is the reason the item in your ListView is being covered up. Next, create a custom selector for your row background that uses a transparent color when the item is touched. This way, your list selector will be shown in place of the background of the item.
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@android:color/transparent" android:state_pressed="true"/>
    <item android:drawable="your_default_color"/>

</selector>

Apply this selector to using the android:background attribute.


text:
Q: What the different between -b:v  and -b  FFmpeg flags? I need to bound the video bitrate, which flag is better to use? I re-encode h.264 video.

A: :v after the b is an example of a stream specifier, which directs and limits the streams to which the option is applied. So, -option:a:2 would only apply to the third audio output stream, whereas -option:a would apply to all audio output streams. -option would apply to all streams.
However, in the case of -b, ffmpeg will catch this syntax and treat it the same as -b:v.
Also, see https://superuser.com/a/1219824 for guide to how the order of options affects result.


text:
Q: Plotting 2-variable Function with integration using MatLab Does anyone have an example of how to plot a 2-variable function with integration in MatLab (without using MuPAD)?
Here is what I've got:
clear all;

%define a, p and w

a=1;
p=1;
w=5;

%calculate xmin and xmax

xmin=a-p/2
xmax=a+p/2

%define the coordinates

x=linspace(xmin,xmax);
y=linspace(0,1);

%define the coordinates along x-y plane

[x,y]=meshgrid(x,y);

%define and compute the given function along the x-y coordinates

z=w-(1/p)*int((x.-y)^2, x, xamin, xmax) ;

figure
surf(y,x,z)
title ('a=1 and p=1');
xlabel('w')
ylabel('t')
zlabel('x')
axis tight
shading interp
colorbar

Clearly, there is something wrong with my function z. The function is
z=w-(1/p)*int(x-t)^2dx where x ranges from a-p/2 to a+p/2
Thanks a lot!

A: Your function
z=w-(1/p)*int((x.-y)^2, x, xamin, xmax) ;

does not depend on x, since
 >> syms x y xmin xmax
 >> func = int((x-y)^2,x,xmin,xmax)

 func =

 xmax*(y^2 + xmax*(xmax/3 - y)) - xmin*(y^2 + xmin*(xmin/3 - y))

so doing a surface plot is not needed, a simple plot is sufficient.
You can do this with
z = xmax*(y.^2 + xmax*(xmax/3 - y)) - xmin*(y.^2 + xmin*(xmin/3 - y));
plot (y ,z);

before converting x and y to a grid via meshgrid:


text:
Q: How can I crossfade divs in one at a time with jquery I'm trying to crossfade image divs in succession upon hovering another div. I'm missing something however, as it's not changing the image upon hover and is instead fading in and out the same div. Any help would be greatly appreciated.
Here's a fiddle.

$('.card').hover(function() {
  var delay = 0;
  $('.fade-m').each(function() {
    var $fade = $(this);
    $fade.find(".front").fadeOut();
    $fade.find(".back").fadeIn();
    setTimeout(function() {
      $fade.find(".back").fadeOut();
      $fade.find(".front").fadeIn();
    }, delay += 500);
  });
});
.fade-m {
  position: relative;
  transform-style: preserve-3d;
  transition: all 1s ease-in-out;
}
.fade {
  border: 1px solid red;
}
.front {
  display: block;
  z-index: 2;
}
.back {
  position: absolute;
  display: none;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: 9999;
}

hover text

A: I believe this is what you want, but it doesn't use jQuery, just pure CSS3.  You may need to run the CSS through an autoprefixer if you want to support browsers that don't support unprefixed versions of some of the properties.

.fade-m {
  position: relative;
  display:block;
}
/* Make all transtions on the img last .5 seconds */
.fade-m img {
  transition: 0.5s all;
}
/* place the back img in the same spot as the front img */
.fade-m .back img {
  position: absolute;
  top: 0;
}
/* Make sure the front img is always on top of the back img */
.fade-m .front img {
  position: relative;
  z-index: 2;
  opacity: 1;
}
/* Change opacity of the front img to 0 on hover */
.card:hover ~ .fade-m .front img {
  opacity: 0;
}

/* Delay the transition on hover of the second .fade-m by .5 seconds */
.card:hover + .fade-m + .fade-m img {
  transition-delay: .5s;
}

hover text

Cleaner version:

/* Only if you don't have similar in your normalize.css/reset.css */
.card ul { padding: 0; }

.card li {
  position: relative;
  height: 50px;
}

/* Make all transtions on the img last .5 seconds */
.card img {
  transition: 0.5s all;
}

/* place images in the same spot and visible */
.card li img {
  position: absolute;
  top: 0;
  left: 0;
  opacity: 1;
}

/* Make sure the front img is always on top of the back img */
.card img:first-child {
  z-index: 2;
}

/* Change opacity of the front img to 0 on hover */
.card:hover img:first-child {
  opacity: 0;
}

/* Use this instead if you want the hover to only work on the h3 and not the entire card
.card h3:hover + ul img:first-child {
  opacity: 0;
}*/

/* Delay the transition on hover of the second .fade-m by .5 seconds */
.card:hover li:nth-child(2) img {
  transition-delay: .5s;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.3/normalize.css" rel="stylesheet"/>

hover text

A: As the comments have mentioned, nobody is really clear on what exactly it is that you are looking for. I took a shot at it, but it was a shot in the dark at best.
setTimeout();
is non-blocking, so it will not delay the execution of a loop or iterator like you have it in your original code. You have to wrap the function to execute in the setTimeout() or setInterval() and stop it when you reach the end of the list of items.
Here's what I came up with based on what I think you are wanting:
http://jsfiddle.net/shzBu/11/
Let me know if that's the effect you were looking for.
EDIT - I misunderstood what you wanted
 Check out this site for crossfading CSS3 transitions! http://css3.bradshawenterprises.com/cfimg/


text:
Q: PHP MYSQL looking for a way to group rows that have same value in certain column I have a table named records with the columns: recordid, artist, album, description and coverimg. Some of the albums in the table have the same artist.
On my site I would like to display it like this:
-artist1
  album1
  album2
- artist2
  album3
-artist3
  album4
  album5
If I use GROUP BY it just shows one row per artist. Is there any other way to group them without resorting to relational tables?
Because now I have a form to insert and update the table through my site, and I have no idea how I would have to code the forms to make this work with relational tables.

A: try this
select artist,group_concat(album) from albums group by artist

gives you
artist1  | album1,album2,album3
artist2  | albumx,albumy

You can split the second column in PHP e.g. using explode(row[1])
That should help you a bit

A: You can do it without a group by:
<?php
$query = 'Select artist, album
    FROM records
    ORDER BY artist'
$result = mysql_query($query);

$artist = '';
while ($line = mysql_fetch_assoc($result)){
    // only show artist when it's an other artist then the previous one
    if ($line['artist'] != $artist){
        echo $line['artist'].'
';
        $artist = $line['artist'];
    }
    echo $line['album'].'
';
}
?>

I know I should not be using mysql_* functions anymore, please choose mysqli_* or PDO....


text:
Q: Pandas : Apply regex with multiple patterns and expand the results along with nan values Say I have a dataframe :
df = pd.DataFrame({'date' : ['Nov 21, 2000','Sep 08, 2000','Nov, 1999','Nov 26, 1998','Apr, 2002','2001','Mar 26, 1998', 'Oct 07, 1999', 'Nov 20, 1995', 'Mar 15, 1996']})
           date
0  Nov 21, 2000
1  Sep 08, 2000
2     Nov, 1999
3  Nov 26, 1998
4     Apr, 2002
5          2001
6  Mar 26, 1998
7  Oct 07, 1999
8  Nov 20, 1995
9  Mar 15, 1996

And I have a regex which has multiple patterns
p = '(\\d{4})|\\s(\\d{2}),|([aA-zZ]+)'
df['date'].str.extractall(p).apply(lambda x: x,axis=0)

I get the values but NaN values for other corresponding rows
            0    1    2
  match
0 0       NaN  NaN  Nov
  1       NaN   21  NaN
  2      2000  NaN  NaN
1 0       NaN  NaN  Sep
  1       NaN   08  NaN
  2      2000  NaN  NaN
2 0       NaN  NaN  Nov
  1      1999  NaN  NaN
3 0       NaN  NaN  Nov
  1       NaN   26  NaN
  2      1998  NaN  NaN
4 0       NaN  NaN  Apr
  1      2002  NaN  NaN
5 0      2001  NaN  NaN
6 0       NaN  NaN  Mar
  1       NaN   26  NaN
  2      1998  NaN  NaN
7 0       NaN  NaN  Oct
  1       NaN   07  NaN
  2      1999  NaN  NaN
8 0       NaN  NaN  Nov
  1       NaN   20  NaN
  2      1995  NaN  NaN
9 0       NaN  NaN  Mar
  1       NaN   15  NaN
  2      1996  NaN  NaN

Expected Output :
         0    1    2

0       2000  21  Nov
1       2000  08  Sep
2       1999  NaN Nov
3       1998  26  Nov
4       2002  NaN Apr
... and so on

For each of the row I need to get 3 values, if the first group is not present, it should return me NA in place of that.
df['date'].str.extractall(p).apply(lambda x: ','.join(x.dropna()),axis=1).groupby(level=0).apply(', '.join)

This gives me
    0    Nov, 21, 2000
    1    Sep, 08, 2000
    2        Nov, 1999
    3    Nov, 26, 1998
    4        Apr, 2002
    5             2001
    6    Mar, 26, 1998
    7    Oct, 07, 1999
    8    Nov, 20, 1995
    9    Mar, 15, 1996
    dtype: object

A: The [aA-zZ] regex part is not matching only letters, the letter matching regex is [a-zA-Z].
Besides, you are joining matches with a comma into single strings, while you want to get three separate columns.
You can use a fixed pattern of yours and merge the groups by using
import pandas as pd
df = pd.DataFrame({'date' : ['Nov 21, 2000','Sep 08, 2000','Nov, 1999','Nov 26, 1998','Apr, 2002','2001','Mar 26, 1998', 'Oct 07, 1999', 'Nov 20, 1995', 'Mar 15, 1996']})

p = r'(\d{4})|\s(\d{2}),|([a-zA-Z]+)'
df['date'].str.extractall(p).groupby(level=0).first()

Output:
      0     1     2
0  2000    21   Nov
1  2000    08   Sep
2  1999  None   Nov
3  1998    26   Nov
4  2002  None   Apr
5  2001  None  None
6  1998    26   Mar
7  1999    07   Oct
8  1995    20   Nov
9  1996    15   Mar

That is, after you collect all matches, group them by first level and use first() to get the dataframe.

A: You can try
p = r'([a-zA-Z]{3})? ?(\d{2})?,? ?(\d{4})'
out = df['date'].str.extractall(p)

print(out)

           0    1     2
  match
0 0      Nov   21  2000
1 0      Sep   08  2000
2 0      Nov  NaN  1999
3 0      Nov   26  1998
4 0      Apr  NaN  2002
5 0      NaN  NaN  2001
6 0      Mar   26  1998
7 0      Oct   07  1999
8 0      Nov   20  1995
9 0      Mar   15  1996


text:
Q: Charge distribution in conductors Suppose we have conducting metal cube and we give a positive charge $Q$ to it.
Now giving positive charge simply implies taking away electrons from that small region , so when we take away electrons the electric field created due to increases positive charge density attracts electrons till the charge reached the surface.
Now we have net charge on the surface but how will this be distributed , I mean whether it will be uniformly distributed or not.
I think it should be uniformly distributed so that the charges are at maximum distance from each other but in actually it is non-uniformly distributed.
How does this happens?

A: It would be uniformly distributed if the conductor was a sphere but in case of cube there occurs high charge density at corners, thus the charge will be non uniformly distributed.
As surface charge density is inversely proportional to area, area at the vertices minimizes to point sized thus charge density is high there.
Take this image as an example


text:
Q: Installing Solaris 10 on sunT5220 - ZFS/UFS raid 10? I am in a bit of a time crunch, and need to get two T5220's built. We were very happy to see two boxes in our aged inventory which had 8 HDD's each, but didn't think to check if they were running hardware RAID or not. Turns out that they aren't. When we install, we are given the option to use UFS or ZFS, but when we select a place to install we're only given the option of installing on one single disk. Is it possible to create a software raid 10 across all of the disks and install the OS on that?
Sorry if any lingo is wrong, I'm not really a Sun guy and our guru is out of town right now. Any help would be really appreciated!
Note: Most of the guides I've found on google entail installing the OS on a single disk, and then creating a separate RAID 10 on other disks. We would actually like the OS to reside on the RAID 10. Hope that clarifies things.

A: I doubt you'll read this, but for the benefit of future readers...
You can install on one UFS disk and then set up mirrors to other disks after it's done. OR you can make a root ZFS pool (with two or more more disks in it) and install there.


text:
Q: How to reload my Python source file, when interactively interpreting it with "python -i" When writing or debugging a Python program, I really like using the -i command line switch to be able to directly inspect my functions without having to run everything from start to finish.
However, whenever I make a change to the code I have to close and restart my interactive session, losing all temporary variables that I might have defined. How do I reload my source file from within the python interpreter?

The builtin function reload looks like it was made for this, but I can only use it with named modules:
>> import my_prog
>> print my_prog.x
-- prints an error, because x is not defined --

-- edited my_prog.py to add the x global now...
>> reload(my_prog)
>> print my_prog.x
-- prints x

However, if I instead to do a from my_prog import * in the beginning reload doesn't work, and doing the import again also has no effect.

A: This has to do with the way Python caches modules.  You need a module object to pass to reload and you need to repeat the import command.  Maybe there's a better way, but here's what I generally use:
In Python 3:
>> from importlib import reload
>> import my_prog
>> from my_prog import *
*** Run some code and debug ***
>> reload(my_prog); from my_prog import *
*** Run some code and debug ***
>> reload(my_prog); from my_prog import *

In Python 2, reload is builtin, so you can just remove the first line.

A: When you use from my_prog import * you're pulling symbols into the interpreter's global scope, so reload() can't change those global symbols, only module-level attributes will be changed when the module is recompiled and reloaded.
For example: myprog.py:
x = 1

In interepreter:
>>> import myprog
>>> myprog.x
1
>>> from myprog import x
>>> x
1

Now edit myprog.py setting x = 2:
>>> reload(myprog)
>>> myprog.x
2
>>> x
1

Repeat the from myprog import * to pull the symbols to global scope again:
>>> reload(myprog)
>>> from myprog import *

A: I got it. For example we enter interative mode using this command:
python3 -i filename.py

Then reload it using importlib package like this:
from importlib import reload
reload(filename) # Need no quotatiom mark


text:
Q: A small table join large table on like, using impala An impala query as below runs very slow.
SELECT pattern, MAX(time)
  FROM (SELECT t.time, p.pattern
          FROM t
          JOIN p
            ON (t.name LIKE p.pattern)) AS tmp
 GROUP BY pattern

p is large of 1billion records, and t is small of only 1 record.
How can I optimize this? This is actually a nested loop join, but why did this take about half an hour to complete?
What's more, when I use the following query
SELECT time
  FROM p
 WHERE name LIKE 'one_pattern'
 ORDER BY time DESC LIMIT 1

It only takes 3s. I am really confused.


text:
Q: Detect if a call has been answered and if not make another call to another number I am making an application that would be connected to a headset and when pressing the central button makes a call.
The problem would be that if that call is not answered I should redial another number but I've been looking and it is not possible to know if the other person answered the call or not, only if it has been made, just finished or there is no call in progress.
Is it possible to perform the action I need, right now I am using phoneStateListener.


text:
Q: Getting error with rsync and scp My issue is an odd one. I am logged into my University's server with my host name and all that good stuff. I am able to copy files from my local computer into my school's account. My issue, is the other way around. I am unable to transfer files from the school's server onto my local computer. I am fairly certain I have the syntax correct:
rsync -v username@hostname:~/hw0/hello.cpp .
the issue is, is that it copies it the home directory in my schools computer. Anyone know how to fix this?
Or even worse, if I use:
rsync -v username@hostname:~/hw0/hello.cpp /Users/anthony
I get the error message:
rsync: change_dir#3 "Users" failed: No such file or directory(2)
rsync error: errors selecting input/output files, dirs (code 3) at main.c(694) [Receiver=3.1.1]
So overall, I am pretty sure the issue is, is that the command on my school's server is trying to send it within the server, i.e. NOT to my local computer.

A: If you are running these rsync commands on the remote computer, you are telling it to connect to itself via ssh and copy the file.
If you run them on the Mac, you are telling the mac to connect to the remote computer and copy the file to itself.  I presume this is what you want to do.
There are two basic solutions to this:

*

*just run the commands on the Mac itself.  The way they are written, they will just work properly in that context.

*If you are able to ssh back to your Mac from the Uni computer, you can rewrite the commands so that it is copying local files (local to the remote computer, that is) to the Mac.  From the remote computer's perspective, your Mac is a remote computer.  For example:
rsync ~/hw0/hello.cpp anthony@mac-host-or-ip:/Users/anthony/
Note that if your Mac is behind a firewall or NAT gateway or similar, it may be difficult to connect back to your Mac...but solving that is an entirely different problem needing a question of its own.


text:
Q: Restarting active query in codeigniter For example, if ı have lines like this:
$this->db->where("blabla",$blala);

And following this line, I decided not to use this where clause (in runtime) and start doing a query from scratch. How can I disregard this where clause in active record?

A: You can't.
This is a logical problem which you have to make sense of.
Instead of saying
$this->db->where('blabla', $blala);
if($dont_use_where_clause) {
  //something to ignore the where cause which CI doesn't provides anyway
}

That's like starting your car and trying to get back the fuel you used to start it with.
You would have to do something more logical like this:
if(!$dont_use_where_clause) {
  $this->db->where('blabla', $blala);
}

This makes sense, because it's the logical way of doing those things. That's like saying 'if I don't want to use fuel, don't start the car'. Get it?

A: Maybe you can try
$this->db->_reset_select();


text:
Q: Auto increase version code after each build in Android Is there a way to auto increase version code after each build in Android? I'm using Gradle.
Thanks

A: Found a custom build.gradle file that does the trick here: link


text:
Q: Starting threads and waiting for them all to finish I have the following piece of code (C#): is it correct?
Thread[] threads = new Thread[totalThread];

for (int i=0; i<totalThread; i++) {
   threads[i] = new Thread(new ThreadStart(Work));
}

sw.Start();

for (int j=0; j<num_threads; j++) {
   threads[j].Start();
}

for (int k=0; k<num_threads; k++) {
   threads[k].Join();
}

sw.Stop();

sw is a Stopwatch, work is some method. I would like to time this method, using a few threads, but the whole thing freezes (seems like it is not joining). I need to know if my thread handling is good, or if I'm screwing up. If the latter, it is obvious that my problem lies in the method I'm calling, rather than in thread mgmt. Thanks.

A: Since you mentioned freezing.  Try to review your Work method and look for deadlocks. Also, add some timeout mechanism on your Join calls.

A: You could get rid of the .Join loop and use a ManualResetEvent in each thread.
You would then wait on the ManualResetEvents to all become signaled.

A: It's perfect as it is. I don't see any problem other that the num_threads/totalThread. Note that if totalThread is big (where with big I mean bigger than 1-2 for each CPU Core), you should probably use the ThreadPool.


text:
Q: Kafka: Get offset of Record by Java Producer Client I am trying to implement a Kafka Producer-Consumer in Java. Below is the snippet. I know this is not a good code(probably killing the whole use of asynchronous), I just want a hands on and for testing.
public void publishMessage(RequestFeedback requestFeedback) {
    LOGGER.info("Going to push Feedback:{}", requestFeedback);
    try {
      ProducerRecord<Object, Object> record = new ProducerRecord<>(TOPIC_NAME,
          objectMapper.writeValueAsString(requestFeedback));
      Future<RecordMetadata> recordMetadataFuture = producer.send(record);
      try {
        RecordMetadata recordMetadata = recordMetadataFuture.get();
        LOGGER.info("Record:{} pushed successfully to Kafka with offset:{}",
          record,recordMetadata.offset());
      } catch (InterruptedException e) {
        e.printStackTrace();
      } catch (ExecutionException e) {
        e.printStackTrace();
      }
    } catch (JsonProcessingException e) {
      LOGGER.error("Error in converting object:{} into JSON String because of:",
          requestFeedback, e);
    }
}

Logs:
{
  "@timestamp": "2017-08-09T15:20:47.839+00:00",
  "@version": 1,
  "message": "Record:ProducerRecord(topic=FEEDBACK_SENTIMENT, partition=null, key=null, value={\"id\":8,\"instanceId\":7,\"userId\":61,\"userResponseId\":12,\"feedbackText\":\"Hello\"} pushed successfully to Kafka with offset:-1",
  "logger_name": "com.kafkaProducer.v3.utils.kafka.FeedbackProducer",
  "thread_name": "main",
  "level": "INFO",
  "level_value": 20000,
  "HOSTNAME": "Shubhams-MacBook-Pro.local",
  "app_name": "kafkaProducer",
  "log_type": "app"
}

The problem is offset is coming as -1. And when I am checking consumer logs for offset, it is coming as different. What I am missing ?


text:
Q: React Native IOS - Receive failed with error "Software caused connection abort" Its my first time when I eject an app built in Expo but I get some strange log when I come back from background in my app and sometimes it gives me Network Error. I also use Socket.IO which I due to this also drops the connection with it
Any idea what it can be and how it should be solved?
2021-01-28 15:44:21.919753+0000 client[15322:3152792] BackgroundSession <4FD896C2-975D-48B7-A148-99A86AF85CD1> connection to background transfer daemon interrupted
2021-01-28 15:44:21.922110+0000 client[15322:3152745] BackgroundSession <B895AD11-0ABE-42C6-B1C3-201FE16EE801> connection to background transfer daemon interrupted
2021-01-28 15:44:21.924908+0000 client[15322:3152787] BackgroundSession <4FD896C2-975D-48B7-A148-99A86AF85CD1> connection to background transfer daemon invalidated
2021-01-28 15:44:21.927499+0000 client[15322:3152745] BackgroundSession <B895AD11-0ABE-42C6-B1C3-201FE16EE801> connection to background transfer daemon invalidated
2021-01-28 15:44:21.927135+0000 client[15322:3152694] [connection] nw_read_request_report [C18] Receive failed with error "Software caused connection abort"
2021-01-28 15:44:21.931216+0000 client[15322:3152694] [connection] nw_read_request_report [C21] Receive failed with error "Software caused connection abort"
2021-01-28 15:44:21.934258+0000 client[15322:3152694] [connection] nw_read_request_report [C1] Receive failed with error "Software caused connection abort"


text:
Q: Matrix Rotation Around an Arbitrary Axis Bug I have been attempting to get matrix rotation around an arbitrary axis working, I think I'm close but I have a bug. I am relatively new to 3D rotations and have a basic understanding of what is going on.
public static Matrix4D Rotate(Vector3D u, Vector3D v)
{
    double angle = Acos(u.Dot(v));
    Vector3D axis = u.Cross(v);

    double c = Cos(angle);
    double s = Sin(angle);
    double t = 1 - c;

    return  new Matrix4D(new double [,]
    {
        { c + Pow(axis.X, 2) * t,  axis.X * axis.Y * t -axis.Z * s, axis.X * axis.Z * t + axis.Y * s, 0 },
        { axis.Y * axis.X * t + axis.Z * s, c + Pow(axis.Y, 2) * t, axis.Y * axis.Z * t - axis.X * s, 0 },
        { axis.Z * axis.X * t - axis.Y * s, axis.Z * axis.Y * t + axis.X * s, c + Pow(axis.Z, 2) * t, 0 },
        { 0, 0, 0, 1 }
    });
}

The above code is the algorithm for the matrix rotation. When I test the algorithm with unit vectors I get the following:
Matrix4D rotationMatrix = Matrix4D.Rotate(new Vector3D(1, 0, 0), new Vector3D(0, 0, 1));

Vector4D vectorToRotate = new Vector4D(1,0,0,0);

Vector4D result = rotationMatrix * vectorToRotate;

//Result
X = 0.0000000000000000612;
Y = 0;
Z = 1;
Length = 1;

With a 90 degree rotation I find it works almost perfectly. Now lets look at a 45 degree rotation:
Matrix4D rotationMatrix = Matrix4D.Rotate(new Vector3D(1, 0, 0), new Vector3D(1, 0, 1).Normalize());

Vector4D vectorToRotate = new Vector4D(1,0,0,0);

Vector4D result = rotationMatrix * vectorToRotate;

//Result
X = .70710678118654746;
Y = 0;
Z = .5;
Length = 0.8660254037844386;

When we take the atan(.5/.707) we find that we have a 35.28 degree rotation instead of a 45 degree rotation. Also the length of the vector is changing from 1 to .866. Does anyone have any tips on what I am doing wrong?

A: Your matrix code looks correct, but you need to normalize the axis too (just because u and v are normalized doesn't mean u cross v also is).
(I would also recommend using a simple multiply instead of Pow, for performance and accuracy reasons; but this is minor and not the source of your problem)

A: Just for posterity, this is the code that I use for this exact thing. I alway recommend using Atan2(dy,dx) instead of Acos(dx) because it is more stable numerically at angles near 90°.
public static class Rotations
{
    public static Matrix4x4 FromTwoVectors(Vector3 u, Vector3 v)
    {
        Vector3 n = Vector3.Cross(u, v);
        double sin = n.Length();  // use |u×v| = |u||v| SIN(θ)
        double cos = Vector3.Dot(u, v); // use u·v = |u||v| COS(θ)

        // what if u×v=0, or u·v=0. The full quadrant arctan below is fine with it.
        double angle = Atan2(sin, cos);
        n = Vector3.Normalize(n);

        return FromAxisAngle(n, angle);
    }
    public static Matrix4x4 FromAxisAngle(Vector3 n, double angle)
    {
        // Asssume `n` is normalized
        double x = n.X, y = n.Y, z = n.Z;
        double sin = Sin(angle);
        double vcos = 1.0-Cos(angle);

        return new Matrix4x4(
            1.0-vcos*(y*y+z*z), vcos*x*y-sin*z, vcos*x*z+sin*y, 0,
            vcos*x*y+sin*z, 1.0-vcos*(x*x+z*z), vcos*y*z-sin*x, 0,
            vcos*x*z-sin*y, vcos*y*z+sin*x, 1.0-vcos*(x*x+y*y), 0,
            0, 0, 0, 1.0);
    }
}

Code is C#


text:
Q: How to consume an ArcGIS Server service from ArcObjects? I have this end point to my ArcGIS Server:
http://myarcgisserver/arcgis/rest/services/prueba/GMRE/MapServer
I'm trying it with GisClient:
public void requestServer(string username, string password)
    {

        string url = "http://myarcgisserver/arcgis/rest/services/prueba/GMRE/MapServer";
        var gisServer = OpenConnection(url);
        MessageBox.Show(gisServer.ToString());

    }

private static IAGSServerConnection OpenConnection(string svcUrl)
    {
        //create a property set to hold connection properties
        var connectionProps = new PropertySet() as IPropertySet;
        //specify the URL for the server
        connectionProps.SetProperty("URL", svcUrl);

        //create a new ArcGIS Server connection factory
        var connectionFactory = (IAGSServerConnectionFactory2)new AGSServerConnectionFactory();
        var gisServer = connectionFactory.Open(connectionProps, 0);
        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(connectionFactory);
        return gisServer;
    }

But I get a exception saying 'Invalid url'
My service in the browser:

How can I consume it from arcobjects?

A: Often, when constructing ArcGIS Server service URLs you need to include the type of service you're connecting to in the URL, such as MapServer for a standard map service.
Try changing your URL to something like "http://myarcgisserver/arcgis/rest/services/prueba/MapServer"
See Components of ArcGIS URLs - ArcGIS Server end user URLs, specifically the section labelled "ArcGIS services", and see the table "REST service values" if MapServer is not correct for your URL.

A: Not sure if this helps, but here's how I have queried an ArcGIS Server Feature Service in the past:
//query objectid = 1
string url = @"https://my.arcgis.server/arcgis/rest/services/MyProject/MapServer/0/query?where=OBJECTID=1&text=&objectIds=&time=&geometry=&geometryType=esriGeometryPoint&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=*&returnGeometry=false&returnTrueCurves=false&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&returnDistinctValues=false&resultOffset=&resultRecordCount=&f=pjson";
string json;

using (WebClient w = new WebClient())
{
    StreamReader sr = new StreamReader(w.OpenRead(queryUrl));
    json = sr.ReadToEnd();
    sr.Close();
}

where json is a JSON string you can deserialize to an object.