text:
Q: How to completely remove node.js from Windows I uninstalled my previous version of node.js (0.8.11) and downloaded the latest, 0.10.24 from the node.js website and installed it. However, after running node --version, it still indicates that I'm running v0.8.11. Obviously, some stuff was left behind during the uninstall process, and it's causing me to have all sorts of errors when trying to add modules through npm. I've seen solutions to this for OSX and Linux, but couldn't find anything for Windows. I'm running Windows 7 64-bit.

A: Scenario:  Removing NodeJS when Windows has no Program Entry for your Node installation
I ran into a problem where my version of NodeJS (0.10.26) could NOT be uninstalled nor removed, because Programs & Features in Windows 7 (aka Add/Remove Programs) had no record of my having installed NodeJS... so there was no option to remove it short of manually deleting registry keys and files.
Command to verify your NodeJS version: node --version
I attempted to install the newest recommended version of NodeJS, but it failed at the end of the installation process and rolled back.  Multiple versions of NodeJS also failed, and the installer likewise rolled them back as well.  I could not upgrade NodeJS from the command line as I did not have SUDO installed.
SOLUTION: After spending several hours troubleshooting the problem, including upgrading NPM, I decided to reinstall the EXACT version of NodeJS on my system, over the top of the existing installation.
That solution worked, and it reinstalled NodeJS without any errors.  Better yet, it also added an official entry in Add/Remove Programs dialogue.
Now that Windows was aware of the forgotten NodeJS installation, I was able to uninstall my existing version of NodeJS completely.  I then successfully installed the newest recommended release of NodeJS for the Windows platform (version 4.4.5 as of this writing) without a roll-back initiating.
It took me a while to reach sucess, so I am posting this in case it helps anyone else with a similar issue.

A: In my case, the above alone didn't work.  I had installed and uninstalled several versions of nodejs to fix this error: npm in windows Error: EISDIR, read at Error (native)  that I kept getting on any npm command I tried to run, including getting the npm version with:  npm -v.
So the npm directory was deleted in the nodejs folder and the latest npm version was copied over from the npm dist: and then everything started working.

A: Whatever Node.js version you have installed, run its installer again. It asks you to remove Node.js like this:

A: I came here because the Remove button was not available from Add/Remove programs. It was saying "Node.js cannot be removed".
This worked:

*

*Got the .msi of my installed Node version. Ran it to repair the installation just in case.

*Opened the Administrator command prompt and ran msiexec /uninstall <node.msi>.

A: I had the same problem with me yesterday and my solution is:
1. uninstall from controlpanel not from your cli
2. download and install the latest or desired version of node from its website
3. if by mistake you tried uninstalling through cli (it will not remove completely most often) then you do not get uninstall option in cpanel in this case install the same version of node and then follow my 1. step
Hope it helps someone.

A: I actually had a failure in the Microsoft uninstall. I had installed node-v8.2.1-x64 and needed to run version node-v6.11.1-x64.
The uninstalled was failing with the error:

Windows cannot access the specified device, path, or file

or similar.
I ended up going to the Downloads folder right-clicking the node-v8.2.1-x64 MSI and selecting uninstall.. this worked.

A: How to remove Node.js from Windows:

*Take a deep breath.

*Run npm cache clean --force

*Uninstall from Programs & Features with the uninstaller.

*Reboot (or you probably can get away with killing all node-related processes from Task Manager).

*Look for these folders and remove them (and their contents) if any still exist. Depending on the version you installed, UAC settings, and CPU architecture, these may or may not exist:

*

*C:\Program Files (x86)\Nodejs

*C:\Program Files\Nodejs

*C:\Users\{User}\AppData\Roaming\npm (or %appdata%\npm)

*C:\Users\{User}\AppData\Roaming\npm-cache (or %appdata%\npm-cache)

*C:\Users\{User}\.npmrc (and possibly check for that without the . prefix too)

*C:\Users\{User}\AppData\Local\Temp\npm-*

*Check your %PATH% environment variable to ensure no references to Nodejs or npm exist.

*If it's still not uninstalled, type where node at the command prompt and you'll see where it resides -- delete that (and probably the parent directory) too.

*Reboot, for good measure.

A:
How to completely remove node.js from Windows

I also ran into this issue.
Solution
I uninstalled NVM for Windows 1.1.7. During the uninstallation, it said it would uninstall all versions of Node.js and npm. Both are now gone :-)

A: The best thing to do is to remove Node.js from the control panel. Once deleted download the desired version of Node.js and install it and it works.


text:
Q: Close single tab of IExplore in C# I am stuck in a problem, i.e. How to close a single particular tab in Internet Explorer.
I can use ShDocvW.dll to solve this problem, but I am just wondering is there any other alternate solution for this problem, I have to do this in OpenSpan Technology based on .net and there I am unable to add the reference of ShDocvW.dll in my project it is throwing an error message as- "Invalid Project reference file".
Thanks In-Advance !!!

A: have you tried "Microsoft internet Controls" from the COM tab. See reference link below.
Cannot add "C:\Windows\System32\shdocvw.dll" to my project

redpajama_set_name: RedPajamaStackExchange


text:
Q: Save facebook profile picture in my own server using Rails I am working in an rails application in which there are a option to signup user using his facebook account.
Now I am using OmniAuth gem to authenticate user from facebook. And saving/uploading user's profile photo using carrierwave.
But I can not upload and save users profile photo in my server, when I getting the user's profile photo link using OmniAuth.
I want not use remote link for profile photo, as any time it will be changed from facebook or my user will want to change his profile photo in my website.
Please help me that how I save in my server the user's profile photo from this facebook link?

A: I use carrierwave to accomplish that:

*

*Add this to your Gemfile, then '$ bundle install'
#for image processing/uploading
gem 'carrierwave'
gem 'mini_magick'

*Generate a new uploader for the image files '$ rails g uploader Image', you can config this one as you like; I configured mine to store a thumbnail version in addition to the original, like so:
 #You need ImageMagick library to use this
 include CarrierWave::MiniMagick

 #This stores a thumbnail version and the original
 #You need ImageMagick
 version :thumb do
    process resize_to_fit: [50, 50]
 end

 #this validates file extensions
 def extension_whitelist
    %w(jpg jpeg gif png)
 end

*I used a separate model to store images in my db, but you can also store the image reference directly to the user model, either way, you just need to add a column with data type string to the model where you want to store the image reference. Something like '$ rails g migration AddImageToUserTable image:string' once you have it, add this to that model file:
  #this tells Carrierwave to use the image attribute in the
  #model to store the file reference
  mount_uploader :image, ImageUploader

*Finally (if you stored the reference in your user model) you can have something like this inside your user model file where you store the facebook responce:
def self.create_from_provider_data(provider_data)
  where(provider: provider_data.provider, uid: provider_data.uid).first_or_initialize do |user|
    user.remote_picture_url = provider_data.info.image
    user.username = provider_data.info.name
    user.email = provider_data.info.email
    user.password = Devise.friendly_token[0, 20]
    user.oauth_token = provider_data.credentials.token
    user.oauth_expires_at = provider_data.credentials.expires_at
    user.save!
  end
end

I was 6 years late xD, but hope this helps someone. :)


text:
Q: Passing a string param to a RESTful service during POST action I am having a RESTful service with the following method:
[WebInvoke]
string GetDataFromStringAsString(string xmlString);

My client call to the method is as below:
var client = new RestClient();
client.BaseUrl = serviceBaseUrl;
var request = new RestRequest(method){RequestFormat = DataFormat.Xml};
request.Resource = resourceUrl;
request.AddParameter("text/xml", requestBody,
ParameterType.RequestBody);
var response = client.Execute(request);

Let us take a string to post as "Hello World".
Now the string that i post to the above method gives me a 400 Bad
request. In order to get it working i had to wrap the above string in
a  element as shown below:
<string xmlns="http://schemas.microsoft.com/2003/10/
Serialization/">Hello World</string>

Now when i post the above string i get a success response back from
the server.
Why is that i have to manually wrap the string to make it work. Is
there a way that i can achieve to post a string without doing the
above manually.

A: The only other way that I am aware of is to use stream as your input parameter. e.g.
[WebInvoke]
string GetDataFromStringAsString(stream xmlString);

The problem with .Net 4 WCF REST is that fundamentally WCF only knows how to pass two types of info, either XML or a stream of bytes.  Personally, I would use WCF Web API instead of the standard WCF REST library because you are going run into lots more of these kinds of issues.


text:
Q: Does C# object removes from memory when inaccessible static void Main(string[] args)
{
    foo f1 = new foo();
    string s1 = f1.fooMethod();

    string s2 = (new foo()).fooMethod();

    // Does anonymous object destroys here?
    // some more code....
    //....
    //....
    //....
    //....
    // f1 is accessible here also
    // some more code....
    //....
    //....
    //....
    //....
    // f1 is accessible here also
}

class foo
{
    public string fooMethod()
    {
        return "fooMethod called";
    }
}

in above code I have created an anonymous object using (new foo()) syntax (I suppose this is what these objects are called) and one f1 object.
Now f1 is accessible in whole code block but that anonymous object is not (of course).
The questions are:

*

*Does that anonymous object destroys in next line as soon as it's
work is done?

*Is this way of creating anonymous objects is good or
bad in comparison to the f1 object creation (specially when we
need to call just one method of that class like in this case)?

A:
I suppose this is what these objects are called

I'm not so sure about that. MSDN does not recognize anonymous objects. It's simply an object that you don't keep a reference to longer than you need. However, CLR keeps the reference until a garbage collection takes place.

Does that anonymous object destroys in next line as soon as it's work is done?

Not necessarily.

Is this way of creating anonymous objects is good or bad in comparison to the f1 object creation

No, it's fine. I'll explain basics of GC in the next few lines.

So how is it with memory reclaiming in .NET?

When you allocate a memory for a resource (an object for instance), it will be stored in the generation 0 on the managed heap. When this generation is full of objects, GC runs

*

*Marks all objects with a flag 0

*Checks all roots and if a root refers to an objects, the object is marked with a flag 1

All objects with a flag 1 are moved to the next generation and the rest of the currently checked generation is reclaimed. This means, that both of your objects can live exactly the same time under some circumstances.
This is by no means a complete description of .NET GC, just an introduction. If you are instereted in more details, read some article or a book.

A: When you use word 'accessible' in your comment, actually you mean variable scope. When you use word 'destroy', actually you mean garbage collection. They are totally different things. One is C# syntax, the other is CLR runtime behavior.
To answer you specific question:

*

*No

*There is no good or bad. In you code, they are the same. No matter how you instantiate foo, one and only one instance is created within whole method.


text:
Q: How to populate a matrix based on criteria for rows and columns (Updated 2x) Updated 2x I have checked the issue and now I can give a better explanation.
I am trying to do a schedule planning using r. My issue is explained next.
I have a set of n workers and they need to work during a period of m months (aka p). The only conditions that need to be satisfied are next:
Each day is always required that np workers need to be working in the factory.
All the workers must have r=8 days of rest per month but each day there must always be np people working.
Those are the conditions that need to be completed for this issue. In this way I think I could use the days of month to populate the days of working but I am not sure on how to set the rest days such that each month each worker only must have 8 days of rest. I would set a matrix with an example of 12 workers during two months. The only conditions are: each day np=8 workers must be in the factory and every month they can only have r=8 days of rest.
I have a code like this:
#Workers
n <- 12;
#Months (Days)
p <- 59;
#Number of people required each day
np <- 8;
#Rest days per month
r <- 8
#Matrix
#Days
vday <- seq(as.Date('2023-02-01'),as.Date('2023-03-31'),by=1)
mm <- matrix(data =NA,nrow = n,ncol = length(vday))
dimnames(mm)[[2]]<-as.character(vday)

But it is complex for me finding a way so that I have np=8 persons working each day and that each month each of them must rest only r=8 days per month but keeping the condition that each day are needed np people in the factory. Resting days could be allocated random each month taking into acount the condition. I would set 1 for working and 0 for resting.

A: I think the way you are naming the variables is misleading as np looks to me as a multiplication. I propose a function that can deal with your problem with a different variable naming.
This function returns an error in two cases:

*

*The total number of workers you consider is not integer-divisible for the number of working groups you need. So if you need 2 groups the total number of workers must be integer-divisible by 2 (2, 4, 8, ..., 14). It could accommodate non-integer division but the coding gets a bit more complex and you should specify what you want to do with the extra workers.

*The work-rest schedule is not feasible with the number of groups you plan to use. For instance a 2-day work/3-day rest schedule is not possible having 2 groups of workers (unless nobody work on certain days).
If no error occurs then the function returns a data.frame with the following characteristics:

*

*Column one the worker ID

*Column two the group ID

*All remaining columns represent the working days and can have the following values: 1 - the worker has to work, 0 - the worker has to rest, NA - the worker has neither to work nor rest.

FUNCTION CODE:
work_schedule <- function(workers, total_days, group_size, day_streak, rest_days){

  if(workers %% group_size != 0){
    stop("workers are not divisible in groups of equal sizes")
  }

  n_groups <- workers / group_size

  df <- data.frame(worker = seq_len(workers), # NOTE FOR MORE THAN 26 GROUPS THE GROUP NAMING MUST BE CHANGED
                   group = rep(LETTERS[seq_len(n_groups)], each = group_size))

  schedule <- matrix(nrow = nrow(df), ncol = total_days)

  pttrn <- c(rep(1, day_streak), rep(0, rest_days))

  d0 <- 1
  g_names <- unique(df$group)
  g_ind <- 1

  while(d0 <= total_days){

    d1 <- d0+length(pttrn)-1
    if(d0+length(pttrn)-1 > total_days){
      d1 <- total_days
    }

    mt <- t(schedule[df$group == g_names[g_ind], d0:d1])

    if( !all(is.na(mt)) ) stop("Not enough groups to comply with working and resting days schedule")

    mt[,] <- pttrn[1:length(d0:d1)]

    schedule[df$group == g_names[g_ind], d0:d1] <- t(mt)

    d0 <- d0 + day_streak

    g_ind <- g_ind + 1

    if(g_ind > length(g_names)){
      g_ind <- 1
    }

  }

  colnames(schedule) <- paste0("D", seq_len(total_days))
  return(cbind(df, schedule))

}

EXAMPLES:
# Example 1
work_schedule(12, 15, 3, 2, 2)

   worker group D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12 D13 D14 D15
1       1     A  1  1  0  0 NA NA NA NA  1   1   0   0  NA  NA  NA
2       2     A  1  1  0  0 NA NA NA NA  1   1   0   0  NA  NA  NA
3       3     A  1  1  0  0 NA NA NA NA  1   1   0   0  NA  NA  NA
4       4     B NA NA  1  1  0  0 NA NA NA  NA   1   1   0   0  NA
5       5     B NA NA  1  1  0  0 NA NA NA  NA   1   1   0   0  NA
6       6     B NA NA  1  1  0  0 NA NA NA  NA   1   1   0   0  NA
7       7     C NA NA NA NA  1  1  0  0 NA  NA  NA  NA   1   1   0
8       8     C NA NA NA NA  1  1  0  0 NA  NA  NA  NA   1   1   0
9       9     C NA NA NA NA  1  1  0  0 NA  NA  NA  NA   1   1   0
10     10     D NA NA NA NA NA NA  1  1  0   0  NA  NA  NA  NA   1
11     11     D NA NA NA NA NA NA  1  1  0   0  NA  NA  NA  NA   1
12     12     D NA NA NA NA NA NA  1  1  0   0  NA  NA  NA  NA   1

# Example 2
work_schedule(14, 15, 7, 2, 2)

   worker group D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12 D13 D14 D15
1       1     A  1  1  0  0  1  1  0  0  1   1   0   0   1   1   0
2       2     A  1  1  0  0  1  1  0  0  1   1   0   0   1   1   0
3       3     A  1  1  0  0  1  1  0  0  1   1   0   0   1   1   0
4       4     A  1  1  0  0  1  1  0  0  1   1   0   0   1   1   0
5       5     A  1  1  0  0  1  1  0  0  1   1   0   0   1   1   0
6       6     A  1  1  0  0  1  1  0  0  1   1   0   0   1   1   0
7       7     A  1  1  0  0  1  1  0  0  1   1   0   0   1   1   0
8       8     B NA NA  1  1  0  0  1  1  0   0   1   1   0   0   1
9       9     B NA NA  1  1  0  0  1  1  0   0   1   1   0   0   1
10     10     B NA NA  1  1  0  0  1  1  0   0   1   1   0   0   1
11     11     B NA NA  1  1  0  0  1  1  0   0   1   1   0   0   1
12     12     B NA NA  1  1  0  0  1  1  0   0   1   1   0   0   1
13     13     B NA NA  1  1  0  0  1  1  0   0   1   1   0   0   1
14     14     B NA NA  1  1  0  0  1  1  0   0   1   1   0   0   1

A: Since it remains unclear what should happen when there are not enough rested workers to fill a full team for the day, this solution assumes there are always enough workers for a rested team to be available every day. It simply rotates through the workers.
library(tidyverse)
n <- 15; p <- 15; np <- 7; k <- 2; r <- 2

sol <- rep(c(integer(k-1), 1), length.out = p-1) |> # Vector of days, 1 for rotation, 0 for same crew
  accumulate(
    .f = \(lhs, rhs) {if (rhs) {c(tail(lhs, np), head(lhs, n-np))} else {lhs}}, # move last np elements to the front of the vector
    .init = c(rep(1L, np), rep(0L, n-np))  # init vector
  ) %>%
  set_names(str_c("D", seq_along(.))) %>%
  c(list(Workers = seq_len(n)), .) |> # Add workers col
  do.call(what = cbind)

sol
#>       Workers D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12 D13 D14 D15
#>  [1,]       1  1  1  0  0  1  1  0  0  1   1   0   0   1   1   0
#>  [2,]       2  1  1  0  0  1  1  0  0  1   1   0   0   1   1   0
#>  [3,]       3  1  1  0  0  1  1  0  0  1   1   0   0   1   1   0
#>  [4,]       4  1  1  0  0  1  1  0  0  1   1   0   0   1   1   0
#>  [5,]       5  1  1  0  0  1  1  0  0  1   1   0   0   0   0   1
#>  [6,]       6  1  1  0  0  1  1  0  0  0   0   1   1   0   0   1
#>  [7,]       7  1  1  0  0  0  0  1  1  0   0   1   1   0   0   1
#>  [8,]       8  0  0  1  1  0  0  1  1  0   0   1   1   0   0   1
#>  [9,]       9  0  0  1  1  0  0  1  1  0   0   1   1   0   0   1
#> [10,]      10  0  0  1  1  0  0  1  1  0   0   1   1   0   0   1
#> [11,]      11  0  0  1  1  0  0  1  1  0   0   1   1   0   0   1
#> [12,]      12  0  0  1  1  0  0  1  1  0   0   1   1   0   0   0
#> [13,]      13  0  0  1  1  0  0  1  1  0   0   0   0   1   1   0
#> [14,]      14  0  0  1  1  0  0  0  0  1   1   0   0   1   1   0
#> [15,]      15  0  0  0  0  1  1  0  0  1   1   0   0   1   1   0

If you care about the distinction between resting 0 and rested non-working NA, you can add that like such:
sol[, -1] <- sol[, -1] |>
  apply(1, \(x) ifelse((cumsum(x==0) %>% {. - lag(., r+1, 0)})>r, NA_integer_, x)) |>
  t()
sol
#>       Workers D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12 D13 D14 D15
#>  [1,]       1  1  1  0  0  1  1  0  0  1   1   0   0   1   1   0
#>  [2,]       2  1  1  0  0  1  1  0  0  1   1   0   0   1   1   0
#>  [3,]       3  1  1  0  0  1  1  0  0  1   1   0   0   1   1   0
#>  [4,]       4  1  1  0  0  1  1  0  0  1   1   0   0   1   1   0
#>  [5,]       5  1  1  0  0  1  1  0  0  1   1   0   0  NA  NA   1
#>  [6,]       6  1  1  0  0  1  1  0  0 NA  NA   1   1   0   0   1
#>  [7,]       7  1  1  0  0 NA NA  1  1  0   0   1   1   0   0   1
#>  [8,]       8  0  0  1  1  0  0  1  1  0   0   1   1   0   0   1
#>  [9,]       9  0  0  1  1  0  0  1  1  0   0   1   1   0   0   1
#> [10,]      10  0  0  1  1  0  0  1  1  0   0   1   1   0   0   1
#> [11,]      11  0  0  1  1  0  0  1  1  0   0   1   1   0   0   1
#> [12,]      12  0  0  1  1  0  0  1  1  0   0   1   1   0   0  NA
#> [13,]      13  0  0  1  1  0  0  1  1  0   0  NA  NA   1   1   0
#> [14,]      14  0  0  1  1  0  0 NA NA  1   1   0   0   1   1   0
#> [15,]      15  0  0 NA NA  1  1  0  0  1   1   0   0   1   1   0


text:
Q: Как правильно сравнить 2 числа неизвестного типа? Пишу функции сортировки чисел. Хочу попробовать сделать их типонезависимыми. Для этого передаю внутрь ф-ию сравнения, которая будет отрабатывать внутри:
прототип ф-ии сортировки:
void bubble_sort(void *array, int count, size_t size, int(*comparer)(void*, void*, size_t));

(Размер массива передаю как int что бы, при отрицательном значении, сортировать по убыванию)
Ф-ии сравнения разделил на 3 категории:

*

*Целые со знаком

*целые без знака

*дробные

Ф-ии сравнения:
inline int icompare(void* a, void* b, size_t size) {
    assert(size <= sizeof(int64_t));
    int64_t _a, _b;
    memcpy(&_a, a, size);
    memcpy(&_b, b, size);
    return _a < _b ? -1 : (_a > _b ? 1 : 0);
}
inline int ucompare(void* a, void* b, size_t size) {
    assert(size <= sizeof(uint64_t));
    uint64_t _a, _b;
    memcpy(&_a, a, size);
    memcpy(&_b, b, size);
    return _a < _b ? -1 : (_a > _b ? 1 : 0);
}
inline static int lfcompare(long double a, long double b) {
    return a < b ? -1 : (a > b ? 1 : 0);
}
inline int fcompare(void* a, void* b, size_t size) {
    assert(size <= sizeof(long double));
    if (size == sizeof(float))
        return lfcompare((long double)*(float*)a, (long double)*(float*)b);
    if (size == sizeof(double))
        return lfcompare((long double)*(double*)a, (long double)*(double*)b);
    if (size == sizeof(long double))
        return lfcompare(*(long double*)a, *(long double*)b);
    return 0;
}

Если целые без знака и дробные отрабатывают нормально, то целые со знаком работают не правильно. По ощущению всё летит из-за неправильного копирования знака и структуры числа. Помогите найти решение или предложите альтернативный вариант написания ф-ий сравнения. Спасибо.

A: В общем случае, если известен только размер двух сравниваемых объектов арифметического типа, но не известен их тип, то наверняка определить значение какого из них больше невозможно.
И причина проста — одна и та же последовательность байтов может представлять одно значение, если её интерпретировать как объект типа T1, и в то же время представлять совершенно другое значение, если её интерпретировать как объект некоторого другого типа T2.
Например, предположим, что sizeof(unsigned int) == sizeof(unsigned long) == 4. И есть такой код:
unsigned int ai = 1;
unsigned int bi = 16777216;

unsigned long al = 1;
unsigned long bl = 16777216;

Просматривая переменные ai, bi, al, bl побайтово и интерпретируя байты как имеющие тип unsigned char, мы могли бы обнаружить следующее соответствие:
ai -> 1 0 0 0
bi -> 0 0 0 1

al -> 0 0 0 1
bl -> 1 0 0 0

Т.е. в данном случае получаем, что 1 0 0 0  <  0 0 0 1, если байты интерпретировать как объект типа unsigned int, но в то же время 1 0 0 0  >  0 0 0 1, если байты интерпретировать как объект типа unsigned long.

Это был общий случай. На практике обычно выполняются следующие ограничения:

*

*Все целочисленные типы кроме _Bool не имеют битов заполнения (padding bits).

*Для представления знаковых целых используется дополнительный код (two's complement).

*Знаковые целые не имеют trap representation.

*Для всех целочисленных типов используется одинаковый порядок байтов: либо little-endian, либо big-endian.

*Если два вещественных типа с плавающей точкой (real floating types) имеют одинаковый размер в байтах, то они имеют одинаковое внутреннее представление.

После исправления небольших недочётов ваши функция сравнения будут работать на системах удовлетворяющих приведённым ограничениям, и в качестве порядка байтов использующих little-endian. (Кроме быть может типа _Bool. Сравнивать объекты данного типа приведёнными функциями не следует.)

В функции сравнения беззнаковых целых ucompare() необходимо инициализировать нулём переменные _a и _b.
uint64_t _a = 0, _b = 0;

Если size < sizeof(uint64_t), то старшие байты переменных _a и _b оказываются неинициализированными. Чтение значения из таких переменных вызывает неопределённое поведение.

Аналогично в функции сравнения знаковых целых icompare() необходимо инициализировать переменные _a и _b. Если исходное число является положительным, то старший биты должны быть инициализирован нулём. Если исходное число является отрицательным, то старшие биты должны быть инициализированы единицами.
inline int icompare(void* a, void* b, size_t size) {
    assert(size <= sizeof(int64_t));
    int64_t _a = 0, _b = 0;
    if ( *((signed char*)a + (size - 1)) < 0 )
        _a = -1;
    if ( *((signed char*)b + (size - 1)) < 0 )
        _b = -1;
    memcpy(&_a, a, size);
    memcpy(&_b, b, size);
    return _a < _b ? -1 : (_a > _b ? 1 : 0);
}

Функция сравнения вещественных типов с плавающей точкой fcompare() потенциально может нарушать правила строгих псевдонимов (strict aliasing rule), что ведёт к неопределённому поведению.
Например, если sizeof(float) == sizeof(double), и функцию вызвать для сравнения двух объектов типа double, то будет выполнена ветвь
if (size == sizeof(float))
    return lfcompare((long double)*(float*)a, (long double)*(float*)b);

К объектам типа double обращаются как к имеющим тип float. Поведение программы не определено.
Лучше использовать функцию memcpy():
inline int fcompare(void* a, void* b, size_t size) {
    assert(size <= sizeof(long double));
    if (size == sizeof(float)) {
        float _a, _b;
        memcpy(&_a, a, size);
        memcpy(&_b, b, size);
        return _a < _b ? -1 : (_a > _b ? 1 : 0);
    }
    if (size == sizeof(double)) {
        double _a, _b;
        memcpy(&_a, a, size);
        memcpy(&_b, b, size);
        return _a < _b ? -1 : (_a > _b ? 1 : 0);
    }
    if (size == sizeof(long double)) {
        long double _a, _b;
        memcpy(&_a, a, size);
        memcpy(&_b, b, size);
        return _a < _b ? -1 : (_a > _b ? 1 : 0);
    }
    return 0;
}

Или memcpy() + union:
typedef union {
    unsigned char buff[sizeof(long double)];
    long double ld;
    double d;
    float f;
} float_union;

inline int fcompare2(void* a, void* b, size_t size) {
    assert(size <= sizeof(long double));
    float_union _a, _b;
    memcpy(&_a.buff, a, size);
    memcpy(&_b.buff, b, size);
    if (size == sizeof(float)) {
        return _a.f < _b.f ? -1 : (_a.f > _b.f ? 1 : 0);
    }
    if (size == sizeof(double)) {
        return _a.d < _b.d ? -1 : (_a.d > _b.d ? 1 : 0);
    }
    if (size == sizeof(long double)) {
        return _a.ld < _b.ld ? -1 : (_a.ld > _b.ld ? 1 : 0);
    }
    return 0;
}

И ещё, раз уж вы решили написать «универсальный компаратор», то при сравнении чисел с плавающей точкой следует помнить про NAN — специальное значение, которое при сравнении операторами ==, >, < с чем угодно, даже с самим собой, всегда возвращает 0. Если сортируемый массив может содержать данное значение, то функцию сравнения необходимо переписать так, чтобы она явным образом задавала некоторый порядок NAN относительно других чисел с плавающей точкой, иначе результат сортировки может быть непредсказуем. Например, считать, что NAN больше положительной бесконечности.


text:
Q: Switching parts of a filename I have a large batch of pdf files which are all in the format "[something] somethingelse".
How can I switch the first part and the end part around to achieve "somethingelse [something]"?
For example (before and after):
[P. Morandi] Field and Galois Theory
Field and Galois Theory [P. Morandi]

[D. S. Bridges] Foundations of Real and Abstract Analysis
Foundations of Real and Abstract Analysis [D. S. Bridges]

[J. G. Ratcliffe] Foundations of Hyperbolic Manifolds
Foundations of Hyperbolic Manifolds [J. G. Ratcliffe]

[R. E. Edwards] Fourier Series - A Modern Introduction Volume 1
Fourier Series - A Modern Introduction Volume 1 [R. E. Edwards]

[B. Bollobás] Graph Theory - An Introductory Course
Graph Theory - An Introductory Course [B. Bollobás]

A: How can I switch the first part and the end part around?

For example (before and after):
[P. Morandi] Field and Galois Theory.pdf
Field and Galois Theory [P. Morandi].pdf

Use the following batch file (test.cmd):
@echo off
setlocal enabledelayedexpansion
for /f "usebackq delims=] tokens=1,2" %%a in (`dir /b *.pdf`) do (
  rem %%b is end part of name and will become 1st part
  rem remove extension
  set _first=%%~nb
  rem remove leading space
  set _first=!_first:~1!
  ren "%%a]%%b" "!_first! %%a].pdf"
  )
endlocal

Notes:

*

*Tested with the first two example filenames in your question.

Example usage:
> dir *.pdf
 Volume in drive F is Expansion
 Volume Serial Number is 3656-BB63

 Directory of F:\test

02/10/2016  19:43                 0 [D. S. Bridges] Foundations of Real and Abstract Analysis.pdf
02/10/2016  19:42                 0 [P. Morandi] Field and Galois Theory.pdf
               2 File(s)              0 bytes
               0 Dir(s)  1,733,769,015,296 bytes free

> test

> dir *.pdf
 Volume in drive F is Expansion
 Volume Serial Number is 3656-BB63

 Directory of F:\test

02/10/2016  19:42                 0 Field and Galois Theory [P. Morandi].pdf
02/10/2016  19:43                 0 Foundations of Real and Abstract Analysis [D. S. Bridges].pdf
               2 File(s)              0 bytes
               0 Dir(s)  1,733,769,015,296 bytes free

Further Reading

*

*An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.

*dir - Display a list of files and subfolders.

*for /f - Loop command against the results of another command.

*parameters - A command line argument (or parameter) is any value passed into a batch script.

*ren - Rename a file or files.

*variables - Extract part of a variable (substring).


text:
Q: Outlook Rules move mail from 1 inbox to another I have 2 mailboxes setup in outlook, both are exchange mail. I would like to set up a rule to run so when i receive a new email from the 2nd inbox to forward it to my primary inbox?
It seems that my rules i have setup dont run against the 2nd inbox unless i manually tell them to by clicking the 'Run Rules' now option and selecting the 2nd inboxes folder.

A: In general Oulook will only run rules automatically on your primary inbox. You can get round this by setting up the rules for your second inbox to run on the server, rather than in Outlook. To do this you will need to connect to that inbox in its own Outlook profile, with it as the primary inbox.


text:
Q: Cant get javascript popcorn sample to work I'm an absolute noob to web programming, and I can't seem to get the popcorn sample below working. I'm trying to implement it from the working example here: http://jsfiddle.net/thisgeek/At3xg/
Can someone please spot what im doing wrong? Notice the words don't highlight in time with the audio in the code below, but they do on the jfiddle example.
Thanks!

        <audio id="greeting" src="http://dl.dropbox.com/u/17154625/greeting.ogg" controls></audio>

           Hello,
           and welcome
           to Stack Overflow.
           Thank you for asking your question.

A: Wrap all your own JavaScript code inside
$(document).ready(function() { /* your code here */ });

or move it after the  tag, so it waits to run until after the HTML body has loaded.
jsFiddle does this automatically when you set the onLoad dropdown in the top-left corner.
http://api.jquery.com/ready/


text:
Q: undecodableError: invalid start byte when processing SRTM data Downloading SRTM-Data using the QGIS-SRTM-Downloader plugin works fine. I now do want to process this image data further by using the contours plugin within the extraction tools of raster data, but there's always an error message:

undecodableError: 'utf-8' codec can't decode byte 0x81 in position
154: invalid start byte

How to solve this problem?
Browsing the web told me that there was once an error with utf-8 related to imagery date, but this should have been solved with release 3.4 (I'm using 3.16).
The same error message also appears when trying to clip the SRTM-image into with a polygon to reduce its extent to a smaller area of interest.


text:
Q: R NMF package: How to extract sample classifications? In the NMF R-package one can use consensusmap() to visualise outputs. The plots show which samples belong to which clusters in the "consensus" track.
I would like to extract this sample classification such that I get a data frame like this:
Sample    Cluster
S1        1
S2        1
S3        2
S4        1
.         .
.         .
S100      2

In the ConsensusClusterPlus package this is easy. You just pull out the results$consensusClass. I cannot find a similar solution for the NMF-package. I have tried to look at the raw plot data, but it is too convoluted to extract any meaning from.
Here an illustration of the problem: I need to find out which 'status' is within which 'consensus'.

A: Walk entire tree and count?
> v <- syntheticNMF(20, 3, 10)

> xx<-consensusmap(x)

> str(xx)
List of 4
$ Rowv  :  ..--[dendrogram w/ 2 branches and 10 members at h = 1,  midpoint = 5.97, value = 3.4]
  ..  |--[dendrogram w/ 2 branches and 7 members at h = 1, midpoint = 3.69, value = 2.5]
  ..  |  |--[dendrogram w/ 2 branches and 4 members at h = 0, midpoint = 2.12, value = 1.6]
  ..  |  |  |--[dendrogram w/ 2 branches and 3 members at h = 0, midpoint = 1.25, value = 1.2]
  ..  |  |  |  |--[dendrogram w/ 2 branches and 2 members at h = 0, midpoint = 0.5, value = 0.8]
  ..  |  |  |  |  |--leaf "2" ( value.2 = 0.4 )
  ..  |  |  |  |  `--leaf "1" ( value.1 = 0.4 )
  ..  |  |  |  `--leaf "3" ( value.3 = 0.4 )
  ..  |  |  `--leaf "4" ( value.4 = 0.4 )
  ..  |  `--[dendrogram w/ 2 branches and 3 members at h = 0, midpoint = 1.25, value = 0.9]
  ..  |     |--[dendrogram w/ 2 branches and 2 members at h = 0, midpoint = 0.5, value = 0.6]
  ..  |     |  |--leaf "6" ( value.6 = 0.3 )
  ..  |     |  `--leaf "5" ( value.5 = 0.3 )
  ..  |     `--leaf "7" ( value.7 = 0.3 )
  ..  `--[dendrogram w/ 2 branches and 3 members at h = 0, midpoint = 1.25, value = 0.9]
  ..     |--[dendrogram w/ 2 branches and 2 members at h = 0, midpoint = 0.5, value = 0.6]
  ..     |  |--leaf "9" ( value.9 = 0.3 )
  ..     |  `--leaf "8" ( value.8 = 0.3 )
  ..     `--leaf "10" ( value.10 = 0.3 )
  $ rowInd: int [1:10] 2 1 3 4 6 5 7 9 8 10
  $ Colv  :  ..--[dendrogram w/ 2 branches and 10 members at h = 1, midpoint = 3.03, value = 3.4]
  ..  |--[dendrogram w/ 2 branches and 3 members at h = 0, midpoint = 0.75, value = 0.9]
  ..  |  |--leaf "10" ( value.10 = 0.3 )
  ..  |  `--[dendrogram w/ 2 branches and 2 members at h = 0, midpoint = 0.5, value = 0.6]
  ..  |     |--leaf "8" ( value.8 = 0.3 )
  ..  |     `--leaf "9" ( value.9 = 0.3 )
  ..  `--[dendrogram w/ 2 branches and 7 members at h = 1, midpoint = 2.31, value = 2.5]
  ..     |--[dendrogram w/ 2 branches and 3 members at h = 0, midpoint = 0.75, value = 0.9]
  ..     |  |--leaf "7" ( value.7 = 0.3 )
  ..     |  `--[dendrogram w/ 2 branches and 2 members at h = 0, midpoint = 0.5, value = 0.6]
  ..     |     |--leaf "5" ( value.5 = 0.3 )
  ..     |     `--leaf "6" ( value.6 = 0.3 )
  ..     `--[dendrogram w/ 2 branches and 4 members at h = 0, midpoint = 0.875, value = 1.6]
  ..        |--leaf "4" ( value.4 = 0.4 )
  ..        `--[dendrogram w/ 2 branches and 3 members at h = 0, midpoint = 0.75, value = 1.2]
  ..           |--leaf "3" ( value.3 = 0.4 )
  ..           `--[dendrogram w/ 2 branches and 2 members at h = 0, midpoint = 0.5, value = 0.8]
  ..              |--leaf "1" ( value.1 = 0.4 )
  ..              `--leaf "2" ( value.2 = 0.4 )
 $ colInd: int [1:10] 10 8 9 7 5 6 4 3 1 2

> lapply(cut(xx$Rowv,0.5)$lower, function(l) rapply(l, function(i) i))
[[1]]
[1] 2 1 3 4

[[2]]
[1] 6 5 7

[[3]]
[1]  9  8 10

A: NMF::predict(NMFfitX_object, what = "consensus")

If you have an object of class NMF.rank, you can access the contained NMFfitX objects for rank = 3 with:
NMF.rank_object$fit$`3`


text:
Q: Dynamic Select in RubyOnRails error in append select I'm trying to do a dynamic select, when user select school appear only the groups that belong to that school, but when I tried to change the select I got this error:

Missing partial admin/groups/_group with {:locale=>[:en], :formats=>[:js, :html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee]}.

CoffeeScript

$(document).on "page:change", ->
  $(document).on 'change', '#schools_select', (evt) ->
    $.ajax 'update_groups',
      type: 'GET'
      dataType: 'script'
      data: {
        school_id: $("#schools_select option:selected").val()
      }
      error: (jqXHR, textStatus, errorThrown) ->
        console.log("AJAX Error: #{errorThrown}")
      success: (data, textStatus, jqXHR) ->
        console.log("Dynamic school select OK!")

HTML
The school belongs to the model of the form, but the group isn't an attribute of the form.

      <%= f.label :school %>

      <%= f.select :school_id, options_for_select(@schools.active.collect { |school|
      [school.name.titleize, school.id] }, 1), {}, { id: 'schools_select' } %>

      <%= label_tag :group %>

      <%= select_tag :group_id, options_for_select(@groups.active.collect { |group|
      [group.name.titleize, group.id] }, 1), { id: 'groups_select' } %>

Javascript
$("#groups_select").empty().append("<%= escape_javascript(render(:partial => @groups)) %>")

Ruby
 def update_groups
   @groups = Group.where(school_id: params[:school_id])
   respond_to do |format|
     format.js
   end
 end

Routes
     get 'students/update_groups', as: 'update_groups'

A: Make your method like below. Also, make sure yr ajax request triggers.
def update_groups
   @groups = Group.where(school_id: params[:school_id])
   render json: @groups, root: false
 end

A: My error was that I didn't tell what to render and then I was trying to update the select in other file, when it wasn't necessary.
This is the updated code
CofeeScript
$(document).on "page:change", ->
  $(document).on 'change', '#schools_select', (evt) ->
    $.ajax 'update_groups',
      type: 'GET'
      dataType: 'script'
      data: {
        school_id: $("#schools_select option:selected").val()
      }
      error: (jqXHR, textStatus, errorThrown) ->
        console.log("AJAX Error: #{errorThrown}")
      success: (data, textStatus, jqXHR) ->
        groups = JSON.parse(data)
        $.each groups, (index) ->
          $('#groups_select').empty().append $('<option></option>').attr('value', groups[index].id).text(groups[index].name)
        return

Ruby
  def update_groups
    @groups = Group.where(school_id: params[:school_id])
    respond_to do |format|
      format.json { render json: @groups }
    end
  end

I delete the javascript file.


text:
Q: How to fast create a variable that all combined the string values of a particular column in a dataframe? temp_day is dataframe, and it has billion rows.
Height_classify <- data.frame(color = c('red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'),
                                  min = c(0, 100,300,500,1000,2000,5000),
                                  max = c(100,300,500,1000,2000,5000,8000))

make_code <- function(temp_day, h_class){
  temp_class <- Height_classify %>% filter(color == h_class)
  min_godo <- temp_class[1,2]
  max_godo <- temp_class[1,3]
  temp_day_hight <- temp_day %>% filter(AltitudeActual_m >= min_godo & AltitudeActual_m < max_godo)
  polys <- stri_c("polys_", temp_class[1,1], " = [")
  hight_flight <- as.data.frame(table(unlist(temp_day_hight$mdH_CallSign)), stringsAsFactors = F)

  for (sFlight in hight_flight$Var1){

    temp_day_hight_flight <- temp_day_hight %>% filter(mdH_CallSign == sFlight)

    if (nrow(temp_day_hight_flight) >1){

      polys <- stri_c(polys, "[")

      for (i in 1:nrow(temp_day_hight_flight)){

        polys <- stri_c(polys, temp_day_hight_flight$coord[i])
        if (i < nrow(temp_day_hight_flight)){
          polys <- stri_c(polys, ", ")
        } else {
          polys <- stri_c(polys, "], ")
        }

      } # for i
    } # if
  }# for sFlight
  polys <- substr(polys, 1, nchar(polys)-2)
  polys <- stri_c(polys, "]\n\n")

  return(polys)
}

Combining many strings in a column takes a lot of time to produce the result.
I think it slows down as the values continue to accumulate in the variable.
polys <- stri_c(polys, temp_day_hight_flight$coord[i])

How can you switch to a function that works faster?


text:
Q: Is there a way to perform the YouTube full screen action programmatically without stopping playback? I am wondering if there is a way of doing the YouTube full screen action (showing in landscape mode only the player) programmatically in android? I tried YouTubePlayer.setFullscreen(true) but that causes the playback to stop I am clueless of where to start.

A: Simply call YoutubePlayer.setFullscreen(true). You can find the reference in the official YouTubePlayer docs.
There are a couple things of importance to note here:

Calling this function may affect the looks of the player's controls, e.g. showing an option to enter or exit fullscreen, changing the layout to better suit the current player size etc.

and

Calling this function will cause any registered YouTubePlayer.OnFullscreenListener to fire


text:
Q: Is WCF Chunking Ready For Production Use? Does anyone know what the status of WCF Chunking?  Is it good for production use? Does anyone have any experience using the new WCF Chunking Channel in production?
http://msdn.microsoft.com/en-us/library/aa717050.aspx
I've downloaded the sample but it seems the API is not ready yet.
Does anyone have any good alternatives to WCF chunking?

A: It is not an API and it is not part of .NET Framework. It is sample of WCF extensibility.  It is up to you to modify sample if it doesn't fit to your needs. I heard about people who used this code in production.


text:
Q: ajax retrieve huge data from server My ajax code is
function senddata()
{
    var ajaxRequest;  // The variable that makes Ajax possible!

    // Create a function that will receive data sent from the server
    ajaxRequest.onreadystatechange = function()
    {
        if(ajaxRequest.readyState == 4)
        {
            document.getElementById("showdata").innerHTML=ajaxRequest.responseText;
        }
    }

    ajaxRequest.open("GET", Handler.php?key=" + value, true);
    ajaxRequest.send(null);
}

I have huge amount of data that gets retrieved through ajax. Now when i call this function, it takes much time to show data. I want here is that as the data gets retrived, it should be displayed on the screen. No need to show whole retrieved data only when everything is fetched but display data as it gets fetched.

A: You're going to want to approach this with the same style of thinking as if you were implementing a pagination system.
I cannot see your Handler.php code, so it might make things difficult as we need to edit things in there.

*

*Make Handler.php accept limit and offset or page query var(s)

*Add the appropriate code in your PHP to handle that (and the case where none are provided, don't just sent everything! default limit to 10 and offset to 0.)

*Functionalize your ajax request and make it paginate:
function getdata(limit, offset)
{
     limit  = limit || 10;
     offset = offset || 0;

     var ajaxRequest;  // The variable that makes Ajax possible!

     // Create a function that will receive data sent from the server
    ajaxRequest.onreadystatechange = function()
    {
       if(ajaxRequest.readyState == 4)
       {
           document.getElementById("showdata").innerHTML=ajaxRequest.responseText;

           // make Handler.php send 'end' when no results have been returned
           if (ajaxRequest.responseText && ajaxRequest.responseText != 'end') {
             getdata(limit, offset + limit);
           }
       }
    }

   ajaxRequest.open("GET", Handler.php?key=" + value + '&limit=' + limit +
     '&offset=' + offset, true);
   ajaxRequest.send(null);
}

getData();

Just make sure Handler.php sends end when there is no more data.


text:
Q: Using classes in selenium to avoid redundant code I have to open 2 Websites , they are the same , so i just have to change the URL , username and pass to login , right now i have two Functions with the same code manually sending 2 diferents sets of users and passwords.
I would like to use A class , to pass the user,pass and url to it and connect to a website , this is what i have thus far :
class Alienvault:

url = ''
alienuser = ''
alienpass = ''
def Conexion(self):

    driver = webdriver.Firefox()
    driver.implicitly_wait(10)
    driver.get(url)
    nombreusuario = driver.find_element_by_name('user')
    password = driver.find_element_by_name('passu')
    nombreusuario.clear()
    password.clear()
    nombreusuario.send_keys(alienuser)
    password.send_keys(alienpass)

    login = driver.find_element_by_id('submit_button')
    login.click()
    time.sleep(4)
    analisis = driver.find_element_by_id('li_analysis')
    analisis.click()
    eventos = driver.find_element_by_id('sm_opt_analysis-security_events')
    eventos.click()
    driver.maximize_window()

A: Try something like this :
class Alienvault:

    def __init__(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(10)

    def login(self, user, password, url):
        self.driver.get(url)
        nombreusuario = self.driver.find_element_by_name('user')
        password = self.driver.find_element_by_name('passu')
        nombreusuario.clear()
        password.clear()
        nombreusuario.send_keys(user)
        password.send_keys(password)
        login = self.driver.find_element_by_id('submit_button')
        login.click()
        time.sleep(4)
        analisis = self.driver.find_element_by_id('li_analysis')
        analisis.click()
        eventos = self.driver.find_element_by_id('sm_opt_analysis-security_events')
        eventos.click()
        self.driver.maximize_window()

con = Alienvault()
con.login('myuser1', 'mypass1', 'www.myurl.com')
con.login('myuser2', 'mypass2', 'www.my_other_url.com')


text:
Q: Convert a date to a different format for an entire new column I want to convert the date in a column in a dataframe to a different format. Currently, it has this format: '2019-11-20T01:04:18'. I want it to have this format: 20-11-19 1:04.
I think I need to develop a loop and generate a new column for the new date format. So essentially, in the loop, I would refer to the initial column and then generate the variable for the new column in the format I want.
Can someone help me out to complete this task?
The following code works for one occasion:
import datetime
d = datetime.datetime.strptime('2019-11-20T01:04:18', '%Y-%m-%dT%H:%M:%S')
print d.strftime('%d-%m-%y %H:%M')

A: From a previous answer in this site , this should be able to help you, comments give explanation
You can read your data into pandas from csv or database or create some test data as shown below for testing.
>>> import pandas as pd
>>> df = pd.DataFrame({'column': {0: '26/1/2016', 1: '26/1/2016'}})
>>> # First convert the column to datetime datatype
>>> df['column'] = pd.to_datetime(df.column)
>>> # Then call the datetime object format() method, set the modifiers you want here
>>> df['column'] = df['column'].dt.strftime('%Y-%m-%dT%H:%M:%S')

>>> df
                 column
0  2016-01-26T00:00:00
1  2016-01-26T00:00:00

NB. Check to ensure that all your columns have similar date strings

A: You can either achieve it like this:
from datetime import datetime

df['your_column'] = df['your_column'].apply(lambda x: datetime.strptime(x, '%Y-%m-%dT%H:%M:%S').strftime('%d-%m-%y %H:%M'))


text:
Q: Laravel cannot get response to parse foreign characters correctly After searching for a suitable answer, I find that the solutions people offer do not work so I am posting here in the hope of some help.
I have a database of users that will list by first letter of name in a directory. However there is one user that breaks the results because their name begins with a letter with a foreign character, namely Á.
I get the user results with:
$users = $this->users->getAll($params);

And then return the response using collection which json encodes it:
return response()->collection($users);

But I get the following error if the above user is returned in results:

The Response content must be a string or object implementing
  __toString(), 'boolean' given.

I've tried using the JSON_UNESCAPED_UNICODE option, like many people suggest in solutions, like this:
return response()->json($users, 200, ['Content-type'=> 'application/json; charset=utf-8'], JSON_UNESCAPED_UNICODE);

but it turns out the response isn't coming back as UTF-8 after attempting to log it. However, as far as I can tell, the database is UTF-8 encoded so I don't understand what's happening here.
The problem is, even if I was to change the character to a regular A, there could still be future users with foreign characters in their name, and I'd rather there be something in place to handle this.
Any help is appreciated.

A: collation utf8mb4_unicode_ci works fine for me.
If you mention your database collation it's define your issue more readable.

A: In config/database.php :
'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => false,
        'engine' => null,
    ],

And now make the columns collation as : utf8mb4_unicode_ci.
Hope this works. Thanks.


text:
Q: (.OFX/.QFX/.QIF/.QBO/.OFC) file converter We are building an application that reads files (.OFX/.QFX/.QIF/.QBO/.OFC) and place the data read in the file in a grid.
Does anyone know of a utility or 3rd party tool to convert the file types (.OFX/.QFX/.QIF/.QBO/.OFC) to something more conventional like XML or CSV. Any help will be greatly appreciated!
We are using c#/ASP.NET for developing out web application. The app is hosted on a Windows server if it makes any difference...

A: fixofx was open sourced from Wesabe. It converts various types of financial files including OFX 1.0 and QIF files to OFX 2.0, which is an XML-based format and so is easily parsed.

A: I wrote a Python script ofx2csv.py that converts OFX/QFX files to CSV, if anyone needs to do this programmatically.

A: I found a solution to this problem.
Bank2CSV Pro converts various bank, credit card and investment files (QIF, OFX, QFX, QBO, OFC) into CSV format (the file will become a table like a regular spreadsheet with rows as transactions. It supports command line mode:
bank2csv_pro.exe input.ofx output.csv
See http://www.propersoft.net/

A: Bank2CSV Pro works well but the free version converts only 10 transactions and the full version costs USD 50. I found a free online tool that converts CSV to OFX and QIF:
http://csvconverter.gginternational.net/
Just upload your csv, select the fields to map and boom - you get your QIF or OFX file. Worked really well for me when I tried to upload my bank files to QBO

A: The  ofx2csv.py script almost works. For the citibank downloads where the csv does not include the 'memo' field and qfx does, I needed to add the memo field to output:
line = {
        'date': transaction.date.strftime(DATE_FORMAT),
        'payee': transaction.payee,
        'memo':transaction.memo,
        'debit': debit,
        'credit': credit,
        'balance': balance
    }

A: Not sure if you are loking for code to accomplish this or for a utility that does it on the desktop. If it i the latter, then try iCreateOFX Basic which reads OFX and QIF files as well as CSV files into a grid.


text:
Q: Can I set the stack pointer in LLVM? I'm working on a small c++-like language which I'll be compiling to LLVM. One of the things I want to implement is cooperative multitasking; there will be a "yield" operator which will hopefully switch the stack pointer and program counter to the next "thread" in my program.
Is it possible to do this in llvm? Can I set the stack pointer register? If not, is there anything else similar I can do?
Edit: LLVM coroutines (http://llvm.org/docs/Coroutines.html) sound promising, though https://internals.rust-lang.org/t/llvm-coroutines-to-bring-awarness/3708/12 brings up some questions regarding stackful or stackless coroutines. I wonder, can they be used to implement a general yield-like operator?
Edit 2: In c++ boost has something called a "context" which can implement stackful coroutines. Still trying to figure out how they do it though. Anyone know?

A: Assuming you have the gcd library available: You can easily implement cooperative multitasking by using a semaphore (dispatch_semaphore_t). The semaphore count is set up so that exactly one of your threads can run at the same time. The yield() function signals and immediately locks the semaphore - the signal() wakes up another thread, and the lock stops the thread that called yield.


text:
Q: C++ Constructor for Implicit Type Conversion I have these codes:
class Type2 {
public:
  Type2(const Type1 & type);
  Type2(int);
const Type2 & operator=(const Type2 & type2);
//....
};

...
  Type1 t1(13);
  Type2 t2(4);

  t2=t1;

As I understood, the 1-argument constructors of Type2 each without an explicit keyword should mean any Type1 objects or int values can be implicitly conveted to Type2 objects.
But in the last line t2=t1;, MS Visual Studio gives me this compile error:

....error C2679: binary '=' : no operator
  found which takes a right-hand operand
  of type 'Type1' (or there is no
  acceptable conversion)....

Seems like MS Visual Studio insisting t2=t1; must match an assignment operator with lhs=Type2 and rhs=Type1.  Why can't it implicitly cast rhs to t2 and then do the copying with the Type2=Type2 operator?

A: I've found the answer.  Because my Type1 got a conversion operator
    class Type1 {
    public:
        Type1 (int );
        operator  Type2() ;//casting to Type2

    ....
    };

This is something called "dual-direction implicit conversion"

A: This code:
#include <iostream>

using ::std::cerr;

class Barney;

class Fred {
 public:
   Fred() { }
   Fred(const Barney &b) { cerr << "Using conversion constructor.\n"; }
};

class Barney {
 public:
   Barney() { }
   operator Fred() const { cerr << "Using conversion operator.\n"; return Fred(); }
};

int main(int argc, const char *argv[])
{
   const Barney b;
   Fred f;
   f = b;
   return 0;
}

generates this error in gcc 4.6:
g++ -O3 -Wall fred.cpp -o a.out
fred.cpp: In function 'int main(int, const char**)':
fred.cpp:23:8: error: conversion from 'const Barney' to 'const Fred' is ambiguous
fred.cpp:21:17: note: candidates are:
fred.cpp:16:4: note: Barney::operator Fred() const
fred.cpp:10:4: note: Fred::Fred(const Barney&)
fred.cpp:7:7: error:   initializing argument 1 of 'Fred& Fred::operator=(const Fred&)'

Compilation exited abnormally with code 1 at Sun Jun 19 04:13:53

Now, if I remove the const after operator Fred(), it then compiles, and uses the conversion constructor. If I also remove the const from the declaration of b in main, it then prefers the conversion operator.
This all fits the overload resolution rules. And gcc generates the appropriate ambiguity error when it can't pick between the conversion operator and the conversion contructor.
I notice that in the examples you gave, the conversion operator is missing a const. This means that there will never be a case in which using the conversion operator or the converting constructor is ambiguous.


text:
Q: calling recursive function when passing a functon for higher order function I want to recursively call higher order function. so I have a list and I'm passing this list to a function name funcName. but I need to pass a function. and I want to put a logic there. i want to check if the element is eric. how do I recursive function for fun i-> syntax?
let aaa c : bool =
      let rec helper c =
        match c with
        |element(i) -> funcName (fun i->if (List.hd i)=eric then true else
                             //now i want to recursively call List.tl inside this inner function
      in
      helper c

A: You seem to be asking how to call a function recursively when it's defined as a fun, which is nameless.
There are ways to do this, but they are more complicated than is worth it (in my opinion).
You can just give a name to the nameless function:
let aaa c : bool =
    let rec helper c =
        let rec helper_helper i =
            if List.hd i = eric then true
            else (* Do your recursive calling of helper_helper *)
        in
        match c with
        | Element i -> funcName helper_helper
    in
    helper c


text:
Q: How do I include two files of the same name in my spring application context? Not sure if this has an answer, but here goes.  I'm using JUnit 4.8.1 to test my Spring 3.1.0.RELEASE project.  I have two JAR files on my classpath.  Within each, there are files of identical names -- /module/rootContext.xml .
In my testApplicationContext.xml file (my Spring context file for my JUnit tests), is it possible to include each of those?  Right now, the only thing I know how to do is
<import resource="classpath:/module/rootContext.xml" />

but I don't know how to specify the exact JAR file where each file lives.
Because I'm dealing with code that's not my own, it is not an option to change the names of the XML files within the JARs.

A: If you want to include both files simultaneosly, you can do it as follows:
<import resource="classpath*:/module/rootContext.xml" />

See also:

*

*4.7.2.2 The classpath*: prefix


text:
Q: laravel 9 401unauthorized database/migration/create_roles_table.php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateRolesTable extends Migration
{
   /**
    * Run the migrations.
    *
    * @return void
    */
   public function up()
   {
       Schema::create('roles', function (Blueprint $table) {
           $table->bigIncrements('id');
           $table->string('name')->unique();
           $table->string('display_name')->nullable();
           $table->string('description')->nullable();
           $table->timestamps();
       });

   }

   /**
    * Reverse the migrations.
    *
    * @return void
    */
   public function down()
   {
       Schema::dropIfExists('roles');
   }
};

create_roles_user_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateRoleUserTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('role_user', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('role_id')->unsigned();
            $table->integer('user_id')->unsigned();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('role_user');
    }
};

user migration
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('secretword');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
};

models User.php
<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable implements MustVerifyEmail
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'secretword',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function roles()
    {
        return $this
            ->belongsToMany(Role::class)
            ->withTimestamps();
    }

    public function users()
    {
        return $this
            ->belongsToMany('App\User')
            ->withTimestamps();
    }

    public function authorizeRoles($roles)
    {
        if ($this->hasAnyRole($roles)) {
            return true;
        }
        abort(401, 'This action is unauthorized.');
    }

    public function hasAnyRole($roles)
    {
        if (is_array($roles)) {
            foreach ($roles as $role) {
                if ($this->hasRole($role)) {
                    return true;
                }
            }
        } else {
            if ($this->hasRole($roles)) {
                return true;
            }
        }
        return false;
    }

    public function hasRole($role)
    {
        if ($this->roles()->where('name', $role)->first()) {
            return true;
        }
        return false;
    }
};

App\Http\Middleware\CheckRole.php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CheckRole
{
   /**
    * Handle an incoming request.
    *
    * @param  \Illuminate\Http\Request  $request
    * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
    * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
    */
   public function handle(Request $request, Closure $next, string $role)
   {
       if (! $request->user()->hasRole($role)) {
           abort(401, 'This action is unauthorized.');
       }
       return $next($request);
   }
}

web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('auth/login');
});

Auth::routes(['verify' => true]);
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::get('/admin', [App\Http\Controllers\AdminController::class, 'index']);
Route::get('/superadmin', [App\Http\Controllers\SuperAdminController::class, 'index']);

Route::resource('posts', PostController::class);

Hello, I'm trying to make an admin panel so that only the admin can have access. I created a user account but I don't know how to change it to admin or super admin. I already have the ready view I wanted to know how I can make an admin user because I'm trying to go to http://127.0.0.1:8000/admin it makes me
401
Unauthorized
how can I become an admin to be authorized to go to these pages?

A: First run the command,
php artisan make:seeder UserSeeder

Then, go to database/seeders/UserSeeder.php and put the following code in run() method
$user = User::find($user_id);
$user->assignRole('Admin');

Then, run the following command
php artisan db:seed --class=UserSeeder

A: First of all try dd(auth()->user()->roles) and see what it returns, check if there is the specified role. Also check dd($this->roles()->where('name', $role)->first()) and see what it returns.
Also I recommend to use the package: Spaties's Laravel-permission


text:
Q: PHP Button limit Okay I have a problem here. Whether users column "checked" is 1 or 0 it ignores the IF statement and still adding 10000 points. Can somebody explain me why ?
foreach ($users as $u) {

    if (isset($username) . $u['checked'] == 0) {

        foreach ($points as $p) {

            $username = $_SESSION['username'];

            $p = $p['points'] + 10000;

            try {
                $q = $pdo->prepare("UPDATE users SET points = ?, checked = ? WHERE username = ?");
                $q->execute(array($p, $ten, $username));
            } catch (Exception $e) {
                echo $e->getMessage();
                die();
            }

            header("Location: index.php");
        }
    } else {
        echo "Nothing";
    }
}

A: Try using a more explicit if statement like
if(isset($username) && $u['checked'] == 0)

Also as Bery said in the comments, isn't $username supposed to be $u?


text:
Q: How to collapsed nav-treeview when I click the submenu in AdminLTE 3.0? As you can see in the GIF when I click the submenu it no longer collapses. What I want is when I click the submenu it will collapse and will not automatically close when I click the page

            <a href="#" class="nav-link <?= $page == 'patients.php' || $page == 'medical_history.php'? 'active':''?>">

Patients

            <ul class="nav nav-treeview <?= $page == 'patients.php' || $page == 'medical_history.php' ? 'show':''?>">

                <a href="patients.php" class="nav-link <?= $page == 'patients.php' ? 'active':''?>">

Patient List

                <a href="medical_history.php" class="nav-link <?= $page == 'medical_history.php' ? 'active':''?>">

Medical History

A: Updated...
I've updated and provided the code you need... just copy and paste this code in the relevant section of your file. I'm sure this will work for you : )

<li class="nav-item <?= $page == 'patients.php' || $page == 'medical_history.php' ? 'menu-open' : '' ?>">
  <a href="#" class="nav-link <?= $page == 'patients.php' || $page == 'medical_history.php' ? 'active' : '' ?>">

Patients

      <a href="patients.php" class="nav-link <?= $page == 'patients.php' ? 'active' : '' ?>">

Patient List

      <a href="medical_history.php" class="nav-link <?= $page == 'medical_history.php' ? 'active' : '' ?>">

Medical History

A: If your AdminLTE template uses bootstrap, then try to add a collapse and a show class in the nested ul element right after the nav-treeview class.

A: Just add display: none


text:
Q: Country list selection box - Set one as selected I have a country list of every country in a form to get a parcel quote.
When a user presses the "Get Quote" button, all the text forms retain the information previously entered using PHP.
How can I do this with the country list box? As I can't have PHP on every option checking if that is the country selected and adding "Selected" to the html.
Is there a better way other than generating the country list from a file in a loop?
EDIT:
Going for the method of looping through a file, and checking..
This is what I have so far:
$countries = fopen("includes/countries.txt", "r");
$countries = explode(";", $countries);

Then in the HTML:
<select id="countries" name="countries">
<?php
    foreach ($countries as $country){
        echo("<option value=\"" . $country . "\">" . $country . "</option>");
    }

?>
</select>

Not yet finished.

A: I assume you have an array with your countries stored. You could try something like this:
$countries = array('Albania', 'Egypt');
$selected_country_id = $_GET['c_id']; // You may need to change this to match with your code
$country_selected = array();

foreach($countries as $country) {
    if($country['id'] == $selected_country_id) {
        $country_selected[ $country['id'] ] = ' selected ';
    } else {
        $country_selected[ $country['id'] ] = '';
    }
}

Then, assuming that you dynamically add your Select-Options, do this:
// In your each-fn

echo '<option value="' . $country['id'] . '" ' . $country_selected[ $country['id'] ] . '>' . $country['name'] . '</option>';

A: Something like this would be better
foreach ($countries as $country) {
    ?>
    <option value="<?php echo $country" <?php echo ($country == $_POST['country'] ? 'selected' : ''; ?>><?php echo $country; ?></option>
    <?php

}

A: <select id="countries" name="countries">
    <?php
        foreach ($countries as $country){
            if(isset($_POST["country"]) && $_POST["country"] == $country){
              $sel = "selected";
            }else { $sel= ""; }
            echo("<option value=\"" . $country . "\"" .$sel.">" . $country . "</option>");
        }

    ?>
    </select>

A: Get All Country-State-City Selectbox ....!!!
See Link : GitHub


text:
Q: ASCII Number to Character Error in PHP I have a problem when I convert ASCII number to character.
I use chr() function to convert it to character. I didn't find any errors in a pure PHP page. But, when I use chr() function in a web page (using Codeigniter framework) that contains jquery and other javascript, chr() function would return an unknown character.
Here's the example :
 chr(218); // It returns `Ú` character in pure PHP page
 chr(218); // It returns `�` character in a complex webpage.

Does any one know why is it happen?
And please tell me how fix it!
Any help would be appreciated :)

A: Use this to set the character encoding of an HTML document
<meta charset="utf-8">

Reference

MetaCharsetAttribute

using php

<?php $mysqli->set_charset("utf8") ?>

Reference
http://www.php.net/manual/en/mysqli.set-charset.php

A: This will be a character encoding problem.
try using
iconv('ISO-8859-1','UTF-8', chr(128));

to force it to use UTF-8.
This is common if you are returning the value from a function or external script as the encoding isn't always carried over to included files.


text:
Q: How get the values of multi entries (when added in fly by jQuery) in view of ASP.NET MVC this is my controller:
public ActionResult Create() {
            Number newNumber = new Number();
        return View(newNumber);
    }

and View :
@model PhoneBook.Models.Number
@{
ViewBag.Title = "Create";
}

Create

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
@Html.HiddenFor(model => model.Contact.Id)
<fieldset>
<legend>Number</legend>

        @Html.LabelFor(model => model.PhoneNumber)

        @Html.EditorFor(model => model.PhoneNumber)
        @Html.ValidationMessageFor(model => model.PhoneNumber)

        @Html.LabelFor(model => model.NumberKind)

    @Html.DropDownListFor(model => model.NumberKind.Title, NumberKinds)

    <input class="AddNew" value="Add New" type="button" />

    <input type="submit" value="Create" />

</fieldset>
}

By press AddNew button (use jQuery AddNewNumber.js) new input+DropDown Added to form in client side. this is script:
$(document).ready(function () {
$('.AddNew').click(function () {
    var targetcloneelements = $(".TargetElements:first").clone();
    targetcloneelements.find('input').val('');
    targetcloneelements.insertAfter('.TargetElements:last');
});
});

This way(Add new) is very usual, All of us can see that in many sites (So that must have a solution), But there is a problem in retrieve values. When I have one entry element(include input+DropDown) I can retrieve values like the following in post of my controller:
[HttpPost]
    public ActionResult Create(Number NewNumber, FormCollection collection) {
            db.Numbers.Add(NewNumber);
            db.SaveChanges();
            return RedirectToAction("Index")
}

I read this articles : 1 , 2 , 3 but none of them haven't any solution for fly mode add entries, when I know the numbers of entity it can be possible but in fly mode it can be 1 or 1000
So, is there any way to retrieve values and add them to DataBase?
Edit:
I find the values in FormCollection but yet I don't know how extract them from collection? This is a picture of the Collection values in breakponit of binding

Edit2:
Find to retrieve all values: (every element has a key that seen in above pic)
string[] PhoneNumbers = collection.GetValues("PhoneNumber");

A: What you are trying to do is called Model binding to a List of object and your case it's Non-Sequential.
ASP.NET MVC DefaultModelBinder can bind arbitrary object if you follow a described convention like below:

Non-Sequential Indices
What happens when you can't guarantee that the submitted values will
  maintain a sequential index? For example, suppose you want to allow
  deleting rows before submitting a list of books via JavaScript.
The good news is that by introducing an extra hidden input, you can
  allow for arbitrary indices. In the example below, we provide a hidden
  input with the .Index suffix for each item we need to bind to the
  list. The name of each of these hidden inputs are the same, so as
  described earlier, this will give the model binder a nice collection
  of indices to look for when binding to the list.

you can read the whole article from : http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
Here is the code sample:
<form method="post" action="/Home/Create">

    <input type="hidden" name="products.Index" value="cold" />
    <input type="text" name="products[cold].Name" value="Beer" />
    <input type="text" name="products[cold].Price" value="7.32" />

    <input type="hidden" name="products.Index" value="123" />
    <input type="text" name="products[123].Name" value="Chips" />
    <input type="text" name="products[123].Price" value="2.23" />

    <input type="hidden" name="products.Index" value="caliente" />
    <input type="text" name="products[caliente].Name" value="Salsa" />
    <input type="text" name="products[caliente].Price" value="1.23" />

    <input type="submit" />
</form>

You controller action should look like this:
[HttpPost]
public ActionResult Index(IEnumerable<Product> products) {

    foreach(var item in products) {

        //play with your product here.
    }
}

Also, see the following articles as well:

Editing a variable length list, ASP.NET MVC 2-style
http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/
Validating a variable length list, ASP.NET MVC 2-style
http://blog.stevensanderson.com/2010/01/28/validating-a-variable-length-list-aspnet-mvc-2-style/

Those two articles for ASP.NET MVC 2 but works same on ASP.NET MVC 3.

A: why don't you add also a new form with a new submit button and submit ONLY the new values?
Of course the old and new form don't have to be nested, since they shouldn't work.
I did it several times, but with a slight different approach.
Your js function should make a post async call to a method that returns a partial view with the whole new form.

A: every element has a key so you can use this for example:
string[] PhoneNumbers = collection.GetValues("PhoneNumber");

A: I am not much knowledgeable about ASP.Net .
But from php & ROR this how it can be made to work.
give the html of input as follow
<input name='some-name[]' class='blah-blah' />
The main idea is to use [] that indicates that this named param would have multiple values .
And in your server side script you can receive it as some-name[0] & some-name[1] as if it was an array. simple.. try it out.


text:
Q: Roman numerals in notes list in enotez I want to use the package enotez because it allows you to click the endnote and link directly to the notes list. I need Roman numeral (lower case) numbers as superscripts for the endnotes. I can get this fine.
I can't, however, get the numerals in the list to b Roman numerals - they are still Arabic numerals. I've tried making a custom enotez-list as per the package instructions. This works for e.g. \textsuperscript{#1} but whatever I try I can't get a Roman numeral function to play with the #1 macro. Any thoughts? MWE below and print out of what the working, wrong version looks like.
\documentclass[11pt]{article}

\usepackage[counter-format=roman]{enotez}
\usepackage{hyperref}

\DeclareInstance{enotez-list}{custom}{paragraph}{
 notes-sep = \baselineskip ,
 format = \normalfont ,
 % number = \roman{#1} % broken attempt
 number = \enmark{#1}
}

\begin{document}

Hello life\endnote{This is an endnote.}

\printendnotes[custom]

\end{document}

A: The answer since v0.9a (2017-04-24) is: redefine \theendnote:
\documentclass[11pt]{article}

\usepackage{enotez}
\usepackage{hyperref}

\renewcommand\theendnote{\roman{endnote}}

\begin{document}

Hello life\endnote{This is an endnote.}

\printendnotes

\end{document}


text:
Q: Save the image from image view to another activity I have a grid view, which contains a lot of images, when any image from the grid is tapped it comes in the center zoomed in, now i can keep swiping left or right with the help of a gesture. What i want is to introduce another gesture which saves the image which is zoomed at that instance be saved in another activity. How can i achieve this.
Here is my code:
public class MainActivity extends Activity {

 private GridView gv;
 private Animator mCurrentAnimator;
 private int mShortAnimationDuration;
 private int j = 0;

 private final GestureDetector detector = new GestureDetector(new SwipeGestureDetector());
    private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;

 // Create Array thumbs resource id's:
 private int thumb[] = { R.drawable.one, R.drawable.two,
   R.drawable.three, R.drawable.four, R.drawable.five,
   R.drawable.six, R.drawable.seven,
   R.drawable.one, R.drawable.two, R.drawable.three,
   R.drawable.four, R.drawable.five, R.drawable.six,
   R.drawable.seven, R.drawable.eight,
   R.drawable.one };

 private ImageView expandedImageView;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  // Initialize the variables:
  gv = (GridView) findViewById(R.id.gridView);

  // Set an Adapter to the ListView
  gv.setAdapter(new ImageAdapter(this));

  // Set on item click listener to the ListView
  gv.setOnItemClickListener(new OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView<?> parent, View v, int pos,
     long id) {

    // Display the zoomed in image in full screen
    j = pos;
    zoomImageFromThumb(v, thumb[pos]);

   }
  });

  // Set the Animation time form the android defaults
  mShortAnimationDuration = getResources().getInteger(
    android.R.integer.config_shortAnimTime);

 }

 // Create an Adapter Class extending the BaseAdapter
 class ImageAdapter extends BaseAdapter {

  private LayoutInflater layoutInflater;

  public ImageAdapter(MainActivity activity) {
   // TODO Auto-generated constructor stub
   layoutInflater = (LayoutInflater) activity
     .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  }

  @Override
  public int getCount() {
   // Set the count value to the total number of items in the Array
   return thumb.length;
  }

  @Override
  public Object getItem(int position) {
   // TODO Auto-generated method stub
   return position;
  }

  @Override
  public long getItemId(int position) {
   // TODO Auto-generated method stub
   return position;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {

   // Inflate the item layout and set the views
   View listItem = convertView;
   int pos = position;
   if (listItem == null) {
    listItem = layoutInflater.inflate(R.layout.grid_item, null);
   }

   // Initialize the views in the layout
   ImageView iv = (ImageView) listItem.findViewById(R.id.thumb);

   // Set the views in the layout
   iv.setBackgroundResource(thumb[pos]);

   return listItem;
  }

 }

 private void zoomImageFromThumb(final View thumbView, int imageResId) {
  // If there's an animation in progress, cancel it immediately and
  // proceed with this one.
  if (mCurrentAnimator != null) {
   mCurrentAnimator.cancel();
  }

  // Load the high-resolution "zoomed-in" image.
  expandedImageView = (ImageView) findViewById(R.id.expanded_image);

  expandedImageView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (detector.onTouchEvent(event))
                    return true;
                else
                    return false;
            }
        });

  expandedImageView.setImageResource(imageResId);

  // Calculate the starting and ending bounds for the zoomed-in image.
  // This step
  // involves lots of math. Yay, math.
  final Rect startBounds = new Rect();
  final Rect finalBounds = new Rect();
  final Point globalOffset = new Point();

  // The start bounds are the global visible rectangle of the thumbnail,
  // and the
  // final bounds are the global visible rectangle of the container view.
  // Also
  // set the container view's offset as the origin for the bounds, since
  // that's
  // the origin for the positioning animation properties (X, Y).
  thumbView.getGlobalVisibleRect(startBounds);
  findViewById(R.id.container).getGlobalVisibleRect(finalBounds,
    globalOffset);
  startBounds.offset(-globalOffset.x, -globalOffset.y);
  finalBounds.offset(-globalOffset.x, -globalOffset.y);

  // Adjust the start bounds to be the same aspect ratio as the final
  // bounds using the
  // "center crop" technique. This prevents undesirable stretching during
  // the animation.
  // Also calculate the start scaling factor (the end scaling factor is
  // always 1.0).
  float startScale;
  if ((float) finalBounds.width() / finalBounds.height() > (float) startBounds
    .width() / startBounds.height()) {
   // Extend start bounds horizontally
   startScale = (float) startBounds.height() / finalBounds.height();
   float startWidth = startScale * finalBounds.width();
   float deltaWidth = (startWidth - startBounds.width()) / 2;
   startBounds.left -= deltaWidth;
   startBounds.right += deltaWidth;
  } else {
   // Extend start bounds vertically
   startScale = (float) startBounds.width() / finalBounds.width();
   float startHeight = startScale * finalBounds.height();
   float deltaHeight = (startHeight - startBounds.height()) / 2;
   startBounds.top -= deltaHeight;
   startBounds.bottom += deltaHeight;
  }

  // Hide the thumbnail and show the zoomed-in view. When the animation
  // begins,
  // it will position the zoomed-in view in the place of the thumbnail.
  thumbView.setAlpha(0f);
  expandedImageView.setVisibility(View.VISIBLE);

  // Set the pivot point for SCALE_X and SCALE_Y transformations to the
  // top-left corner of
  // the zoomed-in view (the default is the center of the view).
  expandedImageView.setPivotX(0f);
  expandedImageView.setPivotY(0f);

  // Construct and run the parallel animation of the four translation and
  // scale properties
  // (X, Y, SCALE_X, and SCALE_Y).
  AnimatorSet set = new AnimatorSet();
  set.play(
    ObjectAnimator.ofFloat(expandedImageView, View.X,
      startBounds.left, finalBounds.left))
    .with(ObjectAnimator.ofFloat(expandedImageView, View.Y,
      startBounds.top, finalBounds.top))
    .with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_X,
      startScale, 1f))
    .with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_Y,
      startScale, 1f));
  set.setDuration(mShortAnimationDuration);
  set.setInterpolator(new DecelerateInterpolator());
  set.addListener(new AnimatorListenerAdapter() {
   @Override
   public void onAnimationEnd(Animator animation) {
    mCurrentAnimator = null;
   }

   @Override
   public void onAnimationCancel(Animator animation) {
    mCurrentAnimator = null;
   }
  });
  set.start();
  mCurrentAnimator = set;

  // Upon clicking the zoomed-in image, it should zoom back down to the
  // original bounds
  // and show the thumbnail instead of the expanded image.
  final float startScaleFinal = startScale;
  expandedImageView.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
    if (mCurrentAnimator != null) {
     mCurrentAnimator.cancel();
    }

    // Animate the four positioning/sizing properties in parallel,
    // back to their
    // original values.
    AnimatorSet set = new AnimatorSet();
    set.play(
      ObjectAnimator.ofFloat(expandedImageView, View.X,
        startBounds.left))
      .with(ObjectAnimator.ofFloat(expandedImageView, View.Y,
        startBounds.top))
      .with(ObjectAnimator.ofFloat(expandedImageView,
        View.SCALE_X, startScaleFinal))
      .with(ObjectAnimator.ofFloat(expandedImageView,
        View.SCALE_Y, startScaleFinal));
    set.setDuration(mShortAnimationDuration);
    set.setInterpolator(new DecelerateInterpolator());
    set.addListener(new AnimatorListenerAdapter() {
     @Override
     public void onAnimationEnd(Animator animation) {
      thumbView.setAlpha(1f);
      expandedImageView.setVisibility(View.GONE);
      mCurrentAnimator = null;
     }

     @Override
     public void onAnimationCancel(Animator animation) {
      thumbView.setAlpha(1f);
      expandedImageView.setVisibility(View.GONE);
      mCurrentAnimator = null;
     }
    });
    set.start();
    mCurrentAnimator = set;
   }
  });
 }

 private class SwipeGestureDetector extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            try {
                if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {

                   if(thumb.length>j)
                    {
                        j++;

                        if(j < thumb.length)
                        {
                         expandedImageView.setImageResource(thumb[j]);
                            return true;
                        }
                        else
                        {
                            j = 0;
                            expandedImageView.setImageResource(thumb[j]);
                            return true;
                        }

                    }
                }
                else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {

                    if(j>0)
                    {
                        j--;
                        expandedImageView.setImageResource(thumb[j]);
                        return true;

                    }
                    else
                    {
                     j = thumb.length-1;
                     expandedImageView.setImageResource(thumb[j]);
                        return true;
                    }
                }
            }
                catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
        }
    }

}

I hope somebody finds a solution for me because it has taken a lot of time and i am failing after all my attempts. Thank-you.
My TRY
    private class SwipeGestureDetector extends
            GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                float velocityY) {
            try {
                if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
                        && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {

                    if (thumb.length > j) {
                        j++;

                        if (j < thumb.length) {
                            expandedImageView.setImageResource(thumb[j]);
                            return true;
                        } else {
                            j = 0;
                            expandedImageView.setImageResource(thumb[j]);
                            return true;
                        }

                    }
                } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
                        && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {

                    if (j > 0) {
                        j--;
                        expandedImageView.setImageResource(thumb[j]);
                        return true;

                    } else {
                        j = thumb.length - 1;
                        expandedImageView.setImageResource(thumb[j]);
                        return true;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }

        Bitmap bm = ((BitmapDrawable) expandedImageView.getDrawable())
                .getBitmap();
    }

    private void storeImage(Bitmap bm) {
        File pictureFile = getOutputMediaFile();
        String TAG = null;
        if (pictureFile == null) {
            Log.d(TAG, "Error creating media file, check storage permissions: ");// e.getMessage());
            return;
        }
        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            bm.compress(Bitmap.CompressFormat.PNG, 90, fos);
            fos.close();
        } catch (FileNotFoundException e) {
            Log.d(TAG, "File not found: " + e.getMessage());
        } catch (IOException e) {
            Log.d(TAG, "Error accessing file: " + e.getMessage());
        }
    }

    private File getOutputMediaFile() {
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.
        File mediaStorageDir = new File(
                Environment.getExternalStorageDirectory() + "/Android/data/"
                        + getApplicationContext().getPackageName() + "/Files");

        // This location works best if you want the created images to be shared
        // between applications and persist after your app has been uninstalled.

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }
        // Create a media file name
        String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm")
                .format(new Date());
        File mediaFile;
        String mImageName = "MI_" + timeStamp + ".jpg";
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + mImageName);
        return mediaFile;
    }

}

I have managed to complete it till here, could anyone please highlight my mistakes and guide me a little bit more?


text:
Q: Bash or Powershell to move files of a certain size to directories of a certain naming convention We have a list of clients under a top level "Clients" folder on a filer. Under the Clients folder are the actual client folders, some with the naming convention "client_test" others "111_1111". I need to scan all the subfolders for clients that will all have *_[0-9]like the 111_1111 client and replace the footer.jpg if it is 4903 bytes or less with a new footer.jpg. Basically if the client has modified the footer from the original we want to leave it but if not would like to overwrite the footer with a new rebranded footer. Any help much appreciated!

A: If you modify the paths as appropriate, I think this bit of PowerShell would do the trick. Test first to see if this rounds up the files you want to replace:
gci c:\Clients\*\footer.jpg |
   ?{($_.directory.name -match ''^\d+-\d+$') -and ($_.length -eq 4904)}

If that works, use the following:
gci c:\Clients\*\footer.jpg |
   ?{($_.directory.name -match '^\d+-\d+$') -and ($_.length -eq 4904)} |
       %{copy-item 'c:\NewArtwork\footer.jpg' "$($_.directory)\footer.jpg" -force}

*

*gci = Get-ChildItem

*?   = Where-Object

*%   = ForEach-Object

Keith


text:
Q: how to identify or recoginize a pattern in data with SQL I'm wondering if this is possible. I am trying to identify records where there is a pattern in the data.
Eg a table with fields ID, DATA_DTE (only daily records), SPEED.
I would like to identify when the field SPEED drops by at least 4 and holds for at least 3 consecutive days in a row
**ID**..**DATA_DTE**...**SPEED**
1........Jan-1............8
1........Jan-2............9
1........Jan-3............4
1........Jan-4............4
1........Jan-5............4
1........Jan-6............7
1........Jan-7............8
1........Jan-8............9

From the above, I basically want to have a SQL query return the ID. Eg "1" in the above eg.
Does anyone know how I can setup my SQL query to return these IDs which match a pattern like this? I'll be running it in ms access 2003.

A: I don't know ms access, but it might do the job:
SELECT DISTINCT id
FROM       data AS d1
INNER JOIN data AS d2 ON d1.id = d2.id AND DateAdd("d",+1,d1.data_dte) = d2.data_dte
INNER JOIN data AS d3 ON d1.id = d3.id AND DateAdd("d",+2,d1.data_dte) = d3.data_dte
INNER JOIN data AS d4 ON d1.id = d4.id AND DateAdd("d",+3,d1.date_dte) = d4.data_dte
WHERE d1.speed - d2.speed >= 4
  AND d1.speed - d3.speed >= 4
  AND d1.speed - d4.speed >= 4


text:
Q: I allocate a dynamic array of characters using pointer, and it gets run time exception? I wrote the following code, but when I allocate word in memory it gets NULL!
where is the problem with the following code? I forced to write in this why to split the lite into words :( please any help
void strSplit(const char *line, char *words[]){

    char *word = new char[81];
    int index = 0;
    int s = strlen(line);
    for(int i = 0; i < s; i++)
    {
        if(line[i] != ' ' && line[i] != ',' && line[i] != ';')
        {
            if(word == NULL)
            {
                strcpy(word, (line[i] + "\0"));
            }
            else
            {
                strcat(word, (line[i] + "\0"));
            }
        }
        else
        {
            if(word != NULL){
                strcpy(words[index], word);
                puts(words[index]);
                index++;
                puts(word);
                word = NULL;
            }
        }

    }
}

A: if (word == NULL) {
    strcpy(word, stuff);
}

This is suicide.


text:
Q: iFogSim: changing the default number of proxies or even any middle layer I'm working on a simulation scenario where I need to have a certain number of  nodes in the middle layers, such as proxies and gateways.
I saw in the refernce article of iFogSim2 that the number of proxies is 12 and the number of gateways is 118 by default.
Actually, I want to change that in order to make different simulation cases.
I tried to search for '118' and '12' in the whole workspace but I don't found the instruction which is responsible of that.
I also looked the config files, but... nothing!
Is there anyone who can help ?


text:
Q: TabBar rotation from portrait to landscape I am making a TabBar based universal app. I have added few extra tabs  and changed the viewController to navigationController. Now when i am trying to rotate the view from portrait to landscape, its rotating the inside view but tabBar does not rotate and it stays at the same place ie at the bottom of the portrait mode where as every other UI are rotating properly.

A: Make sure the controller not supporting the rotation (respectively its owner) overrides shouldAutorotateToInterfaceOrientation and returns YES for all orientations.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
#pragma unused(interfaceOrientation)
    // Overriden to allow any orientation.
    return YES;
}

http://developer.apple.com/library/ios/documentation/uikit/reference/UIViewController_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40006926-CH3-SW23