text:
Q: How to merge a branch to multiple protected branches in gitlab I have a gitlab repository with a protected branch "main" that is the current working version source, then at some point in time this branch is forked for the current version Release (say Version 2.0) and protected. Main is then used for the next version release (Version 3.0).
Each developer will create a unique branch for feature/bug changes that will get merged into the protected branch. Now a bug has been found in the Version 2.0 release that must be patched, therefore the bug also exists in the main as well. Developer creates a branch off the Version2.0 and fixes the bug.
How do I get the bug fix into both protected branches with a single merge?
Basic concept of a single merge is a "Merge Request" to Version2.0, that then automatically mirrors the change to main. However I cannot have changes to main merged to Version2.0.
                /-B-\    /-F-\
----------\----/-----\--/-----\------------/--------Main
           \                              /
            \----Version2.0-\------------/----
                             \          /
                              \-- Bug--/

Or am I going to have to merge to Version 2.0 then rebase the bug onto Main then merge again?
                /-B-\    /-F-\         /-Bug-\
----------\----/-----\--/-----\-------/-------\--------Main
           \
            \----Version2.0-\---------/----
                             \       /
                              \-Bug-/

I am trying to avoid having to be the commit overseer to make sure that every commit to V2.0 is included in v3.0, otherwise we will find the same bug again and assign someone to dedicate time to fix (again).


text:
Q: How to prevent inplace operation of Pandas dataframe? I'm trying to write a function to fill missing data in a Pandas Dataframe. The input of the function is a dataframe with missing values and the column name that I would like the missing value to be filled, and it would return a new datafrme with the missing values filled. The problems is that function would also fill the missing values of the input dataframe, which what I'm not intended to do. Please see my codes below:
    import pandas as pd
    import numpy as np
    from sklearn.impute import SimpleImputer
    table = pd.DataFrame({'feature1':[3,5,np.nan],'feature2':[4,1,np.nan],'feature3':   [6,7,3]})

    def missingValueHandle(dataframe,feature):
        df = dataframe
        df[feature] = df[feature].fillna(axis = 0, method = 'ffill')
        imp = SimpleImputer(strategy = 'mean')
        df = imp.fit_transform(df)
        return df

    new_dataframe = missingValueHandle(dataframe=table,feature = 'feature1')
    new_dataframe

feature1
feature2
feature3

0
3.0
4.0
6

1
5.0
1.0
7

2
5.0
NaN
3

    table

feature1
feature2
feature3

0
3.0
4.0
6

1
5.0
1.0
7

2
5.0
NaN
3

As you can see, my input "table" is changing with the output "new_dataframe", what do I need to do to prevent that from happening?

A: Use the assign method instead of assigning to the passed dataframe.
.assign always returns a new dataframe.
def missingValueHandle(dataframe, feature):
  return (
    dataframe
    .assign(**{feature: lambda df: df[feature].ffill()})
    .pipe(SimpleImputer(strategy='mean').fit_transform))

In this case this can also be done without a lambda:
def missingValueHandle(dataframe, feature):
  return (
    dataframe
    .assign(**{feature: dataframe[feature].ffill()})
    .pipe(SimpleImputer(strategy='mean').fit_transform))

The benefit of the lambda approach is that you can add a row filter in the pipeline before the assign and it still works

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I construct an EnumSet of generic varargs? Assume I want to do something like the following:
public static <V> Set<V> setOf(V... elem)
{
    Set<V> set = null;
    if (elem[0] instanceof Enum)
        set = Sets.newEnumSet(elem, elem[0].getClass());  OR
        set = EnumSet.<V>noneOf(elem[0].getClass());
    return set;
}

Neither of these, or several other variations, seem to work.  Can someone explain to me what's going on?  I have looked at How do I get the type object of a genericized Enum? and some other similar questions, but I still can't get this to work.

A: First of all, you need to make sure the type V is restricted to be an enum type; you can do this by specifiying that V must extends Enum<V>.
Then, you will need to provide the Class of the enum type. Due to type-erasure, you won't be able to derive it at run-time. This is needed because, to construct a new empty EnumSet, you need to specify the type of the elements.
Finally, you have several ways to create the set, but the simplest might be to use the Stream API:
@SafeVarargs
public static <V extends Enum<V>> Set<V> setOf(Class<V> enumClass, V... elem) {
    return Arrays.stream(elem).collect(Collectors.toCollection(() -> EnumSet.noneOf(enumClass)));
}

Note that if you can guarantee that there will be at least 1 element, you could use EnumSet.copyOf(Arrays.asList(elem)) without the need to pass the class.

A: If you can't bound the generic parameter to V extends Enum<V>, you can make compilable code as follows:
public <V> Set<V> setOf(V... elem) {
    Set<V> set = null;
    if (elem[0].getClass().isEnum()) {
        set = (Set<V>) EnumSet.copyOf((Collection<Enum>)Arrays.asList(elem)) ;
    }
    return set;
}

Of course there are unsafe cast warnings.

I also changed the check of the type to:
if (elem[0].getClass().isEnum())

which IMHO is cleaner.


text:
Q: Precision plotting in time axis I have a trouble plotting data, I only want plot HH:MM:SS but the plot shows HH:MM:SS.sssss or HH:MM:SS.%f. Below i gonna detail what I did (matplotlib, numpy are already imported )
Method I
Loading files to plot
import datetime as dt
data=genfromtxt('27JAN12.K7O', delimiter=2*[4]+5*[2]+8*[7])
f245   = data[:, 7]

Generating array for time (1 data per second)
base = dt.datetime(2014,1,27,11,07,59)
time  = array([base + dt.timedelta(seconds=i) for i in range(len(data))])
plot(time,f245)

When i did this, i got this plot (with innecesary precision)

here i got time like 18:15:00.000000 (i just like 18:15:00)
Method II
The same way to load data, in this case only I took the time of the data and coverted in time string
t      =  data[:,1] #in decimals e.g. 18,5 represents 18:30:00
tstr   =  map(str, [dt.timedelta(seconds=x) for x in t])
time = []
for i in tstr:
    try:
        time.append(dt.datetime.strptime(i, "%H:%M:%S"))
    except ValueError:
        time.append(dt.datetime.strptime(i, "%H:%M:%S.%f"))
plot(time,f245)

In this case, i got time like 18:15:00.%f
So, how i could repair this?

A: You should use plot_date to plot datetime objects using matplotlib.
You can use matplotlib.dates.date2num to convert the datetime objects into the matplotlib format.
Furthermore you can use DateFormatter objects to set the formatting of the x-axis tick labels.
I have now included a small example using generated data, hopefully this will explain everything for you.
import numpy as numpy

import matplotlib.pyplot as plt
from matplotlib.dates import date2num, DateFormatter

import datetime as dt

base = dt.datetime(2014, 1, 27, 11, 7, 59)

x = [base + dt.timedelta(seconds=i) for i in range(10)]
y = [i**2 for i in range(10)]

x = date2num(x) # Convert datetime objects to the correct format for matplotlib.

fig, ax = plt.subplots()

ax.plot_date(x, y) # Use plot_date rather than plot

# Set the xaxis major formatter as a DateFormatter object
# The string argument shows what format you want (HH:MM:SS)
ax.xaxis.set_major_formatter(DateFormatter('%H:%M:%S'))

# This simply makes them look pretty by setting them diagonal.
fig.autofmt_xdate()

plt.show()


text:
Q: Using the tr command with character ranges For the past few months, I've been learning about the command line with the help of William E. Shotts' The Linux Command Line.
The Linux Command Line remains a popular book for newbies who would like to learn more about the Linux command line.
In one of the chapters, it introduces the tr command. The book says that character sets can be constructed in one of three ways: an enumerated list such as ABCDEFGHIJKLMNOPQRSTUVWXYZ; a character range, such as A-Z; and POSIX character classes, such as [:upper:].
The part that I don't understand is when the book tells the reader to be wary about using character ranges for the character set because of the locale collation order, and suggests that the reader use POSIX character classes instead.
I've personally never encountered a problem using character ranges such as A-Z with
echo "lowercase letters" | tr a-z A-Z

so why should I refrain from using character ranges in favor of POSIX character classes?
In case you are wondering, my locale is en_US.UTF-8.

A: You're using UTF-8. Yay! ASCII, and by extension UTF-8 (because the UTF guys tried to make it a superset of ASCII), has the alphabets in alphabetical order with no gaps, so a-z contains all the normal lowercase characters and nothing else, and so on.
However, that need not be true on some other encoding. The classic example is EBCDIC:

The gaps between letters made simple code that worked in ASCII fail on
  EBCDIC. For example for (c='A';c<='Z';++c) would set c to the 26
  letters in the ASCII alphabet, but 40 characters including a number of
  unassigned ones in EBCDIC. Fixing this required complicating the code
  with function calls which was greatly resisted by programmers.

I'd like to think nobody uses weird stuff like this anymore, but who knows?

GNU tr doesn't support Unicode, AFAIK, but for programs that do, [[:upper:]] would also match Unicode characters that are considered uppercase alphabets, for example, a full-width "A", or an A with an accent: À.
$ printf "%s\n" A a A À | grep '[[:upper:]]'
A
A
À
$ printf "%s\n" A a A À | grep '[A-Z]'   # I'm also using Unicode, so grep tries to be friendly
A
À
$ printf "%s\n" A a A À | LC_ALL=C grep '[A-Z]'
A


text:
Q: What is the implied subject of "accounting"? I dreamed up these two sentences. I did some research. It seems that they are both correct. I understand that,in Sentence 1, the implied subject of "accounting" is the subject of the first clause — food. What I don't understand is why Sentence 2 is correct. In Sentence 2, the implied subject of the second clause is not the same as the subject of the first clause.
My grammar book says that we can omit the subject of the second clause and change the verb to the "ing" form when the subject same is the same as the subject of the first clause. It doesn't say that we can do this when the subjects are not the same. In Sentence 2, the subject of the first clause is "families". But what "accounting" needs is "food".

*

*Food was the biggest expenditure for families, accounting for 35% of their weekly income.

*Families spent most on food, accounting for 35% of their weekly income.

A: If you ask the question "what accounted for 35% of their weekly income?" the answer in both cases has to be food. 'Their' refers to the families.

A: Your grammar book is correct about omitting the subject in the second clause and using "ing" when it's the same as the first clause, and maybe that's a good place for beginner language learners to start, but the rule applies much more broadly than that.
The subject of the second clause can be removed any time that it appears somewhere in the first clause in a way that makes it unambiguous what the "ing" verb refers to. It doesn't even have to appear as a noun in the first sentence. The "ing" verb can not only refer to subjects, but to object nouns, and even clauses:

The grocery store was sold out of bacon, leaving me with no choice but to cancel the camping trip.

In this example, the grocery store isn't the subject of "leaving". It's the entire situation of the grocery store being out of bacon, so the subject of "leaving" is something like, "the fact that the grocery store was sold out of of bacon".


text:
Q: Hibernate creates self relation on a table using the primary key
I have an Entity Episode
@Id //The unique id.
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;

@Column(name= "title", unique = false, nullable = false)
private String title;

@Column(name= "description", unique = false, nullable = false)
private String description;

@Column(name= "price", unique = false, nullable = false)
private BigDecimal price;

@OneToOne(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
private Image icon;

@OneToOne(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
private Image episodeNexus;

private String repositoryGeneratedId;

@JsonIgnore
@ManyToOne(cascade = {CascadeType.ALL}, fetch = FetchType.LAZY)
@JoinColumn(name="webtoon_id")
Webtoon webtoon;

Webtoon
@Id //The unique id of the webtoon.
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;

@Column(name= "price", unique = false, nullable = false)
private BigDecimal price;

@OneToOne(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
private Image cover;

@OneToOne(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
private Image icon;

@Column(name= "title", unique = false, nullable = false)
private String title;

@Column(name= "author_name", unique = false, nullable = false)
private String authorName;

@Column(name= "description", unique = false, nullable = false)
private String description;

@Column(name= "language", unique = false, nullable = false)
private String language;

@Column(name= "company_id", unique = false, nullable = false)
private Long companyId;

@OneToMany(cascade = {CascadeType.ALL}, fetch = FetchType.LAZY, mappedBy="webtoon", orphanRemoval = false)
@Column(name= "user_review", nullable = true)
private List<Review> userReview = new ArrayList<>();

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy="webtoon", orphanRemoval = false)
@CollectionTable(name= "list_of_episodes")
@Fetch(value = FetchMode.SUBSELECT)
private List<Episode> listOfEpisodes = new ArrayList<>();

@OneToOne(fetch = FetchType.EAGER)
private Category category;

@OneToOne(fetch = FetchType.EAGER)
private SubCategory subCategory;

@OneToOne(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
@JoinColumn(name = "rating", unique=true, nullable=false)
private Rating rating = new Rating();

private String repositoryGeneratedId;

and Image
@Id //The unique id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String nexusId;
private String path;
private String name;
private String generatedUniqueId;
private Long size;

When I start my app, I notice that Hibernate create a foreign-key using the id. How is it possible ?
The code generated is the below. This constraint CONSTRAINT fkae0gia7g5anc7p031c00mdf7x FOREIGN KEY (id) must not exist.
CREATE TABLE public.episode
(
    id bigint NOT NULL,
    description character varying(255) COLLATE pg_catalog."default" NOT NULL,
    price numeric(19,2) NOT NULL,
    repository_generated_id character varying(255) COLLATE pg_catalog."default",
    title character varying(255) COLLATE pg_catalog."default" NOT NULL,
    episode_nexus_id bigint,
    icon_id bigint,
    webtoon_id bigint,
    CONSTRAINT episode_pkey PRIMARY KEY (id),
    CONSTRAINT fkae0gia7g5anc7p031c00mdf7x FOREIGN KEY (id)
        REFERENCES public.episode (id) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT fkeom9w8fbdmqm8j9nkq5hqglia FOREIGN KEY (icon_id)
        REFERENCES public.image (id) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT fksd2jfjxp5puq4cnp4renveldi FOREIGN KEY (episode_nexus_id)
        REFERENCES public.image (id) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT fkthwbcsb0axcklmd5wfhr650b9 FOREIGN KEY (webtoon_id)
        REFERENCES public.webtoon (id) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
)
WITH (
    OIDS = FALSE
)

A: Set hibernate.hbm2ddl.auto value to none in your Hibernate configuration.
See Automatic schema generation in Hibernate User Guide for details.


text:
Q: Access is Denied when connecting to remote computer using WMI from app under IIS I am getting Access is denied exception when I try to connect to a remote server using WMI through IIS (10.0).  This same code works fine through Visual Studio 2015 debug (IIS Express).  Obviously this is a permissions issue, however I cannot find anything definitive or even suggestive on the best way to approach this.
In my example, the client simply makes a POST call to the web service with credentials in the payload.  Then the service attempts to make a WMI connection getting the exception.  The remote server is not in a domain, and the credentials have been verified to have access to the given namespaces.
I'm running IIS 10, but have duplicated this with as low as IIS 7.
Any help is appreciated!
public ManagementScope Connect(Credentials creds, string path)
    {
        _creds = creds;
        _path = path;

        var conOpt = new ConnectionOptions
        {
            Impersonation = ImpersonationLevel.Impersonate,
            Authentication = AuthenticationLevel.PacketPrivacy,
            EnablePrivileges = true,
            Username = _creds.Username,
            Password = _creds.Password,
            //Authority = $"ntlmdomain:{_creds.Domain}"
        };
        // virtualization\v2
        _scope = new ManagementScope($@"\\{_creds.Server}\ROOT\{path}", conOpt);
        _scope.Connect();

        return _scope;
    }

A: I always recommend to avoid WMI calls inside an application on IIS, due to the reason of possible security lacks.
I recommend to create a local windows service as command relay.
So you would call your local service and this service would execute the remote WMI call. The windows service then needs permission to execute the WMI command at the remote machine and you do not have to change the permission of your web application environment.
Just as information: on other platforms like Azure you are not allowed to change the security settings of your WebApp. Also the service / relay way would solve that requirement.

A: A common misunderstanding is that IIS Express is IIS. No.
IIS Express executes the code under your account. That means if your account has necessary permissions then the code runs fine.
However, IIS is purely a hosting service and your code runs under the worker process identity aka application pool identity. Review your IIS settings to understand what I mean.
Only if you change that identity to another suitable one or grant the account necessary permissions, the code can work after.
Note that a web app should not perform such tasks that requires lots of extra permissions and then they can be compromised and lead to serious security issues. That's why the other answer suggests you move the WMI calls to a dedicate Windows service.
I had a blog post a few months ago,
https://blog.lextudio.com/2015/04/web-application-differences-in-visual-studio-and-iis/


text:
Q: Defining function call dynamically with javascript to anchor tag I have an anchor tag with id=1 and I am trying to define onClick="menu_function(shopname)" using the logic below, but it's not working like a.href:
function display_details(shopname,img)
{
    var a = document.getElementById("1");
    a.href = "./menu.php";
    a.onClick ="menu_function(shopname)";
}

Can you tell my why is it not working and guide me into the right direction?

A: Use a function expression as the value for onclick, not a string:
 function display_details(shopname,img)
 {
     var a = document.getElementById("1");
     a.href = "./menu.php";
     a.onclick = function(){
        menu_function(shopname);
     };
 }

Also note: JavaScript is case sensitive and the event is called onclick (lowercase) not onClick.


text:
Q: CheckAll/UncheckAll checkbox with jQuery I have made a check-box checkall/uncheckall.
HTML

 Using Check all function

<input type="checkbox" class="all" onchange="checkAll('selectCheckBox','all','check','true');" />Select All
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 1
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 2
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 3
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 4

main.js
function checkAll(parentId,allClass,checkboxClass,allChecked){
    checkboxAll = $('#'+parentId+' .'+allClass);
    otherCheckBox = $('#'+parentId+' .'+checkboxClass);
    checkedCheckBox = otherCheckBox.filter($('input[type=checkbox]:checked'));
    if(allChecked=='false'){
        if(otherCheckBox.size()==checkedCheckBox.size()){
            checkboxAll.attr('checked',true);
        }else{
            checkboxAll.attr('checked',false);
        }
    }else{
        if(checkboxAll.attr('checked')){
            otherCheckBox.attr('checked',true);
        }else{
            otherCheckBox.attr('checked',false);
        }
    }
}

It works fine. But get bulky when I have whole lot of checkboxes. I want to do same work by using jQuery rather than putting onchange on each checkbox. I tried different sort of things but couldnot work. I tried following one:
$('.check input[type="checkbox"]').change(function(e){
    checkAll('selectCheckBox','all','check','true');
});

to do same work as onchange event but didnot work. Where do I went wrong.

A: I think you just need this: You do not need to pass all the arguments and have the inline onchange event attached to it. You can simplify your code.
$(function () {
    $('input[type="checkbox"]').change(function (e) {
       if(this.className == 'all')
       {
           $('.check').prop('checked', this.checked); //Toggle all checkboxes based on `.all` check box check status
       }
        else
        {
            $('.all').prop('checked', $('.check:checked').length == $('.check').length); // toggle all check box based on whether all others are checked or not.
        }
    });
});

Demo

A: Your selector is wrong:
.check input[type="checkbox"]

Above selects any input of type checkbox that has the ancestor with class .check. It'll match this:

    <input type="checkbox".../>

it should be:
input.check[type="checkbox"]

A: You closed the string here $('.check input[type='checkbox']') instead, you should use double quotes $('.check input[type="checkbox"]')


text:
Q: Teradata ODBC connection issue: No version information available (required by ./tdxodbc64) on ubuntu We are facing the following issue while connecting to teradata server. Driver v16.10 and ubuntu v14.04.

/opt/teradata/client/16.10/bin$ ./tdxodbc64 -c SQLDriverConnect -t -S 'SERVER_IP' -u 'USERNAME' -p 'PASSWORD'
./tdxodbc64: /usr/lib/x86_64-linux-gnu/libodbcinst.so: no version
  information available (required by ./tdxodbc64)
./tdxodbc64: /usr/lib/x86_64-linux-gnu/libodbc.so: no version
  information available (required by ./tdxodbc64)
Segmentation fault (core dumped)

A: It is resolved by set the environmental variables

export ODBCINI="/opt/teradata/client/16.10/odbc_64/odbc.ini"
  export ODBCINSTINI="/opt/teradata/client/16.10/odbc_64/odbcinst.ini"
  export LD_LIBRARY_PATH="/opt/teradata/client/16.10/odbc_64/lib:/opt/teradata/client/16.10/odbc_64/odbc.ini:/opt/teradata/client/16.10/odbc_64/odbcinst.ini"


text:
Q: Xinput polling threading design I have developed a .net library for XInput using P/invoke, and am now getting ready to implement it into a gui (WPF).
I have had a look at the BackgroundWorker class, and have got it working as a test for 1 controller, but its a hack job and clearly it wouldn't be suitable for 2-4 controllers (this was mainly done to see what I needed to do with the gui).
So I'm asking some more of the experienced people here, on how to approach the threading in this app. Should I continue with the BackgroundWorker class or look at TPL in .net 4, or some other method?
The worker thread is required as there is no messaging system for XInput, only a polling system. The worker thread would check input roughly every 20ms or something like that (Thread.Sleep). I am also not sure if there should be only 1 worker thread for all controllers or 4 worker threads (there is a max controller limit of 4).
I'm a bit new to WPF and .NET in general, so any advice welcome :)

A: TPL looks like overkill to me. It looks like it is intended for getting processor intensive tasks to run in parallel on multiple processors.
Polling the controllers will not be overly processor intensive. I would say that the background worker is up to the job, and should be able to handle all the controllers. Poll each controller at the same time.


text:
Q: Read the commands from the text file and execute in sequence So I am told to write a program in which program should read and execute a list of commands from stdin. Each command and its arguments (if any) will appear on a separate line. My program works to their needs but only if I write ./sequence text.file or ./sequence < text.file text.file in the terminal but it is supposed to work when I write ./sequence < text.file.  I can't find the the bug in my code and moreover if someone can show me a better way of doing it will be really appreciated.
text.file
whoami
cal 4 2020
echo The time is:
date

CODE
#define MAX 10
#define LETTERS 256

/*Function definition to parse the command */
void parse(char *line, char **argv){

    char *token = line;
    char *extra;

  /* keep running until the end of the line  */

    while ((token = strtok_r(token, " \t\n", &extra)) != 0)
    {
        *argv++ = token;
        token = 0;
    }
  /* point the end of the argument to NULL*/

    *argv = 0;
}

/*Function definition of main()*/

int main(int argc, char *argv[]){

    char *arg[MAX],line[LETTERS];

    FILE *fp;

   /* Error checking for file opening */

    fp = fopen( argv, "r");
    if(fp == NULL){
        printf("ERROR NO input file \n");
        return 0;
    }
    pid_t pid;
    int status;

    /* Reading file line by line */

    while(fgets(line,LETTERS,fp)!= NULL){

        pid = fork();
    /*Errro checking for creation of child */

        if(pid < 0){
            printf("Fork child process failed!\n");
            exit(1);
        }
        else if(pid == 0){
            parse(line,arg);
            if(execvp(*arg,NULL) < 0){
                printf("Execvp failed!!\n");
                exit(1);
            }
        }
        else{
            wait(&status);       //Waiting for child process to finish.
        }
  }
  return 0;
}

TERMINAL
./sequence < text.file text.file

or
./sequence text.file

RESULT
manrajnsinghdua
     April 2020
Su Mo Tu We Th Fr Sa
          1  2  3  4
 5  6  7  8  9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30

The time is:
Thu Apr 30 11:13:11 ACST 2020

A: Your call to fopen() is not quite right, should be fopen(argv[1], "r");, but only after you confirm that argc >= 2

Instead of doing fopen(), it sounds like you just want to use stdin.
If you want to minimize your code changes, change:
    fp = fopen( argv, "r");

to
    fp = stdin;


text:
Q: Jquery before() with animation I'm trying to make appear the result of an ajax request using before(). It works very well, but now I'd like to make appear the result with animation (toggle, slidedown or something).
Here is the code I use:
jQuery.ajax({
  type: "POST",
  url: "/postcom",
  dataType: "text",
  data: myData,
  success: function(response) {
    $("#results_com").before(response);
    $("#formcomtext").val('');
  },
  error: function (xhr, ajaxOptions, thrownError) {
    console.log(thrownError);
  }
});

html:

Thanks

A: If you use insertBefore, it might be easier:
$(response).insertBefore("#results_com").animate({}, 400);

A: You should just hide #results_com before animating it in. Here's a simple demo for it: http://jsfiddle.net/pERgk/

A: working Demohttp://jsfiddle.net/cse_tushar/pERgk/2/
you can use toggle instead of slideDown
$('#results_com').click(function () {
    $('#results_com').hide().before('This will be the result').slideDown('slow');
});


text:
Q: Can I make my background service not stop or pause in kotlin? (Android Studio) I am making a stopwatch app and would like my stopwatch to continue after 1 minute of the app being closed or the phone being turned off. I was wondering if there was any way for me to make my timer service continue working after the the app is paused. In the background service I am currently using the timer function stop exactly 1 minute after the app is closed. I have been searching the internet for solutions which have pointed me towards foreground services but I am very inexperienced and cannot figure out how to make them work.
Here is my timer service (I got this from Code With Cal on youtube)
class TimerService : Service() {
override fun onBind(p0: Intent?): IBinder? = null

private val timer = Timer()

override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
    val time = intent.getDoubleExtra(TIME_EXTRA, 0.0)
    timer.scheduleAtFixedRate(TimeTask(time), 0, 1000)
    return START_NOT_STICKY
}

override fun onDestroy() {
    timer.cancel()
    super.onDestroy()
}

private inner class TimeTask(private var time: Double) : TimerTask() {
    override fun run() {
        val intent = Intent(TIMER_UPDATED)
        time++
        intent.putExtra(TIME_EXTRA, time)
        sendBroadcast(intent)
    }
}

companion object {
    const val TIMER_UPDATED = "timerUpdated"
    const val TIME_EXTRA = "timeExtra"
}

Can I make this into a service that continues on when the app is closed? Thank you so much (Note: This is my first app and I am very inexperienced. If there is any more code you need, please tell me, thanks!)

A: As Mike M. Answered in the comments:
"Nope, you can't do that, but you don't really need/want to, anyway. All you really need to know whenever your app is setting up the stopwatch is the starting time of the current timing session, and the time it is right now. If you save that starting time somewhere persistent – e.g., in SharedPreferences – then you just need to retrieve that value and do some simple arithmetic to get the stopwatch re-set correctly."
-Thanks so much (-Casper)


text:
Q: Using core.matrix in a IntelliJ IDEA cursive project I am trying to use core.matrix (https://clojars.org/net.mikera/core.matrix/versions/0.33.2) in a simple project in IntelliJ IDEA with Cursive plugin. I am just learning Clojure with some code and the REPL but I can't figure out how to "import" it. Do I have to download a .jar and put it in the lib folder? Which command is used to call those functions in REPL? Do I have to edit the project.iml?
I am aiming for the simplest way of doing it, as simple as writing some code in the REPL, no leiningen projects if it is possible.

A: Yuck. I just created a Clojure project in IntelliJ for the first time. My recommendation is not to. Instead get Leiningen. Use 'lein new whatever-your-app-is-called'. Then import the project into IntelliJ. Then add any dependencies to the project.clj. Cursive integrates with Leningen and Cursive suggests using Leiningen. To the best of my knowledge it can't be done purely via the REPL (the REPL has to be able to find the libraries, something has to tell it where they are, either the IDE or Leiningen).
Leiningen is the simplest way of doing it.
Using Leiningen you'll have a project.clj file. In there is a :dependencies section that takes a vector of libraries to use (org.clojure/clojure being one of them). If you add [net.mikera/core.matrix "0.33.2"] to the vector in :dependencies leiningen should fetch it for you.
Your :dependencies section should look something like this:
:dependencies [[org.clojure/clojure "1.6.0"]
               [net.mikera/core.matrix "0.33.2"]]

EDIT: Leiningen is the recommended way of using Cursive with IntelliJ Idea. In order to do without see Configuring Module Dependencies and Libraries in the jetbrains idea documentation.


text:
Q: Creating a Fake Computer Screen Within a Screen in Website I've begun working on a website for a grant-funded documentary. Within the documentary, one of the characters is building a website about a topic. For the real website, tthey want to put his computer (which is an hand-drawn graphic by the project's artist) around the website design & content as a frame.
To put it another way, when a user visits the actual website, they'll see the character's "screen" with the real design inside of it. In way, it's simulating a computer with a web design inside of my proper web design.
Cue "Inception" score.
Alright, now for the fun part. How in the heck would you go about this? I need to:

*

*Maximize screen real estate within the frame, obviously. However, I also need a way for the whole kit and caboodle to resize well for different monitors.

*Create this thing in such a way that it loads posts and videos well. In essence, I need it to not be sloppy on every device it encounters. Obviously, I'll ditch the concept for mobile, so just talking desktop.

I also have to do it all in WordPress, specifically using Genesis.
Let me know what you think! jQuery is more than acceptable here if it helps, as is any hair-brained idea you have.
Thanks!
/EDIT #3 -- Solved/
Link to site is:
http://www.blackbirdsfell.com

A: Pressing F11 in most browsers enters full screen mode. This will hide both the task bar and the browser URL bar.
In order to create everything else just use several DIVS. 1 div for the url bar, 3 divs for the centre. 1 being in the center(this the website design) and the other 2 on either side creating the computer effect and the last div below. This would be the task bar. Set all your sizes in percentages and make the width 100%. This will make it easily and quickly fit on all monitor sizes.
HTML

INSERT TOP PART OF THE COMPUTER SCREEN

INSERT LEFT PART OF THE COMPUTER SCREEN"

INSERT WEB DESIGN"

INSERT RIGHT PART OF THE COMPUTER SCREEN"

INSERT BOTTOM PART OF THE COMPUTER SCREEN"

CSS
*{ margin: 0; padding: 0; }
#top_bar{ width:100%; }
#left_bar{ float: left; width: 20%; }
#main{ float: left; width: 60%; }
#right_bar{ float: left; width: 20%; }
#bottom_bar { width: 100%; position:absolute; bottom:0; }

The percentages will not be correct. This will be something that you will have to play around with until it fits correctly.
The position: absolute; and bottom: 0; will force the bottom bar to always stay exactly at the bottom. I presume this will help sell the effect and so added that too.

A: Wanna check this one out?
You can adjust all the frames' width and it can also loads dynamic contents.
One DEMO http://layout.jquery-dev.net/demos/nested_simple.html
SOURCE http://layout.jquery-dev.net/demos.cfm

A: I'd just use an iFrame to show the actual content, and then take the illustration and put it around it on the parent page. You could build "navigation" (back button? and working Page Titles?) into the illustration too, that would be pretty simple and pretty cool.
You'll probably want some JS involved to handle resizing of content (in the iframe) and the illustration will probably need to be split up a bit so parts can be resized properly?


text:
Q: code issue convert time in PHP having issues getting code to work properly and am sure I'm just missing something.
Previously I was using the following code:
 echo "<td>" .date("d-M-Y H:i", strtotime($row['vertrekdatum2'])). "</td>";

And have recently redone my php page template so that I can just use the following format for codes:
<? echo "$row[vertrekdatum2]"?>

However, in my previous page I was formatting the date/time to be something more like:  01-Dec-2013 15:14 in the output.
I have been trying to figure out how I would do this with the above code. I have tried the following, but all give me an errors message:
 Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in
 /home/...../public_html/vluchtgegevens/test.php on line 108

I've tried
     <? echo "date("d-M-Y H:i", strtotime($row[vertrekdatum2]))"?>
<? echo "date("d-M-Y H:i", strtotime($row[vertrekdatum2]));"?>
What am I missing?

A: Use Single quotes ' not double quotes "" inside the date function
Do like this
    <?php echo date('d-M-Y H:i', strtotime($row[vertrekdatum2])); ?>
    <?php echo date('d-M-Y H:i', strtotime($row[vertrekdatum2])); ?>


text:
Q: Entering a number in scientific noation in Android apps I want to be able to use scientific notation in my app for the following statement...
float wc = Float.parseFloat(editText3.getText().toString());

which becomes a prompt for a numeric input.  This works as it is, and I can input 2000 but not 2e3.

A: You can also use:
Double.valueOf("9.18E+09").longValue()

or
BigDecimal bd = new BigDecimal("9.18E+09");
long val = bd.longValue();

A: You will have to look at the string and make the changes yourself.
I suggest something like this:
String str = editText3.getText().toString();
double fValue;
if (str.contains("e")) {
    String[] parts = str.split("e");
    double part1 = Double.parseDouble(parts[0]);
    double part2 = Double.parseDouble(parts[1]);
    fValue = part1 * Math.pow(10, part2);
} else {
    fValue = Double.parseDouble(str);
}

Note that this is not tested, but I think it will work fine.


text:
Q: Draw the graph of $y=e^x \sin x$ (without using a graph calculator) I am having a whole lot of problem with these
graphs.
If I try to sketch the graph taking the function $y=e^x \sin x$ itself,it becomes a bit complex.
I can seperately plot the graphs of $y=\sin x$ & $y=e^x$ by studying their function.(On a common X & Y axis).
But i cannot figure out how to transform these 2 to the given one.

A: For graphs of the form $y=f(x)sinx$, draw the graphs of $y=f(x)$ and $y=-f(x)$. Then draw the graph of $y=sinx$ with the usual roots but with the amplitude increasing or decreasing according to the values of $f$. The graphs should touch whenever $sinx$ reaches its maximum and minimum.

A: Evaluate some points of $f$ for intuition. Note that $f(x\pm \pi k) = 0$. Now look at the first and second derivative for increasing/decreasing and for concavity. The general graph will be of an increasing, unbounded oscillation as $e^x$ is increasing without bound and $\sin x$ oscillates.


text: Q: I need to run some C++ code in javascript I need to run some C++ code in javascript. The code is long and actually kinda heavy, and it's slow in javascript. I'm hoping I'll have better results in C++, because it's faster. I can convert to C++ pretty easily, I just need to know how to run this code. And if it doesn't work, it'll be great knowledge anyway and a good way to spend my time in quarantine.


text:
Q: How to run batch file at startup (Windows 10) I am trying to run a batch file with these contents:
ECHO OFF
TIMEOUT /T 2 /NOBREAK
DisplaySwitch.exe /internal
TIMEOUT /T 2 /NOBREAK
DisplaySwitch.exe /external

I've tried putting a shortcut to it in the startup folder, putting the bat itself in the startup folder, and running it as a task using task scheduler. I also have UAC completely disabled. It runs fine when I run it myself, but it won't run at startup. How can I get to run when I start the computer?

A: I was able to solve this issue by running the task at logon instead of startup.


text:
Q: How to render Razor in cshtml page with Servicestack without content page I have markdown in string property of my model and would like to render it onto page. If I have html in that same string property I would simply do:
@Html.Raw(Model.BodyHtml)

Is there a same thing if string contains Markdown rather than Html? I.e. something like:
@Html.MarkdownToHtml(Model.BodyMarkdown)

A: The new @Html.RenderMarkdownToHtml() API for this has just been added in v4.0.34+ that's now available on MyGet, which will let you render markdown with:
@Html.RenderMarkdownToHtml(Model.BodyMarkdown)

In earlier versions of ServiceStack you would call the Markdown implementation itself to render HTML and use the AsRaw() extension method so the returned HTML isn't automatically encoded, e.g:
@(new MarkdownSharp.Markdown().Transform(Model.BodyMarkdown).AsRaw())


text:
Q: Processing - Zoom on clicked area then click again to zoom back out I have a picture then used a flashlight type of light to only show where the mouse is hovering over. That part of the code works, but now I want to use if/else statements to zoom in on the selected area and then click again to zoom back out. Any other way to zoom in on specific area then back out of that area also helps. Really any help will be appreciated!
PImage ispy;

void setup () {
  size(1024,768);
  ispy = loadImage("ispy2.jpeg");
}

void draw () {
  loadPixels();
  ispy.loadPixels();
  for (int x = 0; x < width; x++) {
    for (int y = 0; y < height; y++) {
      int loc = x+y*width;
      float r = red(ispy.pixels[loc]);
      float g = green(ispy.pixels[loc]);
      float b = blue(ispy.pixels[loc]);
      float d = dist(mouseX, mouseY, x, y); //

      float factor = map(d, 0, 200, 2, 0);
      pixels[loc] = color(r*factor, g*factor, b*factor);
    }
  }
  updatePixels();
}

A: Here is my interpretation of what you are talking about. We store a isClicked boolean to store the state of whether we should zoom in or not. When we are going to draw the image, we translate() to the mouse, then we scale(), then we translate() back the same amount that we moved before, but in the opposite direction. What this does is it does the scale transform around the mouse position.
One thing that I couldn't find a way around way your way of updating the pixels directly from the image and the flashlight effect. What the program is doing instead is using your method to make a mask image and applying that to a PGraphics object. Another thing that I noticed is that when just rendering straight to the screen, there is considerable lag from the scaling. Instead, I have moved the drawing to a PGraphics object. This improves the performance.
In the end, to render, the program is drawing everything on the PGraphics object, then applying the mask to that object to get the flashlight effect.
Here is the code that I have:
PImage ispy, distMask;
boolean isClicked = false;
PGraphics renderer;

void createDistanceMask(PImage distMask){ //Takes image and changes its pixels to "alpha" for the PGraphics renderer
  distMask.loadPixels();
  for (int x = 0; x < width; x++) {
    for (int y = 0; y < height; y++) {
      int loc = x+(height-y-1)*width;
      float d = dist(mouseX, mouseY, x, y); //

      int factor = int(map(d, 0, 200, 400, 0)); //Pixel data will be between 0 and 255, must scale down later.
      if (factor > 255)
          factor = 255;
      distMask.pixels[loc] = color(factor,factor,factor);
    }
  }
  distMask.updatePixels();
}

void setup () {
  size(1024,768, P2D);
  ispy = loadImage("ispy2.jpeg");
  distMask = new PImage(width,height);
  renderer = createGraphics(width,height,P2D);
  mouseX = width/2; //Not necessary, but will have black screen until mouse is moved
  mouseY = height/2;
}

void draw () {
  background(0);
  pushMatrix();

  createDistanceMask(distMask);

  renderer.beginDraw(); //Starts processing stuff into PGraphics object
  renderer.background(0);
  if(isClicked){ //This is to get the zoom effect
      renderer.translate(mouseX, mouseY);
      renderer.scale(2);
      renderer.translate(-mouseX, -mouseY);
  }
  renderer.image(ispy,0,0); //Render Image
  renderer.endDraw();
  renderer.mask(distMask); //Apply Distance mask for flashlight effect
  image(renderer,0,0); //Draw renderer result to screen

  popMatrix();
}

void mouseClicked(){
    isClicked = !isClicked;
}

In my comment, I asked about having the screen move to the mouse, which is what this is doing. If you want to "freeze" the screen in one position, what you can do is store a lastMouseClickPosition PVector or simply just ints. Then, when translating, translate to the position instead of the PVector.
Here's the code that would change:
PVector lastClickPos = new PVector(); //Make the position

if(isClicked){ //When Rendering
      renderer.translate(lastClickPos.x, lastClickPos.y);
      renderer.scale(scalingFactor);
      renderer.translate(-lastClickPos.x, -lastClickPos.y);
  }

void mouseClicked(){ //At the bottom
    isClicked = !isClicked;
    lastClickPos.set(mouseX, mouseY);
}


text:
Q: Shell: replacing file text loop using sed and lines numbers I have two files.
The first file contains, in each line, line number and text. For example:
2   AAAA
4   BBBB
5   nnnn

this text should replace the lines in the second file - according to the first column which is the line number on the second file.
So if initially the second files was:
XXXXX
XXXXX
XXXXX
XXXXX
XXXXX
XXXXX

after the change, it would be
XXXXX
AAAA
XXXXX
BBBB
nnnn
XXXXX

I thought using sed :
sed "$Ns/XXXXX/$A/" file > file-after-change

while $N is the line number (taken from the first file) and $A will be the string from the first file.
How can i read the line number first as variable N and the string itself to a different variable (A)?

A: You can use sed to transform the first file into a sed script, and then pass that to a second sed instance.
sed 's%^\([0-9]*\) *\([^ ]*\)$%\1s/XXXXX/\2/' firstfile |
sed -f - secondfile

Linux sed will happily accept -f -; on some other platforms, maybe experiment with -f /dev/stdin or just save the generated script to a temporary file, and delete it when you are done.

A: Alternatively, consider to use awk.
awk 'FNR==NR { seen[$1]=$2; next } seen[FNR] { print seen[FNR]; next } 1' file1.txt file2.txt

A: This might work for you (GNU sed):
sed 's/\s\+/c/' file1 | sed -f - file2

Turn file1 into a sed script and apply it to file2.
The sed script changes each line in file2 referenced by a line number in file1 to the argument following that line number.

A: Here is a potential solution that edits the "second.txt" file 'in place' and is along the lines of what you've already tried:
cat first.txt
2   AAAA
4   BBBB
5   nnnn

cat second.txt
XXXXX
XXXXX
XXXXX
XXXXX
XXXXX
XXXXX

# GNU sed
while read N A
do
    sed -i "${N}s/XXXXX/${A}/" second.txt
done < first.txt

cat second.txt
XXXXX
AAAA
XXXXX
BBBB
nnnn
XXXXX

(macOS sed: while read N A; do sed -i '' "${N}s/XXXXX/${A}/" second.txt; done < first.txt)

A: Ugly but working (guide is the file with line numbers and substitutions, input is the actual input file):
eval "$(cat guide | sed '/^[0-9]\+ */s!^\([0-9]\+\) *\(.*\)!\1s/.*/\2/!' | sed -z "s/\n/;/g;s/.*/sed '&'/")" < input

(Requires GNU sed, I belive.)


text:
Q: volatile variable and atomic operations on Visual C++ x86 Plain load has acquire semantics on x86, plain store has release semantics, however compiler still can reorder instructions. While fences and locked instructions (locked xchg, locked cmpxchg) prevent both hardware and compiler from reordering, plain loads and stores are still necessary to protect with compiler barriers. Visual C++ provides _ReadWriterBarrier() function, which prevents compiler from reordering, also C++ provides volatile keyword for the same reason. I write all this information just to make sure that I get everything right. So all written above is true, is there any reason to mark as volatile variables which are going to be used in functions protected with _ReadWriteBarrier()?
For example:
int load(int& var)
{
    _ReadWriteBarrier();
    T value = var;
    _ReadWriteBarrier();
    return value;
}

Is it safe to make that variable non-volatile? As far as I understand it is, because function is protected and no reordering could be done by compiler inside. On the other hand Visual C++ provides special behavior for volatile variables (different from the one that standard does), it makes volatile reads and writes atomic loads and stores, but my target is x86 and plain loads and stores are supposed to be atomic on x86 anyway, right?
Thanks in advance.

A: Volatile keyword is available in C too. "volatile" is often used in embedded System, especially when value of the variable may change at any time-without any action being taken by the code - three common scenarios include reading from a memory-mapped peripheral register or global variables either modified by an interrupt service routine or those within a multi-threaded program.
So it is the last scenario where volatile could be considered to be similar to _ReadWriteBarrier.
_ReadWriteBarrier is not a function - _ReadWriteBarrier does not insert any additional instructions, and it does not prevent the CPU from rearranging reads and writes— it only prevents the compiler from rearranging them. _ReadWriteBarrier is to prevent compiler reordering.
MemoryBarrier is to prevent CPU reordering!
A compiler typically rearranges instructions... C++ does not contain built-in support for multithreaded programs so the compiler assumes the code is single-threaded when  reordering the code. With MSVC use _ReadWriteBarrier in the code, so that the compiler will not move reads and writes across it.
Check this link for more detailed discussion on those topics
http://msdn.microsoft.com/en-us/library/ee418650(v=vs.85).aspx
Regarding your code snippet - you do not have to use ReadWriteBarrier as a SYNC primitive - the first call to _ReadWriteBarrier is not necessary.
When using ReadWriteBarrier you do not have to use volatile
You wrote "it makes volatile reads and writes atomic loads and stores" - I don't think that is OK to say that, Atomicity and volatility are different. Atomic operations are considered to be indivisible - ... http://www.yoda.arachsys.com/csharp/threads/volatility.shtml

A: Note: I am not an expert on this topic, some of my statements are  "what I heard on the internet", but I think I csan still clear up some misconceptions.
[edit] In general, I would rely on platform-specifics such as x86 atomic reads and lack of OOOX only in isolated, local optimizations that are guarded by an #ifdef checking the target platform, ideally accompanied by a portable solution in the #else path.
Things to look out for

*

*atomicity of read / write operations

*reordering due to compiler optimizations (this includes a different order seen by another thread due to simple register caching)

*out-of-order execution in the CPU

Possible misconceptions
1. As far as I understand it is, because function is protected and no reordering could be done by compiler inside.
[edit] To clarify: the _ReadWriteBarrier provides protection against instruction reordering, however, you have to look beyond the scope of the function. _ReadWriteBarrier has been fixed in VS 2010 to do that, earlier versions may be broken (depending on the optimizations they actually do).
Optimization isn't limited to functions. There are multiple mechanisms (automatic inlining, link time code generation) that span functions and even compilation units (and can provide much more significant optimizations than small-scoped register caching).
2. Visual C++ [...] makes volatile reads and writes atomic loads and stores,
Where did you find that? MSDN says that beyond the standard, will put memory barriers around reads and writes, no guarantee for atomic reads.
[edit] Note that C#, Java, Delphi etc. have different memory mdoels and may make different guarantees.
3. plain loads and stores are supposed to be atomic on x86 anyway, right?
No, they are not. Unaligned reads are not atomic. They happen to be atomic if they are well-aligned - a fact I'd not rely on unless it's isolated and easily exchanged. Otherwise your "simplificaiton fo x86" becomes a lockdown to that target.
[edit] Unaligned reads happen:
char * c = new char[sizeof(int)+1];
load(*(int *)c);      // allowed by standard to be unaligned
load(*(int *)(c+1));  // unaligned with most allocators

#pragma pack(push,1)
struct
{
   char c;
   int  i;
} foo;
load(foo.i);         // caller said so
#pragma pack(pop)

This is of course all academic if you remember the parameter must be aligned, and you control all code.  I wouldn't write such code anymore, because I've been bitten to often by laziness of the past.
4. Plain load has acquire semantics on x86, plain store has release semantics
No. x86 processors do not use out-of-order execution (or rather, no visible OOOX - I think), but this doesn't stop the optimizer from reordering instructions.
5. _ReadBarrier / _WriteBarrier / _ReadWriteBarrier do all the magic
They don't - they just prevent reordering by the optimizer. MSDN finally made it a big bad warning for VS2010, but the information apparently applies to previous versions as well.

Now, to your question.
I assume the purpose of the snippet is to pass any variable N, and load it  (atomically?) The straightforward choice would be an interlocked read or (on Visual C++ 2005 and later) a volatile read.
Otherwise you'd need a barrier for both compiler and CPU before the read, in VC++ parlor this would be:
int load(int& var)
{
  // force Optimizer to complete all memory writes:
  // (Note that this had issues before VC++ 2010)
   _WriteBarrier();

  // force CPU to settle all pending read/writes, and not to start new ones:
   MemoryBarrier();

   // now, read.
   int value = var;
   return value;
}

Noe that _WriteBarrier has a second warning in MSDN:
*In past versions of the Visual C++ compiler, the _ReadWriteBarrier and _WriteBarrier functions were enforced only locally and did not affect functions up the call tree. These functions are now enforced all the way up the call tree.*

I hope that is correct. stackoverflowers, please correct me if I'm wrong.


text:
Q: Secret API key for accessing Django REST framework My aim is to restrict access to API for client applications by specifying API Key. Various services allow you to access their API by means of secret Key, which you have to get in order to perfom requests.
Note: this is not related to user auth.
Is there any straightforward solution to do this in django rest framework? Or just to pass the key in request header and then manually handle it?
Regards

A: There is a third party app now for this purpose called django-rest-framework-api-key.

A: Use the TokenAuthentication class, as documented here.
You'll also want to setup appropriate permissions, probably using the IsAuthenticated class.
Edit: Apologies - re-reading you post it looks like you want a global secret key, not a per-user one. I'd suggest a custom permission class that checks for the request header and fails if it's not present/not correct.


text:
Q: Block means of a matrix with fixed interval R I'm quite new to R and I have not found a solution for my problem despite intensive searching. What I need to do is to find the block means for the columns of for example, a 200x10 matrix for intervals of 10 rows.
In other words, I would like to have the colum means for row 1:10, 11:20, and so in so that in the end I will have a 20x10 matrix of averages.
Thanks in advance.

A: We can use split and colMeans.  We split the dataset by a grouping vector with gl, then get the column means of the list elements (colMeans) and transpose the output
t(sapply(split(as.data.frame(myMat),
       as.numeric(gl(nrow(myMat), 10, nrow(myMat)))), colMeans))

data
set.seed(24)
myMat <- matrix(rnorm(200*10),nrow=200)

A: There are various ways to solve this, but this is one. Basically you create an additional vector to  define the groupings, and then aggregate on that.
df <- data.frame(a=rnorm(100), b=rnorm(100))
res <- aggregate(df, by=list(rep(1:10,each=10)), mean)

A: Given that you have evenly "blocked" data, here is a solution with rowsum,
rowsum(myMat, rep(1:20, each=10)) / 10

Here, rep(1:20, each=10) provides the grouping variable, with the integers 1 through 20 repeated 10 times each, (like 1 1 1 1 1 ... 2 2 2 2 ... 20 20 20 20).
For the data below, this returns
   [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
1  10.4 11.5 11.1  8.4  9.3 11.5 12.1 10.8  8.6   7.9
2   9.4 12.5 12.4 10.6 10.3 11.8 11.2  8.8  9.0  12.5
3   8.9  8.1  9.0 12.5  7.4 10.3 11.5 13.1 12.2   9.8
4  10.2 11.7 13.2 12.4 12.5 11.0 10.2  8.9 11.3   9.5
         ...
18 10.6 11.1 10.5 10.6 12.3  7.9 12.2  7.6 12.3  14.9
19 10.5  8.0 10.5  8.5 10.5 12.8 12.4 12.0 10.9   9.0
20 15.3 11.3 11.8 11.5 10.7  8.8 11.1  9.8 10.6  11.8

It will work on data.frames as well.
data
set.seed(1234)
myMat <- matrix(sample(1:20, 2000, replace=TRUE), 200)
rowsum(myMat, rep(1:20, each=10)) / 10


text:
Q: Required Field Validator only working in IE - not in chrome or firefox In my asp.net (vb on server side) application I am using a required field validator when a submit button is hit. The validator checks the value of txtLatestEnd - which is a hidden text box. The value of this text box is changed via javascript when the user selects an item on the screen before hitting submit.
I have noticed that the required field validator is only working in IE, but not chrome or firefox. Could anyone see why this is happening?
Required field validator
<asp:RequiredFieldValidator ID="reqLinks" Runat="server" ControlToValidate="txtLatestEnd" Display="Dynamic"
EnableClientScript="true" ErrorMessage="Links are required" CssClass="detailrow" Font-Bold="true"></asp:RequiredFieldValidator>

Edit
If it helps - here is the function on the server side that handles the button click
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
    UpdateDatabase()
End Sub

and here is the button itself.
<asp:Button Runat="server" ID="btnSave" Text="Save Milestone" CssClass="smalltextbutton" CausesValidation="True"></asp:Button>

Both the validator and button are their own table rows in an asp.net table
Edit 2: as requested, here's the code for the "hidden" field - by hidden, it is inside a div that is not displayed

    ---------------Hidden Fields---------------------------------------------------

    Latest end date:<input type="text" ID="txtLatestEnd" Runat="server">

    IDs & Cats<input type="text" style="WIDTH:50%" runat="server" id="IDCATList">

    creator: <input type="text" runat="server" id="hdnCreator">

    county county<input type="text" runat="server" id="hdnLinkCount" value="0">

    preloadDateArray<input type="text" runat="server" id="hdnPreLoadDates">

I have also tried moving the button and validator outside of the table, this does nothing to make the validator work.


text:
Q: Speech Recognizer not working when called normally other than button event like onClick I have in my program Speech Recognizer and when I run the startListening method directly in onCreate method Speech Recognizer doesn't seem working.
But when I place startListening method in button onClick method the Speech Recognizer working. I want Speech Recognizer method startListening directly invoked as shown in below program.
Following is my program.
       SpeechRecognizer mSpeechRecognizer;
Intent mSpeechRecognizerIntent;
TextView textView;
String speakId = "one";
String oldId = "";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_robo);
    textView = (TextView) findViewById(R.id.textView);

    mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);

    mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
            Locale.getDefault());

    mSpeechRecognizer.setRecognitionListener(new RecognitionListener() {
        @Override
        public void onReadyForSpeech(Bundle params) {

        }

        @Override
        public void onBeginningOfSpeech() {

        }

        @Override
        public void onRmsChanged(float rmsdB) {

        }

        @Override
        public void onBufferReceived(byte[] buffer) {

        }

        @Override
        public void onEndOfSpeech() {

        }

        @Override
        public void onError(int error) {

        }

        @Override
        public void onResults(Bundle results) {
            ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
            textView.setText(matches.get(0));

            //displaying the first match
            //if (matches != null)
            //processResult(matches.get(0));
        }

        @Override
        public void onPartialResults(Bundle partialResults) {

        }

        @Override
        public void onEvent(int eventType, Bundle params) {

        }
    });

    /*
        below SpeechRecognizer does not start listening when called in MainActivity.
         */

    mSpeechRecognizer.startListening(mSpeechRecognizerIntent);

}

}
But when i call mSpeechRecognizer.startListening(mSpeechRecognizerIntent) inside the button onClick event the SpeechRecognizer is working.
    public void Listen(View view) {
    mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
}

why when the code is placed in onCreate method and not inside the onClick method is not working.
Please tell a solution for that.

A: I just set used setRecognitionListener right after the createSpeechRecognizer  and the code is working.
    mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
    mSpeechRecognizer.setRecognitionListener(recognitionListener);

    mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
            Locale.getDefault());

and then called
 mSpeechRecognizer.startListening(mSpeechRecognizerIntent);

It works without using a button event.
RecogniserListener class should be declared this way.
    RecognitionListener recognitionListener = new RecognitionListener() {
        @Override
        public void onReadyForSpeech(Bundle params) {

        }

        @Override
        public void onBeginningOfSpeech() {

        }

        @Override
        public void onRmsChanged(float rmsdB) {

        }

        @Override
        public void onBufferReceived(byte[] buffer) {

        }

        @Override
        public void onEndOfSpeech() {

        }

        @Override
        public void onError(int error) {
            String message;
            switch (error) {
                case SpeechRecognizer.ERROR_AUDIO:
                    message = "Audio recording error";
                    break;
                case SpeechRecognizer.ERROR_CLIENT:
                    message = "Client side error";
                    break;
                case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
                    message = "Insufficient permissions";
                    break;
                case SpeechRecognizer.ERROR_NETWORK:
                    message = "Network error";
                    break;
                case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
                    message = "Network timeout";
                    break;
                case SpeechRecognizer.ERROR_NO_MATCH:
                    message = "No match";
                    break;
                case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
                    message = "RecognitionService busy";
                    break;
                case SpeechRecognizer.ERROR_SERVER:
                    message = "error from server";
                    break;
                case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
                    message = "No speech input";
                    break;
                default:
                    message = "Didn't understand, please try again.";
                    break;
            }
            textView.setText(message);
        }

        @Override
        public void onResults(Bundle results) {
            ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
            textView.setText(matches.get(0));

            //displaying the first match
            //if (matches != null)
                //processResult(matches.get(0));
        }

        @Override
        public void onPartialResults(Bundle partialResults) {

        }

        @Override
        public void onEvent(int eventType, Bundle params) {

        }

};


text:
Q: SQL query with SUBSTRING and CONTAINS I have following table
ID | Name | Url

Each Url contains address to file fe: "http://blah.blah.com/abcde.bin". Address is always same but file name. In need SQL query to update all cells in this column, where Url contains http and store only file name.
Example:
SELECT URL FROM TABLE

1 | "http://blah.blah.com/abcde.bin"

UPDATE ...

SELECT URL FROM TABLE

1 | "abcde.bin"

A: Try this query:
UPDATE TABLE SET URL = REPLACE(URL ,'http://blah.blah.com/','')

it doesn't use contain or substring, but does the same, with less code.  If it finds the 'http://blah.blah.com/' string, it will be replaced with an empty string, so you will have just your name.
I didn't try it but I think it's correct.
Hope it helps you.

A: If your adress is same except file name then you can do like :
UPDATE TABLE SET URL = REPLACE(URL ,'http://blah.blah.com/','')


text:
Q: How to make the width of select2 show full? How to make the width of select2 show full?

  {{ __('Pages') }}
  <select name="item[{{ $reasonItem['id'] }}][page]" class="form-control col-sm-10 select2" required>
    <option value="">{{ __('Choose') }}</option>
      @foreach($pages as $key=>$val)
        <option value="{{ $key }}" {{ (($key == ($reasonItem['page'] ?? '') ) ? "selected":"") }}>{{$val}}</option>
      @endforeach
  </select>

A: You can try this:
<select name="item[{{ $reasonItem['id'] }}][page]" class="form-control col-sm-10 select2" style="width:100%" required>

It will be work, I checked.

A: Try with:
.select2.select2-container {
    width: 100% !important;
}

A: Add w-auto class or w-100 if Bootstrap 5
class="form-control col-sm-10 select2 w-auto"


text:
Q: Unable to update EclipseLink with M2Eclipse I am using Eclipse with Maven (using m2eclipse) and attempting to add the EclipseLink repository.
Within my pom.xml I have set the following:
<repositories>
  <repository>
    <id>eclipselink</id>
    <url>http://www.eclipse.org/downloads/download.phpr=1&nf=1&file=/rt/eclipselink/maven.repo</url>
  </repository>
</repositories>

I then navigate to the Maven Repository Window and right click the repository and select Full Index Enabled.
This results in the following message being displayed:
4/23/11 1:45:53 PM BST: Updating index eclipselink|http://www.eclipse.org/downloads/download.php?r=1&nf=1&file=/rt/eclipselink/maven.repo
4/23/11 1:45:54 PM BST: Unable to update index for eclipselink|http://www.eclipse.org/downloads/download.php?r=1&nf=1&file=/rt/eclipselink/maven.repo

Any help in solving this problem would be appreciated.

A: If you call that page you will get an 404 page not found...so the url must be wrong.

A: There may not be anything to worry.  It is possible that Eclipselink repository is not having a repository index file which is requested by m2eclipse.
What is important is to check if dependencies specified in your pom, present in Eclipselink repository are getting downloaded correctly.

A: You have a typo in URL:
It should be:
http://www.eclipse.org/downloads/download.php?r=1&nf=1&file=/rt/eclipselink/maven.repo
You missed question mark.
Source:
Can't find the "org.eclipse.persistence" Maven dependency


text:
Q: How to import `snakebite` package in Python 3? I'm trying to connect to Hadoop (HDFS) using Python. I'm using snakebite package for establishing connection. I installed it successfully, but when I'm trying to import it, it gives error as follows:
from snakebite.client import Client
client = Client('localhost', 9000)

Error:

File "C:\pythonNJ\lib\site-packages\snakebite\client.py", line 1473
  baseTime = min(time * (1L << retries), cap);

Is there a way to solve it or can someone please tell me how to establish connection by another way?

A: From its README:

Snakebite requires python2 (python3 is not supported yet)

A: A Python 3 fork has been created since then, snakebite-py3.
pip install snakebite-py3


text:
Q: Choosing n marbles from a mixed set of distinguishable and indistinguishable $$
\begin{array} { l } { \text { In how many ways can one pick } n \text { marbles from } 3 n \text { marbles consisting of } n \text { indistinguishable } } \\ { \text { white marbles, } n \text { indistinguishable black marbles and } n \text { distinguishable coloured marbles. } } \\ { \text { Your solution should contain a precise explanation of your reasoning. } } \end{array}
$$
I have tried to attempt this from working from the number of ways if they were all distinguishable and then minus-ing any repeats, but I am quite stuck.

A: To count the number of ways to pick $n$ marbles from the $3n$, we take cases on how many colored marbles are to be chosen.  If your set of $n$ marbles is to include exactly $k$ colored marbles, there are $\binom{n}{k}$ ways to pick which colored marbles are included.  Here, $k$ will range from $0$ to $n$.  No matter the value of $k$, there are always at least $n-k$ white marbles available and at least $n-k$ black marbles available, because there are $n$ marbles of each type. Thus, by stars and bars, there are $n-k+1$ ways to choose how many white marbles are to be included in your chosen group of marbles.  Overall, there are $(n-k+1)\binom{n}{k}$ choices of $n$ marbles such that $k$ are colored.
Summing over $k$ we see that the total number of choices is given by
$$
\begin{split}
\sum_{k=0}^n (n-k+1)\binom{n}{k} &= (n+1) \sum_{k=0}^n \binom{n}{k} - \sum_{k=0}^n \left( \frac{k \cdot n!}{k!(n-k)!} \right) \\
&= (n+1)2^n - n \sum_{k=0}^n \left( \frac{(n-1)!}{(k-1)!((n-1) - (k-1))!} \right) \\
& = (n+1)2^n - n \sum_{\ell = 0}^{n-1} \binom{n-1}{\ell} = (n+1)2^n - n2^{n-1} \\
&= 2^n + n2^{n-1}.
\end{split}
$$


text:
Q: IPEGA bluetooth gamepad stops sending events after a few seconds I have an IPEGA PG-9025 bluetooth controller and I'm able to connect it to my Ubuntu 15.04 without problems.
It's added as a joystick (js) with all correct data and receiving input, but it stops sending events in a few seconds after connected. It's still listed, but it won't change input states as I press buttons.
I also remember using this controller model successfully using this same notebook, but it was on an earlier Ubuntu version. (13.XX?)
Can someone help me figure why is this happening?
Kernel
4.0.0-040000-generic
Xorg log
[  4011.670] (II) config/udev: Adding input device ipega media gamepad controller (/dev/input/mouse2)
[  4011.670] (II) No input driver specified, ignoring this device.
[  4011.670] (II) This device may have been added with another device file.
[  4011.673] (II) config/udev: Adding input device ipega media gamepad controller (/dev/input/js0)
[  4011.673] (II) No input driver specified, ignoring this device.
[  4011.673] (II) This device may have been added with another device file.
[  4011.721] (II) config/udev: Adding input device ipega media gamepad controller (/dev/input/event15)
[  4011.721] (**) ipega media gamepad controller: Applying InputClass "evdev pointer catchall"
[  4011.721] (**) ipega media gamepad controller: Applying InputClass "evdev keyboard catchall"
[  4011.721] (II) Using input driver 'evdev' for 'ipega media gamepad controller'
[  4011.721] (**) ipega media gamepad controller: always reports core events
[  4011.721] (**) evdev: ipega media gamepad controller: Device: "/dev/input/event15"
[  4011.721] (--) evdev: ipega media gamepad controller: Vendor 0x1949 Product 0x402
[  4011.721] (--) evdev: ipega media gamepad controller: Found 3 mouse buttons
[  4011.721] (--) evdev: ipega media gamepad controller: Found scroll wheel(s)
[  4011.721] (--) evdev: ipega media gamepad controller: Found relative axes
[  4011.721] (--) evdev: ipega media gamepad controller: Found x and y relative axes
[  4011.721] (--) evdev: ipega media gamepad controller: Found absolute axes
[  4011.721] (--) evdev: ipega media gamepad controller: Found x and y absolute axes
[  4011.721] (--) evdev: ipega media gamepad controller: Found keys
[  4011.721] (II) evdev: ipega media gamepad controller: Configuring as mouse
[  4011.721] (II) evdev: ipega media gamepad controller: Configuring as keyboard
[  4011.721] (II) evdev: ipega media gamepad controller: Adding scrollwheel support
[  4011.721] (**) evdev: ipega media gamepad controller: YAxisMapping: buttons 4 and 5
[  4011.721] (**) evdev: ipega media gamepad controller: EmulateWheelButton: 4, EmulateWheelInertia: 10, EmulateWheelTimeout: 200
[  4011.721] (**) Option "config_info" "udev:/sys/devices/pci0000:00/0000:00:14.0/usb1/1-7/1-7:1.0/bluetooth/hci0/hci0:256/0005:1949:0402.0008/input/input22/event15"
[  4011.721] (II) XINPUT: Adding extended input device "ipega media gamepad controller" (type: KEYBOARD, id 16)
[  4011.721] (**) Option "xkb_rules" "evdev"
[  4011.721] (**) Option "xkb_model" "pc105"
[  4011.721] (**) Option "xkb_layout" "br"
[  4011.721] (II) evdev: ipega media gamepad controller: initialized for relative axes.
[  4011.721] (WW) evdev: ipega media gamepad controller: ignoring absolute axes.
[  4011.722] (**) ipega media gamepad controller: (accel) keeping acceleration scheme 1
[  4011.722] (**) ipega media gamepad controller: (accel) acceleration profile 0
[  4011.722] (**) ipega media gamepad controller: (accel) acceleration factor: 2.000
[  4011.722] (**) ipega media gamepad controller: (accel) acceleration threshold: 4
[  4026.788] (II) config/udev: removing device ipega media gamepad controller
[  4026.816] (II) evdev: ipega media gamepad controller: Close
[  4026.816] (II) UnloadModule: "evdev"

A: All above I did only using the program Blueman to connect the controller. After I used BlueDevil from Kde, it suddenly works!
It's connected as a Joystick(js), so I have to use xboxdrv for it to work on most games and emulators, as seen here: Using IPEGA bluetooth gamepad with Steam @ Linux


text:
Q: How to import svg saved as js file in react the js file like
import React from "react";

export default () => (
  <svg
    className="xxx"
    data-testid="ggg"
    width="20"
    height="20"
    viewBox="0 0 20 20"
    fill="none"
    xmlns="http://www.w3.org/2000/svg"
  >
    <path
      d="xxxx"        />
  </svg>
);

how to import this and used in other components?

A: Its a normal component:
import MySvg from 'path/to/svg'

<MySvg />

A: You should name your component like
import React from "react";

export class SvgIcon extends React.Component {
  render() {
    return (
  <svg
    className="xxx"
    data-testid="ggg"
    width="20"
    height="20"
    viewBox="0 0 20 20"
    fill="none"
    xmlns="http://www.w3.org/2000/svg"
  >
    <path d="xxxx"/>
  </svg>
    )
  }
}

And now you can use it:
<SvgIcon/>

Don't forget import component
import SvgIcon from "*component path*";


text:
Q: cordova splash screen is not shown I am learning phonegap and cordova now
I want to run the splash screen, but is is not working
This is my config.xml
<?xml version='1.0' encoding='utf-8'?>

<preference name="SplashScreen" value="screen" />
<preference name="SplashScreenDelay" value="3000" />

<name>Test</name>
<description>Hello World App. to learn phonegap :)</description>
<author email="a.elsayed2010@gmail.com">Amira Elsayed Ismail</author>
<content src="index.html" />
<access origin="*" />

<platform name="android">
    <icon src="res/android/icon.png" density="ldpi" />
    <icon src="res/android/icon.png" density="mdpi" />
    <icon src="res/android/icon.png" density="hdpi" />
    <icon src="res/android/icon.png" density="xhdpi" />

    <splash src="res/screen/android/screen.png" density="land-hdpi"/>
    <splash src="res/screen/android/screen.png" density="land-ldpi"/>
    <splash src="res/screen/android/screen.png" density="land-mdpi"/>
    <splash src="res/screen/android/screen.png" density="land-xhdpi"/>

    <splash src="res/screen/android/screen.png" density="port-hdpi"/>
    <splash src="res/screen/android/screen.png" density="port-ldpi"/>
    <splash src="res/screen/android/screen.png" density="port-mdpi"/>
    <splash src="res/screen/android/screen.png" density="port-xhdpi"/>

 </platform>

My MainActivity Code
   public class MainActivity extends CordovaActivity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        super.init();
        loadUrl(launchUrl);

    }
}

I have already installed the splash screen plugin using the following cmd
cordova plugin add org.apache.cordova.splashscreen

can any one tell me what is the problem here ?

A: config.xml is in cordova folder, this will not work unless you have res folder in the same directory, that is not a good place to store these images. Normally they are stores under the src directory.
Try to use a relative address and check that folder is correct, using different image resolutions (you are incorrectly using the same image resolution):
For example:
<splash density="port-ldpi" src="../src/www/res/screens/android/screen-ldpi-portrait.png"/>
<splash density="port-mdpi" src="../src/www/res/screens/android/screen-mdpi-portrait.png"/>
<splash density="port-hdpi" src="../src/www/res/screens/android/screen-hdpi-portrait.png"/>
<splash density="port-xhdpi" src="../src/www/res/screens/android/screen-xhdpi-portrait.png"/>
<splash density="land-ldpi" src="../src/www/res/screens/android/screen-ldpi-landscape.png"/>
<splash density="land-mdpi" src="../src/www/res/screens/android/screen-mdpi-landscape.png"/>
<splash density="land-hdpi" src="../src/www/res/screens/android/screen-hdpi-landscape.png"/>
<splash density="land-xhdpi" src="../src/www/res/screens/android/screen-xhdpi-landscape.png"/>


text:
Q: 0-1 Integer Knapsack returning wrong answer (Dynamic Programming) The title is pretty self-explanatory, I've been fiddling it for a couple of days now. What is the stupid thing that I'm doing wrong? The problem is for a bunch of materials that are the same weight and thus doesn't have an input vector for values, so it might be the fact that I'm not adding a value in the std::max part, but I've tried doing that and haven't gotten the right answer either. W is the capacity of the knapsack, w is a vector consisting of the weights of the items.
#include <iostream>
#include <vector>

using std::vector;
using std::max;

int optimal_weight(int W, const vector<int> &w) {
     size_t size = w.size();
     int knapsack[size+1][W+1];

     for (size_t a = 0; a <= size; a++) {
         knapsack[a][0] = 0;
     }

     for (int b = 0; b <= W; b++) {
         knapsack[0][b] = 0;
     }

     for (size_t i = 1; i <= size; i++) {
          for (int j = 0; j <= W; j++) {
                   knapsack[i][j] = knapsack[i-1][j];

                   if (w[i-1] <= j) {
                          knapsack[i][j] = std::max(knapsack[i-1][j-w[i-1]], knapsack[i-1][j]);
                    }

                }
         }
      return knapsack[size][W];
    }

A: The line in the code : int knapsack[size][W+1]
should be changed to : int knapsack[size+1][W+1]
It is because arrays are indexed from 0, and in the above case defined  for 0 to size-1 and you are accessing the element at index = size.
Also add the corresponding weights while calculating std::max.


text:
Q: How to set Xcode as core.editor in git? My current git config core.editor returns dreamweaver which I set up two years ago from inside the app(IIRC), and now I don't use it. I am receiving error while amending the author of the last commit.
~$ git commit --amend --author="me <my@mail>"
hint: Waiting for your editor to close the file... fatal: cannot run
dreamweaver: No such file or directory
error: unable to start editor 'dreamweaver'

How do I set it to use Xcode? I tried
git config --global core.editor="xcode"
error: invalid key: core.editor=Xcode

And from https://stackoverflow.com/questions/53550025/git-unable-to-start-xcode-from-terminal-on-mac-os-x, even though xed launches Xcode.
$ git config --global core.editor="xed"
error: invalid key: core.editor=xed

xed -w also launches Xcode so I tried the same instead of ="xed -w" but same error.

A: It's all about syntax sometimes :-)
git config --global core.editor 'xed -w'

Not sure whether you really want to wait for Xcode to launch each time you git commit something. Maybe vi or nano are the better options here.

A: I would never want to do what you want, I think it's a horrible idea, but I tried to, and I succeeded!
What did I do? Easy:

*

*Open Xcode and remove the splash window from the boot (in case it could create some mayhem).

*Find Xcode: well, it's hard to explain how, but I found it at /Applications/Xcode.app/Contents/MacOS/Xcode.

*Repeat your mistake:
$ git config core.editor=/Applications/Xcode.app/Contents/MacOS/Xcode
error: invalid key: core.editor=/Applications/Xcode.app/Contents/MacOS/Xcode
$ _

*Make it right:
$ git config core.editor /Applications/Xcode.app/Contents/MacOS/Xcode
$ echo $?
0
$ _

*Cloned a repo, made a silly change, added it to the index.

*git commit, tada!

If you have any issues repeating this, go back to step 4.


text:
Q: jquery slider not working in IE , works in chrome, firefox i got a problem with a slider, its not working in internet explorer, i tested in IE 7 and 8 and i cant see it, please help
this is my code

A: This is the error I found in IE7:
imgWrap.animate({
    top: '0px',
    left: '135px',
    width: '700px',
    height: '400px', //<--- Remove the comma
}, sotiData.speedImg, function(){
    imgWrap.attr('onclick',  "sotBigImageHide('" + topW2 + "', '" + leftW2 + "')");
});

Please let me know if it solved your problem.


text:
Q: How to run phonegap app in iphone simulator? I'm new in Xcode. I'm having Xcode 4.6 and Mac OS 10.7. I have setup the phonegap environment to my Xcode and can create my phonegap app successfully.
My problem is, when I start to run my app into simulator it's showing the following error:

Developer Tools Access needs to take control of another process for debugging to continue. Type the name and password of a user in the "Developer Tools" group to allow this.

and also showing the username & password textbox.
I have tried to give apple develoer credential and also system credential but not getting any solution.


text:
Q: Qt5.5 XML processing using QDom I'm using the QDom classes to process an XML file, I want the attributes to be processed in the order they are defined in the XML file, this is important.  However it seems the order of the attributes in the 'QDomNamedNodeMap' is different.
Is there any way to ensure the order is as defined in the XML file?

A: As far as I know, you can't rely on order of attributes in XML, by specifications. This could be the reason your library read them in a different order that the literal one. Even if you find a way, you should not trust it: what about if someone else generates the XML to feed your program? See here more about the specifications.
Maybe a change in the design can help you: what about nesting some nodes? Nesting nodes sequence is deterministic.

A: I've written my own classes that read the file and process the nodes and attributes, as per my requirement the attributes are kept in the same order they are presented in the file.


text:
Q: c# inline switch in format string I would like to format phrase and make endings according to number of items.
string s = string.Format("There are {0} items, bla bla {1}",
 itemsCnt,
 () => {switch(itemsCnt)
 {
    case 0:
      return "make some...";
    case 1:
    case 2:
      return "try more";
    default:
      return "enough";
 }}
);

The syntax is not right, I believe the anonymous method should work here somehow...
Update:
I could use separate formating function. I would like to use the function in Razor and I would like to see to formating logic in one place. And furthermore I was curious how to do it :-)

A: Why use a anonymous method here?
A regular would do just as fine:
private string Translate(int itemsCnt)
{
 switch(itemsCnt)
 {
    case 0:
      return "make some...";
    case 1:
    case 2:
      return "try more";
    default:
      return "enough";
 }
}

then the result is:
string s = string.Format("There are {0} items, bla bla {1}",
                         itemsCnt,
                         Translate(itemsCnt));

The string.Format(...) has no overload that take a function

A: The code creates a Func delegate and executes it:
string s = string.Format("There are {0} items, bla bla {1}",
            itemsCnt,
            new Func<string>(() =>
            {
                switch (itemsCnt)
                {
                    case 0:
                        return "make some...";
                    case 1:
                    case 2:
                        return "try more";
                    default:
                        return "enough";
                }
            })()
            );


text:
Q: Button from mainActivity opens a fragment in a second activity i want to push a button in my mainactivity that will start an intent for a new activity with a fragment.
I wrote a main_activity.xml with the button for the MainActivity and a second_activity.xml with a fragment. When I click on the button the second Activity will crash because of the fragment in the xml.
I already added a flag but it does not help.
The idea of the app is to get a googlemap in this second activity by pushing a button in the main activity.
I hope you can help me :/
MainActivity:
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {

    private Button mButton;

    private static final String TAG = Thread.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "+++++ onCreate() +++++");
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        mButton = (Button) findViewById(R.id.mapButton);
        mButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.d(TAG, "+++++ onClick() +++++");
                // TODO Auto-generated method stub
                Intent intent = new Intent(MainActivity.this, SubMain.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });

    }

    protected void onStart() {
        Log.d(TAG, "+++++ onStart() +++++");
        super.onStart();

    }

    protected void onPause() {
        Log.d(TAG, "+++++ onPause() +++++");
        super.onPause();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
    }
}

SubActivity:
public class SubMain extends MainActivity {

    private static final String TAG = SubMain.class.getSimpleName();

    protected void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "+++++ onCreate().SubMain +++++");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.submain);
    }

}

activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
         />

    <Button
        android:id="@+id/mapButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/textView1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:text="Map" />

</RelativeLayout>

submain.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <fragment
        android:id="@+id/fragment1"
        android:name="com.google.android.gms.maps.MapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

LogCat:
11-13 14:48:24.395: D/Thread(30503): +++++ onCreate() +++++
11-13 14:48:24.465: D/Thread(30503): +++++ onStart() +++++
11-13 14:48:24.475: D/Thread(30503): +++++ run() +++++
11-13 14:48:24.480: D/Thread(30503): Thread is running
11-13 14:48:24.980: D/Thread(30503): Thread is running
11-13 14:48:25.485: D/Thread(30503): Thread is running
11-13 14:48:25.985: D/Thread(30503): Thread is running
11-13 14:48:26.485: D/Thread(30503): Thread is running
11-13 14:48:26.985: D/Thread(30503): Thread is running
11-13 14:48:27.240: D/Thread(30503): +++++ onClick() +++++
11-13 14:48:27.270: D/Thread(30503): +++++ onPause() +++++
11-13 14:48:27.305: D/SubMain(30503): +++++ onCreate().SubMain +++++
11-13 14:48:27.305: D/Thread(30503): +++++ onCreate() +++++
11-13 14:48:27.320: D/AndroidRuntime(30503): Shutting down VM
11-13 14:48:27.320: W/dalvikvm(30503): threadid=1: thread exiting with uncaught exception (group=0x41da92a0)
11-13 14:48:27.345: E/AndroidRuntime(30503): FATAL EXCEPTION: main
11-13 14:48:27.345: E/AndroidRuntime(30503): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.thread/com.example.thread.SubMain}: android.view.InflateException: Binary XML file line #7: Error inflating class fragment
11-13 14:48:27.345: E/AndroidRuntime(30503):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
11-13 14:48:27.345: E/AndroidRuntime(30503):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
11-13 14:48:27.345: E/AndroidRuntime(30503):    at android.app.ActivityThread.access$600(ActivityThread.java:140)
11-13 14:48:27.345: E/AndroidRuntime(30503):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
11-13 14:48:27.345: E/AndroidRuntime(30503):    at android.os.Handler.dispatchMessage(Handler.java:99)
11-13 14:48:27.345: E/AndroidRuntime(30503):    at android.os.Looper.loop(Looper.java:137)
11-13 14:48:27.345: E/AndroidRuntime(30503):    at android.app.ActivityThread.main(ActivityThread.java:4898)
11-13 14:48:27.345: E/AndroidRuntime(30503):    at java.lang.reflect.Method.invokeNative(Native Method)
11-13 14:48:27.345: E/AndroidRuntime(30503):    at java.lang.reflect.Method.invoke(Method.java:511)
11-13 14:48:27.345: E/AndroidRuntime(30503):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
11-13 14:48:27.345: E/AndroidRuntime(30503):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
11-13 14:48:27.345: E/AndroidRuntime(30503):    at dalvik.system.NativeStart.main(Native Method)
11-13 14:48:27.345: E/AndroidRuntime(30503): Caused by: android.view.InflateException: Binary XML file line #7: Error inflating class fragment
11-13 14:48:27.345: E/AndroidRuntime(30503):    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
11-13 14:48:27.345: E/AndroidRuntime(30503):    at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
11-13 14:48:27.345: E/AndroidRuntime(30503):    at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
11-13 14:48:27.345: E/AndroidRuntime(30503):    at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
11-13 14:48:27.345: E/AndroidRuntime(30503):    at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
11-13 14:48:27.345: E/AndroidRuntime(30503):    at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:308)
11-13 14:48:27.345: E/AndroidRuntime(30503):    at android.app.Activity.setContentView(Activity.java:1924)
11-13 14:48:27.345: E/AndroidRuntime(30503):    at com.example.thread.SubMain.onCreate(SubMain.java:13)
11-13 14:48:27.345: E/AndroidRuntime(30503):    at android.app.Activity.performCreate(Activity.java:5206)

A: problem solved:
I got the wrong line for the meta-data in the android manifest... a realy stupid mistake. >.<
Bevor:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.thread"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.thread.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.example.thread.SubMain"
            android:label="@string/app_name" >
            <meta-data
                android:name="com.google.android.maps.v2.API_KEY"
                android:value="AIzaSyCpP0eOduM6JF6w8i7xybZgIiZopG4tOVI" /> <!-- wrong line! -->
        </activity>
    </application>

</manifest>

After:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.thread"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.thread.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.example.thread.SubMain"
            android:label="@string/app_name" >
        </activity>

        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="MY_GOOGLE_API_KEY" />
    </application>

</manifest>