text:
Q: Django model default sort order using related table field Is it possible to set the default sort order for a model to a field from a related model (rather than the integer key) i.e. something that yields a SQL order by clause with a field from both models? If so, how? I can do this via query_by but I can't figure out how to set it by default. Thanks.
class Foo(models.Model):
    name = models.CharField(max_length=50)

class Bar(models.Model):
    related = models.ForeignKey(Foo)
    bar_date = models.DateField()

    class Meta:
        ordering = ('bar_date', 'related.name', )

A: Take a look at order-with-respect-to.

A: As an alternative to order_with_respect_to (which only supports one field), you can use a custom manager to provide the ordering. This also allows you to order on multiple fields in Foo and to still have a normal Bar.objects manager. You'll have to test to see if the Meta.ordering or the custom manager ordering is applied first.
class FooSortedManager(models.Manager):
    def get_query_set(self):
        return super(FooSortedManager, self).get_query_set().order_by('foo__name')

class Foo(models.Model):
    name = models.CharField(max_length=50)

class Bar(models.Model):
    related = models.ForeignKey(Foo)
    bar_date = models.DateField()

    foo_sorted = FooSortedManager()

    class Meta:
        ordering = ('bar_date',)

A: I use django 1.2.7 and instead of connecting ForeignKey.Attribute we should use "__", so this code will work:
class Meta:
    ordering = ('bar_date', 'related__name', )

A: In modern version of django it is:
class Meta:
        ordering = ['word']

A: hmm ... I am solving similar thing while upfactoring old django application, written before qs-rf, where "dot" notation was probably used ??? ... it took me few hours to diclose "something" and I am still NOT sure, but ... try to replace dot with "__" (double underscores), this can help, .. In fact, curentlly, I still HOPE TOO :-)))
@stuart: for "order_with_respect_to", I readed something about automatically added physical model field into child table ... I dont completelly understand how things are here ... IMHO documentation is very bad about ordering syntax, howgh!
no comment :-)
http://code.djangoproject.com/ticket/8975
anyway, I like Django, yet ... :-))

A: class Question(models.Model):

  question_text=models.CharField(max_length=200)
        class Meta:
    verbose_name_plural="  Question"

class Choice(models.Model):

  question=models.ForeignKey(Question,on_delete=models.CASCADE)
    class Meta:
    verbose_name_plural=" Choice"

Either you can alter the number of spaces before the class name as above or order it using numbers as below:
class Question(models.Model):

  question_text=models.CharField(max_length=200)
        class Meta:
    verbose_name_plural="1.Question"

class Choice(models.Model):

  question=models.ForeignKey(Question,on_delete=models.CASCADE)
    class Meta:
    verbose_name_plural="2.Choice"


text:
Q: Building virtual infrastructure - how to start? I am building up a virtual infrastructure in vmware workstation, and I don't know how to start. (I am university student, so I have dreamspark licenses and these stuff. The aim of this infrastructure is learning.) The idea is the next:

*

*Host machine (i5-2500K, 8 GB RAM, 250 GB SSD) with Windows 8 Pro (x64) and vmware workstation. Host machine have the developer sw-s (eclipse, vs2012).

*Windows servers: need IIS (ASP.NET), MS-SQL -> definitely windows server 2012 standard

*Linux servers: Apache+PHP+MySQL (Centos 6.4), Oracle (Centos 6.4), Python+Flask (Ubuntu 13.04 Server) (all 64 bit)

*The servers are started when I actually need them.

*And many clients (win8, win7, ubuntu desktop).

Now I decided the linux servers without desktop, and then 256 MB memory are enough for them. Is it possible to install Windows Server 2012 Standart without GUI on 512 MB RAM? Some of the infrastructure is ready, but I still have the question:

*

*The servers will have static IP, while the clients will get by dhcp. That's easy in IPv4, but any good strategies for ipv6?

*I would like to create a domain - like .vmware or something, so I can access my vm-s easily - e.g. luke.vmware. I would not like to hack hosts files, because its hard to maintain on a lot of vm-s. I think I will need a DNS server, which makes life easier. But it should run always. The vm network is behind NAT (VMNet8), so where should I install? Is it ok in the NAT network, or must it be the host machine? Any good advice? I stick to vmware workstation (I have problems with hyper-v performance and virtualbox stability).
-Should I user NFS or is vmware shared folders enough? When yes, NFS should be computer, or VM.

*Is there a good way to maintain the vms (e.g. shared folders, change memory, overall GRID interface), or should i script with the vmware api? I would like an overall interface (sync visio diagram with excel with vmware settings).

Thank you in advance.
Lajos

A:
Host machine (i5-2500K, 8 GB RAM, 250 GB SSD) with Windows 8 Pro (x64)

That's not much RAM space, nor HD space. You'll be able to run 1 or 2 VMs comfortably, but that's it.

and vmware workstation

That's fine for a developer's computer, but if you're interested in learning "enterprise" virutalization you should look at ESXi, Hyper-V Server, or similar.

Windows servers: need IIS (ASP.NET)

That's available in Win8. If you want to try setting up dedicated machines go for it. But if you just want to develop on IIS, I'd recommend just installing it on your development workstation.

MS-SQL -> definitely windows server 2012 standard

MS-SQL can also be installed on Windows 8

Linux servers: Apache+PHP+MySQL (Centos 6.4), Oracle (Centos 6.4), Python+Flask (Ubuntu 13.04 Server) (all 64 bit)

Do you have some purpose for this smattering of technology? That a wide breadth of OSes, and no apparent reason for wanting them (other than "gotta catch'm all" syndrome)

The servers are started when I actually need them.

That much is obvious as you don't have the RAM to start them all in a useful state. You're almost certainly going to run out of HD space setting all that up too.

And many clients (win8, win7, ubuntu desktop).

See previous comment about why the Smörgåsbord of OSes.

The servers will have static IP, while the clients will get by dhcp. That's easy in IPv4, but any good strategies for ipv6?

Why not use static IPs for servers and DHCP for clients in IPv6 as well?? Asking this makes me think you might need to read up on IPv6 a bit more.

I would like to create a domain

Bad idea from the start, but as you're a student just starting the world might forgive you if you use .local. Keep in mind for the future, that "fake" domains should never be used in any environment outside "just messing around". Never in business, not in development environments, not in pre-production, not in testing, never never never. It's a crazy bad habit that will cause many headaches for decades to come. Most SysAdmins hope there's a special level of hell reserved for people who use .local in business environments.

I would not like to hack hosts files, because its hard to maintain on a lot of vm-s. I think I will need a DNS server, which makes life easier. But it should run always.

Correct, this is why DNS was invented in the first place. Probably shouldn't reinvent the wheel. Put the server just about anywhere on your network where all the servers can access it. This could be a VM, or a physical box, or your Host machine...

Should I user NFS or is vmware shared folders enough? When yes, NFS should be computer, or VM.

Windows doesn't do NFS easily, and not well when it does. Like many of the technologies so far, I'd recommend against using it unless it solves a specific problem you're trying to get around.

Is there a good way to maintain the vms (e.g. shared folders, change memory, overall GRID interface), or should i script with the vmware api?

APIs and Scripts are good ideas. I wouldn't get too wild with this unless you really want to dive into it.

I would like an overall interface (sync visio diagram with excel with vmware settings).

Documentation is a good idea. It's got to be the weakest skill I see from college graduates. It's not that they can't create documentation (for the most part), but the quality is lacking, and the discipline to actually do it is severely lacking.
Two thoughts:

*

*You have a monstrous pile of technology there. You seem enthusiastic to learn some of all of it. This is the role of the IT Generalist. However, you're also crossing disciplines a lot, which almost never works out. You have application development software, web development, and infrastructure. The IT Industry has whole conferences on getting these separate and relatively diverse groups to talk to each other more effectively, and to understand one another's different goals. I highly recommend you pick the set of technology or role that you like the most and give it a try, forget the rest at least for now.
Many basic skills cross boundaries. For instance, Administrators (who maintain infrastructure: Systems, Networks, Databases, Security, etc) need to be able to read, understand, and write scripts (PowerShell and VBScript on Win; Shell and Interpreted on *nix); many also know various programming languages. Software Developers need to know a little bit of everything they'll be working on. Web Developers need to know a good amount of the software that runs their sites, and what their clients will be running.

*The other thought is that many people believe the Generalist role is on the decline, and most indications support this. "Jack of all trades - Master of none" is not a compliment. At very small shops knowing a wide variety of technologies is essential as there's few people developing, installing, and maintaining that technology. Outside of those very small shops, everyone else want specialists, masters of their niche.
Check out the Careers site. You'll find postings for "Ruby Developer", "PHP Developer",  ".NET Developer", or "Linux Administrator". If you search for "Generalist" you'll get 17 results right now. The very first one says "Ruby on Rails Generalist" (they're looking for a Ruby Web Developer - NOT actually a generalist). The second listing is a "Java Developer" (also not a generalist). Third is a "Software Engineer - Generalist", and the description immediately starts in to a PaaS Engineer (Virtualization Administrator essentially; also not much of a generalist job). You get the idea, but I went though the list and only 2 are actually looking for something like a Generalist.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Generate local features For each keypoint by using SIFT I have an image and i want to locate key points by using SIFT detector and group them, then i want to generate local features for each key point by using SIFT, would you please help me how I can do it ? Please give me any suggestions
I really appreciate your help

A: I'm not sure that I understand what you mean, but if you extract SIFT features from an image, you automatically get the feature descriptor which is used to compare features to each other. Of course you also get the feature location, size, direction and hessian value with it.
While you can group those features by there position in the image, but there is currently no way that I'm aware of to compare those groups, since they may be locally related, but can have wildly different feature descriptors.
Also I would suggest SURF. It is faster and not patent encumbered.
Have a look at the examples from OpenCV if you want specific instructions on how to retrieve and compare descriptors.

A: If you are using opencv here are the commands to do it, else if you are using the matlab see the link MATCHING_using surf

USING OPENCV::
// you can change the parameters for your requirement
    double hessianThreshold=200;
    int octaves=3;
    int octaveLayers=4;
    bool upright=false;
    vector<KeyPoint>keypoints;

//The detector detects the keypoints in an image here image is RGBIMAGE of Mat type
SurfFeatureDetector detector( hessianThreshold, octaves, octaveLayers, upright );
detector.detect(RGB_IMAGE, keypoints);

//The extractor computesthe local features around the keypoints
SurfDescriptorExtractor extractor;
Mat descriptors;
extractor.compute( last_ref, keypoints, descriptors);

// all the key points local features are stored in rows one after another in descriptors matrix...
Hope it is useful:)


text:
Q: Creating a dice that doubles and continues to roll if it lands on a specific number in C#? I am trying to make a program that I Believe has to make use of recursion. In short: create a program that will throw a Dice. If it lands on a 6, two Dices are created and rolled, and so on until no more 6 are rolled.
The problem is not creating a new or true random object, but the recursive Dices.
The recursion method looks like this:
    public static int Recursion(int a)
    {
        Random m = new Random();

        if (a < 6)
        {
            return a;
        }

        else
        {
            a = m.Next(1, 7);
            return Recursion(a) * 2;
        }
    }

A: Possibly something like this?
public static int Roll() {
   return Roll(new Random(), 1);
}

public static int Roll(Random random, int diceCount) {
    int sum = 0;
    for (int dice = 1; dice <= diceCount; ++dice) {
        int rolled = random.Next(1, 7);
        if (rolled == 6) {
            sum += Roll(random, 2)
        }
        else
        {
            sum += rolled;
        }

    }

    return sum;
}

So, first I roll one die/dice. If it is not 6, then I accept its value as the result. If it is six, then I remove that die/dice, and replace it with two other I roll. Then, for each of the new ones I follow the same rule, until all the dice on the table is rolled and none of them is 6. Now I sum all the value of dice. This is what this recursive algorithm does. Note, that - however it has infinitely low chance - you can play this until the end of times, since there is always chance of rolling 6, so you can possibly roll only 6's until you die.

A: You can make it more object oriented by creating a dice object:
using System;
using System.Collections.Generic;

class Dices
{
    public class Dice
    {
        private static Random roler = new Random();
        private int roledNumber;
        public int Role()
        {
            roledNumber = roler.Next(6) + 1 ;
            return roledNumber;
        }

        public int Number
        {
            get { return roledNumber; }
        }
    }

    static void Main(string[] args)
    {
        List<Dice> allDices = new List<Dice>();

        Dice firstDice = new Dice();
        allDices.Add(firstDice);

        if (firstDice.Role() == 6) createDices(allDices);
    }

    static void createDices(List<Dice> dices)
    {
        Dice first = new Dice();
        dices.Add(first);
        if (first.Role() == 6) createDices(dices);
        Dice second = new Dice();
        dices.Add(second);
        if (second.Role() == 6) createDices(dices);

    }
}


text:
Q: Send private message using Node.js and Socket.io I am implementing a small chat application using node.js and socket.io. Everything goes well till I try to send a private message. Here is the code for the server:
...
var to = users[name];
socket.to(to).emit('private message', {userName: socket.username, message: msg} );
...

Code on the client side:
...
socket.on('private message', function(data){
    alert(data.message);
});
...

My problem is that on the client side the event is never fired, can anyone help me to fix this issue? Thank you.

A: Maybe this is too late to answer..
You can use socket.id to send private message or send data privately.
io.on('connect', function(){
    io.to(socket.id).emit('send message', 'test');
});


text:
Q: How to make nerdcommenter treat .ctp files as .html - VIM I use nerdcommenter to comment code.
I comment by <leader>cc. It does work great when I do it with .html file types. It surrounds code with <-- code -->
But with .ctp files I have to change filetype to html first by :set filetype=html, and it starts working as expected, but my syntax highlight changes too.
Is there a way to make nerdcommenter treat .ctp files as .html?

A: You can add this to your .vimrc
au BufNewFile,BufRead *.ctp set filetype=html

By this line, you make vim assign the filetype by the file extension automatically.

A: Nerdcommenter uses the 'commentstring' setting to determine which sort of comment to use.  :h 'commentstring' gives the following:
                    *'commentstring'* *'cms'* *E537*
'commentstring' 'cms'   string  (default "/*%s*/")
            local to buffer
            {not in Vi}
            {not available when compiled without the |+folding|
            feature}
    A template for a comment.  The "%s" in the value is replaced with the
comment text.

You could use :setlocal cms to change the comment string for the active buffer, or even use an autocommand to :setlocal for you whenever you open the appropriate file type.
Edit:  I suppose I should say that I haven't actually tried this with nerdcommenter in particular, but if it uses 'commentstring' like the documentation says, this should work.

A: Thanks to @ryuichiro it was solved. Here is the full post.
We just have to use alternative commenting like:
let g:NERDCustomDelimiters = {
     \ 'php': { 'left': '//', 'leftAlt': '<!--', 'rightAlt': '-->' }
     \ }

And, to change to alternative commenting style, use <Leader>ca
Again, here is the full post why and how it works.


text:
Q: WebSocket using Springboot I have cloned the following webSocket project https://github.com/thegeekyasian/WebSocket-SpringBoot and the server is up and running.  And postman client was able to connect to the server successfully. But when I rename the packages of this project and I try to connect to the server using postman client I have the following error. Could you please help?
Could not connect to ws://localhost:8080/webSocket
09:38:35
Error: Unexpected server response: 404
Handshake Details
Request URL: http://localhost:8080/webSocket
Request Method: GET
Status Code: 404
Request Headers
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: GmRXEBdLLrcJuIQH59nkuA==
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Host: localhost:8080
Response Headers
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Wed, 11 Jan 2023 17:38:35 GMT
I tried to connect using ws://localhost:8080/webSocket


text:
Q: ViewPager with GridLayout I want to make a ViewPager , when the user click on the photo from an album , he would be able to scroll between images with a ViewPager . I need some help with it . Any answer will be apreciate, thanks. This is my code:
ViewImage class where my photo is showed in full-screen :
  public class ViewImage extends Activity {
    // Declare Variable
             TextView text;
          ImageView imageview;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from view_image.xml
    setContentView(R.layout.view_image);

    // Retrieve data from MainActivity on GridView item click
    Intent i = getIntent();

    // Get the position
    int position = i.getExtras().getInt("position");

    // Get String arrays FilePathStrings
    String[] filepath = i.getStringArrayExtra("filepath");

    // Get String arrays FileNameStrings
    String[] filename = i.getStringArrayExtra("filename");

    // Locate the TextView in view_image.xml
    text = (TextView) findViewById(R.id.imagetext);

    // Load the text into the TextView followed by the position
    text.setText(filename[position]);

    // Locate the ImageView in view_image.xml
    imageview = (ImageView) findViewById(R.id.full_image_view);

    // Decode the filepath with BitmapFactory followed by the position
    Bitmap bmp = BitmapFactory.decodeFile(filepath[position]);

    // Set the decoded bitmap into ImageView
    imageview.setImageBitmap(bmp);

}
}

AlbumActivity class , where is created a new album:
 public class AlbumActivity extends Activity implements AppCompatCallback {
private AppCompatDelegate delegate1;

private final int REQUEST_CODE_CAMERA_IMAGE = 1000;
private final int REQUEST_CODE_EXTERNAL_IMAGE = 2000;

String nameAlbum;
// Declare variables
private String[] FilePathStrings;
private String[] FileNameStrings;
private File[] listFile;
GridView grid;
GridViewAdapter adapter;
File file;
boolean deleted;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    delegate1 = AppCompatDelegate.create(this, this);

    //call the onCreate() of the AppCompatDelegate
    delegate1.onCreate(savedInstanceState);

    //use the delegate to inflate the layout
    delegate1.setContentView(R.layout.album_activity);

    Toolbar toolbar = (Toolbar) findViewById(R.id.mytoolbarr);

    delegate1.setSupportActionBar(toolbar);
    delegate1.setTitle("Your Pictures");

    Button btnChoosePicture = (Button) findViewById(R.id.addimage);
    Intent intent = getIntent();
    nameAlbum = intent.getStringExtra("nameAlbum");
    // Check for SD Card
    if (!Environment.getExternalStorageState().equals(
            Environment.MEDIA_MOUNTED)) {
        Toast.makeText(this, "Error! No SDCARD Found!", Toast.LENGTH_LONG)
                .show();
    } else {
        // Locate the image folder in your SD Card
        file = new File(Environment.getExternalStorageDirectory()
                + File.separator + nameAlbum);
        if (file.isDirectory()) {
            listFile = file.listFiles();
            // Create a String array for FilePathStrings
            FilePathStrings = new String[listFile.length];
            // Create a String array for FileNameStrings
            FileNameStrings = new String[listFile.length];

            for (int i = 0; i < listFile.length; i++) {
                // Get the path of the image file
                FilePathStrings[i] = listFile[i].getAbsolutePath();
                // Get the name image file
                FileNameStrings[i] = listFile[i].getName();
            }
        }

        // Locate the GridView in gridview_main.xml
        grid = (GridView) findViewById(R.id.gridview);
        // Pass String arrays to LazyAdapter Class
        adapter = new GridViewAdapter(this, FilePathStrings, FileNameStrings);
        // Set the LazyAdapter to the GridView
        grid.setAdapter(adapter);

        // Capture gridview item click
        grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                Intent i = new Intent(AlbumActivity.this, ViewImage.class);
                // Pass String arrays FilePathStrings
                i.putExtra("filepath", FilePathStrings);
                // Pass String arrays FileNameStrings
                i.putExtra("filename", FileNameStrings);
                // Pass click position
                i.putExtra("position", position);
                startActivity(i);
            }

        });
        grid.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, final View view, final int position, final long id) {

                AlertDialog.Builder builder = new AlertDialog.Builder(AlbumActivity.this);

                builder.setCancelable(true);
                builder.setMessage("Are you sure you want to delete this picture ?");
                builder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();

                    }

                });
                builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        File filepath = Environment.getExternalStorageDirectory();
                        File dir5 = new File(filepath.getAbsolutePath()
                                + nameAlbum+FileNameStrings[position]);

                        File file3 = new File(String.valueOf(dir5));
                       deleted = file3.delete();
    adapter.notifyDataSetChanged();
                        finish();
                        startActivity(getIntent());

                        dialog.dismiss();

                    }
                });

                builder.setTitle("Delete Picture");
                AlertDialog dialog = builder.create();
                dialog.show();
                return true;
            }
        });

            }

   //select picture from external storage
        btnChoosePicture.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                // choose picture from gallery
                Intent PhotoPickerIntent = new Intent(
                        Intent.ACTION_PICK);
                File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                String pictureDirectoryPath = pictureDirectory.getPath();
                Uri data = Uri.parse(pictureDirectoryPath);
                PhotoPickerIntent.setDataAndType(data, "image/*");

                startActivityForResult(PhotoPickerIntent,
                        REQUEST_CODE_EXTERNAL_IMAGE);

            }
        });
    }
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_setting) {
        return true;
    }else if(id==android.R.id.home){
        finish();
    }

    return super.onOptionsItemSelected(item);
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {

    // get image from external storage

        if(resultCode == RESULT_OK){
        if (requestCode == REQUEST_CODE_EXTERNAL_IMAGE) {
            Uri uri = data.getData();
            InputStream inputStream;
            try {
                inputStream = getContentResolver().openInputStream(uri);
                Bitmap image = BitmapFactory.decodeStream(inputStream);

                ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>();
                bitmapArray.add(image);

                OutputStream output;
                // Find the SD Card path
                File filepath = Environment.getExternalStorageDirectory();

    int count2 =0;
                String paranteze = "("+count2+")";
                int count1 = new File("/mnt/sdcard" +     nameAlbum).listFiles().length;
                count1 = count1 + 1;
               String nameImage = "Wallpaper_" +count1 +".jpg";
 for(int j =0;j<listFile.length;j++){
FileNameStrings[j] = listFile[j].getName();
if(FileNameStrings[j].equals(nameImage)){
    nameImage="Wallpaper_" +count1+paranteze +".jpg";
    count2++;

}
    }
                    count2++;
                    File dir = new File(filepath.getAbsolutePath()
                            + nameAlbum);

                    // Retrieve the image from the res folder

                    // Create a name for the saved image
                    file = new File(dir, nameImage);

                try {
                    inputStream = getContentResolver().openInputStream(uri);
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    output = new FileOutputStream(file);

                    // Compress into png format image from 0% - 100%
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100,   output);
                    output.flush();
                    output.close();

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }

    if (!Environment.getExternalStorageState().equals(
            Environment.MEDIA_MOUNTED)) {
        Toast.makeText(this, "Error! No SDCARD Found!", Toast.LENGTH_LONG)
                .show();
    } else {
        // Locate the image folder in your SD Card
        file = new File(Environment.getExternalStorageDirectory()
                + File.separator + nameAlbum);

        if (file.isDirectory()) {
            listFile = file.listFiles();
            // Create a String array for FilePathStrings
            FilePathStrings = new String[listFile.length];
            // Create a String array for FileNameStrings
            FileNameStrings = new String[listFile.length];

            for (int i = 0; i < listFile.length; i++) {
                // Get the path of the image file
                FilePathStrings[i] = listFile[i].getAbsolutePath();
                // Get the name image file
                FileNameStrings[i] = listFile[i].getName();
                // Locate the GridView in gridview_main.xml
                grid = (GridView) findViewById(R.id.gridview);
                // Pass String arrays to LazyAdapter Class
                adapter = new GridViewAdapter(this, FilePathStrings,   FileNameStrings);
                // Set the LazyAdapter to the GridView
                grid.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            }
            }
        }

    }

}

@Override
public void onSupportActionModeStarted(ActionMode mode) {

}

@Override
public void onSupportActionModeFinished(ActionMode mode) {

}

@Nullable
@Override
public ActionMode onWindowStartingSupportActionMode(ActionMode.Callback    callback) {
    return null;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_album_activity, menu);

    return true;
}

@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
    switch (item.getItemId()){
        case R.id.action_add:

            // choose picture from gallery
            Intent PhotoPickerIntent = new Intent(
                    Intent.ACTION_PICK);
            File pictureDirectory =         Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            String pictureDirectoryPath = pictureDirectory.getPath();
            Uri data = Uri.parse(pictureDirectoryPath);
            PhotoPickerIntent.setDataAndType(data, "image/*");

            startActivityForResult(PhotoPickerIntent,
                    REQUEST_CODE_EXTERNAL_IMAGE);

         break;
        case R.id.action_delete:

            break;

    }
    return super.onMenuItemSelected(featureId, item);

}
  }

And of  course my GridViewAdapter class
  public class GridViewAdapter extends BaseAdapter {
  ImageView image;
   // Declare variables
private Activity activity;
private String[] filepath;
private String[] filename;

private static LayoutInflater inflater = null;

public GridViewAdapter(Activity a, String[] fpath, String[] fname) {
    activity = a;
    filepath = fpath;
    filename = fname;
    inflater = (LayoutInflater) activity
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

}

public int getCount() {
    return filepath.length;

}

public Object getItem(int position) {
    return position;
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
    View vi = convertView;
    if (convertView == null)
        vi = inflater.inflate(R.layout.gridview_item, null);
    // Locate the TextView in gridview_item.xml
    TextView text = (TextView) vi.findViewById(R.id.text);
    // Locate the ImageView in gridview_item.xml
     image = (ImageView) vi.findViewById(R.id.grid_image);

    // Set file name to the TextView followed by the position
    File file = new File(filepath[position]);
    Picasso.with(activity).load(file).placeholder(R.drawable.rtrt).fit().centerCrop().into(image);

    // Decode the filepath with BitmapFactory followed by the position

    // Set the decoded bitmap into ImageView
  //  image.setImageBitmap(bmp);
    return vi;
}

}


text:
Q: how can I get list of the users data in google play subscriptions Our app has already implemented in-app purchase.
But, we previously don't keep track of it, and only relies on the google's service whether a user's level is premium or regular.
Now, we want to track it in our server as well.
Is it possible to get the users data who've bought our subscriptions? (especially his/her email)

A: Based from the following documentations, there is no currently existing method to get a list of your app's subscriber's.

*

*Google Play Developer - API Reference

*In-app Subscriptions
Currently existing features with Google Play Developer API is that, it offers an HTTP-based API that lets you perform such tasks as:

*

*Remotely query the validity of a specific subscription at any time

*Cancel a subscription

*Defer a subscription's next billing date

*Refund a subscription payment without canceling the subscription

*Refund and revoke a subscription

The API is designed to be used from your backend servers as a way of securely managing subscriptions, as well as extending and integrating subscriptions with other services.
For complete information, you may go through Google Play Developer API.


text:
Q: MySQL LIKE operator with wildcard and backslash It's frustrated with MySQL's pattern escaping used in LIKE operator.
root@dev> create table foo(name varchar(255));
Query OK, 0 rows affected (0.02 sec)

root@dev> insert into foo values('with\\slash');
Query OK, 1 row affected (0.00 sec)

root@dev> insert into foo values('\\slash');
Query OK, 1 row affected (0.00 sec)

root@dev> select * from foo where name like '%\\\\%';
Empty set (0.01 sec)

root@dev> select * from foo;
+------------+
| name       |
+------------+
| with\slash |
| \slash     |
+------------+
2 rows in set (0.00 sec)

root@dev> select * from foo where name like '%\\\\%';
Empty set (0.00 sec)

root@dev> select * from foo where name like binary '%\\\\%';
+------------+
| name       |
+------------+
| with\slash |
| \slash     |
+------------+
2 rows in set (0.00 sec)

According to MySQL docs: http://dev.mysql.com/doc/refman/5.5/en/string-comparison-functions.html#operator_like
%\\\\% is the right operand, but why it yields no result?
EDIT:
The database I'm testing that in has character_set_database set to utf8. To further my investigation, I created the same setup in a database that has character_set_database set to latin1, and guess what, '%\\\\%' works!
EDIT:
The problem can be reproduced and it's the field collation problem. Details: http://bugs.mysql.com/bug.php?id=63829

A: In MySQL 5.6.10, with the text field collation utf8mb4_unicode_520_ci this can be achieved by using 5 backslash characters instead of 4, i.e:
select * from foo where name like binary '%\\\\\%';

Somehow, against all expectations, this properly finds all rows with backslashes.
At least this should work until the MySQL field collation bug above is fixed. Considering it's been more than 5 years since the bug is discovered, any app designed with this may outlive its usefulness before MySQL is even fixed - so should be a pretty reliable workaround.

A: With MySQL 5.0.12 dev on Windows 10 I got the following results when I changed the query from
SELECT * FROM `foo` WHERE `name` LIKE '%http:\/\/%'

to
SELECT * FROM `foo` WHERE `name` LIKE '%http:\\\\\\\%'

it works and yet the first string with forward slashes was the original field content. It seems to have interpreted forward slashes as backslashes.

A: It seems it has some relation to that MySQL bug: http://bugs.mysql.com/bug.php?id=46659
I think you connect to mysql not specifying correct --character-set-server option (which defaults to latin1 with collation latin1_swedish_ci), and having utf-8 as the current charset of the console. That causes incorrect char conversions and comparisons when you deal with data which supposed to be converted to the utf8 from the charset of --character-set-server.


text:
Q: Affect of db availability during backups How can we know if you database is available while the backup jobs are running ? Do backups affect the availability of the databases ?
Please let me know
Thanks

A: Database backup does not obtain any locks or block anything while running.
Things that can cause some performance issue, If your are writing backups to the same drive where you data/data files are residing, if your system has to read and write at the same time on same drives than can slow the queries that are reading from database.
But I dont think anyone does backups to the same drives where data files are , kind of pointless. Other then that it shouldn't affect the performance.


text:
Q: How do I clear all custom opts that I've set for HoloViews? How do I clear all custom opts that I've set for HoloViews, so that the default, out of the box, opts are used?
For example, if I've defined
opts.defaults(
    opts.Scatter(color='blue',
                 hooks=[mpl_style_hook]),
    opts.Histogram(color='orange',
                 hooks=[mpl_style_hook]),
    opts.Bars(color='green',
                 hooks=[mpl_style_hook]),
    backend='matplotlib'
)

How can I completely remove all of the specified opts for Scatter, Histogram and Bar?

A: Good question! I am not aware of any way to do that besides restarting Python, because I don't think we current store a copy of the original option tree. There may already be a way to save the option tree before setting those defaults and then restore it, but if so I don't know it! Feel free to file a feature request at https://github.com/holoviz/holoviews/issues .


text:
Q: Why do i have to log in twice in backend to log in? I have to put my username and password in twice for the administrator back-end.

*

*The first time I type in my user name and password, I return to the login with blank fields.

*The second time I get logged in...

Are some users experiencing the same? Weard can someone help?
There is one post with a user having the same problem, but I did not find the usefull answers:
http://forum.joomla.org/viewtopic.php?t=558305
Joomla version 2.5.9

A: The login problem was related to my domain configuration and the interaction with Joomla.
I updated the .htaccess file like:
RewriteCond %{HTTP_HOST} ^domain\.com [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,L]

In this way, my users always get redirected to: www.domain.com
Even coming to domain.com
This give them direct access, but is also beter for other plugin's and modules that use web-cloud services, depending on the www.domain.com (they will not work on domain.com)
Examples: Social Login with Google/Facebook/Twitter; Map API's and other API's
I hope this will help some users! It helped me :-)

A: I had the same problem and for me the way to fix this was as follows:
I had set the "live" domain to be www.mydomainname.com (in configuration.php in root)
When then trying to login to the backend using the domain name mydomainname.com (without the www) I had to login twice.
The answer for me was to simply ensure that I always did login using http://www.mydomainname.com/administrator.....
If you however have specified your live domain to be without the www, then you need to use the admin login url without the www accordingly.


text:
Q: Comparación input con integer Pregunta básica de newbie, será una tontería, pero estoy dándole vueltas y no veo el problema...
Tengo un input en mi HTML y quiero comparar el valor introducido con la longitud de un array.
La forma en que obtengo el valor del input es así:

Bien, este bucle FOR funciona correctamente:

Cuando llega al límite se sale con el Break y hace lo que tiene que hacer. (si pongo en el input 5 sale cuando en el array hay 5 entradas, si pongo 10 a la décima, etc... lo he probado y va bien)
Pero más abajo tengo otro IF en el que simplemente comparo si la longitud del array es menor al dato introducido en el input y en este IF no entra nunca...

En el debugger veo que están bien los dos valores como enteros, debería hacer bien la comparación:

Estoy usando el método parseInt para convertir el string introducido en un entero y comparar así con el array.lenght pero no entra nunca en este segundo IF...
He probado el parseInt con base 10 como está en la imagen y sin pasarle nada en la base, pero nada, no funciona.
¿Qué me falta?

A: Iba a dejar esto sin comentario alguno, pero el sistema de respuesta me obliga a escribir al menos 30 caracteres en la misma.


text:
Q: build and install Android source on your own Android device? It is not clear to me from looking at the page on building the android source, but is it possible to build the source yourself and install it on your own device (not an emulator), e.g. a GT-N8013?

A:
but is it possible to build the source yourself and install it on your own device (not an emulator), e.g. a GT-N8013?

All Android devices have proprietary drivers, which you would either need to get from the manufacturer (unlikely) or figure out how to copy off of your device to blend into your ROM mod. The AOSP source code is just Android.

Does source.android.com/source/building.html give the necessary information to build and install Android?

Not for an arbitrary device like a "GT-N8013".


text:
Q: bash or perl inline capture of multiple pattern matches Simple thing :
content='"id":"1234"abcdefg"id":"3456"'

need to get the id's out:
perl -le '@m = ( $content =~ /\"id\"\:\"(.*)\"/g); print for @m'

Not working but need a one liner for use on confluence json/output for processing by Ansible.

A: Use
grep -Po 'id":"\K.*?(?=")' <<< "$content"

-P enables perl regexes.
-o prints only the matching parts instead of whole lines.
\K lets grep forget that it matched id":" before.
.*? matches as few caracters as possible ...
(?=") ... until a " is the next character. The " will not be included in the match.
Output for your example:
1234
3456

A: In Perl:
perl -sE 'say for $str =~ /"id":"(.*?)"/g' -- -str="$content"


text:
Q: Why aren't tables in posts supported via markdown or as raw html? Wanting to display information in a table is not that uncommon, particularly so for SQL questions on stackoverflow (SQL deals with tables of data).
There is support for tables in various markdown libraries, and it's pretty straightforward, so:

*

*Why can't we just support it? What's the big deal?

*If there is a good reason, why can't the <table> tag (and the various row/column tags) be allowed as raw html?

Related questions, but not duplicates IMHO because there doesn't seem to be a good reason put forward for "why not":

*

*Can we add Markdown support for tables?

*Is there Markdown to create tables?


text:
Q: Locale reverts to old locale after exiting root? Heyo~
I am having an issue whenever I change locale. At present, I am getting this error whenever I run the locale command.

locale: Cannot set LC_ALL to default locale: No such file or directory
LANG=
LANGUAGE=en
  en
LC_CTYPE="POSIX"
LC_NUMERIC=en
LC_TIME=en
LC_COLLATE="POSIX"
LC_MONETARY=en
LC_MESSAGES="POSIX"
LC_PAPER=en
LC_NAME=en
LC_ADDRESS=en
LC_TELEPHONE=en
LC_MEASUREMENT=en
LC_IDENTIFICATION=en
LC_ALL=

After entering root using 'sudo -i' or 'sudo su', I use 'export LC_ALL="en_GB"'. Using locale whilst in root gives this.

LANG=
LANGUAGE=en
  en
LC_CTYPE="en_GB"
LC_NUMERIC="en_GB"
LC_TIME="en_GB"
LC_COLLATE="en_GB"
LC_MONETARY="en_GB"
LC_MESSAGES="en_GB"
LC_PAPER="en_GB"
LC_NAME="en_GB"
LC_ADDRESS="en_GB"
LC_TELEPHONE="en_GB"
LC_MEASUREMENT="en_GB"
LC_IDENTIFICATION="en_GB"
LC_ALL=en_GB

However, after leaving root, via 'exit', 'reboot' or simply closing the Terminal, the changes completely revert and the "locale: Cannot set LC_ALL to default locale: No such file or directory" error returns. The output of 'locale' is the same as before I used 'export LC_ALL="en_GB"'
I've attempted to use 'dpkg-reconfigure locales' to no effect.
Anyone know how to fix this?

A: Your locale is a complete mess.

*

*Please go to "System Settings -> Language Support".

*Drag the language of your choice to the top, and click "Apply system-wide".

*Move to the "Regional Formats" tab, select the region of your choice, and click "Apply system-wide".

*Reboot.

Hopefully that does it.


text:
Q: Processing XML in ASP pages Folks....Probably a simple question, but I have not been able to find the simple answer.  Assume the following XML structure is being analyzed in an ASP or ASPx page.
<level1>
<Block1>
 <codes>
    XS
    SM
    <c>M</c>
    <d>L</d>
    <e>XL</e>
 </codes>
</Block1>
<Block2>
 <codes>
    XP
    P
    <c>M</c>
    <d>G</d>
    <e>XG</e>
 </codes>
</Block2>
</level1>

Now, I can and I have used VBS code like
    For each L2Element in L1.Childnodes...
to iterate through the levels, blocks and the codes. However, if I really only interested in getting the text for the tag <c> in <Block2>, Is there a simple method which I can use to get it directly without iterating through all levels, blocks and codes?
Thanks....RDK

A: You can use XPath to query the node you want.
Dim xmlDoc : Set xmlDoc = [your xml document here]
xmlDoc.setProperty "SelectionLanguage", "XPath"

Then, you can select the node you want as follows:
Dim oNode
Set oNode = xmlDoc.selectSingleNode("//Block2/codes/c")

You can then retrieve the value from oNode. Don't forget to check if it is Nothing first, though. oNode will be equal to Nothing if the XPath query didn't find it's target.
In the event that you want to select multiple nodes, there is also a selectNodes() method with which you can also use XPath. It will return a collection of nodes, that has a length property that you can use for iterating through them. Access each node of the collection with item(index).


text:
Q: How to divide a n dimensional simplex in n+1 equal parts I want to divide a n dimensional simplex (convex hull of n+1 points) in n+1 parts. E.g. consider the simplex in 2-D which is the convex hull of points (0,0,1), (0,1,0) amd (1,0,0). It can be divided in three parts as
$P_1 = \{(0,1,0),(1/2,1/2,0),(0,1/2,1/2),(1/3,1/3,1/3)\}$
$P_2 = \{(1,0,0),(1/2,1/2,,0),(1/2,0,1/2),(1/3,1/3,1/3)\}$
$P_3 = \{(0,0,1),(1/2,0,1/2),(0,1/2,1/2),(1/3,1/3,1/3)\}$
I can somehow arrive at these partitions by considering intersection of some halfspaces (line joining the vertex to the midpoint of the other side). However, I am unable to extend this to higher dimensions.
Is  there an algorithm in literature which does the same partitions. Can someone point me to some reference.
Thanks

A: The magic word is "barycenter". The convex hull of the barycenter and any one face of the simplex has the right volume.

A: In fact, there are much more such divisions. The group of simplex is $S_{n+1}$, so it contains a subgroup $H=\langle (123\dots n+1)\rangle$ of order $n+1$ acting transitively on the hyperfaces. Now take a ray $r$ from the center $O$ of the simplex, and let $\{r_1,\dots,r_{n+1}\}$ be its orbit under the action of $H$. Every $n$ of these rays generate a polyhedral cone, the union of these cones is the whole space (unless something degenerates), and $H$ permutes these cones transitively. Hence $H$ also permutes the intersections of these cones with the simplex, and they are congruent. So, we obtain a desired division.
The pictures below show two types of such divsion of a regular tetrahedron.


text:
Q: how to catch firestore permission denied exception when the user doesn't have enough permissions to write to the database? When I try to write to database with a user account that doesn't have write permission I get this exception as expected

Exception has occurred.
PlatformException (PlatformException(firebase_firestore, com.google.firebase.firestore.FirebaseFirestoreException: PERMISSION_DENIED: Missing or insufficient permissions., {code: permission-denied, message: The caller does not have permission to execute the specified operation.}))

But I am unable to catch it.
Calling this Method causes the exception
Future<void> addRecord(Product product) async {
    try {
      await FirebaseFirestore.instance
          .collection("products")
          .doc()
          .set(product.toMap())
          .catchError((err) {
        print("error is" + err.toString());
      });
    } on PlatformException catch (e) {
      print("eee" + e.toString());
    }
  }

This exception is I believe caught as in the console I am getting this message:

eee[cloud_firestore/permission-denied] The caller does not have permission to execute the specified operation.

But there is one more message in the console

W/Firestore(12930): (21.4.3) [Firestore]: Write failed at products/SPeUO9260uCoIfpDsSag: Status{code=PERMISSION_DENIED, description=Missing or insufficient permissions., cause=null}


text:
Q: Save positions of vector in another vector I have a vector of points and generate some geometrics with those points. To save memory, I use the index of the vector as reference and not the point itself.
Example:
Triangle(index[0], index[4], index[6]);

instead of
Triangle(Point(x0, y0), Point(x4, y4), Point(x6, y6));

However, I need to store some positions for later reference.
Is it preferable to save it as int or as iterator? How much space does that iterator take compared to the int?
Specific:
Do I do
std::vector<int> laterUse;
or
std::vector< std::vector<Point>::const_iterator > ?
What are the advantages or disadvantages? I'm more interested in saving memory than in speed.


text:
Q: Save button click function not working in mvc3? Hi guys i have a table where i have a edit the project link ...when i click on that it takes me to a Edit page where i have textboxes for editing  record and a button to Save..but i click on Save button its not working can any one help me where am i doing wrong here is my code
This is my Edit.aspx page:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<Gridview_BugTracker.Models.BugTracker_DataHelper>" %>
<!DOCTYPE html>

 <title></title>
        <%: ViewBag.Title="Edit" %>

             <% using (Html.BeginForm())
                 { %>
        <form action="Edit.aspx" method="post"></form>

        <%:Html.ValidationSummary(true)%>
        <fieldset>
                <legend>Projects</legend>

             <%:Html.HiddenFor(model => model.ProjectId)%>

                     <%:Html.LabelFor(model => model.projectName)%>

                        <%:Html.EditorFor(model => model.projectName)%>
                        <%:Html.ValidationMessageFor(model => model.projectName)%>

                        <%:Html.LabelFor(model => model.Description)%>

                        <%:Html.EditorFor(model => model.Description)%>
                        <%:Html.ValidationMessageFor(model => model.Description)%>

                        <%:Html.LabelFor(model => model.status)%>

                        <%:Html.EditorFor(model => model.status)%>
                        <%:Html.ValidationMessageFor(model => model.status)%>

                        <input type="submit" value="Save" />

        </fieldset>
<%} %>
                <%: Html.ActionLink("Back to List", "Index")%>

And this is my controller function:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Edit(int id, BugTracker_DataHelper updatemodel)
{
    SqlConnection editconn = new SqlConnection(@"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=BugTracker;Data Source=SSDEV6\SQLEXPRESS");
    {
            editconn.Open();
            SqlCommand ecmd = new SqlCommand("Select ProjectId,projectName,Description,status From Projects Where ProjectId=" + id, editconn);
            SqlDataReader dr = ecmd.ExecuteReader();
            if (dr.Read())
            {
                    updatemodel.ProjectId = Convert.ToInt16(dr["ProjectId"]);
                    updatemodel.projectName = dr["projectName"].ToString();
                    updatemodel.Description = dr["Description"].ToString();
                    updatemodel.status = dr["status"].ToString();
            }
            else
            {
                    dr.Close();
            }
            dr.Close();
            editconn.Close();
            return View(updatemodel);
    }
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(BugTracker_DataHelper updatemodel, FormCollection collection, int id)
{
    SqlConnection editconn = new SqlConnection(@"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=BugTracker;Data Source=SSDEV6\SQLEXPRESS");
    {

            SqlCommand ecmd = new SqlCommand("EditGetList", editconn);
            ecmd.CommandType = CommandType.StoredProcedure;
            editconn.Open();
            ecmd.Parameters.Add("projectID", SqlDbType.Int).Value = updatemodel.ProjectId;
            ecmd.Parameters.Add("projectName", SqlDbType.VarChar).Value = updatemodel.projectName;
            ecmd.Parameters.Add("Description", SqlDbType.VarChar).Value = updatemodel.Description;
            ecmd.Parameters.Add("Status", SqlDbType.VarChar).Value = updatemodel.status;
            editconn.Close();

            return View(updatemodel);
    }
}

when i click on SAVE button in aspx page it should go to Edit method in my controller .....what am i doing wrong here.........

A: Are you suppsed to have two forms?
<% using (Html.BeginForm())
{ %>
     <form action="Edit.aspx" method="post"></form>

Or were you trying to set the action of your BeginForm?
The button that you are pressing is actually a part of the first form and not the second.
So this
 <form action="Edit.aspx" method="post"></form>

is currently not doing very much.
If you want the save button to be doing something in the second form then you will need to put the button inside the form tags like so:
 <form action="Edit.aspx" method="post">
    <input type="submit" value="Save" />
 </form>


text:
Q: Would there be anything stopping me from removing both wp_head and wp_footer? Some plugins rely on either wp_head or wp_footer or both to introduce their own stylesheets and JavaScript. Those scripts take time to load and slow down my website. Therefore, I would like manually control all the scripts on my site.
I'm thinking of removing wp_head() and wp_footer() entirely.
Would the sky falls down if I do so?
I've read this.

A: Don't remove wp_head() or wp_footer() as they are required for triggering other hooks. Instead, conditionally remove scripts / stylesheets based on page type, page ID, page template, post category, etc.
I reckon you mostly need to worry about this on the site's front page, since all your site CSS and main JavaScript will be loaded on that page and cached for the rest of the website (yes?) and once people have downloaded everything on the front page and cached various assets, any gzipped scripts and stylesheets should be pretty quick to load on whatever page follows.
Here's a rip from a site I did last year, where I knocked out a bunch of scripts and CSS just from the front page.
// actions to remove unnecessary scripts and styles
add_action('wp_print_scripts', 'wpse_84052_removeScripts', 100);
add_action('wp_print_styles', 'wpse_84052_removeStyles');

/**
* performance: remove some scripts we don't need on splash page
*/
function wpse_84052_removeScripts() {
    if (is_front_page()) {
        // events manager
        wp_dequeue_script('events-manager');
        wp_dequeue_script('events-manager-pro');

        wpse_84052_removeObjectFilters('wp_head', 'EM_Pro');
        wpse_84052_removeObjectFilters('wp_head', 'EM_Coupons');

        // NextGEN Gallery
        wp_dequeue_script('ngg-slideshow');
        wp_dequeue_script('shutter');
    }
}

/**
* performance: remove some stylesheets we don't need on splash page
*/
function wpse_84052_removeStyles() {
    if (is_front_page()) {
        // WP Flexible Map plugin styles
        wp_dequeue_style('flxmap');

        // NextGEN Gallery plugin styles
        wp_dequeue_style('NextGEN');
        wp_dequeue_style('shutter');

        // Events Manager plugin styles
        wp_dequeue_style('events-manager');

        // wp-category-posts-list plugin styles
        wp_dequeue_style('wp_cpl_css_3');
        wp_dequeue_style('wp_cpl_css_2');
        wp_dequeue_style('wp_cpl_css_1');
        wp_dequeue_style('wp_cpl_css_0');
        wp_dequeue_style('wp-cpl-base-css');
    }
}

/**
* remove filters that are methods of an object of some class
* @param string $filterName name of action or filter hook
* @param string $className name of class for object method
*/
function wpse_84052_removeObjectFilters($filterName, $className) {
    global $wp_filter;

    // must take a variable to iterate over array of filters,
    // else a subtle reference bug messes up the original array!
    $filters = $wp_filter[$filterName];

    foreach ($filters as $priority => $hooks) {
        foreach ($hooks as $idx => $filter) {
            // check for function being a method on a $className object
            if (is_array($filter['function']) && (is_a($filter['function'][0], $className) || $filter['function'][0] === $className)) {
                remove_filter($filterName, $idx, $priority);
                break;
            }
        }
    }
}


text:
Q: Program Safety Planes for Universal Robotics (UR-10) in UR script language My university just purchased a UR-10 for our mechanical engineering department and I'm currently working on it as a summer project.
I was learning how to use the scripting language, reading through the documentation, but I could not find anywhere the ability to programmatically define safety planes.
As of right now, we want to setup safety planes using a depth camera we have, but I can't find any documentation on the subject.
I'm just curious to know if there is a command that takes a positional argument that would let me set up a safety plane in a room a distance away from the robot arm.

A: There isn't a way to programmatically create safety planes for the UR-10. You have to just create joint limits for certain motions you don't want the arm to move in.


text:
Q: how to display 7 days of week weather forecast in c# I have tried this code many times. below code but getting Error.
this is the API used to get the 7 days week forecast. in below I entered the city "London".so I can get the 7 days forecast report of London.
http://api.apixu.com/v1/forecast.xml?key=5742bec32f4141e08db171907171010&q=london&days=7

when I write the code in c#. instead of London, I passed the one textbox control.because
the country which I entered in the textbox.the particular country is 7-day forecast will be displayed at grid view.
 this is the code I tried
string city = txtcity.Text;
                string uri = string.Format("http://api.apixu.com/v1/forecast.xml?key=02d3de968c424e20b5a74149172409 &q=" + city + " &days=7");

I strucked at this point. I don't know how to pass the textbox name within URL.
the final result has to be displayed on the grid view control. I tried the code below. 7 days forecast will have to display on the grid view.
            XmlReader xmlFile;
            xmlFile = XmlReader.Create(uri);
            DataSet ds = new DataSet();
            ds.ReadXml(xmlFile);
            dataGridView1.DataSource = ds.Tables[1];

please, anyone, help me to solve this problem

A: I have came accross with something like that:
string city = txtcity.Text;
// string.Format("foo{0}{1}", "bar", "foobar"); the bracket {0} will be replaced with bar and {1} with foobar
// General better instead of using string concatenation "foor" + "bar" + "foobar"
string uri = string.Format("http://api.apixu.com/v1/forecast.xml?key=02d3de968c424e20b5a74149172409&q={0}&days=7", city);

DataSet ds = new DataSet();

// XmlReader is an IDisposable besure to dispose it
//using (IDisposable) makes sure, that the object gets disposed, when not needed anymore
using (XmlReader xmlFile = XmlReader.Create(uri))
{
    ds.ReadXml(xmlFile);
}

dataGridView1.DataSource = ds.Tables[1];

which results into:
Grid containing the data


text:
Q: HA configuration on Compute Engine Is it possible to have something like this using compute engine? In my case I would like to have an external IP address as a service IP so this IP can be configured in any compute engine VM.
Is it possible? Thanks

A: I searched my notes, and all I found is: http://googlegenomics.readthedocs.io/en/latest/use_cases/setup_gridengine_cluster_on_compute_engine/ This is might be not what are you looking but I hope this can help.


text:
Q: How to Integrate babun shell in VS code I have tried changing the settings for "terminal.integrated.shell.windows" to babun mintty location. But the babun shell window opens separately and doesn't integrate with the VS code. Anyone knows how to achieve this?

A: I was searching for any solution for this issue before and I could not find any. But I was curious how Babun itself run the command "Open Babun here" from right-click menu and noticed it runs this command:
C:\Users\YOURUSER\.babun\cygwin\bin\mintty.exe /bin/env CHERE_INVOKING=1 /bin/zsh.exe

I've tried setting mintty.exe as shell and using leading commands as shell arguments, but this method opens an external terminal. I've noticed this behavior is because using mintty.exe, so I replaced mintty.exe with env.exe itself. At last, these are the settings:
"terminal.integrated.shell.windows": "C:\\Users\\YOURUSER\\.babun\\cygwin\\bin\\env.exe",
"terminal.integrated.shellArgs.windows": [
  "CHERE_INVOKING=1",
  "/bin/zsh.exe"
]

Edit: This might not completely relate to this question, but because of having the similarity, I think it might worth mentioning.
During my search for a solution, I've seen many other questions about the same issue for integrating Atom's PlatformIO IDE Terminal package or JetBrain's IDEs with Babun's zsh.
In the case of Atom, setting the Shell Override to C:\Users\YOURUSER\.babun\cygwin\bin\env.exe and Shell Arguments to CHERE_INVOKING=1 /bin/zsh.exe opens zsh.exe as an integrated terminal in the project directory.
In the case of JetBrain, I've used WebStrom and this works:
cmd.exe "/k C:\Users\ehsan\.babun\cygwin\bin\env.exe CHERE_INVOKING=1 /bin/zsh.exe"

A: After trying for 2 hours finally made it work.
Before reading my way of doing this, you might want to got through this issue first.
By default babun is installed in C:\Users\13000\.babun\. So we can configure it by overriding user setting in VS Code as:
"terminal.integrated.shell.windows": "C:\\Users\\YOURUSERNAME\\.babun\\cygwin\\bin\\zsh.exe",

After saving , reload the window and you are done.
You will get something like :
Hope this helps!

A: Just complementing the correct answer that Pramesh Bajracharya gave above, you can override user settings in VS Code opening the VS Code and going in:
File->Preferences->Settings

And then paste in the field shown in your right side (WORKSPACE SETTINGS):
{
    "terminal.integrated.shell.windows": "C:\\Users\\YOURUSER\\.babun\\cygwin\\bin\\zsh.exe"
}

More information can be found in https://code.visualstudio.com/docs/editor/integrated-terminal
Thanks Pramesh Bajracharya!


text:
Q: Error for create data frame ts with zoo package I try to create a data frame for temporal series analysis with zoo package with my especific case, but doen't work, my artificial script is:
require(zoo)

TSdata<-NULL

TSdata$id<-seq(1:30) ##ID

TSdata$Date<-seq(as.Date("2015/1/15"), by = 15, length.out = 30) ## Vector of date

TSdata$rain<-rnorm(30,mean=125)#Covariate 1

TSdata$temp<-rnorm(30,mean=32.6) #Covariate 2

TSdata$y<-rpois(30,lambda=15) # Response variable

TSdata<-as.data.frame(TSdata) ## Convert to data frame

## Create temporal series object

ts.data <- read.zoo(text="TSdata", format="%Y/%m/%d", index.column = 2) ## Here the problem

A: There are two errors in your code: (1) If you want create a zoo object with read.zoo() from a data.frame, then you simply need to supply the object TSdata and not a character string with its name "TSdata". (2) The format is not "%Y/%m/%d". But as the index is already a Date column, no format needs to be supplied anyways.
Simply do:
read.zoo(TSdata, index.column = 2)
##            id     rain     temp  y
## 2015-01-15  1 125.3376 32.91936 13
## 2015-01-30  2 125.2048 32.71199 17
## 2015-02-14  3 125.7443 32.74698 17
## ...

A: The right solution is to given by the other answer. As another option you can use the constructor zoo:
zoo(x=TSdata[,!grepl("Date",colnames(TSdata))],
    order.by = TSdata$Date)

#            id     rain     temp  y
# 2015-01-15  1 122.6501 32.46969 18
# 2015-01-30  2 124.4833 31.46569 13
# 2015-02-14  3 125.2021 33.05852 13


text:
Q: I don't fully understand this implementation despite seeing documentation (subtle crypto) What do each individual letters(e and n respectively) represent and what is the code afterward (RSAPSS forward)? I have a general idea - but I would appreciate a more thorough break down of the problem. Thank you for your time.
window.crypto.subtle.importKey("jwk", {
      kty: "RSA",
      e: "AQAB",
      n: "vGO3eU16ag9zRkJ4AK8ZUZrjbtp5xWK0LyFMNT8933evJoHeczexMUzSiXaLrEFSyQZortk81zJH3y41MBO_UFDO_X0crAquNrkjZDrf9Scc5-MdxlWU2Jl7Gc4Z18AC9aNibWVmXhgvHYkEoFdLCFG-2Sq-qIyW4KFkjan05IE",
      alg: "PS256",
      ext: true,
                  },
      RSAPSS, false, ["verify"])
      .then(ok("rsa-pss", "importKey", "jwk-pub"))
      .catch(err("rsa-pss", "importKey", "jwk-pub"));


text:
Q: Data added using matInput Textbox is not visible in the developer tools I am using matInput Texbox of Material in angular12. While trying to inspect the element to get the values entered in the textbox in developer tools I see that the entered text is not visible.
This is required as we are performing selenium testing on the application. Its required to navigate and read through the data entered from the DOM.


text:
Q: PySpark: convert RDD[DenseVector] to dataframe I have the following RDD:
rdd.take(5) gives me:
[DenseVector([9.2463, 1.0, 0.392, 0.3381, 162.6437, 7.9432, 8.3397, 11.7699]),
 DenseVector([9.2463, 1.0, 0.392, 0.3381, 162.6437, 7.9432, 8.3397, 11.7699]),
 DenseVector([5.0, 20.0, 0.3444, 0.3295, 54.3122, 4.0, 4.0, 9.0]),
 DenseVector([9.2463, 1.0, 0.392, 0.3381, 162.6437, 7.9432, 8.3397, 11.7699]),
 DenseVector([9.2463, 2.0, 0.392, 0.3381, 162.6437, 7.9432, 8.3397, 11.7699])]

I would like to make it a data frame which should look like:
-------------------------------------------------------------------
| features                                                        |
-------------------------------------------------------------------
| [9.2463, 1.0, 0.392, 0.3381, 162.6437, 7.9432, 8.3397, 11.7699] |
|-----------------------------------------------------------------|
| [9.2463, 1.0, 0.392, 0.3381, 162.6437, 7.9432, 8.3397, 11.7699] |
|-----------------------------------------------------------------|
| [5.0, 20.0, 0.3444, 0.3295, 54.3122, 4.0, 4.0, 9.0]             |
|-----------------------------------------------------------------|
| [9.2463, 1.0, 0.392, 0.3381, 162.6437, 7.9432, 8.3397, 11.7699] |
|-----------------------------------------------------------------|
| [9.2463, 2.0, 0.392, 0.3381, 162.6437, 7.9432, 8.3397, 11.7699] |
|-----------------------------------------------------------------|

Is this possible? I tried to use df_new = sqlContext.createDataFrame(rdd,['features']) , but it didn't work. Does anyone have any suggestion? Thanks!

A: Map to tuples first:
rdd.map(lambda x: (x, )).toDF(["features"])

Just keep in mind that as of Spark 2.0 there are two different Vector implementation an ml algorithms require pyspark.ml.Vector.


text:
Q: Remove text from textarea after form submission React I have a form that is sending an email once user has clicked submit but the text is still staying in the text area. What can I do to clear the textarea once form has been submitted?
import "./contact.css";
import phone from "../../img/phone.png";
import email from "../../img/email.png";
import github from "../../img/github.png";
import link from "../../img/link.png";
import resume from "../../img/resume.png";
import { useRef, useState } from "react";
import emailjs from "@emailjs/browser";

const Contact = () => {
  const formRef = useRef();
  const [done, setDone] = useState(false);

  const handleSubmit = (event) => {
    event.preventDefault();
    emailjs
      .sendForm(
        "service_fh7vxks",
        "template_z5wczcw",
        formRef.current,
        "mhYkqvVVsQZ1u1ogA"
      )
      .then(
        (result) => {
          console.log(result.text);
          setDone(true);
        },
        (error) => {
          console.log(error.text);
        }
      );
  };

  return (

Let's talk

              +61 490 522 328

              CV

                linkedin.com/in/tobias-bedford

            Who are you? Lorem ipsum dolor sit amet consectetur
            adipisicing elit. Vel provident ex quis adipisci quidem magni hic
            eos quae deleniti dignissimos sequi rerum nam atque reprehenderit
            et, odio ad? Aliquam, repellat.

          <form ref={formRef} onSubmit={handleSubmit}>
            <input type="text" placeholder="name" name="user_name" />
            <input type="text" placeholder="subject" name="user_subject" />
            <input type="text" placeholder="email" name="user_email" />
            <textarea rows="5" placeholder="message" name="message"></textarea>
            <button>Submit</button>
            {done && "Thank you..."}
          </form>

  );
};

export default Contact;

I believe it could be possible through using setstate(), but though there is maybe an easier way built into React. Any help would be greatly appreciated.

A: Indeed, I would use useState for this. You can save a declare the value with a default message, use an onChange handler to update the value, then clear it after you submit the form.
  const [done, setDone] = useState(false);
  const [textMessage, setTextMessage] = useState('');

  const handleSubmit = (event) => {
    event.preventDefault();
    emailjs
      .sendForm(
        "service_fh7vxks",
        "template_z5wczcw",
        formRef.current,
        "mhYkqvVVsQZ1u1ogA"
      )
      .then(
        (result) => {
          console.log(result.text);
          setDone(true);
          setTextMessage('');
        },
        (error) => {
          console.log(error.text);
        }
      );
  };

const handleChange = (e) => {
     setTextMessage(e.target.value);
}

//...then in your form, use defaultValue and onChange:
<textarea rows="5" defaultValue={textMessage} //OR
 value={textMessage} onChange={handleChange} placeholder="message" name="message"></textarea>

A: You may set a id for your form and reset it while submit success
//function
const handleSubmit = (event) => {
  document.getElementById('my_form').reset();
}

//form
<form id='my_form'>
   {--code here --}
</form>

if only clear for textarea and other remain you may try to set id for text area and do below in your submit function
//function
const handleSubmit = (event) => {
  document.getElementById('textarea_id').value = '';
}


text:
Q: Using Spring expression language to assert if a property (with comma separated values) loaded from a properties file, contains "value" I have the following problem, I have a certain configuration class in spring boot which contains beans, which I would like to be created only if a certain property which has a list of values, contains a certain value.
now the configuration class looks something like this:
@ConditionalOnExpression("#{'${conditions.values.options}'.contains('ScenarioOne')}")
ConfigurationForScenarioOne{

  @Bean
  public StudentBean getStudentBean(){
  ...
  }
}

In the properties file I would have something like so:
conditions.values.options=${CONDITIONS_VALUES_OPTIONS}

Then provide the value of CONDITIONS_VALUES_OPTIONS at runtime like so:
-DCONDITIONS_VALUES_OPTIONS=ScenarioOne,ScenarioTwo,ScenarioFive

The reason why I want to do this is to be able to deploy the app and have different beans be in use depending on the value given at runtime.
I will have several of these Configuration classes that will be created based on which ones of these properties are passed.
TO achieve this I was trying to rely on Spring Expression language to do the following:
1-Read the property conditions.values.options, then convert it to a list, then verify if the list contained the desired configuration string.
So far I have tried several expressions including:
@ConditionalOnExpression("#{'${conditions.values.options}'.contains('ScenarioOne')}")

and other similar expressions, with no luck. Can someone help me see what I am missing here?

A: I was able to get the desired behavior using this:
@ConditionalOnExpression("#{T(java.util.Arrays).asList('${conditions.values.options}').contains('ScenarioOne')}")

So dissecting this a little bit in the hopes to help others who may come across similar problems:
It seems that spring reads comma separated properties as an Array, this is bogus because the following can be done using spring boot:
The following two statements are valid:
@Value("${property.with.comma.separated.values}")
private List<String> prop;

OR
@Value("${property.with.comma.separated.values}")
private String [] prop;

now the expression:
"#{'${conditions.values.options}'.contains('ScenarioOne')}"

will throw an error saying that the Array class does not contain a method called '.contains()'
hence this is why I had to resort to use some method execution:
T(java.util.Arrays).asList('${conditions.values.options}')

to read the comma separated values, convert the String array into a List and then perform the '.contains(..)' method invocation.
I wish there was a simpler way to do it, to have to do a method invocation in there seems like overkill.
I am open to sugestions

A: Can you try writing your annotation values like this and check :
@ConditionalOnExpression("#{${conditions.values.options}}.contains('ScenarioOne')")

Write the contains method after the curly brackets.


text:
Q: Error while connecting .net 5 app with sql server using docker I've been trying to connect .net 5 app with mssql server using docker. I've been always getting this error: Microsoft.Data.SqlClient.SqlException (0x80131904): Login failed for user 'sa'.
This is appsetting.json file:
  "ConnectionStrings": {
  "OrderingConnectionString": "Server=localhost;Database=OrderDb;User
  Id=sa;Password=SwN@12345678;"
  },

This is docker-compose.yml file:
  orderdb:
    image: mcr.microsoft.com/mssql/server:2017-latest

This is docker-compose.override.yml file
  orderdb:
    container_name: orderdb
    environment:
        SA_PASSWORD: "SwN@12345678"
        ACCEPT_EULA: "Y"
    restart: always
    ports:
     - "1433:1433"

Can anyone help me to solve that?


text:
Q: MySQL returns only first line when querying for MAX() and all names I have the following table:
students:
name:     semester:
AAAA      1
BBBB      2
CCCC      3
DDDD      4

Where students is the name of the table and name & semester are the colums.
I want to select all the names and the max number of semesters.
Therefore I use the following SQL-Statement:
SELECT MAX(semester), name FROM students;

As result I get the correct maximum number of semesters, but only the first name.
Why does it only return one name and why the first of the table (and not the one with max semesters)?
I'm not interested in how to fix this but in why it behaves like this.
I'm using MariaDB 10.4.11.

A: You must use GROUP BY to group each name.  Otherwise it will aggregate the whole table, which of course only return one row.
SELECT MAX(semester), name
FROM students
GROUP BY name;

A: It behaves like this because you are using an older version of MySQL that allows malformed queries.
Why is the query malformed?  You have an aggregation query with no GROUP BY, so it returns one row.  But, name is not aggregated -- and presumably you have multiple names in the database.
MySQL used to support this syntax wholeheartedly but returns an arbitrary value of name.  Now it requires that you set a configuration parameter in order to use it.


text:
Q: Which design pattern to use for usage of 2 generated versions of same class We have web application which have also soap API (lets call it apiVersion1). Now we need to add some new functionality and due to that, we need to implement apiVersion2, but for some consumers we still need to keep alive apiVersion1.
Let say we have following 2 classes generated from WSDL:
pkg.apiVersion1.SomeGeneratedClass
pkg.apiVersion2.SomeGeneratedClass

In apiVersion1 we have used something like this:
pkg.apiVersion1.SomeGeneratedClass someClass = converter.getSomeGeneratedClass(someClassVO);
someClass.setProperty(xyz);
...

Now I need to change our code as follows:
if(isapi2v0Supported){
    pkg.apiVersion2.SomeGeneratedClass someClass = converter.getSomeGeneratedClass(someClassVO);
    someClass.setProperty(xyz);
    ...
}
else{
    pkg.apiVersion1.SomeGeneratedClass someClass = converter.getSomeGeneratedClass(someClassVO);
    someClass.setProperty(xyz);
    ...
}

But I don't like that solution and I would like to use it somehow like this, so I will do not need to change usage of SomeGeneratedClass, because it is exactly same for pkg.apiVersion1.SomeGeneratedClass and pkg.apiVersion2.SomeGeneratedClass:
SomeGeneratedClassWrapper someClass = converter.getSomeGeneratedClass(someClassVO);
someClass.setProperty(xyz);
...

Is there any design pattern which I can use for this purpose? If not, do you have some advice how to deal with this specific problem?
Please notice that mentioned 2 classes are generated from WSDL, so we can not (or don't want) to modify them.


text:
Q: ContactsContract.Directory - How do I return a Photo? I am trying to figure out why I can't seem to pass a photo Uri (Uri.parse(http://url/image.png)) to the contacts app via ContactsContract.Directory
I have a web service which allows searching of an address book. One of the returned fields is a url of the contact which resides on a webserver which I have verified is accessible from my Honeycomb Tablet.
My ContactsContract.Directory seems to be working flawlessly returning results, but when I pass back as part of the FILTER query Contacts.PHOTO_THUMBNAIL_URI w/ the Uri.parse(http://url/image.png) the search results still return as expected, but I still only see the temporary template.
The uri for the directory query has an option for photo supported.
if (column.equals(Directory.PHOTO_SUPPORT)) {
                    row[i] = Directory.PHOTO_SUPPORT_FULL;
                }

I have tried all combinations of Directory.PHOTO_SUPPORT* and none seem to make a difference.
My only thought is that the contacts app does not support downloading photos from a URL. So I also tried
    File myFile  = new File("/sdcard/testuser.jpg");
row[photoUri] = Uri.fromFile(myFile);

And I verified that testuser.jpg was on the sdcard. This worked fine. However due to the way the directory search is done I would like  to load it on the fly, and not cache (for the time being) to the sdcard.
Any help would be appreciated.

A: I think I have found the answer.. Looks like the exception was being logged in Verbose (had my logcat set at Debug). Anyway, was pretty sure about this, but looks like there is no Provider for http uri. Off to create a content provider, just not sure how I will return an image from a content provider, but will figure it out. Any hints/tips would be appreciated and given answer credit.
09-16 10:20:25.550: VERBOSE/ContactPhotoManager(11691): java.io.FileNotFoundException: No content provider: http://domain/testimage.jpg
09-16 10:20:25.550: VERBOSE/ContactPhotoManager(11691):     at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:595)
09-16 10:20:25.550: VERBOSE/ContactPhotoManager(11691):     at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:527)
09-16 10:20:25.550: VERBOSE/ContactPhotoManager(11691):     at android.content.ContentResolver.openInputStream(ContentResolver.java:362)
09-16 10:20:25.550: VERBOSE/ContactPhotoManager(11691):     at com.android.contacts.ContactPhotoManagerImpl$LoaderThread.loadRemotePhotos(ContactPhotoManager.java:722)
09-16 10:20:25.550: VERBOSE/ContactPhotoManager(11691):     at com.android.contacts.ContactPhotoManagerImpl$LoaderThread.loadPhotosInBackground(ContactPhotoManager.java:652)
09-16 10:20:25.550: VERBOSE/ContactPhotoManager(11691):     at com.android.contacts.ContactPhotoManagerImpl$LoaderThread.handleMessage(ContactPhotoManager.java:563)
09-16 10:20:25.550: VERBOSE/ContactPhotoManager(11691):     at android.os.Handler.dispatchMessage(Handler.java:95)
09-16 10:20:25.550: VERBOSE/ContactPhotoManager(11691):     at android.os.Looper.loop(Looper.java:132)
09-16 10:20:25.550: VERBOSE/ContactPhotoManager(11691):     at android.os.HandlerThread.run(HandlerThread.java:60)


text:
Q: Sharepoint Online search result is different on filename search with and without asterisk wild character I have two files, BTWaste.RN_SpecSheet.pdf and BTWasteCI.RN_SpecSheet.pdf, which are on same library, same folder and upload at the same time.  I use "filename: btwaste" and "filename: btwaste*" to search.  I expect result are the same for both search. Why only one file on search result for "filename: btwaste" searching?
I remove dot on file name, BTWasteRN_SpecSheet.pdf and BTWasteCIRN_SpecSheet.pdf, result is still the same.

A: It's how KQL query works in SharePoint:https://learn.microsoft.com/en-us/sharepoint/dev/general-development/keyword-query-language-kql-syntax-reference

When you use words in a free-text KQL query, Search in SharePoint
returns results based on exact matches of your words with the terms
stored in the full-text index. You can use just a part of a word, from
the beginning of the word, by using the wildcard operator (*) to
enable prefix matching. In prefix matching, Search in SharePoint
matches results with terms that contain the word followed by zero or
more characters.


text:
Q: Does Python have static variable like Java when using cloudpickle? I am new to Python.
There is another question, Are static class variables possible?, that has answered how to use static variables in Python. But it will be different when serializing a class using cloudpickle.
Because cloudpickle will serialize the whole class, including static variables, and restore when loaded. That makes two classes with the same name exist.
Does Python have things like classloader in Java, that can make sure only one class instance exists in the whole context?


text:
Q: What can be my problem with my client api? I'm trying to make a simple full stack application with a self made API that has to store transactions, it receives a description of the transaction, the amount (negative or positive), the date the transaction was made and a transaction type (income, expense). The API works just fine, I can make GET, POST and DELETE requests to it with Postman, my problem seems to be at the front end and I can't find a way to solve it, the GET request works but when I want to make a POST request the data I send from my form gets to the API with null values. I tried making the request with Axios and using fetch, but none of them solved the issue. I hope somebody can give me a hand with it
This is my code on my server.js
const express = require("express");
const bodyParser = require("body-parser");

const apiRouter = require("./routes/api");

const app = express();

app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});

require("./db");

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.post("/", function (req, res, next) {
  console.log(req.body);
  res.send("response");
});

app.use("/api", apiRouter);

app.listen(3001, () => {
  console.log("Está vivo!");
});

This is from my api.js
const router = require("express").Router();

const middleWares = require("./middlewares");
const apiTransactionsRouter = require("./api/transactions");
const apiUsersRouter = require("./api/users");

router.use("/transactions", /*middleWares.checkToken,*/ apiTransactionsRouter);
router.use("/users", apiUsersRouter);

module.exports = router;

And this is from the app.js (there might be some useless lines, I'm aware of it, but I'm trying to finish the app to clear the file a bit, so forgive me for that)
import React, { Component } from "react";
import "./App.css";
import "bootstrap/dist/css/bootstrap.min.css";
import axios from "axios";
import { Modal, ModalBody, ModalFooter, ModalHeader } from "reactstrap";

class App extends Component {
  //state
  constructor(props) {
    super(props);
    this.state = {
      transactions: [],
      isLoading: false,
      isError: false,
      createModal: false,
      form: {
        id: "",
        concepto: "",
        monto: "",
        fecha: "",
        tipo: "",
      },
    };
  }

  //get petition
  async componentDidMount() {
    this.setState({ isLoading: true });

    const resp = await fetch("http://localhost:3001/api/transactions/");

    //check the answer
    if (resp.ok) {
      const transactions = await resp.json();
      /*console.log(transactions);*/
      this.setState({ transactions, isLoading: false });
    } else {
      this.setState({ isError: true, isLoading: false });
    }
  }

  //post petition with fetch
  async postPetition() {
    try {
      let result = fetch("http://localhost:3001/api/transactions/", {
        method: "post",
        headers: {
          //Accept: "application/json",
          "Content-Type": "application/x-www-form-urlencoded",
        },
        body: JSON.stringify({
          form: {
            concepto: this.state.form.concepto,
            monto: this.state.form.monto,
            fecha: this.state.form.fecha,
            tipo: this.state.form.tipo,
          },
        }),
      });
      this.componentDidMount();
      this.createModal();
      console.log(result);
    } catch (e) {
      console.log(e);
    }
  }

  //post petition with axios
  /*postPetition = async () => {
    delete this.state.form.id;
    await axios
      .post(url, this.state.form)
      .then((response) => {
        console.log(response);
        console.log(response.data);
        this.createModal();
        this.componentDidMount();
      })
      .catch((error) => {
        console.log(error.message);
      });
  };*/

  //render table functions
  renderTableHeader = () => {
    return Object.keys(this.state.transactions[0]).map((attribute) => (
      {attribute.toUpperCase()}
    ));
  };

  renderTableRows = () => {
    return this.state.transactions.map((transaction) => {
      return (

          {transaction.id}
          {transaction.description}
          {transaction.amount}
          {transaction.date}
          {transaction.transactionType}

            <button
              className="btn btn-primary"
              onClick={() => this.selectTransaction(transaction)}
            >
              Editar
            </button>
            {"  "}
            <button className="btn btn-primary">Eliminar</button>

      );
    });
  };

  //create transaction
  createModal = () => {
    this.setState({ createModal: !this.state.createModal });
  };

  //select transaction
  selectTransaction = (transaction) => {
    this.setState({
      modalType: "update",
      form: {
        id: transaction.id,
        concepto: transaction.description,
        monto: transaction.amount,
        fecha: transaction.date,
        tipo: transaction.transactionType,
      },
    });
  };

  //handle change function
  handleChange = async (e) => {
    e.persist();
    await this.setState({
      form: {
        ...this.state.form,
        [e.target.name]: e.target.value,
      },
    });
    console.log(this.state.form);
  };

  //App
  render() {
    const { form } = this.state;

    const { transactions, isLoading, isError } = this.state;
    if (isLoading) {
      return
Cargando...
;
    }

    if (isError) {
      return
Error...
;
    }

    return transactions.length > 0 ? (

Tu saldo es de:

$0

        <button className="btn btn-success" onClick={() => this.createModal()}>
          Nueva operación
        </button>

              ID
              Concepto
              Monto
              Fecha
              Tipo
              Acciones

{this.renderTableRows()}

        <Modal isOpen={this.state.createModal}>
          <ModalHeader style={{ display: "block" }}>
             this.createModal()}>
              x

          </ModalHeader>
          <ModalBody>

              ID
              <input
                className="form-control"
                type="text"
                name="id"
                readOnly
                onChange={this.handleChange}
                value={form ? form.id : this.state.transactions.length + 1}
              />

              Concepto

              <input
                className="form-control"
                type="text"
                name="concepto"
                id="concepto"
                onChange={this.handleChange}
                value={form ? form.concepto : ""}
                placeholder="Compra, venta, etc..."
              />

              Monto

              <input
                className="form-group"
                type="text"
                name="monto"
                id="monto"
                onChange={this.handleChange}
                value={form ? form.monto : ""}
                placeholder="Monto"
              />

              Fecha

              <input
                className="form-group"
                type="date"
                name="fecha"
                id="fecha"
                onChange={this.handleChange}
                value={form ? form.fecha : ""}
              />

              Tipo de operación

              <input
                className="form-group"
                type="text"
                name="tipo"
                id="tipo"
                onChange={this.handleChange}
                value={form ? form.tipo : ""}
                placeholder="Ingreso o egreso..."
              />

          </ModalBody>
          <ModalFooter>
            <button
              className="btn btn-success"
              onClick={() => this.postPetition()}
            >
              Crear
            </button>
            <button
              className="btn btn-danger"
              onClick={() => this.createModal()}
            >
              Cancelar
            </button>
          </ModalFooter>
        </Modal>

    ) : (

No hay información para mostrar...

    );
  }
}
/*{this.renderTableHeader()}*/

export default App;

A: Since you're sending JSON, set the Content-Type header to application/json. And you have to await the result of the fetch call since it returns a promise.
const result = await fetch('http://localhost:3001/api/transactions/', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    form: {
      concepto: this.state.form.concepto,
      monto: this.state.form.monto,
      fecha: this.state.form.fecha,
      tipo: this.state.form.tipo,
    },
  }),
})

You can then access the values in the backend via req.body.form.
const { concepto, monto, fecha, tipo } = req.body.form


text:
Q: Give editor ability to edit custom settings without access to Main Settings I have created a custom settings page that I've positioned in tools > Custom Settings
add_action('admin_init', array('siteSettings', 'register'));
add_action('admin_menu', array('siteSettings', 'menu'));

$page = add_management_page(PLUGIN_NICK.' Plugin Options', PLUGIN_NICK, 'delete_posts', PLUGIN_ID.'_options', array('siteSettings', 'showPage'));

<form action="options.php"

The form posts to options.php (even though I've put it in tools menu), and the editor role gets permission died when trying to update the form, although they can access the form without errors, they just can't save.
I fixed this with
$editor = get_role('editor');
$editor->add_cap('manage_options');

However this gives them menu items; Appearance, Settings, and all other admin menus created by plugins which I don't want (I only want them to be able to access things in Tools which they had before).
Thanks!

A: Use the Settings API or hook a function to admin_init that checks permissions and nonces, saves the updated values and redirects to the custom settings page.


text:
Q: Angular cached, multicast observable, don't make HTTP call until subscribed I have a service that exposes some global state using an observable. The state must be initialized by making an HTTP call. I want all consumers of the state to receive the same value, receive the current value when they subscribe to the observable, and receive updates when the state changes.
This scenario is typically handled using a Subject, which can be initialized by subscribing it to the observable returned by the HTTP request.
However, I don't want the HTTP request to be executed until the first time something subscribes to the global state observable. If you use the subscribe method of the Subject, the HTTP request is called then.
I have the following code in the service. This works, but it seems like there should be a simpler way to do this.
  private initialized = false;
  private readonly subject = new ReplaySubject<string>(1);

  constructor(private readonly httpClient: HttpClient) {}

  get data$(): Observable<string> {
    return new Observable<string>(subscriber => {
      if (!this.initialized) {
        this.refresh();
      }
      let subscription = this.subject.subscribe(value => subscriber.next(value));
      return () => subscription.unsubscribe();
    });
  }

  refresh(): void {
    this.httpClient.get<string>('https://...')
      .pipe(
        tap(() => this.initialized = true)
      )
      .subscribe(value => this.subject.next(value));
  }

Sandbox: https://codesandbox.io/s/reverent-almeida-d2zbjx?file=/src/app/test.service.ts

A: The following should accomplish what you want.  The data$ field should be the merge of two observables.  The first will be the initial http call and the other will be listening to emission from refreshSubject to call the service again.
The initial call won't execute until the first subscription is made and any call to refreshSubject will be ignored as well.
Finally, using shareReplay will cause all subsequent subscribers to get the last result.  The refCount parameter is used so that if subscriber count becomes zero, the subscription is completely unsubscribed, and the next subscriber will initiate the first call again.  If this behavior is not desirable, you can just use shareReplay(1) which will always have the last result and continue to listen to refreshSubject.
readonly refreshSubject = new subject<void>();
readonly data$ = merge(
  this.httpClient.get<string>('https://...'),
  this.refreshSubject.pipe(
    switchMap(() => this.httpClient.get<string>('https://...'))
  )
).pipe(
  shareReplay({ bufferSize: 1, refCount: true })
);

A: I'm not sure what the subscribe and unsubscribe in your data$() method is doing. Does this simpler version (returning subject.asObservable()) also meet your requirements?
get data$(): Observable<string> {
  if (!this.initialized) {
    this.refresh();
  }
  return this.subject.asObservable();
}

A: What I tend to do in similar situations is to create a service that works like this.

*

*It exposes methods to fire the execution of commands, e.g. execute the http call

*It exposes Observables to which clients can subscribe when they want to react to changes

*Internally uses Subjects to trigger the notifications in the public Observables when the execution of the commands returns something (or errors)

So, in code, it would look something like this
export class MyService {
  private _subject = new ReplySubject<any>(1);
  public data$ = this._subject.asObservable();

  constructor(private readonly httpClient: HttpClient) {}

  public executeRemoteService(inputParams: any) {
     // the request is executed as soon as a client calls this method
     // the subject notifies, errors and completes mirroring what the
     // http client does
     this.httpClient.get<string>('https://...')
      .pipe(
         tap(this.data$)
      )
      .subscribe()
  }
}

Any client interested in data$, i.e. interested in changes in the global state, has to subscribe to data$ and this can happen in any moment.
When is the moment to fire the execution of the service, any component can call the execution of the executeRemoteService method which will then triggers the notifications in data$.

A: Based on the answer from @DanielGimenez, I implemented the solution below. It has the advantage of being slightly simpler and more DRY.
private readonly refreshSubject = new BehaviorSubject<void>(void 0);

constructor(private readonly httpClient: HttpClient) {
  this.data$ = this.refreshSubject
    .pipe(
        switchMap(() => this.httpClient.get<string>('https://...')),
        shareReplay(1)
    );
}

readonly data$: Observable<string>;

refresh(): void {
  this.refreshSubject.next();
}


text:
Q: vb listview - reading a value into a string I've searched thoroughly before asking, I'd like to find out how to take some text from a listview and pass it into a string. Theres only one column in the listview and only one row. The value in it is an integer.
The closest I came was this:
teststring = ListView1.Items.ToString

but that just filled the string with "System.Collections.Generic.List`1[System.Web.UI.WebControls.ListViewDataItem]"
Update: I'm working under ASP.NET

A: Use this,
teststring =  ListView1.Items(ListView1.Items.Count - 1)

Instead of
teststring = ListView1.Items.ToString

Because your attempt will get the ListViewItemCollection (Non-Technically: group of items), But actually your need is to get a single item from that group. If you need further clarifications, Please refer this.
Update,
 teststring =  Ctype(ListView1.Items(ListView1.Items.Count - 1),Control).text

A: Try this:
teststring = ListView1.Items(0).Text