text:
Q: Interpose C struct function pointer i'm trying to interpose function declared as a pointer in a C struct inside dynamic library on macOS.
I have this struct in libA.dylib:
libA.h:
typedef struct AStruct {
    int (*sub)(AStruct *pAStruct, int a, int b);
} AStruct;

extern "C" AStruct * AStruct_new();

libA.cpp:
int sub(AStruct *pAStruct, int a, int b) {
    return a - b;
}

AStruct * AStruct_new() {
    AStruct *pAStruct = (AStruct *)malloc(sizeof(AStruct));
    pAStruct->sub = *sub;
    return pAStruct;
}

after name mangling, i've figured out that corresponding name in library is this: _Z3subP7AStructii
inside my dylib (which i'm injecting into a client code) i'm doing this:
typedef struct AStruct {
    int (*sub)(AStruct *pAStruct, int a, int b);
} AStruct;

extern "C" int _Z3subP7AStructii(AStruct *pAStruct, int a, int b);

int _sub(AStruct *pAStruct, int a, int b) {
    printf("interposed %s: ", __func__);
    return pAStruct->sub(pAStruct, a, b);
} DYLD_INTERPOSE(_sub, _Z3subP7AStructii)

DYLD_INTERPOSE - is Apple's macro from here
the same code successfully works for regular C function, C++ static/instance methods, can't figured out what's wrong with function pointer inside struct :(

A: If I understand correctly, you want all calls to sub (or rather _Z3subP7AStructii) to actually be calling your _sub function instead? The problem is that when the "client" calls some_astruct->sub(...) it doesn't actually call _Z3subP7AStructii directly, and therefore your _sub function won't be called.
In other words, the "client" doesn't have a call to _Z3subP7AStructii, but instead it have a call to whatever some_astruct->sub is pointing to. The _Z3subP7AStructii function could even not be exported by the libA library (i.e. have internal linkage with e.g. static), and it could still be called through the structure.
A possible solution to this is not to "interpose" the sub function, but instead the AStruct_create function. In your version call the original, then replace the pointer to the sub function in the structure to your own function (possibly saving the original so you can use it).


text:
Q: Java Class cannot override method in abstract class which has a method signature that contains an interface I have the setup:
public abstract class AbstractDbManager {

    public abstract boolean createTable();

    public abstract int insert(Stockable rm);

    public abstract Stockable get(String key);

    public abstract int save(Stockable rm);

}

public interface Stockable {

}

public class Stock implements Stockable{

}

public class StockDbManager extends AbstractDbManager{

    @Override
    public boolean createTable() {
        return true;
    }

    @Override
    public int insert(Stock stk) {
     return 0;
    }

    @Override
    public Stock get(String key) {
        return null;
    }

    @Override
    public int save(Stock stk) {
        return 0;
    }

}

Why wont the methods: int insert(Stock stk) and  int save(Stock stk)  in StockDbManager override the methods:
abstract int insert(Stockable rm); and abstract int save(Stockable rm); in AbstractDbManager despite the fact that every Stock is also a Stockable ?
Note however that  Stock get(String key) method in StockDbManager successfully overrides the abstract Stockable get(String key); method in AbstractDbManager.

A: The method insert(Stockable) requires that it accepts all implementations of Stockable, and your implementation does not satisfy that requirement of the contract: it only accepts a specific implementation of Stockable (ie Stock).
For return values this works different: Stockable get(..) says it will return a Stockable, and given Stock is a Stockable, narrowing it down in the implementation to Stock get(..) is acceptable as it fulfills the contract.

redpajama_set_name: RedPajamaStackExchange


text:
Q: IOS 10 Swift 3 Core plot does not display Y grid I am trying to use coreplot pod and I am not able to figure out how to display "Y Axis" grid nor ticks on Axes itself, please have a look at my code bellow and advise
Thank you.`
        let yAxis = axisSet.yAxis
    yAxis?.labelingPolicy = CPTAxisLabelingPolicy.fixedInterval
    yAxis?.majorIntervalLength = plotYInterval as NSNumber?
    yAxis?.minorTicksPerInterval = 4
    yAxis?.minorTickLength = 5
    yAxis?.majorTickLength = 7
    yAxis?.title = "Degree C"
    yAxis?.titleOffset = 5
    yAxis?.labelFormatter = axisLabelFormatter

Hi Eric,
here the full init code
func initLinePlot() {
    //Initialize and display Graph (x and y axis lines)
    graph = CPTXYGraph(frame: graphView.bounds)
    self.graphView.hostedGraph = self.graph;

    //apply styling to Graph
    graph?.apply(CPTTheme(named: CPTThemeName.plainWhiteTheme))

    //set graph backgound area transparent
    graph?.fill = CPTFill(color: CPTColor.clear())
    graph?.plotAreaFrame?.fill = CPTFill(color: CPTColor.clear())
    graph?.plotAreaFrame?.fill = CPTFill(color: CPTColor.clear())

    //This removes top and right lines of graph
    graph?.plotAreaFrame?.borderLineStyle = CPTLineStyle(style: nil)
    //This shows x and y axis labels from 0 to 1
    graph?.plotAreaFrame?.masksToBorder = false

    // set padding for graph from Left and Bottom
    graph?.paddingBottom = 30;
    graph?.paddingLeft = 20;
    graph?.paddingRight = 0;
    graph?.paddingTop = 0;

    //Define x and y axis range
    let plotSpace = graph?.defaultPlotSpace
    plotSpace?.allowsUserInteraction = true
    plotSpace?.delegate = self;

//       self.resetPlotRange()
    let axisSet = graph?.axisSet as! CPTXYAxisSet;

    let axisLabelFormatter = NumberFormatter()
    axisLabelFormatter.generatesDecimalNumbers = false
    axisLabelFormatter.numberStyle = NumberFormatter.Style.decimal

    //Define x-axis properties
    //x-axis intermediate interval 2
    let xAxis = axisSet.xAxis
    xAxis?.majorIntervalLength = plotXInterval as NSNumber?
    xAxis?.minorTicksPerInterval = 4;
    xAxis?.minorTickLength = 10;
    xAxis?.majorTickLength = 15;
    xAxis?.title = "Time (s)"
    xAxis?.titleOffset = 10;
    xAxis?.labelFormatter = axisLabelFormatter

    //Define y-axis properties
    let yAxis = axisSet.yAxis
    yAxis?.labelingPolicy = CPTAxisLabelingPolicy.fixedInterval
    yAxis?.majorIntervalLength = plotYInterval as NSNumber?
    yAxis?.minorTicksPerInterval = 4
    yAxis?.minorTickLength = 5
    yAxis?.majorTickLength = 7
    yAxis?.title = "Degree C"
    yAxis?.titleOffset = 5
    yAxis?.labelFormatter = axisLabelFormatter

    //Define line plot and set line properties
    linePlot = CPTScatterPlot()
    linePlot?.dataSource = self
    graph?.add(linePlot!, to: plotSpace)

    //set line plot style
    let lineStyle = linePlot?.dataLineStyle!.mutableCopy() as! CPTMutableLineStyle
    lineStyle.lineWidth = 2
    lineStyle.lineColor = CPTColor.blue()
    linePlot!.dataLineStyle = lineStyle;

    //set graph grid lines
    let gridLineStyle = CPTMutableLineStyle()
    gridLineStyle.lineColor = CPTColor.red()
    gridLineStyle.lineWidth = 2// 0.5
    xAxis?.majorGridLineStyle = gridLineStyle
    yAxis?.majorGridLineStyle = gridLineStyle
    yAxis?.majorTickLineStyle = gridLineStyle
}

A: For the fixedInterval labeling policy, the majorIntervalLength determines the distance between major tick marks. By default, numbering starts at zero (0), so tick marks will only be visible if they fall within the yRange of the plot space. For example, if the ticks are 10 units apart, but the range only covers five units, there may not be any visible ticks in that range.
The default line style for major tick marks is a black line one (1) point wide. Set the majorTickLineStyle to use a different style. Grid lines are not drawn by default. Set the majorGridLineStyle to show the grid lines. There are corresponding properties for minor tick marks and grid lines, too.


text:
Q: Why doesn't "Open console here" open cmd on the correct drive if not used on the C-Drive? When I [Shift + Right-Click] a folder that isn't on my C drive and select "Open console here" I get a cmd window up that isn't opened at the correct location, but instead is pointing at C:\Windows\system32. I have to manually switch to the correct drive, but when I do it is then at the correct folder. This is hardly the end of the world, but it's a minor annoyance that's really starting to get on my nerves...
Note: It does work correctly for locations on the Cdrive.
Is this the expected behaviour when used outside of C?
If not, how do I fix it?
If it is, how can I change it to load folders of other drives directly?

For example, if I attempt to open a console window pointing at a folder on my desktop, like so:

I get a cmd window pointing at C:\Windows\system32 that I have to manually switch to the D:, but upon doing so you can see that the folder within D: has been selected successfully:

Update
It seems "Open console here" might be non-standard (see comments).
For completeness, it turns out that I see the probably standard "Open command window here" lower down the list when clicking inside a folder (it's "file space", not on the folder icon itself), as per the image below, so there's some difference between the two that's cropped up:

A: Having examined the registry and asked people on chat, I've determined that the parameters being passed to the instance of cmd that was invoked here were incorrect.
The command can be found in [HKEY_CLASSES_ROOT\Directory\shell\cmd\command] and I had a (Default) value of:
cmd.exe /k cd \"%L\"

Changing this to the following value (obtained in that brief chat session) has resolved the issue:
cmd.exe /s /k pushd \"%V\"

That said, while the problem is fixed, I don't know what caused this change initially...

A: The self-answer by DMA57361 clearly has solved the original problem. I thought I'd add some info I discovered....
First, I noticed a suspicious value in the key HKEY_CLASSES_ROOT\Directory\shell\cmd named Extended. On a hunch, I renamed that value to xxx-Extended and now the "Open command window here" menu item often appears without the Shift key. Since the old tweak-ui solution didn't require the shift key, this discovery makes me happy!
Second, my relatively unmodified Windows 7 Pro 64-bit installation has the registry key HKEY_CLASSES_ROOT\Directory\shell\cmd\command with only a default value of cmd.exe /s /k pushd "%V" set (Note that the type is REG_SZ, not REG_EXPAND_SZ. The meaning of %V (and the reported usage of %L) are not the result of environment variable substitution, and the expansion must be done by Explorer itself.)
The available context menu plugins are listed as subkeys of the registry key HKEY_CLASSES_ROOT\Directory\shellex\ContextMenuHandlers. (The other keys in ....\shellex are handlers for other kinds of shell extensions.) One of those handlers, or perhaps one of the other extensions, is probably the origin of the strange default value of the ....\command key.
Edit
A neighboring key, HKEY_CLASSES_ROOT\Directory\Background\shell\cmd, also has a value named Extended. It turns out the this one controls the context menu in the folder's content view (right pane, and the desktop itself) while the one named above controls the context menu of folder objects themselves (their icons on the right or on the desktop, or anywhere on the folder tree on the left).

A: pushd is required if you want Windows 7 to switch drive letters to the directory i.e. switch drive also.
The registry key needed looks like the following (I call it DOS) - put it into a .reg file and execute:
Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Folder\shell\DOS]

[HKEY_CLASSES_ROOT\Folder\shell\DOS\command]
@="\"C:\\WINDOWS\\SYSTEM32\\CMD.EXE\" /s /K  pushd \"%v\""


text:
Q: Backup space to Primary space ratio Short version:
I'm building a NAS box to act as storage for backups.  How big does it need to be compared to the amount of data it's backing up to adequately cover deleted files and previous versions of files (assuming that I save incremental changes rather than full backups)?
Long version:
I'm looking to replace our existing storage over the summer.  Currently it's just a trio of RAID 5 volumes located in a 7-year-old server; total space: ~550GB.  Backup is to 40 400GB tapes.  Since server C: drives and system states live on those tapes as well and the existing space is starting to fill up, we've moved to a staggered backup (every weeknight does a full backup for 1/5 of the total, plus a differential on the rest).
To keep it simple I'm planning for a straight migration of our existing three volumes to newer, bigger, faster ones.  We still have a lot Windows XP, so I'm hoping for 6TB of space  to max out each volume to the 2TB supported by XP, so each volume with have 4 1TB disks in RAID 10.  For backups, I want to ditch tape and go all disk.
So here's the plan:  I'm hoping to build 3 units.  The first two are the primary and a hot standby. I'll replicate to the standby nightly.  The final unit will be for backups, and I'll locate it on the far end of campus and use my existing Backup Exec software to pull from the standby unit to the backup unit (pull from the standby to reduce network contention or downtime on the primary).  Since all the new systems will be running Server 2008 R2, there's no 2TB storage limit any more.  My backup unit can use much larger volumes.
This should have multiple versions of files for the "Oops, I deleted that file I needed. By the way, it's been a week" case and also protect against the "Oh no, our server room caught fire" scenario.
So my question (at last) comes down to this:
Is there a good rule of thumb for how much space should I build into the backup unit (and if so, what is it)?   If not, what do I need to know to make an informed decision about how much space I need?
To this point, I've been planning on about 2.5x more space than my primary (or about 15GB), but I'd like something a little more accurate than a number I pulled out of the air.
Part 2: comments on my general strategy here are appreciated.  What am I missing?  How could I do this for less?

A: I've come up with a potential answer to my own question that I can provide for other comment/vote on:
I can plan for a new full backup each month (or other fixed period), with incrementals every night, and use logs from my existing backup as a reference.  I'll take the size of my current full backup and compare it that plus to the cumulative size of all my differentials in the last 30 days.  That should give me a better idea of the ratio I'm looking for, at least relative to how we currently use our data.  It's not perfect (weekly differential will be larger than daily incremental), but it's better than the guess I'm using right now.
Of course, I'd like to hear comments on how well people think this will work, how (in)accurate it will be, and on issues I raised in "Part 2" at the end.


text:
Q: How to set the CSS content property with a Google Material Icon? How can I insert the Google Material Icon "chevron icon right" (https://design.google.com/icons/#ic_chevron_right) in the following CSS content property:
.bullet li a:before {
    content: "";
}

A: Update on 2018
Google removed the codes which were displayed earlier for IE9 and below. To get the codes visit the codepoints file in the GitHub repository.
Link to codepoints in GitHub repository: https://github.com/google/material-design-icons/blob/master/font/MaterialIcons-Regular.codepoints

Step 1: Include the Material Icons Stylesheet.
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
Step 2 :
CSS Code:
.bullet li a:before {
    font-family: "Material Icons";
    content: "\e5cc";
}

Explanation: The value e5cc is the code which you see for the chevron.

A: Try this.
.bullet li a:before {
    font-family: FontAwesome;
    content: "\f054";
}

You can refer here for content values

A: Update for 2022
Using the new Material Symbols Outlined
.selector::before {
    font-family: "Material Symbols Outlined";
    content: "\e5cc";
}

Reference here

A: ::before {
    font-family: 'Material Icons';
    content: "\E87C";
}

::after {
    font-family: 'Material Icons';
    content: "face";
}

http://codepen.io/estelle/pen/MwvOjd

A: You can use this for rtl mode:
.bullet li a:before {content: '\E5CB';}

A: If you already included the minified CSS from materialdesignicons.com then just use the Material Design Icons font family instead:
::after {
    font-family: 'Material Design Icons';
    content: "\f054";
}

There is also a convenient Cheat Sheet available.

A: Update on Jun 2021
The code points of Material Icons are in the Google Fonts webpage, in the section of Material Icons.
Step 1: Include the Material Icons Stylesheet.
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

Step 2: CSS Code.
::after {
    font-family: 'Material Icons';
    content: "/e5cc";
}

Explanation: The value e5cc is the code which you see for the chevron in the next link and image.
https://fonts.google.com/icons?selected=Material+Icons&icon.query=chevron
How to get the content code of chevron icon


text:
Q: What kind of service is runit's svlogd expecting? The runit manual states that in the configuration one  can use an option to submit logs to:

ua.b.c.d[:port]
      tells svlogd to transmit the first len characters of selected log messages to the IP address a.b.c.d, port number port. If port isn't
  set, the default port for syslog is used (514). len can be set through
  the -l option, see below. If svlogd has trouble sending udp packets,
  it writes error messages to the log directory. Attention: logging
  through udp is unreliable, and should be used in private networks
  only.

I know that rsyslogd is running list on this port.
So this could be one possible option...
But are there any other?

A: The question is slightly vague, but from the sound of it, I think you are asking if you can use svlogd to send syslog messages to another program besides rsyslogd.  The answer is, any program that provided a syslog service would suffice.  There is more than just rsyslogd that provides a syslog network service.
However, the way runit was intended to "natively" handle logging is probably backwards from what you are thinking.
The idea is that you have a service of some kind, and that service writes output through stdout or stderr.  The runsv program will bring up svlogd and erect a pipe between your service and svlogd; all your service has to do is send data to stdout/stderr, svlogd will write directly to disk, and life is good.  Because the pipe is maintained by runsv, should there be issues with the service going down, output is still captured and delivered to svlogd - so in theory, you don't loose logging data due to a service crash.
There is another program by the same author, socklog, that acts as a syslog front-end that funnels to a svlogd.  Because there are a lot of programs that just assume that /dev/log is available, socklog provides this interface so that syslog data can be captured - it acts as a substitute syslog service.  This is the opposite of what you are suggesting.
I'm not saying you shouldn't use syslog, I'm just saying that there's more than one way to do this.  If you really want to shunt your output from svlogd back to syslog, then yes, any old syslog service will do just fine, but it may be worth considering going "all native" and ditching rsyslogd altogether, if your installation permits this.


text:
Q: How to give seconds of delay before after Button press I want a 3 second delay after a condition is satisfied which should not stop any other process.
When I press a button for 3 seconds I want a return value true
(timer should only start after button is pressed) else it must be false. Any suggestions how to do it? Here's what I have tried but is not working
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(3, GPIO.IN, pull_up_down=GPIO.PUD_UP)

def button():
    if GPIO.input(3) == GPIO.LOW:
      start_time =time.time()
      if (time.time() - start_time) >= 5:
        return True
      else:
        return False
    else:
      return False

A: Here is the solution
def button():
    global start_time, end_time
    if GPIO.input(3) == GPIO.HIGH:
        start_time = time.time()
        return False
    if GPIO.input(3) == GPIO.LOW:
        end_time = time.time()
        if (end_time - start_time) >= 3:
            return True
        else:
            return False


text:
Q: Vue - Unexpected token '<' I have a really simple code. I'm trying to learn Vue by following this tutorial on youtube
https://www.youtube.com/watch?v=4deVCNJq3qc
I am stuck at 31:30 with this code:
Vue.component('car-list', {
 template:

{{ car }}

 })

for some reason it breaks the whole code and when i inspect the page on google chrome i get the error
Uncaught SyntaxError: Unexpected token '<'

screenshot of the error: https://ibb.co/CnzRFtZ
I am using Atom as my editor.
my whole code

      {{ carzName }}

      <input v-model="newCar" @keyup.enter="addCar">
      <button @click="addCar">+ Add</button>

        {{ car }}

      <car-list :cars="cars" />

Thanks to anyone who is willing to explain me where the problem is at.

A: Template needs to be string. Add backtick quotes around it.
Vue.component('car-list', {
  template: `

{{ car }}

`
})

Edit: To iterate more on @Lawrence Cherone comment there is no need to register the component globally with Vue.component if you are gonna register it within your vue app.
Version 1: Register globally
Vue.component('car-list', {
  template: `

{{ car }}

`
 })

and then remove component property from vue app
const app = new Vue({
  el: '#root',
  data: {}
})

Verison 2: Register within app
const carList = {
  template: `

{{ car }}

`
}

And then
const app = new Vue({
   el: '#root',
   component: {
      carList
   },
   data: {}
})


text:
Q: A question about using mock or new in Junit & Mockito Background Info
I have a thread. It's a dedicated thread to continuously take out a task from a queue and write to a persistent repository. So it's code is like this.
public class Processor extends Thread {
    //Context saves reference to the task queue and the write backEnd service
    public GeneralProcessor(Context context){initProcessor( context,  Type.GENERAL);}
    public void run() {
        ...
        synchronized (Processor.class) {
            Thread curThread=currentThread();
            Context context=getContext();
            ConcurrentLinkedQueue<Task> taskQue =context.getTasks();
            if (taskQue.size() > 0) {
                Task t = taskQue.poll();
                Transaction ts = new Transaction();
                //all works to copy Task's member values to Transaction, and add other values to this transaction
                //...
                context.getService().save(ts);//this is the line I want to monitor. This is also related to issue in some way.

            }
        }
    }
}

The Issue
But there is an issue when I wrote a unit test for this class. My original unit test is this.
@ExtendWith(MockitoExtension.class)
public class GeneralProcessorTest {
    @InjectMocks
    private GeneralProcessor generalProcessor;
    @Mock
    private Context context;
    @Spy
    private ConcurrentLinkedQueue<Task> tasks;
    @Mock
    private TransactionRepository transactionRepository;
    @Captor
    private ArgumentCaptor<Transaction> transactionArgumentCaptor;
    @Mock
    private TransactionService transactionService;

   @BeforeEach
    void setup() {
        //transactionService=new TransactionServiceImpl(transactionRepository);
    }

    @Test
    @SneakyThrows
    void should_match_save_times_single_thread() {
        //given
        CountDownLatch latch=new CountDownLatch(0);
        this.tasks.add(new Task(10));
        //stub code
        when(context.getTasks()).thenReturn(tasks);
        when(context.getService()).thenReturn(transactionService);
        //when
        generalProcessor.start();
        latch.await(1, TimeUnit.SECONDS);
        //then
        //the issue happened here!
        verify(transactionService).save(transactionArgumentCaptor.capture());
        List<Transaction> capturedArguments = transactionArgumentCaptor.getAllValues();
        assertEquals(capturedArguments.size(),1);
    }

But I got:
Wanted but not invoked:
transactionService.save(
    <Capturing argument>
);
at com.example.demo.GeneralProcessorTest.should_match_save_times_single_thread(GeneralProcessorTest.java:65)
Actually, there were zero interactions with this mock.

In fact, I tried to init transactionService with new. But Mockito told me that in verify I can only use Mock object.
So I am confused. Is there any way to let me use verify while at the same time keep transactionService working as a normal object? Any info is appreciated.


text:
Q: Programming series of lights that turn on/off I have 5 on/off lights that I would like to be managed dynamically in angular. As seen below:

These are placed in parallel to a (working) slider and I want them to share the same scope.
The basic logic is that when the slider is at 3, lights 1,2 & 3 should be ON and lights 4 & off should be OFF. There are two CSS classes to show this green-on and green-off.
Hardcoded HTML:
4

3

2

1

OFF

I know in angular to create a directive like so:

Directive
angularApp.directive('lights', function () {
    return {
        restrict: 'A',
        scope: {
            ngModel: '='
        },
        link: function (scope, element, attrs) {
            return scope.$watch('ngModel', function (newVal) {
                if (newVal !== null) {
                    //update
                }
            });
        }
    }
});

This will listen to the value of lightValue which will range from 0-4.
But I'm stuck as to where to put the logic as aforementioned that will change the class depending on the value.
Do I create a template or return the HTML in the link and use $compile?
Finally, is there a more efficient way than using ifs to assign the class (psuedo code below)?
if (lightValue == 4) {
    light1 = on;
    light2 = on;
    light3 = on;
    light4 = on;
} else if (lightValue == 3) {
    light1 = on;
    light2 = on;
    light3 = on;
} else if (lightValue == 2) {
    light1 = on;
    light2 = on;
} //etc..

Update:
Thanks, I was able to use ngClass with some conditional statements to the desired effect:
<span class="light" ng-class="{'green-on' : notches == 4, 'green-off' : notches < 4 }">4

= 3, 'green-off' : notches < 3 }">3

= 2, 'green-off' : notches < 2 }">2

= 1, 'green-off' : notches < 1 }">1

 0 }">OFF

I guess I could try write this into the directive to make it reusable.

A:
ng-class

changes the class according to scope values
from ng-class official doc:

Map Syntax   Example

<input type="checkbox" ng-model="deleted"> deleted (apply "strike" class)

<input type="checkbox" ng-model="important"> important (apply "bold" class)

<input type="checkbox" ng-model="error"> error (apply "red" class)

Finally, is there a more efficient way than using ifs to assign the class (psuedo code below)?

yes, just use ng-class and simple logic in your html templates

A: i will assume your slider currently triggers a zero based integer value depending on the position where it is, changing lightValue. then your lights class should activate based on it.
<span ng-class="{'green-off' : lightValue <= 4 }" class="light">4

<span ng-class="{'green-off' : lightValue <= 3 }" class="light">3

<span ng-class="{'green-off' : lightValue <= 2 }" class="light">2

<span ng-class="{'green-off' : lightValue <= 1 }" class="light">1

<span ng-class="{'green-off' : lightValue <= 0 }" class="light">off

you could of course make this loop dynamic to generate the spans etc.

A: All you would need is an ng-class on each element like this...
4

So if 'lightValue' is a variable in your controller, if that variable = 4, then the 'your-class-to-add' class will be added to that element.


text:
Q: Generating CSV reports that have 1 million+ rows in ASP.NET I am seeking your advice with regards to generating CSV reports.
I have an ASP.NET application that is produces reports on billing data. Recently, I have noticed that when it tries to export a report file the web application is unresponsive and will throw in an OutOfMemory exception or Server timeout exception.
What I did to amend this was to:

*

*Place the necessary indexes in SQL server to get the records faster

*Use SqlDataReader to fetch the data from SQL server

*Specify the criteria needed to pull out necessary records instead of getting all information in one call.

I have also thought of limiting the maximum number of records returned from the database but the system needs to produce all information regardless of how big the rowcount is returned because the information being downloaded will be critical for our client's financial records.
I am wondering, what methods/solutions that can be used to render CSV reports that have huge data in ASP.NET?
Looking forward for your response.
Cheers,
Ann

A: To solve the server timeout exception I would try to produce the reports asynchronously.  So when your application receives a request to generate a report it should launch another thread that does the generation and return the request immediately.
You'll then need another page that lets visitors pick up reports after they've been generated.
This all involves a bit more work within the application of course, to record what reports are being generated,  and mark them as generated when complete.
As for the out of memory exception - that is specific to the way you are generating the reports.  It's very rare to get out of memory exceptions unless you really are doing something quite crazy - so are you somehow consuming lots of memory in your CSV generation - creating lots and lots of string objects for example?  Make sure you're using StringBuilder,  or better still perhaps stream the output directly into a file.
Final tip - if you are serving huge files like this make sure you have GZIP or DEFLATE compression enabled for these file types on your IIS configuration.  That will significantly reduce the size of the package to be delivered to the client - but at the cost of some processing time.

A:
I am wondering, what methods/solutions that can be used to render CSV reports that have huge data in ASP.NET?

The best way is to not do it in ASP.NET. You need a separate process, at the very least a thread inside your ASP app but it would be better to offload to another server/service.

A: Pre render them and download them as URI\files. I have found that rendering big files like this needs to be out of the regular Click&Wait for the page to render and come back. Or if they must be onclick, A Ajax like start and a occasional query to determine percentage done is much better and when 100% then you release the URI.


text:
Q: How do I make an Android widget stick to the right of the layout? I am designing an android layout for a comment system. I need to make the ImageView (expandImage) stick to the right of the layout permanently no matter how short or long the text in commentTextView. If the text is short, expandImage moves to the left, and if the text is long it pushes expandImage off the screen. I don't want that.
I have used gravity but it makes no difference. I also tried Relative Layout but it messed up the layout.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="5dp"
    android:paddingBottom="5dp">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="@android:color/white"
        app:cardCornerRadius="2dp"
        app:cardElevation="4dp"
        app:cardUseCompatPadding="true">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:layout_marginLeft="10dp"
            android:orientation="horizontal">

            <com.mikhaellopez.circularimageview.CircularImageView
                android:layout_width="48dp"
                android:layout_height="48dp"
                android:src="@drawable/photo_female_5"/>

            <View
                android:layout_width="5dp"
                android:layout_height="5dp"/>

                <LinearLayout
                    android:id="@+id/linearLayout"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="username"
                        android:textColor="@android:color/black"
                        android:textSize="18sp"
                        android:textStyle="bold" />

                    <TextView
                        android:id="@+id/commentTextView"
                        android:layout_width="wrap_content"
                        android:layout_height="match_parent"
                        android:layout_marginRight="50dp"
                        android:singleLine="false"
                        android:text="This is a comment. It spills" />

                </LinearLayout>

                <View
                    android:layout_width="5dp"
                    android:layout_height="5dp" />

            <ImageView
                android:id="@+id/expandImage"
                android:layout_width="32dp"
                android:layout_height="32dp"
                android:layout_gravity="center_vertical"
                android:layout_marginRight="5dp"
                android:src="@drawable/ic_expand_arrow" />

        </LinearLayout>

    </androidx.cardview.widget.CardView>

</LinearLayout>

This is the way it currently looks in the image:
enter image description here
Please, how do I make expandImage stick to the right of the layout without moving at all. Thank you in advance.

A: Long story short:
You can put RelativeLayout inside your CardView and in it add those attributes:
android:layout_alignParentRight="true"
android:layout_centerVertical="true"

So you will get the expandImage in the needed position without rebuilding linear layout
Full code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingTop="5dp"
    android:paddingBottom="5dp">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="@android:color/white"
        app:cardCornerRadius="2dp"
        app:cardElevation="4dp"
        app:cardUseCompatPadding="true">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:orientation="horizontal">

                <com.mikhaellopez.circularimageview.CircularImageView
                    android:layout_width="48dp"
                    android:layout_height="48dp"
                    android:src="@drawable/photo_female_5" />

                <View
                    android:layout_width="5dp"
                    android:layout_height="5dp" />

                <LinearLayout
                    android:id="@+id/linearLayout"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="username"
                        android:textColor="@android:color/black"
                        android:textSize="18sp"
                        android:textStyle="bold" />

                    <TextView
                        android:id="@+id/commentTextView"
                        android:layout_width="wrap_content"
                        android:layout_height="match_parent"
                        android:layout_marginRight="50dp"
                        android:singleLine="false"
                        android:text="This is a comment. It spills" />

                </LinearLayout>

                <View
                    android:layout_width="5dp"
                    android:layout_height="5dp" />

            </LinearLayout>

            <ImageView
                android:id="@+id/expandImage"
                android:layout_width="32dp"
                android:layout_height="32dp"
                android:layout_alignParentEnd="true"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:layout_gravity="center_vertical"
                android:layout_marginEnd="5dp"
                android:layout_marginRight="5dp"
                android:src="@drawable/ic_expand_arrow" />

        </RelativeLayout>

    </androidx.cardview.widget.CardView>

</LinearLayout>

A: <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingTop="5dp"
android:paddingBottom="5dp">

<androidx.cardview.widget.CardView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/white"
    app:cardCornerRadius="2dp"
    app:cardElevation="4dp"
    app:cardUseCompatPadding="true">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:orientation="horizontal">

        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/image"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:layout_alignParentStart="true"
            android:layout_centerVertical="true"
            android:src="@drawable/photo_female_5" />

        <LinearLayout
            android:id="@+id/linearLayout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toEndOf="@id/image"
            android:orientation="vertical">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="username"
                android:textColor="@android:color/black"
                android:textSize="18sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/commentTextView"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_marginRight="50dp"
                android:singleLine="false"
                android:text="This is a comment. It spills" />

        </LinearLayout>

        <View
            android:layout_width="5dp"
            android:layout_height="5dp" />

        <ImageView
            android:id="@+id/expandImage"
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:layout_alignParentEnd="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="5dp"
            android:src="@drawable/ic_expand_arrow" />

    </RelativeLayout>

</androidx.cardview.widget.CardView>

</LinearLayout>


text:
Q: Extracting data from HTML file using c# script What I need to do : Extract (Information of From, To, Cc and Subject ) and remove them from HTML file. Without the use of any 3rd party ( HTMLAgilityPack, etc)
What I am having trouble with: What will be my approach to get the following(from,to,subject,cc) from the html tags?
Steps I tried: I tried to get the index of
 and the last index of the email @sampleemail.com but I think that is a bad approach since in some html files there will be a lot of
"
" , regarding the removal of the from,to,cc and subject I just used the string.Remove(indexOf, i counted the characters from indexOf to lastIndexOf) function and it worked
Sample tag containing information of from:

From:1234@sampleemail.com<o:p></o:p>

HTML FILE output:

A: HTMLAgilityPack is your friend. Simply using XPath like //p[@class ='MsoNormal'] to get tags content in HTML
public static void Main()
{
    var html =
    @"
From:1234@sampleemail.com<o:p></o:p>
                                     ";

    var htmlDoc = new HtmlDocument();
    htmlDoc.LoadHtml(html);

    var nodes = htmlDoc.DocumentNode.SelectNodes("//p[@class ='MsoNormal']");

    foreach(var node in nodes)
        Console.WriteLine(node.InnerText);
}

Result:
From:1234@sampleemail.com

Update
We may use Regex to write this simple parser. But remember that it cannot clear all cases for complicated html document.
    public static void MainFunc()
    {
        string str = @"
From:1234@sampleemail.com<o:p></o:p>
                                     ";
        var result = Regex.Replace(str, "<(?:\"[^\"]*\"['\"]*|'[^']*'['\"]*|[^'\">])+>", "");
        Console.WriteLine(result);
    }


text:
Q: Spawning a Python Tkinter process through Rust's spawn does not give the stdout continuously I'm starting an individual process from Rust like this:
let stdout = std::process::Command::new("python3")
    .arg(tool_path)
    .args(python_params)
    .stdout(std::process::Stdio::piped())
    .spawn()
    .unwrap()
    .stdout
    .ok_or_else(|| "Could not capture standard output.")
    .unwrap();

I'm starting a Python process of my script and print it out like so:
let reader = std::io::BufReader::new(stdout);

reader
    .lines()
    .filter_map(|line| line.ok())
    .for_each(|line| println!("{}", line));

This will continuously print out all my prints inside my Python script. If my Python script looks like this:
print("foo.pyyyyyyy")
while True:
    print("asdasd")

I will see first "foo.pyyyyyyy" printed, and then a continuous stream of "asdasd" prints in my terminal.
However, if my Python script consists of a Tkinter update loop like this:
from tkinter import *
window = Tk()
window.title("Welcome to LikeGeeks app")
window.mainloop()
print("foo.pyyyyyyy")

It does not print the "foo.pyyyyyyy" statement until after I terminate the external process.
Is there a way to circumvent this? I would really like to be able to pipe my Tkinter prints to my Rust app.

A: Thanks to @jmb and @acw1668 for the answer:
My issue had something to do with the I/O buffer when starting my python script. Adding the -u flag when calling my script solved the issues:
python3 -u path_to_script parameters
from the docs:
-u
Force the binary layer of the stdout and stderr streams
(which is available as their buffer attribute) to be unbuffered.
The text I/O layer will still be line-buffered if writing to the console,
or block-buffered if redirected to a non-interactive file.

See also PYTHONUNBUFFERED.


text:
Q: EnumDropDownListFor Conditionally hide items I want to conditionally hide the elements in the EnumDropDownListFor based on if the user is logged in or not.
Enum
public enum SortType
{
    [Display(ResourceType = typeof(NavigationItems), Name = "BestMatch")]
    Best_Match = 0,
    [Display(ResourceType = typeof(NavigationItems), Name = "Alphabetical")]
    Alphabetical,
    [Display(ResourceType = typeof(NavigationItems), Name = "PriceAsc")]
    PriceAsc,
    [Display(ResourceType = typeof(NavigationItems), Name = "PriceDesc")]
    PriceDesc
}

The items I am looking to hide are PriceAsc & PriceDesc
I have tried looking into the AutoGenerateFilter and AutoGenerateField properties to no avail.
View
@Html.EnumDropDownListFor(x => x.sortType, new { id = "orderResults" })

A: var sortTypesToExclude = new[] { SortType.PriceAsc, SortType.PriceDesc }.Cast<int>();
var sortTypes = Enum.GetValues(typeof(SortType)).Cast<int>().Where(i => userLoggedIn || !sortTypesToExclude.Contains(i));
var sortTypesAsSelectList = sortTypes.Select(i => new SelectListItem() { Value = i.ToString(), Text = ((SortType)i).ToString() });


text:
Q: Making text bold in an email in PL/SQL I am trying to format text in the variable var_sub_title bold before sending it in email bold.
  declare
  var_sub_title varchar2(60);
  var_txt varchar2(500);
  var_msg_sub varchar2(60);

  begin
  select sub_title, txt, subject into var_sub_title, var_txt, var_msg_sub from table where msg_id = :id;
     -- SEND EMAIL --
  HTMLDB_MAIL.SEND(
       P_to   => 'email@mail.com',
       p_from =>'email@email.net',
       p_body => var_sub_title||CHR(10)||CHR(13)||var_txt||CHR(10)||CHR(13);
       p_subj => var_msg_sub);
   htmldb_mail.push_queue;
  end;

how can i archiev this?

A: As documentation says, you need to pass your HTML-formatted text to parameter p_body_html, not p_body:

Plain text and HTML e-mail content. Passing a value to p_body, but not p_body_html results in a plain text message. Passing a value to p_body and p_body_html yields a multi-part message that includes both plain text and HTML content.

So your code should be:
declare
  var_sub_title varchar2(60);
  var_txt varchar2(500);
  var_msg_sub varchar2(60);

  begin
  select sub_title, txt, subject into var_sub_title, var_txt, var_msg_sub from table where msg_id = :id;
     -- SEND EMAIL --
  HTMLDB_MAIL.SEND(
       P_to        => 'email@mail.com',
       p_from      => 'email@email.net',
       p_body_html => '<b>'|| var_sub_title || '</b>' || CHR(10) || CHR(13) || var_txt || CHR(10) || CHR(13);
       p_subj      => var_msg_sub);
   htmldb_mail.push_queue;
  end;

Also there are other restrictions on length and ability to process HTML emails by recipient's email client.

When using HTMLDB_MAIL.SEND, remember the following:

*

*No single line may exceed 1000 characters. The SMTP/MIME specification dictates that no single line shall exceed 1000 characters. To comply with this restriction, you must add a carriage return or line feed characters to break up your p_body or p_body_html parameters into chunks of 1000 characters or less. Failing to do so will result in erroneous e-mail messages, including partial messages or messages with extraneous exclamation points.

*Plain text and HTML e-mail content. Passing a value to p_body, but not p_body_html results in a plain text message. Passing a value to p_body and p_body_html yields a multi-part message that includes both plain text and HTML content. The settings and capabilities of the recipient's email client determine what displays. Although most modern e-mail clients can read a HTML formatted email, remember that some users disable this functionality to address security issues.

*Avoid images. When referencing images in p_body_html using the  tag, remember that the images must be accessible to the recipient's e-mail client in order for them to see the image


text:
Q: I want to do translate, rotate and scale while merging the two textures First of all, please understand that sentences may not be smooth using a translator.
I'm going to combine the two textures and create them into one texture.
Example) 1. image__  2. image__  3. result__
A simple combination of two textures is not a problem.
The problem is that translate, rotate and scale should be applied to one texture and merged, but I can't think of a way. I'd appreciate it if you could help me.
here my code :
Texture2D CombineTexutes(Texture2D _textureA, Texture2D _textureB, int startX = 0, int startY = 0)
{
    //Create new textures
    Texture2D textureResult = new Texture2D(_textureA.width, _textureA.height);
    //create clone form texture
    textureResult.SetPixels(_textureA.GetPixels());
    //Now copy texture B in texutre A
    for (int x = startX; x < _textureB.width + startX; x++)
    {
        for (int y = startY; y < _textureB.height + startY; y++)
        {
            Color c = _textureB.GetPixel(x - startX, y - startY);
            if (c.a > 0.0f) //Is not transparent
            {
                //Copy pixel colot in TexturaA
                textureResult.SetPixel(x, y, c);
            }
        }
    }

    //Apply colors
    textureResult.Apply();
    return textureResult;
}

A: This is relatively tricky with pixel transformations. You would have to read up on various algorithms for every of those tasks.
A much easier solution would be to use game objects with sprite renderers and then render everything onto a "render texture" (if you really need a texture).
Game objects with a sprite renderer can be easily rotated, scaled etc.
Your result image does look as if it was actually deforming the sprite though, not just scaled in a direction.
If that's your goal, then I'd recommend looking at the Animation 2D package. That allows you to do near anything with sprites.


text:
Q: Access OwnerTableView ParentItem It is my Vb.net code it works perfectly.
Protected Sub ChkTaxCheckedChanged1(ByVal sender As Object, ByVal e As EventArgs)

        Dim chkTax As CheckBox
        Dim gv1 As GridDataItem
        chkTax = TryCast(sender, CheckBox)
        gv1 = DirectCast(chkTax.NamingContainer, GridDataItem)

        Dim txtAmount1 As Label = CType(gv1.OwnerTableView.ParentItem.FindControl("lblItemAmount"), Label)
End Sub

But now I want to achieve the same functionality in clientside using JavaScript.
Like :
function ChkTaxCheckedChanged1(sender, args) {
    var check = sender.get_parent()..??????
}

Any one know how can I do this?

A: Try this.
<script>
            function handleClick(sender,args) {
                //i have used jquery so do not forgot add jquery reference
                var checkboxid = sender.get_id();
                var parentRow = checkboxid.parent().parent().parent().parent().parent().parent()[0].previousSibling;
                $(parentRow).find('span').html('Your text comes here');
            }
        </script>


text:
Q: Last Step to Set Up a Nginx Server with Rails I've been trying to set up an nginx server on my VPS to deploy my rails app.
Everything has been successful until the last command, and if I get this to work, I will be able to see my app on the server.
I did
sudo service nginx restart

and finally,
sudo update-rc.d uinicorn_app defaults

but it says
update-rc.d: /etc/init.d/unicorn_app: file does not exist

I manually checked the file by going into the directory, and the file was there. However, when I ran the command below, I got the following.
deployer@max:/$ file /etc/init.d/unicorn_app
/etc/init.d/unicorn_app: broken symbolic link to `/home/deployer/apps/app/current/config/unicorn_init.sh'

How do I fix this issue and finish setting up my server?
Update: it seems like my deploy.rb config is not working properly because I cannot find /home/deployer/apps/app/current folder. Here's part of my deploy.rb:
namespace :deploy do
  %w[start stop restart].each do |command|
    desc "#{command} unicorn server"
    task command, :roles => :app, :except => {:no_release => true} do
      run "/etc/init.d/unicorn_#{application} #{command}"
    end
  end

  task :setup_config, :roles => :app do
    sudo "ln -nfs #{current_path}/config/nginx.conf /etc/nginx/sites-enabled/#{application}"
    sudo "ln -nfs #{current_path}/config/unicorn_init.sh /etc/init.d/unicorn_#{application}"
    run "mkdir -p #{shared_path}/config"
    put File.read("config/database.example.yml"), "#{shared_path}/config/database.yml"
    puts "Now edit the config files in #{shared_path}."
  end

Any ideas?

A: If you can't locate your current file, run
cap deploy:cold

which will deploy your application, run all pending migrations, and start the server for the first time.


text:
Q: Add category to body class I want to add the currenty category to the body class.
How do I need to modify my current code, to add also the current category as a body class to the is_singular( 'knowledgebase' ) section?
My current code looks like this:
function add_body_class( $classes ) {

    global $pakb;

    if( is_page( $pakb->get( 'kb_page' ) ) && ! is_null(  $pakb->get( 'kb_page' ) ) ) {
        $classes[] = 'pakb-main';
    } elseif ( is_tax( 'knowledgebase_category' ) ) {
        $classes[] = 'pakb-category';
    } elseif ( is_singular( 'knowledgebase' ) ) {
        $classes[] = 'pakb-single';
    }

    return $classes;

}

A: This late in the process you should be able to rely on context set up, even outside of loop.
On top of my head something like this should work:
$categories = wp_get_post_categories( get_the_ID(), [ 'fields' => 'names' ] );

A: Here I don't understand what is global $pakb.
But extending to Rarst answer :
add_filter('body_class', 'add_body_class');

function add_body_class($classes) {
    global $pakb;
    global $post;

    if( is_page( $pakb->get( 'kb_page' ) ) && ! is_null(  $pakb->get( 'kb_page' ) ) ) {
        $classes[] = 'pakb-main';
    } elseif ( is_singular( 'knowledgebase' ) ) {
        // getting all category name related to this post
        $categories = wp_get_post_categories( $post->ID, [ 'fields' => 'names' ] );

        $classes[] = $categories;
    }

    return $classes;

return $classes;
}


text:
Q: (Interface, Class) Kotlin: Expecting member declaration Class Aim: read review point and comment, ensure that point is within 0-5
class LimitedReview(val point:Int, val comment:String):Review {
if (point<0){
    point=0
}
if (point>5){
    point = 5
}
override fun stars(): Int =point
override fun info(): String =comment
}

interface Review{
fun stars():Int
fun info():String
}

Error:(2, 5) Kotlin: Expecting member declaration
  Error:(2, 17) Kotlin: Conflicting overloads: public final fun (): Unit defined in LimitedReview, public final fun (): Unit defined in LimitedReview
  Error:(2, 17) Kotlin: Function declaration must have a name

*

*may i know how to change my code?

*which topic should i learn to avoid the same error again?

Thanks!

A: The property you have in the primary constructor of the class will assign the value that you call the constructor with to the point property directly, when your class is created, and you can't modify it any more.
Basically, this code:
class LimitedReview(val point: Int)

Is the same as this:
class LimitedReview(point: Int) {
    val point: Int = point // ctor param to property
}

If you want to perform logic before assigning the value to the property, you have to move the property outside the constructor, and initialize it manually.
This can be done in an initializer block, if you have complex logic for it:
class LimitedReview(point: Int) {
    val point: Int

    init {
        if (point < 0) {
            this.point = 0
        } else if (point > 5) {
            this.point = 5
        } else {
            this.point = point
        }
    }
}

Or if you can fit it into a single expression (coerceIn comes in handy here), then inline with the property declaration:
class LimitedReview(point: Int) {
    val point: Int = point.coerceIn(0..5)
}


text:
Q: performance issue due to huge number of dom elemets I have a webpage where I repeats div with same class thousand times in a loop due to which  browser engine just seemed to choke.
Is there any way of improving a page with a lot of dom elements? or infinite scroll on dom elemnts?

 content 1

 content 2

 content 3

 content 4
 //so on like 10000 same divs in loop

A: if I were you I would first place a set of divs that fills the screen. When you scroll to the bottom of the page you could get another couple of elements. then repeat the process. If you reach the amount of divs you want you could start append elements from the start.

A: You can load first 20 or so, and others can be loaded asynchronously with AJAX methods, triggered by scroll or visibility of one of the bottom. Unloading top DOMs is not recommended anyway. General suggestion for best performance practice is to avoid using large numbers of DOM elements with ID tags.
See more about that here


text:
Q: How to check if a folder exists at a regular interval in java My goal is to check if a Hadoop path exists and if yes, then it should download some file. Now in every five minutes, I want to check if the file exists in the Hadoop path.
currently,  my code is checking if the file exists but not on an interval basis.
public boolean checkPathExistance(final org.apache.hadoop.fs.Path hdfsAbsolutePath)
{
    final Configuration configuration = getHdfsConfiguration();
    try
    {
        final FileSystem fileSystems = hdfsAbsolutePath.getFileSystem(configuration);
        if (fileSystems.exists(hdfsAbsolutePath))
        {
            return true;
        }
    }
    catch (final IOException e)
    {
        e.printStackTrace();
    }
    return false;
}

The criteria are this checkPathExistance method should be called in every five minutes to check if the file exists. And when it will return true, the file should be downloaded.
 public void download(final String hdfs, final Path outputPath)
{
    final org.apache.hadoop.fs.Path hdfsAbsolutePath = getHdfsFile(hdfsLocalPath).getPath();
    logger.info("path check {}", hdfsAbsolutePath.getName());
    final boolean isPathExist =  checkPathExistance(hdfsAbsolutePath);
    downloadFromHDFS(hdfsAbsolutePath, outputPath);
}

Can I please get some help here ?

A: For the file copying (and not folder copying, if I understood correctly within your question's context) you can just use the copyToLocalFile method from FileSystem as seen here by specifying the boolean that checks if you want to delete the source file, and the input (HDFS)/output (local) paths.
As for the periodic checking of the existence of the file in HDFS, you can use a ScheduledExecutorService object (Java 8 docs here) by specifying that you want your functions' execution to run every 5 minutes.
The following program takes two arguments, the path of the input file in the HDFS and the path of the output file locally.
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class RegularFileCheck
{
    public static boolean checkPathExistence(Path inputPath, Configuration conf) throws IOException
    {
        boolean flag = false;

        FileSystem fs = FileSystem.get(conf);

        if(fs.exists(inputPath))
            flag = true;

        return flag;
    }

    public static void download(Path inputPath, Path outputPath, Configuration conf) throws IOException
    {
        FileSystem fs = FileSystem.get(conf);
        fs.copyToLocalFile(false, inputPath, outputPath);   // don't delete the source input file
        System.out.println("File copied!");
    }

    public static void main(String[] args)
    {
        Path inputPath = new Path(args[0]);
        Path outputPath = new Path(args[1]);

        Configuration conf = new Configuration();

        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

        Runnable task = () ->
        {
            System.out.println("New Timer!");

            try
            {
                if(checkPathExistence(inputPath, conf))
                    download(inputPath, outputPath, conf);
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        };

        executor.scheduleWithFixedDelay(task, 0, 5, TimeUnit.MINUTES);
    }
}

The console output of course is continuous and looks like the one on the screenshot below (test.txt is the file stored in HDFS, test1.txt is the file to be copied locally). You can additionally modify the code above if you want to stop the re-executions after the file has been found and copied already, or if you want to stop checking for the file after a while.

To stop the search and copying, simply replace to the code above with the following snippet:
Runnable task = () ->
{
    System.out.println("New Timer!");

    try
    {
        if(new File(String.valueOf(outputPath)).exists())
            System.exit(0);
        else if(checkPathExistence(inputPath, conf))
            download(inputPath, outputPath, conf);
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
};

And the program will stop after the file has been copied, as seen from the console output:


text:
Q: Infer the type of a generic on an interface This may be a duplicate, as I imagine it's a relatively common problem, but I wasn't able to find anything unfortunately.
If I want to define a function that takes a generic, typescript is often able to infer the type of the generic:
const f = <T>(x: Record<string, T>) => x;

const x = f({ a: { x: 1 }, b: { x: 1 } });

Typescript has no problem here, and I don't need to provide the type of the generic.
If, however, I try and do the same thing in an interface, I can't; I need to explicitly provide the type:
type X<T> = Record<string, T>;

const x: X = { a: { x: 1 }, b: { x: 1 } };

In some ways I can see why this is; we can define the type of a variable before we actually give it a value, so the generic isn't always inferable. But neither can I do this:
const x = { a: { x: 1 }, b: { x: 1 } } as X;

It seems as though it's part of the language's syntax that for types and interfaces, you have to explicitly provide the type of generics; but am I missing something? Can anyone provide any help at all?

A: It seems like this is being worked upon, see issue-26242 , in particular issue-26242-comment (and also issue-30120 , which looks very similar to your example here ) :

Maybe adopt the ? from the partial application proposal
foo<?, ?, string>(); // returns [{}, {}, string]
which already stands for optional in TypeScript. Actually, the meaning of would be pretty similar to the proposal and could allow for something like this:
type Foo<T, U, V> = T | U | V;
type Bar = Foo<?, string, ?>; // equal to type Bar<A, B> = A | string | B;

(I found this by searching for 2314 , the error code that is currently given by the playground reg. your code snippet, I have previously had success with searching on the error codes).


text:
Q: How to access android root directory I am developing an application using ionic framework.
The app creates files (*.json) and stores them in  /data/user/0/ when i verify whether they exist or not, the result was true which means the files exist in the mentioned directory and I can access and modify their content without problem, but when I check the directory with a file manager or from the computer, no result, the directory is empty.
Could someone tell me what should I do?

A: use adb to copy the file. Even if it's in root dir, u should have access to it via adb.
Do adb pull data/user/0/filename.json path_on_ur_comp.json.
this will copy the file to the directory you define in the 2nd parameter.
// EDIT:
adb is part of the Android SDK, stands for Android Debug Bridge.
You can use this for MANY MANY different reason but of course, the "main" reason is to debug Android devices. You can use it to transfer files in your case.
In Windows, it's located here:

C:\Users\USERNAME\AppData\Local\Android\sdk\platform-tools\adb

In Mac, it's lcoated here:

/Users/USERNAME/Library/Android/sdk/platform-tools/adb

Depending on which OS you use, open that either with Terminal (Mac) or Command Prompt (Windows).
Once you do that, run the following command:
For Mac:
adb pull data/user/0/filename.json /Users/USERNAME/Desktop/somefile.json

For Windows:
adb pull data/user/0/filename.json c:\Users\USERNAME\Desktop\somefile.json

This will copy the file and put it on your desktop


text:
Q: How to solve Raspberry Pi 3B & Bme280 Remote I/O error Let me start off with the components used:

*

*GPIO extension board to connect the raspberry pi to components

*Bme280

*Pi 3B

Problem description:
This problem was intermittent at first. We were receiving reading and the error occured out of nowhere, made adjustment to the sensor(taking out and putting it back in) which solved it but when we touch the sensor the error showed up again.
We decided to change the sensor and the problem turned from intermittent to persistent. Now we have this as permanent issue.
We removed the package for BME280 and SmBus2 and decided to reinstall it again.
RPI Bme280: https://pypi.org/project/RPi.bme280/
I followed this BME280 installation guide, however when prompting for 'i2cdetect -y 1' there were lines but no number showing up.
What has been confirmed so far:

*

*Patching up of circuits was fine, tested with my lecturer pi and it
works fine.

*Codes is fine, we even use the sample code provided by RPi.bme280

*I2c was enabled everytime
Please help me because I am really lost. I needa submit this by next week so any help is appreciated.
Problem pic --> Picture of the problem

A: I've tried to respond, but there is a few pitfalls in SMBus and i2c, so to break the question into smaller bits I've quoted your original message with an indent. The response is provided beneath.

This problem was intermittent at first. We were receiving reading and the error occurred out of nowhere, made adjustment to the sensor(taking out and putting it back in) which solved it but when we touch the sensor the error showed up again.

I locked onto the statement, "Touched the sensor". Is there a chance the BME280 experienced an ESD discharge? And therefore is now partially or fully broken?
Are you using an ESD safe room? or at least ESD bracelet. You will not notice small ESD discharges, and for small electronics even a sub 1000V discharge can cause damage instantly or over time.  (Fundamentals of Electrostatic Discarge - incompliancemag.com)

I followed this BME280 installation guide, however when prompting for 'i2cdetect -y 1' there were lines but no number showing up.

The I2Cdetect -y 1
Will send a ReadBit message to each possible slave 0-127.  Then listens for the ACK on the slave address.
The message is very simple, but does the trick for detecting working i2c slaves.
As you stated there is no "Lines", i would suggest the slave either has issues responding, if the BME280 has the correct 3v3+GND supplied.
As another possability, could you redo this step dtparam=i2c_arm=on,i2c_baudrate=400000
(Set the baudrate way down to 10000 /10k. Should this solve the issue and you need higher bandwidth, attempt on "50000 /50k" or "100000 /100k") This is just to eliminate the possibility the slave cannot opperate on this high frequency. 400k Baudrate for SMBus is high for a prototype/testing scenario. Very small amounts of interference can corrupt the data over SDA.
Another possibility is the Sink-Current which i've learned the hard way is not the same on i2c and SMBus over i2c.
Is you Pull-up resistor appropriate for the limited sink-current?

The SMBus specifies a minimum sink current of 100µA, and a maximum of 350µA, compared to 3mA for the I²C bus   (Ampere=Voltage/Resistance Ohm).

Now to the Software issue.
From your supplied picture on imgur.
File "newcodes_''''''''''''''.py" line 2, in
Your compiler cannot find "bme" where you attempt to import bme280.  Reference/path issue?
This can be the cause for other issues further into the code calls.
I don't know what SW you are writing the code in, but if there is an option to insert a breakpoint and run a debug build. I would suggest starting there :)

A: Alright I have resolved the issue, I changed the wire from jumper wire to hard wire. Thank you guys for your response. I appreciate all of them :D


text:
Q: Changing packet priority in IPv6 by routers Why are routers allowed to change the priority of an IPv6 packet?. If they do so then, a packet with high priority might be dropped. Then giving priority to the packets makes no sense!.

A: Any network device can change the DSCP values.
It is a matter of trust. For instance, ISPs will not trust your markings (you may be able to pay your direct ISP to trust your markings, to a certain degree, but subsequent ISPs in the path will ignore or change them to BE). You wouldn't/shouldn't trust another network's markings on your own network.
QoS is all about fairness, as you define it. Other network administrators will define it differently than you do. You should almost never trust an application's markings, otherwise all the applications could mark their traffic as EF. For instance, by default, Cisco switches will remark all incoming traffic to BE.
You should mark the traffic as close to the source as possible (on the access switch, if you can) so that you can treat it the way you like for as long as possible in your own network.


text:
Q: Search record using jsp-tags I have a page containing a list of records. I need to have a search box in my list page where in, when the user type a key word and click the search button, the contents of the table should then be filtered depending on the keyword that the user typed in.
This is what I've done so far.
In my View, I have this:
         <form:find finderName="BySearchWord" id="ff_ph_com_domain_Accommodation" path="/accommodations">
            <field:input disableFormBinding="true" field="searchKeyword" id="f_ph_com_domain_Accommodation" max="255" required="true"/>
        </form:find>

I am using jsp-tags named find for this.
In my Controller, I have this method.
@RequestMapping(params = "find=BySearchWord", method = RequestMethod.GET)
public String list(@RequestParam("searchKeyword") String searchKeyword, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, @RequestParam(value = "sortFieldName", required = false) String sortFieldName, @RequestParam(value = "sortOrder", required = false) String sortOrder, Model uiModel) {
    if (page != null || size != null) {
        int sizeNo = size == null ? 10 : size.intValue();
        final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
        uiModel.addAttribute("accommodations", Accommodation.findAllAccommodationBySearchBox());
    } else {
        uiModel.addAttribute("accommodations", Accommodation.findAllAccommodationBySearchBox());
    }
    addDateTimeFormatPatterns(uiModel);
    return "accommodations/list";
}

I honestly am not sure if it is right to put this here, but this is what I have on my domain so far.
public static List<Accommodation> findAllAccommodationBySearchBox() {
    return entityManager().createQuery("SELECT a FROM Accommodation a WHERE a.person.firstName LIKE :searchKeyword OR a.person.middleName LIKE :searchKeyword OR a.person.lastName LIKE :searchKeyword OR a.room.roomNumber LIKE :searchKeyword OR a.person.pvId LIKE :searchKeyword OR a.startDate LIKE :searchKeyword OR a.endDate LIKE :searchKeyword", Accommodation.class).getResultList();
}

public static List<Accommodation> findAllAccommodationBySearchBox(String searchKeyword) {
    String jpaQuery = "SELECT a FROM Accommodation a WHERE a.person.firstName LIKE :searchKeyword OR a.person.middleName LIKE :searchKeyword OR a.person.lastName LIKE :searchKeyword OR a.room.roomNumber LIKE :searchKeyword OR a.person.pvId LIKE :searchKeyword OR a.startDate LIKE :searchKeyword OR a.endDate LIKE :searchKeyword";
  if (searchKeyword == null || searchKeyword.length() == 0) throw new IllegalArgumentException("The search keyword is required");
  searchKeyword = searchKeyword.replace('*', '%');
  if (searchKeyword.charAt(0) != '%') {
    searchKeyword = "%" + searchKeyword;
  }
  if (searchKeyword.charAt(searchKeyword.length() - 1) != '%') {
    searchKeyword = searchKeyword + "%";
  }
    return entityManager().createQuery(jpaQuery, Accommodation.class).getResultList();
}

and this on another class:
public List<Accommodation> findAllAccommodationBySearchBox(String searchKeyword) {
    if (searchKeyword == null || searchKeyword.length() == 0) throw new IllegalArgumentException("The description argument is required");
    searchKeyword = searchKeyword.replace('*', '%');
    if (searchKeyword.charAt(0) != '%') {
        searchKeyword = "%" + searchKeyword;
    }
    if (searchKeyword.charAt(searchKeyword.length() - 1) != '%') {
        searchKeyword = searchKeyword + "%";
    }
    EntityManager em = Accommodation.entityManager();
    TypedQuery<Accommodation> q = em.createQuery("SELECT a FROM Accommodation a WHERE a.person.firstName LIKE :searchKeyword OR a.person.middleName LIKE :searchKeyword OR a.person.lastName LIKE :searchKeyword OR a.room.roomNumber LIKE :searchKeyword OR a.person.pvId LIKE :searchKeyword OR a.startDate LIKE :searchKeyword OR a.endDate LIKE :searchKeyword", Accommodation.class);
    q.setParameter("searchKeyword", searchKeyword);
    return q.getResultList();
}

I am following a tutorial I've found online but the structure of that is a bit different with what I have so I couldn't quite point out what I've not been doing. I'm really at a lost right now. I've been trying to figure this out for almost a day now.
P.S. I only got as far as being able to type something on the search box and having the page redirected after I clicked the search button but I only got an exception message saying "Query argument searchKeyword not found in the list of parameters provided during query execution."
Hope someone can help me out.

A: This whole code looks a little bit messy, but your first problem would be the list(...) method in your controller. It takes a lot of arguments but what it basically does is:
@RequestMapping(params = "find=BySearchWord", method = RequestMethod.GET)
public String list(@RequestParam("searchKeyword") String searchKeyword, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, @RequestParam(value = "sortFieldName", required = false) String sortFieldName, @RequestParam(value = "sortOrder", required = false) String sortOrder, Model uiModel) {
    uiModel.addAttribute("accommodations", Accommodation.findAllAccommodationBySearchBox());

    addDateTimeFormatPatterns(uiModel);
    return "accommodations/list";
}

because your if statement doesn't matter at all. So fix your if statement if you want it to do anything. You probably want to limit search result so pass the values to findAllAccommodationBySearchBox() and use them with setMaxResults() and setFirstResult() methods.
Now, you call findAllAccommodationBySearchBox() method without any arguments (this shouldn't be possible at all using your query) which will always throw the exception as you don't provide the query with required parameters.
Your 'first' (you don't want to have two methods with same usage, same names, same arguments and even different code inside btw) findAllAccommodationBySearchBox(String searchKeyword) also doesn't add required parameter.


text:
Q: Javascript: Find value of an element in tag by classname I have the following code:

   1:0
   Geometric Decomposition
   1

   1:11
   Pipeline
   1

UPDATE
I am iterating through the table rows to get the value in class="Pattern" while also reading the value of the first cell (ID e.g. 1:01). My current javascript code:
 nodeIds = []
 nodePatterns = []
for(i = 0; i < tds.length; ++i) {
    var cells = tds[i].getElementsByTagName("td");
    nodeIds.push(cells[0].innerHTML);
    nodePatterns.push(cells[1].innerHTML);
}

But with cells[1].innerHTML I just get the following values:

*

*Geometric Decomposition

*Pipeline
Now I am looking for a way to get the value of tag span with class="Pattern" i.e. Geometric Decomposition and Pipeline. I could use javascript functions like indexOf... but I was looking for a more elegant way to solve this problem by calling the tags with their tag name.
Is their a way?

A: document.querySelector('.pattern')

or to be more specific than that, possibly
document.querySelector('span.Pattern')

The getElementsBy* methods return HTMLCollections, which can be difficult to work with. When you want collections, consider using querySelectorAll instead, which returns a static NodeList - unlike an HTMLCollection, it can be iterated over directly, it won't change while it's being iterated over, and it's much more flexible.
Or, when you're just selecting one element, just use .querySelector.
Another side note: unless you want to get HTML markup in particular, it's generally easier to use .textContent rather than .innerHTML.

A: You can use the function querySelector which selects the first found element.

console.log(document.querySelector('table tr td span.Pattern').textContent)
.as-console-wrapper { max-height: 100% !important; top: 0; }

   Geometric Decomposition

If you need to get access to multiple span elements, you can use the function querySelectorAll which returns a NodeList of found elements.
To get the first TD, you can go up using the function closest and then execute the function querySelector.

Array.prototype.forEach.call(document.querySelectorAll('table tr td span.Pattern'), function(span) {
  console.log(span.closest('tr').querySelector('td').textContent);
  console.log(span.textContent);
});
.as-console-wrapper { max-height: 100% !important; top: 0; }

      1:0
      Geometric Decomposition
      1

      1:11
      Pipeline
      1


text:
Q: Vue: Typescript not working only in App.vue So, I created a vue app with vue CLI to be using it with typescript... and everything worked fine... all my components work fine with typescript... even main.ts works well...
the problem is if I try to use typescript in my App.vue file tough, I get a SyntaxError... super weird, coz I never had this problem before and typescript works fine in my other projects.... I cannot figure out, why it is not working.... even a simple thing like this:
<template src="./App.html"></template>

<script>
import { Component, Vue } from "vue-property-decorator";

@Component()
export default class App extends Vue {
  a: string = "";
  mounted() {}
}
</script>

produces

SyntaxError: C:\DEVELOPMENT\app\src\App.vue: Unexpected token (9:3)

   7 | @Component()
   8 | export default class App extends Vue {
>  9 |   a: string = "";
     |    ^
  10 |   mounted() {}
  11 | }
  12 |

Obviously if I remove :string part all works well...
my tsconfig file is pretty standard, haven't done any changes to that part.... and the App.vue is places as it should be, root of src folder
my tsconfig
   {
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "noImplicitThis": true,
    "noImplicitAny": false,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "resolveJsonModule": true,
    "baseUrl": ".",
    "types": [
      "node"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "es2015",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "src/**/*.scss",
    "src/**/*.html",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

so can somebody tell me what might be going on?

A: To use TypeScript inside a Vue component, you will need to specify the language inside the script tag like this:
<script lang="ts">

Without the lang attribute Vue assumes your component is JavaScript, so TypeScript seems invalid to it.


text:
Q: Reusing Umbraco datetime picker Umbraco 7 has this date/time picker

How do you reuse that in a custom control to avoid reinventing the wheel?
Currently I only have a plain textbox:
<input type='text' ng-model='validTo' />

A: Possibly the easiest way is to instantiate the right editor in the controller and bind it to the umbEditor directive.  Your template might include something like this:
    <umb-property ng-if="validTo.hasValue" property="validTo.model">
        <umb-editor model="validTo.model"></umb-editor>
    </umb-property>

while your controller might contain something like this:
$scope.validTo = {
    model: null,
    existingValue: null,
    hasValue: false
};

function buildDateTimePickerModel(alias, label, description) {
    return {
        editor: "Umbraco.DateTime",
        label: label,
        description: description,
        hideLabel: false,
        view: "datepicker",
        alias: alias,
        value: null,
        validation: {
            mandatory: false,
            pattern: ""
        },
        config: {
            format: "YYYY-MM-DD HH:mm:ss",
            pickDate: true,
            pickTime: true,
            useSeconds: true
        }
    };
};

$scope.validTo.model = buildDateTimePickerModel('validTo', 'Valid To', 'Enter the Valid To date');

Or something like that.  I've not tested it but have derived it from an existing project of mine that implements the ContentPicker on a custom UI in a similar fashion.
You might also find this useful to get an idea of the available config options:
https://github.com/umbraco/Umbraco-CMS/blob/dev-v7/src/Umbraco.Web.UI.Client/src/views/propertyeditors/datepicker/datepicker.controller.js#L4-L16


text:
Q: Run action and defined speed I am trying to create a performance test in .NET and one of the steps is to "call" server at defined speed like: persistent ~400 calls per second.
The problem is that running server call has different length from: 10ms to 100ms.
My first try was simple for loop with Thread.Sleep but this gives me results form 250-600 calls per second, depending on moment and server responses :(

A: I assume you need a steady rate of calls per second (that is, you need 400 calls per second distributed evenly over the second as much as possible).
You need adaptive delays during your test - if your server sends responses slowly, you need less delay; when the server is fast, you need more delay between calls. You can keep track of past server response times and calculate the delay for the current call based on that to come as close to the 400 calls / second rate as possible. It'll still fluctuate somewhat but it'll be much better than a simple hard-coded Thread.Sleep.
You need to keep in mind, that with many active threads (depending on hardware resources), the sleep duration of a thread may fluctuate as well. I don't know how familiar you are with the nuances of Thread.Sleep - you should read this answer to understand the limitations, as this may play a role in scheduling your test calls.

A: I think implementing loads and performance tests for your functions could be complicated considering all the threading stuff that needs to be simulated.
You can use Visual Studio Load test for this purpose and it has wizards to help you simulate what kind of load you need...
Take a look at this article for your reference:
https://msdn.microsoft.com/en-us/library/vstudio/dd293540(v=vs.110).aspx
Just note that for LoadTest you will need the VS Ultimate version...


text:
Q: Undefined index btn php Estoy haciendo una página con una vista principal, que tiene el botón de buscar usuario, cargar usuario y mostrar lista de usuarios.
Todos finalmente acaban llamando a la controladora que tiene funciones de acuerdo al value de los botones. Me funcionan perfecto, salvo el de lista de usuarios, que me dice:

undefined index btn

en todas las lineas donde esta btn en la controladora principal (no sólo en el de lista de usuarios), cuando en el resto de los btn no me dice eso!
Principal

Sistema de Gestion de Multas

    <button class="btn btn-default" type="submit" name="btn" value="cargar">Cargar usuario</button> //Esto me lleva a la pagina de alta personas, la cual llama a la controladora desde el action del formulario
<form method="post" action="../controladoras/controladoraprincipal.php">
//formulario
<button type="submit" class="btn btn-info" name="btn" value="agregar">Agregar</button>

Cuando llega a la controladora, sabe qué hacer mediante
if ($_POST["btn"] == "agregar")
{
    if (empty($_POST['nombre']) || empty($_POST['apellido'])  || empty($_POST['dni']) || empty($_POST['direccion']) || empty($_POST['fechanacimiento']))
        throw new Exception('Debe pasar todos los valores');
    $nombre = $_POST['nombre'];
    $apellido = $_POST['apellido'];
    $dni = $_POST['dni'];
    $direccion = $_POST['direccion'];
    $fechanacimiento = $_POST['fechanacimiento'];
    $persona1 = new Persona ($nombre, $apellido, $dni, $direccion, $fechanacimiento);
    $daop->agregar($persona1);
    $listado = $daop->todas();

    require_once ('../vistas/listadeusuarios.php');
}

Y así funciona perfecto. Ahora, cuando mando directo de la vista principal a la controladora con el botón "Lista de usuarios":

<button class="btn btn-default" type="submit" name="btn" value="lista">Listado de usuarios
</button>

controladora principal
$daop= new PersonaJsonDao();

if ($_POST["btn"] == "lista")
{
    $listado = $daop->todas();
    require_once('../vistas/listadeusuarios.php');
}

El resultado es

Notice: Undefined index: btn in
  C:\wamp\www\proyectomultas\controladoras\controladoraprincipal.php on
  line 13 Call Stack
  Time  Memory  Function    Location 1  0.0019  149288  {main}( )   ..\controladoraprincipal.php:0

Y me marca que ese error está en todas las líneas donde esta btn. Ssin embargo en el resto de las líneas donde esta btn, cuando lo uso no me marca ese error.

A: No puedes enviar, tal cual como lo tienes, mediante un  y por POST el valor del <button>.
El <button> debería ir en un <form>:
<form method="post" action="../controladoras/controladoraprincipal.php">

    <button class="btn btn-default" type="submit" name="btn" value="lista">Listado de usuarios</button>
</form>

y en controladoraprincipal.php:
if (isset('btn') && $_POST['btn'] == 'lista') {

     // resto de código
}


text:
Q: Associating Strings with enums in C# I work on C# window ...vs05 ......i want to put space on enum string ....i do it below code have this.....My problem is after select a value from the combo how can i get the index number of this value .....and if i gone to edit mode then i need to show the value what is user already selected .....how to get enum selected value on basis of index number
public enum States
{
  California,
  [Description("New Mexico")]
  NewMexico,
  [Description("New York")]
  NewYork,
  [Description("South Carolina")]
  SouthCarolina,
  Tennessee,
  Washington
}

public static string GetEnumDescription(Enum value)
{
   FieldInfo fi = value.GetType().GetField(value.ToString());

   DescriptionAttribute[] attributes =
                    (DescriptionAttribute[])fi.GetCustomAttributes(
                     typeof(DescriptionAttribute), false);

   if (attributes != null && attributes.Length > 0)
      return attributes[0].Description;
   else
      return value.ToString();
}

public static IEnumerable<T> EnumToList<T>()
{
    Type enumType = typeof(T);

    // Can't use generic type constraints on value types,
    // so have to do check like this
    if (enumType.BaseType != typeof(Enum))
       throw new ArgumentException("T must be of type System.Enum");

    Array enumValArray = Enum.GetValues(enumType);
    List<T> enumValList = new List<T>(enumValArray.Length);

    foreach (int val in enumValArray)
    {
       enumValList.Add((T)Enum.Parse(enumType, val.ToString()));
    }

    return enumValList;
 }

 private void Form1_Load(object sender, EventArgs e)
 {
    //cboSurveyRemarksType = new ComboBox();
    cboSurveyRemarksType.Items.Clear();
    foreach (States state in EnumToList<States>())
    {
       cboSurveyRemarksType.Items.Add(GetEnumDescription(state));
    }
 }

A: *

*You could iterate through the enums available (Enum.GetValues(enumType)) and see which one has the description chosen (not the best performance but it is probably not significant for combo-boxes).

*You could create your own attribute, and have the index there as well (ugly in terms of coding practice)

*If you want to improve performance on option #1 you could pre-cache a Dictionary<String, Integer> object with the descriptions of each enum, and use that instead.

A: So you have an integer and you want to convert it back to the enum type? Just cast it. So long as you haven't explicitly specified any values in your enum declaration, and so long as the "index" you've got is 0-based you should be able to do:
States state = (States) stateIndex;

(Note that by normal .NET naming conventions this should be called State by the way - plurals are usually reserved for flags.)
This answer is based on the text of your question rather than your code - I can't see anything in your code which really refers to an index.

A: Simple. You can cast the selected index (which is an integer) to the States enum. I have written a simple test method which demonstrates a few examples of using the enum that should help clear the concept:
private static void TestMethod()
    {
        foreach (States state in EnumToList<States>())
        {
            Console.Write(GetEnumDescription(state) + "\t");
            Int32 index = ((Int32)state);
            Console.Write(index.ToString() + "\t");
            States tempState = (States)index;
            Console.WriteLine(tempState.ToString());

        }
        Console.ReadLine();
    }

If you don't understand, would be happy to clarify further.


text:
Q: What does it mean that $\dim V=\dim F[x]/(p(x))=\deg p(x)$ $\dim V=\dim F[x]/I=\deg p(x)$ where $V$ is a $F[x]$-module and $I=(p(x))$
Here $p$ is irreducible.
$V$ is in fact a vector space over a field $F$, but by a linear operator $T\in End_F(V)$, made into a $F[x]$-module: $$f(T)\cdot v:=f(T(v))\in V$$
for all $v\in V,\,f\in F[x]$.
What I don't get is the meaning of $\dim F[x]/I$ and why the equalities hold.
Isn't the dimension of a ring, or, scalars is just 1?
EDIT: $(p(x))$ is maximal

A: I suppose that $F$ is a field.
Then the dimension is to be understood as dimension as vector space over $F$ and the equality is true because one can easily prove that if $\deg p(x)=d$ and $\bar x$ denotes the class of $x$ in the quotient then
$$
1,\bar x, \bar x^2,\ldots\bar x^{d-1}
$$
is a basis of $F[x]/(p(x))$.


text:
Q: Converting datetime to date and displaying in vuejs input I'm trying to convert a datetime result to date using split. But as much as it shows the date correctly without the time, it doesn't display in the input.

data(){
    return {
      date_created: String(this.date_created).split('T')[0],
      },
},
methods: {
      editItem (item) {
        this.date_created = item.society_date_created
        this.dialog = true
      },
},
created: function(){
                   axios.get(process.env.VUE_APP_Back+"/societies")
                        .then(response => {
                          this.society = response.data;
                        })
                        .catch(error => {
                          this.society = error.data;
                        });
                  this.loadTable= false;
},
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<input class="form-control" type="date" v-model="date_created" disabled>

Reponse date_created in api

2020-06-30T00:00:00.000Z

A: You need to set this.date_created in your editItem method
data(){
  return {
    date_created: null
    },
},
methods: {
    editItem (item) {
      this.date_created = item.society_date_created.split('T')[0]
      this.dialog = true
    },
},


text:
Q: Binary-Relay don't expand SOAP message in wso2 EI and wso2 API Manager We are using wso2 api manager (2.1.0) to manage our SOAP apis.
The reponse message of a our web service has content type "application/dime".
We change axis2.xml to use binary-relay (builder and formatter) with that content type.
<messageFormatter contentType="application/dime"
   class="org.wso2.carbon.relay.ExpandingMessageFormatter"/>

<messageBuilder contentType="application/dime"
   class="org.wso2.carbon.relay.BinaryRelayBuilder"/>

The response SOAP message is not expanded, so we have a return envelope like this
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
    <ns:binary xmlns:ns="http://ws.apache.org/commons/ns/payload">DCAAAAApACkAAAJxdXVpZDo3MTRDNk...U9GCgA=</ns:binary>
</soapenv:Body>
</soapenv:Envelope>

We saw the same behaviour with wso2 enterprise integrator (6.1.1).
Is there any configuration that we have to do to enable expanding of response SOAP message in api manager or enterprise integrator?
Would we do something else?

A: maybe the Content-Type in the API Manager is not preserved, look at this: WSO2 api manager not propagating content type header for multipart form data you can set the property http.headers.preserve to preserve Content-Type.

A: The APIM is working as expected in this scenario. You have set the binary formatters for your content  type. So APIM,ESB treat your payload as a binary content and pass the same binary content inside a soap envelop.
You need to define the correct formatter and builder for your content type "application/dime". Refer [1] on how Message Builders and Formatters work. Identify the correct formatter and builder for your type.
[1] - https://docs.wso2.com/display/ESB500/Working+with+Message+Builders+and+Formatters


text:
Q: Trying to set the audio input for webRTC I am trying to set the audio input in a webRTC Electron App. This function runs with no errors but it is completely ignored. The app is based on jssip. Anyone got any ideas?
function setaudioinput(audioSource){
log.info("Trying to set audio input to",audioSource)
const constraints = { audio: {deviceId: audioSource ? {exact: audioSource} : undefined}, };
navigator.mediaDevices.getUserMedia(constraints)
    .then(function(stream) {
    var audioTracks = stream.getAudioTracks();
    log.info('Got stream with constraints:', constraints);
    log.info('Using Audio device: ' + audioTracks[0].label);
    localStorage.setItem('AUDIOINPUT', audioSource);
})

}


text:
Q: Elementary number-theory proof sought Take any 8 3-digit numbers $\in \mathbb Z^+$. There will always be at least two of them which you can put next to eachother to form a 6-digit number which is divisible by 7. Why?

A: The 6 digit number can be represented as $1000y+x$ where $y$ and $x$ are 3 digit numbers.
Now note that: $$1000y+x\equiv 6y+x\mod(7)$$
You can always choose two numbers with same remainder using the pigeonhole principle.

A: a) Show that a 6-digit number, which is formed by two 3-digit numbers that leave the same remainder with respect to division by $7$, is divisible by $7$.
b) Think about how you can use a) to conclude.


text:
Q: Submitting follow & unfollow with jquery okay so the main problem im having is that , im trying post isset to my php file which contains mysqli_query to insert the follower and remove the follower , i have tried it in simple way by making an follow  and it worked fine with follow and unfollow , but now im trying to do it without refreshing the page , but somehow its notworking at all. and im new to jquery :).
<?php
$query = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT id FROM follow_user WHERE userid='$userid' AND follow_id='$uid'");
if(mysqli_num_rows($query)== 1)
{
    echo "
 Follow
";

    echo"
 Following
";
}
else
{
    echo "
 Follow
";

    echo"
 Following
";
}

?>

jquery

$(function () {
    $(".follow").click(function () {
        var datastring = '?action=follow&uid=' + userid;
        $.ajax({
            type: "POST",
            url: "include/follow_user.php",
            data: datastring,
            success: function (html) {}
        });
        $("#follow" + userid).hide();
        $("#remove" + userid).show();
        alert("Yeah!");
        return false;
    });
});

//remove class
$(function () {
    $(".remove").click(function () {
        var datastring = '?action=unfollow&uid=' + userid;
        $.ajax({
            type: "POST",
            url: "include/follow_user.php",
            data: datastring,
            success: function (html) {}
        });
        $("#remove" + userid).hide();
        $("#follow" + userid).show();
        alert("Yeah!");
        return false;
    });
});

A: The code for success actions should be inside the success callback or else they will be called anytime without the conclusion of the request itself. Take a look:
$(".follow").click(function () {
    $.ajax({
        type: "POST",
        url: "include/follow_user.php",
        data: {action:"follow", uid: userid},
        success: function (html) {
            $("#follow" + userid).hide();
            $("#remove" + userid).show();
            alert("Yeah!");
        }
    });
});

Then in your "follow_user.php" you have to return the process state(e.g. 1 ok - 2 error):
if(mysqli_num_rows($query)== 1)
{
    echo "1";
}
else
{
    echo "2";
}

Then in your callback you check it:
success: function(data)
{
    if (data == "1")
    {
        $("#follow" + userid).hide();
        $("#remove" + userid).show();
        alert("Yeah!");
    }
    else
    {
        alert("Some error occur");
    }
}