text:
Q: how to make ng-repeat work with filter and one time binding? Good day.
I am looking a way to speed up
items rendering with ng-repeat.
My angular version is 1.6.4
My code example, responsible for templates rendering, is:
div ng-repeat="data in vm.items
 | filter: {status: vm.filterValue, title: vm.fitler@Value}
 |  orderBy:vm.sortParam"

I used for this purpose one time binding
<div ng-repeat="data in ::vm.items
| filter: {status: vm.filterValue, title: vm.fitler@Value}
|  orderBy:vm.sortParam"

it renders the data on the page, but filter is not working at all.
Each repeated  element has it's separate directive with controller, scope and listeners (i've also added :: inside {{}} for optimization aims).
Also i've added debounce(250) parameter for input, used for search. It makes UI bit better (smaller freezing between input some text and it's appearing in input)
Can you, please, provide recommendations to increase performance of rendering with ng-repeat and how to use filter with ng-repeat and filter option?


text:
Q: Vectorize Functions in R I have this dataset in R that looks something like this:
   id = sample.int(10000, 100000, replace = TRUE)
res = c(1,0)
results = sample(res, 100000, replace = TRUE)
date_exam_taken = sample(seq(as.Date('1999/01/01'), as.Date('2020/01/01'), by="day"), 100000, replace = TRUE)

my_data = data.frame(id, results, date_exam_taken)
my_data <- my_data[order(my_data$id, my_data$date_exam_taken),]

my_data$general_id = 1:nrow(my_data)
my_data$exam_number = ave(my_data$general_id, my_data$id, FUN = seq_along)
my_data$general_id = NULL

Using the R programming language, I wrote this loop that calculates conditional probabilities for the next exam results of a student conditional on the previous exam:
    library(data.table)

    setDT(my_data)

    my_list = vector("list", length(unique(my_data$id)))

# Create an empty vector with pre-specified dimensions
my_vector = vector("list", 100)

for (i in 1:length(unique(my_data$id)))
{
    tryCatch({
        start_i = my_data[my_data$id == i,]
        pairs_i =  data.frame(first = head(start_i$results, -1), second = tail(start_i$results, -1))
        frame_i =  as.data.table(table(pairs_i))
        frame_i[, id := i]
        print(frame_i)
        my_vector[[i]] = frame_i
    }, error = function(e){})
}

final = rbindlist(my_vector)

I am now trying to "vectorize" this code for improved efficiency. Here is my attempt:
# I don't think I need to create a "list or vector" to store the results in advance?
my_vector = sapply(unique(my_data$id), function(i) {

    {tryCatch({
        setDT(my_data)
        start_i = my_data[my_data$id == i,]

        pairs_i =  data.frame(first = head(start_i$results, -1), second = tail(start_i$results, -1))
        frame_i =  as.data.frame(table(pairs_i))
      frame_i$i = i
        print(frame_i)
        return(frame_i)
    }, error = function(e){print(paste("An error occurred:", e))})
    }

})

# produced an error, so I tried a different code
 final = rbindlist(my_vector, fill = TRUE)
# not sure if this fully worked either?
final = do.call(rbind.data.frame, my_vector)

Have I correctly "vectorized" this code?
UPDATE: Probability Calculation Template:
library(dplyr)

total_1 = final %>% group_by(first, second) %>% summarise(totals = n())
total_2 = total_1 %>% group_by(first) %>% summarise(sum = sum(totals))

join = merge(x = total_1, y = total_2, by = c("first"), all = TRUE)
join$probs = join$totals/join$sum
na.omit(join)

A: library(magrittr)
library(dplyr)
group_by(my_data, id)%>%
summarise(first = head(results, -1), second = tail(results, -1))%>%
ungroup

redpajama_set_name: RedPajamaStackExchange


text:
Q: Windows 10 fails to boot without recovery disk Every time I boot up my PC, I see this message after the BIOS splash screen:
boot selection failed because a required device is inaccessible 0x000000f
From then, only Windows 10 will only boot when a recovery or installation image is available from USB or Optical drive.
Tried the following without solving the issue:
In Windows RE (Recovery Environment)

*

*Bootrec

*

*/fixmbr - Fix Master Boot Record (successful)

*/fixboot - Fix Boot (successful)

*/rebuildbcd -Rebuild Boot Configuration Data (requested system device cannot be found)

*Chkdsk (no errors)

In Windows 10

*

*Automatic Repair

*Reinstallation of Windows 10 while saving profile and apps

When scanning for OS /scanos, I see 2x Windows Installations on the D: Drive: Windows and Windows.old
However when booted in Windows 10, the Windows system files are located on C: drive, not D.
My PC: HDD Labels

*

*How do I reconcile the two label differences?

*

*Is that why the BIOS
cannot see the C drive because it thinks it is D?

*Is there anything I can do, short of a clean install?

A: For booting a GPT disk with Windows 7/8/10 by UEFI firmware 3 partitions on disk are needed:

*

*EFI System partition (with boot files)

*MS Reserved partition

*Windows partition itself
If all needed partitions are present on disk you can write/rewrite boot files with:
bcdboot W:\Windows /s Z: /f UEFI

where W: is Windows drive, Z: is EFI System (use diskpart.exe to map EFI System).
You should substitute the drive letters in example command with the mappings on your system.
Don't forget to boot Windows installation DVD/USB the UEFI way!
EDIT: EFI System is not mapped usually to a drive letter. You can use diskpart.exe on admin command prompt, then "list disk", select disk number that has EFI System with "select disk 0" (or 1), then "list part", then "select part 1 or 2 or 3 (whatever EFI System is). Then "assign LETTER=Z". Then "quit".
When you boot from USB it is not guaranteed that Windows partition is mapped to drive C: (when having more hard disks even less guaranteed). If you boot from USB and your Windows partition is mapped to D: - this is OK! Then the suggested command above would be "bcdboot D:\Windows /s Z: /f UEFI".
(end of EDIT)


text:
Q: Laravel 5.0 git push failed in openshift When i push my project in openshift it's show some error and after that home page show blank. Please tell me how to overcome this problem.
Show this Error:
remote: Migrating storage and log directories...
remote: Running 'php artisan migrate --force'...
remote: PHP Parse error:  syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in /var/lib/openshift/5625fa370c1e66983300012f/app-root/runtime/repo/config/app.php on line 147
remote: -------------------------
remote: Git Post-Receive Result: failure
remote: Activation status: failure
remote: Activation failed for the following gears:
remote: 5625fa370c1e66983300012f (Error activating gear: CLIENT_ERROR: Failed to execute action hook 'deploy' for 5625fa370c1e66983300012f application supportti    cketsystem
remote: #<IO:0x00000002268390>
remote: #<IO:0x00000002268318>
remote: )
remote: Deployment completed with status: failure
remote: postreceive failed
To ssh://5625fa370c1e66983300012f@supportticketsystem-zahidulislam.rhcloud.com/~    /git/supportticketsystem.git/
d2e663c..6122fb1  master -> master

This error show when i push my project in openshift
Config/app.php file code:
<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Application Debug Mode
    |--------------------------------------------------------------------------
    |
    | When your application is in debug mode, detailed error messages with
    | stack traces will be shown on every error that occurs within your
    | application. If disabled, a simple generic error page is shown.
    |
    */

    'debug' => env('APP_DEBUG'),

    /*
    |--------------------------------------------------------------------------
    | Application URL
    |--------------------------------------------------------------------------
    |
    | This URL is used by the console to properly generate URLs when using
    | the Artisan command line tool. You should set this to the root of
    | your application so that it is used when running Artisan tasks.
    |
    */

    'url' => env('APP_URL', 'http://localhost'),

    /*
    |--------------------------------------------------------------------------
    | Application Timezone
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default timezone for your application, which
    | will be used by the PHP date and date-time functions. We have gone
    | ahead and set this to a sensible default for you out of the box.
    |
    */

    'timezone' => 'UTC',

    /*
    |--------------------------------------------------------------------------
    | Application Locale Configuration
    |--------------------------------------------------------------------------
    |
    | The application locale determines the default locale that will be used
    | by the translation service provider. You are free to set this value
    | to any of the locales which will be supported by the application.
    |
    */

    'locale' => 'en',

    /*
    |--------------------------------------------------------------------------
    | Application Fallback Locale
    |--------------------------------------------------------------------------
    |
    | The fallback locale determines the locale to use when the current one
    | is not available. You may change the value to correspond to any of
    | the language folders that are provided through your application.
    |
    */

    'fallback_locale' => 'en',

    /*
    |--------------------------------------------------------------------------
    | Encryption Key
    |--------------------------------------------------------------------------
    |
    | This key is used by the Illuminate encrypter service and should be set
    | to a random, 32 character string, otherwise these encrypted strings
    | will not be safe.
    |
    */

    'key' => env('APP_KEY', 'eaAJlaAlABGDmSOIOoBKZBuwZnGdjYMn'),

    'cipher' => MCRYPT_RIJNDAEL_128,

    /*
    |--------------------------------------------------------------------------
    | Logging Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure the log settings for your application. Out of
    | the box, Laravel uses the Monolog PHP logging library. This gives
    | you a variety of powerful log handlers / formatters to utilize.
    |
    | Available Settings: "single", "daily", "syslog", "errorlog"
    |
    */

    'log' => 'daily',

    /*
    |--------------------------------------------------------------------------
    | Autoloaded Service Providers
    |--------------------------------------------------------------------------
    |
    | The service providers listed here will be automatically loaded on the
    | request to your application. Feel free to add your own services to
    | this array to grant expanded functionality to your applications.
    |
    */

    'providers' => [

        /*
         * Laravel Framework Service Providers...
         */
        'Illuminate\Foundation\Providers\ArtisanServiceProvider',
        'Illuminate\Auth\AuthServiceProvider',
        'Illuminate\Bus\BusServiceProvider',
        'Illuminate\Cache\CacheServiceProvider',
        'Illuminate\Foundation\Providers\ConsoleSupportServiceProvider',
        'Illuminate\Routing\ControllerServiceProvider',
        'Illuminate\Cookie\CookieServiceProvider',
        'Illuminate\Database\DatabaseServiceProvider',
        'Illuminate\Encryption\EncryptionServiceProvider',
        'Illuminate\Filesystem\FilesystemServiceProvider',
        'Illuminate\Foundation\Providers\FoundationServiceProvider',
        'Illuminate\Hashing\HashServiceProvider',
        'Illuminate\Mail\MailServiceProvider',
        'Illuminate\Pagination\PaginationServiceProvider',
        'Illuminate\Pipeline\PipelineServiceProvider',
        'Illuminate\Queue\QueueServiceProvider',
        'Illuminate\Redis\RedisServiceProvider',
        'Illuminate\Auth\Passwords\PasswordResetServiceProvider',
        'Illuminate\Session\SessionServiceProvider',
        'Illuminate\Translation\TranslationServiceProvider',
        'Illuminate\Validation\ValidationServiceProvider',
        'Illuminate\View\ViewServiceProvider',

        /*
         * Application Service Providers...
         */
        'App\Providers\AppServiceProvider',
        'App\Providers\BusServiceProvider',
        'App\Providers\ConfigServiceProvider',
        'App\Providers\EventServiceProvider',
        'App\Providers\RouteServiceProvider',
        Collective\Html\HtmlServiceProvider::class,

        Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class,

    ],

    /*
    |--------------------------------------------------------------------------
    | Class Aliases
    |--------------------------------------------------------------------------
    |
    | This array of class aliases will be registered when this application
    | is started. However, feel free to register as many as you wish as
    | the aliases are "lazy" loaded so they don't hinder performance.
    |
    */

    'aliases' => [

        'App'       => 'Illuminate\Support\Facades\App',
        'Artisan'   => 'Illuminate\Support\Facades\Artisan',
        'Auth'      => 'Illuminate\Support\Facades\Auth',
        'Blade'     => 'Illuminate\Support\Facades\Blade',
        'Bus'       => 'Illuminate\Support\Facades\Bus',
        'Cache'     => 'Illuminate\Support\Facades\Cache',
        'Config'    => 'Illuminate\Support\Facades\Config',
        'Cookie'    => 'Illuminate\Support\Facades\Cookie',
        'Crypt'     => 'Illuminate\Support\Facades\Crypt',
        'DB'        => 'Illuminate\Support\Facades\DB',
        'Eloquent'  => 'Illuminate\Database\Eloquent\Model',
        'Event'     => 'Illuminate\Support\Facades\Event',
        'File'      => 'Illuminate\Support\Facades\File',
        'Hash'      => 'Illuminate\Support\Facades\Hash',
        'Input'     => 'Illuminate\Support\Facades\Input',
        'Inspiring' => 'Illuminate\Foundation\Inspiring',
        'Lang'      => 'Illuminate\Support\Facades\Lang',
        'Log'       => 'Illuminate\Support\Facades\Log',
        'Mail'      => 'Illuminate\Support\Facades\Mail',
        'Password'  => 'Illuminate\Support\Facades\Password',
        'Queue'     => 'Illuminate\Support\Facades\Queue',
        'Redirect'  => 'Illuminate\Support\Facades\Redirect',
        'Redis'     => 'Illuminate\Support\Facades\Redis',
        'Request'   => 'Illuminate\Support\Facades\Request',
        'Response'  => 'Illuminate\Support\Facades\Response',
        'Route'     => 'Illuminate\Support\Facades\Route',
        'Schema'    => 'Illuminate\Support\Facades\Schema',
        'Session'   => 'Illuminate\Support\Facades\Session',
        'Storage'   => 'Illuminate\Support\Facades\Storage',
        'URL'       => 'Illuminate\Support\Facades\URL',
        'Validator' => 'Illuminate\Support\Facades\Validator',
        'View'      => 'Illuminate\Support\Facades\View',
        'Form' => Collective\Html\FormFacade::class,
        'Html' => Collective\Html\HtmlFacade::class,

    ],

];

Config/app.php file..... line 147's code pic is here

A: The push itself is not failing, what is failing is the php parsing of your config/app.php, which has a syntax error.
The class name resolution using ::class is only supported since PHP >= 5.5. You need to import the HtmlServiceProvider as:
'providers' => [
    // ...
    'Collective\Html\HtmlServiceProvider',

Also, to run Laravel 5.0 you need to have PHP >= 5.4, so make sure you're not using 5.3


text:
Q: How to get a variable that is nested inside another function So, I have this code:
function readLineMemory() {
loadFile = dialog.showOpenDialog({properties: ['openFile']});
console.log(loadFile);
var lr = new LineByLineReader(loadFile[0]);
lr.on('error', err => {
    return console.log(err);
});
lr.on('line', function (line) { // called every line
    // var html = '';
    const lineParse = JSON.parse(line);
    JSONParsed.push(lineParse);
    let htmlTabled = tableify(lineParse) + '
';
    html = html + htmlTabled;
});
lr.on('end', function () { // called when file is read fully
    html = 'data:text/html,' + html;
})} return html

However, when I try to return the html value, it just returns undefined. I have been banging my head on the wall for a while with this, and I just cannot figure out what I am doing wrong. As far as I'm aware, the code isn't async. The html value should actually be a string of html code that I am using in another function.

A: The callbacks are asynchronous, according to what I see in the code here: https://github.com/Osterjour/line-by-line/blob/master/line-by-line.js#L43-L45
setImmediate(function () {
    self._initStream();
});

The parsing doesn't start until the next "tick" in the event loop. Generally, it's good to assume that most callbacks take place asynchronously. You'll want to convert your function to also be asynchronous:
function readLineMemory(cb) {
  let html = '';
  const loadFile = dialog.showOpenDialog({properties: ['openFile']});
  const lr = new LineByLineReader(loadFile[0]);
  lr.on('error', err => {
      cb(err);
    })
    .on('line', function (line) { // called every line
      const lineParse = JSON.parse(line);
      JSONParsed.push(lineParse);
      let htmlTabled = tableify(lineParse) + '
';
      html = html + htmlTabled;
    })
    .on('end', function () { // called when file is read fully
      html = 'data:text/html,' + html;
      cb(null, html);
    });
}

(or IMO even better with promises):
function readLineMemory() {
  return new Promise(function (resolve, reject) {
    let html = '';
    const loadFile = dialog.showOpenDialog({properties: ['openFile']});
    const lr = new LineByLineReader(loadFile[0]);
    lr.on('error', err => {
        reject(err);
      })
      .on('line', function (line) { // called every line
        const lineParse = JSON.parse(line);
        JSONParsed.push(lineParse);
        let htmlTabled = tableify(lineParse) + '
';
        html = html + htmlTabled;
      })
      .on('end', function () { // called when file is read fully
        html = 'data:text/html,' + html;
        resolve(html);
      });
  });
}


text:
Q: Store Bitmap Screenshot in Android Cache Can someone please help me make my code below store to cache rather than my sd card.  I am taking a screenshot of my application to use for sharing on social media.

// image naming and path  to include sd card
                String mPath = Environment.getExternalStorageDirectory().toString() + "/" + ACCUWX.IMAGE_APPEND;

                // create bitmap screen capture
                Bitmap bitmap;
                View v1 = mCurrentUrlMask.getRootView();
                v1.setDrawingCacheEnabled(true);
                bitmap = Bitmap.createBitmap(v1.getDrawingCache());
                v1.setDrawingCacheEnabled(false);

                OutputStream fout = null;
                imageFile = new File(mPath);

                try {
                    fout = new FileOutputStream(imageFile);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
                    fout.flush();
                    fout.close();

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

And here is my Social Media code to share the screenshot:

Intent socialIntent = new Intent(Intent.ACTION_SEND);
                    socialIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    Uri uri = Uri.fromFile(new File(mPath));

                    socialIntent.putExtra(Intent.EXTRA_STREAM, uri);
                    socialIntent.setType("image/jpeg");

                    startActivity(Intent.createChooser(socialIntent, "How do you wanna share?"));

A: Although it is not a good idea to store bitmap in cache because there will be memory leak issue. But, you can do following thing to store bitmap in cache.

static HashMap<String, Bitmap> cache=new HashMap<String, Bitmap>();

to store bitmap into cache

cache.put(filename, bmp);

later, to retrieve bitmap from cache use following code,
    if(cache.containsKey(filename)){
        imageView.setImageBitmap(cache.get(filename));
    }


text:
Q: Fix broken external Links? I just noticed this:
All partner links have this structure:
https://www.webseite.de/shop/?sPartner=77.77.77777
https://www.webseite.de/shop/?sPartner=666666666

The links given to the partners look like this:
https://www.webseite.de/shop/default/?sPartner=77.77.77777
https://www.webseite.de/shop/default/?sPartner=666666666

The only thing that occurs to me is that the problem could possibly be corrected using modrewrite via the htacces.
Do you have any ideas how the problem can be solved?

A: You can rewite the incorrect url to the correct one using htaccess
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

## Rule ##
RewriteRule ^shop/default/?$ shop/ [L]


text:
Q: Sphere Volume Calculator Hello I am making a volume calculator and I can't seem to get the volume to display on screen. Would doing an alert solve this? This assignment requires me to use anonymous functions so I am having a hard time getting the function to run.
HTML

 Calculate the Volume of a Sphere

 Radius
 <input id="radius" name="radius"  required>
 </input>

 <button id="calc" onclick=sphereVol> calculate </button>

JavaScript

 var sphereVol = function(radius){
 var c = (4/3) * Math.PI * Math.pow(radius, 3);
 return c;
 }

A: You need to manipulate the DOM to receive the input and to show the output. Your function is right, but here's one way of manipulating the DOM:
HTML

 Calculate the Volume of a Sphere

 Radius
 <input id="radius" name="radius" required>

 <button id="calc" onclick=sphereVol()> calculate </button>

Your volume:

JavaScript
 var sphereVol = function(){
    var radius = document.getElementById("radius").value;
    var c = (4/3) * Math.PI * Math.pow(radius, 3);

    document.getElementById("outputVolume").innerHTML = c;
 }

What changed:

*

*I called the function in the onclick sphereVol by saying sphereVol()

*I looked up the volume

*I changed the HTML to show the result

Further Reading:

*

*https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById

*https://www.w3schools.com/jsref/prop_text_value.asp

*https://www.w3schools.com/js/js_htmldom_html.asp

A: There are a couple of bugs in your program. I have improved your code and also read the comment in each line.

 Calculate the Volume of a Sphere

 Radius
 <input id="radius" name="radius"  required>
 </input>

 <button id="calc" onclick="sphereVol()"> calculate </button>

A: You need to get the radius from the input and the output it somewhere. You could use alert() or console.log() but it's nicer if you can output to the page. document.getElementById() is a fundamental way of getting elements from the DOM and value can help get the input. Here's a super-simplified version:

var sphereVol = function() {
  // get the radius
  let radius = document.getElementById('radius').value
  var c = (4 / 3) * Math.PI * Math.pow(radius, 3);
  // display the result
  document.getElementById('result').textContent = "Volume ≈ " + c.toFixed(4);
}

 Calculate the Volume of a Sphere

Radius
<input id="radius" name="radius" required>
</input>

<button id="calc" onclick="sphereVol()"> calculate </button>


text:
Q: Maven dependency causes NoClassDefFoundError in servlet I have created a servlet as a Dynamic Web Project in Eclipse, then converted it to a Maven project. I initially created it as a simple "Hello World" servlet and "Run on Server" worked fine.
I then added another (Maven) project in my workspace as a dependency and referenced one of the classes in that project. Now the servlet fails with a NoClassDefFoundError exception as soon as a class from the dependency is referenced. What gives?

A: Browsing through some other question I found some helpful hints:
I tried Run as > maven install on the project, which failed with an error indicating my dependency could not be found. Turns out I needed to add my dependency to my local repo first—behavior is different from a standard Java application here.
Choose the dependency, then Run as > maven install to store the dependency in your local repository.
After that I was able to run the servlet on my server with no further issues.


text:
Q: Does Pointer to Dynamic Container Persist? I know dynamic data structures like vectors, lists, maps and sets allocate their elements on the heap autonomously, therefore I cannot take a pointer to an element and expect it to stay valid, if the data structure gets modified. But can I make a pointer to the structure itself and know that it will always stay valid? I would assume the structure has some kind of anchor in the stack, that will always have the same address or something, regardless of where its elements are allocated... ?
so, can I safely do something like this with STL dynamic containers?
int main()
{

    std::set<int> s;
    std::set<int>* s_ptr = &s;

    for (int i = 0; i < 1000000; ++i)
    {
        s.insert(i);
    }

    std::cout << s_ptr->size() << std::endl;

}

In my test this did work. But because of UB I cannot rely on that.

A: Your usage of the pointer is safe. The pointer will be valid as long as s is alive. In this case, s will be alive until the end of the function.


text:
Q: ArcGis Server: Separate Virtual Directories for Services? This is a Windows system. As we know, ArcGIS Server creates a default 'arcgis' virtual directory in IIS and that becomes the starting point for various services. While that is a convenient 'one size fits all' kind of a solution it doesn't help trying to secure some web Services which should be only accessible from within the intranet while still enabling other Services to be accessible from the outside.
So what we need is a way to create different virtual directories in IIS for the Services which would need enhanced security. If we could create a different virtual directory for a secure Service then we can simply use IIS's domain/ip based restrictions on that directory to limit to only the intranet IPs. Is that even possible in ArcGIS Servers?
Perhaps, some other option could be to somehow use URL redirect/reverse proxy or use a Service's own security for some role/user based one--but that would require Active Directory on the server and sounds complicating to setup?

A: Ah ha! In the end the solution was quite simple. And I think will work?! Here it is:!
1) Disable port 6080 by default outside the intranet. Easy to do in my organization!
2) Create URL Re-write URL in IIS: With a 'wildcard' rule of *services/CULAND and Url Redirect to: http://myarcgisserver:6080/arcgis/rest/services/CULAND (I am making it 'temporary' for now)
And so anyone outside the network may be able to see the port 80 based URL to /services/CULAND but they can't access it because the direct will be to port 6080, which will be inaccessible outside the network.
I am going to test it further and even use some javascript application for testing.
What do guys say?
Thanks.


text:
Q: How can I select only 1 word with formatBlock When I select a word in my application and want to give it a span, the whole sentence is included. Does anyone know how I can solve this?
I think it's up to formatBlock but I have no idea what I can use as a replacement for formatBlock.
<button id="span" type="button" class="btn btn-outline-secondary">T</button>

{!! old('answers',$task->description) !!}

<textarea name="answers" id="answerstextarea" style="display:none"></textarea>

 $('#span').on('click', function () {
            document.execCommand('formatBlock', false, '
');

            let bq = $('#textarea').find('blockquote').first().text();
            $.ajaxSetup({
                headers: {
                    'X-CSRF-Token': parent.$('meta[name="csrf-token"]').attr('content')
                }
            });
            $.post('{{route('translate')}}', {'totranslate' : bq}, function (data) {
                $('#translate .modal-body').html(data);
                $('#translate').modal('show');

                $('#textarea blockquote').replaceWith('' + bq + '');
                let text = $('#textarea').html();

                $('#textarea-show').html(text);
                $('textarea#answers2textarea').html(text);

            });

        });

A: As the name applies the formatBlock command will format a line/block, it would not be applicable to selected words
The following post includes a function to do the formatting if you can not use formatBlock
Make selected text bold/unbold
here is a list of commands you can use with execCommand maybe you can do the formatting using some other command.
https://www.w3schools.com/jsref/met_document_execcommand.asp


text:
Q: How to update the UI during the doInBackground portion of a thread? I have a time consuming task that is taking place in the doInBackground() method, but from within that method, I want to be able to update the progressDialog with percentage data. How can I do this?
    class GetDataTask extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute()
    {
        mProgressDialog = ProgressDialog.show(getActivity(),Constants.APP_NAME,"Getting data", true);
    }

    @Override
    protected Void doInBackground(Void... params)
    {
        //go get data, update mProgressDialog
        return null;
    }

    @Override
    protected void onPostExecute(Void res)
    {

    }
}

A: Override the  onProgressUpdate() method like this:
@Override
protected void onProgressUpdate(Integer... progress) {
    super.onProgressUpdate(progress);
    mProgressDialog.setProgress(progress[0]);
}

and publish the progress with
publishProgress((int) (total * 100 / fileLength));

Try to refer to this link

A: AsyncTask has method onProgressUpdate(Integer...) that you can call each iteration for example or each time a progress is done during doInBackground() by calling publishProgress().
Refer to the docs for more details

Note that the second parameter is the progress variable
class GetDataTask extends AsyncTask<Void, String, Void> {

    @Override
    protected void onPreExecute()
    {
        mProgressDialog = ProgressDialog.show(getActivity(),Constants.APP_NAME,"Getting data", true);
    }

    @Override
    protected Void doInBackground(Void... params)
    {
        publishProgress(""+(int)count);
        return null;
    }

    protected void onProgressUpdate(String... progress) {
        /**
         * Sets current progress on ProgressDialog
         */
        mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }

    @Override
    protected void onPostExecute(Void res)
    {

    }
}


text:
Q: How to model Paxos in TLA+ Toolbox? I try to model Paxos (Paxos example) in TLA+ Toolbox (toolbox). What numbers should I put in the model to make it work? Or are there other ways a confirmation of this algorithm in this toolbox?
Base on this code:
CONSTANT Value,     \* The set of choosable values.
     Acceptor,  \* A set of processes that will choose a value.
     Quorum     \* The set of "quorums", where a quorum" is a
                \*   "large enough" set of acceptors

I try numbers like this:
Acceptor <- [11,12,13,14,15];
Quorum <- [11,12,13,14,15,16,17,18,19];
Value <- [0,1];
but I get ArrayIndexOutOfBoundsException error.

A: There are a few issues with your model:

*

*For specifying a set, you should use curly braces, so Acceptor <- {11,12,13,14,15}.

*Quorum should be a set of sets of acceptors, e.g. Quorum <- {{11,12,13},{12,13,14}}.


text:
Q: Inverse Mellin Transform We all know that the Inverse Mellin Transform is
$$\left\{\mathcal{M}^{-1}\varphi\right\}(x) = f(x)=\frac{1}{2 \pi i} \int_{c-i \infty}^{c+i \infty} x^{-s} \varphi(s)\, \mathrm{d}s.$$
So what is my problem? I want to calculate an integral, which looks like:
$$\frac{1}{2 \pi i} \int_{c-i \infty}^{c+i \infty} x^{s} \varphi(s)\, \mathrm{d}s$$
I want to express this integral as a Inverse Mellin Transformation. My idea was to do a small substitution, so that $s \rightarrow -s$. But then the integral has different boundaries:
$$-\frac{1}{2 \pi i} \int_{-c+i \infty}^{-c-i \infty} x^{-s} \varphi(s)\, \mathrm{d}s = \frac{1}{2 \pi i} \int_{-c-i \infty}^{-c+i \infty} x^{-s} \varphi(s)\, \mathrm{d}s$$
This is an Inverse Mellin Transform but $c\rightarrow-c$. How can I get to a real Inverse Mellin Transform?


text:
Q: Frequent OVER_QUERY_LIMIT using Google Places API KEY even before the No. of limitation We are using Google Places API KEY in order to use 'Search' provided from Google and as far as we know the number of usage for API KEY is limited to 100,000 times  per day.
However, we frequently kept on getting OVER_QUERY_LIMIT even before searching 100,000 times and receive "No Result" on the screen. The debug result was as we said 'OVER_QUERY_LIMIT'.
Is there any case and reason for OVER_QUERY_LIMIT to be appeared?
What is the solution for this?
Thank you in advance.

A: If you are using mobile connection your problem may reside in your mobile operator. The vast majority of operators use a technique called NAT overloading and assign the same external IP to a number of devices. If your operator assigns a very large number of devices to a single IP and a number of them uses similar services, everyone will have a problem, as all requests will appear to stem from the same IP.
This question has interesting answers to this problem, that I encountered too.

A: I was able to find 3 throttle limits for the places api, given by google.

*

*10 api calls per every 1 second

*100 api calls per every 100 seconds

*50,000 api calls per 1 day

If I were to go over any of these limits, I would receive the OVER_QUERY_LIMIT error and it would return no results for that given address.
I found a way to have my program sleep for 11 seconds after calling the places api with a dataset of 10 addresses. Then the program would call the places api with a new dataset of 10 address. This solution gets around the 10calls/second and the 100calls/100seconds throttle limits. However, I did run into the OVER_QUERY_LIMIT error once I tried my 25th dataset of 10 address (after 240 api calls). So it is clear that there are other throttles not published to help protect the google maps platform.
But, I did see that the limits mentioned above may be changed if you get in contact with the google api help team and sort it out with them.


text:
Q: How to generate short unique names for uploaded files in nodejs I need to name uploaded files by short unique identifier like nYrnfYEv a4vhAoFG hwX6aOr7. How could I ensure uniqueness of files?

A: Very simple code. produce a filename almost unique
or if that's not enough you check if the file exists
function getRandomFileName() {
var timestamp = new Date().toISOString().replace(/[-:.]/g,"");
var random = ("" + Math.random()).substring(2, 8);
var random_number = timestamp+random;
return random_number;
}

A: Update: shortid is deprecated. Use Nano ID instead. The answer below applies to Nano ID as well.

(Posting my comments as answer, with responses to your concerns)
You may want to check out the shortid NPM module, which generates short ids (shockingly, I know :) ) similar to the ones you were posting as example. The result is configurable, but by default it's a string between 7 and 14 characters (length is random too), all URL-friendly (A-Za-z0-9\_\- in a regex).
To answer your (and other posters') concerns:

*

*Unless your server has a true random number generator (highly unlikely), every solution will use a PRNG (Pseudo-Random Number Generator). shortid uses Node.js crypto module to generate PRNG numbers, however, which is a much better generator than Math.random()

*shortid's are not sequential, which makes it even harder to guess them

*While shortid's are not guaranteed to be unique, the likelihood of a collision is extremely small. Unless you generate billions of entries per year, you could safely assume that a collision will never happen.

*For most cases, relying on probability to trust that collisions won't happen is enough. If your data is too important to risk even that tiny amount, you could make the shortid basically 100% unique by just prepending a timestamp to it. As an additional benefit, the file names will be harder to guess too. (Note: I wrote "basically 100% unique" because you could still, in theory, have a collision if two items are generated in the same timestamp, i.e. the same second. However, I would never be concerned of this. To have a real 100% certainty your only option is to run a check against a database or the filesystem, but that requires more resources.)

*The reason why shortid doesn't do that by itself is because for most applications the likelihood of a collision is too small to be a concern, and it's more important to have the shortest possible ids.

A: One option could be to generate unique identifiers (UUID) and rename the file(s) accordingly.
Have a look at the kelektiv/node-uuid npm module.

EXAMPLE:
$ npm install uuid

...then in your JavaScript file:
const uuidv4 = require('uuid/v4'); // I chose v4 ‒ you can select others
var filename = uuidv4(); // '110ec58a-a0f2-4ac4-8393-c866d813b8d1'

Any time you execute uuidv4() you'll get a very-fresh-new-one.

NOTICE: There are other choices/types of UUIDs. Read the module's documentation to familiarize with those.

A: export default generateRandom = () => Math.random().toString(36).substring(2, 15) + Math.random().toString(23).substring(2, 5);

As simple as that!

A: function uniqueFileName( filePath, stub)
{
    let id = 0;
    let test = path.join(filePath, stub + id++);
    while (fs.existsSync(test))
    {
        test = path.join(filePath, stub + id++);
    }
    return test;
}

A: Try following snippet:-
    function getRandomSalt() {
    var milliseconds = new Date().getTime();
    var timestamp = (milliseconds.toString()).substring(9, 13)
    var random = ("" + Math.random()).substring(2, 8);
    var random_number = timestamp+random;  // string will be unique because timestamp never repeat itself
    var random_string = base64_encode(random_number).substring(2, 8); // you can set size here of return string
    var return_string = '';
    var Exp = /((^[0-9]+[a-z]+)|(^[a-z]+[0-9]+))+[0-9a-z]+$/i;
    if (random_string.match(Exp)) {                 //check here whether string is alphanumeric or not
        return_string = random_string;
    } else {
        return getRandomSalt();  // call recursivley again
    }
    return return_string;
}

File name might have an alphanumeric name with uniqueness according to your requirement. Unique name based on the concept of timestamp of current time because current time never repeat itself in future and to make it strong i have applied a base64encode which will be convert it into alphanumeric.
   var file = req.files.profile_image;
   var tmp_path = file.path;
   var fileName = file.name;
   var file_ext = fileName.substr((Math.max(0, fileName.lastIndexOf(".")) || Infinity) + 1);
   var newFileName = getRandomSalt() + '.' + file_ext;

Thanks

A: I think you might be confused about true-random and pseudo-random.
Pseudo-random strings 'typically exhibit stastical randomness while being generated by an entirely deterministic casual process'. What this means is, if you are using these random values as entropy in a cryptographic application, you do not want to use a pseudo-random generator.
For your use, however, I believe it will be fine - just check for potential (highly unlikely) clashes.
All you are wanting to do is create a random string - not ensure it is 100% secure and completely random.


text:
Q: How to disable the text editing feature of keyboard in xamarin forms? I want to disable the text editing feature of the keyboard which allows the keyboard to copy paste the values in Entry. This is my renderer code.
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
    base.OnElementChanged(e);
    if (Control != null)
    {
        Control.InputType = Android.Text.InputTypes.ClassText;

        Control.CustomSelectionActionModeCallback = new Callback();
        Control.CustomInsertionActionModeCallback = new Callback();
        Console.WriteLine("CustomSelectionActionModeCallback");

        Control.SetTextIsSelectable(false);
        Control.LongClickable = false;
        Control.SetOnTouchListener(EntryTouchListener.Instance.Value);
    }
}

This is the MyEntry class code
public class MyEntry : Entry
{
    public MyEntry()
    {
        BackgroundColor = Color.Gray;
        Keyboard = Keyboard.Create(KeyboardFlags.None);
    }
}

I have tried to set the KeyboardFlags as none as suggested in the following suggestion
Can I prevent keyboard suggestions from Xamarin.forms
Still it didn't help. This is how my UI looks like

I have to hide or disable the text editing feature from my keyboard. I have no clue how to fix this issue. Any suggestions?


text:
Q: How to use yum to install from a DVD I use Fedora 14. Some days ago, I used the command yum remove openoffice.org-* and removed openoffice successfully. The, I wanted to get it back. I have all the packages and dependancies required to install in an installation dvd. The problem is that when I try to manually install each package, yum does not check dependencies in the DVD. How can I configure yum to look for all dependancies and packages required, in the DVD?

A: Sounds like you need to update your /etc/yum.repos.d to include your dvd. See here for details: Howto Setup yum repositories to update or install package from ISO CDROM Image

A: Probably the easiest thing to do here, to just fix this problem, is to install the "yum-plugin-tmprepo" plugin and do:
yum history undo <transaction id> --tmprepo=/path/to/DVD/packages

...where you can get the transaction ID from yum history list openoffice.


text:
Q: How do you map strings in the database to enums in your model without introducing a second property? My database has a table like this:
Cats
- CatId INT PK
- Name VARCHAR(100)
- FavoriteToy VARCHAR(100)

And my code looks like this:
Cat.cs
public int CatId { get; set; }
public string Name { get; set; }
public Toy FavoriteToy {get; set; }

StaticVariables.cs
public enum Toy { Box, Ball, StuffedAnimal }

In a normalized database I would use a lookup table in the database to store all the toys and then the Cats table would just store a ToyId. But for this situation it's a lot easier to just store the FavoriteToy as a string even though it will be redundant.
The problem is I don't know how to convert a string in the database to an enum in code without creating a second FavoriteToyString property and having FavoriteToy just be a computed that returns the enum derived from FavoriteToyString.
I've heard this might be possible in the current version of entity framework. Is that true? Can you please show me how to do this?

A: You may use DTO class and automapper to solve your issue :)

A: Generally, yes a lookup table reference is a better option since your data can comply with referential integrity. That is, No cat records with toys that your Enum hopefully doesn't contain. (Though your Enum would need to be kept in sync with the Toys table.) You can configure EF to store enumerations as a string using a bit of a trick with the mapping:
public class Cat
{
  [Key]
  public int CatId { get; set; }
  public string Name { get; set; }

  [Column("FavoriteToy")]
  public string FavoriteToyMapped { get; set; }

  [NotMapped]
  public Toy FavoriteToy
  {
    get { return (Toy)Enum.Parse(typeof(Toy), FavoriteToyMapped); }
    set { FavoriteToyMapped = value.ToString(); }
  }
}

The caveat of this approach is that where you might use Linq to Entity to filter on your cat's favorite toy, you need to reference the FavoriteToyMapped value in the query expression because EF/DB won't know what FavoriteToy is.
I.e.
Cats with a favorite toy of "Yarn"
var catsThatLoveYarn = context.Cats.Where(c => c.FavoriteToyMapped == Toys.Yarn.ToString()).ToList();
// not
var catsThatLoveYarn = context.Cats.Where(c => c.FavoriteToy == Toys.Yarn).ToList();
// Will error because EF doesn't map that property.

Once you are working with instances of entities, that the set of entities has been pulled back from the database, you can further access/refine queries with FavoriteToy. Just be cautious and prepared for the unknown field if you use it too early and EF goes and tries to compose a query.
var threeYearOldCats = context.Cats.Where(c => c.Age == 3).ToList();
var threeYearOldCatsThatLoveYarn = threeYearOldCats.Where(c => c.FavoriteToy == Toys.Yarn).ToList();

This is Ok because the .ToList() in the first query executed the EF-to-SQL, so threeYearOldCats is now a local List<Cat> of cat entities, not an IQueryable<Cat>.


text:
Q: In LuaTeX, what is the "identity" linebreak_filter? (Or: how can we use `tex.linebreak` to match the default line-breaking algorithm?) Consider the following LaTeX document (to be compiled with lualatex):
\documentclass{article}
\usepackage{lipsum}
\begin{document}
\directlua{
  function shouldbenoop(head, isDisplay)
    return tex.linebreak(head)
  end
}
% \directlua{luatexbase.add_to_callback('linebreak_filter', shouldbenoop, 'This should be same as the default?')}

\lipsum
\end{document}

Whether or not the add_to_callback line is commented out, the output appears to be the same, that is our overridden linebreak filter, which calls tex.linebreak, appears to do the same thing that TeX does by default.
However, when we try the same with plain TeX (to be compiled with luatex):
\input ltluatex % For luatexbase.add_to_callback
\input plipsum
\directlua{
  function shouldbenoop(head, isDisplay)
    return tex.linebreak(head)
  end
}
% \directlua{luatexbase.add_to_callback('linebreak_filter', shouldbenoop, 'This should be same as the default?')}

\lipsum{1-20}
\bye

and use the linebreak filter (uncomment the commented line above), the result looks bad, between paragraphs:

The paragraphs appear to overlap almost, and we need to set a higher \parskip to get "proper" results (of course they're not proper in the sense that they differ from the result without using the linebreak filter).
The issue is not with loading ltluatex in plain, as the result is the same with this:
\input plipsum
\directlua{
  function shouldbenoop(head, isDisplay)
    return tex.linebreak(head)
  end
}
\directlua{callback.register('linebreak_filter', shouldbenoop)}

\lipsum{1-20}
\bye

It also doesn't have anything to do with plipsum, as it is reproducible by simply typing out paragraphs without loading the package.
What is going on? And more importantly, what can we write as a linebreak_filter in plain TeX, that will perfectly reproduce the effect of the default line-breaking (that is, be identical to not having a linebreak_filter)?

A: You need to reset (at least) \prevdepth something like this, otherwise \prevdepth gets the "start of list" value of -1000pt and the following paragraph is set with no space before it.
\directlua{
  function shouldbenoop(head, isDisplay)
    h,t =tex.linebreak(head)
    tex.prevdepth= t.prevdepth
   return h
  end
}
\directlua{callback.register('linebreak_filter', shouldbenoop)}

\hsize3cm
\parindent0pt

g g g g g g g g g g g g g g g g g g g g g g g g g g g g g g g g

\showthe\prevdepth
g g g g g g g g g g g g g g g g g g g g g g g g g g g g g g g g

a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a

a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a

\bye

A: I am not deleting this for sentimental reasons, but from informed comment and comment and from the answer by @FrankMittlebach and @DavidCarlisle it is expected that \prevdepth (and \prevgraf) settings must be restored by the callback. I have not read the manual but it seems from that further comment by @ShreevatsaR that one needs to gather the information from other sources as well.

This is too long but is a comment: in the LaTeX case too, something is broken. Here is my test file:
\documentclass{article}

\begin{document}
\directlua{
  function shouldbenoop(head, isDisplay)
    return tex.linebreak(head)
  end
}
%\directlua{luatexbase.add_to_callback('linebreak_filter', shouldbenoop, 'This should be same as the default?')}

\parskip 0pt

\def\x{\rule{2cm}{5pt} }

\def\y{\x\x\x\x}
\def\z{\y\y}

\z

\z g g g

\z

\thispagestyle{empty}
\showoutput

\end{document}

The g g g in second paragraph cause the third to move down, when the \directlua is executed. The baselineskip glue computed by TeX should be 4.94pt but turns out to be 7pt (making the distance from bottom of g to next baseline exactly 7pt+5pt=12pt).
Here is a diff of the logs, cut down to the relevant things. At top of each portion the result with the \directlua executed, at bottom, with it commented out. Clearly the last paragraph is positioned lower in former case due to the descenders of letter g: TeX's mechanism is broken for maintaining a constant base line.
*** 84,90 ****
  ...\hbox(0.0+0.0)x345.0, direction TLT
  ..\glue 25.0
  ..\glue(\lineskip) 0.0
! ..\vbox(550.0+0.0)x345.0, glue set 477.88895fil, direction TLT
  ...\write-{}
  ...\glue(\topskip) 5.0
  ...\hbox(5.0+0.0)x345.0, glue set - 1.0, direction TLT
--- 83,89 ----
  ...\hbox(0.0+0.0)x345.0, direction TLT
  ..\glue 25.0
  ..\glue(\lineskip) 0.0
! ..\vbox(550.0+0.0)x345.0, glue set 479.94873fil, direction TLT
  ...\write-{}
  ...\glue(\topskip) 5.0
  ...\hbox(5.0+0.0)x345.0, glue set - 1.0, direction TLT
***************
*** 168,174 ****
  ....\glue(\parfillskip) 0.0 plus 1.0fil
  ....\glue(\rightskip) 0.0
  ...\glue(\parskip) 0.0
! ...\glue(\baselineskip) 7.0
  ...\hbox(5.0+0.0)x345.0, glue set - 1.0, direction TLT
  ....\localpar
  .....\localinterlinepenalty=0
--- 167,173 ----
  ....\glue(\parfillskip) 0.0 plus 1.0fil
  ....\glue(\rightskip) 0.0
  ...\glue(\parskip) 0.0
! ...\glue(\baselineskip) 4.94
  ...\hbox(5.0+0.0)x345.0, glue set - 1.0, direction TLT
  ....\localpar
  .....\localinterlinepenalty=0
***************

Image of output with \directlua executed:

The last paragraph is moved down.

And \the\prevdepth indeed produces 0.0pt in the lua filter case and 2.06pt without it. (the kind of things one expects as collateral damage from using a \special, like happens with using \color etc... but here the \showoutput does not show such a thing, so must be more in the innards of luatex).


text:
Q: How to automatically sort files out? I have many files in my external harddrive, so I want to automatically tell the computer to sort all my files into folders, by their size, extension, name and other variables. Is there any program that will allow me to perform these tasks. Please teach me how to install it too.

A: If you're OK to use bash commands, you should look the man page for the find command .
find . -name \*.txt -size +599k -exec mv {} bigTextFolder \;

With this line, you can move all .txt files bigger or equal than 600KB into the bigTextFolder folder. You can find a lot of documentation about find on the net (Beginner Linux Guide) and the list of all tests available in the man page (first link).
To understand the command, look arguments:

*

*. is the directory where find will look for file. You can replace that by the path of your HDD.

*-name \*.txt is the name filter. It can use wildcards(*) if you escape them with . You can read this like "Find all the file with a name ended by .txt". Replace that by the pattern you're looking for:

*

*All file beginning by a: find . -name a\*

*The file aba.txt: find . -name aba.txt

*-size +599k is the size filter. Here you say "Find all the file with a size strictly superior too 599KB". Change 599 to the size you want, and k is just the unit.

*-exec allows to execute another command once a file is found. So here, for each file found, we do mv fileFounded targetFolder. The {} will be replace by your result. This part has to end with \;.

Keep in mind that you have a lot of other filters: type, date, owner, permissions,...

A: I am not aware of some readily available program for it, but you can write a shell script by combining commands like
du -a | sort -nr

will display files in reverse order of size.
and you can use it in combination with NorTicUs's script mentioned in post above
find . -name \*.txt -size +599k -exec mv {} bigTextFolder \;

to specify dynamic size by replacing 599K with variable holding output of 1st command.

A: I'm making a Python script that sort files by their extensions. In the future it will have more features but I think that this can help you
https://github.com/phaalonso/FileOrganizer


text:
Q: Salesforce - Link developer account I have used a Docusign trail account which was linked to my salesforce earlier. The trail docusign account has expired.
I have created a new docusign developer account and would like to link to the salesforce org.

A: Yes it is possible - just uninstall the previous one and you should be able to do it. if not link it to a different salesforce Org.


text:
Q: Qt auto software version? Does Qt maintain any sort of versioning information about your program like .NET does? Like the build number? Or does it provide an easy way to access the SVN revision?

A: No.
But if you're using qmake then you can set compiler flags in the build system based on the results of arbitrary commands, which might be usable to do what you want.
For example, if you were using git, you could do something like this in your .pro file:
REVISION = $$system(git rev-parse HEAD)
DEFINES += APP_REVISION=$$REVISION

That would give you an APP_REVISION macro when compiling your program, which you could use like this:
// stringize macro
#define _STR(X) #X
#define STR(X) _STR(X)
QTextStream(cout) << "MyApp revision " STR(APP_REVISION) << endl;


text:
Q: Clear git local cache I have a Webstorm project that I was about to commit, but before pressing the commit button in the Git Windows GUI, I remembered that I don't want to commit my .idea folder content.
So I used the website that auto generates .gitignores for certain IDEs and added it to my .gitignore file.
All .idea files that are explicitly ignored are still showing up to commit, despite me removing and re-added the files in question.
I've also committed the gitignore file without any other files, and re-pasted my content, but it still is not ignoring the .idea files.
How do I tell Git to refresh or clear its cache?
I tried /cd ing into the directory in question, and typing
git clean -n
but no files show up.

A: after that change in git-ignore file run this command , This command will remove all file cache not the files or changes

git rm -r --cached .

after execution of this command commit the files
for removing single file or folder from cache use this command

git rm  --cached filepath/foldername

A: git rm --cached *.FileExtension

This must ignore all files from this extension

A: To remove cached .idea/ directory.
e.g. git rm -r --cached .idea

A: if you do any changes on git ignore then you have to clear you git cache also
> git rm -r --cached .
> git add .
> git commit -m 'git cache cleared'
> git push

if want to remove any particular folder or file then
git rm  --cached filepath/foldername

A:
All .idea files that are explicitly ignored are still showing up to commit

you have to remove them from the staging area
git rm --cached .idea

now you have to commit those changes and they will be ignored from this point on.
Once git start to track changes it will not "stop" tracking them even if they were added to the .gitignore file later on.
You must explicitly remove them and then commit your removal manually in order to fully ignore them.

A: When you think your git is messed up, you can use this command to do everything up-to-date.
git rm -r --cached .
git add .
git commit -am 'git cache cleared'
git push

Also to revert back last commit use this :
git reset HEAD^ --hard


text:
Q: SQL database login for 'Config' on instance '' failed. Additional error information from SQL Server is included below In our internet farm in search server I saw below errors in event viewer. How to solve these issues.

SQL database login for SPL_Config' on instance 'SQL123_SQL' failed.

Additional error information from SQL Server is included below.

Login failed for user 'dc1L\Server1LSEARCH$'.

for the search service application I am using dedicated domain account for search service application service account.

A: You need to change permission for SharePoint_Config database, you can do as follows:

*

*Login to SQL Server Management Studio under Database Engine using authorized login account.

*Expand Security tree and then r-click on Logins > New Login

*Click Search and then type your new login account (remember that you must use fully structure domain_name\user_name)

*After creating new login account, expand Databases tree, r-click on SharePoint_Config database and then select Properties.

*Click Permission setting, select account and then select permission you want to assign for account.

Another Resolution
This error occurs because the SharePoint Timer service cannot log on to the SharePoint_Config database on the instance of Microsoft SQL Server that is used by SharePoint. To deploy Microsoft Dynamics NAV Portal Framework, Microsoft Dynamics NAV Setup creates a SharePoint Timer job through the SharePoint application programming interface (API). The SharePoint Timer must have access to the SharePoint_Config database.
To resolve this issue, add the logon account of the SharePoint Timer service as a user of the SharePoint_Config database. Give role membership to the account db_owner.


text:
Q: Can't Tell If Fetch Or Relationship Is The Problem I am adding object exercise to object session (as a relationship).
In a view, I want to fetch and display exercises for a particular session object.
Right now it is showing all exercises in the database rather than just for that session object.
The relationship between the two objects is called "exercises".
This is the current code I am using for the fetch if anyone can help me.
    // Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Exercise" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];

LogResultsViewController *logResultsTableViewController = [[LogResultsViewController alloc]init];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat: @"exercises = %@", logResultsTableViewController.selectedSession]];

// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];

// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];

Updated Code:
- (void) viewDidLoad
{
NSSet *exercises = [self.selectedSession valueForKey:@"exercises"];
NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"timeStamp" ascending:YES]];
NSArray *sorted = [exercises sortedArrayUsingDescriptors:sortDescriptors];
sorted = self.exerciseArray;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [exerciseArray count];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    cell.textLabel.text = [exerciseArray objectAtIndex:indexPath.row];
    return cell;
}

When I NSLog the selectedSession, here is what it shows:
selectedSession: <Session: 0x7336940> (entity: Session; id: 0x7334f70 <x-coredata://17D44726-23F7-402F-9CBE-2EED96212E14/Session/p1> ; data: {
    exercises = "<relationship fault: 0x5d34680 'exercises'>";
    timeStamp = "2011-05-31 04:41:07 +0000";
Also, when I NSLog the NSSset called exercises, I get:
Relationship fault for (<NSRelationshipDescription: 0x711b370>), name exercises, isOptional 1, isTransient 0, entity Session, renamingIdentifier exercises, validation predicates (
), warnings (
), versionHashModifier (null), destination entity Exercise, inverseRelationship exercises, minCount 0, maxCount 0 on 0x7140790
Update:
Ok so I changed the code in cellForRowAtIndex to have
Exercise *exercise = (Exercise *)[exerciseArray objectAtIndex:indexPath.row];
 cell.textLabel.text = exercise.name;
Now it shows the exercise name but it is showing the same list of exercises for all sessions, instead of just for the session to which it belongs to.

A: If your instances of Session have a relationship to instances of Exercise, you don't need to do another fetch to get the session's exercises. You can just follow the relationship and get them directly-- they'll be loaded automatically. From your code it looks like logResultsTableViewController.selectedSession is an instance of Session. If that's the case, you can get all of that session's exercies as follows (assuming the relationship is called exercises):
NSSet *exercises = [logResultsTableViewController.selectedSession valueForKey:@"exercises"];

You can then sort that NSSet as needed.


text:
Q: How to dynamically make the option selected if it's equal to something? I'm not good at jQuery or HTML I want to select the option depending on the value passed from an ajax call. The following is what's inside my html
<label class="item item-input">
        <input id="" type="text" required ng-model="Data.CompanyTitle">
        <select style="width: 100%">
            <option>Partner</option>
            <option>System</option>
            <option>Council</option>
        </select>
</label>

Data.CompanyTitle passes either Partner, System or Council. I want the option to be selected depending on what the value of Data.CompanyTitle is.

A: You can give the select a model and if the value of the option is equal to your variable it  gets auto selected
<select ng-model="selectModel">
    <option value="dummy">dummy</option>
</select>

and when you set $scope.selectModel = 'dummy' you can see dummy selected

A:

var data = "System";
$('select option').filter(function() {
  console.log($(this).text() == data)
  return $(this).text() == data;
}).prop('selected',true);
.red{color:red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="item item-input">
  <input id="" type="text" required ng-model="Data.CompanyTitle">
  <select style="width: 100%">
    <option>Partner</option>
    <option>System</option>
    <option>Council</option>
  </select>
</label>

*

*Use .filter()

Description: Reduce the set of matched elements to those that match the selector or pass the function's test.

*Use .prop()

Description: Get the value of a property for the first element in the set of matched elements.

Use filter to get the matching select option from the data. Then use prop to set the selected option

A: Find option by value:
var _value= 'System';
$('.item select  option[value="'+_value+'"]').prop('selected', true);

to get or set value from/to input you need to give id some id or class and:
get
 $('#search').val();
 $('.search').val();

to set
 var _value= 'System';
 $('#search').val(_value);
 $('.search').val(_value);

and there is simple example


text:
Q: Aligning multiple figures I am trying to align multiple tikzpictures.
It gets complicated as I need the following figures to be aligned

*

*possibly two y-axis

*possibly legends

*captions

The pgfplots manual gives 3 possible methods (see "4.19.4
Alignment In Array Form (Subplots)")

*

*tikzpicture environment inside of tables

*matrix inside of tikzpicture

*groupplots
Currently I try option 1 as option 2 doesnot easily work together with legends.
I have not tried option 3.
A minimal working example looks as follows
\documentclass[letterpaper,11pt,english]{article}
\usepackage[ascii]{inputenc}
\usepackage[T1]{fontenc}

\usepackage{subcaption}
\usepackage{graphicx}

\usepackage{pgfplots}
\pgfplotsset{compat=1.15, small}

\begin{document}

example ref to fig \ref{fig1}

\begin{center}
  \begin{tabular}{p{5cm}p{5cm}}                                        % "p{5cm}": predefined width is need for captionof to work
      \begin{tikzpicture}[baseline,trim axis left]
        \begin{axis}[ylabel={yname}]
          \addplot {x};
        \end{axis}
    \end{tikzpicture}
    \captionof{figure}{\textbf{Confusion Matrix foobar}}
    \label{fig1}
  &
    \begin{tikzpicture}[baseline,trim axis right]
      \pgfplotsset{set layers, scale only axis, xmin=-5,xmax=5,width=5cm}   % pgfplots' manual recommends those options: The Reference -> Axis Descriptions -> Two Ordinates
      \begin{axis}[
          ylabel={$f(x)=x^2$},
          yticklabel pos=upper,
          ylabel style={font=\Huge},
        ]
        \addplot {x^2};
        \label{x2}
      \end{axis}
      \begin{axis}[
          ylabel={$f(x)=x^5$},
          yticklabel pos=upper,
          ylabel style={font=\Huge},
          axis y line* = left,
          ymode=log
        ]

        % add potential to legend. only legend entries of last axis will be displayed.
        \addlegendimage{/pgfplots/refstyle=plot_x2}\addlegendentry{$x^2$}

        \addplot [red] {x^5};
        \addlegendentry{$x^5$}
      \end{axis}
    \end{tikzpicture}
  \\
    \begin{tikzpicture}[baseline,trim axis left]
      \begin{axis}[xlabel=$x$,xlabel style={font=\Huge}]
        \addplot {x^3};
      \end{axis}
    \end{tikzpicture}
  &
    \begin{tikzpicture}[baseline,trim axis right]
      \begin{axis}[yticklabel pos=upper]
        \addplot {x^4};
      \end{axis}
    \end{tikzpicture}
  \\
  \end{tabular}
\end{center}

\end{document}

A: The idea is to align the origins of all the tikzpictures by using a common cell size.  First we determine the distances to the bounding box for each picture, then we add extra points to produce a common bounding box for each picture.
The resulting cell size is far too large for the page.  Some savings can be obtained by doing each column separately, but it still won't fit inside the margins.
\documentclass[letterpaper,11pt,english]{article}
\usepackage[ascii]{inputenc}
\usepackage[T1]{fontenc}

\usepackage{subcaption}
\usepackage{graphicx}

\usepackage{pgfplots}
\pgfplotsset{compat=1.15, small}

%\usepackage{showframe}% MWE only

\newcommand{\xleft}{0pt}% reserve global names
\newcommand{\xright}{0pt}
\newcommand{\ybottom}{0pt}
\newcommand{\ytop}{0pt}

\newcommand{\maxborders}[1]{% #1 = \csname to store left offset
  \path (current bounding box.south west);
  \pgfgetlastxy{\x}{\y}
  \global\expandafter\let\csname #1\endcsname=\x
  \ifdim \xleft>\x\relax \global\let\xleft=\x \fi
  \ifdim \ybottom>\y\relax \global\let\ybottom=\y \fi
  \path (current bounding box.north east);
  \pgfgetlastxy{\x}{\y}
  \ifdim \xright<\x\relax \global\let\xright=\x \fi
  \ifdim \ytop<\y\relax \global\let\ytop=\y \fi}

\begin{document}

example ref to fig \ref{fig1}

\begin{center}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  \sbox0{\begin{tikzpicture}[baseline]
        \begin{axis}[ylabel={yname}]
          \addplot {x};
        \end{axis}
      \maxborders{left0}
    \end{tikzpicture}}
  \sbox1{\begin{tikzpicture}[baseline]
      \pgfplotsset{set layers, scale only axis, xmin=-5,xmax=5,width=5cm}   % pgfplots' manual recommends those options: The Reference -> Axis Descriptions -> Two Ordinates
      \begin{axis}[
          ylabel={$f(x)=x^2$},
          yticklabel pos=upper,
          ylabel style={font=\Huge},
        ]
        \addplot {x^2};
        \label{x2}
      \end{axis}
      \begin{axis}[
          ylabel={$f(x)=x^5$},
          yticklabel pos=upper,
          ylabel style={font=\Huge},
          axis y line* = left,
          ymode=log
        ]

        % add potential to legend. only legend entries of last axis will be displayed.
        \addlegendimage{/pgfplots/refstyle=plot_x2}\addlegendentry{$x^2$}

        \addplot [red] {x^5};
        \addlegendentry{$x^5$}
      \end{axis}
      \maxborders{left1}
    \end{tikzpicture}}
  \sbox2{\begin{tikzpicture}[baseline]
      \begin{axis}[xlabel=$x$,xlabel style={font=\Huge}]
        \addplot {x^3};
      \end{axis}
      \maxborders{left2}
    \end{tikzpicture}}
  \sbox3{\begin{tikzpicture}[baseline]
      \begin{axis}[yticklabel pos=upper]
        \addplot {x^4};
      \end{axis}
      \maxborders{left3}
    \end{tikzpicture}}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  \begin{tabular}{ll}
    \begin{tikzpicture}[baseline]
      \node[anchor=base west, inner sep=0pt] at ({\csname left0\endcsname},0) {\usebox0};
      \path (\xleft,\ybottom) (\xright,\ytop);
      \draw[red] (current bounding box.south west) rectangle (current bounding box.north east);
    \end{tikzpicture}
  &
    \begin{tikzpicture}[baseline]
      \node[anchor=base west, inner sep=0pt] at ({\csname left1\endcsname},0) {\usebox1};
      \path (\xleft,\ybottom) (\xright,\ytop);
      \draw[red] (current bounding box.south west) rectangle (current bounding box.north east);
    \end{tikzpicture}
  \\
    \parbox{\dimexpr \xright-\xleft}{% put captions is separate row
      \captionof{figure}{\textbf{Confusion Matrix foobar}}
      \label{fig1}}
  &
  \\
    \begin{tikzpicture}[baseline]
      \node[anchor=base west, inner sep=0pt] at ({\csname left2\endcsname},0) {\usebox2};
      \path (\xleft,\ybottom) (\xright,\ytop);
      \draw[red] (current bounding box.south west) rectangle (current bounding box.north east);
    \end{tikzpicture}
  &
    \begin{tikzpicture}[baseline]
      \node[anchor=base west, inner sep=0pt] at ({\csname left3\endcsname},0) {\usebox3};
      \path (\xleft,\ybottom) (\xright,\ytop);
      \draw[red] (current bounding box.south west) rectangle (current bounding box.north east);
    \end{tikzpicture}
  \\
  \end{tabular}
\end{center}

\end{document}

A: Personally i find the use of groupplots much more appealing. Also for two y-axes within one plot environment please see this thread.
\documentclass[letterpaper,11pt,english]{article}
\usepackage{subcaption}
\usepackage{graphicx}

\usepackage{pgfplots}
\usepgfplotslibrary{groupplots}
\pgfplotsset{compat=1.15, small}

\begin{document}

\begin{figure}[htb]
    \centering
    \begin{tikzpicture}[
        subcaption/.style={anchor=north, font=\small},
        baseline,
        trim axis left
    ]
    \begin{groupplot}[
    group style={
        group name=plotGroup,
        group size=2 by 2,
        horizontal sep=1.5cm,
        vertical sep=1.5cm,
    },
    height=5cm,
    width=5cm,
    ]
    %
    %   plot creation
    \nextgroupplot[ylabel={yname}]
    \addplot {x};
    \nextgroupplot[
        xmin=-5,xmax=5,
        ylabel={$f(x)=x^2$},
        yticklabel pos=upper,
        ylabel style={font=\Huge},
    ]
    \addplot {x^2};
    \addlegendimage{red}
    \legend{$x^2$,$x^5$}
    \nextgroupplot[
        xlabel=$x$,
        xlabel style={font=\Huge}
    ]
    \addplot {x^3};
    \nextgroupplot[yticklabel pos=upper]
    \addplot {x^4};
    \end{groupplot}
    %
    %   post axis
    \path let \p1 = (plotGroup c1r2.below south), \p2 = (plotGroup c2r2.below south) in (\x2,\y1) coordinate (tmpCoord);
    %
    \node[subcaption] at (plotGroup c1r1.below south) {(a) subtext 1\phantomsubcaption\label{fig:1}};
    \node[subcaption] at (plotGroup c2r1.below south) {(b) subtext 2\phantomsubcaption\label{fig:2}};
    \node[subcaption] at (plotGroup c1r2.below south) {(c) subtext 3\phantomsubcaption\label{fig:3}};
    \node[subcaption] at (tmpCoord) {(d) subtext 4\phantomsubcaption\label{fig:4}};
    \end{tikzpicture}
    \caption[]{}
    \label{fig:all}
\end{figure}
\end{document}


text:
Q: Torch: How to shuffle a tensor by its rows? I am currently working in torch to implement a random shuffle (on the rows, the first dimension in this case) on some input data. I am new to torch, so I have some troubles figuring out how permutation works..
The following is supposed to shuffle the data:
if argshuffle then
    local perm = torch.randperm(sids:size(1)):long()
    print("\n\n\nSize of X and y before")
    print(X:view(-1, 1000, 128):size())
    print(y:size())
    print(sids:size())
    print("\nPerm size is: ")
    print(perm:size())
    X = X:view(-1, 1000, 128)[{{perm},{},{}}]
    y = y[{{perm},{}}]
    print(sids[{{1}, {}}])
    sids = sids[{{perm},{}}]
    print(sids[{{1}, {}}])
    print(X:size())
    print(y:size())
    print(sids:size())
    os.exit(69)
end

This prints out
Size of X and y before
99
1000
128
[torch.LongStorage of size 3]

99
1
[torch.LongStorage of size 2]

99
1
[torch.LongStorage of size 2]

Perm size is:
99
[torch.LongStorage of size 1]
5
[torch.LongStorage of size 1x1]
5
[torch.LongStorage of size 1x1]

99
1000
128
[torch.LongStorage of size 3]

99
1
[torch.LongStorage of size 2]

99
1
[torch.LongStorage of size 2]

Out of the value, I can imply that the function did not shuffle the data. How can I make it shuffle correctly, and what is the common solution in lua/torch?

A: dim = 0
idx = torch.randperm(t.shape[dim])

t_shuffled = t[idx]

If your tensor is e.g. of shape CxNxF (channels by rows by features), then you can shuffle along the second dimension like so:
dim=1
idx = torch.randperm(t.shape[dim])

t_shuffled = t[:,idx]

A: I also faced a similar issue. In the documentation, there is no shuffle function for tensors (there are for dataset loaders). I found a workaround to the problem using torch.randperm.
>>> a=torch.rand(3,5)
>>> print(a)
tensor([[0.4896, 0.3708, 0.2183, 0.8157, 0.7861],
        [0.0845, 0.7596, 0.5231, 0.4861, 0.9237],
        [0.4496, 0.5980, 0.7473, 0.2005, 0.8990]])
>>> # Row shuffling
...
>>> a=a[torch.randperm(a.size()[0])]
>>> print(a)
tensor([[0.4496, 0.5980, 0.7473, 0.2005, 0.8990],
        [0.0845, 0.7596, 0.5231, 0.4861, 0.9237],
        [0.4896, 0.3708, 0.2183, 0.8157, 0.7861]])
>>> # column shuffling
...
>>> a=a[:,torch.randperm(a.size()[1])]
>>> print(a)
tensor([[0.2005, 0.7473, 0.5980, 0.8990, 0.4496],
        [0.4861, 0.5231, 0.7596, 0.9237, 0.0845],
        [0.8157, 0.2183, 0.3708, 0.7861, 0.4896]])

I hope it answers the question!

A: A straightforward solution is to use permutation matrices (those that are usual in linear algebra). Since you seem to be interested in the 3d case, we will have to flatten your 3d tensor first. So, here's an example code (ready-to use) that I came up with
data=torch.floor(torch.rand(5,3,2)*100):float()
reordered_data=data:view(5,-1)

perm=torch.randperm(5);
perm_rep=torch.repeatTensor(perm,5,1):transpose(1,2)

indexes=torch.range(1,5);
indexes_rep=torch.repeatTensor(indexes,5,1)

permutation_matrix=indexes_rep:eq(perm_rep):float()
permuted=permutation_matrix*reordered_data

print("perm")
print(perm)
print("before permutation")
print(data)
print("after permutation")
print(permuted:view(5,3,2))

As you will see from one execution, it reorders the tensor data according to the row indexes given in perm.

A: Based on your syntax, I assume you're using to torch with lua rather than PyTorch.
torch.Tensor.index is your function, it works like below:
x = torch.rand(4, 4)
p = torch.randperm(4)
print(x)
print(p)
print(x:index(1,p:long())


text:
Q: Не работает iframe. Просто показывает белую страницу У меня есть такой код
<iframe width="800" height="400" src="landing/index.html"></iframe>

А показывает мне такое.... То есть пустой iframe. Сама страница landing/index.html, если её отдельно загрузить, нормально отображается.


text:
Q: Suddenly TPS is too high like 90K to 3000K but active session is 250 My DB application connected with pgBouncer and pgpool
Node info:

*

*3 Pgbouncer

*3 pgpool

*3 dbnode (1 is primary 2 is standby)

For pgbouncer:  default_pool_size=200 ,reserve_pool_size=10
For pgpool: num_init_children=2000 ,max_pool=4
For postgres: max_connection=29000, wal_sync_method=fsync, shared_buffer=8GB, wal_buffers=16MB,max_wal_size=8GB,min_wal_size=2GB,max_parallel_workers = 16
System: RAM: 40GB, CPU:24, SWAP:16GB
My issue is that when TPS is too high in that time suddenly my application become slow. Here my average TPS between 40K - 60K. But suddenly it is over 100K-300K where active session 200-290. I am not sure why it is happening? Is it due to slow query or configuration (pgbouncer,pgpool) issue?
Need expert opinion.


text:
Q: Filtros no Web Panel Eu fiz uma aplicação para gerenciar todos os equipamentos de TI de uma empresa, eu consigo listar quantos de cada tipo de equipamento existem no total, e também consigo mostrar só um tipo especifico, como notebooks ou desktops, mas não consigo fazer uma listagem mostrando quantos notebooks ou impressoras eu tenho em certa filial. (irei anexar prints).
Gostaria de que quando eu digitasse o nome de certa filial no segundo campo, só aparecesse os equipamentos daquela filial.
Esse é o código do meu Event Load no Web Panel na aba Events
Event Load
    &EquipQtn = count(Nome_Equipamento)
    &FilialStartCheck = (Nome_Filial)
EndEvent

Esse é o código do meu Grid no Web Panel
TipoEquipamentoNome like '%'+&EquipStartCheck.Trim()+'%';
Nome_Filial like '%'+&FilialStartCheck.Trim()+'%';

A: A primeira questão a verificar é se essa GRID é baseada em atributos ou variáveis somente. Quando a GRID é baseada em atributo o evento LOAD executa por linha, quando a GRID é baseada em variáveis somente o evento LOAD é executado apenas uma vez, isso deve ser levado em consideração no seu For each.
Existe algumas maneiras de realizar o count condicionalmente. Você pode fazer um for each manualmente filtrando a filial, ou mesmo buscar este valor de uma procedure ou um data provider. Eu faria da seguinte maneira:
Event Load
&count.SetEmpty()
For Eeach
    where Nome_Filial like '%'+&FilialStartCheck.Trim()+'%' WHEN not &FilialStartCheck.IsEmpty()

   &count += 1
EndFor
&EquipQtn = &count
&FilialStartCheck = (Nome_Filial)
EndEvent

Qualquer dúvida só comentar.


text:
Q: Python 3: Removing u200b (zwsp) and newlines (\n) and spaces - chaining List operations? I'm really stumped as to why this doesn't work. All I want to do is removing zwsp (u200b), and newlines and extra spaces from content read from a file.
Ultimately, I want to write this out to a new file, which I have functional, just not in the desired format yet.
My input (a short test file, which has zwsp / u200b in it) consists of the following:
Australia 1975
    Adelaide    2006   23,500
    Brisbane (Logan)     2006    29,700
    Brisbane II (North Lakes)   2016   29,000

Austria 1977
    Graz     1989    26,100
    Innsbruck    2000    16,000
    Klagenfurt   2008    27,000

My code so is as follows:
input_file = open('/home/me/python/info.txt', 'r')
file_content = input_file.read()
input_file.close()

output_nospace = file_content.replace('\u200b' or '\n' or ' ', '')

print(output_nospace)

f = open('nospace_u200b.txt', 'w')
f.write(output_nospace)
f.close()

However, this doesn't work as I expect.
Whilst it removes u200b, it does not remove newlines or spaces. I have to test for absence of u200b by checking the output file produced as part of my script.
If I remove one of the operations, e.g. /u200b, like so:
output_nospace = file_content.replace('\n' or ' ', '')

...then sure enough the resulting file is without newlines or spaces, but u200b remains as expected. Revert back to the original described at the top of this post, and it doesn't remove u200b, newlines and spaces.
Can anyone advise what I'm doing wrong here? Can you chain list operations like this? How can I get this to work?
Thanks.

A: The result of code like "a or b or c" is just the first thing of a, b, or c that isn't considered false by Python (None, 0, "", [], and False are some false values). In this case the result is the first value, the zwsp character. It doesn't convey to the replace function that you're looking to replace a or b or c with ''; the replace code isn't informed you used 'or' at all. You can chain replacements like this, though: s.replace('a', '').replace('b', '').replace('c', ''). (Also, replace is a string operation, not a list operation, here.)
Based on this question, I'd suggest a tutorial like learnpython.org. Statements in Python or other programming languages are different from human-language sentences in ways that can confuse you when you're just starting out.

A: As indicated by @twotwotwo, the following implementation of a .replace chain solves the issue.
output_nospace = \
file_content.replace('\u200b', '').replace('\n', '').replace(' ', '')

Thanks so much for pointing me in the right direction. :)


text:
Q: Web-based .resx file editor? I'm working on a SharePoint site, and the site eventually needs to be localized to many different languages. We can use resource files, but we'd like for the translators to be able to update those files while the site is live, without requiring developer assistance to recompile, redeploy, etc.
To me, I think the easiest way to do this would be to provide a web application to edit the .resx files as they sit in the App_GlobalResources directory. Does anyone know of some sort of a web-based .resx editor like that? I found one from LavaBlast, but it displays the values for all languages at once. With the number of languages we plan on having, I think that would eventually get unwieldy.
Any suggestions are appreciated.

A: I used the one you found: http://blog.lavablast.com/post/2008/02/RESX-file-Web-Editor.aspx  It took a couple of hours but it works a treat.  I think that having the multiple languages editable at the same time is very helpful to avoid getting your resx files out of sync, and to see blank entries easily.

A: Not a direct solution, but DotNetNuke contains a full lanaguage file editor, you might be able to extract the logic from it for your own use.

A: Microsoft released a tool called the Enterprise Localization Toolkit you might look at:
http://msdn.microsoft.com/en-us/library/aa479334.aspx
It has been ages since I played with it, but it should fit at least some of your requirements. It is easy enough for a non-techie to use. You do not edit RESX directly, however, so it might not be exactly what you need. You gen them instead and then deploy.


text:
Q: How to make unique incrementing counter in MySQL How to assign unique auto incrementing values to a certain column? Kind of like AUTO_INCREMENT does but it should be NULL at the time of insertion and assigned at some later point.
I have a table that gets regular data inserts and a few workers that process that data and set processed_at datetime field when they're done. Now I want incrementally select new processed rows since the last call. If I naively use where processed_at > @last_update_time I'm afraid there might be a situation where some records are processed at the same second and I miss some rows.
update: Can I just do
begin;
select @max := max(foo) from table1;
update table1 set foo = @max + 1 where id = 'bar' limit 1;
commit;

if foo column is indexed?

A: You can use a trigger to implement that.
CREATE TABLE my_increment (value INT, table_name TEXT);
INSERT INTO my_increment VALUES (0, 'your_table_name');

CREATE TRIGGER pk AFTER UPDATE ON your_table_name
BEGIN

UPDATE  my_increment
SET     value = value + 1
WHERE   table_name = 'your_table_name';

UPDATE  your_table_name
SET     ID2 = (
            SELECT value
            FROM my_increment
            WHERE table_name = 'your_table_name')
WHERE   ROWID = new.ROWID;
END;

But bear in mind that this trigger will work on every execution of the Update query.
You can also do it manually:
Create the table to store increment value:
CREATE TABLE my_increment (value INT, table_name TEXT);
INSERT INTO my_increment VALUES (0, 'your_table_name');

Then when you want to update the table, get the last value from this table and insert value+1 to your column needed to be incremented.


text:
Q: Why doesn't following code work for a linked list with just 2 nodes having same value? The following function deletes duplicates in an unsorted linked list. It works for all cases except when the linked list has just two nodes which have duplicate values such as 10->10>NULL
Can someone point me where I am going wrong ?
void deldup(struct node* head)
{
    struct node* outer = head;
    struct node* inner, *temp;

    while (outer->next != NULL && outer != NULL)
    {
        inner = outer;
        while (inner != NULL && inner->next != NULL)
        {
            if (inner->next->data == outer->data)
            {
                temp = inner->next;
                inner->next = inner->next->next;
                free(temp);
            }
            else
            {
                inner = inner->next;
            }
        }
        outer = outer->next;
    }
}

A: After deletion of the second 10, outer->next is null which gets assigned to outer. The next outer while loop condition tries to access outer->next first which crashes.
Solution: Reverse outer->next != NULL && outer != NULLinto outer != NULL && outer->next != NULL. Remember, the second part of a logical AND isn't evaluated if the first one is false already, eactly for scenarios like this one.


text:
Q: Question about Java's proposed value types I'm reading the Project Valhalla proposal to add value types to Java. It's arguing for explicit value types because the compiler can't automatically move allocations from the heap to the stack very well even if the objects are immutable (all fields are final) because it can't know if some code won't suddenly check the object for reference equality or try to lock on it. Object identity must be preserved, and with it heap allocation, garbage collection, and a boatload of overhead for small objects that are allocated in tight loops.
My question is why can't the object's identity be preserved on the stack as well? I mean, issue each object a unique id, and use it as its identity instead of its address. Immutable objects can then be always passed by value and never garbage collected.
It seems like a much simpler and more palatable solution than value types, even if some objects grow by another 8-12 bytes. I've used C#, and explicit value types are a pain. They add a lot of conceptual bloat to a language.

A: The stack allocation is not why this proposal is being made.  You're fixating on one minor benefit among a lengthy list of more substantial ones.  Your alternative solution has a lot of overhead, especially when some of the actual main goals of the proposal are eliminating the space overhead of an object header (8 to 16 bytes) and a reference (4 to 8 bytes), and the time overhead of the pointer dereference, when they are not needed statically.
Regarding being able to determine the stack vs heap allocation, you're probably not as good at predicting it for reference types as you think you are, and that's a good thing.  No one cares where their memory is allocated except C or C++ programmers, and they wish they didn't have to care.
Also keep in mind the JVM is used by other languages, like Scala, that already have value types and use immutable types extensively and could really benefit from the optimizations JVM support would enable.

A: Preserving identity on the stack can work.
However, the resulting JIT optimization will not be as widely-applicable as true value types. For example, value types can be stored (by inlining) as fields inside objects, in arrays, etc. Objects on the stack, meanwhile, can be stored only inside local variables of functions.
Nevertheless, if we limit the scope to optimizing transient small objects (which do occur in Java a lot), preserving identity does work. However, things get a tad hairy if we find ourselves passing the object to a context that expects a reference. (Eg, try to store it in a field.) We can allocate a heap "double" and use its address. We'll add this address to a map. Next time, we look up the object's ID in the map to get the address of the same heap double. At GC time, we'll need to check over our stack-allocated objects to know which heap doubles may be freed. What mitigates this cost is the fact that the number of local variables isn't usually large, and if we find ourselves creating many heap doubles, we can change the methods back to using heap-allocated objects.
On balance, this appears a reasonable optimization compared to relying solely on escape analysis. It would be interesting to hear why, on balance, the JIT team decided against implementing it.


text:
Q: Data structure for partitioning the integers from 0 to N into disjoint sets I require a data structure that partitions the integers from 0 to N into disjoint sets, like so:
{0, 1, 7},
{9},
{4, 5},
{6, 2, 8, 3}

With the following operations implemented efficiently (better than O(N)):
Which set does an element belong to?
0 -> [0], 8 -> [3]

Iterate over all the members of a set
[2] -> {4, 5}

Move an element to a different set
8 [3] -> [1]

Merge two sets
merge [0], [1]

Move 1 or more elements to a new set
[4] = new set {2, 4}

An obvious solution is something like:
std::vector<std::vector<int>> sets;
std::vector<int> elementToSetIndex;

but that requires many heap allocations for the vector<vector<int>>.  I'd like to use fewer heap allocations if possible.
The number of elements N will be fixed for the lifetime of the structure.

A: I was taking an algorithms class that addresses this type of problem. It is solved using a data structure they call Union-Find:
Recommended read : https://www.cs.princeton.edu/~rs/AlgsDS07/01UnionFind.pdf
Comes complete with java implementations of the UF ADT
Read even more: http://algs4.cs.princeton.edu/15uf/

A: If for the merge operation you guarantee that the values on one part of the merge all lower than the values on the other side of the merge you can do all operations on log(N) except listing the element (which is log(N) + the_number_of_elements). Example:
Merging {2, 5, 7} with {9, 10, 11} => {2, 5, 7, 9, 10, 11}
But Not: {2, 5, 7} with {4, 6}.
If this is what you want you could use a Treap: http://en.wikipedia.org/wiki/Treap
Later Edit: You can implement the treap solution for the general merge case
I'll try explaining the solution assuming you have some general knowledge of Treaps
So here's how it works:

*

*each element should represent a Treap Node. It should hold a pointer to his father and the two sons, the value itself, the randomly generated priority and the number of nodes in the subtree.

*The key of the node won't be the value (as you would expect) but the index of the node in the inorder traversal of the tree (which can be calculated in O(log n) because of our structure)

*Operation 1 : To find the treap that holds the information just go up on the treap until you reach a node that doesn't represent a value, but an entire treap (you could have a boolean field, or any other way you like). O(log n)

*Operation 2 : Just do an inorder traversal of the that specific treap, you're done (it is O(number of elements) )

*Operation 3 : Remove the node (like usual in a Treap) and insert it the specific Treap at the end (its key would be greater than the key of any other element in that Treap so it's easy). Both operations take O(log n)

*Operation 4 : This one is actually pretty easy. You merge the two treaps (with the typical merge treap algorithm) with the convention that any element on the right compares greater than every element on the left (because after the emrge every element on the right wil have a higher index in the inorder traversal than any element on the left). You're choice of who's left and who's right, it doesn't matter. Complexity: O(log N).

*

*I suspect here that by merging you mean moving everythimg from one set to the other, leaving the first one empty

*Operation 5 : Move some elements to a new set. This is equivalent to

*

*Creating a new set: Just create a new treap root O(1)

*Move every element with operation 3: O(log n) per element

A: There is a way to make the merge operation O(1) and provide amortized O(1) run-time for most of the other operations. Although, repeated merge operations can slow it down to O(M) where M is the number of merges that have been done. This is done by a lazy evaluation with a tree with no limit as to how many child nodes each node has.
The best way is to use an undirected forest graph. Where every set becomes a tree, which I'll refer to as a tree-set for clarity. Unlike most implementations of a tree-set this tree will not be a binary tree. Each node in the tree-set contains three types of links. There is a single node-supernode link if the node is not the root of the tree-set. There are also any number of node-subnode (child) links as well as any number of node-integer links. It should be made so that integers/subnodes/supernodes can be added/removed at O(1) cost for each removal. Supernodes are used to allow traversal towards the root rather than just away from it.
The operations go as followed, with nodes being labeled as letters in the examples.

*

*Which set does an element belong to?: Look up the element in the graph and go up the treeset until the root is reached keeping track of the nodes accessed along the way. Cut the links between the nodes and make it so that the element and each node directly links to the super node. For example, if the path followed was [1,A,B,C,Z], with Z being the root node of the tree-set. Then the undirected edges (1,A), (A,B), and (B,C) would be removed and replaced with edges (1,Z), (A,Z), and (B,Z) with the direct link to the root node being ignored to avoid removing it then adding it back.

*Iterate over all the members of a set: Recursively iterate over all of the integers by following subnodes. Since this iterates over all of the integers, all of the edges (regardless of type) in the tree-set can be deleted and every integer can be made to have a direct node-integer connection with the root node.

*Move an element to a different set: Look up the element in graph. Delete it's current node-integer edge and replace it with a direct node-integer edge with the root of it's new tree-set.

*Merge two sets: Each root node should keep track of the depth of the tree-set. This is used to decide which root node of tree-sets to be merged will become the root node of the merged tree-sets. The idea during a merge of k tree-sets is to make all of the root nodes of the other tree-sets direct subnodes of the root node of the tree-set with the greatest depth. This results in the new depth being the same as the max depth or the max depth plus one if there are two or more max depth tree-sets. Therefor merging tree-sets of the same depth leads can lead to having to multiply every operation cost by O(log M). The benefit is that the log is actually at least 2 rather than exactly 2 since the tree-sets are not strictly binary.

*Move 1 or more elements to a new set: Create a new root note then use that as the different set and run "Move an element to a different set", for each element to be moved. Amortized O(k) where k the number of elements to be moved.

*Copying tree-sets can be supported by allowing multiple node-supernodes links and treeing the roots at the end of each of those supernode chains separately. This approach allows for a lazy copy where the copying is done over time rather than right away. For simplicity though, it's easier to just use one super-node for every node.
Edit: I'd thought I recalled seeing this approach before. This is UnionFind with path compression implemented as a undirected graph.