text:
Q: How to stop gatekeeper always asking for app verification in standard account? I've recently done a clean install of High Sierra and am struggling with reducing the annoyance of the app verification from gatekeeper. For security I log in as a standard user and have a separate admin account - this is the first time I've tried that separation between admin and standard accounts, which is where the problem may lie.
If I right-click the app and 'open', then confirm open again in the gatekeeper dialog, then I will still be asked every time I open the app.
I have disabled gatekeeper (security pane now has third radio button - allowing 'Anywhere' for download source) but this hasn't helped.
I used brew cask to download and install a number of apps and suspect it's those that I can't permanently approve.

A: you can try this in terminal To add an application to Gatekeepers exceptions and approved application launch list,
spctl --add /Path/To/Application.app

replace the Path and Application with yours


text:
Q: linux C++: libaio.h doesn't contain definition for io_context_t? I've got a super simple .cpp file like below:
    $cat test001.cpp
    #include<libaio.h>
    int main(){
        io_context_t ctx={0};
        struct iocb io,*p=&io;
        return 0;
    }

But once compile it with gcc 4.1.2, it prompts error:
    $g++ test001.cpp -laio
    test001.cpp:1:19: error: libaio.h: No such file or directory
    test001.cpp: In function 'int main()':
    test001.cpp:3: error: 'io_context_t' was not declared in this scope
    test001.cpp:3: error: expected `;' before 'ctx'
    test001.cpp:4: error: aggregate 'iocb io' has incomplete type and cannot be defined

Well I'm already using "libaio.h". Why it still fails?

A: sudo apt-get install libaio-dev It should definitely fix the issue. It is for Linux kernel AIO access library - development files.

redpajama_set_name: RedPajamaStackExchange


text:
Q: The property on entity type has a temporary value while attempting to change the entity's state to 'Deleted'. Either set a permanent value explicitly When i try to delete some data, i got an error message like this

InvalidOperationException: The property 'EntitasID' on entity type 'EntitasViewModel' has a temporary value while attempting to change the entity's state to 'Deleted'. Either set a permanent value explicitly or ensure that the database is configured to generate values for this property.

this is my delete function in controller:
   ''' [Authorize]
    public IActionResult Delete(int? id)
    {
        EntitasViewModel entitasViewModel = _context.Master_Entitas.Where(p => p.EntitasID == id)
            .Include(p => p.HoldingViewModel).FirstOrDefault();
        return View(entitasViewModel);
    }

    // POST: Entitas/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    [Authorize]
    public IActionResult DeleteConfirmed(int? id)
    {
            EntitasViewModel entitasViewModel = new EntitasViewModel();
            _context.Attach(entitasViewModel);
            _context.Entry(entitasViewModel).State = EntityState.Deleted;

            _context.SaveChanges();
            _notyf.Success("Data berhasil dihapus", 3);

            return RedirectToAction(nameof(View));

    }'''

this is my model:
public class EntitasViewModel
    {
        [Key]
        public int EntitasID { get; set; }
        public string NamaEntitas { get; set; }

        [ForeignKey("HoldingViewModel")]
        [DisplayName("HoldingViewModel")]
        public int HoldingID { get; set; }
        public virtual HoldingViewModel HoldingViewModel { get; set; }

        [NotMapped]
        public List<HoldingViewModel> master_Holding { get; set; }

    }

Please help me guys this is for my thesis thank youu

A: When you want to delete data, you should get the model by it, not create a new one.
public IActionResult DeleteConfirmed(int? id)
{
        EntitasViewModel entitasViewModel = _context.Master_Entitas.Where(p => p.EntitasID == id)
        .Include(p => p.HoldingViewModel).FirstOrDefault();
        _context.Entry(entitasViewModel).State = EntityState.Deleted;

        _context.SaveChanges();
        _notyf.Success("Data berhasil dihapus", 3);
        return RedirectToAction(nameof(View));
}

Related Post:
entity framework Remove vs EntityState.Deleted


text:
Q: Fatal Error While Running Artisan (Laravel) on Command Line I am experiencing a fatal error while using artisan on the (fantastic) Laravel PHP framework.
I recently downloaded v3.2.1 of Laravel, and I tried running the following command line from within the directory that artisan resides:
php artisan key:generate

This should create a random key for me in my applications/application.php file. (Please see http://laravel.com/docs/artisan/commands for a specific reference to this command.)
However, when I run this command from the shell I receive the following error:
Warning: chdir(): No such file or directory (errno 2) in /home/[USERNAME REMOVED]/websites/[DIRECTORY REMOVED]/htdocs/dev/sb4/paths.php on line 62

Parse error: syntax error, unexpected T_STRING in /home/[USERNAME REMOVED]/websites/[DIRECTORY REMOVED]/htdocs/dev/sb4/laravel/core.php on line 1

This is what's on line 62 of paths.php:
chdir(__DIR__);

This is what's on line 1 of core.php:
<?php namespace Laravel;

My question is this: Are there any specific environment, directory, or other permissions that I should modify to get artisan up and running.
A little background:

*

*I installed Laravel 3.2.1 yesterday for the first time

*I can run a simple web application successfully on my system (i.e. I can route a request to a controller and load up the associated blade properly)

*I simply downloaded the Laravel 3.2.1 (laravel-laravel-v3.2.1-8-gaae8b62.zip) from GitHub and extracted it on my server

My environment:

*

*PHP 5.3.13 on a shared host at Dreamhost

*FireSSH to run the commands

My root directory: (permissions in parenthesis)

*

*/application (775)

*/bundles (775)

*/laravel (775)

*/public (775)

*/storage (775)

*/artisan (664)

*/paths.php (777)

Please let me know if there are any other details about my setup that relevant. I'm really not sure what will help in troubleshooting this issue.
--
UPDATE: I also posted this issue to Laravel's GitHub issue tracker. (https://github.com/laravel/laravel/issues/820)

A: Namespaces and the __DIR__-pseud-constant were introduced in PHP 5.3. It seems you are running an old version. You should update to at least 5.3.
php -v

A: First off, thanks @KingCrunch, your first response led me down the correct path toward resolving this issue. Additionally, I received an excellent response from Dreamhost technical support (specifically Gary S), who gave me the concise answer I was looking for.
The issue was: I was running PHP 5.2.17 at the CLI, whereas my web server was running PHP 5.3.13.
The resolution is: Use
/usr/local/php53/bin/php artisan <command>

when running artisan commands at the CLI. This will ensure that all of my artisan commands are run using PHP 5.3 and above, which satisfies Laravel's PHP 5.3+ requirements.


text:
Q: Why do links over image work in Chrome/Firefox but not in Internet Explorer? I created an image with some links on top of it here. It works as it should in Google Chrome and Firefox but not in Internet Explorer 8. Does anybody know how/whether I could fix that?

A: For some obscure reason, IE sometimes "doesn't like" completely transparent areas of absolutely positioned links. Setting any explicit background to them other than default transparent none (background: url(about:blank) "hack" usually does the trick) seems to make IE treat them correctly. In IE9+, background:rgba(0,0,0,0) also seems to do the trick (although it should be just the same as transparent per CSS spec).

A: You might need to specify the z-index of the image to ensure it appears behind the links in IE8.

A: i dont have your code but i think this may help you. try this class:
.dict {
position: relative;
margin-top: -138px;
float: left;
display: block;
height: 116px;

A: On the links there should be a z-index value for start, in IE(6-7-8), z-index is only working when the parent element also has a z-index value:
.dict {
    display: block;
    height: 116px;
    position: absolute;
    top: 79px;
    z-index: 2;
}
<div style="position:relative;width:860px;height:200px;z-index:1;">

A: I still don't know why it's not working. But the problem is solved (even for ie8) by removing the img from the html and using it as a background with CSS.


text:
Q: Why am I getting 'Foreign Key Mismatch' when trying to save a model form in Django? I am trying to save an instance of a modelform in Django. I have setup a template to input information to the form and a view to handle the save. The form validates fine, but when trying to save it generates a foreigkey mismatch error. What am I doing wrong here?
I am running Django 2.0.0. I have already tried adding and removing the primary_key option without any luck and deleting my sqlite database, clearing all pycache, and migrating again. The problem persists.
#models.py
from django.db import models
import uuid
from users.models import Company, CustomUser
from delivery import settings

class Location(models.Model):
    location_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    address = models.CharField(max_length = 120)
    date_added = models.DateField(auto_now_add = True)

class Shipment(models.Model):
    date_created = models.DateField(auto_now_add=True)
    sender_company = models.ForeignKey(Company, on_delete = models.PROTECT, related_name='sender')
    receiver_company = models.ForeignKey(Company, on_delete = models.PROTECT, related_name='receiver')
    origin = models.ForeignKey(Location, on_delete = models.SET_DEFAULT, default = 'Location no longer active.', related_name='origin')
    destination = models.ForeignKey(Location, on_delete = models.SET_DEFAULT, default = 'DESTINATION UNKNOWN', related_name='destination')
    expected_arrival = models.DateField()
    weight = models.FloatField()
    current_handler = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.SET_DEFAULT, default = 'UNKNOWN')
    shipment_id = models.UUIDField(unique=True, primary_key = True, default=uuid.uuid4, editable=False)

#forms.py
from django import forms
from .models import Location, Shipment

class LocationRegisterForm(forms.ModelForm):

    class Meta:
        model = Location
        fields = '__all__'

class CreateShipment(forms.ModelForm):

    class Meta:
        model = Shipment
        exclude = ['current_handler', 'shipment_id']

    def clean_expected_arrival(self):
        expected_arrival = self.cleaned_data['expected_arrival']
        date_created = self.cleaned_data['date_created']
        if expected_arrival < date_created:
            raise ValidationError('Expected arrival date cannot be in the past.')
        return expected_arrival

#views.py
from django.shortcuts import render, redirect
from .forms import CreateShipment, LocationRegisterForm
from users.permissions import group_required

@group_required('delivery_employee')
def new_shipment(request):
    if request.method == 'POST':
        form = CreateShipment(request.POST)
        if form.is_valid():
            temp_form = form.save(commit=False)
            current_user = request.user
            temp_form.current_handler = current_user
            temp_form.save()
            return redirect('dash-home')
        else:
            return render(request, 'shipments/new-shipment.html', {'form':form})
    form = CreateShipment()
    return render(request, 'shipments/new-shipment.html', {'form':form})

@group_required('delivery_employee')
def add_location(request):
    if request.method == 'POST':
        form = LocationRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('new-shipment')
        else:
            return render(request, 'shipments/location-register.html', {'form':form})
    form = LocationRegisterForm()
    return render(request, 'shipments/location-register.html', {'form':form})

I get the error message:
File "C:\Python34\lib\site-packages\django\db\backends\sqlite3\base.py", line 303, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: foreign key mismatch - "shipments_shipment" referencing "shipments_location"

Thank you!

A: Your origin and destination fields set default value to plain strings, their default values should be the default Location instances instead.
Create methods like get_default_origin and get_default_destination where you will return the existing records from the database. Assign those methods to default argument, like
origin = models.ForeignKey(Location, on_delete = models.SET_DEFAULT, default=self.get_default_origin, related_name='origin')
destination = models.ForeignKey(Location, on_delete = models.SET_DEFAULT, default=self.get_default_destination, related_name='destination')


text:
Q: Makefile pattern rules on multiple subdirectories So I have a GNU Makefile to compile all .cpp files from my Game directory and its subdirectories into .o files in build/obj folder (no subdirectories in that one). My problem is that only the first file in the list is compiled, I know the problem is that I need a build pattern, but I can't think of a way to implement this in each subdirectory. I've tried several things, looping through all the directories using foreach, removing the filename from the directory and putting a wildcard in place, but all to no avail. Any help?
SRC_DIR=src
BUILD_DIR=build
OBJ_DIR=$(BUILD_DIR)/obj

GAME_DIR=$(SRC_DIR)/Game
GAME_DIRS=$(GAME_DIR)/Classes $(GAME_DIR)/ConVars $(GAME_DIR)/EventListener $(GAME_DIR)/Functions $(GAME_DIR)/Interfaces $(GAME_DIR)/Modules $(GAME_DIR)/NetVars $(GAME_DIR)/Offsets $(GAME_DIR)

SRC_FILES=$(foreach dir,$(GAME_DIRS),$(wildcard $(dir)/*.cpp))
OBJ_FILES=$(addprefix $(OBJ_DIR)/,$(notdir $(patsubst %.cpp,%.o,$(SRC_FILES))))

all: $(OUT)

$(OUT): $(OBJ_FILES)
    $(CC) -shared $^ -o $@ -std=c++17 -lgdi32

$(OBJ_FILES): $(OBJ_DIR)/%.o: $(SRC_FILES)
    $(CC) -c $< $(CFLAGS) -o $@

A: This is wrong:
$(OBJ_FILES): $(OBJ_DIR)/%.o: $(SRC_FILES)

It says, each object file depends on ALL the source files.  The SRC_FILES variable expands to the same list of files every time, so for every object file the list of prerequisites is the same, so every time you compile it you use $< which expands to the first prerequisite, so the same file is compiled over and over.
In a pattern rule the part of the name that matches the pattern must be identical between the target and prerequisite, and the part of the name that doesn't match the pattern must be static.
As a result there is no way to use one single pattern rule to build all your source files like this.  There are a number of options you have:
You can create multiple pattern rules, one for each source directory (it's easier to avoid static pattern rules in this situation):
$(OBJ_DIR)/%.c : Classes/%.cpp
         ...
$(OBJ_DIR)/%.c : ConVars/%.cpp
         ...

Or, you can put the object files into a subdirectory of OBJ_DIR, but with the same prefix.  So instead of Classes/class.cpp building to obj/class.o, it would build to obj/Classes/class.o.  For this you'd use:
OBJ_FILES=$(addprefix $(OBJ_DIR)/,$(patsubst %.cpp,%.o,$(SRC_FILES)))

$(OBJ_FILES): $(OBJ_DIR)/%.o : %.cpp
        @mkdir -p $(@D)
        $(CC) -c $< $(CFLAGS) -o $@

(note, it's not really right to use CC and CFLAGS for building C++ code; those variables are traditionally used to build C code.  CXX and CXXFLAGS are the best variables for building C++ code)
The other option is to use VPATH, like this:
 VPATH = $(GAME_DIRS)

 $(OBJ_FILES): $(OBJ_DIR)/%.o : %.cpp
          $(CC) -c $< $(CFLAGS) -o $@


text:
Q: Google search box only works 50% of the time I'm writing a new tab extension for Firefox, and I'd like to have a box that you can type in and have it search Google. I really don't want to use a custom Google search, just because I feel like it's inconsistent and seems cheap.
All that it's supposed to do is add your query to the end of the google URL (in the correct formatting, of course) and redirect you to that page. I have it working sometimes, but not all of the time.
Here's the code I have:
JS:
var textstring;

//Gets the text from the form
function getQ() {
    textstring = document.forms['Search'].elements[0].value;
}

//Does a Google Search
function googleSearch() {
    window.location ="http://www.google.com/search?q="+textstring;
}

//main function to run everything
function main() {
    getQ();
    googleSearch();
}

HTML:
<form name="Search" >

    <input type="text" name="q" size="31" maxlength="255" value="" />

    <input type="button" value="Google Search" onclick="main();" />

</form>

Not sure why that last /form isn't showing up, but that's in there just so you guys know.
It works like 25% of the time. I can't figure out what's wrong with it. Could it just be that I'm testing it locally? I've been testing it in Firefox, but it seems to have the same issue in IE or Chrome, as well.

A: Why don't you just submit to google (and avoid all the javascript) ?
<form name="Search" method="get" action="http://www.google.com/search" >

and use a normal submit button like
<input type="submit" value="Google Search" />

Since you have named the input element q and the method of the form is get it will create the correct url.
example: http://jsfiddle.net/gaby/gxun9/


text:
Q: 'page' not found in kaminari when used as dependency in gem I am buiding and i wish to kaminari as a gem, it seems like kaminari is being installed since i checked the bundle command on the test_app and the gem.
product = Product.order('products.created_at DESC').page(params[:page]).per(4)

I get an error saying ::
Undefined method 'page'.

I am using the above code in the gem btw.
def index
  product = Product.order('products.created_at DESC').page(params[:page]).per(4)
end

Product is the model.


text:
Q: R code for SDM using randomForest I wonder if someone can provide me with R code for running Species Distribution model using  randomForest where I can't find any tutorials or demos for this.

A: I'm beginning to work on this subject and I found this:
https://cran.r-project.org/web/packages/dismo/vignettes/sdm.pdf
The tutorial seems to be a good starting point because it contains a lot of code examples including random forest!


text:
Q: Checking server status I'm trying to check the status on multiple servers at the same time but when I load the form the app is just freezing without any error. This is what im using to check server status. Any idea?
TcpClient tcpClient = new TcpClient();

try
{
    tcpClient.Connect("ip address here", port);
    Status1.Text = "Online";
    Status1.ForeColor = Color.Green;
}
catch (Exception)
{
    Status1.Text = "Offline";
    Status1.ForeColor = Color.Red;
}

try
{
    tcpClient.Connect("ip address here", port);
    Status2.Text = "Online";
    Status2.ForeColor = Color.Green;
}
catch (Exception)
{
    Status2.Text = "Offline";
    Status2.ForeColor = Color.Red;
}

A: Have a look at this code snippet, this will not block the UI thread and keep the form responsive.
    static async Task CheckConnection()
    {
        TcpClient tcpClient = new TcpClient();

        try
        {
            await tcpClient.ConnectAsync("ip address here", port);
            Status1.Text = "Online";
            Status1.ForeColor = Color.Green;
        }
        catch(AggregateException a)
        {
            Status1.Text = "Offline";
            Status1.ForeColor = Color.Red;
        }
        catch (Exception)
        {
            Status1.Text = "Offline";
            Status1.ForeColor = Color.Red;
        }

    }

if you are new to this programming model, check out this link


text:
Q: Object callback defined in unusual way in Java I came across a code, and 1 thing stumped me. Here is the code
static public Return fun1()
{
  return new register(new SomeMap[]{
         null,
         new SomeMap(new Basic(String.class), new Basic(String.class))
  })
  {
    @Override
    public Return getSomething(int val)
    {
     ....
    }
  };
}

As you can see the override callback method is defined outisde the scope of new register(..). The call back function seems to be defined outside within its own code block. Is this possible? How does this work?
) is before the function override.
Shouldn't it be like this?
static public Return fun1()
    {
      return new register(new SomeMap[]{
             null,
             new SomeMap(new Basic(String.class), new Basic(String.class))
      }

        @Override
        public Return getSomething(int val)
        {
         ....
        }
      );
    }

public static class register extends SomeMap
{
   public register(SomeMap[] somemaps)
   {
   }

    public Return getSomething(int val)
    {
     ....
    }
}

public static abstract class SomeMap
{
   // no constructors here just some method definitions here
}

A: While a regular simple anonymous class looks just
new Anonymous() {
    public void method() {
        // implementation
    }
};

The example takes a SomeMap[] constructor argument, but otherwise it's the same thing
new register(       // New anonymous class
    new SomeMap[]{  // Provide SomeMap[] for the constructor
         null,      // SomeMap[0] contains null
         new SomeMap(new Basic(String.class), new Basic(String.class)) // SomeMap[1] has data
    }) {            // End constructor
        // Define the method, in the right place
        @Override
        public Return getSomething(int val) {
        }
    };  // End anonymous class

I wouldn't let that kind of code fly though, even if it were properly formatted.


text:
Q: How can I get default data from route in mojolicious? I want to create some routes with restrictions by role. Something like this:
my $auth = $app->routes->under->to('auth#check');
$auth->get('/list')->to('some#list')->name('list');
$auth->get('/add')->to('some#add', roles => ['user', 'admin'])->name('add');

I don't have any problem with checking roles in after_dispatch hook. But I cannot access this data when I'm trying to create a links for this routes.
For example, I'm a guest on /list route and want to form menu with available links. So, I have to check roles from route /add to decide to show this link or not.
For this moment I found only one way to get default data from route with name:
 app->routes->lookup('add')->pattern->defaults->{roles}

And it looks like a hack. How I can do this in a right way?

A: You are right. This method to get defaults of the route is documented here
my $defaults = $pattern->defaults;
$pattern     = $pattern->defaults({foo => 'bar'});


text:
Q: Devising a test for a Web Developer I need to devise a test for web developers.
This test should screen both good grasp of the DOM and manipulating it and
Good skills in designing scalable and efficient DB and server side code, And to salt it a bit with web specific problems (like translating from one encoding to another, clean input-security).
And best of all, cram it into 3 hours.

A: A company called Red Snapper has a test for applicants. Perhaps you can look into it and see if you can't find things there that can help you.

A: It sounds like you already know exactly what you want to test the developer on... why don't you just make him create a small website that includes some of the ideas you have already suggested. However, in 3 hours it's unlikely you'll get the full experience of any developer.
You could use something like a message queuing system, as that should be simple enough, where any user can post messages that have to be accepted by an administrator - and once accepted are displayed on the page.
This example may seem ultra-trivial, but a lot goes into something this simple: database input sanitation, database creation, managing sessions, proper authentication and authorization, Ajax if you want it, proper separation of business logic from presentation, etc.
Basically, keep the test simple if it's a 3 hour venture.


text:
Q: With the Mixcloud API how would you search for shows that have a specific track in them? I want to be able to search for all shows that contain a specific track using the Mixcloud API.
Looking through the documentation for the Mixcloud https://www.mixcloud.com/developers/, as well as the Ruby library I was debating using: https://github.com/actfong/mixcloud, I can't see this functionality exposed, is there a way to do it that I don't know about?

A: Well, it was possible quite not a long time ago, but it seems that Mixcloud has disabled this feature in the API.
An example app, that implemented this kind of search: https://github.com/mixcloud/Mixcloud-LazyDJ
Funny thing is that it's official and still powered in the mixcloud.com domain.
Check out this code:
 $.getJSON(LazyDJ.host + '/track/' + artistSlug + '/' + trackSlug + '/?callback=?', function(response) {
    results = [response];
    addResults();
    if (getTO !== null) {
        clearTimeout(getTO);
        getTO = null;
    }
});

Additionally, it also worked using a classic WWW URL scheme, like:
http://mixcloud.com/track/eric-prydz/call-on-me
Was never documented or supported though, since the main site revamp few years ago.
I've send an email to the support crew regarding re-enabling of this feature, since I have been extensively using it for private purposes.


text:
Q: Solr Queries do not return expected values We have a solr configuration simply like this https://gist.github.com/118d17e93267123f4870
According to that, I'm indexing a title The Secret of Rhonda Byrne or the Law of Attraction in the Bible with an id.
Then I go to the Solr Analysis tool to see how its gonna get indexed in this field. So the index analysis if that field type with given value is returning something like;
secret rhonda byrne law attraction bible

Just to make sure, I'm querying the id field of that title to see if its there. Positive.
But when I query this index with the analysis tool result I get no results. My query is like;
select?qf=title_stm&q="Secret+Rhonda+Byrne+Law+Attraction+Bible"&fl=id,title&defType=dismax

As given in comments, debug output of that query is here;
https://gist.github.com/9b88fd6b5f043c90d539

A: Issue is with : -
<filter class="solr.StopFilterFactory"
        ignoreCase="true"
        words="stopwords.txt"
        enablePositionIncrements="true"
        />

The enablePositionIncrements with increment the positions whenever it encounters the stopwords.
Hence, when you do an exact phrase match this would not match as position of the indexed title are not next to each other.
Read more of it here.
You should disable the position increments to able to be do a phrase match.
<filter class="solr.StopFilterFactory"
        ignoreCase="true"
        words="stopwords.txt"
        enablePositionIncrements="false"
        />


text:
Q: Automated zip process sometimes skips files Part of my application exports data in a series of CSV files, adds a cover note and then packs all this data into a password protected zip file, ready for dispatch.
Here's the relevant code that does the zipping.
private bool ZipFiles(string zipfile, string filename, string password)
{
    string arguments = string.Format(@"a -tzip ""{0}"" ""{1}"" -p{2}", zipfile, filename, password);

    ProcessStartInfo startInfo = new ProcessStartInfo(_zipExePath)
    {
        UseShellExecute = false,
        RedirectStandardError = true,
        RedirectStandardInput = true,
        RedirectStandardOutput = true,
        CreateNoWindow = true,
        ErrorDialog = false,
        Arguments = arguments,
        WindowStyle = ProcessWindowStyle.Hidden
    };

    try
    {
        Process.Start(startInfo);
    }
    catch (Exception ex)
    {
        Log.Error("Zip Process Failed", ex);
        return false;
    }

    return true;
}

It's called like this:
string notePath = CreateNote(task);
string zipfile = _outputPath + "\\" task.TaskNumber + ".zip";
string filewildcard = _outputPath + "\\Data\\*.csv";

if (!ZipFiles(zipfile, filewildcard, task.Password) || !ZipFiles(zipfile, notePath, task.Password))
{
    Log.Error("Failed to created zip archive for Id " + task.TaskID);
    hasError = true;
}

Most of the time, this works without issue. However, there's an intermittent issue which causes some of the target files not to end up in the archive. Most of the time when this happens the note gets included, but none of the data. Rarely, no files at all are included in the archive.
There doesn't seem to be any unifying factor in the tasks that fail. Sometimes a task will fail to produce a correct zip and then, after being reset, it can be run again and create the zip correctly.
Whenever I've tried to use the debugger to step through this code to replicate the issue, the files zip as expected. I've done this a lot of times and in the debugger it seems to work without fault every single time.
No error is logged when the files don't all zip.
So I assumed it might be a timing issue - that effectively the code was getting to the zip portion before the disk had finished outputting the data. I added a wait in between the code that generates data, and the code I've posted
Thread.Sleep(500);

That didn't fix it. So I made it longer and longer. There's now a ten minute pause, and this issue still occurs.
I'm out of ideas on what could be causing this. Does anyone have any other thoughts?

A: I think the problem may be caused by this code:
if (!ZipFiles(zipfile, filewildcard, task.Password) || !ZipFiles(zipfile, notePath, task.Password))
{
    Log.Error("Failed to created zip archive for Id " + task.TaskID);
    hasError = true;
}

When the if statement is executed, it first calls ZipFiles which will return almost immediately with a true result, it will then call ZipFiles again (second condition of the if statement) so that you have two instances of the zip utility running at almost the same time, using the same zip filename. They might be stepping on eachother's toes.
You could try adding a call to Process.WaitForExit to make sure the first instance completes before starting the second:
try
{
    Process p = Process.Start(startInfo);
    p.WaitForExit();
}
catch (Exception ex)
{
    Log.Error("Zip Process Failed", ex);
    return false;
}

The try/catch in this code will not catch any exceptions that occur in the zip utility. It will catch any exceptions that occur while starting the executable. You may wish to check the value of p.ExitCode to see if the utility had any problems and if so, return false.


text:
Q: exponential function does not work in r but pol does I would like to fit/draw an exponential function but it does not work. For
before_database.frame<- read.table("APD_data.txt",
                                  header = TRUE,
                                  sep = "",
                                  dec="."
                                 )

Single_APD.frame<- before_database.frame[before_database.frame$Serial_number==912009913, ]

# fit<- lm(Voltage ~ poly(Amplification,2), data=Single_APD.frame)
fit<- lm(Voltage ~ exp(Amplification), data=Single_APD.frame)

I receive:
Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) :
  NA/NaN/Inf in 'x'

But " ~ poly(Amplification, 2)" works. What is wrong? I already searched for the error but the solutions do not work for me.
Thank you!
Data

A: This answer is based on comments with the OP @Ben
The error you were getting with lm(Voltage ~ exp(Amplification), data=Single_APD.frame):
Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) :
NA/NaN/Inf in 'x'

suggested that at least one of your values was NA/NaN/Inf. The range of your values
What is output of range(Single_APD.frame$Amplification)?
@ChiPak Sure, it's" [1] 1.00252 1903.74000

-----poly-----
~ poly(Amplification, 2) was not giving you an error, but poly doesn't do you what you expected.
See https://stackoverflow.com/questions/19484053/what-does-the-r-function-poly-really-do.

You probably were looking for
val <- 1:5
2^val

This explains why poly works.
-----Error-----
Going back to your error:
exp(1903.74000)

is Inf, which explains your error

A: Your dataset probably contains NULL values NA, and for this reason the function exp for those values, can not be calculated.
Your dataset contains NA values, or not?


text:
Q: C# Console.WriteLine from another Thead doesn't work I have a simple problem that I can't resolve. I am learning how to use Thread in C#, and I try to write in the console from another Thread with that code :
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        Thread thread = new Thread(myFunc);
    }

    public void myFunc()
    {
        Console.WriteLine("Test");
    }
}

There is nothing printing on the output. If I move the WriteLine in the public MainWindow() it works... where is the problem ?
Thanks !

A: You have created the thread, but it is not running. You need to start the thread. Call thread.Start() after you create it.

A: And even if you start the thread (as @mike mentioned and should be added) you will not see anything! Because before your thread get any chance to run your program (Main method) will end.

A: Call
thread.Start();
thread.Join();

so the thread can start running and finish.


text:
Q: Most General Theory of Stochastic Integration I've learnt continuous stochastic integration using the classical books:
- Revuz & Yor,
- Karatzas & Shreve and
- Oksendal.
Now I want to learn general stochastic integration, i.e. possibly discontinuous semimartingales.
Can anyone recommend some literature, which covers this topics and also provides some exercises?

A: The monograph Stochastic Integration and Differential Equations by Philip E. Protter covers stochastic integration with respect to semimartingales and provides exercises at the end of each chapter. This is the standard reference, I would say (at least for graduate students).
The first part of Limit Processes for Stochastic Processes by Jean Jacod and Albert Shiryaev also discusses stochastic integration with respect to semimartingales. Although this is not an easy read, you should manage if you are familiar with stochastic processes and integration (with respect to continuous martingales) and if you like rigorous books. However, the book doesn't contain any exercises.

A: Protters book uses a more modern approach based on functional analysis - whereas Jacod uses the "classical approach".
Jacods exposition is very short (but nevertheless rigorous) - the whole theory is developed in less than 60 pages. (Personally i found Jacods book better)
I want to point out a third option. In fact this is perhaps the most rigorous and self contained treatment you can get (as literally every basic property of martingales is proven as well) - however it requires a lot of time and dedication. Its the book "Probabilities and Potential  B: Theory of Martingales" from Dellacherie & Meyer.


text:
Q: Coding for cellphones I have a old LG MG280 cellphone that I'd like to code some simple things for. It has Java support, but I know that it is not simply making a Java ME application. It has to follow some specific specs otherwise the app will not run. Does anyone know what those specs are?

A: JavaME platforms are made up of a profile and a configuration. Most mobile phones use some combination of the Mobile Information Device Profile (MIDP) and the Connected Limited Device Configuration (CLDC).
The LG MG280 you are interested in uses MIDP-2.0 and CLDC-1.1, which is pretty standard.
To get started with development you'll probably want to be using the Sun Java Wireless Toolkit (frequently abbreviated to SJWT or WTK). Or, if you are a windows user, you can use the (newer) JavaME SDK 3.0. This gives you tools needed to compile/package applications and an emulator which lets you run/debug application on a desktop computer.
There are numerous tutorials available online. Here's a few to get you started:

*

*http://today.java.net/pub/a/today/2005/02/09/j2me1.html

*http://developers.sun.com/mobility/midp/articles/wtoolkit/

*http://developers.sun.com/mobility/learn/

*http://www.developer.com/java/j2me/article.php/1561591

A: Find out which J2ME profile it has - MIDP etc. Then find an appropriate tutorial, such as this one.


text:
Q: Simulation veins-run has encountered a problem. Simulation terminated with exit code: -1073740940 I use Omnet++ 5.4.1 Veins 4.7.1 and Sumo 30.
My simulation works well and generates the right output
But when the simulation time runs end or I stop the simulation, it shows the following error:

simulation veins-run' has encountered a problem. finish with error
    Simulation terminated with exit code: -1073740940
  Working directory: C:/Users/AB/src/omnetpp-5.4.1/samples/veins/examples/veins
  Command line: ../../../../bin/opp_run.exe -m -u Qtenv -n .;../../src/veins --image-path=../../images -l ../../src/veins omnetpp.ini
  Environment variables:
  PATH=;C:/Users/AB/src/omnetpp-5.4.1/samples/veins/src;C:\Users\AB\src\omnetpp-5.4.1\bin;C:\Users\AB\src\omnetpp-5.4.1\tools\win64\mingw64\bin;C:\Users\AB\src\omnetpp-5.4.1\tools\win64\usr\bin;;C:/Users/AB/src/omnetpp-5.4.1/ide/jre/bin/server;C:/Users/AB/src/omnetpp-5.4.1/ide/jre/bin;C:/Users/AB/src/omnetpp-5.4.1/ide/jre/lib/amd64;.;C:\Users\AB\src\omnetpp-5.4.1\bin;C:\Users\AB\src\omnetpp-5.4.1\tools\win64\mingw64\bin;C:\Users\AB\src\omnetpp-5.4.1\tools\win64\usr\local\bin;C:\Users\AB\src\omnetpp-5.4.1\tools\win64\usr\bin;C:\Users\AB\src\omnetpp-5.4.1\tools\win64\usr\bin;C:\Windows\System32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Users\AB\src\omnetpp-5.4.1\tools\win64\usr\bin\site_perl;C:\Users\AB\src\omnetpp-5.4.1\tools\win64\usr\bin\vendor_perl;C:\Users\AB\src\omnetpp-5.4.1\tools\win64\usr\bin\core_perl;C:\Users\AB\src\omnetpp-5.4.1;
  OMNETPP_ROOT=C:/Users/AB/src/omnetpp-5.4.1/
  OMNETPP_IMAGE_PATH=C:\Users\AB\src\omnetpp-5.4.1\images

And the finish() method doesn't work, and I can't record the information and use it to draw chart.
Please help me to solve my problem.
Thanks.

A: In your omnetpp.ini set:
debug-on-errors = true

and start the simulation in debug mode. The debugger should show the command that causes an error. Reference: OMNeT++ Tutorial - 2.3 Debugging
Another clue: unfortunately OMNeT++ uses decimal numbers for exit code, while hex values are more valuable. The exit code -1073740940 has the hex representation: 0xc0000374. One may use the last number for looking among Microsoft Windows exception codes.


text:
Q: sqlcmd not connecting to Azure database I am trying to use the command below to access my database within Azure
sqlcmd -s tcp:DBNAME HERE.database.windows.net -U USERNAME -P PASSWORD

I get the error

Sqlcmd: Error: Microsoft ODBC Driver 13 for SQL Server : Named Pipes
  Provider: Could not open a connection to SQL Server [2]. . Sqlcmd:
  Error: Microsoft ODBC Driver 13 for SQL Server : Login timeout
  expired. Sqlcmd: Error: Microsoft ODBC Driver 13 for SQL Server : A
  network-related or instance-specific error has occurred while
  establishing a connection to SQL Server. Server is not found or not
  accessible. Check if instance name is correct and if SQL Server is
  configured to allow remote connections. For more information see SQL
  Server Books Online..

Has anyone ever had this?  I have downloaded the latest version of sqlcmd
I need to get a lot of data into my Azure database, but I am running out of options as the Import Data option in management studio cant cope.  This was the first method I tried.  After processing 70000 of 250000 rows it just goes to stopped with no error message, thats what then led me to try with BCP SQLCMD
Paul

A: Your command is incorrect. The 'S' should be capitalized and you should provide the server name, not the database name.
sqlcmd -S tcp:myServer.database.windows.net -d database -U username -P password

See the documentation page for the complete syntax of sqlcmd.

A: Please make a ping to the name of your Azure SQL Database server as shown below:
C:\> ping myserver.database.windows.net

The ping command should fail but it should return the current IP of your SQL Azure Database server. If it fails to return that IP, then you cannot access to Azure server due to a DNS resolution problem.
If the ping command returned the IP address successful, then try to telnet your SQL Azure Database server as shown below.
C:\> telnet myserver.database.windows.net 1433

If the telnet command fails make sure your computer firewall or network hardware is allowing traffic to the IP returned on the previous step and make sure TCP port 1433 is open. If your are trying this from a corporate network, please contact your network administrator with this requirements.
Please note that you may need to enable the telnet command via Control Panel -> Program and Features -> Turn on/off features.

A: I just want to point out that BCP and sqlcmd are two different tools.
BCP is the bulk copy command.  The later is the command line tool for querying.
If you are getting a named pipes issue, you might not have the client and/or server libraries configured.
Please go to SQL Server Configuration manager to check the settings.
By default, Azure SQL database is using TCP and you do not need to tell it on the command line.

In the image above, I am connecting to a Azure SQL database using the correct switches from books on line.  Querying the sys.tables catalog returns the information that I expect.  Two tables with different names.  One duplicated named table under different schemas.
The BCP command will work the same way.  You might even want to try a format file.
I want to clarify your statement that importing is taking a long time.  Please remember that Azure SQL database is platform as a service.  The database tiers are set at predetermined DTU's.  That means stuffing the server with a lot of data will result in a throttled server at MAX DTU's.
I would look at the portal and see if that is your situation.
In short, sqlcmd, bcp and the import/export wizard are perfect tools for data loads a lot larger than the numbers you are talking about.  Just remember, syntax is key to any successful program!


text:
Q: How do I fix a missing lifetime specifier? I have a very simple method. The first argument takes in vector components ("A", 5, 0) and I will compare this to every element of another vector to see if they have the same ( _ , 5 , _) and then print out the found element's string.
Comparing ("A", 5, 0 ) and ("Q", 5, 2) should print out Q.
fn is_same_space(x: &str, y1: i32, p: i32, vector: &Vec<(&str, i32, i32)>) -> (&str) {
    let mut foundString = "";

    for i in 0..vector.len() {

        if y1 == vector[i].1 {
            foundString = vector[i].0;
        }

    }
    foundString
}

However, I get this error
error[E0106]: missing lifetime specifier
 --> src/main.rs:1:80
  |
1 | fn is_same_space(x: &str, y1: i32, p: i32, vector: &Vec<(&str, i32, i32)>) -> (&str) {
  |                                                                                ^ expected lifetime parameter
  |
  = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `x` or one of `vector`'s 2 elided lifetimes

A: So the problem comes from the fact that vector has two inferred lifetimes, one for vector itself (the &Vec part) and one for the &str inside the vector.  You also have an inferred lifetime on x, but that really inconsequential.
To fix it, just specify that the returned &str lives as long as the &str in the vector:
fn is_same_space<'a>(                        // Must declare the lifetime here
    x: &str,                                 // This borrow doesn't have to be related (x isn't even used)
    y1: i32,                                 // Not borrowed
    p: i32,                                  // Not borrowed or used
    vector: &'a Vec<(&'a str, i32, i32)>     // Vector and some of its data are borrowed here
) -> &'a str {                               // This tells rustc how long the return value should live
    ...
}

A: By specifying a lifetime:
fn is_same_space<'a>(x: &'a str, y1: i32, p: i32, vector: &'a Vec<(&'a str, i32, i32)>) -> (&'a str)

This is only one of many possible interpretations of what you might have meant for the function to do, and as such it's a very conservative choice - it uses a unified lifetime of all the referenced parameters.
Perhaps you wanted to return a string that lives as long as x or as long as vector or as long as the strings inside vector; all of those are potentially valid.

I strongly recommend that you go back and re-read The Rust Programming Language. It's free, and aimed at beginners to Rust, and it covers all the things that make Rust unique and are new to programmers. Many people have spent a lot of time on this book and it answers many beginner questions such as this one.
Specifically, you should read the chapters on:

*

*ownership

*references and borrowing

*lifetimes
There's even a second edition in the works, with chapters like:

*

*Understanding Ownership

*Generic Types, Traits, and Lifetimes

For fun, I'd rewrite your code using iterators:
fn is_same_space<'a>(y1: i32, vector: &[(&'a str, i32, i32)]) -> &'a str {
    vector.iter()
        .rev() // start from the end
        .filter(|item| item.1 == y1) // element that matches
        .map(|item| item.0) // first element of the tuple
        .next() // take the first (from the end)
        .unwrap_or("") // Use a default value
}

*

*Removed the unneeded parameters.

*Using an iterator avoids the overhead of bounds checks, and more clearly exposes your intent.

*Why is it discouraged to accept a reference to a String (&String) or Vec (&Vec) as a function argument?

*Rust does not use camelCase variable names.

*I assume that you do want to return the string from inside vector.

*Remove the redundant parens on the return type


text:
Q: Getting max value using relation on two table Using postgresql I have to build two tables named country and neighbour. Here is the query that I wrote.
CREATE TABLE country (
    cid         INTEGER     PRIMARY KEY,
    cname       VARCHAR(20) NOT NULL,
    height      INTEGER     NOT NULL,
    population  INTEGER     NOT NULL
);

CREATE TABLE neighbour (
    country     INTEGER     REFERENCES country(cid) ON DELETE RESTRICT,
    neighbor    INTEGER     REFERENCES country(cid) ON DELETE RESTRICT,
    length      INTEGER     NOT NULL,
    PRIMARY KEY(country, neighbor)
);

Now I want the question I am stuck on is for each country I have to find a neighbor country with highest elevation point. I have to report its id and name
I have to get country's id and name and it's neighbouring country's id and name with highest elevation point.
SELECT country.cid,country.cname,foo.cid,foo.cname
from country,(SELECT cid,cname
from country
    join neighbour
        on country.cid = neighbour.neighbor) as foo
group by country.cid, country.cname, foo.cid, foo.cname;

This is what I have done but I don't where to add max() clause to find the highest elevation point.

A: You can use joins and distinct on:
select distinct on (c1.cid, c1.cname)
    c1.cid,
    c1.cname,
    c2.cid neighbour_cid,
    c2.cname, neighbour_name
from country c1
inner join neighbour n on n.cid = c1.cid
inner join country c2 on c2.cid = n.neighbour
order by c1.cid, c1.cname, c2.height desc

For each country, the query follows the relationship through bridge table neighbour table and, recovers all neighbours by joining country a second time. Then, distinct on keeps the neigbour with the greatest height only.


text:
Q: Sync Model layer with presentation after animation? I have a gestureRecognizer with panning connected to a view. The panning moves the view and then when I release the finger I have an animation to move it back to where it began. This all works so far. The problem comes when I try to sync the model and presentation layers after the animation so it wouldn't go back to position before animation. When I add this new code the view first jumps up, then animates and then finally jumps back down. What am I doing wrong?
// Animation
var animation = CABasicAnimation()
animation.keyPath = "position.y"
animation.byValue = -panLength!
animation.duration = 1
self.view.layer.addAnimation(animation, forKey: "basic")    // Run animation

// Sync model to presentation layer so that view don't snap back to former position.
var currentPos = self.view.layer.position
currentPos.y -= panLength!
self.view.layer.position = currentPos // Sync model and pressentation layer.

Screenshot of simulator http://www.zamzar.com/download.php?uid=1bb237dc1b54a7d79c5f52c38715ea-ddbfdec855bd14d6&targetID=12Sr3NF0Ch8sOBNQrQinrOM_ZDHIILMpt&fileID=p19b7q9rca4is3b31a4m2qgaof4.gif

A: The solution I found use another way of setting up the animation:
            // Animation
            UIView.animateWithDuration(0.7, delay: 0.0, options: .CurveEaseOut, animations: {
                var frame = self.view.layer.frame
                frame.origin.y -= self.panLength!
                self.view.layer.frame = frame

                }, completion: { finished in
                    println("Animation done!")
            })0


text:
Q: Is it safe/wise to run Drupal alongside bespoke business web apps in production? I'm interested to know the general community feeling about the safety of running Drupal alongside bespoke, business critial ASP.NET MVC apps on a production server.
Previously my employer's Drupal based 'visitor website' was hosted as a managed service with a 3rd party. While the LoB sites were hosted in-house. That 3rd party is no longer available so I'm considering my options:

*

*Bring Drupal in-house

*Find another 3rd party

My concern is that I have little experience with Drupal administration (and no experience securing it) and that the addition of PHP to my IIS server poses a security risk.
Is there a best practice that I can follow in this situation?

A: Vortexfive is right. This is more of a sysadmin question.
Now at https://serverfault.com/questions/446366/is-it-safe-wise-to-run-drupal-alongside-bespoke-business-web-apps-in-production


text:
Q: How to call Elastic Search for current queue load? While querying ES extensively, I get
Failed to execute [org.elasticsearch.action.search.SearchRequest@59e634e2] lastShard [true]
org.elasticsearch.common.util.concurrent.EsRejectedExecutionException: rejected execution (queue capacity 1000) on org.elasticsearch.search.
action.SearchServiceTransportAction$23@75bd024b
        at org.elasticsearch.common.util.concurrent.EsAbortPolicy.rejectedExecution(EsAbortPolicy.java:62)
        at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:823)
        at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1369)
        at org.elasticsearch.common.util.concurrent.EsThreadPoolExecutor.execute(EsThreadPoolExecutor.java:79)
        at org.elasticsearch.search.action.SearchServiceTransportAction.execute(SearchServiceTransportAction.java:551)
        at org.elasticsearch.search.action.SearchServiceTransportAction.sendExecuteQuery(SearchServiceTransportAction.java:228)
        at org.elasticsearch.action.search.type.TransportSearchQueryThenFetchAction$AsyncAction.sendExecuteFirstPhase(TransportSearchQueryThenFetchAction.java:83)

on a quite regular basis.
My plan, now, is to pause the query requests until the queue load is lower than x. You can query the client for its stats
client.admin().cluster().threadPool().stats().iterator();

But since my client is not a data node (I presume that's why), I get queue=0 returned, while the server node throw the above error.
I know why this gets thrown, and I know how to update the setting, but that just postpones this error, and creates others...
How do I ask the cluster nodes what their queue load is?
PS: I'm using the Java Api
What I've tried, without requested result, blank line indicative of another try, unless otherwise specifiied
//Nodes stats
final NodesStatsResponse nodesStatsResponse = client.admin().cluster().prepareNodesStats().execute().actionGet();
final NodeStats nodeStats = nodesStatsResponse.getNodes()[0];
final String nodeId = nodeStats.getNode().getId(); // need this later on

// same as before, but with explicit NodesStatsRequest (with id)
final NodesStatsResponse response = client.admin().cluster().nodesStats(new NodesStatsRequest(nodeId)).actionGet();
final NodeStats[] nodeStats2 = response.getNodes();
for (NodeStats nodeStats3 : nodeStats2) {
    Stats stats = nodeStats3.getThreadPool().iterator().next();
}

// Cluster?
final ClusterStatsRequest clusterStatsRequest = new ClusterStatsRequestBuilder(client.admin().cluster()).request();
final ClusterStatsResponse clusterStatsResponse = client.admin().cluster().clusterStats(clusterStatsRequest).actionGet();
final ClusterStatsNodes clusterStatsNodes = clusterStatsResponse.getNodesStats();

// Nodes info?
final NodesInfoResponse infoResponse = client.admin().cluster().nodesInfo(new NodesInfoRequest(nodeId)).actionGet();// here
final NodeInfo[] nodeInfos = infoResponse.getNodes();
for (final NodeInfo nodeInfo : nodeInfos) {
    final ThreadPoolInfo info = nodeInfo.getThreadPool();
    final Iterator<Info> infoIterator = info.iterator();
    while (infoIterator.hasNext()) {
        final Info realInfo = infoIterator.next();
        SizeValue sizeValue = realInfo.getQueueSize();
        // is no == null, then (¿happens?, was expecting a nullpointer, but Thread disappeared)
        if (sizeValue == null)
            continue;
        // normal queue size, no load (oddly found 1000 (expected), and one of 200 in one node?)
        final long queueSize = sizeValue.getSingles();
    }
}

The issue is that some of the processes need to be called instantly (e.g. user requests), whereas others may wait if the database is too busy (background processes). Preferably, I'd assign a certain amount of the queue to processes that stand on immediate requests, and the other part on background processes (but I haven't seen this option).
Update
It appears, which I didn't expect, that you can get a query overload with a single bulk query, when the total amount of separate searches exceed 1000 (when x shards, or x indices, divide by 1000/x for the number of searches). So bulking,,, not an option, unless you can make a single query. So when you target on 700 search results at once (taking in account the above statement), you'll need to know whether more than 300 items reside in the queue, for then it'll throw stuff.
To sum up:
Assume the load, per call, is the maximum bulkrequest so I cannot combine requests. How, then, can I start pausing requests before elasticsearch starts throwing the above stated exception. So I can pause a part of my application, but not the other? If I know the queue is filled, say, half way, the background process must sleep some time. How do I know the (approximated) queue load?

A: The way you are trying to look at the queue usage is wrong, as you are not looking at the correct statistics.
Have a look at this piece of code:
    final NodesStatsResponse response = client.admin().cluster().prepareNodesStats().setThreadPool(true).execute().actionGet();
    final NodeStats[] nodeStats2 = response.getNodes();

    for (NodeStats nodeStats3 : nodeStats2) {
        ThreadPoolStats stats = nodeStats3.getThreadPool();

        if (stats != null)
            for (ThreadPoolStats.Stats threadPoolStat : stats) {
                System.out.println("node `" + nodeStats3.getNode().getName() + "`" + " has pool `" + threadPoolStat.getName() + "` with current queue size " + threadPoolStat.getQueue());
            }
    }

First of all you need setThreadPool(true) to be able to get back the thread pool statistics otherwise it will be null.
Secondly, you need ThreadPoolStats not ThreadPoolInfo which is for thread pool settings.
So, it's your second attempt, but incomplete. The 1000 you were seeing was the setting itself (the max queue size), not the actual load.

A: I'm hoping this is not the answer, source https://www.elastic.co/guide/en/elasticsearch/guide/current/_monitoring_individual_nodes.html#_threadpool_section:

Bulk Rejections
If you are going to encounter queue rejections, it will most likely be
  caused by bulk indexing requests. It is easy to send many bulk
  requests to Elasticsearch by using concurrent import processes. More
  is better, right?
In reality, each cluster has a certain limit at which it can not keep
  up with ingestion. Once this threshold is crossed, the queue will
  quickly fill up, and new bulks will be rejected.
This is a good thing. Queue rejections are a useful form of back
  pressure. They let you know that your cluster is at maximum capacity,
  which is much better than sticking data into an in-memory queue.
  Increasing the queue size doesn't increase performance; it just hides
  the problem. If your cluster can process only 10,000 docs per second,
  it doesn't matter whether the queue is 100 or 10,000,000—your cluster
  can still process only 10,000 docs per second.
The queue simply hides the performance problem and carries a real risk
  of data-loss. Anything sitting in a queue is by definition not
  processed yet. If the node goes down, all those requests are lost
  forever. Furthermore, the queue eats up a lot of memory, which is not
  ideal.
It is much better to handle queuing in your application by gracefully
  handling the back pressure from a full queue. When you receive bulk
  rejections, you should take these steps:
Pause the import thread for 3–5 seconds. Extract the rejected actions
  from the bulk response, since it is probable that many of the actions
  were successful. The bulk response will tell you which succeeded and
  which were rejected. Send a new bulk request with just the rejected
  actions. Repeat from step 1 if rejections are encountered again. Using
  this procedure, your code naturally adapts to the load of your cluster
  and naturally backs off.
Rejections are not errors: they just mean you should try again later.

Particularly this When you receive bulk rejections, you should take these steps I don't like. We should be able to handle oncoming problems on forehand.


text:
Q: Error running Xamarin.iOS on an iPad. Xamarin Forms does anyone know why this is happening? The solution is new and does not support running it from a physical iPad. I have a valid developer credential
A123 A125
A124


text:
Q: Парсер текста между тегами Необходимо на C# сделать парсер погоды, температуры воздуха. Нашел HtmlAgilityPack, но никак не могу въехать как пользоваться. Мне нужна инфа между тегами
31

Помогите въехать или подскажите где посмотреть примеры, в google их много, но все какие то закрученные.
В возможном дубликате речь идет о парсинге атрибутов.

A: Можно использовать AngleSharp.
Ваш пример будет примерно такого вида:
var parser = new HtmlParser();
    var document = parser.Parse(@"

    Hello, world

1

            Head1
            Head2

            31
            content

            32
            content

");

var cells = document.QuerySelectorAll("table#menutable td.bla.ble");
foreach (var cell in cells)
{
    Console.WriteLine(cell.Text());
}

Наиболее просто подключить AngleSharp при помощи механизма NuGet пакетов, встроенного в студию.
В окне Solution Explorer щелкните правой кнопкой мыши на нужном проекте и выберите пункт Manage NuGet Packages. Затем выполните поиск пакета AngleSharp (требуется подключение к интернету) и установите.
Механизм NuGet очень удобен, я рекомендую потратить некоторое время на его изучение.

A: Вот пример выборки значений из элементов 	 структуру HTML документа для парсинга взял здесь.
var doc = new HtmlDocument();

doc.Load(@"C:\myHtml.html");
var nodes = doc.DocumentNode
               .Descendants("table")
               .SelectMany(y => y.SelectNodes("//tr/td"))
               .Select(s => s.InnerText)
               .ToList();


text:
Q: UnicodeDecodeError: ('unknown', u'\xe0', 0, 1, '') temp = "à la Carte"
print type(temp)
utemp = unicode(temp)

The code above results in an error.
My goal is to process the temp string and use a find to check if it contains specific string in it but cannot process due to the error:
UnicodeDecodeError: ('unknown', u'\xe0', 0, 1, '')

A: You need to specify the encoding: otherwise unicode() doesn't know what \xe0 means, because that is encoding-specific.
>>> temp = "à la Carte"
>>> utemp = unicode(temp,encoding="Windows-1252")
>>> utemp
u'\xe0 la Carte'
>>> print utemp
à la Carte

A: In python 2, the ordinary string literal cannot hold such unicode characters, so even if the parser manages to get through it, it is still an error. That's why there exists a unicode literal type. So to make it work, first you have to declare the encoding of the python file, and second, use a unicode literal. Like this:
# -*- coding: utf-8 -*-
temp = u"à la Carte"
print type(temp)
utemp = unicode(temp)


text:
Q: Programmatically creating multiple instances of asp web app with different domain names and in different Virtual Machines I created a new ASP.NET MVC web app which is responsible for school management. Now I want to create new web app that helps to deploy this app with new sub-domain and new database for new registred client.
What is the best approach to do this work ?
I have small information about this type of apps, according to this information I think it is some thing related to services provided by web hosting companies such as Microsoft Azure which provides creation and configuration of Virtual Machines programmatically with the ability to deploy app to this new created VMs also programmatically ! am I write ?!
If you still didn't understand my problem kindly try to visit shopify (https://www.shopify.com/) which provides store creation for non professionals with the same way that I want in my project.
Thank you

A: The code below creates a new virtual directory on the IIS host.
    /// <summary>
    /// Create a new virtual directory on the iis host.
    /// </summary>
    /// <param name="iisHostPath">The iis host path.</param>
    /// <param name="physicalPath">The physical path to the directory.</param>
    /// <param name="virtualDirectoryName">The virtual directory name.</param>
    /// <param name="defaultDocument">The defualt document to set.</param>
    /// <returns>True if the virtual directory was created else false.</returns>
    /// <example>
    /// iisHostPath : [servername]/[service]/[websiteID]/[Root] : localhost/W3SVC/1/Root
    /// defaultDocument : [document] : default.aspx
    /// </example>
    /// <remarks>
    /// <para>iisHostPath : [servername]/[service]/[websiteID]/[Root] : localhost/W3SVC/1/Root</para>
    /// <para>defaultDocument : [document] : default.aspx</para>
    /// </remarks>
    public virtual bool CreateVirtualDirectory(string iisHostPath, string physicalPath,
        string virtualDirectoryName, string defaultDocument)
    {
        // Validate the inputs.
        if (String.IsNullOrEmpty(iisHostPath))
            throw new System.ArgumentNullException("IIS path can not be null.",
                new System.Exception("A valid IIS path should be specified."));

        // Validate the inputs.
        if (String.IsNullOrEmpty(physicalPath))
            throw new System.ArgumentNullException("Physical can not be null.",
                new System.Exception("A valid physical path should be specified."));

        // Validate the inputs.
        if (String.IsNullOrEmpty(virtualDirectoryName))
            throw new System.ArgumentNullException("Virtual directory name can not be null.",
                new System.Exception("A valid virtual directory name should be specified."));

        // Validate the inputs.
        if (String.IsNullOrEmpty(defaultDocument))
            throw new System.ArgumentNullException("Default document can not be null.",
                new System.Exception("A valid default document should be specified."));

        // Create a new directory entry
        // instance to the iis machine.
        DirectoryEntry localMachine = new DirectoryEntry(
            "IIS://" + iisHostPath);

        // Add the iis virtual directory
        // to the iis collection.
        DirectoryEntry virtName = localMachine.Children.Add(virtualDirectoryName, "IIsWebVirtualDir");

        // Commit the changes for the account.
        virtName.CommitChanges();

        // Assign default properties.
        virtName.Properties["Path"][0] = physicalPath;
        virtName.Properties["DefaultDoc"][0] = defaultDocument;
        virtName.Properties["AccessScript"][0] = true;

        // These properties are necessary for an application to be created.
        virtName.Properties["AppFriendlyName"][0] = virtualDirectoryName;
        virtName.Properties["AppIsolated"][0] = "1";
        virtName.Properties["AppRoot"][0] = "/LM/" + iisHostPath;

        // Commit the changes for the account.
        virtName.CommitChanges();

        // Close the connections.
        virtName.Close();
        localMachine.Close();

        // Return success.
        return true;
    }

The code below creates a new web site on the II host.
    /// <summary>
    /// Create a new web site on the iis host.
    /// </summary>
    /// <param name="iisHostPath">The iis host path.</param>
    /// <param name="websiteID">The unique web site id.</param>
    /// <param name="websiteName">The name of the web site.</param>
    /// <param name="physicalPath">The physical path to the root directory.</param>
    /// <returns>True if the web site was created else false.</returns>
    /// <example>
    /// iisHostPath : [servername]/[service] : localhost/W3SVC
    /// websiteID : [number] : 454354
    /// </example>
    /// <remarks>
    /// <para>iisHostPath : [servername]/[service] : localhost/W3SVC</para>
    /// <para>websiteID : [number] : 454354</para>
    /// </remarks>
    public virtual bool CreateWebSite(string iisHostPath,
        string websiteID, string websiteName, string physicalPath)
    {
        // Validate the inputs.
        if (String.IsNullOrEmpty(iisHostPath))
            throw new System.ArgumentNullException("IIS path can not be null.",
                new System.Exception("A valid IIS path should be specified."));

        // Validate the inputs.
        if (String.IsNullOrEmpty(websiteID))
            throw new System.ArgumentNullException("Web site id can not be null.",
                new System.Exception("A valid web site id should be specified."));

        // Validate the inputs.
        if (String.IsNullOrEmpty(websiteName))
            throw new System.ArgumentNullException("Web site name can not be null.",
                new System.Exception("A valid web site name should be specified."));

        // Validate the inputs.
        if (String.IsNullOrEmpty(physicalPath))
            throw new System.ArgumentNullException("Physical can not be null.",
                new System.Exception("A valid physical path should be specified."));

        // Create a new directory entry
        // instance to the iis machine.
        DirectoryEntry localMachine = new DirectoryEntry(
            "IIS://" + iisHostPath);

        // Add the iis web site
        // to the iis collection.
        DirectoryEntry siteName = localMachine.Children.Add(websiteID, "IIsWebServer");

        // Assign the web site properties.
        siteName.Properties["ServerComment"][0] = websiteName;
        siteName.CommitChanges();

        // Commit the changes for the account.
        siteName.CommitChanges();

        // Add the iis web site
        // to the iis collection.
        DirectoryEntry rootName = siteName.Children.Add("Root", "IIsWebVirtualDir");

        // Assign the web site properties.
        rootName.Properties["Path"][0] = physicalPath;
        rootName.Properties["AccessScript"][0] = true;

        // Commit the changes for the account.
        rootName.CommitChanges();

        // Close the connections.
        rootName.Close();
        siteName.Close();
        localMachine.Close();

        // Return success.
        return true;
    }

The code below sets the port number on a web site on the IIS host.
    /// <summary>
    /// Set a port number to a web site on the iis host.
    /// </summary>
    /// <param name="iisHostPath">The iis host path.</param>
    /// <param name="portNumber">The port number.</param>
    /// <returns>True if the port number was assigned else false.</returns>
    /// <example>
    /// iisHostPath : [servername]/[service]/[websiteID] : localhost/W3SVC/1
    /// </example>
    /// <remarks>
    /// <para>iisHostPath : [servername]/[service]/[websiteID] : localhost/W3SVC/1</para>
    /// </remarks>
    public virtual bool SetWebSitePortNumber(string iisHostPath, int portNumber)
    {
        // Validate the inputs.
        if (String.IsNullOrEmpty(iisHostPath))
            throw new System.ArgumentNullException("IIS path can not be null.",
                new System.Exception("A valid IIS path should be specified."));

        // Validate the inputs.
        if (portNumber < 1)
            throw new System.ArgumentNullException("Port number not valid.",
                new System.Exception("The port number must be greater than zero."));

        // Create a new directory entry
        // instance to the iis machine.
        DirectoryEntry localMachine = new DirectoryEntry(
            "IIS://" + iisHostPath);

        // Set the web site port number.
        localMachine.Properties["ServerBindings"][0] = ":" + portNumber + ":";

        // Commit the changes for the account.
        localMachine.CommitChanges();

        // Close the connections.
        localMachine.Close();

        // Return success.
        return true;
    }

Note that localMachine.Properties["ServerBindings"][0] = refers to Bindings in the Advanced Settings of your web site in IIS.


text:
Q: How can I watch for changes to an expression in the Perl debugger? With the Perl debugger, I know I can set breakpoints at certain lines of code with the b command. Can I get the debugger to stop as soon as the contents of a variable has changed?

A: You can create watch points using the w command in the Perl debugger.
Crash course on the w debugger command:
Create a watch-expression by typing w and then an expression that will monitored for changes:
DB<1> w $variablename

Enter c to continue until the watched expression changes. Once you do, you will get output similar to this:
DB<2> c
Watchpoint 0:   $variablename changed:
    old value:  ''
    new value:  'hi'
main::(ex.pl:6):    $variablename = "";

Note that the debugger stops at the statement after the changed has happened, so the line displayed might not be relevant at all.
Also note that the expression is stringified. So for example, changing a variable to undef will give you this output:
  DB<2> c
Watchpoint 0:   $variablename changed:
    old value:  'hi'
    new value:  ''
main::(ex.pl:7):    $variablename = undef;

If the variable is subsequently changed to an empty string, the debugger will not stop, as a stringified empty string and a stringified undef is considered equal.
If the watch expression is a list, the debugger will compare the stringified elements of the list:
  DB<1> w $variablename, "second"

  DB<2> c
Watchpoint 0:   $variablename, "second" changed:
    old value:  'one', 'second'
    new value:  'two', 'second'
main::(hi.pl:6):    $variablename = "three";

You can use array variables or hash variables as watch-expressions, and they will be treated as any other list.
To delete a watch-expression, use the W command, and to view a list of active watch-expressions, use the L command.
Tip: Use temporary global variables
Since the watch-expression is re-evaluated with every statement, you can't expect a watch-expression that uses a lexical variable to work out of scope. A quick tip is to create a global reference to the lexical, and track that instead:
DB<1> $main::my_debug_variable = $hashref_lexical_variable

DB<2> w $main::my_debug_variable->{key_im_watching}

Tip: Use Data::Dumper
Use Data::Dumper to watch the contents of a non-scalar:
DB<1> w Data::Dumper->Dump([$hashref])

This is preferable to a simple w $hashref, because it will stop when the values of the hash change, rather than simply the address the reference is pointing (since a hashref stringifies to something like HASH(0x2a07a90)).

A: Additionally, you can use "ddd your_script.pl&" in the Linux, and watch variables like C/C++ debugger do in GUI.


text:
Q: External SalesForce Forms Is it possible to create external SalesForce Forms that can populate fields in the same way as inside salesforce?
We offer online teaching and the idea is that teachers, after every lesson, can fill in a timesheet and select the student and their own name from a master detail relationship with one of the other object via a lookup field or drop down list -- similar to how you can do it in Salesforce.

I've tried to do it using form Assembly, but the fields do not appear in the resulting forms.

So is it possible to duplicate the experience from inside salesforce, but on a form that teachers can use to submit data after every lesson?

A: This seems like a good use case for a Community, which in Salesforce is essentially a portal in which your partners can interact with your Salesforce instance and data in a controller manner, but not as full users. To do things like view accounts, cases, leads or submit information. This is the overview on Salesforce communities http://www.salesforce.com/communities/overview/, it's a big topic of course and implementing it is definitely not a quick thing, but given what your business model sounds like, it may be a good fit for you.
On the other hand, you could also implement this similar to web to lead or case, using the rest or soap api, and creating a web form, and then submitting the information to salesforce via the api. That would be more of a one off, solve this use case solution though.

A: To directly answer your question yes it can be done.

*

*Salesforce Sites, although you will have to build your own access control if needed.

*Your own web server that utilizes the preexisting Salesforce API
If you want an internal SF way of doing it the other answer about communities would be a good fit if you can swing the licenses but you asked for external so.....


text:
Q: I need to plot frequency distribution (on the Y-axis) of a one column data file with gnuplot Using Gnuplot, we can plot the frequency of a one column data file with the command

plot 'name of the file' smooth frequency w l

My problem here is that, the I need the frequency to be on the Y-axis instead of the X-axis. Is there a trick to actually do that. I have already tried

plot 'name of the file' using 2:1 smooth frequency w l

But it doesn't work.
If there is also a way to do that in mathematica, I will be happy to Know.
ThanKs You!

A: BarChart[{2, 5, 6}, ChartStyle -> "Rainbow", BarOrigin -> Left,
 ChartLegends -> Map[ToString, Range[5]]]

Edit
data = {{0.118082595966, 0.0139434994702}, {0.232690587709,
    0.0541449096085}, {0.323755025675,
    0.10481731665}, {0.635064375908, 0.403306761548}, {1.03995593543,
    1.08150834764}, {1.24757861309, 1.55645239584}, {1.24985914502,
    1.5621478824}, {1.28010876631, 1.63867845358}, {1.39387084749,
    1.94287593949}, {1.61826799763, 2.61879131215}};
g = ListLinePlot[data, ImageSize -> 300];
g2 = Show[g /. x_Line :> Reverse[x, 3], ImageSize -> 300,
   PlotRange -> Automatic];
Row[{g, g2}, Spacer[5]]


text:
Q: JPA parent/child relationship Using JPA (Hibernate) I'm trying to implement the below relationship and was wondering if others have any suggestions about the best approach:
@Entity(name="SOMETHING")
public class Something {
    List<MetaDatum> metaData;
}

@Entity(name="SOMETHING_COMPLETELY_DIFFERENT")
public class SomethingCompletelyDifferent {
    List<MetaDatum> metaData;
}

@Entity(name="META")
public class MetaDatum {

}

Basically it's n completely unrelated objects which each have a collection of common child objects; simple to implement in the object model, slightly more troublesome in the database!
I'm sure this must be a common occurrence but I've had trouble finding any example implementations since I don't really know the right search terms.
Thanks for your time!

A: Looks like a case for the @OneToMany annotation on the metaData fields in your Something and SomethingCompletelyDifferent (SCD)entities. Where you go from there depends.
Since Something and SCD do not have a common ancestor, you cannot simply make the relation bidirectional and use a join column.
There are several solutions, so you will have to decide depending on your actual use case.

*

*simply stick with the unidirectional relation, if you do not need to traverse from MetaDatum to it's parent entities. The relation will be mapped with join tables by hibernate.

*make separate MetaDatum1 and MetaDatum2 entities that can have bidirectional relations to their respective parent objects.

*create a common ancestor for the two parent entities, containing a bidirectional relation to MetaDatum

*create two entities, each encapsulating a List<MetaDatum>, tailored for a bidirectional relation to your Something and SCD entities


text:
Q: making an auto layout of UIimageView and textview inside scrollview for iOS 10.2 in xcode8 I am making a note taking app in xcode8 for iOS 10.2. The note is consist of a textfield, textview and imageview. I am adding textview and imageview in separate scrollviews (to provide the facility of zooming and adjusting image). Then I have added both scroll views in a stackview to ensure that imageview and textview stands side by side in a landscape mode. To do that, I have added variation to axis property of stackview( width=any, height= compact and Gamut=any, and set that to the horizontal, as shown in right corner of screenshot to see view hierarchy without any constraints).
I have tried many constraints but, every time it fails to adopt. Let's take an example, I am adjusting size of the scrollviews on the size of content(by setting top,bottom,leading and trailing constraint), the stack view is adjusted to the main view. Now, the only thing that needs to be adjusted is text view and imageview with respect of stack view. But, here is the tricky part If I include a fixed trailing constraint of text view to the stack view; it will work in portrait mode.As soon I turn into landscape mode that constraint will not work(the trailing constraint which have 0 distance from stackview) because the edge will be side to the imageview not to the stackview(because I am putting image and text side by side as explained above) which will make textview larger than required, same goes for imageview's leading constraint to the stack view and vertical distance constraint betweem image view and textview.I think the root of the problem is I have made a variation to the axis of a stack view (in order to get text and image side by side in landscape mode) but, that was necessary part.Can anyone have solution for this? Do you think there can be other problem? Should I choose Intrinsic Size of scrollviews to placeholder option or let it be system default?
Thank you.

A: So I hope I understand the question and I will try to walk you through what I understand you hope to accomplish.  I preface this by saying I just started using UIStackView because of backwards compatibility.
Note.  To get the magic of ScrollView with AutoLayout I almost always embed them in another UIView.  There are reasons to not but in this case you will see how valuable this is to AutoLayout.
Step 1) Drag your UIStackView and add Top,Bottom,Leading, and Trailing.  Now add 2 UIViews and set the UIStackView to Fill Equally.  It will now look like the image(Background colors to check your work).
Step 2) Now add a UIScrollView to each of these UIViews.  Add Leading,Trailing,Top,and Bottom on each of these.
Step 3) Add a UITextView and UIImageView to the ScrollViews respectively.  Now Autolayout is mad at us :( but we will fix that.
Step 4) Drag from the UIImageView to the View that is holding the UIScrollView(First Set of Views we added).  See image

-Choose the option to add Equal Widths. See Image

Repeat the same step but add Equal Heights.  Now add Top, Bottom, Leading, and Trailing to the ScrollView.
Step 5) Repeat exact Step 4 with UITextView
Your final view hierarchy should look like this.

Now you can rotate your UIStackView and do what you want I think.

And Horizontal

Side by Side Preview

I did add a <= 0.1 equal heights multiplier on the textfield at the top but I don't know if that was necessary.
Enjoy.


text:
Q: Python: replace a string in a CSV file I am a beginner and I have an issue with a short code. I want to replace a string from a csv to with another string, and put out a new
csv with an new name. The strings are separated with commas.
My code is a catastrophe:
import csv

f = open('C:\\User\\Desktop\\Replace_Test\\Testreplace.csv')
csv_f = csv.reader(f)

g = open('C:\\Users\\Desktop\\Replace_Test\\Testreplace.csv')
csv_g = csv.writer(g)

findlist = ['The String, that should replaced']
replacelist = ['The string that should replace the old striong']

#the function  ?:
def findReplace(find,replace):
s = f.read()
for item, replacement in zip(findlist,replacelist):
s = s.replace(item,replacement)
g.write(s)

for row in csv_f:
print(row)

f.close()
g.close()

A: You can do this with the regex package re. Also, if you use with you don't have to remember to close your files, which helps me.
EDIT: Keep in mind that this matches the exact string, meaning it's also case-sensitive. If you don't want that then you probably need to use an actual regex to find the strings that need replacing. You would do this by replacing find_str in the re.sub() call with r'your_regex_here'.
import re

# open your csv and read as a text string
with open(my_csv_path, 'r') as f:
    my_csv_text = f.read()

find_str = 'The String, that should replaced'
replace_str = 'The string that should replace the old striong'

# substitute
new_csv_str = re.sub(find_str, replace_str, my_csv_text)

# open new file and save
new_csv_path = './my_new_csv.csv' # or whatever path and name you want
with open(new_csv_path, 'w') as f:
    f.write(new_csv_str)


text:
Q: Teamcity not autobuild for develop branch I use for a C # project, Git since TFS.
When I make my changes, Teamcity detects the changes. But for only the development bran the build does not fire automatically. To know that the master works to him very well.
Do you have an idea ?
Below you will find the settings for the branch develop
1) My Teamcity dashboard

2) My config trigger

3) My config VCS

4) My branchs on tfs

A: There is a similar thread for your reference here: Select Git branch for TeamCity Build,  just try the solution mentioned in the thread:

You can try to parameterize the "Ref name" of the git VCS setup. What
  this means is you declare a variable of the form %variable.name% in
  your build, create a build parameter under the "configuration
  parameter:" category.
For each build target set this value and you should be able to pick
  the specific branch that you want to run the target for.

*

*Set up a VCS root. Key here is the %BranchName% parameter.

*Create a Build template and use the VCS root that was just created.

*Create a new build, based on the template.


text:
Q: Manual Focus using android camera2 API I want to develop an Android Camera App for myself (can share it if there are interested people) that has a manual focus while video recording.
I've added a SeekBar to the google sample Camera2 app but I can't find the way to implement the manual focus.
I found Manual focus in camera2, android but it doesn't work on my LG G4.
The stock camera app is almost perfect since it doesn't allow the manual focus in video mode.
Does anyone of you have an idea ?
EDIT: here's the code of the SeekBar listener:
@Override
public void onStopTrackingTouch(SeekBar seekBar) {}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {
    mPreviewBuilder.set(CaptureRequest.CONTROL_AF_MODE, CameraMetadata.CONTROL_AF_MODE_OFF);
}

@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
    float minimumLens = characteristics.get(CameraCharacteristics.LENS_INFO_MINIMUM_FOCUS_DISTANCE);
    float num = (((float)progress) * minimumLens / 100);
    mPreviewBuilder.set(CaptureRequest.LENS_FOCUS_DISTANCE, num);
}

A: Eddy Talvala described everything correctly in his answer, but if you still feel complicated, here is a code snippet that sets focus to infinity (which has value 0f):
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
int[] capabilities = characteristics
    .get(CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES);

boolean isManualFocusSupported = IntStream.of(capabilities)
    .anyMatch(x -> x == CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_MANUAL_SENSOR);

if (isManualFocusSupported) {
    previewBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_OFF);
    previewBuilder.set(CaptureRequest.LENS_FOCUS_DISTANCE, 0f);
}

A: You need to check if the device you're running on actually supports manual controls in camera2.
The key is whether the available capabilities of the camera device lists MANUAL_SENSOR. If so, then you can control the lens by setting the autofocus mode to OFF, and then setting the lens focus distance to your desired value.  If MANUAL_SENSOR is not listed, then the device very likely doesn't support manual focus control (Some manufacturers use private interfaces for their default camera app to implement manual focus control, unfortunately).
These should all go into the repeating request you're using to control preview.


text:
Q: Failed to transform class with name org.apache.hadoop.fs.FileSystem$Cache. Reason: org.apache.hadoop.fs.FileSystem$Cache$Key class is frozen Getting java.lang.RuntimeException: org.apache.hadoop.fs.FileSystem$Cache$Key class is frozen.
Java               : 11
JVM vendor name    : Oracle Corporation
JVM vendor version : 11.0.7+8-LTS
JVM name           : Java HotSpot(TM) 64-Bit Server VM
JVM version        : 11.0.7+8-LTS
JVM info           : mixed mode
OS name            : Windows 10
OS version         : 10.0

Using Hadoop client version 3.1.0 and Power mockito version 1.7.4
Please help me out.


text:
Q: How to retrieve DATETIME together with milliseconds I'm doing:
CREATE TABLE foo (d DATETIME);
INSERT INTO foo VALUES('2013-10-09 10:58:43.159');
SELECT d FROM foo;

and getting
2013-10-09 10:58:43

How can I get DATETIME back together with milliseconds?

A: MySQL 5.6.4 and above supports that. Use
CREATE TABLE foo (d DATETIME(6));


text:
Q: How to conifgure ViteJS in Laravel to load any static assets in /public My M.O. for using images in CSS is this:

*

*All images are somewhere in /public (typically /public/img) in order to be easily loadable by any style, script or view with an absolute path /

*In my SCSS files I refer to the images with an absolute path starting with / :

body {
    background: url('/img/body-bg.png');
}

I am migrating from Mix to ViteJS and all of my old code is written like this. It makes total sense and the images can be just as well be loaded by anything else, for example my blade files:

Now ViteJS somehow does not like it and according to other answers wants me to refer to images like this in CSS:
body {
    background: url('/public/img/body-bg.png');
}

or like this in Blade files:

According to ViteJS documentation I should be able to say what / means with either the base or the publicDir settings but they don't seem to have any effect in vite.config.js file.
Is there a way to make ViteJS work the way Mix did? I don't care about image versioning and frankly don't want the bundling process to copy all my images from somewhere else into the /public/build directory. I want to keep them where they are and just load them normally with /img/image.png.

A: You don't reference the public folder, when your app is live that public folder should be the root of your web directory.
You should read through the documentation: https://laravel.com/docs/9.x/vite
The default setting is to use the same path as what is used in the vite.config.js. Then use the vite blade directive e.g.
@vite(['resources/js/users-form.js'])

The blade directive will load the proper path for you to the bundled version in the public folder.


text:
Q: Array entries, and incrementing a counter according to rules in java I'm trying to write a method in java that will increment a counter for each time one of the following rules is satisfied when iterating through an array.
1) Two adjacent values in an array equal each other and the first value in each pair starts at an even numbered index value (0,2,4...etc)
2) For all adjacent pairs of entries, the values of one pair equal the values of the next pair and length(adjacent pairs of entries) mod 2 = 0
So 0,0,0,0,1,1 satisfies this rule but 0,0,0,1 does not (there are only 3 0's which violates the last condition)
So far I have this, which implements the first rule:
public class ArrayEvaluate {

public static double evaluate(int[] array)
{
    double  ruleSat = 0;
      for(int index = 0; index < array.length; index++){

            if((array[index] == array[index + 1]) &&(index%2==0)){
                ruleSat++;
            }
}
return ruleSat;
}
 public static void main(final String[] args){

int[] array = new int[6];
array[0]= 1;
array[1]=1;
array[2]=3;
array[3]=3;
array[4]=4;
array[5]=4;

evaluate(array);
 }
}

However, this does not work completely, and I'm not sure how to go about the second rule.
Thanks

A: public static double evaluate(int[] array) {
    double ruleSat = 0;
    for (int index = 0; index < array.length; index++) {
        if (index != array.length-1) {
            if ((array[index] == array[index + 1]) && (index % 2 == 0)) {
                ruleSat++;
            }
        }
    }
    return ruleSat;
}

This will prevent the index out of bounds error your receiving
Update for second rule:
This separates the logic for rule 1 and rule 2 so if you ever need to change a rule individually they are independent.
public class ArrayEvaluate {
public static double evaluate(int[] array) {
    double something = 0;
    int rule1Occurences = testRule1(array);
    int rule2Occurences = testRule2(array);
    System.out.println(rule1Occurences);
    System.out.println(rule2Occurences);
    return something;//not sure how rules relate
}
//This counts when array element == next array element
public static int testRule1(int[] array){
    int ruleSat = 0;
    for (int index = 0; index < array.length; index++) {
        if (index != array.length - 1) {
            if ((array[index] == array[index + 1]) && (index % 2 == 0)) {
                ruleSat++;
            }
        }
    }
    return ruleSat;
}
//This blocks the pairs off in sets of two disregarding any odd parings
public static int testRule2(int[] array)
{
    int rule2Sat = 0;
    for (int index = 0; index < array.length; index++) {
        if(index <= array.length - 4){
            if (array[index] + array[index+1] == array[index+2] + array[index+3]) {
                rule2Sat++;
            }
        }
    }
    return rule2Sat;
}

public static void main(final String[] args) {

    int[] dataSet = new int[6];
    dataSet[0] = 0;
    dataSet[1] = 0;
    dataSet[2] = 0;
    dataSet[3] = 0;
    dataSet[4] = 4;
    dataSet[5] = 4;

    System.out.println(evaluate(dataSet));
}

}

A: Since you say its not homework, this is what I would do
public class ArrayEvaluate {
    public static int evaluate(int... array) {
        int counter = 0;
        for(int i = 0; i < array.length-1; i += 2)
            if(array[i] == array[i + 1]) { // rule one
               counter++;
               if (i < array.length-3 &&
                     array[i] == array[i + 2] &&
                     array[i + 2] == array[i + 3]) // rule two
                  counter++;
            }
        return counter;
    }

  public static void main(String... args){
    int test1 = evaluate(1,2,3,3,4,4);
    assert test1 == 2;
    int test2 = evaluate(0,0,0,0,1,1);
    assert test1 == 4;
    int test2 = evaluate(0,0,0,1,1,1);
    assert test1 == 2;
  }
}


text:
Q: Ползунок ui и jcarousel Есть карусель jcarousel, которая прокручивается при помощи кнопок вперед-назад и ползунка ui.

Когда нажимаешь на кнопки и медленно перемещаешь ползунок, то всё работает нормально. Проблема возникает, когда ползунок перемещается быстро. Предположим, он переместился на 5 позиций, а карусель прокручивается только 3 раза. Код:

 $('.ui_slider').slider({
          value: 1,
          min: min,
          max: max,
          slide: function(event, ui) {
          if (last_val > ui['value']) {
    var step = last_val - ui['value']; //считаем, на сколько позиций сдвинули ползунок
    for(var i=0;i<step;i++) $(".jcarousel-prev").click(); //лстаем назад

            } else {
            var step = ui['value']-last_val;
            for(var i=0;i<step;i++)  $('.jcarousel-next').click(); //листаем вперед

Может кто-нибудь сталкивался с такой проблемой?
A: привяжите позицию ползунка к номеру картинки.
$('.jcarousel').jcarousel('scroll', N);

чтобы было плавно сделайте интерполяцию позиций ползунка в количество картинок (через пропорцию)


text:
Q: Sync to Outlook 2010 with redemption in vb.net I am developing an application where I want to sync the outlook calendar, mail, etc.
The piece of code which is there with me is working fine for outlook 2003, 2007.
but I don't know what's the problem it is causing for outlook 2010.
I use the following:
redemption dll 5.4 version-32 bit
office object core 14 dll-32 bit
office -32 bit version
visual studio 2008
I am getting this error:

Cannot create ActiveX component.

On the following line:
session = CreateObject("Redemption.RDOSession")

Where session is:
Dim session As Redemption.RDOSession

After which the following error is displayed:

Either there is no default mail client or the current mail client cannot fulfill the messaging request

I have tried various things but it's same. I also reinstalled, repaired outlook, repaired registry.
Any ideas?

A: this worked for me:
first, I will say I used the Customize.exe that comes with redemption to create a dll called ffloader.dll
Next, I registered that dll as follows (32 bit)
regsvr32 ffloader.dll
Finally in the vb.net code I created the session as follows:
Dim Session As Redemption.RDOSession = CreateObject("ffloader.ffRDOSession")
Hope that helps!


text:
Q: How to get app name by package name in android? I am writing a command line tool to get app name by package name, and trying the following ways.

*

*PackageManager in android API provide the function, but mine tool is not an APK, thus there's no Context.

*command AAPT can parse app name from apk, adb shell aapt dump badging /data/app/com.google.android.apps.inbox-1/base.apk, but my device has no aapt, I downloaded one from here, it complains "error: only position independent executables (PIE) are supported".
any helps?

A: To get App Name try this. It would provide the application name which is defined in  tag of app's manifest.
PackageManager packageManager = getApplicationContext().getPackageManager();
    ApplicationInfo applicationInfo ;
    try {
        applicationInfo = packageManager.getApplicationInfo( this.getPackageName(), 0);
    } catch (final NameNotFoundException e) {
        applicationInfo = null;
    }
    String applicationName = (String) (applicationInfo != null ? packageManager.getApplicationLabel(applicationInfo ) : "(unknown)");

A: You can use AAPT2 command in linux to get the package name of an APK.
./aapt2 dump packagename <path_to_apk>

But you need to download newer versions of AAPT2 from here:
Download AAPT from Google Maven
You can try this executing this command in a shell script, so that you will be able to use the package name.
PS: I used AAPT2 version 3.3.0-5013011 for testing the above command.


text:
Q: Django - suing font awersome in unicode form I want to use font awersome in my project in the way, that user can choose which icon he wants. I found django-fontawesome-5 but there is one problem - there is no access to icon's unicode and I need it for one javascript component (html doesn't work there, and unicode does). I was looking all over the internet, but I coundn't find anything that would allow me to add font-awersome icons, with their unicodes somhow stored. My question is do you know how to get this feature?

A: The unicode codes are stored in icons.json and in icons_semantic_ui.json
Since you've got the codes source you can define a custom templatetag or a model/mixin method  or a function which just gets a code from one of those json files using icon name
You can see example in fontawesome_5/utils.py