text:
Q: Problems with custom module installation I am new to OpenERP, Python and PostgreSQL and I'm trying to create a custom module in OpenERP 7.
I have looked around over the Internet but cannot find a step by step guide on

how to create and install a custom module in OpenERP?

I am using Windows 7.

A: Implementation step just follow the below Link
Click to Guide Steps By Steps Module implementation
Reference link provide the implementation Stuff which is used to implement the Module in OpenERP 7.0
Follow the  Ref.Stuff for OpenERP 7.0
I hope this will helpful for you


text:
Q: mix-blend-mode sticky position I'm trying to get my Hello World to be affected by the red background color as it slides behind, how can this be achieved, if possible at all? The text should change color as the below element slide behind the text

body {
  height: 150vh;
  background: #000;
}

h1 {
  mix-blend-mode: difference;
  color: rgb(255, 255, 255);
  z-index: 2;

}

.top {
  position: sticky;
  top: 0;
  height: 50vh;
z-index: 1;

}

.bottom {
  background: rgb(232, 12, 12);
  position: sticky;
  top: 0;
  height: 50vh;
  position: relative;
  isolation: isolate;
}

Hello World

A: for the mix-blend-mode to work apply it like this

body {
            height: 150vh;
            background: #000;
          }

          h1 {

            color: rgb(255, 255, 255);
            z-index: 2;

          }

          .top {
            mix-blend-mode: difference;
            position: sticky;
            top: 0;
            height: 50vh;
          z-index: 1;

          }

          .bottom {
            background: rgb(232, 12, 12);
            position: sticky;
            top: 0;
            height: 50vh;
            position: relative;
            isolation: isolate;
          }

Hello World

some one in your comment section also said the same thing - Dai

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make sef image link with uploaded tinymce in django? I published my django site but everyday i am finding new problems :)
Today i realised my images in the article has no slugify link.
Forexample in this page https://www.endustri.io/monokristal-gunes-paneli-nedir-calisma-prensibi-avantajlari/
my tinymce settings is
{
    "height": 500,
    "entity_encoding": "raw",
    "menubar": "file edit view insert format tools table help",
    "plugins": 'print preview paste importcss searchreplace autolink autosave save code visualblocks visualchars fullscreen image link media template codesample table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists wordcount imagetools textpattern noneditable help charmap emoticons quickbars',
    "toolbar": "fullscreen preview | undo redo | bold italic forecolor backcolor | formatselect | image link | "
    "alignleft aligncenter alignright alignjustify | outdent indent |  numlist bullist checklist | fontsizeselect "
    "emoticons | ",
    "custom_undo_redo_levels": 50,
    "quickbars_insert_toolbar": False,
    "file_picker_callback": """function (cb, value, meta) {
        var input = document.createElement("input");
        input.setAttribute("type", "file");
        if (meta.filetype == "image") {
            input.setAttribute("accept", "image/*");
        }
        if (meta.filetype == "media") {
            input.setAttribute("accept", "video/*");
        }

        input.onchange = function () {
            var file = this.files[0];
            var reader = new FileReader();
            reader.onload = function () {
                var id = "blobid" + (new Date()).getTime();
                var blobCache = tinymce.activeEditor.editorUpload.blobCache;
                var base64 = reader.result.split(",")[1];
                var blobInfo = blobCache.create(id, file, base64);
                blobCache.add(blobInfo);
                cb(blobInfo.blobUri(), { title: file.name });
            };
            reader.readAsDataURL(file);
        };
        input.click();
    }""",
    "content_style": "body { font-family:Roboto,Helvetica,Arial,sans-serif; font-size:14px }",
}

And i found these codes
'images_upload_handler': 'function(blobInfo, success, failure) {
        var xhr, formData;
        xhr = new XMLHttpRequest();
        xhr.withCredentials = false;
        xhr.open("POST", "/path/to/upload/handler");
        xhr.onload = function() {
            var json;
            if (xhr.status != 200) {
                failure("HTTP Error: " + xhr.status);
                return;
            }
            json = JSON.parse(xhr.responseText);
            if (!json || typeof json.location != "string") {
                failure("Invalid JSON: " + xhr.responseText);
                return;
            }
            success(json.location);
        };
        formData = new FormData();
        formData.append("file", blobInfo.blob(), blobInfo.filename());
        xhr.send(formData);
    }',

I added these codes to my actual codes but i recieve an error like this.

This image has url like this.
How can i make this image url like endustri.io/(image or media)/image-name.webp
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAApQAAAGVCAMAAAB3pZE2AAAC2VBMVEXz8/Tz8/QoKCktLS4iQX0iRYI6OjwgNmz///8xMTMhQ38hSIchSoo2NjdYWFohPnchOnIhQn5/f4EhR4W+H3DMzM6mpqchRYQhSIYiRoPI0eEhRIJeXl9iYmTX19fIz97p6eoAAACbnaBuRO/Wi/Sf2N27f+CaPUOkapdYxS6xil1jFKrWOUWscotY5Rah2j1DpGqXWMUusYpdb5AlujV99XpgrKAAAAAElFTkSuQmCC

A: You receive these errors because the value of the property 'images_upload_handler' (Line 187) is a JavaScript function that extends over several lines. This JavaScript function is a multi line string, like the JavaString function in Line 161 for the property 'file_picker_callback'. You have to treat the JavaScript function in Line 187 the same way. Write in Line 187
    'images_upload_handler': """function(  ...

and at the end of the JavaScript functino in Line 208
    }""",

For further Details on multiline strings in Python see https://stackoverflow.com/a/10660443/5655611
Per default, TinyMCE stores images as data URL. This URL contains the data of the whole image. That's why the URL is so long. With data URLs it is possible to embed images directly into HTML. So you can save text, formatting and images i.e. all data of a single document in a single HTML file. That also has advantages.
To save the images separately:

*

*Use images_upload_url instead of images_upload_handler. That is easier.

*If you configure an images_upload_url, a file upload function is already integrated in Tiny Mce. I.e. you don't need file_picker_callback.
That means you can use the following for your Tiny Mce settings

{
    "height": 500,
    "entity_encoding": "raw",
    "menubar": "file edit view insert format tools table help",
    "plugins": 'print preview paste importcss searchreplace autolink autosave save code visualblocks visualchars fullscreen image link media template codesample table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists wordcount imagetools textpattern noneditable help charmap emoticons quickbars',
    "toolbar": "fullscreen preview | undo redo | bold italic forecolor backcolor | formatselect | image link | "
    "alignleft aligncenter alignright alignjustify | outdent indent |  numlist bullist checklist | fontsizeselect "
    "emoticons | ",
    "custom_undo_redo_levels": 50,
    "quickbars_insert_toolbar": False,
    "content_style": "body { font-family:Roboto,Helvetica,Arial,sans-serif; font-size:14px }",
    "images_upload_url": "upload-file",
}

In order for the url upload-file to work, you have to make following adjustments:
Settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

Urls.py:
urlpatterns = [
    ...
    path("upload-file", views.upload_file, name="upload_file"),
    ...
]

Views.py:
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from slugify import slugify
import os
import json
import urllib.parse
@csrf_exempt
def upload_file(request):
    file= request.FILES['file']
    filename= file.name
    filenameParts= os.path.splitext(file.name)
    slugifiedFilename= slugify(filenameParts[0]) + filenameParts[1]
    osFilename= os.path.join(settings.MEDIA_ROOT, slugifiedFilename)
    with open(osFilename, 'wb+') as destination:
        for chunk in file.chunks():
            destination.write(chunk)
    url= urllib.parse.urljoin( settings.MEDIA_URL, slugifiedFilename)
    data= json.dumps( {"location": url})
    return HttpResponse( data, content_type='application/json')

Attention:
Beware of the @csrf_exempt. It could be a security risk. See the django documentation for further information.


text:
Q: Not able to restore NuGet Packages Severity    Code    Description Project File    Line
Error       NuGet Package restore failed for project EncoreTix: Unable to find version '3.3.0' of package 'Castle.Windsor'..            0\

Image of the Error
Tried restoring it, deleting the folder and restore it. Nothing seems to help.


text:
Q: overwrite type definition of npm package I use the direct-vuex package with vuexfire. Now I need to change some type defs from the direct-vuex package for compatibility with vuexfire.
How can I do that?
It have no effect when I declare the direct-vuex module in my types file. My other type defs working fine.
declare module 'direct-vuex' {

  export type ToDirectStore<O extends AppStore> = ShowContent<{
    readonly state: ShowContent<DirectState<O>>
    getters: ShowContent<DirectGetters<O>>
    commit: ShowContent<DirectMutations<O>>
    dispatch: ShowContent<DirectActions<O>>
    original: VuexStore<O>
  }>

  type DirectActions<O extends StoreOrModuleOptions> =
    ToDirectActions<OrEmpty<O['actions']>>
    & GetActionsInModules<FilterNamespaced<OrEmpty<O['modules']>>>
    & MergeActionsFromModules<FilterNotNamespaced<OrEmpty<O['modules']>>>

  type ToDirectActions<T extends ActionsImpl> = {
    [K in keyof T]: Parameters<T[K]>[1] extends undefined
      ? (() => PromiseOf<ReturnType<T[K]>>)
      : ((payload >>>>>> Here i need to add a "?" sign <<<<<<<<<: Parameters<T[K]>[1]) => PromiseOf<ReturnType<T[K]>>)
  }
}

Thanks for help


text:
Q: Feed forward Neural Network not working in JS I am working on a project in Javascript where after the user has specified the size of the neural network and the weights, my program will create a feed forward NN that can predict the outcome of an input set based on already defined weights. My program does not train the network through backpropagation or anything else, it just takes in predefined weights to feed it through the network.
I have trained a neural network in Simbrain (Java based NN software) through backprop and i have exported the weights that resulted from training the network in Simbrain to a JS file that will input those weights when creating the NN.
My problem is that even though my neural network performs the way it's supposed to on most NN (even those with more than 3 layers) (see picture 1), but it keeps getting very different outputs from what it should be getting, according to the NN in Simbrain (see picture 2), my question therefore is, what am I doing wrong?
I have already made sure that both Simbrain and my own program use the same sigmoidal function (f(x) = 1 / (1 + 1 / e^x)), so the problem isn't that.
Any help, including help that isn't directly related to my problem but rather to neural networks in general, is greatly appreciated. Thank you for reading this far.
The constructors for the NN
function NeuralNetwork(layers /*2d array*/, weight3 /*3d array*/) {
/*
for the second test case, layers and weight3 are respectively:
[
  [0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5],
  [0,0,0,0,0,0,0,0,0,0],
  [0,0,0,0,0,0,0,0,0,0,0],
  [0,0,0]
];    , and
[
  [
    [0.8026458866414493,-4.88941104413936,-4.226087540974577,-4.530573464438122,-1.4556229469839264,-4.31689275950382,-2.598025750964335,-1.4024486094322206,-4.2746136202736595,-1.114811712353249],
    [-0.7018557602796472,-1.5899008962198744,-0.16868647158179298,-1.5305564633774085,-1.4933903630534928,-1.0700257428899125,-4.302200807112217,-1.6005131049772037,0.1368813977388942,-1.5986983805280093],
    [-0.29876796358044566,-2.4380450712541997,-1.5397608205098134,-2.3059188256916676,-1.5036183940283618,-1.7713981036865771,-1.2577757481948733,-1.7750243327951924,-1.2961124127198986,-1.6383194273199955],
    [-0.6170049336232494,-3.3128244088884964,-3.331978879084264,-3.1456639968607307,-1.2964187225461807,-2.9267790861009417,-1.9560748559032006,-1.3973642251104967,-3.4449373490550164,-1.2039858563847703],
    [0.28760582772383936,-0.029647036107864125,2.401661305865335,0.15614131284929608,0.9967571587559184,1.3920493637059834,2.053160398236636,1.560406973436222,2.5003616706837324,1.1406280698546443],
    [-1.431355486584377,-0.5254956135639378,0.585966810464151,-0.47056989178558917,-0.34719568935262807,3.0873904709552016,2.7466680699367627,-0.3183084147224785,0.4307418811280014,-0.4347019809871141],
    [4.730305578112657,2.794618188382498,2.7725054494795303,2.7971993062957767,3.0121313133902494,4.52697776884291,0.1861088251573733,3.3324377979102677,3.4776335904379945,3.220162438476049],
    [1.3365670221393215,4.151102261635236,4.448937517824129,3.818527635050038,1.1622076847092544,5.056756438356793,-4.811867833736578,1.4279903810573407,5.067869165923729,1.2084930462786259],
    [-7.653884362627585,3.4481239221814506,-1.3517036269721663,2.9744225300717084,-3.4121450698649567,-6.262463291313358,10.0,-5.000134578924327,-1.701089610696345,-4.510549176789293]
  ], [
    [0.738937123642736,1.0027735638897857,-0.4895642945264585,-0.4966409487023605,-3.411429095495459,-0.645660237498346,0.4795890293073677,-1.1530391624279934,-0.5844011923153196,-0.18971906794059312,0.24259889837466253],
    [-1.3289019929201453,-1.3846783936643814,-3.1027185772051857,-3.051664033849648,0.8551718079643078,-1.0150243513426276,-1.1322190191703165,-0.8017220694962384,-3.3343695886290257,-1.5355207800814192,-1.1708434001066501],
    [-1.2376066287024123,-1.3769667430967405,-2.301168906630486,-2.325621305132306,1.9450338961713791,-0.6571756279826005,-1.1591625309611004,-0.40914317621655133,-2.489673013800612,-1.3075292847341096,-0.9491990659165409],
    [-1.2735133823287095,-1.2998934938770366,-2.7684415870018477,-2.795194685738332,0.6119467566598199,-0.9188836490585277,-1.1200651160455346,-0.6609228479081031,-2.9594533679041617,-1.4427187863617232,-1.0109174567197428],
    [-1.3424373302583281,-1.5343976853123078,-0.9412451891990541,-0.9181715664124199,0.39356360921646094,-1.0424607517601023,-1.502583319884496,-1.0152736611391637,-0.9513379926677091,-0.8563445028619694,-1.2613129065351194],
    [1.479041505318804,1.810007067391299,-2.8023717750684107,-2.7812453328904354,-2.3035371159432065,0.03115788970802594,1.9657984684801135,-0.06598157999814092,-3.127064931997624,-0.823555626227005,1.264759264824068],
    [-2.888035414770285,-2.994031589353307,3.6767014622022303,3.6660677492715528,-9.181646436584106,-3.263884016795336,-3.88349373084228,-3.7712237821378527,4.041549967683737,-0.687691881794572,-3.4265218341885384],
    [-1.778832083041489,-2.12273644922548,-1.0963638066243724,-1.030260217185849,1.1187575804787673,-1.2409528854652865,-2.1738688894809637,-1.2743917544089247,-1.107812865029798,-1.0629428830636494,-1.7751739289407722],
    [-1.004719873122501,-1.0443553807939716,-2.577499515628139,-2.5776692043229663,2.9709867841159,-0.5274719498845833,-0.843890283520379,-0.20671418403893513,-2.7179118826886026,-1.306839176041484,-0.7570735658813299],
    [-1.6272666988539848,-1.827183409776364,-0.9438773753269729,-0.9435987081211876,0.7660203923230526,-1.2259095997120846,-2.031459716170598,-1.3231868095404185,-0.9964657871022223,-0.9165692090752512,-1.58444425796673]
  ], [
    [3.725973720696792,-1.6646641113226457,-2.690673963411094],
    [3.800277429998268,-2.085738176798833,-2.63291827658551],
    [3.9016422516515155,2.0672177107134138,-3.855168383990615],
    [3.8880037099581446,2.1381928663964778,-3.8429910059416983],
    [-1.162825551537172,2.35558424769462,-2.2926681297161076],
    [2.9764021713068542,0.3197129292281053,-2.8308532112377027],
    [3.820130175045188,-1.7806950056811943,-3.106860347494969],
    [2.967938499849539,0.8691409343754017,-3.130904551603304],
    [4.0701841361555715,2.228471656300074,-4.053369245616366],
    [3.2231153003534962,0.9718378272580407,-2.658010203549737],
    [3.4876764892680967,-1.2622479268130227,-2.870582831864283]

  ]
];
I copied these directly from the simbrain weights matrices.
*/
this.layers = [];
  for(var i = 0; i < layers.length; i++) { // the creation of the layers
    this.layers.push(new Layer(layers[i]));
  }
  for(var f = 0; f < layers.length - 1; f++) { // the creation of the connections between neurons of different layers, uses predefined weights
    this.layers[f].connectLayers(layers[f + 1], weight3[f]);
  }
  /*this.getChances = function(neuron, layer) { // this function isn't important
    var total = 0;
    for(var g = 0; g < layer.neurons.length; g++) {
      total += layer.neurons[g].value;
    }
    var prob = layer.neurons[neuron].value / total * 100;
    var decOdds = 100 / prob;
    return [(prob).toFixed(2), decOdds.toFixed(2)];
  } */
  this.reset  = function(values) { // reset the neuron values
    for (var i = 0; i < this.layers.length; i++) {
      for (var t = 0; t < this.layers[i].neurons.length; t++) {
        this.layers[i].neurons[t].value = values[i][t];
      }
    }
  }
  this.run = function() { // the main function that will make the NN predict
    for (var t = 0; t < this.layers.length; t++) { // for each layer
      if(t !== 0) { // if not the first layer (input shouldn't be activated)
        this.activate(t);
      }
      if(t !== this.layers.length - 1) { // if not the last layer (the output cannot preActivate a layer that comes after it)
        this.preActivate(t); // this affects the layer that comes after it
      }
    }
  }
  this.preActivate = function(t) { // multiply the weights by the value of the neurons and add the result to the next layer (pre activation)
    for (var p = 0; p < this.layers[t].neurons.length; p++) { // for the neurons in the current layer
      for (var v = 0; v < this.layers[t].neurons[p].weights.length; v++) { // for the weights of the current neuron (the amount of weights is equal to the amount of neurons in the next layer)
        this.layers[t + 1].neurons[v].value += this.layers[t].neurons[p].weights[v].value * this.layers[t].neurons[p].value; // increment the neurons in the next layer
      }
    }
  }
  this.activate = function(t) { // take the sigmoid for each neuron in the current layer (activation)
    for (var hp = 0; hp < this.layers[t].neurons.length; hp++) {
      this.layers[t].neurons[hp].value = this.sigmoid(this.layers[t].neurons[hp].value);
    }
  }
  this.sigmoid = function(x) { // the sigmoidal function
    return 1 / (1 + 1 / pow(Math.E, x));
  }
}

function Layer(neurons /*1d array*/, weight2 /*2d array*/) { // create a new layer
  this.neurons = [];
  for(var i = 0; i < neurons.length; i++) {
    this.neurons.push(new Neuron(neurons[i]));
  }
  this.connectLayers = function(targetLayer /*1d array*/, weight2 /*2d array*/) { // create the connections
    for(var f = 0; f < this.neurons.length; f++) { // for each neuron in its own layer
      for(var t = 0; t < targetLayer.length; t++) { // for each neuron in the next layer
        this.neurons[f].weights.push(new Weight(weight2[f][t])); // get the weight from the predefined set and make it the value of that weights
      }
    }
  }
}

function Neuron(value /*float*/) {
  this.value = value;
  this.weights = [];
  this.x; // for drawing on a canvas
  this.y; // for drawing on a canvas
}

function Weight(value /*float*/) {
  this.value = value;
  this.x; // for drawing on a canvas
  this.y; // for drawing on a canvas
}


text:
Q: Predicate should concatenate and reverse, but always returns false I am new at Prolog and just started practising the built-in list predicates. So I was trying to write a code that concatenates two lists and order them descending(reverse them). The problem is that the code always returns false, and I have no idea why it doesn't return what I am expecting.
reverse(append([6,5,4],[3,2,1]),Y).
Also tried:
reverse(append([6,5,4],[3,2,1],X),Y). & reverse(append([6,5,4],[3,2,1],X),X).
But none of them actually worked. I would be thankful if someone can tell me the solution.


text:
Q: Launch a pdf file from java I am trying to open a pdf file from the following code.
try {
         String currentDir = System.getProperty("user.dir");
         currentDir = currentDir+"/Report.pdf";
         System.out.println("Current dir using System:" +currentDir);
         if ((new File(currentDir)).exists())
             {
         Process p = Runtime
         .getRuntime()
     .exec("rundll32 url.dll,FileProtocolHandler " +currentDir);
     p.waitFor();
     }
         else
             {
        System.out.println("File is not exists");
     }
    System.out.println("Done");
}
    catch (Exception ex)
        {
    ex.printStackTrace();
    }

The print statement gives me the correct path of the file , i.e
Current dir using
System:/Users/mshariff/NetBeansProjects/javaGUIbuilding/Report.pdf
but the program is giving the following error.
java.io.IOException: Cannot run program "rundll32": error=2, No such file or directory

I am using Mac OSX & Netbeans.

A: The solution you have at hand will only work an Windows (rundll32 is a Windows command)
Instead, you should take advantage of Desktop API
For example...
public static void main(String[] args) {
    try {
        Desktop desktop = Desktop.getDesktop();
        if (desktop.isSupported(Desktop.Action.OPEN)) {
            desktop.open(new File("Your.pdf"));
        } else {
            System.out.println("Open is not supported");
        }
    } catch (IOException exp) {
        exp.printStackTrace();
    }
}


text:
Q: Rails LEFT OUTER JOIN to load multiple models I have a model called Entry that has_many :entry_states. EntryState has an attribute called :read.
I want to get all entries whether or not there is an entry_state so I think a LEFT OUTER JOIN is the best way to go see Left outer join on Coding Horror
However I also want to include an attribute of EntryState in the result. So I have a query that looks like:
entries = Entry.select('entries.*, entry_states.read').
joins("LEFT OUTER JOIN entry_states ON entries.id = entry_states.entry_id AND entry_states.user_id = #{user_id}")

The problem with this is the entry_states object is not available after this.
I can get the read state like:
entries.first.read
>> t

Which gives me the raw column value, but this is a boolean column so it would be great to get back true or false
What would be even better is if I could get the whole EntryState object. I've tried using .includes(:entry_state), but I have not found a way to include the outer join condition of AND entry_states.user_id = #{user_id}


text:
Q: Location of the resource files for the spinning wait cursor? For a presentation I am making, I want to find my Mac's system's default "Spinning Wait Cursor" resources.
I was told that the cursors are in here:
    /System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/HiServices.framework/Versions/A/Resources/cursors
and here:
    /System/Library/Frameworks/WebKit.framework/Versions/Current/Frameworks/WebCore.framework/Resources/
Indeed, one can find some large and vectorized versions of most cursors in the first folder, and some other, smaller ones in the second.
But, there seems to be no beach ball in there.
I know one can find the graphics in high resolution online easily, but for my project I would need to get the original system files.
A screenshot or animated screenshot also wouldn't be what I'm looking for. I couldn't find the info anywhere.
Note 1:
From the GUI, a user can see the spinning wait cursor in various different sizes depending on the settings in System Preferences > Accessibility > Display > Cursor size, and then proceeding to crash their computer.
Note2:
I am not trying to change my OS' appearance.
Can anyone help me find where the resource is?
Is it hardcoded like the startup chime?

A: Cursors are rendered using CoreGraphics
The Wait Cursor or what is sometimes affectionately know as the "spinning beachball of death" is rendered in CoreGraphics (Apple's 2D rendering engine). Meaning, they are generated on the fly depending on what your preferences are set to (i.e. cursor size).
The CoreGraphics file is located at /System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/CoreGraphics.framework/Versions/A/CoreGraphics
From my research I was able to find the parameters for the Wait Cursor: $23766C - $23D66C"
As far as working with images stored in CoreGraphics, I can point you to this tutorial:  Core Graphics on OS X Tutorial
Static Images of Wait Cursor
There is a directory that has static images of the cursors:
/System/Library/Frameworks/GLUT.framework/Versions/A/Resources
Within that directory you will find a number of TIFF files.  The specific file is waitCursor.tiff
Opening the file with preview (open waitCursor.tiff) yields the following graphic (it's quite small):

How I located the file....
The El Capitan cusors link you provided had broken img src links, so I used the one for Yosemite for reference as they are pretty much the same.  The icon you wanted is called the "Wait cursor."
So, using the find command in Terminal, I executed the following:
find /System -iname waitcursor*

The command basically says starting from the /System directory, look for all files with the name "waitCursor" in it regardless of case.
I guessed the format of the name from the file naming conventions in the directory you initially provided.  For example, the "Resize Down" cursor was called "resizedown".

A: Here's the El Capitan spinning beachball from materialup.com

A: On macOS Catalina, they are stored as PDF files:
/System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/HIServices.framework/Versions/A/Resources/cursors
Animated cursors are stored as static, vertical sprite sheets, that you need to manually convert to GIFs.
I extracted the cursors from CoreGraphics myself. You can download them here, as TIFF files.
UPDATE: I updated the Google Drive link to include all cursors in Big Sur.
Another answer here mentions /System/Library/Frameworks/GLUT.framework/Versions/A/Resource, which appears to be static images of cursors from NeXTSTEP, not macOS cursors, but close.


text:
Q: Authlogic gem: use last_request_at column at session level not in user level Problem: If I logged in as the same user on two devices(say A and B) and I use my application in one device(A) whereas the other device(B) remains inactive. The device B does not logout when the session expires while using feature logout_on_timeout.
I am trying to implement logout_on_timeout feature of authlogic gem, which I successfully implemented but the problem is authlogic updates the last_request_at attribute of User in every request no matter the browser or devices where it logged in. So if I logged in the same user from mobile as well as from desktop and one of the device is active then the other device remains active too because it uses the same shared last_request_at attribute from User.
Reference code from authlogic gem: lib/authlogic/acts_as_authentic/logged_in_status.rb

        # Returns true if the last_request_at > logged_in_timeout.
          def logged_in?
            unless respond_to?(:last_request_at)
              raise(
                "Can not determine the records login state because " \
                  "there is no last_request_at column"
              )
            end
            !last_request_at.nil? && last_request_at > logged_in_timeout.seconds.ago
          end

So How can I solve this problem? Is there any way to implement it at the session-level? Like using last_request_at in UserSession model.

A: I decided to not use the logout_on_timeout feature but rather use the remember_me feature then override the remember_me_for method in UserSession and set the dynamic value. Because logout_on_timeout uses last_request_at attribute value from the User to check if session timeout or not, and last_request_at is shared in all session, so When a user opens an app in two devices then both will remain active if one of them is active(kinda incomplete feature or bug maybe).
Also, update the session(ActiveRecord::SessionStore::Session) for the current user and change the session's data column value with the generated value from instance method generate_cookie_for_saving of UserSession at the end of each request because authlogic only update the session only when creating or deleting the UserSession.
Note: I am using activerecord-session_store gem to persist session in the database.


text:
Q: mongoose Index not created when the function schema.index({ "name": "text" }); used enter image description here
enter image description here
schema.index({ "$**": "text" });
schema.index({ "name": "text" });

A: you can use
const mongoose = require("mongoose");
const adminSchema = mongoose.Schema(
 {
  name: { type: String, unique:true }// you can create index here also

 }


text:
Q: What are the differences between "The spacecraft / airplane flew into the air" & "The spacecraft / airplane flew into the sky"?
the air:  the space above the ground or around things
into the air
Flames leapt into the air.
through the air
He fell 2,000 metres through the air without a parachute.

sky /skaɪ/ ●●● S2 W2 noun (plural skies)
1 [singular, uncountable] the space above the Earth where clouds and
  the Sun and stars appear
The sky grew dark, and a cold rain began to fall.
A shooting star sped across the night sky.
in the sky
There wasn't a cloud in the sky.

So I would say "The spacecraft flew into the air" when it was off the ground a bit not too high. Whereas, "The spacecraft flew into the sky" when it was off the ground very high, maybe above the cloud.
What are the differences between "The spacecraft / airplane flew into the air" & "The spacecraft / airplane flew into the sky"?

A: Idiomatically, there isn't really a difference. People do say "up in the air" to refer to the sky. Technically though, there is air all around us; whereas the sky is above the ground.
Phrases like "it soared into the air" are perfectly idiomatic, but so are phrases like "go into the open air" to simply mean "go outside".
"The sky" always refers to the area up above the earth. Planes fly in the sky, and when you are on a plane you might say you are "up in the sky".
So there is a difference, but you can use either in your context, and they should be understood.

A: Technically, "air" is a substance, while "sky" is a place. You could say, "I filled the test tube with air", but you wouldn't say, "I filled the test tube with sky." Or even in a more common sense, you could say "The air in this room smells bad", but you wouldn't say "The sky in this room smells bad." Conversely, it would be perfectly valid to say, "On the Moon there is no air in the sky."
But that said, people do sometimes use "air" to mean something like "the outdoors above the ground". Like people will say, "I saw a plane flying through the air."
As I think about how people use the words idiomatically, I suppose that "air" can mean anywhere outside, but "sky" usually means high above your head. Like you could say, "The frog jumped into the air" if he jumped 12 inches. But you wouldn't say, "The frog jumped into the sky". Not unless you were trying to make a poetic exaggeration.


text:
Q: Remove duplicate values in csv files I have a csv file wit values like
68,68
70,70
80,90

Here i would like it to remove the duplicates i.e. give the output
68
70
80,90

Or
 68,
 70,
 80,90

But i tried searching everywhere and was not able to find how to do this

A: Depending on the size of your input, a naive approach could be fine:
$ cat test
68,68
70,70
80,90
$ cat readvals.py
#! /usr/bin/env python
import csv
vals = [] # a list for the entire file
with open('test') as infile:
    lines = csv.reader(infile,delimiter=',')
    for i, line in enumerate(lines):
        vals.append([]) # append a sub-list for this row.
        for val in line:
            if val not in vals[i]:
                vals[i].append(val) # add values for the row
print(vals)
$ python readvals.py
[['68'], ['70'], ['80', '90']]

A: For removing duplicate rows I use this code.
import pandas as pd

df = pd.read_csv('myfile.csv')

df.drop_duplicates(inplace=True)

df.to_csv('myfile.csv', index=False)

A: i would suggest you to have a look at these below since its not clear about your requirement.
pandas documentation:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html
Example ref: https://www.journaldev.com/33488/pandas-drop-duplicate-rows-drop_duplicates-function


text:
Q: How to make background and border entire viewport but keep content inside container How would I make the background colour and border stretch the entire viewport width but keep the content inside the container.
https://jsfiddle.net/DTcHh/7808/
So basically I need the background and border to stretch the entire viewport width but keep the content inside the different colours
HTML:

                    something will go in here

                    something will go in here

                something will go in here

CSS:
@import url('//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css');

header .col-sm-8, header .col-sm-4, header .col-sm-6 {
    padding: 0;
}

.green {
    background: #f4f9f5;
    border-top: 7px solid #a9cab3;
    border-left: 7px solid #a9cab3;
    height: 150px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.blue {
    background: #c9dee3;
    border-top: 7px solid #70c9d9;
    height: 150px;
    display: flex;
}

.blue .col-sm-6 {
    display: flex;
    justify-content: center;
    align-items: center;
}

A: Hope this is what you were looking for!
HTML:

                        column 1.1

                        column 1.2

                    column 2.1

CSS:
@import url('//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css');

header {
    padding: 0;
}

.container {
    width: 100%;
}

.green {
    background: #f4f9f5;
    border: 7px solid #a9cab3;
    height: 150px;
    text-align: center;
}

.blue {
    background: #c9dee3;
    border: 7px solid #70c9d9;
    height: 150px;
    text-align: center;
}


text:
Q: Display image based on a query result in asp GridView i am looking for a way that:
If the Gridview contains a result, don't show the result but instead an clickable image that will direct me to a new page with the result(this i guess in the properties of the image).
And if the gridview is empty, then display another image.
I know how to do it if the gridview is empty i use
But i would like to know how to show an image if gridview is not empty.
Any ideas?
Thanks

A: <a href='<%# String.Format("{0}{1}{2}{3}{4}{5}{6}  {7}8}",Eval("CourseName"),"/","Colleges","/",Eval("StateName").ToString().Replace(" ", "-"),"/",Eval("CityName").ToString().Replace(" ", "-"),"/",Eval("CollegeName").ToString().Replace("-", "=").Replace(" ", "-").Replace("..","--")) %>' rel="canonical" title='<%# Eval("CollegeName")%>'>
            <img Height="50px" ImageUrl='<%# String.Format("{0}{1}","\\images\\CollegeImages\\" , string.IsNullOrEmpty(Eval("CollegeImage").ToString()) ?"noImageCollege.jpg":Eval("CollegeImage")) %>' Width="50px" alt='<%# Eval("CollegeName") %>' title='<%# Eval("CollegeName") %>' />


text:
Q: Why is long-term relative frequency used to predict the probability of the event occuring in a single trial? I am a beginner statistics student learning probability from a frequentist perspective. I am confused on the application of a 'probability' to the real world.
Probability is the relative frequency of an event, performed over a very large (theoretically, infite) trials. My question: how is this useful when trying to predict the outcome of the random process in a single trial?
For example, having a dice land on one has a probability of $\frac 16$. That's fine if we want to predict the chance of landing a one over a large number of dice rolls, but it's not accurate for predicting the outcome of the dice roll in a single roll.
So my question is what is the rationale of using long-term relative frequency for the chance of a single repetition of the experiment to predict an event? Is it just the 'best guess' we have?
I know logically it may just be the 'best guess' we have, but intuitively it's not clicking for me. An intuitive explanation would help with as much minimal math language as possible!
Edit: To clarify, this is my confusion. The relative frequency of landing on a one in (for example) 6 rolls of the dice is NOT equal to 1/6 nor does it have to come near 1/6. It only comes close to 1/6 after a large number of trials.
So my question is in one trial/roll of the dice why is 1/6 the best prediction we have for estimating the probability of landing a 1? Is it because the long-term relative frequency is about the best guess we have for the outcome of any single trial? Is there more to this than it just being the best guess?

A: Let $X\sim \textrm{Bernoulli}(p)$, assume $p$ not known. If we have IID samples $X_1,X_2,...,X_n$ and $N_1$ the total count  of successes then the 'most likely' (maximum likelihood) $p$ is given by the argument maximizing the joint probability of the outcomes (they are IID so you just multiply the pmfs):
$$p_n^*=\max_{p \in [0,1]}\prod_{k=1}^n(p\mathbb{I}_{\{1\}}(X_k)+(1-p)\mathbb{I}_{\{0\}}(X_k))=\max_{p\in [0,1]}p^{N_1}(1-p)^{n-N_1}$$
If $0<N_1<n$ we set the derivative to $0$
$$\frac{d}{dp}p^{N_1}(1-p)^{n-N_1}=\frac{(1-p)^{n-N_1}p^{N_1-1}(np-N_1)}{p-1}=0$$
$$\implies p^*_n=\frac{N_1}{n}$$
otherwise $p^*=0$ if $N_1=0$ and $p^*=1$ if $N_1=n$. This is the relative frequency of successes in our sample. Now we have for example
$$E[p^*_n]=\frac{np}{n}=p$$
$$P(|p^*_n-p|>\varepsilon)\leq\frac{1}{\varepsilon^2}E[|p^*_n-p|^2]=\frac{1}{\varepsilon^2}\textrm{Var}[p^*_n]=\frac{p(1-p)}{\varepsilon^2n}\stackrel{n \to \infty}{\to} 0$$
So it has desirable properties and we use $p^*_n$ to estimate $p$ in frequentist stats. In other words $p^*$ is not the probability $p$ per se but the probability of $|p^*_n-p|$ being greater than arbitrary $\varepsilon>0$ goes to $0$ in the limit $n \to \infty$.

A: Having a fair die (i.e. equally weighted on all sides) land on "one" has a probability of $\frac16$. That's fine if we want to predict the chance of landing a "one" over a large number of dice rolls, and it's also accurate for predicting the outcome of the die roll in a single roll.  Probability can be defined as the chance of the stated outcome divided by the total number of possible outcomes. The probability of a fair die landing on an even number is $\frac36 = \frac12$ since there are three even numbers on a total of six sides.  The chance of flipping heads on a fair coin is $\frac12$ since there are two sides and only one is heads.  The frequencies of observed observations represent the sample outcome which may not be equal to the underlying population outcome.


text:
Q: How to copy files containing certain string using Shutil? I've been tasked with writing a very simple script but I can't for the life of me figure out how to...
All I need to do is use the module Shutil to copy all files that contains "Tax_" from ~/Documents folder to my current working directory.
import shutil
import os

src = os.path.expanduser('~/Documents/Tax 2018')
dst = os.getcwd()

for files in src:
    if 'bdd' in files: # also tried: if files.startswith("Tax_")
        shutil.copy(files,dst)

Does not work. We were also given the option of finding files with Shutil.which("Tax_") but that simply doesn't work.

A: You can try something like this:
from glob import glob

for file in glob('~/Documents/Tax 2018/Tax_*'):
    shutil.copy(file, dst)

glob will return a list of file matching the wildcard pattern, int his case those files Starting with Tax_ on the given path.

A: Maybe something like this will work for you. It asks you for the input directory and then asks you where you want to save the files. If the save directory does not exist then it is created, if the save directory already exists then it simply continues. The final input() function is just there to leave up the python console so you can see it has finished.
The benefit of using shutil.copy2 is that it attempts to preserve the metadata of the files.
Also depending on how your files are named, you weren't very specific you may need to slightly alter this line if 'tax_' in file.lower():.
import shutil
import os

input_dir = input('Please enter directory that contains that tax files.\n')
output_dir = input('\nPlease enter the path where you want to save the files.\n')

for file in os.listdir(input_dir):
    if 'tax_' in file.lower():

        if not os.path.exists(output_dir):
            os.makedirs(output_dir)

        shutil.copy2(os.path.join(input_dir, file), os.path.join(output_dir, file))

input('\nFinished --> Files are saved to %s' % output_dir)  # format() or f strings are ideal but not sure which python version you have

A: Make sure to give the files a file type and hopefully this will work for you:
#!/usr/bin/env python3

#Imports
from shutil import copyfile
import shutil
import os

# Assigning the variables to search and the location
file_str = "Tax_201"
search_path = os.path.join(os.path.expanduser('~'),'Documents')

# Repeat for each file in the search path
for filename in os.listdir(path=search_path):
    # Check if the file starts with Tax_2018
    if filename.startswith(file_str):
        # Assigning the variables for the src and destination
        path_src = os.path.join(os.path.expanduser('~'),'Documents', filename)
        path_destination = os.path.join(os.path.expanduser('~'),'Documents', 'Taxes', filename)
        # Copy the file that matched the file_str
        shutil.copyfile(path_src, path_destination)
    else:
        # Stop the loop
        break

Output

Documents/
├── Taxes
├── Tax_2018.txt
├── Tax_2019.txt

Documents/Taxes/
├── Tax_2018.txt
├── Tax_2019.txt

A: Please try:
import glob
import os
import shutil

dst = os.getcwd()
str_target = 'bdd'     # OR 'Tax_'

f_glob = "~/Documents/Tax 2018/{}*.txt".format(str_target)
ls_f_dirs = glob.glob(f_glob)

for f_dir in ls_f_dirs:
    shutil.copy(f_dir, dst)


text:
Q: Importing data from Postgres using OLE DB source not showing all data I am using OLE DB source to import data from a Postgres database to SQL Server database using OLE DB Destination. When I execute the package, it is running successfully.
Eventhough it is saying 'N' number of records are written to OLE DB destination, I couldn't find all  records always in PostgreSQL DB destination table. There are no error records.
Like for example I query my Employee table in  Postgres :
EmpId Name PositionId
10    Bob  1
25    Alex 2
54    Mary 22

When I try to visualize data in the OLE DB Source with a connection manager pointing to Postgres, I only find :
EmpId Name PositionId
10    Bob  1
54    Mary 22

I can't find the record :
EmpId Name PositionId
25    Alex 2

A: I ended up using ODBC Postgresql Connection :

*

*I configure a PostgreSQL connection in the ODBC Administration Tool.

*I chose the correct version acc(32/64 bit) and opened the ODBC
Administration Toollike below :

*

*I chose the Add button:

*

*I selected the PostgreSQL Unicode driver and Clicked Finish. It will open
up the following window. I fill the fields according to the database
related properties that I have.


text:
Q: Unable to connect to kafka MSK using segmentio/kafka-go I am trying to create a function that checks if a topic exists in my AWS MSK
func KafkaTopicExist(kafkabroker string, topic string) bool {
conn, err := kafka.Dial("tcp", kafkabroker)
if err != nil {
    log.WithError(err).Warn("Kafka broker connection error")
}
defer conn.Close()

partitions, err := conn.ReadPartitions()
if err != nil {
    log.WithError(err).Warn("Can not get all partitions to obtain ")
}

m := map[string]struct{}{}

for _, p := range partitions {
    m[p.Topic] = struct{}{}
}
_, exists := m[topic]
return exists

}
kafkabroker is a string that takes MSK TLS private endpoint. I get a connection error.
while using PLAINTEXT endpoint works.
am I missing something is the config?


text:
Q: Device runs out of disk space during In-App Purchase download Apple's documentation talks about handling the situation where a user runs out of disk space while downloading your In-App-Purchase content

Ensure that your app handles errors gracefully. For example, if the
  device runs out of disk space during a download, give the user the
  option to discard the partial download or to resume the download later
  when space becomes available.
https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/StoreKitGuide/Chapters/DeliverProduct.html

But give no examples or clue at the best practise.
What is the best way to firstly recognise that they have run out of disk space during a download and secondly how to resume the download later when space becomes available?

A: A good UI tells the user about the state of the app.  While the app is downloading, it's incumbent on the app to let the user know that's happening.  The simplest error check would just check for failure of any sort and report the most specific error possible.
The next more proactive idea would be to check for failures as above, but add the check for disk space to give a more specific error.
If you know a lot about the download size, like a minimum size, then you could check space even more proactively before the download begins.  The situation to avoid (if you have foreknowledge) is a long, large, partial download followed by a disk space error that was predictable earlier.


text:
Q: why cant ubuntu 14.04 install on my windows 8.1 please can you tell me how to install ubuntu on my windows 8.1 ive tried to install with the disk. But its not installing its saying missing file from the disk but it installed on another laptop.

A: What model of computer do you have? What OS was the second computer? windows 8.1 uses UEFI to start up, which is different from an older OS, which would use BIOS.

A: if you having license version of windows 8.1 than you might be not installing Ubuntu.
you might be install Ubuntu using wubi.
Help for Wubi
I hope this will help you to solve your problem.


text:
Q: I want to use the condition of the match statement in Rust to do "0..=a+5" I would like to use Rust's match statement to process variables differently when they are in an arbitrary range and in other cases. In that case, the code would look like this:
// idx is usize variable
// num is usize variabel

let res: Option<f64> = match idx {
    1..=num-5 => {
        Some(func())
    },
    _ => None,
};

But I receive an error:
error: expected one of `::`, `=>`, `if`, or `|`, found `-`
  --> src/features.rs:34:22
   |
34 |         1..=num-5 => Some(func()),
   |            ^ expected one of `::`, `=>`, `if`, or `|`

A: You can check the dynamic range over a match guard:
fn main() {
    let idx = 6;
    let num = 15;
    let res = match idx {
        n if (1..=num - 5).contains(&n) => Some("foo"),
        _ => None,
    };
    println!("{:?}", res);
}

Playground

A: Runtime values cannot be referenced in patterns. Also you cannot make operations.
Use const instead
const num :i32 = 19 - 5;

let res: Option<f64> = match idx {
    1..=num => {
        Some(func())
    },
    _ => None,
};


text:
Q: Java, even number of even digits, odd number of odd digits This program is essentially a game where the user must enter numbers to see which numbers are good: numbers with an even number of even digits, and an odd number of odd digits.
So first of all, the program ends when I enter a one digit number, which is not intentional. I assume that has something to do with the while being while (n > 0). There also is likely an issue with the if (numEven % 2 == 0......) because the print results seem almost random, with a number being good and the same number not being good sometimes.
Honestly, I am lost at this point. Thank you so much in advance for any help.
UPDATE: This code is working how I want it to, I just wanted to thank everybody who helped out! It's my first semester of computer science class, so I'm still rather new at this...excuse my mistakes that were likely pretty stupid :)
package quackygame;
import java.util.Scanner;
public class QuackyGame
{
    public static void main(String[] args)
   {
       System.out.println("Welcome to the Number Game!"
                + " Try to figure out the pattern "
                + "in the numbers that Wallace likes!");

        Scanner scan = new Scanner (System.in);
        int n;
        int numEven = 0;
        int numOdd = 0;
        boolean isEven;

        do
        {
           System.out.print("Enter a number > 0: ");
           n = scan.nextInt();
           while (n > 0)
           {
               if (n % 2 == 0)
                 {
                   //n is even
                   isEven = true;
                   numEven++;
                 }
                else
                 {
                   //n is odd
                   isEven = false;
                   numOdd++;
                 }
               n /= 10;
           }
           //if numEven is even and numOdd is odd
           if (numEven % 2 == 0 && numOdd % 2 == 1)
               System.out.println("Wallace liked your number!");
           else
           {
               System.out.println("Wallace didn't like your number.");
           }
           numEven = 0;
           numOdd = 0;

        }

        while (n >= 0);
    }

}

A: There are a few core issues in the code based on the desired results that you described. The most glaring issue I see is that you intend for the game to essentially "start from scratch" at the beginning of each round, but you never actually reset the numEven and numOdd variables. This is the source of your print results seeming random. For example, if you started a game and input the number:
34567
The game would process the number and say that it is a favorable number because it is odd, has an odd number of odd digits (3), and has an even number of even digits (2). However, upon playing the game again, it would execute the same code without setting the variables back to 0, which means that upon entering:
34567
The game would process this number as a bad number because the accumulated value of odd digits would be 6 instead of 3 (since 3 the first time + 3 the second time results in 6), and 6 is even. So what we want to do is this:
...

int n;

do
{
    int numEven = 0;
    int numOdd = 0;

    System.out.print("Enter a number: ");
    n = scan.nextInt();

...

By placing the numEven and numOdd declarations inside of the "do" block, they are local variables which only exist for the duration of the do block. We could also do something as simple as this:
...

    else
    {
        System.out.println("Wallace didn't like your number.");
    }
    numEven = 0;
    numOdd = 0;
}
while (n > 0);

...

Just resetting the values will help us to keep track of the actual intended values of numOdd and numEven more consistently.
With regard to the program closing when you input a single digit number, I'm not sure. That doesn't make sense because since it is a do-while loop it should at least execute once, and issue one of the print statements. I'm loading this code into my IDE right now to give it a run through. I'll update my answer if I find something.
-EDIT-: Upon reading your question again, it seems that you may not be suggesting that the program closes before actually completing any of its functions, but simply that it closes at all. The reason for the closing of the program is that you are performing an integer division arithmetic function where you probably want to be using a different type of number. Let me explain:
In normal human counting, we have our natural set of numbers which have no decimal points. They usually start like this:
1, 2, 3, 4, 5 ...
Then we have a separate set of numbers for math where we operate with more precision:
0.5, 1.4232, 3.142 ...
When we are talking about numbers with normal human language, we assume that dividing 1 by 2 results in 0.5. However, computers do not implicitly know this. In order for a computer to reach the conclusion "0.5" from the division of 1 by 2, you need to explicitly tell it that it should use a certain type of number to produce that output.
The "normal" numbers I referenced earlier are most loosely related to the integer in programming. It's basically a number without a decimal point. What that means is that whenever you divide two integers together, you always get another integer as the result. So if you were to divide 1 by 2, the computer would not interpret the result as 0.5 because that number has a decimal. Instead, it would round it down to the nearest integer, which in this case is 0.
So for a more specific example referencing the actual question at hand, let's say we input the number 5 into our program. It goes through all of the calculations for odds and evens, but eventually gets to this line:
n /= 10

This is where things get funky. We are dividing two integers, but their result does not come out as a perfect integer. In this case, the result of 5 / 10 is again 0.5. But for the computer, since we are dividing two integers, the result 0.5 just won't do, so after rounding down to the nearest integer we get 0. At this point, there is one fatal mistake:
(while n > 0);

When we perform this check, we get false and the while loop ends. Why? Because after performing n /= 10, n becomes 0. And 0 is not greater than 0.
How can we fix this? The best thing to do is probably just use a floating point number to perform the calculations. In Java, this is pretty easy. All we really have to do is:
n /= 10.0

When Java sees that we are dividing by 10.0, which is not an integer, it automatically converts "n" to a floating point number to divide by 10.0. In this case then, if n is 5, our result in dividing 5 by 10.0 will be 0.5. Then, when we run:
(while n > 0);

This becomes true! And the loop does not break.
I am going to put all of these changes into my IDE just to confirm that everything is working as intended for me. I would suggest you give it a try too to see if it fixes your problems.
Hope this helps.

A: You are increasing numEven or numOdd count each time you input a number, and then you use if (numEven % 2 == 0 && numOdd % 2 == 1) , it is random because if you put number 33 for the first time => numOdd = 1; => true => "Wallace likes" , but next time you put 33 for the second time  => numOdd = 2; => false => "Wallace doesnt like".
Edit* Maybe you wanted something like this?
public static void main(String[] args)
{
       System.out.println("Welcome to the Number Game!"
                + " Try to figure out the pattern "
                + "in the numbers that Wallace likes!");

        Scanner scan = new Scanner (System.in);
        int n;
        boolean isEven;

        do
        {
           System.out.print("Enter a number: ");
           n = scan.nextInt();

           //if 0, you leave the loop
           if(n==0) {
               System.out.println("You pressed 0, have a nice day");
               break;
           }
           if (n % 2 == 0)
           {
               //it is even
               isEven = true;
           }

           else
           {
               //it is not even
               isEven = false;
           }

           //if even then he likes it, otherwise he does not
           if (isEven)
               System.out.println("Wallace liked your number!");
           else
           {
               System.out.println("Wallace didn't like your number.");
           }

        }
        //put any contition here, lets say if you press 0 , you leave the loop
        while (n != 0);
    }


text:
Q: Numpy complicated data structure I'm quite new to python. What I would like to do is reading some c-like structs from a binary file. The structs, in the c program that creates them, are defined as:
struct B{
    uint16 y;
    uint8 c[SIZE2];
}

struct A{
    uint32 x;
    struct B b[SIZE1];
}

I would like to be able to read all the A-structs using the NumPy package function fromFile, but I have no idea how to call a proper dtype method, like:
record = numpy.dtype([
    ("field1", numpy.uint8),
    ("field2", numpy.uint16),
    ("field3", numpy.uint32)
])

with a such complicated data structure.
Could you please help me writing it? Thank you in advance!

A: This is a bit of guess, since I haven't worked with C structs much.
In [125]: SIZE1, SIZE2 = 3,4

In [127]: dtB=np.dtype([('y',np.uint16),('c',np.uint8,(SIZE2,))])
In [128]: np.ones((2,), dtype=dtB)
Out[128]:
array([(1, [1, 1, 1, 1]), (1, [1, 1, 1, 1])],
      dtype=[('y', '<u2'), ('c', 'u1', (4,))])
In [129]: _.itemsize
Out[129]: 6

In this definition, each record of this array consists of 6 bytes, 2 for y field, 4 for the c field.
Then nest that in a A definition
In [130]: dtA=np.dtype([('x',np.uint32),('b',dtB,(SIZE1,))])
In [131]: np.ones((2,), dtype=dtA)
Out[131]:
array([(1, [(1, [1, 1, 1, 1]), (1, [1, 1, 1, 1]), (1, [1, 1, 1, 1])]),
       (1, [(1, [1, 1, 1, 1]), (1, [1, 1, 1, 1]), (1, [1, 1, 1, 1])])],
      dtype=[('x', '<u4'), ('b', [('y', '<u2'), ('c', 'u1', (4,))], (3,))])
In [132]: _.itemsize
Out[132]: 22

Each record has 4 bytes for the x field, 3*6 for the 3 b elements.
In [133]: __.tobytes()
Out[133]: b'\x01\x00\x00\x00\x01\x00\x01\x01\x01\x01\x01\x00\x01\x01\x01\x01\x01\x00\x01\x01\x01\x01\x01\x00\x00\x00\x01\x00\x01\x01\x01\x01\x01\x00\x01\x01\x01\x01\x01\x00\x01\x01\x01\x01'

And trying to make the array more interesting:
In [136]: A['x']=[1,2]
In [139]: A['b']['y'] *= 3
In [141]: A['b']['c'][0]=2
In [142]: A['b']['c'][1]=3
In [143]: A
Out[143]:
array([(1, [(3, [2, 2, 2, 2]), (3, [2, 2, 2, 2]), (3, [2, 2, 2, 2])]),
       (2, [(3, [3, 3, 3, 3]), (3, [3, 3, 3, 3]), (3, [3, 3, 3, 3])])],
      dtype=[('x', '<u4'), ('b', [('y', '<u2'), ('c', 'u1', (4,))], (3,))])
In [144]: A[0].tobytes()
Out[144]: b'\x01\x00\x00\x00\x03\x00\x02\x02\x02\x02\x03\x00\x02\x02\x02\x02\x03\x00\x02\x02\x02\x02'

Are those bytestrings consistent with your c struct?


text:
Q: IsModified is always false on entry's collection after modifying I have a many-to-many relationship set up with Entity Framework like this:
public class Student
{
    public int StudentId { get; set; }
    public string Name { get; set; }

    public List<StudentCourse> StudentCourses { get; set; }
}

public class Course
{
    public int CourseId { get; set; }
    public string Name { get; set; }

    public List<StudentCourse> StudentCourses { get; set; }
}

public class StudentCourse
{
    public int StudentId { get; set; }
    public Student Student { get; set; }

    public int CourseId { get; set; }
    public Course Course { get; set; }
}

I have a method where you can modify the Courses that a Student is enrolled in, by both removing and adding StudentCourses for the Student.
One thing I want to do is check if the StudentCourses collection was modified for the Student. I'm trying to do this by using the IsModified property on the Student entry.
public async Task<Student> EditStudentAsync(int id)
{
    var existingStudent = await _dbContext.Students
            .Include(s => s.StudentCourses)
            .FirstOrDefaultAsync(s => s.Id.Equals(id));

    existingStudent.StudentCourses.RemoveAll(sc =>
        ...
        // courses to delete
    );
    existingStudent.StudentCourses.AddRange(
        ...
        // courses to add
    );

    // check if StudentCourses have been added to or deleted from
    bool coursesChanged = _dbContext.Entry(existingStudent)
                              .Collection(s => s.StudentCourses).IsModified;
    coursesChanged = _dbContext.Entry(existingStudent)
                         .Navigation("StudentCourses").IsModified;
    // do something if they changed

    await _dbContext.SaveChangesAsync();
    return existingStudent;
}

But it's always coming back as false even when I've added to or removed from the collection. I've tried doing this two different ways, with Collection and Navigation on the Student entry, and neither one works.
Is there a different way I should be doing this?


text:
Q: Simplify my code     If bar1.Visible = False Or bar1.Value > 0 Then
        npc1.Visible = False
    End If
    If bar2.Visible = False Or bar2.Value >= 0 Then
        npc2.Visible = False
    End If
    If bar3.Visible = False Or bar3.Value >= 0 Then
        npc3.Visible = False
    End If
    If bar4.Visible = False Or bar4.Value >= 0 Then
        npc4.Visible = False
    End If
    If bar5.Visible = False Or bar5.Value >= 0 Then
        npc5.Visible = False
    End If

This goes on up to bar10 and npc10
I don't know how to apply loops or arrays.  I am not the best a programming but my project is due soon and i'm freaking out because it has to look good.  Please help and break it down if you can!

A: For n = 1 to 10
    Set c = Me.Controls("bar" & n)
    If c.Visible = False Or c.Value > 0 Then
        Me.Controls("npc" & n).Visible = False
    End If
Next n

A: try this
Dim i As Long

For i = 1 To 10 Step 1
    If bar(i).Visible = False Or bar(i).Value >= 0 Then
        npc(i).Visible = False
    End If
Next i


text:
Q: Issue in react MUI table in horizontal scroll when i show button in right side of table on hover My EditDeleteButton button cell that I am showing button based on hover in a row that working fine I make EditDeleteButton to position: "absolute"
and table to position: "relative"
    MuiTableBody: {
      styleOverrides: {
        root: {
          position: "relative",
        },
      },
    },

I set position: "relative" to the table because if I am not set it to relative then in vertical scroll when I scroll down then EditDeleteButton dow in next line of hover so because of that I set table body to "relative"
my EditDeleteButton button cell that I am showing button based on hover in a row that working fine but what my issue is if you see an image its working fine but when in a table horizontal scroll will appear then edit and delete button cell will get move under scroll so If I need to edit or delete it I need to scroll it then I am able to do it the table component I am passing that all this outside of the table in my table component I need to make it like that button will visible right side of the table if horizontal scroll appire or not it will not get affected.
  onMouseEnter: (e) => {
      setHoveredRow(column.index);
   },
   onMouseLeave: (e) => {
     setHoveredRow(null);
   },
  const EditDeleteButton = ({ row }) => {
    return (
      <Box
        display="flex"
        alignItems="center"
        sx={{
          position: "absolute",
          right: 0,
          float: "right",
          height: 35,
        }}
      >
        {row.index === hoveredRow && (
          <>
            <IconButton
              onClick={() => {
                setTeamRowData(row.original);
              }}
              aria-label="edit"
            >
              <Edit />
            </IconButton>
            <IconButton
              onClick={() => {
                setTeamRowData(row.original);
                handleClickOpen();
              }}
              aria-label="delete"
            >
              <Delete />
            </IconButton>
          </>
        )}
      </Box>
    );
  };
  const teamColumns = useMemo(
    () => [
      {
        Header: "Team Name",
        accessor: "teamName",
      },
      {
        Header: "Manager",
        accessor: "managerName",
      },
      {
        Header: "Branch",
        accessor: "branch",
      },
      {
        Header: "Product",
        accessor: "product",
      },
      {
        Header: "date",
        accessor: "date",
      },
      {
        Header: "screen 1",
        accessor: "screen1",
      },
      {
        Header: "screen 2",
        accessor: "screen2",
      },
      {
        Header: "screen 3",
        accessor: "screen3",
      },
      {
        Header: "screen 4",
        accessor: "screen4",
      },
      {
        Header: "screen5",
        accessor: "screen5",
      },
      {
        Header: " ",
        accessor: "button",
        disableSortBy: true,
        minWidth: 1,
        maxWidth: 2,
        Cell: EditDeleteButton,
      },
    ],
    [hoveredRow]
  );

without horizontal scroll works fine

when horizontal scroll appire so I need to scroll to see button

A: Here is a working solution which pins the right column. Codesandbox demo and full code below.
Dynamically-generated table:

Static table:

Want to pin the left column instead?

*

*In StickyTableCell, simply change right: 0 in both head and body to left: 0

*Then wrap the first column in <StickyTableCell> instead of wrapping the last

Full code:
import React from "react";
import {
  makeStyles,
  TableContainer,
  TableBody,
  TableCell,
  TableHead,
  TableRow,
  Table,
  withStyles
} from "@material-ui/core";

const useStyles = makeStyles((theme) => ({
  root: {
    width: "100%",
    marginTop: theme.spacing(3)
  },
  head: {
    backgroundColor: "#fff",
    minWidth: "50px"
  },
  tableContainer: {
    maxHeight: "400px"
  },
  cell: {
    minWidth: "100px"
  }
}));

const StickyTableCell = withStyles((theme) => ({
  head: {
    backgroundColor: theme.palette.common.black,
    color: theme.palette.common.white,
    right: 0,
    position: "sticky",
    zIndex: theme.zIndex.appBar + 2
  },
  body: {
    backgroundColor: "#ddd",
    minWidth: "50px",
    right: 0,
    position: "sticky",
    zIndex: theme.zIndex.appBar + 1
  }
}))(TableCell);

const StyledTableCell = withStyles((theme) => ({
  head: {
    backgroundColor: theme.palette.common.black,
    color: theme.palette.common.white
  },
  body: {
    fontSize: 14
  }
}))(TableCell);

const StyledTableRow = withStyles((theme) => ({
  root: {
    "&:nth-of-type(odd)": {
      backgroundColor: theme.palette.action.hover
    }
  }
}))(TableRow);

const App = () => {
  let id = 0;
  function createData(name, calories, fat, carbs, protein) {
    id += 1;
    return { id, name, calories, fat, carbs, protein };
  }

  const data = [
    createData("Frozen yoghurt", 159, 6.0, 24, 4.0),
    createData("Ice cream sandwich", 237, 9.0, 37, 4.3),
    createData("Eclair", 262, 16.0, 24, 6.0),
    createData("Cupcake", 305, 3.7, 67, 4.3),
    createData("Gingerbread", 356, 16.0, 49, 3.9),
    createData("Frozen yoghurt", 159, 6.0, 24, 4.0),
    createData("Ice cream sandwich", 237, 9.0, 37, 4.3),
    createData("Eclair", 262, 16.0, 24, 6.0),
    createData("Cupcake", 305, 3.7, 67, 4.3),
    createData("Gingerbread", 356, 16.0, 49, 3.9),
    createData("Frozen yoghurt", 159, 6.0, 24, 4.0),
    createData("Ice cream sandwich", 237, 9.0, 37, 4.3),
    createData("Eclair", 262, 16.0, 24, 6.0),
    createData("Cupcake", 305, 3.7, 67, 4.3),
    createData("Gingerbread", 356, 16.0, 49, 3.9),
    createData("Frozen yoghurt", 159, 6.0, 24, 4.0),
    createData("Ice cream sandwich", 237, 9.0, 37, 4.3),
    createData("Eclair", 262, 16.0, 24, 6.0),
    createData("Cupcake", 305, 3.7, 67, 4.3),
    createData("Gingerbread", 356, 16.0, 49, 3.9)
  ];

  const classes = useStyles();

  return (
    <div>
      <TableContainer className={classes.tableContainer}>
        <Table stickyHeader aria-label="sticky table">
          <TableHead>
            <TableRow>
              <StyledTableCell className={classes.head} numeric>
                Dessert (100g serving)
              </StyledTableCell>

              <StyledTableCell className={classes.head} numeric>
                Calories
              </StyledTableCell>

              <StyledTableCell className={classes.head} numeric>
                Fat (g)
              </StyledTableCell>

              <StyledTableCell className={classes.head} numeric>
                Carbs (g)
              </StyledTableCell>

              <StyledTableCell className={classes.head} numeric>
                Protein (g)
              </StyledTableCell>

              <StyledTableCell className={classes.head} numeric>
                Protein (g)
              </StyledTableCell>

              {/** Sticky */}
              <StickyTableCell className={classes.head}>
                <StyledTableCell className={classes.head} numeric>
                  Protein (g)
                </StyledTableCell>
              </StickyTableCell>

            </TableRow>
          </TableHead>
          <TableBody>
            {data.map((n) => {
              return (
                <StyledTableRow key={n.id}>
                  <StyledTableCell
                    numeric
                    align="right"
                    className={classes.cell}
                  >
                    {n.name}
                  </StyledTableCell>

                  <StyledTableCell
                    numeric
                    align="center"
                    className={classes.cell}
                  >
                    {n.fat}
                  </StyledTableCell>

                  <StyledTableCell
                    numeric
                    align="center"
                    className={classes.cell}
                  >
                    {n.carbs}
                  </StyledTableCell>

                  <StyledTableCell
                    numeric
                    align="center"
                    className={classes.cell}
                  >
                    {n.protein}
                  </StyledTableCell>

                  <StyledTableCell
                    numeric
                    align="center"
                    className={classes.cell}
                  >
                    {n.calories}
                  </StyledTableCell>

                  <StyledTableCell
                    numeric
                    align="center"
                    className={classes.cell}
                  >
                    {n.fat}
                  </StyledTableCell>

                  {/** Sticky */}
                  <StickyTableCell>
                    <StyledTableCell
                      numeric
                      align="center"
                      className={classes.cell}
                    >
                      {n.carbs}
                    </StyledTableCell>
                  </StickyTableCell>
                </StyledTableRow>
              );
            })}
          </TableBody>
        </Table>
      </TableContainer>
    </div>
  );
};

export default App;


text:
Q: Performance issues with Cassandra MaterializedViews We have created a cassandra cluster with 9 nodes. Each one is equipped with 4Cores and 16G RAM. We are writing 15-25 Million records with 28 columns.
The data model we have designed is as follows ( i just renamed the columns and shortened the actual schema for making it brief).
CREATE TABLE main_table(
col1 ... col28,
PRIMARY KEY((col1,col2),col_date,col_with_some_seq_number))
WITH CLUSTERING ORDER BY (col_date DESC,col_with_some_seq_number desc) AND  default_time_to_live = 5270400;

CREATE MATERIALIZED VIEW mv_for_main_table AS
SELECT [col1.. col11],
FROM main_table
WHERE col1 IS NOT NULL AND col2 IS NOT NULL AND col_date IS NOT NULL AND col_with_some_seq_number IS NOT NULL
PRIMARY KEY ((col1),col2, col_date, col_with_some_seq_number)
WITH CLUSTERING ORDER BY (col_date DESC, col_with_some_seq_number DESC, col2 DESC);

Its just moving one of the partition key to clustering key in
  materialized view.

We are loading the data from spark and do not modified any cassandra related configurations.
After ingesting around 150 Million records, the ingestion started failing and each node is giving lot of mutation failures.
Is there any performance issues with materialized views.? or the definition i have used is not efficient.?
We have tried few changes to configuration such as reducing the concurrent writes,throughput MB. After all the tries, we have dropped materialized view and then every thing started working well.
We have done enough testing to conclude that only after materialized view inclusion the writes are getting slow by huge margin and mutations are getting dropped.
We are planning to have separate tables instead of materialized views for the above configuration, but i want to know if there is any mistake with the materialized views or data model that we have used.

A: One place to understand materialized views (MV) in depth: http://www.doanduyhai.com/blog/?p=1930
There is a lock on a partition of the base table when having MVs. This local lock has a cost (see in my blog post)
I have also another remark about your hardware sizing, 4CPUs is below the official recommendation which is 8 CPUs: http://cassandra.apache.org/doc/latest/operating/hardware.html
Write workload in Cassandra is CPU-bound.In your case your CPU is also used by Spark, that may explain your bottleneck.
Please post here a screen capture of dstat and htop

A: What the materialized view does is create another table and write to it when you write to the main table. So, if you drop the materialized view and create manually another table I'm afraid you'll be on the same boat.
In my opinion, the performance problem is due to overloading one particular node. Indeed, when you demote one of your PARTITION KEY column to a CLUSTERING KEY column, assuming the same data ingestion pattern (that assumption clearly holds, because each write is "reflected" to the other table), you are going to create hotspots, because more data tend to lie on the same partition. This translates to longer compactions and read-repairs, and more stress on the cluster in general (eg because each node have to sort more data for each partition).


text:
Q: unable to execute sql procedure on oracle live sql I created a procedure
create or replace procedure dba_role
as
   user  varchar2(200);
   ref   varchar2(200);

begin

  insert into dba_role_privs(grantee,granted_role) (select user as grantee,granted_role from dba_role_privs where grantee=ref);

end;

The procedure is getting created but I'm not able to execute the procedure. I've tried different methods to execute it by passing parameters but nothing worked.
Can anyone please tell how to execute this procedure in oracle live SQL
the parameters to be passed are both strings(varchars)
for example:
I've tried "Execute dba_role('alex','hunter');
The error is
**ORA-06550: line 1, column 7:
**PLS-00306: wrong number or types of arguments in call to 'DBA_ROLE' **

A: As well as missing the two parameters that you are trying to pass (parameters should appear in brackets immediately following the procedure name, as explained in d r's answer), you can't insert into a DBA view. For one thing, it's not in your schema (unless you are creating your procedure as SYS, which you should never do because SYS is reserved for Oracle internals) and you haven't been granted INSERT privilege, but also because it is defined with multiple joins and unions etc and is therefore not an updatable view. Even it it were, your procedure only specifies two of its seven columns.
Even if you did have privileges and it was updatable and you supplied all of the values, directly updating internal data dictionary tables is unsupported and could damage your database. If you want to grant a privilege to a role you should use the GRANT command:
grant reports_user to hr;

To revoke the grant,
revoke reports_user from hr;

A: create or replace procedure
    dba_role(p_user IN VarChar2, p_ref IN VarChar2) AS

begin
  insert into dba_role_privs(grantee, granted_role) (select p_user as grantee, granted_role from dba_role_privs where grantee = p_ref);
end dba_role;
/

Above is how it should be defined - with two VarChar2 parameters. And below is how to call it:
Begin
    dba_role('alex', 'hunter');
End;
/

The problem with your code was that user and ref were declared as variables within the scope of the procedure (not as parameters) so, when the procedure was called with parameters (like I did above) then you tryed to pass two parameters to the procedure not accepting any. On the other side, if you call it without parameters (just as dba_role;) then user and ref were both Null.


text:
Q: MDX left-join of two sets I've developed data into to sets.
The first set looks like this:
set1
acctA   CatA    budget  10
acctA   CatB    budget  20
acctA   CatC    budget  30
acctB   CatA    budget  10
acctB   CatB    budget  20
acctB   CatC    budget  30
acctC   CatA    budget  10
acctC   CatB    budget  20
acctC   CatC    budget  30

and the second set:
set2
acctA   CatA    expense 7
acctA   CatB    expense 8
acctB   CatB    expense 20
acctC   CatB    expense 19
acctC   CatC    expense 3

The output report needs to be matched up like this.
desired output
        CatA            CatB            CatC
        budget  expense budget  expense budget  expense
acctA   10      7       10      8       10      -
acctB   20      -       20      23      20      -
acctC   30      -       30      19      30      3

In all accts there will be a budget amount in all Cat(s).
Each budget Cat will be represented in all accts just on time.
An acct will not always have an expense for a given Cat.
Any expense value has to be given to a distinct acct-Cat pair.
Would you rather return these sets to SSRS and join them in the report?
How would you join them in MDX?
Thanks.

A: We don't know much about your cube.
To return what you mention in straight mdx is something along these lines:
SELECT
  [Category].[Category].MEMBERS
  *
  {[Measures].budget, [Measures].expenses} ON COLUMNS
  [Account].[Account].MEMBERS ON ROWS
FROM [YourCube];

Can you amend the above please so we have an idea of your mdx?  - it will need to amended to work with SSRS as only the Measures hierarchy will be allowed on columns.

A: Lol.  The correct answer is ... get those nulls our of your cube's data


text:
Q: Persist form data during page transition in Asp.Net MVC 5 Jquery mobile Application I am working on a application (Asp.Net MVC 5 Jquery mobile Application) containing a form page. There are 3 buttons on the form page which go to other pages and take data from user for specific modules. But when user comes back to Main Form from those pages , he loses data which he put already in the form. It just gets flushed. I want to persist that data as well during page transitioning.
The solution I researched are about saving data in session but in my case the form fields in the main form are created dynamically.
I am unable to find out a way out that how can I persist main form data during page transitioning.
Any help?


text:
Q: pause function while child window is displayed in Qt in Qt Creator I have a mainwindow and a QWidget as tool-window (setWindowFlags(Qt::tool)). When I call the tool window the user can change some settings. These changes then alter some data in the mainwindow.
I create the widget, show it, then I want to update the data in mainwindow, but the function doesn't wait for the widget to close. So the update procedures after the show are imidiately executed and have no effect. When I show a QMessageBox the function waits for the user to close it.
Is there a flag or something I can set for the QWidget so the function waits?
void userclicksonsettings(){
 settings = new Settings(this);  // Settings is a QWidget-class with ui
 settings->show();
 // function should wait till settings is closed
 // set up mainwindow with new values
}

Thanks.

A: I just solved it.
Using QDialog instead of QWidget as base class allows to call the window with
    QDialog::exec();
and the parent widget will pause until the window is closed again.
Edit: here is the source of the solution I just digged out of a backup disk. I have to say though, it's some years ago I last used Qt and this code, so it could be incorrect. I hope it helps to get the idea.
settingsForm.h
#include <QDialog>
class SettingsForm : public QDialog
{
    Q_OBJECT

public:
    explicit SettingsForm(QWidget *parent = 0);
    ~SettingsForm();
// other variables and slots etc.
};

settingsForm.cpp
#include "settingsform.h"
#include "ui_settingsForm.h"

#include <QColorDialog>

SettingsForm::SettingsForm(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SettingsForm)
{
    ui->setupUi(this);
    this->setWindowFlags(Qt::Tool);

// initializing functions
}

SettingsForm::~SettingsForm()
{
    delete ui;
}

mainwindow.h
#include "settingsForm.h"
// ...

To call the settingsWindow in from the mainwindow initialize the object and call it like a QDialog
mainwindow.cpp
settingsform = new SettingsForm(this);
if(settingsform->exec() == QDialog::Accepted){
    // update form from settings
}

I had also a settings-class for all the variables that could be set with the form, which was passed to the settingsForm and updated when the user clicked OK.

A: I do it this way:
void userclicksonsettings() {
    settings = new Settings(this);
    settings->setWindowModality(Qt::ApplicationModal);
    settings->show();
   //...
}

Qt::ApplicationModal -
The window is modal to the application and blocks input to all windows.


text:
Q: How to handle memory allocation in C I am new in C and i am creating a simple program in which i am writing value to the multidimensional error .But I am getting error "Segmentation fault" or some time when i am running the code it is getting in Infinite loop.
int main(){
int i,j;
int num1=10;
int num2=10;
double data[num1][num2];

    for(i=0;i<=num1;i++){
        for(j=0;j<=num2;j++){
            if(i==0) {
                data[i][j]=121.21;
            }
            else {
                data[i][j]=0.0;
            }
        }
    }
}

When i am doing the hardcoding of values on below structure it is working fine :
change double data[num1][num2]; to double data[10][10];
How can we fix this issue in C.

A: You're overrunning the bounds of the array in your loops:
for(i=0;i<=num1;i++){
    for(j=0;j<=num2;j++){

In the outer loop i ranges from 0 to num1, while in the inner loop j ranges from 0 to num2.  However, the maximum valid index for each array dimension is num1-1 and num2-1 respectively.  Reading / writing past the end of an array invokes undefined behavior, which is why it sometimes worked and sometimes didn't.
Change the loop conditions to <:
for(i=0;i<num1;i++){
    for(j=0;j<num2;j++){

A: It seems you are going over the memory the program is allowing you to access. You are allocating memory for 100 values (10*10). However, when dealing with arrays in most programming languages, it is important that you know index 0 counts as one such that you can go from array[0] - array[9] and that is declaring an array with memory for 10 spots since we start at 0 in most programming languages.
A clean way to fix this code would be:
for (int i=0; i < num1; i++) {
    for (int j=0; j < num2; j++ {

This would avoid accessing memory location at index 10 which is not allocated.


text:
Q: convert HttpWebRequest authentication with cookies into UnityWebRequest I'm authenticating with a server that, through a series of redirects sets a CSRF cookie. I also get a oauth2 cookie that I need to include for all subsequent queries.
I'm able to obtain all the cookies and authenticate using HttpWebRequest - but I'd like to convert this to use UnityWebRequest so I can make use of Coroutines to not block the main game loop.
I am able to obtain the CSRF cookie in both HttpWebRequest and UnityWebRequest - ✅
The issue I'm having is how to send this CSRF cookie using UnityWebRequest when trying to login.
My HttpWebRequest looks like this...
 ServicePointManager.ServerCertificateValidationCallback = TrustCertificate;
 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
 request.KeepAlive = true;
 request.ContentType = "application/x-www-form-urlencoded";
 request.Method = method;
 request.AllowAutoRedirect = false;
 request.CookieContainer = new CookieContainer();
 Cookie csrf = new Cookie("_oauth2_proxy_csrf", CSRF_COOKIE, "/", server_ip);
 request.CookieContainer.Add(csrf);
 request.Proxy = null;

 if (method == "POST")
 {
     NameValueCollection nvc = new NameValueCollection();
     nvc.Add("login", username);
     nvc.Add("password", password);
     StringBuilder postVars = new StringBuilder();
     foreach (string key in nvc)
         postVars.AppendFormat("{0}={1}&", key, nvc[key]);
     postVars.Length -= 1; // clip off the remaining &

     using (var streamWriter = new StreamWriter(request.GetRequestStream()))
     {
         streamWriter.Write(postVars.ToString());
     }
 }

 var response = (HttpWebResponse)request.GetResponse();

This works successfully, the server authenticates me and provides an authentication cookie - ✅
Now, my translated UnityWebRequest code looks like this...
 List<IMultipartFormSection> post_data = new List<IMultipartFormSection>();
 post_data.Add(new MultipartFormDataSection("login", username));
 post_data.Add(new MultipartFormDataSection("password", password));

 UnityWebRequest request = UnityWebRequest.Post(url, post_data);
 request.uploadHandler.contentType = "application/x-www-form-urlencoded";
 request.certificateHandler = new ForceAcceptAll();
 request.redirectLimit = 1;
 request.SetRequestHeader("_oauth2_proxy_csrf", CSRF_COOKIE);
 string cookie = string.Format("{0}={1}", "_oauth2_proxy_csrf", CSRF_COOKIE);
 request.SetRequestHeader("Cookie", cookie);
 yield return request.SendWebRequest();

The server doesn't appear to be receiving the cookie correctly. It won't authenticate correctly and doesn't provide the auth cookie like it does with HttpWebResponse
I think it boils down to how to translate
request.CookieContainer.Add(csrf); into UnityWebRequest - ❓
which I thought would be:
string cookie = string.Format("{0}={1}", "_oauth2_proxy_csrf", CSRF_COOKIE);
request.SetRequestHeader("Cookie", cookie);

The Unity docs say that UnityWebRequest has an internal cookie engine - but as far as I can see it completely opaque so I can't see what the contents are.


text:
Q: Finding VBA Comments using RegEx I am trying to find all VBA comments using regular expressions. I have something that mostly works, but there are a few exceptions that I cannot figure out.
Expression I am using:
'(?!.*").*

Take our test code:
Working - This is a test 'This should be captured
Working - "this is a test" 'This should be captured
Not Working - "this is a test" 'This should be "captured"
Not Working - This is a test 'This should be "captured"
Working - "this is a test 'this should not capture'" 'this should capture
Working - "this isn't a test" 'this should capture

Here is a link to this example in RegExr: http://regexr.com/3f24h
For some reason that third and fourth examples are not capturing. The problem seems to be with having a string value in the comments and I cannot figure out how to fix it.
Any advice?

A: You can't find all of the comments (let alone string literals) in VBA code with regular expressions - period.  Trust me, I tried during work on the Smart Indenter module of Rubberduck (in case that wasn't explicit enough - full disclosure, I'm a contributor). You'll need to actually parse the code.  The first issue that you'll run into are line continuations:
'Comment with a line _
continuation

Debug.Print 'End of line comment _
with line continuation.

Debug.Print 'Multiple line continuation operators _ _
still work.

Debug.Print 'This is actually *not* a line continuation_
Debug.Print 42

This makes it difficult to identify string literals, especially you're using line-by-line processing:
Debug.Print 42 'The next line... _
"...is not a string literal"

You also have to handle the old Rem comment syntax...
Rem old school comment

...which also support line continuations:
Rem old school comment with line _
continuation.

You might be thinking "that can't be so bad, Rem has to start a line".  If you are, you forgot about the statement separator (:)...
Debug.Print 42: Rem statement separator comment.

...or its evil twin the statement separator combined with a line continuation:
Debug.Print 42: Rem this can be _
continued too.

You covered a couple of the issues with sorting out string literals and comments like these...
Debug.Print "Unmatched double quotes." 'Comment"
Debug.Print "Interleaved single 'n double quotes." 'Comment"

...but what about bracketed identifiers like this beast (courtesy of @ThunderFrame)?
'No comments or strings in the line below.
Debug.Print [Evil:""Comment"'here]

Note that the syntax highlighter SO uses doesn't even catch all of these bizarre corner cases.

A: Maybe something like
^(?:[^"'\n]*("(?:[^"\n]|"")*"))*[^"]*'(.*)$

It handles multiple quoted strings, as well as strings having quoted (double) "'s (which I believe is VBA's way).
(I guarantee it will fail in some cases, but probably will work in most ;)
Check it out here at regex101.
Edit
Added some of Comintern's examples and adjusted the regex. It still can't handle the bracketed identifiers though (which I don't even know what it means :S See the last line). But it now handles his continued line comments.
^(?:[^"'\n]*(?:"(?:[^"\n]|"")*"))*[^']*('(?:_\n|.)*)

Check it out here at regex101.

A: This should work:
("[^"]+"\s)?'.+

Tested here: https://regex101.com/r/dd60QS/1


text:
Q: Response outputstream content length? I am writing to output stream through various methods. How can I, before I close it, find out content length of the outputstream?

A: The problem is that you must set the content length in the response header before you start writing any data to the output stream.  So your options are:

*

*Write the data to a byte[] array using ByteOutputStream and then copy that to the response output stream once you have the size of the data.  However, if you're writing large files, this obviously isn't an option.

*Write the data to a temp file and then copy that to the response output once you get the file size.  Depending on what you're doing, this may have a performance penalty that is unacceptable.

*Depending on how expensive it is to generate the data in the first place, you could generate it once, and throw it away to get the count and then generate it again.  Guessing that this is unlikely to be a realistic solution.

*Resign yourself to the fact that you won't be able to report the content length in the response header.

A: You may consider writing to your own ByteArrayOutputStream and flush it to the response output stream at the very end.

A: The easiest way is probably to wrap it in another OutputStream implementation which forwards on all the write requests, but keeps an internal counter. Then you just write to that instead. Shouldn't be too hard to implement - and indeed there may be one already.
EDIT: Just guessing at a sensible name (CountingOutputStream) came up with an implementation in Apache Commons IO.
EDIT: As noted elsewhere, if this is for HTTP and your client isn't already doing buffering of the full data (in which case I'd have thought it could work out the content length), you may have problems due to needing to write the length before writing the data. In some cases you may find that it will work up to a certain size (which the client buffers) and then fail. In that case, David's solutions will be appropriate.


text:
Q: Separating a 2D Array into Regions bounded by a Continuous Line I am a beginner hobbyist programmer in my first year of college. Recently I've been obsessed with the puzzle game "The Witness", for its minimalist yet surprisingly difficult puzzles. As a passion project I'm attempting to recreate just the Puzzle element of the game for others to enjoy.
THE GAME
This is How the Game Looks So Far
Essentially, you have a white path that is controlled by the user, and you must navigate that path through the grid, splitting the grid into region consisting of black and white tiles. Each region must have only white or only black tiles.
I've posted a picture of how the project looks so far, with a solved puzzle.
THE PROBLEM
I cannot for the life of me figure out a function to split the grid into regions as shown in the image. The Path is a 1D array of x and y coordinates of each point in the path. when its done, it should be at the top right corner of the grid at (cols,rows). This is assuming the lower left corner is (0,0).
Path = [[x1,y1],[x2,y2],...,[cols,rows]]

each Puzzle has n rows and n columns, so id like a function getRegions(path, cols, rows) that takes in the path, and the rows and columns, and outputs an array like this
arrayWithRegions=
[[2,3,3,2],
 [2,2,2,2],
 [1,1,1,2],
 [1,1,1,2]]

where each square is marked as being in a distinct region based on the boundaries set by the path and the outer border. The example is how the array would look for the puzzle in the image provided. (disregard the black and white blocks, they don't matter right now)
I'd appreciate any sort of help or even a nudge in the right direction. Thanks!

A: You can just execute Flood fill algorithm using path line and field edges as borders.
Choose any unmarked cell (for example - left bottom one), start flood fill with region mark 1, traverse all possible cells. Then find another unmarked cell, start fill with region mark 2 and so on.
The simplest recursive implementation of FF algo and sequential search of unmarked cells should work nicely for small size of your field.


text:
Q: Auto delete comment if Contains How to Auto-Delete comment if contains certain string?
i tried with this but not work:
add_action( 'transition_comment_status', 'my_approve_comment_callback', 10, 3 );

function my_approve_comment_callback( $new_status, $old_status, $comment ) {
    if (strpos($comment->comment_content, 'dog') !== false) {
            wp_delete_comment( $comment->comment_ID, true );
    }
}

I have also tried with:
wp_list_comments('callback=better_comment');

function better_comment($comment, $args, $depth) {
    if (strpos($comment->comment_content, 'dog') !== false) {
            wp_delete_comment( $comment->comment_ID, true );
    }
}

Nothing work =(

A: It is better to use 'comment_post' action for this purpose, it is fired when the comment is saved in database:
add_action('comment_post', 'my_comment_post_callback', 10, 3);

function my_comment_post_callback($comment_id, $comment_approved, $commentdata) {
    if (strpos($commentdata['comment_content'], 'dog') !== false) {
        $post_url = get_permalink($commentdata['comment_post_ID']);
        wp_delete_comment($comment_id, true);
        wp_redirect($post_url);
        exit;
    }
}


text:
Q: Javascript: something like PHP file_get_contents <?php
    //simply api
    if(isset($_POST["submitmail"])){
        if(strlen($_POST["mail"]) >= 5){
            $api = file_get_contents("API_LINK");

            if($api == "good"){
                echo "<script>alert('Thanks');</script>";
            }
        }else{
            echo "<script>alert('Try again');</script>";
        }
    }
?>

That's my very simple api, kind of. I'd like to somehow convert this into JS. The PHP code will activate the URL, and on the API_LINK I'll store the data from the url.
The very same with JS or a similar solution would be perfect.