text:
Q: When using Filestream Filemode.Append does it overwrite what is lying next to the file? Lets assume that exactly 1 byte after the File-1-EOF another file (file2) starts.
If I open up file 1 and use FileStream Filemode.Append, does it overwrite file2 or does it make another copy at a place where there is enough memory?
Thanks, in regards!
Edit:
For everyone after me: I forgot that you have a file system, which is split into chunks. Making this question nonsense!

A: You appear to be laboring under the misapprehension that files are stored sequentially on disk, and that extending one file might overwrite parts of another file. This doesn't happen when you go via a filestream append in c#. The operating system will write the bytes you add however it likes, wherever it likes (and it likes to not overwrite other files) which is how files end up broken into smaller chunks (and why defragging  is thing) scattered all over the disk. None of this is of any concern to you, because the OS presents those scattered file fragments as a single contiguous stream of bytes to any program that wants to read them
Of course, if you wrote a program that bypassed the OS and performed low level disk access, located the end of the file and then blindly write more bytes into the locations after it then you would end up damaging other files, and even the OS's carefully curated filesystem .. but a .net file stream won't make that possible
TLDR; add your bytes and don't worry about it. Keeping the filesystem in order is not your job

A:
If I open up file 1 and use FileStream Filemode.Append, does it overwrite file2 or does it make another copy at a place where there is enough memory?

Thankfully no.
Here's a brief overview why:
Your .NET C# code does not have direct OS level interaction.
Your code is compiled into byte-code and is interpreted at runtime by the .NET runtime.
During runtime your byte-code is executed by the .NET Runtime which is built mostly in a combination of C#/C/C++.
The runtime secures what it calls SafeHandles, which are wrappers around the file handles provided by what I can assume is window.h(for WIN32 applications at least), or whatever OS level provider for file handles you're architecture is running on.
The runtime uses these handles to read and write data using the OS level API.
It is the OS's job to ensure changes to yourfile.txt, using the handle it's provided to the runtime, only affects that file.
Files are not generally stored in memory, and as such are not subject to buffer overflows.
The runtime may use a buffer in memory to.. buffer your reads and writes but that is implemented by the runtime, and has no affect on the file and operating system.
Any attempt to overflow this buffer is safe-guarded by the runtime itself and the execution of your code will stop. Regardless, if a buffer overflow happened on this buffer successfully - no extra bytes will be written to the underlying handle. Rather the runtime would likely stop executing with a memory access violation, or general unspecified behavior.
The handle you're given is little more than a token that the OS uses to keep track which file you want to read or write bytes to.
If you attempt to write more bytes to a file than an architecture allows - most operating systems will have safe guards in place to end your process, close the file, or straight up send an interrupt to crash the system.


text:
Q: How to automatically add tags via capture template in org mode? I was trying to add a specific tag by default to my capture template. So that when the capture is complete, it looks like the following
  * TODO                                  :customtag:

This was the closest thread I was able to find. I was trying to figure out if there is a simpler way to do this, using just template expansions.

A: The best way to go about this is to use the function org-set-tags
The following capture template solves the above question
(org-capture-templates
   '(("p" "Personal" entry
      (file "xyzz/location")
      "* TODO [Personal] %? %(org-set-tags \"personal\")
DEADLINE: %^t")))

Using %() around org-set-tags will ensure that the function is evaluated. You can replace "personal" with any tag of your choice.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add Icon beside each item in a List preference In Android along with selected indicator I am working on a Xposed module and I need to have an icon beside each item in my List Preferences.
I am able to do this :
http://s20.postimg.org/gjveleu5p/Screenshot_2014_01_18_16_47_38.png
But I want exactly like This one :
http://s20.postimg.org/ee13qwqp9/Screenshot_2014_01_29_12_32_38.png
My Java Class File:
package ic.lunar.xposed.exthemer.list.preferences;

import ic.lunar.xposed.exthemer.R;
import android.content.Context;
import android.preference.ListPreference;
import android.util.AttributeSet;

public class Sim_Icon_List_Preference extends ListPreference {

Context context;

public Sim_Icon_List_Preference(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.context = context;
    setDialogLayoutResource(R.layout.activity_my_list_preference); //inherited from DialogPreference
}
}

My Layout Xml File:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:paddingBottom="@dimen/activity_vertical_margin"
  android:paddingLeft="@dimen/activity_horizontal_margin"
  android:paddingRight="@dimen/activity_horizontal_margin"
  android:paddingTop="@dimen/activity_vertical_margin"
  tools:context=".MyListPreference" >
<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:src="@drawable/tw_sim_icon_home" />
<ImageView
    android:id="@+id/imageView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/imageView1"
    android:layout_toRightOf="@+id/imageView1"
    android:src="@drawable/tw_sim_icon_heart" />
</RelativeLayout>

A: When you need a ListPreference with (per row) a text and an icon, you can find a solution via this description.


text:
Q: What to do with this Swift language compiling error on windows I'm trying to learn how to build an ios mobile app and decided to install swift for windows. After I downloading and installing the software. I tried to compile and run the sample Hello.swift to test it but this error shows up. What to do? Thanks in advance
p.s. I already redownload and reinstalled the SwiftForWindows

A: Okay I already figure out the solution to my problem. Just install the Visual studio 14 and check the C++ on the option of installing


text:
Q: How to apply responsive table functions to a table loaded by ajax? I have a little script that applies foundation responsive tables css when the screen is resized,  which works just fine. The problem is that if a table is loaded VIA ajax to the page, the script won't run on mobile devices , because the screen never gets resized.
here is the script:
jQuery(document).ready(function() {

  var switched = false;
  var updateTables = function() {
    if ((jQuery(window).width() < 767) && !switched ){
      console.log('reconfig table');
      switched = true;
      jQuery("table.responsive").each(function(i, element) {
        splitTable(jQuery(element));
      });
      jQuery('.scrollable.scroll-right').scrollLeft(10000);
      return true;
    }
    else if (switched && (jQuery(window).width() > 767)) {
      switched = false;
      jQuery("table.responsive").each(function(i, element) {
        unsplitTable(jQuery(element));
      });
    }

    jQuery('.scrollable.scroll-right').scrollLeft(10000);

  };

  jQuery(window).load(updateTables);
  jQuery(window).on("redraw",function(){switched=false;updateTables();}); // An event to listen for
  jQuery(window).on("resize", updateTables);

    function splitTable(original)
    {
      var wrapperClass = '';
      var classnames = jQuery('table.responsive').attr('data-scrollbar-position');
      if(classnames == 'left'){
        wrapperClass = 'scroll-right';
      }

      original.wrap("
");

        var copy = original.clone();
        copy.find("td:not(:first-child), th:not(:first-child)").css("display", "none");
        copy.removeClass("responsive");

        original.closest(".table-wrapper").append(copy);
        copy.wrap("
");
        original.wrap("
");

    setCellHeights(original, copy);
    }

    function unsplitTable(original) {
    original.closest(".table-wrapper").find(".pinned").remove();
    original.unwrap();
    original.unwrap();
    }

  function setCellHeights(original, copy) {
    var tr = original.find('tr'),
        tr_copy = copy.find('tr'),
        heights = [];

    tr.each(function (index) {
      var self = jQuery(this),
          tx = self.find('th, td');

      tx.each(function () {
        var height = jQuery(this).outerHeight(true);
        heights[index] = heights[index] || 0;
        if (height > heights[index]) heights[index] = height;
      });

    });

    tr_copy.each(function (index) {
      jQuery(this).height(heights[index]);
    });
  }

});

how can I apply this to mobile devices?

A: Once you load new content using AJAX, run
jQuery(window).resize();

This triggers a the resize event and should redraw.


text:
Q: Create timestamped labels on csv files (ruby code) I am running a transaction download script through Ruby. I was wondering if it is possible to label each .csv it creates with the current date/time the script was run. Below is the end of the script.
CSV.open("transaction_report.csv", "w") do |csv|
  csv << header_row
  search_results.each do |transaction|
    transaction_details_row = header_row.map{ |attribute| transaction.send(attribute) }
    csv << transaction_details_row
  end
end

A: Like this?
CSV.open("transaction_report-#{Time.now}.csv", "w") do |csv|
  csv << header_row
  search_results.each do |transaction|
    transaction_details_row = header_row.map{ |attribute| transaction.send(attribute) }
    csv << transaction_details_row
  end
end

This just appends the time of generation to the file name. For example:
"transaction_report-#{Time.now}.csv"
# => "transaction_report-2019-10-10 16:09:07 +0100.csv"

If you want to avoid spaces in the file name, you can sub these out like so:
"transaction_report-#{Time.now.to_s.gsub(/\s/, '-')}.csv"
# => "transaction_report-2019-10-10-16:09:40-+0100.csv"

Is that what you're after? It sounds right based on the question, though happy to update if you're able to correct me :)


text:
Q: Angular Schematics: trustedSubscriber._addParentTeardownLogic I'm trying to build an Angular Schematics to help me and my team create NgRx actions fast. This is the schematics function, most of it is copied from various tutorials:
export default (options: CCSchematicsAction): Rule => {
    return (tree: Tree, _context: SchematicContext) => {
        const modulePath = options.modulePath.replace(/-?module$/, ""); // "shared/application-tools"
        const moduleFolder = normalize("src/app/" + modulePath); // "src/app/shared/application-tools"
        const modulePathComponents = modulePath.split("/"); // ["shared", "application-tools"]
        const moduleIdentifier = modulePathComponents
            .map(part => classify(part))
            .join(".")
        + ".Action"; // "Shared.ApplicationTools.Action"

        const action = options.name.replace(/-?action$/, "");
        const path = normalize(moduleFolder + "/action/" + action) + "/";

        const templateSource = apply(url("./files"), [
            template({
                action: action,
                moduleIdentifier: moduleIdentifier
            }),
            move(path)
        ]);

        return chain([
            mergeWith(templateSource)
        ])(tree, _context);
    };
}

I invoke the schematics with
schematics cc-generate:action load-stuff-action --modulePath shared/ui

and get the following, which I can't even find any info to on the web:
TypeError: trustedSubscriber._addParentTeardownLogic is not a function
    at MergeMapSubscriber.Subscriber [as constructor] (/Users/voss/Development/cc/cc-schematics/node_modules/rxjs/internal/Subscriber.js:45:43)
    at MergeMapSubscriber.OuterSubscriber [as constructor] (/Users/voss/Development/cc/cc-schematics/node_modules/rxjs/internal/OuterSubscriber.js:20:42)
    at new MergeMapSubscriber (/Users/voss/Development/cc/cc-schematics/node_modules/rxjs/internal/operators/mergeMap.js:48:28)
    at MergeMapOperator.call (/Users/voss/Development/cc/cc-schematics/node_modules/rxjs/internal/operators/mergeMap.js:39:33)
    at Observable.subscribe (/Users/voss/Development/cc/cc-schematics/node_modules/rxjs/internal/Observable.js:24:22)
    at DefaultIfEmptyOperator.call (/usr/local/lib/node_modules/@angular-devkit/schematics-cli/node_modules/rxjs/internal/operators/defaultIfEmpty.js:24:23)
    at Observable.subscribe (/Users/voss/Development/cc/cc-schematics/node_modules/rxjs/internal/Observable.js:24:22)
    at TakeLastOperator.call (/usr/local/lib/node_modules/@angular-devkit/schematics-cli/node_modules/rxjs/internal/operators/takeLast.js:35:23)
    at Observable.subscribe (/Users/voss/Development/cc/cc-schematics/node_modules/rxjs/internal/Observable.js:24:22)
    at DoOperator.call (/usr/local/lib/node_modules/@angular-devkit/schematics-cli/node_modules/rxjs/internal/operators/tap.js:29:23)

Edit:
When I remove everything and just return an empty chain, the error stays.
export default (_options: CCSchematicsAction): Rule => {
    return (tree: Tree, _context: SchematicContext) => {
        return chain([noop()])(tree, _context);
    };
}

So what's wrong with the chain function?

A: Ok nevermind, the problem was the differing versions of @angular-devkit/schematics-cli..

A: It looks that today rxjs has released a new version 6.3.2 that solves this issue.


text:
Q: Right Bar Button item not working Actually i am placing a bar button on right side of navigation bar, it's not working. But when i use it as left bar button item, it's working fine. I am  using ios5.
It was also not working when i have both button left and right bar button. Then i set the frame for both, then these are working. But when i have only one button on right side, it's not working.
 UIButton *but1 = [UIButton buttonWithType:UIButtonTypeCustom];//customising map button.

but1.frame = CGRectMake(270,0,50,40);

[but1 addTarget:self action:@selector(clicked) forControlEvents:UIControlEventTouchUpInside];//on cilcking an map button clicked method is called.

buttonRight = [[UIBarButtonItem alloc]initWithCustomView:but1];//setting map button on Navigation bar.

self.navigationItem.rightBarButtonItem = buttonRight;//setting button on the Right of navigation bar.

how to trace out this error?

A: UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithTitle: @"edit" style: UIBarButtonItemStyleBordered target: self action: @selector(edit_details)];
self.navigationItem.rightBarButtonItem = addButton;

A:     UIToolbar* toolbar = [[UIToolbar alloc]
                          initWithFrame:CGRectMake(0, 0, 50, 45)];
    [toolbar setBarStyle: UIBarStyleBlackOpaque];
    // create an array for the buttons
    NSMutableArray *buttons = [[NSMutableArray alloc] initWithCapacity:0];

    // create a standard BarButtonItem
    UIBarButtonItem *SettingsBtn = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"icon_setting.png"] style:UIBarButtonItemStylePlain
                                   target:self
                                   action:@selector(ActionMethod:)];
    [buttons addObject:SettingsBtn];
    [SettingsBtn release];

    // put the buttons in the toolbar and release them
    [toolbar setItems:buttons animated:NO];
    [buttons release];

    // place the toolbar into the navigation bar
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]
                                              initWithCustomView:toolbar]autorelease];
    [toolbar release];

A: For Swift 4.2 code:
In the View did load function
let addButton = UIBarButtonItem(title: "edit", style: .plain, target: self, action: #selector(edit))
 navigationItem.rightBarButtonItem = addButton

Function definition goes here:
@objc func edit() {
    // Body definition
}


text:
Q: Where are the common places to store application data I am working on a Windows based desktop App and when the App starts up I need to store some small piece of data at somewhere.
The purpose is to share some data between the instances of the same App. Again, the size of the data is very very small, in this case,it is just a string.
I did some research and find out there are following options:

*

*MSMQ

*Registry

*a plain text file

*shared memory

*.Net configuration model

Now I am using the easiest one - #3. I am wondering how other people deal with the same problem? Any suggestions?
Thanks

A: Add 5: .net configuration model. You can set fields under project settings -> settings, those will be available in the namespace AssemblyName.Properties in the Settings object.
If you really need to do it on your own, I'd advise you to save those files in %appdata%\YourProgramName. You can get the path via Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).

A: The file system is the best place to persist data. If the settings are per user, store the files in the user's home folder. If the settings are shared between users, store the files in the shared data directory (this was C:\Program Files last time I used Windows). You should create a subdirectory for your application in either of these locations.
A simple text file is good for a simple string.
A data interchange format such as json or yaml is good for a complex data structure.
A database, such as SQLite (normally stored in a .db file) is good for when you have to read and write data frequently to disk.

A: You might be able to use the built in settings available to you within the C# project.
Here is a MSDN link on how to use the settings within a C# project.
MSDN Settings Tutorial
If you need something more complex, a flat file might suit your needs as well.

A: If the data you want to store is not sensitive, it is fine to store it in a plain text file.
Using %appdata% is more centralized, I like the idea.

A: I think the answer to your question of which approach to use will depend on the process you're using. If you're running more of an Agile process for your development I'd do the bare minimum during your iteration to get the settings stored and shared successfully between your Apps. As more requirements surface about what the applications need or possibly performance becomes an issue just re-design your solution to satisfy the new requirements.
However if you're following more of a Waterfall process for your development (big design up front) and if you're at all anticipating that your application's requirements will grow beyond what you currently know (and this obviously happens quite often) then I'd design and build a solution that has been known to work well in the past. Some sort of database engine, whether heavy weight like MySQL or Microsoft's SQL Server Or a lightweigher version like SQLite will provide a well structure mechanism to share data between multiple application.
Here is also another discussion on stackoverflow about whether to use SQLite or XML for settings.

A: I use a combination of database for more secure and user specific data, such as usernames and scores (I'm creating a game), and the registry for more global settings.


text:
Q: Angular rendering before loaded data? In Angular 9, I'm getting data from subscribe() inner forEach. I can see that my variable is loaded with data, but Angular is not rendering. I suspect that Angular is rendering before my variable is loaded.
How can I resolve it?
Called function
this.servicePromotion.list(text)
    .subscribe((res: any) => {
        this.gridList = [];

        if (res) {
          console.log('GRID LIST', this.gridList) // -> here I can show "cupom" property filled.
          this.gridList = this.mapperCalendatioStatus(res.list) // -> but when I try redering on screen, it's not shown
        }
    })

Function that loop "promocoes" and search p.id in a subscribe.
mapperCalendatioStatus(promocoes) {
    promocoes.forEach(p => {
          const promocoesStatus = [];
          let campaignExists = '';

          const consultaPromocao = new ConsultaPromocaoModel();
          consultaPromocao.id = p.id
          consultaPromocao.codigoIdentificacao = p.codigoIdentificacao;
          consultaPromocao.nome = p.nome;

          this.serviceCouponGenerate.getByIdPromocao(p.id).subscribe((response: any) => {
          if (response.length) {
            campaignExists = 'YES'
          } else {
            campaignExists = 'NO'
          }
          consultaPromocao.cupom = campaignExists;

          promocoesStatus.push(consultaPromocao);

    })

    return promocoesStatus;
}

Cupom column to be need filled

My variable filled (cupom: "SIM" for example)


text:
Q: Import phonegap's R.java to my plugin? I am trying to make a phonegap plugin to open up a activity to play a video through android's videoView (because lets face it android's webview can't play html video). I got everything working but I have to include the R.java from phonegap's package into mine for my plugin to work/build and eliminate the "R can not be resolved to a variable" errors.
my plugin is up at https://github.com/mikeRead/videoview if you read the "important!" section you can find out what I have to do to fix the R... problem.
basically the user has to change an import statement in my plugin to their phonegap package name, so R.id and R.layout works.
I'm  a web developer and by far from an android or phone gap coder so any help/hints on this (other than the eclipse fixes) is welcome
THANKS!

A: The problem described in your question can be solved by adding an after_plugin_install hook to your plugin . I have programmed a hook to modify my Activity called SketchActivity.java as shown below. Change the package name to your plugin as required.
#!/usr/bin/env node
/*
A hook to add R.java to the draw activiy in Android platform.
*/

var fs = require('fs');
var path = require('path');

var rootdir = process.argv[2];

function replace_string_in_file(filename, to_replace, replace_with) {
    var data = fs.readFileSync(filename, 'utf8');
    var result = data.replace(to_replace, replace_with);
    fs.writeFileSync(filename, result, 'utf8');
}

var target = "stage";
if (process.env.TARGET) {
    target = process.env.TARGET;
}

    var ourconfigfile = path.join( "plugins", "android.json");
    var configobj = JSON.parse(fs.readFileSync(ourconfigfile, 'utf8'));
  // Add java files where you want to add R.java imports in the following array

    var filestoreplace = [
        "platforms/android/src/in/co/geekninja/plugin/SketchActivity.java"
    ];
    filestoreplace.forEach(function(val, index, array) {
        if (fs.existsSync(val)) {
          console.log("Android platform available !");
          //Getting the package name from the android.json file,replace with your plugin's id
          var packageName = configobj.installed_plugins["in.co.geekninja.Draw"]["PACKAGE_NAME"];
          console.log("With the package name: "+packageName);
          console.log("Adding import for R.java");
            replace_string_in_file(val,"package in.co.geekninja.plugin;","package in.co.geekninja.plugin;\n\nimport "+packageName+".R;");

        } else {
            console.log("No android platform found! :(");
        }
    });

place it inside /hooks/after_plugin_install/ directory in your plugin
And add the following line between your <platform name="android"> ... </platform> tag:
<hook type="after_plugin_install" src="hooks/after_plugin_install/hook-add-r-import.js" />

The code will be executed every time when someone adds the plugin using cordova plugin add command and writes the R.java import right below the package declaration


text:
Q: Word VSTO add-in development: How to find the color of a text in a Range in RGB format? I'm developing an add-in for MS Word using C#. I need to find the color of the text within a Range object in RGB format.

*

*I tried using Range.Font.Color, which is supposed to give the RGB value. But I'm getting negative and out-of-range values from it.

*Range.Font.TextColor gives me a NotImplemented exception.

I'm using Visual Studio 2010. Please help me.

A: Here's a little test method that can put html style tags for the font color into the document (I needed to do that for bold and italic and just wanted to see if I could get the color) If you fiddle with it you might be able to get what you need it's c# vsto for Word
private void TEST()
{
        Range currentWord = Globals.ThisAddIn.Application.ActiveDocument.Words.First;
        object collapseStartObj = WdCollapseDirection.wdCollapseStart;
        object oText = "";
        object oMiss = System.Reflection.Missing.Value;
        object oFindStop = WdFindWrap.wdFindStop;
        object oCountOne = 1;
        object oWordUnit = WdUnits.wdWord;
        int count = 0;
        while (currentWord != null)
        {
            count++;
            currentWord.Find.Font.Bold = currentWord.Font.Bold;
            currentWord.Find.Font.Italic = currentWord.Font.Italic;
            currentWord.Find.Font.ColorIndex = currentWord.Font.ColorIndex;
            string text = currentWord.Font.ColorIndex.ToString();
            string thatColor = Regex.Replace(text, @"\d", ""); //remove any digits
            string simpleColor = Regex.Replace(thatColor, "wd", "");//remove the wd
            //MessageBox.Show(simpleColor); //for testing

            currentWord.Find.Forward = true;
            currentWord.Find.Format = true;
            currentWord.Collapse(ref collapseStartObj);
            currentWord.Find.Execute(ref oText, ref oMiss, ref oMiss, ref oMiss, ref oMiss, ref oMiss, ref oMiss, ref oFindStop, ref oMiss, ref oMiss, ref oMiss, ref oMiss, ref oMiss, ref oMiss, ref oMiss);
            if (simpleColor != "NoHighlight")
            {
                try
                {
                    string theText = currentWord.Duplicate.Text;
                    string thatText = Regex.Replace(theText, "\r", "");//get rid of carriage return

                    currentWord.Find.Execute(FindText: thatText, Format: true, ReplaceWith: "^&", MatchWildcards: true, Replace: Word.WdReplace.wdReplaceOne);

                }
                catch { }
            }
        currentWord = currentWord.Next(ref oWordUnit, ref oCountOne);
        }
 }

A: Convert a Range.Font.Color to a System.Drawing.Color using Don Rotman's extension method for  Converting Word 2007's WdColor to .NET Color Class
 MSWord.WdColor color = app.Selection.Range.Font.Color;
 Color myColor = color.ToColor(); //ToColor is the extension method described in link

Now, even when the Range.Font.Color does not return an actual enumeration value like WdOrange but instead returns something like: -654245889 , it will be converted to System.Drawing.Color object which contains all of the RGB data.
Works for me. Does it work for you?


text:
Q: read bytes from file in custom (template) array I have a binary file. One piece of data can be 8,16,32,64 bit signed and unsigned int. I'm trying to write the template function and here is what I've done until now:
    public T[] GetLayerBytes<T>(int LayerNum)
    {
        int typeSize = Marshal.SizeOf(typeof(T));

        int layerPixelCount = typeSize * bitmapWidth * bitmapHeigth;

        string recFileName = "my.rec";

        using (FileStream fs = File.OpenRead(recFileName))
        using (BinaryReader br = new BinaryReader(fs))
        {
            fs.Seek(layerPixelCount * LayerNum, SeekOrigin.Begin);
            T[] b = new T[layerPixelCount];

            //fs.Read(b, 0, layerPixelCount); this doesn't work
            //br.Read(b, 0, layerPixelCount); this doesn't work too
            return b;
        }
    }

In C++ I would use CFile::Read for this.
Is there any way to read bytes/int16/uint16 etc. similar to what I've tried without switch/cases for different T types?
Thanks in advance for all possible ellegant solutions.

A: Based on your comments, I'd recommend using the BinaryFormatter.Deserialize method.
The BinaryFormatter has a Binder property which you can use for choosing the type of the object you want.
In addition, I think you'll want to use the SurrogateSelector in order to transform the serialized data however you want...


text:
Q: Conditionally replacing items with two lists I am trying to replace any '-' instances in list A with elements from list B in the same index. Right now my output does not modify list A at all, so I suspect my for loop is working with a copy.
A = [ ["dog", ["corgi",'-',"labrador"]], ["cat", ["tabby","persian",'-']] ]
B = ["BLANK 1","BLANK 2","BLANK 3"]
i = 0
for one,two in zip(A[i][1],B):
    if one == '-':
        one = two
    i += 1
print(A)

I want my output (i.e. modified list A) to look like this:
[ ["dog", ["corgi","BLANK 2","labrador"]], ["cat", ["tabby","persian","BLANK 3"]] ]

Many thanks for any guidance y'all can give me!

A: In order to perform such a complex operation, we can break it down to simpler operations. At the simplest level, we want to replace the dash (-) with another string:
>>> x = 'corgi'
>>> y = 'BLANK 1'
>>> x if x != '-' else y
corgi

>>> x = '-'
>>> y = 'BLANK 2'
>>> x if x != '-' else y
BLANK 2

The next step is to replace ["corgi",'-',"labrador"] with ["corgi",'BLANK 2',"labrador"]:
>>> breed = ["corgi",'-',"labrador"]
>>> B = ["BLANK 1","BLANK 2","BLANK 3"]
>>> zip(breed, B)
[('corgi', 'BLANK 1'), ('-', 'BLANK 2'), ('labrador', 'BLANK 3')]
>>> [x if x != '-' else y for x, y in zip(breed, B)]
['corgi', 'BLANK 2', 'labrador']

Finally, we come to the big picture:
>>> C = [ [animal,
      [x if x != '-' else y for x, y in zip(breed, B)] ]
      for animal, breed in A]

>>> print C
[['dog', ['corgi', 'BLANK 2', 'labrador']], ['cat', ['tabby', 'persian', 'BLANK 3']]]

A: Yes, the for loop merely assigns the values from list created by zip() into the variables one and two.
Instead, you could do something like this:
for sublist in A:
    for index, value in enumerate(sublist[1]):
        if value == '-':
            sublist[1][index] = B[index]

This should work since lists are passed around by reference, and thus the sublist assigned by the outer for loop will still refer to the same lists as are referenced by A.

A: You need to zip over the whole list and then do the dereferencing inside the loop.
for a, b in zip(A, B):
    a[1] = [B[i] if v == '-' else v for i, v in enumerate(a[1])]

A: This works improving your existing code a little bit
A = [ ["dog", ["corgi",'-',"labrador"]], ["cat", ["tabby","persian",'-']] ]
B = ["BLANK 1","BLANK 2","BLANK 3"]

i = 0
while i < 2:
    for ele in A[i][1]:
        if ele == '-':
            dashindex = A[i][1].index(ele)
            A[i][1][dashindex] = B[dashindex]
    i = i+1;
print(A)

Output:

[['dog', ['corgi', 'BLANK 2', 'labrador']], ['cat', ['tabby', 'persian', 'BLANK 3']]]


text:
Q: JPA RollbackException persist transaction causes subsequent valid transactions to fail? I have a @Transactional service performing a persist action into an oracle DB.  If i run a persist breaking a unique violation i get the expected rollbackException:ConstraintException.
The problem is that any subsequent request (even if not breaking the unique constraint) to persist throws the same exception.
It seems like JPA is not clearing the object to persist out of its transaction manager? Am i even close?  I need a little explaination.
Repo:
@Repository
public class UserRepository {

    @PersistenceContext(type=PersistenceContextType.EXTENDED)
    private EntityManager em;

    public User findUserById(long id){
        CriteriaBuilder builder = em.getCriteriaBuilder();
        CriteriaQuery<User> query = builder.createQuery(User.class);

        Root<User> root = query.from(User.class);

        Predicate whereClause = builder.equal(root.get(User_.userId), id);

        return em.createQuery(query.where(whereClause)).getSingleResult();
    }

    public User findUserByCredentials(String credentials){

        CriteriaBuilder builder = em.getCriteriaBuilder();
        CriteriaQuery<User> query = builder.createQuery(User.class);

        Root<User> root = query.from(User.class);

        Predicate whereClause = builder.equal(root.get(User_.credentials), credentials);

        return em.createQuery(query.where(whereClause)).getSingleResult();
    }

    public void registerUser(User user){
         em.persist(user);
    }
}

ServiceImpl:
@Transactional(readOnly=true)
@Service("userService")
public class UserServiceImpl implements UserService {

    @Resource
    private UserRepository userRepository;
    public void setUserRepository(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public User findUserById(long id) {
        return userRepository.findUserById(id);
    }

    public User findUserByCredentials(String credentials){
        return userRepository.findUserByCredentials(credentials);
    }

    @Transactional(readOnly=false)
    public void registerUser(User user){
        userRepository.registerUser(user);
    }

}

error throw in endpoint:
@PayloadRoot(localPart="RegisterUserRequest", namespace = "http://www.missingwire.com/schemas/User")
public RegisterUserResponseDocument registerUser(RegisterUserRequestDocument requestDoc){

    RegisterUserRequest request = requestDoc.getRegisterUserRequest();
    User user = new User();
    user.setCredentials(request.getCredentials());
    user.setPassword(request.getPassword());
    user.setHonorRating(BigDecimal.valueOf(STARTING_USER_HONOR_RATING));
    user.setAccountActive(true);
    user.setDateCreated(new Date());
    user.setVerified(false);

    UserProfile userProfile = new UserProfile();
    userProfile.setEmailAddress(request.getEmail());
    userProfile.setFirstName(request.getFirstName());
    userProfile.setLastName(request.getLastName());
    userProfile.setDateCreated(new Date());
    userProfile.setUser(user);
    user.setUserProfile(userProfile);

    **userService.registerUser(user);**  //HERE IS THE EXCEPTION THROW

    RegisterUserResponseDocument responseDoc = RegisterUserResponseDocument.Factory.newInstance();
    RegisterUserResponse response = responseDoc.addNewRegisterUserResponse();
    UserType userType = response.addNewUser();
    userType.setAccountActive(user.getAccountActive());
    userType.setCredentials(user.getCredentials());
    userType.setDateCreated(DateConverter.convertDateToXML(user.getDateCreated()));
    userType.setUserId(user.getUserId());
    userType.setVerified(user.getVerified());

    return responseDoc;

}

Exception:

org.springframework.orm.jpa.JpaSystemException: Error while committing
  the transaction; nested exception is
  javax.persistence.RollbackException: Error while committing the
  transaction   at
  org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:311)
    at
  org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:102)
    at
  org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerSynchronization.convertException(ExtendedEntityManagerCreator.java:501)
    at
  org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerSynchronization.afterCommit(ExtendedEntityManagerCreator.java:481)
    at
  org.springframework.transaction.support.TransactionSynchronizationUtils.invokeAfterCommit(TransactionSynchronizationUtils.java:133)
    at
  org.springframework.transaction.support.TransactionSynchronizationUtils.triggerAfterCommit(TransactionSynchronizationUtils.java:121)
    at
  org.springframework.transaction.support.AbstractPlatformTransactionManager.triggerAfterCommit(AbstractPlatformTransactionManager.java:953)
    at
  org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:796)
    at
  org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723)
    at
  org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:393)
    at
  org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120)
    at
  org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at
  org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
    at $Proxy37.registerUser(Unknown Source)    at
  com.missingwire.achieve.soa.endpoint.UserEndpoint.registerUser(UserEndpoint.java:76)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:616)     at
  org.springframework.ws.server.endpoint.MethodEndpoint.invoke(MethodEndpoint.java:132)
    at
  org.springframework.ws.server.endpoint.adapter.MarshallingMethodEndpointAdapter.invokeInternal(MarshallingMethodEndpointAdapter.java:140)
    at
  org.springframework.ws.server.endpoint.adapter.AbstractMethodEndpointAdapter.invoke(AbstractMethodEndpointAdapter.java:53)
    at
  org.springframework.ws.server.MessageDispatcher.dispatch(MessageDispatcher.java:231)
    at
  org.springframework.ws.server.MessageDispatcher.receive(MessageDispatcher.java:172)
    at
  org.springframework.ws.transport.support.WebServiceMessageReceiverObjectSupport.handleConnection(WebServiceMessageReceiverObjectSupport.java:88)
    at
  org.springframework.ws.transport.http.WebServiceMessageReceiverHandlerAdapter.handle(WebServiceMessageReceiverHandlerAdapter.java:57)
    at
  org.springframework.ws.transport.http.MessageDispatcherServlet.doService(MessageDispatcherServlet.java:221)
    at
  org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:669)
    at
  org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:585)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)     at
  javax.servlet.http.HttpServlet.service(HttpServlet.java:717)  at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at
  org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at
  org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at
  org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at
  org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at
  org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at
  org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at
  org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
    at
  org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602)
    at
  org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:679) Caused by:
  javax.persistence.RollbackException: Error while committing the
  transaction   at
  org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:93)     at
  org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerSynchronization.afterCommit(ExtendedEntityManagerCreator.java:478)
    ... 39 more Caused by: javax.persistence.PersistenceException:
  org.hibernate.exception.ConstraintViolationException: Could not
  execute JDBC batch update     at
  org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1235)
    at
  org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1168)
    at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:81)
    ... 40 more Caused by:
  org.hibernate.exception.ConstraintViolationException: Could not
  execute JDBC batch update     at
  org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:96)
    at
  org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
    at
  org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
    at
  org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:114)
    at
  org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:109)
    at
  org.hibernate.jdbc.AbstractBatcher.prepareBatchStatement(AbstractBatcher.java:244)
    at
  org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2395)
    at
  org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2858)
    at
  org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:79)
    at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:267)   at
  org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:259)
    at
  org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:178)
    at
  org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
    at
  org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
    at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1206)  at
  org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:375)     at
  org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
    at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:76)
    ... 40 more Caused by: java.sql.BatchUpdateException: ORA-00001:
  unique constraint (ACHIEVE.SYS_C0016488) violated
at
  oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:10070)
    at
  oracle.jdbc.driver.OracleStatementWrapper.executeBatch(OracleStatementWrapper.java:213)
    at
  org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
    at
  org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)

A: You're injecting an entity manager for an extended persistence context. That means that the lifetime of the persistence context is not tied to the lifetime of the transaction: it stays open until you close it explicitely.
Since you got a RollbackException, the persistence context is in a dirty, inconsistent state, and the only thing you can do is close it immediately.
If the persistence context was a transactional one, it would be closed automatically. But since you're using an extended context, it's up to you to close it explicitely.
Make sure to read and understand the following section of the Spring documentation:

The @PersistenceContext annotation has an optional attribute type,
  which defaults to PersistenceContextType.TRANSACTION. This default is
  what you need to receive a shared EntityManager proxy. The
  alternative, PersistenceContextType.EXTENDED, is a completely
  different affair: This results in a so-called extended EntityManager,
  which is not thread-safe and hence must not be used in a concurrently
  accessed component such as a Spring-managed singleton bean. Extended
  EntityManagers are only supposed to be used in stateful components
  that, for example, reside in a session, with the lifecycle of the
  EntityManager not tied to a current transaction but rather being
  completely up to the application.

A: Adding:
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)

To methods you want to exclude transactionallity (queries, for example), you'll avoid this problem.


text:
Q: How to write conditional within html element in blazor? @if (unit.unitNum != null)
 {

@unit.unitNum - @unit.type

 }

Is there a way to right conditional within div element?
I have to write conditional for unit.type too so it will be many ifs.

A: Yes you can write a conditional within a div element.

    @if(unit.unitNum != null)
    {
        @unit.unitNum - @unit.type
    }
    else {
        @* just do whatever you want here or don't write an else clause *@
    }

Note that you can also use String interpolation

    @if(unit.unitNum != null)
    {
        @($"{unit.unitNum} - {@unit.type}")
    }

You could even simplify this a bit more. Also since you didn't specify this, the type of unit.unitNum doesn't really matter here, e.g. it could be an int, or a string.

    @($"{(unit.unitNum != null ? unit.unitNum : "no number found")} - {@unit.type}")


text:
Q: Code only texting me one article rather then all of my scraped data I am trying to scrape data (text) off a website and send it to my phone as an SMS using Twilio. I am using selenium to scrape 5 'articles' from my favourite game and then appending a list which I then send as an SMS to my iphone. I use a for loop to get each article and then add it to the list.
lst = []
news = driver.find_elements_by_class_name("article")
for new in news[:5]:
    the_big_news= str(new.text)
    print(the_big_news)
    print(divider)
    lst.append(new.text + divider)

print(lst)

account_sid = '[sid]'
auth_token = '[token]'
client = Client(account_sid, auth_token)

message = client.messages.create(
    messaging_service_sid='[mssid]',
    body = lst,
    to='[my number]'
)

print(message.sid)

When I run this, I get a text but it is only the first article followed by the divider rather than all the 5 like how it prints out on pycharm. It seems as if my for loop is only running once but i know thats not true because it prints all five articles. My question is how can I get this code to send me all five articles rather then just the first one. If you need me to send more code, i can. Thanks in advance.


text:
Q: Enable PC behind router to be pinged I've got a Windows 7 PC running a webservice accessing the internet through a standard router. I forwarded the required ports in the router accordingly and was able to use the service successfully from outside.
However, when I try to ping the PC, the request never succeeds. From my point of understanding, pings are performed using ICMP, which is not using ports, so I can't forward a port. Is there any way to get ping requests forwarded to and answered by the PC? (The router itself does not answer pings, apparently, nor do I want it to - I'd really prefer the PC to do that.)
Additionally, the PC does already answer pings from within the local network, but do I need to setup Windows so it also answers requests from outside?

A: What do you mean by 'standard router'?  You mention port forwarding which leads me to believe you are talking about a typical consumer router meant for broadband usage.
Routers like this use NAT, to enable them to use a single address from an ISP.  There is probably no way you will be able to forward ICMP to individual machines through a typical cheap-o router.
About the only exception is if your router has a 'DMZ' option.  This option typically allows you to set a single address as a DMZ device.  Any incoming traffic that is not forwarded anywhere else will be forwarded to the DMZ device.

A: With NAT in use, your best bet is to either perform the ping from another device inside the local NAT network or from the NAT router device. Direct ICMP through the NAT is highly unlikely due to the functionality of the NAT.


text:
Q: How do you disconnect from a MySQL server in VSCode? I am connected simultaneously to both a MySQL server (connection is visible at bottom left in VSCode), and an SQL Server (connection is visible at the bottom right of VSCode).
I am creating tables for the SQL Server but the tables are being created in MySQL Server not SQL Server. I want to disconnect VSCode from the MySQL Server without shutting MySQL. I still want MySQL running. But I want the commands in VSCode to be performed in SQL Server.

A: There is no disconnect which unless I'm missing something, is a huge oversight. I cannot have both VSCode extensions running at the same time. Am I the only one who has attempted to use two different flavours of SQL at the same time in VSCode?
I have to disable the viscode-database extension while I am using the SQL Server (mssql) extension.
Even if I stop the MySQL Database in XAMPP for example, VSCode will still try to use the MySQL Server which then just gives errors since I have stopped the MySQL Server.


text:
Q: How to prevent dask client from dying on worker exception? I'm not understanding the resiliency model in dask distributed.
Problem
Exceptions raised by a workers kills embarrassingly parallel dask operation. All workers and clients die if any worker encounters an exception.
Expected Behavior
Reading here: http://distributed.dask.org/en/latest/resilience.html#user-code-failures
Suggests that exceptions should be contained to workers and that subsequent tasks would go on without interruption.

"When a function raises an error that error is kept and transmitted to the client on request. Any attempt to gather that result or any dependent result will raise that exception...This does not affect the smooth operation of the scheduler or worker in any way."

I was following the embarrassingly parallel use case here:
http://docs.dask.org/en/latest/use-cases.html
Reproducible example
import numpy as np
np.random.seed(0)

from dask import compute, delayed
from dask.distributed import Client, LocalCluster

def raise_exception(x):
    if x == 10:
        raise ValueError("I'm an error on a worker")
    elif x == 20:
        print("I've made it to 20")
    else:
        return(x)

if __name__=="__main__":

    #Create cluster
    cluster = LocalCluster(n_workers=2,threads_per_worker=1)
    client = Client(cluster)

    values = [delayed(raise_exception)(x) for x in range(0,100)]
    results=compute(*values,scheduler='distributed')

Task 20 is never accomplished. The exception on task 10 causes the scheduler and workers to die. What am I not understanding about the programming model? Why does this count as gathering? I just want to run each task and capture any exceptions for later inspection, not raise them on the client.
Use Case
Parallel image processing on a University SLURM cluster. My function has a side-effect that saves processed images to file. The processes are independent and never gathered by the scheduler. The exception causes all nodes to die on the cluster.
Cross-listed on issues, since I'm not sure if this is a bug or a feature!
https://github.com/dask/distributed/issues/2436

A: Answered in repo - dask delayed computes all-or-nothing. Use dask map from concurrent futures interface + wait. This was designed, not a bug.
https://github.com/dask/distributed/issues/2436


text:
Q: Lua / Java / LuaJ - Handling or Interrupting Infinite Loops and Threads I'm using LuaJ to run user-created Lua scripts in Java. However, running a Lua script that never returns causes the Java thread to freeze. This also renders the thread uninterruptible. I run the Lua script with:
JsePlatform.standardGlobals().loadFile("badscript.lua").call();

badscript.lua contains while true do end.
I'd like to be able to automatically terminate scripts which are stuck in unyielding loops and also allow users to manually terminate their Lua scripts while they are running. I've read about debug.sethook and pcall, though I'm not sure how I'd properly use them for my purposes. I've also heard that sandboxing is a better alternative, though that's a bit out of my reach.
This question might also be extended to Java threads alone. I've not found any definitive information on interrupting Java threads stuck in a while (true);.
The online Lua demo was very promising, but it seems the detection and termination of "bad" scripts is done in the CGI script and not Lua. Would I be able to use Java to call a CGI script which in turn calls the Lua script? I'm not sure that would allow users to manually terminate their scripts, though. I lost the link for the Lua demo source code but I have it on hand. This is the magic line:
tee -a $LOG | (ulimit -t 1 ; $LUA demo.lua 2>&1 | head -c 8k)

Can someone point me in the right direction?
Some sources:

*

*Embedded Lua - timing out rogue scripts (e.g. infinite loop) - an example anyone?

*Prevent Lua infinite loop

*Embedded Lua - timing out rogue scripts (e.g. infinite loop) - an example anyone?

*How to interrupt the Thread when it is inside some loop doing long task?

*Killing thread after some specified time limit in Java

A: I struggled with the same issue and after some digging through the debug library's implementation, I created a solution similar to the one proposed by David Lewis, but did so by providing my own DebugLibrary:
package org.luaj.vm2.lib;

import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs;

public class CustomDebugLib extends DebugLib {
    public boolean interrupted = false;

    @Override
    public void onInstruction(int pc, Varargs v, int top) {
        if (interrupted) {
            throw new ScriptInterruptException();
        }
        super.onInstruction(pc, v, top);
    }

    public static class ScriptInterruptException extends RuntimeException {}
}

Just execute your script from inside a new thread and set interrupted to true to stop the execution. The exception will be encapsulated as the cause of a LuaError when thrown.

A: There are problems, but this goes a long way towards answering your question.
The following proof-of-concept demonstrates a basic level of sandboxing and throttling of arbitrary user code. It runs ~250 instructions of poorly crafted 'user input' and then discards the coroutine. You could use a mechanism like the one in this answer to query Java and conditionally yield inside a hook function, instead of yielding every time.
SandboxTest.java:
public static void main(String[] args) {
    Globals globals = JsePlatform.debugGlobals();

    LuaValue chunk = globals.loadfile("res/test.lua");

    chunk.call();
}

res/test.lua:
function sandbox(fn)
    -- read script and set the environment
    f = loadfile(fn, "t")
    debug.setupvalue(f, 1, {print = print})

    -- create a coroutine and have it yield every 50 instructions
    local co = coroutine.create(f)
    debug.sethook(co, coroutine.yield, "", 50)

    -- demonstrate stepped execution, 5 'ticks'
    for i = 1, 5 do
        print("tick")
        coroutine.resume(co)
    end
end

sandbox("res/badfile.lua")

res/badfile.lua:
while 1 do
    print("", "badfile")
end

Unfortunately, while the control flow works as intended, something in the way the 'abandoned' coroutine should get garbage collected is not working correctly. The corresponding LuaThread in Java hangs around forever in a wait loop, keeping the process alive. Details here:
How can I abandon a LuaJ coroutine LuaThread?

A: I've never used Luaj before, but could you not put your one line
JsePlatform.standardGlobals().loadFile("badscript.lua").call();

Into a new thread of its own, which you can then terminate from the main thread?
This would require you to make some sort of a supervisor thread (class) and pass any started scripts to it to supervise and eventually terminate if they don't terminate on their own.

A: EDIT: I've not found any way to safely terminate LuaJ's threads without modifying LuaJ itself. The following was what I came up with, though it doesn't work with LuaJ. However, it can be easily modified to do its job in pure Lua. I may be switching to a Python binding for Java since LuaJ threading is so problematic.
--- I came up with the following, but it doesn't work with LuaJ ---
Here is a possible solution. I register a hook with debug.sethook that gets triggered on "count" events (these events occur even in a while true do end). I also pass a custom "ScriptState" Java object I created which contains a boolean flag indicating whether the script should terminate or not. The Java object is queried in the Lua hook which will throw an error to close the script if the flag is set (edit: throwing an error doesn't actually terminate the script). The terminate flag may also be set from inside the Lua script.
If you wish to automatically terminate unyielding infinite loops, it's straightforward enough to implement a timer system which records the last time a call was made to the ScriptState, then automatically terminate the script if sufficient time passes without an API call (edit: this only works if the thread can be interrupted). If you want to kill infinite loops but not interrupt certain blocking operations, you can adjust the ScriptState object to include other state information that allows you to temporarily pause auto-termination, etc.
Here is my interpreter.lua which can be used to call another script and interrupt it if/when necessary. It makes calls to Java methods so it will not run without LuaJ (or some other Lua-Java library) unless it's modified (edit: again, it can be easily modified to work in pure Lua).
function hook_line(e)
    if jthread:getDone() then
        -- I saw someone else use error(), but an infinite loop still seems to evade it.
        -- os.exit() seems to take care of it well.
        os.exit()
    end
end

function inithook()
    -- the hook will run every 100 million instructions.
    -- the time it takes for 100 million instructions to occur
    --   is based on computer speed and the calling environment
    debug.sethook(hook_line, "", 1e8)
    local ret = dofile(jLuaScript)
    debug.sethook()
    return ret
end

args = { ... }
if jthread == nil then
    error("jthread object is nil. Please set it in the Java environment.",2)
elseif jLuaScript == nil then
    error("jLuaScript not set. Please set it in the Java environment.",2)
else
    local x,y = xpcall(inithook, debug.traceback)
end

Here's the ScriptState class that stores the flag and a main() to demonstrate:
public class ScriptState {

    private AtomicBoolean isDone = new AtomicBoolean(true);
    public boolean getDone() { return isDone.get(); }
    public void setDone(boolean v) { isDone.set(v); }

    public static void main(String[] args) {
        Thread t = new Thread() {
            public void run() {
                System.out.println("J: Lua script started.");
                ScriptState s = new ScriptState();
                Globals g = JsePlatform.debugGlobals();
                g.set("jLuaScript", "res/main.lua");
                g.set("jthread", CoerceJavaToLua.coerce(s));
                try {
                    g.loadFile("res/_interpreter.lua").call();
                } catch (Exception e) {
                    System.err.println("There was a Lua error!");
                    e.printStackTrace();
                }
            }
        };
        t.start();
        try { t.join(); } catch (Exception e) { System.err.println("Error waiting for thread"); }
        System.out.println("J: End main");
    }
}

res/main.lua contains the target Lua code to be run. Use environment variables or parameters to pass additional information to the script as usual. Remember to use JsePlatform.debugGlobals() instead of JsePlatform.standardGlobals() if you want to use the debug library in Lua.
EDIT: I just noticed that os.exit() not only terminates the Lua script but also the calling process. It seems to be the equivalent of System.exit(). error() will throw an error but will not cause the Lua script to terminate. I'm trying to find a solution for this now.

A: Thanks to @Seldon for suggesting the use of custom DebugLib. I implemented a simplified version of that by just checking before every instruction if a predefined amount of time is elapsed. This is of course not super accurate because there is some time between class creation and script execution. Requires no separate threads.
class DebugLibWithTimeout(
    timeout: Duration,
) : DebugLib() {

    private val timeoutOn = Instant.now() + timeout

    override fun onInstruction(pc: Int, v: Varargs, top: Int) {
        val timeoutElapsed = Instant.now() > timeoutOn
        if (timeoutElapsed)
            throw Exception("Timeout")
        super.onInstruction(pc, v, top)
    }
}

Important note: if you sandbox an untrusted script calling load function on Lua-code and passing a separate environment to it, this will not work. onInstruction() seems to be called only if the function environment is a reference to _G. I dealt with that by stripping everything from _G and then adding whitelisted items back.
-- whitelisted items
local sandbox_globals = {
    print = print
}

local original_globals = {}
for key, value in pairs(_G) do
    original_globals[key] = value
end

local sandbox_env = _G
-- Remove everything from _G
for key, _ in pairs(sandbox_env) do
    sandbox_env[key] = nil
end

-- Add whitelisted items back.
-- Global pairs-function cannot be used now.
for key, value in original_globals.pairs(sandbox_globals) do
    sandbox_env[key] = value
end

local function run_user_script(script)
    local script_function, message = original_globals.load(script, nil, 't', sandbox_env)
    if not script_function then
        return false, message
    end

    return pcall(script_function)
end


text:
Q: No computer on network can play YouTube videos I have a Netgear FVG318v1 router and all computers on the network cannot play any YouTube videos. I have tried with 3 computers, PC and Mac with all different kinds of browsers.
All I get from YouTube is static and "An error occured, please try again later"
Googling yielded that this seems to be a common problem with that kind of router and some people apparently had MTU issues. I tried several MTUs btw. 1500 and 600 with no luck. I also update the router's firmware to the latest one just now.
I am at my wit's end. Any ideas would be greatly apppreciated!

A: Try doing a traceroute to that hostname and check for circular routing.  I am having the same problem right now with a RV082 and have a ticket in with my ISP.
In my case the hostname is r1---sn-3ovavbt-5bne.googlevideo.com
Edit: confirmed routing issue with my ISP, they fixed it and is working now.

A: Try using a different browser.  I have had this problem when using Chromium for example.  I understand that this may not be a complete solution but try opening a Youtube video that doesn't work in another browser.
For example, some Youtube videos don't work in Chromium for me (I'm on Ubuntu 12.04), while they open and work fine in Firefox.


text:
Q: convert interger to decimal using databinding I have a Integer value: 10000, which I want to databind it to the interface as 100.00.
android:text="@{BigDecimal(viewModel.transactionDetail.transaction.amount).toString()}"

A:
Data binding is not for implementing logics inside view, it is
  provided to attach view to data models.

If you use controllers / handler, you can put your converting logic there. See data binding documentation, you will always see Handlers in their examples.
Way 1
Using handler you can write your converting logic inside handler.
<variable
    name="handler"
    type="com.package.MainHandler"/>

android:text="@{handler.getAmountInDollar(transaction.amount)}"

In your Activity/Fragment
binding.setHandler(new Handler());

In Handler
public String getAmountInDollar(int amount) {
    return new DecimalFormat("##.##").format(amount);
}

Way 2
If you don't use presenter still, you can do this.
public class Transaction {
    private int amount;

    public String getAmountInDollar() {
        return new DecimalFormat("##.##").format(amount);
    }
}

Now you can do this
android:text="@{transaction.amountInDollar}"

That's the way you should do this.


text:
Q: What does this nested struct declaration mean? #include <bits/stdc++.h>

using namespace std;
struct {
  struct {
    struct {
      char *OwO[12];
    }iwi;
  }uwu;
}owo;

int main() {
  *owo.uwu.iwi.OwO = "What's this?";
  printf("%s\n", *owo.uwu.iwi.OwO);
  return 0;
}

Hi guys I don't know how this code actually work? Can anyone explain this to me?

A: Consider for example this declaration
struct {
  char *OwO[12];
}iwi;

It at first declares an unnamed structure with one data member that has the type of an array with 12 elements of the type char *. And then it declares an object named iwi of the structure.
So to access the data member OwO of the object iwi you can use the expression
iwi.OwO

that returns lvalue of the array OwO.
If to apply the operator * to the expression then the array OwO is implicitly converted to pointer to its first element and has the type char **. Dereferencing the pointer we get the first element of the array of the type char *.
We can assign the element with a string literal as
*iwi.OwO = "What's this?";

That is the first element of the array that has the type char * now gets the address of the string literal.
Here is a demonstrative program
#include <stdio.h>

struct {
  char *OwO[12];
} iwi;

int main(void)
{
    *iwi.OwO = "What's this?";

    printf( "%s\n", *iwi.OwO );

    return 0;
}

Its output is
What's this?

In the original code this unnamed structure is included into two other unnamed structures
struct {
  struct {
    struct {
      char *OwO[12];
    }iwi;
  }uwu;
}owo;

That is with have object owo of the unnamed outer structure that has data member uwu of the enclosed unnamed data structure that in turn has data member iwi of the most inner unnamed structure.
So to access the data member OwO we have to list all names of object
owo.uwu.iwi.OwO

So we have gotten an access to the most inner data member OwO. And now dereferncing the expression as it was shown in the demonstrative program above we initialize the first element of the array with the string literal "What's this?".
And in the same way we can output it using this full expression
printf("%s\n", *owo.uwu.iwi.OwO);

A: It's several nested unnamed struct types.
Here is the same thing using named types, and indexing instead of dereferencing.
struct Inner
{
    char* OwO[12];
};

struct Middle
{
    Inner iwi;
};

struct Outer
{
    Middle uwu;
};

Outer owo;

int main() {
  owo.uwu.iwi.OwO[0] = "What's this?";
  printf("%s\n", owo.uwu.iwi.OwO[0]);
  return 0;
}


text:
Q: Filter orders within JOIN just the items i selected via a checkbox MYSQL
I want to filter "orders" according to their items within a form's checkboxes.
For example,
I checked
ITEM A + ITEM B , but not ITEM C
ORDER 1
ITEM A
ORDER 2
ITEM B
ORDER 3
ITEM A
ITEM B
ITEM C
ORDER 4
ITEM A
ITEM B
What i want to have is:
ORDER 1 & ORDER 2 & ORDER 4 ,but not ORDER 3 because this has also ITEM C
MY QUERY LIKE THIS
SELECT
P.id as product_id,P.name as product_name,
O.id as order_id,O.group_id,O.payment_date,O.payment_type_id,I.quantity,
M.name,M.surname,M.email
FROM tbl_orders O
LEFT JOIN tbl_order_items I on I.order_id = O.id
LEFT JOIN tbl_products P on P.id = I.product_id
LEFT JOIN tbl_members M on M.id = O.member_id
WHERE
     I.product_id in (1044,1129,20976,16775)
AND
     O.status_id = 311 and O.payment_status_id = 349

Thank you

A: I'm guessing that the core problem is that you want to EXCLUDE orders which have any of the unchecked values, and INCLUDE orders which have at least one of the checked values.
SELECT
P.id as product_id,P.name as product_name,
O.id as order_id,O.group_id,O.payment_date,O.payment_type_id,I.quantity,
M.name,M.surname,M.email
FROM tbl_orders O -- start with orders

-- add in the items, but use INNER to avoid orders that do not have
-- at least one order_item whose id was checked
INNER JOIN tbl_order_items I on I.order_id = O.id
           AND I.product_id in (1044,1129,20976,16775)
-- left join in the items which were NOT checked.  If there are any, the
-- rows will have bad product ids in them.
-- But if there ARE NOT any bad items in the order,
-- then there will only be one row with NULL for BADITEMS.product_id
LEFT JOIN tbl_order_items BADITEMS on BADITEMS.order_id = O.id
           AND BADITEMS.product_id NOT in (1044,1129,20976,16775)
-- Pull in the product information
INNER JOIN tbl_products P on P.id = I.product_id
-- Pull in member information
LEFT JOIN tbl_members M on M.id = O.member_id
WHERE
     -- the inner join has already insured that we only get orders
     -- that have checked items.
     -- To remove the orders that ALSO had unchecked items,
     -- We take only rows where the BADITEMS join failed.
     BADITEMS.product_id IS NULL
AND
     O.status_id = 311 and O.payment_status_id = 349


text:
Q: Replace src of  by using its  classname $aaa ='

';
$replace = $url;
how to replace 'src' with $replace by using "myclass" ?
is that possible to do like this "preg_replace('some pattern',$replace,$aaa)"; ??

A: $aaa ='

';

This is best way to do it. You dont need class name of parent element.
Alternate Way
If you are sure you want to do it by using classname of parent element try using JS
document.getElementByClassName('myclass')[0].children[0].src='er.jpg';

You can add  this JS code to the PHP file (in script tag) to achieve this.


text:
Q: Div `100%` height with `40px` bottom margin I know something similar has been asked before here.
But it's a little different as it involves css transitions.
http://jsfiddle.net/fariskassim/rWNJN/4/
.panel{

width:inherit;
height: 0%;
display:block;
position: absolute;

background: #000;
opacity:0;
z-index: 2;

margin-top: 40px;
margin-right: 40px;
margin-left: 40px;
margin-bottom: 40px;

bottom:0;
top:0;
left:0;
right:0;

-webkit-transition: all .8s ease-in-out;
-moz-transition: all .8s ease-in-out;
-o-transition: all .8s ease-in-out;
transition: all .8s ease-in-out;

}

When the box is opened,
i'm trying to get the green box have a 40px on all sides from the browser perimeter, I've managed to do it for the left / right and top but bottom is a problem.
Any idea how do i fix this?
EDIT: at the same time, i still want the wipe in and out effect when opening and closing the box.
http://jsfiddle.net/fariskassim/rWNJN/4/

A: Whatever you want + Responsive height
.panel:target{

    background-color: rgba(226, 229, 16, 0.8);
    opacity:100;
    height: auto;

    width:inherit;
    display:block;

    margin-top: 40px;
    margin-right: 40px;
    margin-left: 40px;
    margin-bottom:40px;
    bottom:0;
    top:0;
    left:0;
    right:0;
}

auto adjust demo

A: That is because you have given height:100% in the .panel:target. Remove it then it will be fine.
.panel:target{

    background-color: rgba(226, 229, 16, 0.8);
    opacity:100;

    width:inherit;
    display:block;

    margin-top: 40px;
    margin-right: 40px;
    margin-left: 40px;

    bottom:0;
    top:0;
    left:0;
    right:0;
}

DEMO


text:
Q: r function similar to pmin() but finds nth lowest value across columns in dataframe? I would like a function that would find the nth lowest value across columns. In other words, a function that is similar to pmin() but rather than finding the lowest, I am hoping it returns the nth lowest. Thank you in advance!

A: Here is a simple one (it could be modified to deal with NAs):
nth_lowest <- function(x,n) x[order(x)[n]]

Apply it to a data frame, using rowwise() and c_across() from the dplyr package.
df %>%
  rowwise() %>%
  mutate( second_lowest = f(c_across(x:z),2))

Output:
         x      y      z second_lowest
     <dbl>  <dbl>  <dbl>         <dbl>
 1 -0.560   1.22  -1.07        -0.560
 2 -0.230   0.360 -0.218       -0.218
 3  1.56    0.401 -1.03         0.401
 4  0.0705  0.111 -0.729        0.0705
 5  0.129  -0.556 -0.625       -0.556
 6  1.72    1.79  -1.69         1.72
 7  0.461   0.498  0.838        0.498
 8 -1.27   -1.97   0.153       -1.27
 9 -0.687   0.701 -1.14        -0.687
10 -0.446  -0.473  1.25        -0.446

Input:
set.seed(123)
df <- data.frame(x=rnorm(10), y=rnorm(10), z=rnorm(10))

A: df %>%
  rowid_to_column() %>%
  pivot_longer(-rowid)%>%
  arrange(value)%>% #You could arrange with decreasing to find max
  group_by(rowid) %>%
  summarise(value = nth(value, 2)) # Find the second minimum

# A tibble: 10 x 2
   rowid   value
   <int>   <dbl>
 1     1 -0.560
 2     2 -0.218
 3     3  0.401
 4     4  0.0705
 5     5 -0.556
 6     6  1.72
 7     7  0.498
 8     8 -1.27
 9     9 -0.687
10    10 -0.446

A: We may also do this with pmap and nth
library(purrr)
library(dplyr)
pmap_dbl(df, ~ nth(sort(c(...)), n = 2))


text:
Q: CSP style-src: 'unsafe-inline' in a landing page I use the Webflow tool to set up my website. I export the code to host it on my server.
I have set up the Content-Security-Policy header.
Problem : most of the styles are inline. I can't add the hash for all of them, there are too many ...
Is it so dangerous to put unsafe inline on style-src ?
Note that this is a 99.9% static site (just a contact form).
Thank you for your help!

A: The dangers of 'unsafe-inline' in style-src are discussed here: https://scotthelme.co.uk/can-you-get-pwned-with-css/
If you can restrict the rest of your CSP, the dangers will be limited, but there will always be someone who disagrees. If it is technically possible you could use nonces, as you could use the same nonce for all tags, but change it on every pageload. It seems like you don't want or can extract all the CSS to a separate file, which would of course be the simplest solution.


text:
Q: How to show Toolbar's logo, icon, title, subtitle when wrapped in a CollapsingToolbarLayout? After Android Support Design Library was released, I wanted to implement an effect like a page of Twitter Profile, in which Toolbar's title and subtitle could be changed as screen scrolled vertically. So I tried to use CoordinatorLayout, AppBarLayout, CollapsingToolbarLayout and Toolbar from Android Support Design Library to achieve this effect. Everything worked as expected except that Toolbar's content couldn't be showed or changed as I wanted. I should have been wanting to display collapseIcon, navigationIcon, title, subtitle of Toolbar, but they didn't show up even though I had set them in the layout and programmatically. Just as the blog said,

Note that in those cases, you should call setTitle() on the
  CollapsingToolbarLayout, rather than on the Toolbar itself.

If you have checked the doc, you would find out CollapsingToolbarLayout only focus on settings of title, but can do nothing about collapseIcon, navigationIcon and subtitle.
So could someone tell me how to achieve this effect by Toolbar and CollapsingToolbarLayout? If they couldn't be able, then what other things could be? Anybody has any ideas about this?
Any tips will be appreciated. Thanks in advance.

A: This issue was reported here as a bug. I have personally experienced this with one of my apps. Setting the topMargin for the toolbar works for me. As somebody commented on the bug report, here is the fix, as a function from the issue report.
private void fixApi21ToolBarBug(Toolbar toolbar){
    if(Build.VERSION.SDK_INT!=21) return; //only on api 21
    final int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
    final int result = (resourceId > 0) ? getResources().getDimensionPixelSize(resourceId) * 2 : 0;
    final CollapsingToolbarLayout.LayoutParams params = (CollapsingToolbarLayout.LayoutParams) toolbar.getLayoutParams();
    params.topMargin -= result;
    toolbar.setLayoutParams(params);
}

See the result here.

A: Ran into the same issue. For me it was fixed by removing the android:fitsSystemWindows="true" from the layoutparameters. However, this will mean that the status bar will not be part of the collapsing Toolbar backdrop.


text:
Q: Calling a function in a sibling self-executing function So, I'm trying to call a function from another function that doesn't share the same scope.
As you can see, we have the jQuery function and then the callback function that is calling it. I should also note that Swiper is a touch slider, but I'm not sure it's relevant in this case, because I want to understand theoretically how I can call a function that sits within an anonymous function.
jQuery(function($) {
  var productPageSwiper = new Swiper('.swiper-container',{
    spaceBetween: 10,
    centeredSlides: true
  });
});

var callback = function(){
  productPageSwiper.slideTo(3);
}

callback();

A: If you can make productPageSwiper accessible to both functions by increasing it's scope, that will work.
jQuery(function($) {
  window.productPageSwiper = new Swiper('.swiper-container',{
    spaceBetween: 10,
    centeredSlides: true
  });
});

var callback = function(){
  window.productPageSwiper.slideTo(3);
}

callback();

Or to avoid polluting the global scope:
jQuery(function($) {
  productPageSwiper = new Swiper('.swiper-container',{
    spaceBetween: 10,
    centeredSlides: true
  });
});

var callback = function(swiper) {
  swiper.slideTo(3);
}

callback(productPageSwiper);


text:
Q: $this->getOrders() I am using Magento 1.7.
In recent.phtml under app/design/frontend/default/custom_theme/template/sales/order, there is the following call:
$_orders = $this->getOrders();

and later on $_orders is used to extract each one of the orders. I know that getOrders() returns the orders for that customer, but I was trying to find the definition of getOrders(), but seem to be not able to find it.
I used <?php var_dump(get_class($this)); ?> at the start of recent.phtml to look for the method in the returned class, but still can't find it.
I also read that from the use of Zend, it is possible to use set or get functions that are not defined.
Could you please tell me if I understood something wrong and how could I find the method definition? Any help will be much appreciated.

A: Open this file app\code\core\Mage\Sales\Block\Order\Recent.php. Check inside the __construct they are setting the orders.
like this $this->setOrders($orders);.

A: set and get is magento's magic methods
Magento magic methods are define in class Varien_Object located in lib/Varien/Object.php
    public function __call($method, $args)
    {
        switch (substr($method, 0, 3)) {
            case 'get' :
                //Varien_Profiler::start('GETTER: '.get_class($this).'::'.$method);
                $key = $this->_underscore(substr($method,3));
                $data = $this->getData($key, isset($args[0]) ? $args[0] : null);
                //Varien_Profiler::stop('GETTER: '.get_class($this).'::'.$method);
                return $data;
            case 'set' :
                //Varien_Profiler::start('SETTER: '.get_class($this).'::'.$method);
                $key = $this->_underscore(substr($method,3));
                $result = $this->setData($key, isset($args[0]) ? $args[0] : null);
                //Varien_Profiler::stop('SETTER: '.get_class($this).'::'.$method);
                return $result;
            case 'uns' :
                //Varien_Profiler::start('UNS: '.get_class($this).'::'.$method);
                $key = $this->_underscore(substr($method,3));
                $result = $this->unsetData($key);
                //Varien_Profiler::stop('UNS: '.get_class($this).'::'.$method);
                return $result;
            case 'has' :
                //Varien_Profiler::start('HAS: '.get_class($this).'::'.$method);
                $key = $this->_underscore(substr($method,3));
                //Varien_Profiler::stop('HAS: '.get_class($this).'::'.$method);
                return isset($this->_data[$key]);
        }
        throw new Varien_Exception("Invalid method ".get_class($this)."::".$method."(".print_r($args,1).")");
    }

What Magento (or PHP for that matter) does is looks for a method called getOrders() . Simple enough. When it cannot find it, it looks up through it's parent classes until it simply cannot find getOrders()  anywhere. When it reaches this point, it goes through it's last resort, the __call()  method. Basically it passes the method and it's arguments to the __call()  method.
What Magento does from this point is sees whether or not the method begins with any of these prefixes: get, set, uns, has. From there, it accesses or manipulates the protected $_data  array within the object.
get fetches the data, set sets new data in the key, uns unsets data from that key, and has returns a boolean value on whether or not that key exists in the array.
So magento Mage_Sales_Block_Order_Recent::__construct() method setOrders order using $this->setOrders($orders); and we can fetch that data using magento magic methos $this->getOrders();
To know more about magic mathod visit this reference link


text:
Q: Error while running bundle update after doing git clone I'm using window operating system for ruby on rails application.
I just clone the git repository which is a ruby on rails application. But, when I do bundle update it shows this error
libv8-node 15.14.0.1 with native extensions
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.
bundle update
Fetching https://github.com/mimemagicrb/mimemagic.git
Fetching https://github.com/scambra/devise_invitable.git
Fetching gem metadata from https://rubygems.org/.........
Fetching gem metadata from https://rubygems.org/.
Resolving dependencies................
Using rake 13.0.4 (was 13.0.3)
Using concurrent-ruby 1.1.9 (was 1.1.8)
Using i18n 1.8.10
Using minitest 5.14.4
Using thread_safe 0.3.6
Using tzinfo 1.2.9
Using activesupport 5.1.7
Using builder 3.2.4
Using erubi 1.10.0
Using racc 1.5.2
Using nokogiri 1.11.7 (x64-mingw32) (was 1.11.2)
Using rails-dom-testing 2.0.3
Using crass 1.0.6
Using loofah 2.10.0 (was 2.9.0)
Using rails-html-sanitizer 1.3.0
Using actionview 5.1.7
Using rack 2.2.3
Using rack-test 1.1.0
Using actionpack 5.1.7
Using nio4r 2.5.7
Using websocket-extensions 0.1.5
Using websocket-driver 0.6.5
Using actioncable 5.1.7
Using globalid 0.4.2
Using activejob 5.1.7
Using mini_mime 1.1.0
Using mail 2.7.1
Using actionmailer 5.1.7
Using activemodel 5.1.7
Using arel 8.0.0
Using activerecord 5.1.7
Using public_suffix 4.0.6
Using addressable 2.8.0 (was 2.7.0)
Using execjs 2.8.1 (was 2.7.0)
Using autoprefixer-rails 10.2.5.1 (was 10.2.4.0)
Using awesome_print 1.9.2
Using bcrypt 3.1.16
Using method_source 1.0.0
Using thor 1.1.0
Using railties 5.1.7
Using best_in_place 3.0.3
Using bindex 0.8.1
Using popper_js 1.16.0
Using rb-fsevent 0.11.0 (was 0.10.4)
Using ffi 1.15.3 (x64-mingw32) (was 1.15.0)
Using rb-inotify 0.10.1
Using sass-listen 4.0.0
Using sass 3.7.4
Using bootstrap 4.1.3
Using bundler 1.17.3
Using byebug 11.1.3
Using xpath 3.2.0
Using capybara 2.18.0
Using mini_magick 4.11.0
Using ruby-vips 2.1.2 (was 2.1.0)
Using image_processing 1.12.1
Using marcel 1.0.1
Using ssrf_filter 1.0.7
Using carrierwave 2.2.2 (was 2.2.1)
Using chartkick 4.0.5 (was 3.4.2)
Using childprocess 3.0.0
Using chronic 0.10.2
Using chunky_png 1.4.0
Using cocoon 1.2.15
Using coffee-script-source 1.12.2
Using coffee-script 2.4.1
Using coffee-rails 4.2.2
Using copy_carrierwave_file 1.3.0
Using orm_adapter 0.5.0
Using responders 3.0.1
Using warden 1.2.9
Using devise 4.8.0 (was 4.7.3)
Using devise_invitable 2.0.5 (was 2.0.3) from https://github.com/scambra/devise_invitable.git (at master@db1f065)
Using dotenv 2.7.6
Using dotenv-rails 2.7.6
Using exception_notification 4.4.3
Using excon 0.84.0 (was 0.79.0)
Using faker 2.18.0 (was 2.17.0)
Using faraday-em_http 1.0.0
Using faraday-em_synchrony 1.0.0
Using faraday-excon 1.1.0
Using faraday-httpclient 1.0.1
Using faraday-net_http 1.0.1
Using faraday-net_http_persistent 1.1.0
Using faraday-patron 1.0.0
Using multipart-post 2.1.1
Using ruby2_keywords 0.0.4
Using faraday 1.5.0 (was 1.3.0)
Using formatador 0.3.0 (was 0.2.5)
Using mime-types-data 3.2021.0704 (was 3.2021.0225)
Using mime-types 3.3.1
Using fog-core 2.2.4 (was 2.2.3)
Using multi_json 1.15.0
Using fog-json 1.2.0
Using fog-xml 0.1.3
Using ipaddress 0.8.3
Using fog-aws 3.10.0
Using font-awesome-rails 4.7.0.7
Using groupdate 5.2.2
Using sprockets 3.7.2
Using sprockets-rails 3.2.2
Using rails 5.1.7
Using invisible_captcha 2.0.0
Using jbuilder 2.11.2
Using jquery-rails 4.4.0
Using jquery-ui-rails 6.0.1
Using jwt 2.2.3 (was 2.2.2)
Using kaminari-core 1.2.1
Using kaminari-actionview 1.2.1
Using kaminari-activerecord 1.2.1
Using kaminari 1.2.1
Fetching libv8-node 15.14.0.1
Installing libv8-node 15.14.0.1 with native extensions
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

current directory:
C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/libv8-node-15.14.0.1/ext/libv8-node
C:/Ruby27-x64/bin/ruby.exe -I C:/Ruby27-x64/lib/ruby/2.7.0 -r
./siteconf20210707-3776-1v98cj2.rb extconf.rb
creating Makefile
C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/libv8-node-15.14.0.1/ext/libv8-node/builder.rb:12:in
`build_libv8!': failed to download node 15.14.0 (Libv8::Node::BuilderError)
from
C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/libv8-node-15.14.0.1/ext/libv8-node/location.rb:30:in
`install!'
        from extconf.rb:9:in `<main>'
==== in
C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/libv8-node-15.14.0.1/ext/libv8-node
==== running
C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/libv8-node-15.14.0.1/libexec/download-node

extconf failed, exit code 1

Gem files will remain installed in
C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/libv8-node-15.14.0.1 for inspection.
Results logged to
C:/Ruby27-x64/lib/ruby/gems/2.7.0/extensions/x64-mingw32/2.7.0/libv8-node-15.14.0.1/gem_make.out

An error occurred while installing libv8-node (15.14.0.1), and Bundler cannot
continue.
Make sure that `gem install libv8-node -v '15.14.0.1' --source
'https://rubygems.org/'` succeeds before bundling.

In Gemfile:
  mini_racer was resolved to 0.4.0, which depends on
    libv8-node

Here are the versions that I'm using
Rails 6.1.4
ruby 2.7.3p183 (2021-04-05 revision 6847ee089d) [x64-mingw32]
Bundler version 2.2.21

When I do bundle install it shows this,
bundle install
Fetching gem metadata from https://rubygems.org/.........
Fetching gem metadata from https://rubygems.org/.
Resolving dependencies....
Bundler could not find compatible versions for gem "ruby ":
  In Gemfile:
    ruby

    spring-watcher-listen (~> 2.0.0) was resolved to 2.0.1, which depends on
      listen (>= 2.7, < 4.0) was resolved to 3.1.5, which depends on
        rb-inotify (~> 0.9, >= 0.9.7) was resolved to 0.10.1, which depends on
          ffi (~> 1.0) was resolved to 1.15.0, which depends on
            ruby  (< 3.1.dev, >= 2.3) x64-mingw32

    capybara (~> 2.13) was resolved to 2.18.0, which depends on
      nokogiri (>= 1.3.3) was resolved to 1.11.2, which depends on
        ruby  (< 3.1.dev, >= 2.5) x64-mingw32

    pg (~> 0.18) was resolved to 0.21.0, which depends on
      ruby  (< 2.5, >= 2.0) x64-mingw32

Could not find gem 'ruby  (< 2.5, >= 2.0)', which is required by gem 'pg (~>
0.18)', in any of the relevant sources:
  the local ruby installation

Here is the gem file,

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
# gem 'rails', '~> 5.1.4'
rails_version = "~> 5.1.4"
gem "activesupport",  rails_version
gem  "actionpack",    rails_version
gem  "actionview",    rails_version
gem  "activemodel",   rails_version
gem  "activerecord",  rails_version
gem  "activejob",     rails_version
gem  "actioncable",   rails_version
gem  "railties",      rails_version

gem "sprockets-rails", ">= 2.0.0"
# Use postgresql as the database for Active Record
gem 'pg', '~> 0.18'
# Use Puma as the app server
gem 'puma', '~> 3.7'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
# gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
gem 'dotenv-rails'
gem 'mimemagic', github: 'mimemagicrb/mimemagic', ref: '01f92d86d15d85cfd0f20dabd025dcbd36a8a60f'
gem 'awesome_print', require: 'ap'
gem 'carrierwave'
gem 'fog-aws'
gem 'jquery-rails'
gem 'jquery-ui-rails'
gem 'rqrcode'
gem 'devise'
gem 'faker'
gem 'kaminari'
gem "chartkick"
gem 'groupdate'
gem 'rubyzip', require: 'zip'
gem 'pdfkit', require: 'pdfkit'
gem 'mini_magick'
gem 'best_in_place', '~> 3.0.1'
gem 'rails3-jquery-autocomplete'
gem 'zip_tricks'
gem 'bootstrap', '~> 4.1.1'
gem "cocoon"
gem "font-awesome-rails"
gem 'devise_invitable', github: 'scambra/devise_invitable'
gem 'invisible_captcha'
gem 'mini_racer'
gem 'exception_notification'
gem 'copy_carrierwave_file'

##SMS stuff
gem 'twilio-ruby'
gem 'whenever'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  # Adds support for Capybara system testing and selenium driver
  gem 'capybara', '~> 2.13'
  gem 'selenium-webdriver'
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '>= 3.0.5', '< 3.2'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

A: Your pg gem version is 0.8 which requires ruby < 2.5
If you want to use with ruby > 2.5 you will have to upgrade the pg gem.
You can use RailsBump to check for all the supported version for any particular gem


text:
Q: How can you control the compile order in leininigen? This should be a simple problem to solve but every time I try to compile I am getting class not found exceptions caused by the fact that leininigen is trying to compile classes in the wrong order. I've gone as far as trying to explicitly define the order classes should be compiled on the project.clj file using the :aot but that is being ignored. The files that are getting class not found exceptions have :require statements in the ns declaration but they are also being ignored. How can I change the compile order?
I have used lein clean because I had some stale classes that the system was refusing to overwrite and now it won't compile at all. I am getting very frustrated with this language as it seems nothing works the way it should.
Here is an example error I'm getting (replaced base namespace with )
Exception in thread "main" java.lang.NoClassDefFoundError: <MyProject>/util$loading__4910__auto__, compiling:(obj.clj:1:1)

The file that it is failing in contains ...
(ns <MyProject>.obj
  (:gen-class)
  (:require <MyProject>.util)
)

util.clj contains...
(ns <MyProject>.util
  (:gen-class)
)

project.clj contains...
  :aot [
    ;...
    <MyProject>.util
    <MyProject>.obj
    ;...
  ]


text:
Q: Cannot import MySQLdb - python - Windows 8.1 I am trying to import MySQLdb in python. I checked and followed all possible solutions but I am still not able to import it. I have Windows 8.1.
So I started fresh, I installed the latest version of python (2.7.8), set the path and pythonpath variables, and then tried installing the MySQL-python-1.2.5.win-amd64-py2.7  from the link (https://pypi.python.org/pypi/MySQL-python/)
This is the error I get
>>> import MySQLdb
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named MySQLdb

I have tried searching and following many links. Nothing worked!! Can someone please help me with this.
Thanks

A: Issue resolved.
I dint have a C compiler / Visual Studio in my laptop - This link might help http://mysql-python.blogspot.com/2012/11/is-mysqldb-hard-to-install.html
I installed MinGW - http://sourceforge.net/projects/mingw/?source=typ_redirect
Selected the c++ option
I uninstalled Anaconda, Python and Installed anaconda again. So python 2.7.7 got installed along with Anaconda. Did a conda init,
conda install pip

pip install mysql-python

and then import MySQLdb
No Error!! Hope this helps!!
====================================================================
Update - Jan 2, 2015
If you want to try installing mysql-python package using conda instead of pip, you can try the following, which worked for me.
conda install binstar

binstar search -t conda mysql-python

This will show you 10 different packages for different OS.
krisvanneste mysql-python is for Win-64
To know more about this package use the command
 binstar show krisvanneste/mysql-python

This will show you the command to install the mysql-python package which happens to be
conda install --channel https://conda.binstar.org/krisvanneste mysql-python

This will install the required package.
Now trying import MySQLdb in python wont throw error.


text:
Q: Python: add the key to each list item, and then convert to dictionary lst = [1,2,3,4]

I have hard coded keys ['one','two','three','four','five']
and I want the dictionary like
{'one':1, 'two':2, 'three':3, 'four':4, 'five':None}

Keys are always more than the number of items in list.

A: Here are a couple of ways to do it
>>> K=['one','two','three','four','five']
>>> V=[1,2,3,4]
>>> dict(map(None, K, V))
{'four': 4, 'three': 3, 'five': None, 'two': 2, 'one': 1}

>>> D=dict.fromkeys(K)
>>> D.update(zip(K,V))
>>> D
{'four': 4, 'three': 3, 'five': None, 'two': 2, 'one': 1}

A: import itertools

lst = [1,2,3,4]
lst2 = ['one','two','three','four','five']

print dict(itertools.izip_longest(lst2, lst, fillvalue=None))
# {'five': None, 'four': 4, 'one': 1, 'three': 3, 'two': 2}

A: >>> dict(zip(keys, lst + [None]*(len(keys)-len(lst))))
{'four': 4, 'three': 3, 'five': None, 'two': 2, 'one': 1}


text:
Q: web server to application server communication I Need to pass request from web server to application server.
web server and application server lies in a separate box.
so what is the best technology to use in this scenario ?
Web Server : I have html page, i need to fill it and submit.
Application server : I need  to receive that submitted request with all the form values and need to perform some action.
in application layer , i am planning to do mapping to spring controller , is it fine ?
please explain the best possible solution.

A: Personal experience is use service-oriented-architecture for communications between servers.
So if u have App Server that wants to communicate with Web Server then create services (e.g. WSDL) that will manage that communication.
This will enable data management, consistency, security and potentially transformation (if you need it).
The biggest benefit we have seen is the ability to remove the server and replace it without any other changes to code and still have it work off the bat.
Hope that helps


text:
Q: No type parameters for method with tricky Higher Kind Let's set up issue conditions
trait Bound

class T1[B <: Bound]

class WrapperT1[B <: Bound, T2[B2 <: Bound] <: T1[B2]](val t: T2[B])

class WrapperT2[HB <: Bound, B <: HB, T2[B2 <: HB] <: T1[B2]](val t: T2[B])

Problem comes when i'm defining a method to auto infered argument type on WrapperT2.
def autoInferedMethod[B <: Bound, T2[B2 <: Bound] <: T1[B2]](arg: WrapperT1[B, T2]): Unit = Unit

def notAutoInferedMethod[HB <: Bound, B <: HB, T2[B2 <: HB] <: T1[B2]](arg: WrapperT2[HB, B, T2]): Unit = Unit

// Works
autoInferedMethod(new WrapperT1[Bound, T1](new T1[Bound]))
// Works
autoInferedMethod(new WrapperT1(new T1[Bound]))

// Doesn't works
notAutoInferedMethod(new WrapperT2[Bound, Bound, T1](new T1[Bound]))
// Compilator errors

no type parameters for method notAutoInferedMethod: (arg: ex.Q2.WrapperT2[HB,B,T2])Unit exist so that it can be applied to arguments (ex.Q2.WrapperT2[ex.Bound,ex.Bound,ex.T1])

[error]  --- because ---

[error] argument expression's type is not compatible with formal parameter type;

[error]  found   : ex.Q2.WrapperT2[ex.Bound,ex.Bound,ex.T1]

[error]  required: ex.Q2.WrapperT2[?HB,?B,?T2]

[error]     notAutoInferedMethod(new WrapperT2[Bound, Bound, T1](new T1[Bound]))

[error]  found   : ex.Q2.WrapperT2[ex.Bound,ex.Bound,ex.T1]

[error]  required: ex.Q2.WrapperT2[HB,B,T2]

[error]     notAutoInferedMethod(new WrapperT2[Bound, Bound, T1](new T1[Bound]))

I'm supposed it comes from
[HB <: Bound, ..., T2[B2 <: HB] <: ...]

But i have no idea for why and if there it exists a workaround for it, any help to understand this issue is welcome.
Update, it seems to works on 2.13 but not on 2.11/2.12


text:
Q: Can't click on the website using Selenium I thought I understood the concept but I guess I don't ..
I would like to click on a button from a list of tabs on a HTML page

Today

My timesheet

#list continues ....

I would like to click on the tab "sub_tab_timeclock_my_timesheet" so in my code I did
# some code

driver = webdriver.Chrome(driverPath)

driver.get(url)

username = driver.find_element_by_id("user_handle")
password = driver.find_element_by_id("user_password")

username.send_keys("myUser")
password.send_keys("myPass")

driver.find_element_by_class_name("button1").click()

driver.find_element_by_id("sub_tab_timeclock_my_timesheet").click()

I did pass the login page but then I don't understand why my code doesn't work for clicking on the tab "My timesheet" which has the ID "sub_tab_timeclock_my_timesheet".
The error message is :
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="sub_tab_timeclock_my_timesheet"]"}
  (Session info: chrome=85.0.4183.83)

What am I doing wrong ?
Thanks,

A: It seems like you may be encountering a timing issue. Try implementing a wait in between driver.find_element_by_class_name("button1").click() and driver.find_element_by_id("sub_tab_timeclock_my_timesheet").click().
To do so, you'll need to do something like this:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

try:
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "sub_tab_timeclock_my_timesheet"))
    )
finally:
    driver.quit()

Not too sure about the Python code as I'm a .NET dev, but check this article for syntax specifics:
https://selenium-python.readthedocs.io/waits.html