text:
Q: Authentication error in openStack's Horizon dashboard I'm trying to setup an openStack controller from a VirtualBox VM. My VirtualBox host is Windows 10 and the guest is Ubuntu Server 14. The guest should (someday) function as an openStack controller, and it should control a Compute node running on some x86 located somewhere in my network (I should later on control it through it's IP). Right now - I'm still in the earlier stage of trying to log on to my Horizon dashboard, but I keep getting an authentication error when I try to log into the openStack dashboard.
To sum it up:

*

*Running on Windows 10 as a host, where I made a bridge between my local Ethernet adapter, and VirtualBox's virtual Ethernet adapter. This way all machines are able to ping each other.

*I'm running an Ubuntu Server 14, on VirtualBox 5

*All machines can ping each other, and I can reach the Horizon dashboard log-in screen when I enter <IP>/horizon in my web browser.

*Upon entering username and password in dashboard - I get: An error occurred authenticating. Please try again later.
I've gone through numerous trials and ways to solve this - going through https://ask.openstack.org/en/questions/ , https://askubuntu.com/ , https://www.virtualbox.org ,  https://superuser.com/ and probably anything I could find on a google search.
Things I've noticed:

*

*Running the setup with no VM (just some three x86) works fine.

*I've had to adjust some Windows 10 features just to run VirtualBox,
so I thought maybe the Windows 10 and VBox 5 integration wasn't too
good, but working with VBox 4 didn't solve it either.

Has anyone else tried a VM included setup with openStack? Any Ideas?


text:
Q: How to deserialize Json with nested lists It's not my first time deserializing Json into c# classes but I am having some trouble when these Json have nested  lists. Here is the returned Json of a list of workOrders:
[
  {
    "_id": "5cacdda0b4e6d128a61187ca",
    "taskInstance": [
      {
        "_id": "5cacdda0b4e6d128a61187cc"
      }
    ],
    "isRunning": false
  },
  {
    "_id": "5cacebb0b4e6d128a61187d1",
    "taskInstance": [
      {
        "_id": "5cacebb0b4e6d128a61187d3"
      }
    ],
    "isRunning": false
  }
]

and here the C# classes:
WorkOrder
public class WorkOrder{
    public string Id { get; set; }
    public List<TaskInstance> TaskInstances { get; set; }
    public string IsRunning { get; set; }
}

and TaskInstance
public class TaskInstance{
    public string Id { get; set; }
}

And here is the code that I'm using to check the result:
JObject jsonResponse = JObject.Parse(data["data"].ToString());
string workOrderJson = jsonResponse["workOrderInstances"].ToString();
List<WorkOrder> wos = JsonConvert.DeserializeObject<List<WorkOrder>>(workOrderJson);

foreach (WorkOrder wo in wos){
    Debug.Log("WO _id: " + wo.Id);
    Debug.Log("wo.TaskInstances: "+ wo.TaskInstances);
    Debug.Log("WO isRunning: " + wo.IsRunning);
}

And while I'm seeing the correct values for WO._id and WO.isRunning wo.TaskInstances seems to be returning null or at leat throws a null reference exception whenever I try to access it.
I've searched other topics before but none of the solutions seem to work. I'm not sure what I am missing. Thank you for your help.
Disclaimer:
the raw data in JObject.Parse(data["data"] looks like this:
{
  "data": {
    "workOrderInstances": [
      {
        "_id": "5cacdda0b4e6d128a61187ca",
        "taskInstance": [
          {
            "_id": "5cacdda0b4e6d128a61187cc"
          }
        ],
        "isRunning": false
      },
      ...
     ]
  }
}

A: Use this model:
Because the problem with your model is:
JSON property name and model property name is not the same in your code.
So whenever you need your own custom name in property use
[JsonProperty("JsonPropertyName")]
 public partial class Root
    {
        [JsonProperty("_id")]
        public string Id { get; set; }

        [JsonProperty("taskInstance")]
        public TaskInstance[] TaskInstances { get; set; }

        [JsonProperty("isRunning")]
        public bool IsRunning { get; set; }
    }

    public partial class TaskInstance
    {
        [JsonProperty("_id")]
        public string Id { get; set; }
    }

Let me know if it works for you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: USB drive enabled but not showing in Windows 10 File Explorer I'm running VirtualBox 5.0.12 on a Mac, and I have a USB drive that is connected to my Mac. The VirtualBox says it is using the USB device, but the device is not showing up in File Explorer. The virtual machine has been shut down & rebooted, but the USB still doesn't show up. I think sometimes I can hear the Windows "USB connected" sound.
Edit: Windows device manager says "The device cannot start. An invalid parameter was passed to a service or function."

A: If its Virtual Box, are you sure you've installed the guest essentials? This is a requirement for Virtual Box to pick up external folders/shares from your home OS. I'm fairly sure this includes USB devices:
https://www.virtualbox.org/manual/ch04.html

Shared folders
  These provide an easy way to exchange files between the host and the guest. Much like ordinary Windows network shares, you can tell VirtualBox to treat a certain host directory as a shared folder, and VirtualBox will make it available to the guest operating system as a network share, irrespective of whether guest actually has a network. For details, please refer to Section 4.3, "Shared folders".

Installation:

In the "Devices" menu in the virtual machine's menu bar, VirtualBox has a handy menu item named "Insert Guest Additions CD image", which mounts the Guest Additions ISO file inside your virtual machine. A Windows guest should then automatically start the Guest Additions installer, which installs the Guest Additions into your Windows guest. Other guest operating systems (or if automatic start of software on CD is disabled) need manual start of the installer.

Although, this doesn't appear to be a thing for Mac right now:

Mac OS X guests:
  VirtualBox does not provide Guest Additions for Mac OS X at this time.

This forum might help: https://forums.virtualbox.org/viewtopic.php?f=8&t=45349

The way that I have found to solve this problem that seems to work almost every time is:

*

*Insert the USB drive,

*wait for OSX to mount the drive,

*eject the drive in Finder, and

*then select the Devices|USB Devices menu and select the USB drive to mount the drive.


text:
Q: Is it safe to just subscribe to Publishers in the assembly phase and leave it at that? I've asked in Gitter already but looks like it's not too active these days..
I was curious, is it safe to use such constructs in production code:
private Mono<Void> someHandler() {
        someService.registerPlayer(internalPlayer)
                        .subscribe();

        return Mono.empty();
    }

and then just use this Publisher from WebFlux controller method, for example?
do we have anything in the official documentation about it? All the examples I could find in the Reference, seem to be examples of calling reactive code from blocking code and observing behavior.
I guess this Disposable returned here will be GC-ed quite soon, right?
and what would be the right way to achieve similar result (emitting on the outer Publisher without having to wait till the inner Publisher completes; but making sure it's completed nevertheless)

A: If I understand you correctly, then it is basically a fire-and-forget scenario, but nothing prevents you from using additional operators on that chain to process the results.
If by "to beconfident that the subscription will complete" you mean "do something if it is completed successfully" or "do something if it is completed with error" then:
If you want to start some processing in a separate thread and return immediately, and also be confident in completion of that sepapate processing, then you can use both subscribeOn() and put some operators to that chain to handle the results of success or errors of that processing, just as you do when you build any reactive chain.
To handle the results you can use, for example, .map(), doOnNext(), flatMap(), switchIfEmpty(), etc., whatever fits your requirements,
To handle errors, you can use, for example, onErrorResume(), onErrorContinue(), onErrorMap(), onErrorReturn(), doOnError(), etc., whatever fits your requirements.
Here is an example how it would look like:
private Mono<Void> someHandler() {
    someService.registerPlayer(internalPlayer)
            // handle results
            .doOnNext(...)

            // handle errors
            .orErrorResume(...)
            // the whole subscription process will happen on the thread provided by the Scheduler you specified
            .subscribeOn(Schedulers.boundedElastic())
            .subscribe();
    // return immediately
    return Mono.empty();
}


text:
Q: Python Pandas add data in to column if it same key I need some help about Pandas
   model        timestamp
0  Punto  20200124_083155
1  Punto  20200124_163540
2  Doblo  20200124_122052
3  Doblo  20200124_150801
4  Panda  20200124_134350
5   Tipo  20200124_195955

I want it become to
   model        timestamp
0  Punto  20200124_083155;20200124_163540
1  Doblo  20200124_122052;20200124_150801
2  Panda  20200124_134350
3  Tipo   20200124_195955

Please, everybody help me, can give me some example?, thank so much.

A: You can use agg for that and concatenate the grouped data.
new_df = df.groupby('model')['timestamp'].agg(timestamp= lambda x: ';'.join(x))

print(new_df)
                             timestamp
model
Doblo  20200124_122052;20200124_150801
Panda                  20200124_134350
Punto  20200124_083155;20200124_163540
Tipo                   20200124_195955

new_df.reset_index(inplace=True)
print(new_df)

   model                        timestamp
0  Doblo  20200124_122052;20200124_150801
1  Panda                  20200124_134350
2  Punto  20200124_083155;20200124_163540
3   Tipo                  20200124_195955

A: Suppose you have:
df_new=pd.DataFrame()
df_new['name']=['Punto','Doblo','Doblo','Punto','Punto','Tipo']
df_new['date']=['20200124_083155','20200124_163540','20200124_122052','20200124_150801',
'20200124_134350','20200124_195955']

output:
name    date
0   Punto   20200124_083155
1   Doblo   20200124_163540
2   Doblo   20200124_122052
3   Punto   20200124_150801
4   Punto   20200124_134350
5   Tipo    20200124_195955

Use shift with groupby:
df_new['date2']=df_new.groupby('name').shift(-1)
df_new['date2']=';'+df_new['date2']
df_new['date2']=df_new['date2'].fillna('')

output:
name    date    date2
0   Punto   20200124_083155 ;20200124_150801
1   Doblo   20200124_163540 ;20200124_122052
2   Doblo   20200124_122052
3   Punto   20200124_150801 ;20200124_134350
4   Punto   20200124_134350
5   Tipo    20200124_195955

if you want to see it in the same column:
df_new['date3']=df_new['date']+df_new['date2']

output:
  name  date    date2   date3
0   Punto   20200124_083155 ;20200124_150801    20200124_083155;20200124_150801
1   Doblo   20200124_163540 ;20200124_122052    20200124_163540;20200124_122052
2   Doblo   20200124_122052     20200124_122052
3   Punto   20200124_150801 ;20200124_134350    20200124_150801;20200124_134350
4   Punto   20200124_134350     20200124_134350
5   Tipo    20200124_195955     20200124_195955

It is not concise. But this approach will ensure that you only have two dates in the column. Unlike with groupby and transform method


text:
Q: gadget in site with custom setting fields I'm wondering if the following is possible.
When you insert your gadget in a site page, you can config some settings such as height, border and url.
Is it possible to add custom fields to config the gadget?
For example, use selects the gadget (url), then additional fields appear.

A: There's workarounds to achieve such functionality (i.e. have a set of parameters for a script per sites page), but it's not possible to do specifically what you're asking. i.e. to put a parameter field on the script gadget interface.
Anyway, that seems like a real good enhancement Apps Script gadgets for Sites could have. You could open an enhancement request on Apps Script issue tracker.


text:
Q: How can i apply a color= argument to all plots in a dropdown menu How can i apply the color = 'sex' argument to all the plots?  it's only working on the first (G1 G2 G3) plot now... When I select G2/G3 from the dropdown menu the boxplot won't show the 'sex' from the dataframe.
dropdown_buttons = [{'label':'G1, G2, G3', 'method': 'update',
                 'args':[{'visible': [True, True, True]},
                        {'title': 'G1, G2, G3'}]},
                {'label':'G1', 'method': 'update',
                 'args':[{'visible': [True, False, False]},
                        {'title': 'G1'}]},
               {'label':'G2', 'method': 'update',
                 'args':[{'visible': [False, True, False]},
                        {'title': 'G2'}]},
               {'label':'G3', 'method': 'update',
                 'args':[{'visible': [False, False, True]},
                        {'title': 'G3'}]},
               ]

fig5 = go.Figure(px.box(students, x='age', y=['G1', 'G2', 'G3'], color = 'sex',
                   labels = {'age': 'Age', 'G3': 'G3', 'sex': 'Sex'}))

fig5.update_layout({'updatemenus':[{'type': "dropdown",
                              'x': 1.3,
                              'y': 0.5,
                              'showactive': True,
                              'active': 0,
                              'buttons': dropdown_buttons}]})

fig5.show()


text:
Q: How to remove Windows 7 partition and install Windows 10 I have a dual-boot with Windows 7 alongside Ubuntu 20.04. I'd like to upgrade Windows by removing W7 first and then install W10 from scratch.
Here is my disk lay-out:

*

*sda1: boot partition Windows

*sda2: Windows 7 installation

*(sda3: extended partition)

*sda5: /root partition of ubuntu

*sda6: swap partition

*sda7: /home partition

I assume I have to do following steps:

*

*Remove partition sda1 & sda2

*Install Windows 10 on the unallocated space

*Repair grub using boot-repair-disk or using a live-cd
ps 1: I've created a backup of my whole drive using clonezilla in case of..
ps 2: Both os are installed in bios mode hence no no efi partition
Should this give the desired result of having a dualboot with W10 alongside Ubuntu?
Do I overlook something?

A: I performed the above steps and all went well.
I summarize and mark this as the answer:

*

*Remove the boot partition of Windows (sda1) + Windows partition (sda2) (Ubuntu is still bootable)

*Install Windows on the unallocated space

*Windows will reboot after installation. From then on only Windows is bootable.

*Reboot from the boot-repair-disk and choose Recommended Repair. This will take some minutes. Review the log - normally it should have found Ubuntu & Windows OS partitions.

*Reboot again and now you should be presented with GRUB menu on boot

This process is really straightforward. Just pay attention to which partition(s) are assigned to Windows and always make a backup before you perform these steps (!).


text:
Q: how to retrieve attribute data-id values without clicking How do I retrieve all data-id attribute values? I have tried using jquery but only 1 id or 1 value is obtained
for my code

    <a href="" class="show_more comment-count-custom" id="show_more" data-idpost="<?= $p["id_post"] ?>">show more comments

jquery
var id = $(".show_more").data("idpost");
console.log(id)

the results that I got
but only 1 id or 1 value is obtained

A: To build an array of the data-idpost values from all .show-more elements you can use map():

var idData = $('.show_more').map((i, el) => el.dataset.idpost).get();
console.log(idData);

  show more comments

  show more comments

  show more comments

A: If the show_more class as multiple .You could use with Jquery#map() and jquery.get() api method

var ids = $(".show_more").map((i,elem)=> $(elem).data("idpost")).get()
console.log(ids)

    show more comments
    show more comments
    show more comments


text:
Q: Learning TensorFlow from PyTorch? I have mastered PyTorch proficiently. Is there any way or tutorial to learn TensorFlow efficiently?

A: You can start with this course provided by google.
https://developers.google.com/machine-learning/crash-course/first-steps-with-tensorflow/toolkit


text:
Q: Windows 8 OEM clean install error - Media driver is missing I'm trying to make a clean install of windows 8 on my new ASUS S46CB laptop. It uses an OEM key.
So, in order to make it, I created an bootable USB, using the microsoft media tools program (link)
I used a pendrive formated with NTFS and everything went fine.
EVERYTHING was done using an USB 2.0 port.
When I restarted my computer, I changed my BIOS settings to boot from my pendrive. After that, I could see the windows 8 installation setup. But when I tried to install I received the following message:
Load Driver
A media driver your computer needs is missing. This could be a DVD, USB or Hard disk driver. If you have a CD, DVD, or USB flash drive with the driver on it, please insert it now.
Note: If the installation media for Windows is in the DVD driver or on a USB drive, you can safely remove it from this step.
I tried to do everything again and again, believing I could have downloaded a corrupted file or something, however, It didn't work.
What should I do??


text:
Q: Excel VBA - insert bulk images in sheet I am using below vba code to get images in excel sheet but this code add images in sheet as link, so when i am sending sheet to another pc that person get image location not found error.
How can i add attach images in sheet instead of link of image???
Sub AddOlEObject()
    Dim mainWorkBook As Workbook

    Set mainWorkBook = ActiveWorkbook
    Sheets("Object").Activate
    Folderpath = "C:\phoenix"
    Set fso = CreateObject("Scripting.FileSystemObject")
    NoOfFiles = fso.GetFolder(Folderpath).Files.Count
    Set listfiles = fso.GetFolder(Folderpath).Files

    For Each fls In listfiles
        strCompFilePath = Folderpath & "\" & Trim(fls.name)
        If strCompFilePath <> "" Then
            If (InStr(1, strCompFilePath, ".jpg", vbTextCompare) > 1) Then
                counter = counter + 1
                Sheets("Object").Range("A" & counter).Value = fls.name
                Sheets("Object").Range("B" & counter).ColumnWidth = 50
                Sheets("Object").Range("B" & counter).RowHeight = 150
                Sheets("Object").Range("B" & counter).Activate
                Call insert(strCompFilePath, counter)
                Sheets("Object").Activate
            End If
        End If
    Next

End Sub

Function insert(PicPath, counter)
    'MsgBox PicPath
    With ActiveSheet.Pictures.insert(PicPath)
        With .ShapeRange
            .LockAspectRatio = msoTrue
            .Width = 100
            .Height = 150
        End With
        .Left = ActiveSheet.Range("B" & counter).Left
        .Top = ActiveSheet.Range("B" & counter).Top
        .Placement = 1
        .PrintObject = True
    End With
End Function

A: Is the Image a single image that you have saved in a personal directory that you use frequently? Also is the image saved as .JPEG?
why don't you use a simple VBA code below?
Sub CALLPICTURE()

Worksheets("SHEET1").Shapes.AddPicture Filename:="I:\Control\DECOMP\ Images\Zebra.jpg", linktofile:=msoFalse, _
            savewithdocument:=msoCTrue, Left:=0, Top:=0, Width:=632, Height:=136

End Sub

You could add as many images as you want to.


text:
Q: How to run aws configure on Amazon AWS EC2 automatically without interaction without prompt? I'm trying to set up Amazon AWS EC2 instance to talk to s3. The basic command is
aws configure

then follow the prompt to enter
AWS Access Key ID [None]: my-20-digit-id
AWS Secret Access Key [None]: my-40-digit-secret-key
Default region name [None]: us-east-1
Default output format [None]: text

However, what I really want is to have the command
aws configure

automatically without interaction, i.e., no prompt and wait for input
I know there are files at
~.aws/credentials
~.aws/config

where I put those 4 key=value pairs. And the "credentials" file looks like
[default]
aws_secret_access_key = my-40-digit-secret-key
aws_access_key_id = my-20-digit-id

while the "config" file looks like
[default]
region = us-east-1
output = text

However, with those file at ~/.aws/, I get into ~/.aws/, and at the command line, I type and enter command
aws configure

I still got the prompt to ask me
AWS Access Key ID [None]:
AWS Secret Access Key [None]:
Default region name [None]:
Default output format [None]:

If I don't enter valid values at prompt, I won't be able to connect to s3, for example via command
aws s3 ls s3://mybucket

I turned help to amazon aws documentation pages. At this page, it mentions this option
"Command line options – region, output format and profile can be specified as command options to override default settings."
as the first option for aws configure
https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html
However, it didn't mention how to use the command line options. I tried something like this
aws configure --region us-east-1

but I still got
AWS Access Key ID [None]:
AWS Secret Access Key [None]:
Default region name [None]:
Default output format [None]:

exactly like I have no option of "--region us-east-1"
If I try to
aws configure --aws_access_key_id my-20-digit-id --aws_secret_access_key my-40-digit-secret-key --region us-east-1

I get this
usage: aws [options] <command> <subcommand> [parameters]
aws: error: argument subcommand: Invalid choice, valid choices are:

How I can run the command
aws configure

automatically, no prompt, no interaction.
Please help! TIA
Edit and response to helloV, as the format in main post is much clearer than comment.
I tried the command helloV mentioned, but I got error
aws configure set aws_access_key_id my-20-digit-id
usage: aws [options] <command> <subcommand> [parameters]
aws: error: argument subcommand: Invalid choice, valid choices are:

Thanks though.
Continue on "aws configure set"
On another EC2 instance where I've already set connection to s3, I enter
aws configure set region us-east-1

runs and returns to command prompt ">"
aws configure set aws_access_key_id my-20-digit-id

runs and returns to command prompt ">"
aws configure set aws_secret_access_key my-40-digit-secret-key

runs and returns to command prompt ">"
aws configure

runs but comes with prompts and waits for interaction
AWS Access Key ID [****************ABCD]:
AWS Secret Access Key [****************1234]:
Default region name [us-east-1]:
Default output format [text]:

helloV:
here is my screen looks like
ubuntu@ip-11111:~/.aws$ more config
[default]
region = us-east-1
output = text
ubuntu@ip-11111:~/.aws$ more credentials
[default]
aws_secret_access_key = my-40-digit-secret-key
aws_access_key_id = my-20-digit-id
ubuntu@ip-11111:~/.aws$ aws s3 ls s3://

I got this
Unable to locate credentials. You can configure credentials by running "aws configure".

After this, I run
aws configure list
  Name                    Value             Type    Location
  ----                    -----             ----    --------
profile                <not set>             None    None
access_key                <not set>             None    None
secret_key                <not set>             None    None
region                us-east-1      config_file    ~/.aws/config

Looks like it does not check ~/.aws/credentials file, but ~/.aws/config file is in the list.

A: You describe the file very well. Why not just create a file and put it in the right place? I just tried... it's exactly the same as running aws configure
UPDATE: You mention that you want to access S3 from EC2 instance. In this case you shouldn't be using credentials at all. You should user Roles instead

A: These commands worked for me. If this doesn't works for you. Try do the first time using the interaction mode aws configure
aws --profile default configure set aws_access_key_id "my-20-digit-id"
aws --profile default configure set aws_secret_access_key "my-40-digit-secret-key"

A: I figured out, finally. Use export such as
export AWS_ACCESS_KEY_ID=my-20-digit-id
export AWS_SECRET_ACCESS_KEY=my-40-digit-secret-key
export AWS_DEFAULT_REGION=us-east-1

then run
aws s3 ls s3://

would work. Don't run "aws configure" as others mentioned.
Thank you all.

A: The solution is that you actually don't have to run aws configure! After you run it for the 1st time and established the credentials (~/.aws/credentials) and config (~/.aws/config), going forward you simply have to run the required aws command. I tested this with a cron job and did a "aws s3 ls" command and it worked without having to provide a configure command before it.

A: Follow this command
$aws configure set aws_access_key_id default_access_key
$ aws configure set aws_secret_access_key default_secret_key
$ aws configure set default.region us-west-2

or
aws configure set aws_access_key_id <key_id> && aws configure set aws_secret_access_key <key> && aws configure set default.region us-east-1

For more details use this link
https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configure/set.html

A: I use something like this:
aws configure --profile my-profile-name <<-EOF > /dev/null 2>&1
${AWS_ACCESS_KEY_ID}
${AWS_SECRET_ACCESS_KEY}
${AWS_REGION}
text
EOF

also to cleanup after automated process, and not remove `~/.aws/ directory (since some other credentials might be stored there) I run:
aws configure --profile my-profile-name <<-EOF > /dev/null 2>&1
null
null
null
text
EOF


text:
Q: Determining Process I Have data as below
Schedule
+------------+----------------+
|   Date     | Lesson Teacher |
+------------+----------------+
| 2018-01-03 | Math           |
| 2018-01-03 | English        |
| 2018-01-03 | Sports         |
| 2018-01-03 | Biology        |
| 2018-01-03 | Math           |
| 2018-01-03 | English        |
| 2018-01-03 | Sports         |
| 2018-01-03 | Biology        |
| 2018-01-04 | Math           |
| 2018-01-04 | English        |
| 2018-01-04 | Sports         |
| 2018-01-04 | Biology        |
+------------+----------------+

Teacher
+-------------+------------+-----------+
|   Lesson    |  Teacher   |  Priority |
+-------------+------------+-----------+
| Math        | Alex       |         1 |
| Math        | Bob        |         2 |
| Math        | Steve      |         3 |
| English     | Alex       |         1 |
| English     | Bertha     |         2 |
| Sports      | Noah       |         1 |
| Sports      | Steve      |         2 |
| Biology     | Bertha     |         1 |
| Biology     | Bob        |         2 |
+-------------+------------+-----------+

Every teacher only can teach 1 lesson in a date, so if the schedule already filled with first priority teacher the next will be fill with the second in the same date of lesson schedule. Does anyone can help?
thx

A: I would use the windows functions
select sch.date, sch.lesson, t.teacher
from teacher t
join
(
   select s.*,
        row_number() over (partition by date, lesson order by date) priority
   from schedule s
) sch on sch.lesson = t.lesson and t.priority = sch.priority

demo


text:
Q: Error while pushing NuGet-package into GitLab Package Registry -> NuGet.Temporary.Package I have trouble with pushing NuGet packages into our company GitLab package registry.
In my NuGet-Package I pack some binaries. Here is the Nuspec-file:
<?xml version="1.0" encoding="utf-8"?>
<package>
  <metadata>
    <id>test</id>
    <version></version>
    <authors>Company</authors>
    <description>Demo Project</description>
  </metadata>
  <files>
    <file src="../../__out/test/**" target="" />
  </files>
</package>

I build the nuget packages which looks good in CI (I have downloaded and inspected the nuget-file)
After the build I push the NuGet-Package with this CI job into the registry.
Gitlab CI:
deploy:
  stage: deployNuGet
  image: mcr.microsoft.com/dotnet/sdk:5.0-buster-slim
  script:
    - dotnet nuget add source "$CI_SERVER_URL/api/v4/projects/$CI_PROJECT_ID/packages/nuget/index.json" --name gitlab --username gitlab-ci-token --password $CI_JOB_TOKEN --store-password-in-clear-text
    - dotnet nuget push __out/package/test.0.0.1.nupkg" --source gitlab

This leads to following CI log:
$ dotnet nuget add source "$CI_SERVER_URL/api/v4/projects/$CI_PROJECT_ID/packages/nuget/index.json" --name gitlab --username gitlab-ci-token --password $CI_JOB_TOKEN --store-password-in-clear-text
Package source with Name: gitlab added successfully.
warn : No API Key was provided and no API Key could be found for 'https://XXXX/api/v4/projects/XXXX/packages/nuget'. To save an API Key for a source use the 'setApiKey' command.
Pushing test.0.0.1.nupkg to 'https://XXXXXX/api/v4/projects/XXXXX/packages/nuget'...
  PUT https://XXXXX/api/v4/projects/XXXXXX/packages/nuget/
  Created https://XXXXX/api/v4/projects/XXXXXX/packages/nuget/ 780ms
Your package was pushed.

This worked fine for quit a while, but now I get an different behavior.
The instead of the test package there is a NuGet.Temporary.Package.

When I move over the error sign it shows following message:
Invalide Package: failed metadate extraction

Does someone have an idea how to fix this issu?
Thank you!
Jan

A: This was a gitlab (14.0.x) error on self-managed AWS instances.
There is also an MR for fixing this.
Here is the issue with an sulution https://gitlab.com/gitlab-org/gitlab/-/issues/335488#note_623985000


text:
Q: Spatie Medialibrary Custom Custom Directory As Prefix I am using spatie/laravel-medialibrary:8.0.
When I uploaded file, it was saved in storage/public directory.
1/filename.file_extension, 2/filename.file_extension...

I think 1, 2... are ids of files.
Is there any way to put different prefix directory according to user?
For example, I want to put like this.
public/storage/user_id/1/filename.file_extension,

I searched about it but couldn't find exact answer,
Can anyone help me?
Thanks

A: The way to go it's under docs Using a custom directory structure.
To override the default folder structure, a class that conforms to the PathGenerator-interface can be specified as the path_generator in the config file.
For example, you can create a new class that extends that interface and return some path for your models
class CustomPathGenerator implements PathGenerator
{
    public function getPath(Media $media) : string
    {
        if ($media instanceof Post) {
            return 'user_id/' . $media->user_id . '/' . $media->id;
        }
        return $media->id;
    }

    public function getPathForConversions(Media $media) : string
    {
        return $this->getPath($media) . 'conversions/';
    }

    public function getPathForResponsiveImages(Media $media): string
    {
        return $this->getPath($media) . 'responsive/';
    }
}

Then update the config file and point to that class:
'path_generator' => CustomPathGenerator::class,

References:
spatie/laravel-medialibrary Docs Using a custom directory structure.
Laracasts Spatie MediaLibrary default storage depending on the model "best answer".


text:
Q: Compiling grpc gives CMake Error at cmake/cares.cmake I'm trying to build gRpc on ubuntu Docker, following https://chromium.googlesource.com/external/github.com/grpc/grpc/+/HEAD/BUILDING.md.
Here's how I'm trying to compile grpc on ubuntu focal (Docker):
RUN apt-get update && apt-get install build-essential autoconf libtool pkg-config cmake
RUN curl -L https://github.com/grpc/grpc/archive/v1.32.0.zip -o grpc-1.32.0.zip
RUN unzip grpc-1.32.0.zip \
    && cd grpc-1.32.0 \
    && mkdir -p cmake/build \
    && cd cmake/build \
    && cmake ../.. \
    && make -j \
    && make install

But I get:
CMake Warning at cmake/abseil-cpp.cmake:30 (message):
  gRPC_ABSL_PROVIDER is "module" but ABSL_ROOT_DIR is wrong
Call Stack (most recent call first):
  CMakeLists.txt:250 (include)

CMake Error at cmake/cares.cmake:25 (add_subdirectory):
  The source directory

    /tmp/grpc-1.32.0/third_party/cares/cares

  does not contain a CMakeLists.txt file.
Call Stack (most recent call first):
  CMakeLists.txt:253 (include)

CMake Warning at cmake/protobuf.cmake:51 (message):
  gRPC_PROTOBUF_PROVIDER is "module" but PROTOBUF_ROOT_DIR is wrong
Call Stack (most recent call first):
  CMakeLists.txt:255 (include)

CMake Warning at cmake/re2.cmake:41 (message):
  gRPC_RE2_PROVIDER is "module" but
  RE2_ROOT_DIR(/tmp/grpc-1.32.0/third_party/re2) is wrong
Call Stack (most recent call first):
  CMakeLists.txt:256 (include)

CMake Warning at cmake/ssl.cmake:55 (message):
  gRPC_SSL_PROVIDER is "module" but BORINGSSL_ROOT_DIR is wrong
Call Stack (most recent call first):
  CMakeLists.txt:257 (include)

CMake Warning at cmake/zlib.cmake:39 (message):
  gRPC_ZLIB_PROVIDER is "module" but ZLIB_ROOT_DIR is wrong
Call Stack (most recent call first):
  CMakeLists.txt:259 (include)

There's very little information about cares and grpc, I found this: https://stackoverflow.com/a/54819108/6655884, but I do not want to use cares, I want instead to use autotools build


text:
Q: How to proxy outbound LDAP traffic in AWS? I have several app servers in AWS/EC2, where customers may use their LDAP implementations to authentication into our product.
Some of our customers cannot whitelist us by FQDN.
The app servers will be using iptables/NAT to send that LDAP traffic (port varies by customer) to a 'proxy machine' which should then forward that traffic out to it's destination.
iptables -t nat -A OUTPUT -p tcp --dport 389 -j DNAT --to-destination x.x.x.x:3128

iptables -A FORWARD -p tcp -d x.x.x.x --dport 3128 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT

As you might have guessed by the port - initially this proxy had Squid installed. I could verify via tcpdump that LDAP traffic was getting to that box on that port, but Squid would never pick up on it or do anything with it.
Failing to find any working examples online, I've moved to HAProxy - largely to a similar result.  I also can't find any documentation of HAProxy being used in this manner - with most of it largely being a reverse proxy, or a load balancer.
I've explored setting up a iptables based router as well, but AWS is preventing public IPs on machines with 2 Ethernet interfaces.

A: This is extremely straightforward in HAProxy.  The thing you're overlooking is that in this configuration, HAProxy is still performing the role of a reverse proxy.  The "backend" is the customer's LDAP server, an the frontend is only accessible to you.
listen label_for_the_proxy
    bind 0.0.0.0:389
    mode tcp
    server label_for_the_server 203.0.113.111:389 check rise 1 fall 2 inter 60000 fastinter 5000 downinter 2000 on-error sudden-death

This is a combination frontend and backend configuration.
Connect to port 389 on this instance, and you'll find yourself talking to the customer's LDAP server.  Note that this example is taken from a working environment similar to what you describe, but this configuration, as shown, must not be assumed to be sufficiently secure.
You don't want to transport LDAP in the clear across the Internet.  In the environment where I'm using this, it's very similar to your application, except the HAProxy is in the middle of a couple of IPSec tunnels, which is why there is no TLS.    But that has no impact on the principles of the configuration.


text:
Q: Installing node packages like ts-java and others and keep getting node-gyp issues I am running an Ec2 with Amazon and have node 7 installed successfully. I have also made sure that node-gyp is installed. I am currently trying to add on some other packages for titan-gremlin functionality and every install I get the same error message.
/root/.nvm/versions/node/v7.0.0/bin/ts-java -> /root/.nvm/versions/node/v7.0.0/lib/node_modules/ts-java/bin/ts-java.sh
/root/.nvm/versions/node/v7.0.0/bin/ts-java.js -> /root/.nvm/versions/node/v7.0.0/lib/node_modules/ts-java/bin/ts-java.js

> java@0.7.2 install /root/.nvm/versions/node/v7.0.0/lib/node_modules/ts-java/node_modules/java
> node-gyp rebuild

sh: node-gyp: command not found
/root/.nvm/versions/node/v7.0.0/lib
└── (empty)

npm ERR! Linux 4.4.35-33.55.amzn1.x86_64
npm ERR! argv "/root/.nvm/versions/node/v7.0.0/bin/node" "/root/.nvm/versions/node/v7.0.0/bin/npm" "install" "-g" "ts-java"
npm ERR! node v7.0.0
npm ERR! npm  v3.10.8
npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn

npm ERR! java@0.7.2 install: `node-gyp rebuild`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the java@0.7.2 install script 'node-gyp rebuild'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the java package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-gyp rebuild
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs java
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls java
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /root/npm-debug.log
npm ERR! code 1

I am at the end of my rope. I have made sure that the node-gyp is accessible to all users. please help.
Here is debug log
    verbose lifecycle java@0.7.2~install: PATH:      /root/.nvm/versions/node/v7.0.0/lib/node_modules/npm/bin/node-gyp-  bin:/root/.nvm/versions/node/v7.0.0/lib/node_modules/ts-java/node_modules/java/node_modules/.bin:/root/.nvm/versions/node/v7.0.0/lib/node_modules/ts-java/node_modules/.bin:/root/.nvm/versions/node/v7.0.0/lib/node_modules/.bin:/root/.nvm/versions/node/v7.0.0/bin:/usr/local/sbin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/aws/bin:/root/bin
11008 verbose lifecycle java@0.7.2~install: CWD: /root/.nvm/versions/node/v7.0.0/lib/node_modules/ts-java/node_modules/java
11009 silly lifecycle java@0.7.2~install: Args: [ '-c', 'node-gyp rebuild' ]
11010 info lifecycle java@0.7.2~install: Failed to exec install script
11011 verbose unlock done using /root/.npm/_locks/staging-bbc034c0b63d0621.lock for /root/.nvm/versions/node/v7.0.0/lib/node_modules/.staging
11012 silly rollbackFailedOptional Starting
11013 silly rollbackFailedOptional Finishing
11014 silly runTopLevelLifecycles Finishing
11015 silly install printInstalled
11016 verbose stack Error: java@0.7.2 install: `node-gyp rebuild`
11016 verbose stack spawn ENOENT
11016 verbose stack     at ChildProcess.<anonymous> (/root/.nvm/versions/node/v7.0.0/lib/node_modules/npm/lib/utils/spawn.js:33:16)
11016 verbose stack     at emitTwo (events.js:106:13)
11016 verbose stack     at ChildProcess.emit (events.js:191:7)
11016 verbose stack     at maybeClose (internal/child_process.js:877:16)
11016 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
11017 verbose pkgid java@0.7.2
11018 verbose cwd /root
11019 error Linux 4.4.35-33.55.amzn1.x86_64
11020 error argv "/root/.nvm/versions/node/v7.0.0/bin/node" "/root/.nvm/versions/node/v7.0.0/bin/npm" "install" "-g" "ts-java"
11021 error node v7.0.0
11022 error npm  v3.10.8
11023 error file sh
11024 error code ELIFECYCLE
11025 error errno ENOENT
11026 error syscall spawn
11027 error java@0.7.2 install: `node-gyp rebuild`
11027 error spawn ENOENT
11028 error Failed at the java@0.7.2 install script 'node-gyp rebuild'.
11028 error Make sure you have the latest version of node.js and npm installed.
11028 error If you do, this is most likely a problem with the java package,
11028 error not with npm itself.
11028 error Tell the author that this fails on your system:
11028 error     node-gyp rebuild
11028 error You can get information on how to open an issue for this project with:
11028 error     npm bugs java
11028 error Or if that isn't available, you can get their info via:
11028 error     npm owner ls java
11028 error There is likely additional logging output above.
           11029 verbose exit [ 1, true ]

A: I ended up needing to install gyp using
sudo yum install gyp

Thanks to anyone who took the time to look at the question.


text:
Q: How to create a Vultr.com-like user interface demonstration In https://www.vultr.com/, they have a frame with a video-like demo of their UI.
It's not actually video - the text is selectable.
Is there a specific library used for this?

A: I whet to they sites, I opened my console and typed for (let script of document.scripts) console.log(script.src) to see all scripts running there from external sources. The output is as you see:
"https://www.google-analytics.com/analytics.js"
"https://www.vultr.com/dist/js/jquery.min.js?v=250"
"https://www.vultr.com/dist/js/core.min.js?v=250"
"https://www.vultr.com/dist/js/main.js?v=250"
"https://www.vultr.com/_js/global.js?v=250"
""
"https://www.googleadservices.com/pagead/conversion.js"

then copied the forth URL into another tab, and got the file content which beginning is as follow: (I choose it because it wasn't minified)
    $(function()
{
  'use strict';

  handleMainMenu();
  handleResponsiveSidebar();
  handleAccordionMenu();
  handleTooltips();
  handleFloatingLabels();
  handlePackageSwitcher();
  checkBoxes($('body'));

  var animation_offset_px = 200;
  if (typeof onGetAnimationOffsetPx === 'function')
  {
    animation_offset_px = onGetAnimationOffsetPx();
  }
  handlePageAnimations(animation_offset_px);

  if ($('body').hasClass('page-scrollspy'))
  {
    handleScrollSpySidebar();
  }

  $('.reponsive-image-types > li > a').on('click', function(e)
  {
     e.preventDefault();
     var imageType = $(this).data('type');
     var imagePreview = $('.responsive-image .browser');
     imagePreview.removeClass('desktop-size tablet-size mobile-size').addClass(imageType);
     $(this).closest('ul').find('li').removeClass('active');
     $(this).parent().addClass('active');
     imagePreview.find('.control-panel').removeClass('animated');
     setTimeout(function()
         {
       imagePreview.find('.control-panel').addClass('animated');
     }, 1000);
  });

And as far as I can see, the wisdom of select-ability is defined in that function: (check the source of that script, even scripts) there is only 2 occurrences


text:
Q: How do you get the Youtube channel picture I want to get Youtube Channel's picture. For getting Video picture it's so simple: http://img.youtube.com/vi/" + item.VideoId + "/mqdefault.jpg

A: Solved.
var json = new WebClient().DownloadString("http://gdata.youtube.com/feeds/api/users/"+YT_CHANNEL_NAME);
        string str = "thumbnail url='";
        string ImagePic = json.Substring(json.IndexOf("thumbnail url") + str.Length);
        if (ImagePic.Contains("'"))
        {
            ImagePic = ImagePic.Remove(ImagePic.IndexOf("'"));
            ImageChannel.ImageUrl = ImagePic;

        }


text:
Q: How to solve $\sqrt{2-x} = x$ How I see it:
$$(\sqrt{2-x})^2 = x^2 $$
$$2-x = x^2 \implies x^2 + x - 2 = 0$$
$$x^2 + x - 2 = (x+2)(x-1)$$
So the solutions for $x$ are $-2$ or $1$, but my textbook says $1$ is the only answer.
If I solve for $x=-2$ then I get $\sqrt{2-(-2)}=-2 \implies \pm2 = -2$
so isn't it true that $-2$ or $2$ equals $-2$? Shouldn't $-2$ also be a solution?

A: $$\sqrt{2-x} = x \implies 2-x = x^2$$ by squaring both sides, so after solving this quadratic, we'll need to check other solutions in case we introduced any spurious solutions. Anyway, on we go! $$2-x = x^2 \iff (x+2)(x-1) = 0$$
So $x=-2$ or $x=1$ satisfies the quadratic. Check both solutions in the original equation and throw away the one that does not work.
Basically, the spurious solution problem arises since $a=b \implies a^2 = b^2$ but this is only a one-way implication, the reverse isn't true. So you cannot say $a = b \iff a^2 = b^2$ because that just isn't true. What if $b=-a$?

A: This is a common mistake that a lot of people fall into.  When they see $\sqrt{9}$ for example, they might say "this is the number such that when you square it you get $9$" and so they get $\sqrt{9} = \pm 3$.  But this is wrong.
When you see the square root of something, the thing you should say to yourself is "this is the positive number such that when you square it, you get the other number".  So $\sqrt{81}$ is the positive number such that when you square it, you get $81$.  So $\sqrt{81} = 9$.
Now, if you are asking for the solutions of $x^{2} = 81$, then this would be $x = \pm \sqrt{81} = \pm 9$, but the square root of a number is always positive.  So you are asking yourself the question to solve $x^{2} = 81$, but you are asking it for when trying to find $\sqrt{81}$, and that is where you are going wrong.

A:
What this equation is saying is that a function on the left hand side is the same as the function on the right hand side. And you are trying to find the value of x that makes this statement true. That being said your explanation is correct if you consider each side of these equations as IMPLICIT equations. The image above shows the function "x" in blue, and the function "$\sqrt{2-x}$" in red. If you consider "$\sqrt{2-x}$" as an implicit equation, instead of a function you get the green and read curves together, and where they intersect with the blue function, those are your solutions.

A: No, $-2$ should not be a solution. The square root of a positive number is by definition always positive, meaning that $\sqrt{4}=2$ and not $\sqrt{4}=\pm 2$. Thus you only get $2=-2$ which is obviously not true.
Another way to look at it: squaring both sides of an equation does not need to be an equivalent transformation. An easy example to consider would be $$1=x \iff (1)^2=(x)^2 \iff \pm1=x,$$ so from $x=1$ we somehow get two solutions $x=\pm 1$.
So whenever you square both sides of an equation, you might get false solutions. To avoid this, you either check every solution you get in the original equation, or you first determine when LHS/RHS of the equation are both positive.

A: Hint:
since $\sqrt{2-x}\ge 0$ (by definition of square root) and it is real-defined only if $2-x\ge 0$ we have:
$$
\sqrt{2-x}=x \iff
\begin{cases}
2-x \ge 0\\
x \ge 0\\
2-x=x^2
\end{cases}
$$
in general: the solution of an equation of the form $\sqrt{A}=B$ is equivalent to the system:
$$
\begin{cases}
A\ge 0\\
B \ge 0\\
A=B^2
\end{cases}
$$

A: The important concepts here are equivalence and implications. The operation to square both sides is not an equivalence relation $\Leftrightarrow$. This means that the sets of solutions do not need to be the same before as after.
Squaring is a forward implication $\Rightarrow$ which means that all solutions will be preserved - we are sure to not lose any solution on the way.
But it is not a backward implication $\Leftarrow$, which would mean that the solution set on the right would be preserved when going to the left.
So all in all we are sure that after squaring all solutions to the original equation will be preserved, but that there may also be introduced other, new solutions.


text:
Q: Is there a way to make elements be relative to a position:fixed element? I have a navbar at the top of the page that I want to be fixed. The problem is that if I make it fixed as opposed to absolute or something, stuff that would normally be below it takes its place and it sits on top making the content invisible. Any way I can get them to notice the fixed element and position accordingly without having to position:absolute or position:relative all of them?

A:

nav{
  width: 100%;
  position: fixed;
  top:0;

}

A: Apply a margin-top or padding-top to the first non-fixed element on the page, with a value as high as the height of the fixed-position navbar. Typically that element would be main, the first section or similar, possibly also simply the first (non-fixed) div, depending on your page structure.


text:
Q: Printing the value of the keywords field of the YAML header in a Markdown file as an inline list This question is a spin-off from Writing thanks and keywords from Markdown to docx via Pandoc.
In my specific setting I am converting the contents of a Markdown file to a docx document via Pandoc. The Markdown file opens with a YAML header for certain metadata among which is a list of keywords as required by the publisher for the target docx document. This list is entered as the value of the keywords YAML field as per the MWE below.
My problem is that the list is printed in the target document as a paragraph list; i.e. it starts a new paragraph and each item is printed in its own paragraph. The wished for output is instead an inline list; i.e., a single (logical, not necessarily typographic) line of items (the keywords) separated by some constant delimiter (in my case, a comma, but this particular is unsubstantial).
How can this be achieved?
---
title: The Title
author: The Author
thanks: |
  The author wishes to thank certain support.
abstract: |
  This is the abstract.
keywords: [one, two, three, four]
---

# A Heading

Text body.

I have considered a Lua filter along the lines of
function Meta (meta)
  meta.abstract = meta.abstract .. {pandoc.Emph("Keywords: ")} .. meta.keywords
  return meta
end

but this returns precisely the list of keywords as a paragraph list rather than an inline list.

A: Pandoc tries to guess what we want, but in this case we should be a bit more explicit: we intersperse comma and space separators between the keywords, then use that to construct a separate paragraph for keywords:
function Meta (meta)
  -- insert comma and space between keywords
  local keywords, sep = pandoc.Inlines{}, pandoc.Inlines ', '
  for i, kw in ipairs(meta.keywords or {}) do
    keywords:extend(kw)
    if i ~= #meta.keywords then
      keywords:extend(sep)
    end
  end

  -- Append keywords paragraph to abstract
  meta.abstract = meta.abstract ..
    {pandoc.Para({pandoc.Emph 'Keywords: '} .. keywords)}
  return meta
end


text:
Q: Shuffling string list in C# Windows phone 7 I've looked everywhere on how to shuffle/randomize a string list in C# for the windows phone 7. I'm still a beginner you could say so this is probably way out of my league, but I'm writing a simple app, and this is the base of it. I have a list of strings that I need to shuffle and output to a text block. I have bits and pieces of codes I've looked up, but I know I have it wrong. Any suggestions?

A: The Fisher-Yates-Durstenfeld shuffle is a proven technique that's easy to implement. Here's an extension method that will perform an in-place shuffle on any IList<T>.
(It should be easy enough to adapt if you decide that you want to leave the original list intact and return a new, shuffled list instead, or to act on IEnumerable<T> sequences, à la LINQ.)
var list = new List<string> { "the", "quick", "brown", "fox" };
list.ShuffleInPlace();

// ...

public static class ListExtensions
{
    public static void ShuffleInPlace<T>(this IList<T> source)
    {
        source.ShuffleInPlace(new Random());
    }

    public static void ShuffleInPlace<T>(this IList<T> source, Random rng)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (rng == null) throw new ArgumentNullException("rng");

        for (int i = 0; i < source.Count - 1; i++)
        {
            int j = rng.Next(i, source.Count);

            T temp = source[j];
            source[j] = source[i];
            source[i] = temp;
        }
    }
}


text:
Q: Split a string using a whitespace and CRLF as delimiters C++ I have a piece of code that currently splits a string using a whitespace as a delimiter. Each token is stored collectively in a vector of strings.The split function is show below:
vector<string> split(const string &s, char delim) {
    stringstream ss(s);
    string item;
    vector<string> tokens;
    while (getline(ss, item, delim)) {
        tokens.push_back(item);
    }
    return tokens;
}

The vector is defined as such:
vector<string> mocapVector = split(buffer.str(), ' ');

Example output of the vector can be seen here,  where an item of the vector is outputted, and the console is shown alongside the original data file (the entire string before it is split.
To reiterate:
a b c
d e f
g h i

gets outputted  as:
a

b

c
d

e

f
g

h

i

In the example, only the whitespace is a delimiter, and not CRLF (end of line).
My question is, how can I use both whitespace AND CRLF as delimiters simultaneously, so that each string in the vector is a single token, and not clumps of tokens together?
Ideally would like to avoid using external libraries if at all possible.
Thank you!
EDIT: Solution has been found thanks to @mindriot and @πάνταῥεῖ .
The solution is:
vector<string> split(const string &s, char delim) {
        stringstream ss(s);
        string item;
        vector<string> tokens;
        while (ss >> item) {
            tokens.push_back(item);
        }
        return tokens;
    }

Thanks to all who responded!


text:
Q: j2me lwuit list take the same cell background I am making a list that has persons and every ones rate as a cell background
the list gives every cell the same rate background but when scroll the list up or down the cell that I'm dragging take it's real rate background but other cells stay the same rate background image
I'm using nokia s40 full touch emulator
This is the code that I'm using for the cell renderer
    list.setRenderer(new ListCellRenderer() {

        public Component getListFocusComponent(List list) {
            // TODO Auto-generated method stub
            return null;
        }

        public Component getListCellRendererComponent(List list,
                Object value, int index, boolean isSelected) {
            String rate = "";

            rate = Transportation.getDriverRate(value.toString(),
                    CityListForm.selectedCity);
            rate = (Integer.parseInt(rate)) > 25 ? "" + 5 : ""
                    + Integer.parseInt(rate) / 5;
            rate = "/" + rate + ".png";
            Image image = null;
            Label label = null;
            try {

                image = (Image.createImage(rate));
                System.out.println(rate);
            } catch (IOException e) {
                e.printStackTrace();
            }
            label = new Label();

            label.getStyle().setBgImage(image);
            label.setText(value.toString());
            label.getStyle().setAlignment(RIGHT);
            label.setTextPosition(RIGHT);
            Style style = label.getStyle();
            style.setBgColor(16777215);
            style.setFgColor(0);

            label.setPreferredH(42);
            return label;
        }
    });

A: Use List.setMutableRendererBackgrounds(true);

A: thnx for the answer
i solved it by making a container and butting two labels inside it one for the value and the other for the rate icon and give the container a layout and return the container in the getListCellRendererComponent() method


text:
Q: Is there any way to make steam ask for guard every time? Yes, I know it's weird! But there is any way I can do it from steam files?
For example, by editing the loginusers.vdf?

A: This should be possible by making sure "Remember me" is not checked when logging in. With that Steam will always need to re-authenticate to login.
And yes, changing the value of "RememberMe" to "0" in loginusers.vdf should force it to need to re-authenticate, or you can just logout of the Steam client.


text:
Q: Which fork of GitX is the most active? I've been using the original GitX but I've noticed it hasn't had any updates for quite a while. Which version of GitX is the most active, in terms of updates/stability/features?

*

*The original (Screenshots & Info)

*The brotherbard fork (Screenshot)

*Germán Laullón's fork (Screenshots & Info)

*Some other fork?

A: Judging by the commit histories, I'd say Laullón's fork.
Update to this answer, Judging by the commit histories, I'd say rowanj's fork now a days. Download link is in the Readme.md with lots of changes!


text:
Q: html dropdownlist helper in javascript I'd to set a local javascript variable to the output of an html helper. See the following snippet for an example:
<script type="text/javascript">
     $(function () {
              var dtypes = '@Html.DropDownList("TypeId",new SelectList(@ViewBag.MyTypes,"Value","Text"))';
      });
      alert(dtypes);
</script>

This doesn't give me an alert. Am I doing something wrong?
Thanks for any help.

A: You should encode your html to be valid JavaScript string:
<script type="text/javascript">
 $(function () {
          var dtypes = '@Ajax.JavaScriptStringEncode(Html.DropDownList("TypeId",new SelectList(@ViewBag.MyTypes,"Value","Text")))';
  });
  alert(dtypes);
</script>

A: You could simply use @Ajax.JavaScriptStringEncode("") and \ in the string  before quotation mark.
Your code would be:
var dtypes = '@Ajax.JavaScriptStringEncode("Html.DropDownList(\"TypeId\",
   new SelectList(@ViewBag.MyTypes,\"Value\",\"Text\"))")';

A: Encode your html helper with @Ajax.JavascriptStringEncode(); And dont forget to convert the Html.DropDownList Helper to string with .ToString().
Here is an example:
<script type="text/javascript">
    $(function () {
      var dtypes = '@Ajax.JavaScriptStringEncode(Html.DropDownList("TypeId",new SelectList(@ViewBag.MyTypes,"Value","Text")).ToString())';
     });
    alert(dtypes);
</script>


text:
Q: Measuring and analyzing survey data I am in charge of creating a new survey for a food education/cooking class program for middle and high school students. The overall goal of the program is to improve overall knowledge and confidence when it comes to cooking and making healthier choices. The survey aims to evaluate the program impact and behavior changes. I am unsure of the best survey method and statistical analysis for a program like this. Any thoughts?

A: I used to work at a research analyst for a grant funded program at local MS/HSs. Usually, with a survey like this, I would recommend using Qualtrics (https://www.qualtrics.com/). If you're not tech savvy, it'll simplify the data collection process and analysis.
You can create a free account that accepts up to about 1500 responses. You can then export the data to Excel or whatever.

The survey aims to evaluate the program impact and behavior changes. I am unsure of the best survey method and statistical analysis for a program like this. Any thoughts?

As for the survey itself, I recommend reviewing what exactly you want to show/prove with the results, and how that should be measured. Also, if there is an intervention program being implemented, it would behoove you to conduct a pre- and post- survey with the same students for comparable results.
For the analysis, I would keep things simple with means and proportions. Don't over complicate the solution to the problem.
I can adjust this response based on any specific questions you may have. Feel free to ask anything!


text:
Q: is PeekMessageW function actually dispatching the message? In the documentation for Microsoft, it states PeekMessageW dispatch the message if any.
But why in this case is there the  need of a DispatchMessageW function ?  The few example I could gather use both together, calling DispatchMessage after PeekMessage/GetMessage.
I also can observe experimentally that peekMessage does not dispatch the message but seems to only give a look at the message queue.

A: The behavior of PeekMessageW is documented:

During this call, the system delivers pending, nonqueued messages, that is, messages sent to windows owned by the calling thread using the SendMessage, SendMessageCallback, SendMessageTimeout, or SendNotifyMessage function. Then the first queued message that matches the specified filter is retrieved.

Messages and Message Queues explains the terminology as well as the underlying principles.


text:
Q: Want to forcely enable Pjax in IE9 in yii2 Some here now, I am in such situation that I need to use Pjax for IE9 in yii2.As I already proceed with many Pjax forms ..reverting back to ajax is not a good option for me.. Anywhere can help me .. for this..

A: No, it doesn't work in IE < 10. So have to use jquery .ajax function and make a server request.


text:
Q: Change HSQL database in Java EE web project I have two projects: one for JPA persistence and other for the Java EE Web project which uses the ZK framework.
For the database I am using HSQL with the persistence-unit defined as follows:
<persistence-unit name="rubioseq-database" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>sing.proyectosi.Employee</class>
    <class>sing.proyectosi.Department</class>
    <class>sing.proyectosi.Project</class>
    <properties>
        <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />
        <property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver" />
        <property name="hibernate.connection.username" value="sa" />
        <property name="hibernate.connection.password" value="" />
        <property name="hibernate.show_sql" value="true" />
        <property name="hibernate.connection.url" value="jdbc:hsqldb:file:data/store" />
        <property name="hibernate.hbm2ddl.auto" value="create" />
    </properties>
</persistence-unit>

Well, and the web project uses this persistence unit. My issue is the following: the HSQL files are stored under my home directory (/home/user/data/store) and I wonder if there is any way of specifying a route relative to the project path.
Thank you very much for your help.

A: The path to the database is defined below. You need to change it to include a variable that equals a directory path defined in your JEE web:
<property name="hibernate.connection.url" value="jdbc:hsqldb:${mydbpath}/store" />

See the Guide:
http://www.hsqldb.org/doc/2.0/guide/dbproperties-chapt.html#dpc_variables_url


text:
Q: Compilar pango: ERROR: Tried to override dependency 'glib-2.0' which has already been resolved or overridden Estoy tratando de compilar Pango:
./make-release.sh

Las últimas líneas de la salida de la consola de bash:
glib| Checking if "atomic ops define" compiles: YES
glib| Run-time dependency threads found: YES
glib| Header <pthread.h> has symbol "pthread_attr_setstacksize" : YES
glib| Header <pthread.h> has symbol "pthread_attr_setinheritsched" : YES
glib| Header <pthread.h> has symbol "pthread_condattr_setclock" : YES
glib| Header <pthread.h> has symbol "pthread_cond_timedwait_relative_np" : NO
glib| Header <pthread.h> has symbol "pthread_getname_np" : YES
glib| Header <sys/syscall.h> has symbol "SYS_sched_getattr" : YES
glib| Checking if "pthread_setname_np(const char*)" with dependency threads links: NO
glib| Checking if "pthread_setname_np(pthread_t, const char*)" with dependency threads links: YES
glib| Checking if "stack grows check" runs: NO (1)
glib| Checking for function "iconv_open" : YES
glib| Run-time dependency libpcre found: YES 8.39
glib| Library m found: YES
glib| Run-time dependency libffi found: YES 3.2.1
glib| Run-time dependency zlib found: YES 1.2.11
glib| Checking for function "ngettext" : YES
glib| Checking for function "bind_textdomain_codeset" : YES
glib| Run-time dependency mount found: YES 2.27.0
glib| Run-time dependency libselinux found: NO (tried pkgconfig and cmake)
glib| Checking for function "getxattr" : YES
glib| Has header "sys/xattr.h" : YES
glib| Checking if "XATTR_NOFOLLOW" compiles: NO
glib| Checking for function "strlcpy" : NO
glib| Checking if "/proc/self/cmdline" runs: YES
glib| Program python3 found: YES (/usr/bin/python3)
glib| Program bash found: YES (/bin/bash)
glib| Run-time dependency bash-completion found: NO (tried pkgconfig and cmake)
glib| Program sh found: YES (/bin/sh)
glib| Program env found: YES (/bin/env)
glib| Configuring glibconfig.h using configuration
glib| Dependency sysprof-capture-4 skipped: feature sysprof disabled

subprojects/glib/glib/meson.build:408:8: ERROR: Tried to override dependency 'glib-2.0' which has already been resolved or overridden at /initrd/mnt/dev_save/descargas/pango-master/pango-master/meson.build:206:

A full log can be found at /initrd/mnt/dev_save/descargas/pango-master/pango-master/release_build/meson-logs/meson-log.txt

Error:

subprojects/glib/glib/meson.build:408:8: ERROR: Tried to override dependency 'glib-2.0' which has already been resolved or overridden at /initrd/mnt/dev_save/descargas/pango-master/pango-master/meson.build:206:

A full log can be found at /initrd/mnt/dev_save/descargas/pango-master/pango-master/release_build/meson-logs/meson-log.txt

/initrd/mnt/dev_save/descargas/pango-master/pango-master/meson.build:206:
# gobject
glib_dep = dependency('glib-2.0', version: glib_req_version,
                      fallback: ['glib', 'libglib_dep'])

/initrd/mnt/dev_save/descargas/pango-master/pango-master/release_build/meson-logs/meson-log.txt
static int
__getcmdline (void)
{
/* This code is a dumbed-down version of g_file_get_contents() */
#ifndef O_BINARY
#define O_BINARY 0
#endif
#define BUFSIZE 1024
  char result[BUFSIZE];
  struct stat stat_buf;

  int fd = open ("/proc/self/cmdline", O_RDONLY|O_BINARY);
  if (fd < 0)
    exit (1);
  if (fstat (fd, &stat_buf))
    exit (1);

  if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
    {
      if (read (fd, result, BUFSIZE) <= 0)
        exit (1);
    }
  else
    {
      FILE *f = fdopen (fd, "r");
      if (f == NULL)
        exit (1);

      if (fread (result, 1, BUFSIZE, f) <= 0)
        exit (1);
    }

  return 0;
}

int
main (void)
{
  exit (__getcmdline ());
}
Compiler stdout:

Compiler stderr:
 /initrd/mnt/dev_save/descargas/pango-master/pango-master/release_build/meson-private/tmp0qbpsv3c/testfile.c: In function '__getcmdline':
/initrd/mnt/dev_save/descargas/pango-master/pango-master/release_build/meson-private/tmp0qbpsv3c/testfile.c:26:11: warning: implicit declaration of function 'read'; did you mean 'fread'? [-Wimplicit-function-declaration]
   26 |       if (read (fd, result, BUFSIZE) <= 0)
      |           ^~~~
      |           fread

Program stdout:

Program stderr:

Checking if "/proc/self/cmdline" runs: YES
Program python3 found: YES (/usr/bin/python3)
Program bash found: YES (/bin/bash)
Pkg-config binary for MachineChoice.HOST is cached.
Determining dependency 'bash-completion' with pkg-config executable '/usr/bin/pkg-config'
env[PKG_CONFIG_PATH]:
env[PKG_TAB_COMPLETION]: true
Called `/usr/bin/pkg-config --modversion bash-completion` -> 1

CMake binary for MachineChoice.HOST is cached.
Preliminary CMake check failed. Aborting.
Run-time dependency bash-completion found: NO (tried pkgconfig and cmake)
Program sh found: YES (/bin/sh)
Program env found: YES (/bin/env)
Configuring glibconfig.h using configuration
Dependency sysprof-capture-4 skipped: feature sysprof disabled

subprojects/glib/glib/meson.build:408:8: ERROR: Tried to override dependency 'glib-2.0' which has already been resolved or overridden at /initrd/mnt/dev_save/descargas/pango-master/pango-master/meson.build:206:

¿Cómo se soluciona esto?

A: Basicamente el problema es que estas reescribiendo la dependencia, creo que la forma correcta seria la siguiente:
En pango-master/meson.build:
Elimina:
# gobject
glib_dep = dependency('glib-2.0', version: glib_req_version,
                      fallback: ['glib', 'libglib_dep'])

Agrega:
    if meson.version().version_compare('>=0.54.0')
  meson.override_dependency('glib-2.0', libglib_dep)
endif

El cual primero comprobará antes de escribir la libreria.

A: La solución es, en vez de bajar master.zip, mejor clonar el repositorio con git clone:
git clone https://gitlab.gnome.org/GNOME/pango.git


text:
Q: FTP and Apache don't get along with ownership I moved from managed VPS to unmanaged VPS few weeks ago and set it up as I could find guides on net. I've installed Kloxo as my webui for server management etc.
I have a problem with ownership permissions.
Most of my websites are running Wordpress, and it is crucial for me to have apache permissions on those folders so WP can do updates and install plugins. But when I give apache ownership ftp breaks in a way that I can't write anything.
I found that groups are for this, and did add apache and ftp to the same group and chowned the folders, but without success. It gives me, or the 403 forbidden in some cases, or the ftp access but not the apache. I'm a bit confused on how to set things up :|
I was also trying to switch to suphp as it can solve some things hear (as I can read), but I have php 5.2.17 version which doesn't go along O_o
I would upgrade to php5.3 if I'm sure that would solve problems, but as my sites need to be live, I have almost no room for playing.
What are your suggestions? I need to have both ftp and php(apache) write permissions!

A: You need to make sure you change the group of apache and FTP user to be for example new_group.
Then, you need to change the ownership and permissions of files/folders using the following commands:
$ sudo chgrp new_group -R /path/to/folder
$ sudo chmod g+rwx /path/to/folders
$ sudo chmod g+rw /path/to/files

Folders should be given x permission to be able to access them.


text:
Q: Using C++ headers (.h) vs headers plus implementation (.h + .cpp), what are the disadvantages? As a novice C++ programmer I have always put my classes interface in .h files and implementation in .cpp files. However I have recently tried C# for a while and I really like its clean syntax and way to organize files, in particular there is no dinstinction between headers and implementation, you usually implement a class for each .cs file and you don't need headers.
I know that in C++ this is also possible (you can code "inline" functions in .h files), but up to now I have always seen a clear distinction between .h and .cpp files in C++ projects. What are the advantages and disadvantages of this approach?
Thank you

A: Don't forget build times.
Putting implementation code in header files makes them more likely to be changed. And changing header files will cause rebuilds of all the CPP files that include them, which in turn increases build times. This can be significant in larger projects.
I am also a fan of keeping the implementation hidden from users of my libraries. Unfortunately this doesn't work for template classes.
My rule of thumb: keep declarations in .H files, keep definitions in .CPP files.

A: it's cooler to have the symbols defined at one place for the case you wanted to compound C++ with already compiled binaries (typicly when using a library). imagine you need to define external symbols for global stuff in your binaries. if you had .cpp and .h code in the same file you would have to define the symbols for your binaries for every such file. in two files way you could have just the one .h with definitions for binaries and a lot of .cpp files that use it.

A: There's a few ways that separating the two help in C++.  Firstly, if you'd like to update a library without changing an interface then having the code in the C++ file means that you simply can update the library rather than the library plus the headers.  Secondly it hides the implementation.  That is, it forces people to look at your class only in terms of the interface, the thing that should concern them if the code is well written.  Finally, there's a sort of asthetic cleanness with interface + documentation that comes with this separation.  It's something you have to get used to but after a while it'll feel natural (opinion.)

A: The main difference is that something implemented inside a .h file will be placed in every compilation unit that includes that header, this will create redundancy during the compile phase in the final binary executable.. while splitting with .h and .cpp will compile it in a single object file that is later linked against the other objects files by having just one compiled binary code that implements that header file.
In addition if you declare things just inside a .h you are not able to share variables and structures between more other .cpp files..

A: It's interesting to note that C# seems to be going in the C/C++ direction to some extent recently, with the introduction of partial classes.
The particular advantage of this in the IDE is that the Visual Studio designer will modify the part of the class that deals with visual controls, or data members, and their layout without any worries about mucking up the methods (application logic) that reside in a separate file.

A: I would echo @wheaties and add a few further items

*

*Compilation is easier (may be it's just me), I've never been able to get compilation to work just right if you modify the header only (as in all the implementation files that have included it). I believe in Makefiles you have to add the dependencies manually which is a real pain in very large scale projects (again could just be me). So if you have your code in implementation files, then changes simply mean recompiling that particular file - very useful when you want to do quick changes, build and test.

*Let me re-iterate the hiding aspect, most often you don't want people to know the implementation details due to the sensitive nature of the code, and thus only expose the headers plus the pre-built libraries, and the separation is key here.

*Forward declarations, neat trick where you don't need to include the implementation details of a class in the header file if it's not being "used" in any of the code in the header, but then in the implementation file you can include the real header and "it all works nicely" (helps if you have cyclic dependencies - why you have them is different issue!)

A: On a recent large project the authors of systems I wanted to use had placed a lot of the code in .h files. When including their .h files into my own source it added further dependencies to my file. After including the dependencies for their project I ended up with typedef collisions. If they had separated the code and only placed declarations in the .h file it would have been much simpler. I suggest using posix types and only putting declarations into .h files.

A: I see that a lot of responses advocate separation, primarily for build-time and implementation hiding benefits. Both are definitely pluses, though I'll argue the counter example: Boost.
Most Boost libraries use a .hpp file with no external linking. The reason is that this is often required in the case of templates, when the compiler must know the argument types from the calling routine. So you might not have a choice if you want to stick with the "modern" C++ approach of shunning classes for templates.

A: As for the comparison part of .cs versus .cpp/.h I think you need to keep in mind the background the lead architect of C#: Anders Hejlsberg. In Delphi you also don't have the distinction of header and module (ignoring include files for this discussion). You simply have two sections in a unit file initialization and implementation.
The other points were already mentioned.


text:
Q: update and insert query for split name can anyone please help me right the following stored procedure of split name in first and last name in stored procedure in SQL for update and insert query.
Create[dbo].[storedprocedure]
SELECT LEFT(@FullName, CHARINDEX(',', @FullName) - 1) AS [FirstName],
       RIGHT(@FullName, CHARINDEX(',', REVERSE(@FullName)) - 1) AS [LastName]
From table name

Thanks in advance

A: If I've understood your request you could create a type to use as list parameter for the procedure
CREATE TYPE [dbo].[FullNamesList] AS TABLE(
    [FullName] varchar(20) NULL
);

and after this, you can create this procedure to insert splitter name the table you prefer (my FirstLastNameTable)
CREATE PROCEDURE [dbo].[storedprocedure]
    @groupFullNames FullNamesList READONLY

    AS
    BEGIN

        INSERT INTO FirstLastNameTable(FirstName, LastName)
        SELECT LEFT(G.FullName, CHARINDEX(',', G.FullName) - 1) AS [FirstName],
               RIGHT(G.FullName, CHARINDEX(',', REVERSE(G.FullName)) - 1) AS [LastName]
        FROM @groupFullNames G

    END


text:
Q: const extern C-array linker multiple definitions I've got several source files for updating them. They refuse to compile for quite obvious reason (all uninteresting source stripped):
// hashset.h
class HashSet {
    unsigned prime = 0; // Index to table size (c++11 syntax)
    unsigned long table_size () const { return prime_list [prime]; }
};

//hashet.cpp
const unsigned long prime_list [] = {53, 97, 193, 389, 769,
      1543, 3079, 6151, 12289, 24593, 49157, 98317};

prime_list is undefined when called from HashSet::table_size in the header. I tried to fix the source, adding extern const unsigned long prime_list []; to the header and extern to this array definition. After make clean && make I got
g++ main.o dictionary.o hashset.o  -o spell
dictionary.o:(.rodata+0x4): multiple definition of `num_primes'
main.o:(.rodata+0x4): first defined here
dictionary.o:(.rodata+0x20): multiple definition of `prime_list'
main.o:(.rodata+0x20): first defined here
hashset.o:(.rodata+0x4): multiple definition of `num_primes'
main.o:(.rodata+0x4): first defined here
hashset.o:(.rodata+0x20): multiple definition of `prime_list'
main.o:(.rodata+0x20): first defined here
collect2: error: ld returned 1 exit status

As I found out, in fact if just prime_table is defined as
// hashset.cpp
extern const unsigned long prime_list [] = {53, 97, 193, 389, 769,
      1543, 3079, 6151, 12289, 24593, 49157, 98317};

and the body of table_size () is moved to hashset.cpp (to avoid compilation errors), I get these linker errors. Without extern I have no errors. Why is it so? I have only one definition of this array, I do not expose it in any manner to other my source files (I do not put extern const unsigned long prime_list []; to the header now). How it can be multiply defined?
To be clear, my source now:
// hashset.h
class HashSet {
    unsigned prime = 0; // Index to table size (c++11 syntax)
    unsigned long table_size () const;
};

//hashet.cpp
extern const unsigned long prime_list [] = {53, 97, 193, 389, 769,
      1543, 3079, 6151, 12289, 24593, 49157, 98317};
unsigned long HashSet::table_size () const {
     return prime_list [prime];
}

Now extern in the .cpp is unnecessary, but I just wonder, what's wrong? And is there a way to put back the body of table_size() to the header file to allow it to be inline?
upd prime_list and prime_table are the same object. I mistakenly changed the name while shortening the source for this post; fixed now.

A: Remove extern. It should be fine.
For putting the method to header file , just declare the array with extern in header file.
 extern const unsigned long prime_table [];

Also you are not getting errors because of prime_table , but num_primes.
Works perfectly for me .
 Build of configuration Debug for project tmpCheck **
make all
Building file: ../src/hashset.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/hashset.d" -MT"src/hashset.d" -o "src/hashset.o" "../src/hashset.cpp"
Finished building: ../src/hashset.cpp
Building file: ../src/tmpCheck.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/tmpCheck.d" -MT"src/tmpCheck.d" -o "src/tmpCheck.o" "../src/tmpCheck.cpp"
Finished building: ../src/tmpCheck.cpp
Building target: tmpCheck
Invoking: GCC C++ Linker
g++  -o "tmpCheck"  ./src/hashset.o ./src/tmpCheck.o
Finished building target: tmpCheck
 Build Finished **
 #ifndef HASHSET_H_
 #define HASHSET_H_

  extern const unsigned long prime_list [];
  // hashset.h
  class HashSet {
     unsigned prime ; // Index to table size (c++11 syntax)
   public:
      HashSet():prime(0){
        //
      }
      unsigned long table_size () const { return prime_list [prime]; }

  };
  #endif /* HASHSET_H_ */

   #include "hashset.h"
   //hashet.cpp
   const unsigned long prime_list [] = {53, 97, 193, 389, 769,
      1543, 3079, 6151, 12289, 24593, 49157, 98317};

A: I think that if usage of extern specificator, suggested by @Adnan Akbar haven`t solved you issue, then it might be caused by multiply inclusion of header files.
So in that case there is a simple solution to you problem:
use conditional translation directives or
#pragma once in your "hashset.h"


text:
Q: React Native: Getting a "there is no route key defined" error My code is located here
i am getting an error that says: There is no route defined for key employeeList. Must be one of: 'auth','main'. I checked the router.js and the this component is nested in the main scene so i am not sure what the issue is. i am getting this when i wish to create an employee or delete an employee,. I believe it has to do with navigating back to the employeelist screen.

A: Change  to  and import stack from react-native-router-flux and do it for root, auth as well.
When you go to the first element of a stack, you call it with its key. That means if you want to go to employeeList you have to call Actions.main().
Thats why people usually name their parent stack with the name of the screen and first with "_" prefix. You could name your stack with employeeList and first scene with _employeeList. Try this and let me know the outcome please
<Router navigationBarStyle={{ backgroundColor: '#2980b9'}}  titleStyle={{ color:'#fff', alignSelf:'center' }} >
        <Stack key="root" hideNavBar={true}>
            <Stack key='auth'>
                <Scene key='login' component={LoginForm} title = 'Please login' />
            </Stack>
            <Stack key='employeeList'>
                <Scene
                    key='_employeeList'
                    component={EmployeeList}
                    title ='Employee'
                    rightTitle="Add"
                    onRight={()=> Actions.createEmployee()}
                    initial
                    rightButtonTextStyle ={{ color:'white',alignSelf:'center',marginRight:5 }}
                />
                <Scene
                    key='createEmployee'
                    component={EmployeeCreate}
                    title='Create Employee'
                />
            </Stack>
        </Stack>
    </Router>


text:
Q: Unable to initiate application class from dynamic module In base app, have the Application class and declared into AndroidManifest.xml file:
public class App : SplitCompatApplication() {

     override fun onCreate() {
       super.onCreate()
     }
}

<application
    android:name=".App"
    android:icon="@mipmap/ic_launcher"/>

In dynamic module, which should be downloaded onDemand, have another Application class.
public class OnDemandApplication : Application() {

     override fun attachBaseContext(base: Context) {
         super.attachBaseContext(base)
         SplitCompat.install(this)
     }

     override fun onCreate() {
        super.onCreate()

        /* compiled code */
     }
}

How can I initiate the dynamic module application class?


text:
Q: How To Select all numbers on python I want select all the numbers on python not choose a random number
how to do it
while True:
    id = ['407474340', '1950713662', '7993793340', '1606183110', '534649695', '2540710248']

    ran = ''.join(random.choice(id))


text:
Q: Implementing a Code Freeze with Subversion Say I'm working on a project and I know that I've completed a specific class and that it should not be edited again, ever. How can I lock this class so no more commits on it can happen? I've tried locking it, but that only lasts one commit and still allows me to edit it.

Reasoning:
I have a class that performs one thing, and one thing only. It manages X part of the database. X will not change, therefor the class will not have to change. Any changes could be hazardous and introduce bugs which are not necessary. For sake of example this is one class in a project containing a googol (1.0 x 10^100) of classes. Branching for one minor class would be overly complicated, especially if half the classes were like this, you'd wind up with half a googol branches, at least.

A: Create a branch of your entire project - then you can merge future changes from your trunk as and when you want to deploy them.

A: EDIT:
Based on your edit, if you know it won't change, then why even worry about it?  If you don't trust your developers then there is some other problem, but from what I can see you are trying to use version control to "solve" something that is not really there.
I, and I assume many others, are very suspicious about the "no changing" assertion.
Just leave it the way it is.
two other options are pre-commit hooks or access control via the permissions file.
POST PRIOR TO EDIT:
If you are using apache for the repository you can set the permissions to read only fr that file(s).  But in my opinion this is a big mistake.
For your builds you can just force a particular revision in the "get"?
Create a branch and enforce that as the one to use all the time.
If you add commit hook notifications you can be made aware of changes to your files that you do not want.
Alternatively you can have a development branch and the "approved" branch and just never promote any changes to that file(s)

A: You might be able to use a pre-commit hook that rejects changes to specific files under specific conditions.
http://svnbook.red-bean.com/en/1.2/svn.reposadmin.create.html#svn.reposadmin.create.hooks

A: Well, to start with, the basic answer is you don't know that a particular class should never ever be edited again.  Believe me, it will be.
That said, a code freeze -- where you say "no more changes" -- is easily implemented in svn by pulling a tag or a branch (the difference is pretty arbitrary) on the code.
If you want to freeze one file, consider using an svn property to tag it.

A: I wouldn't use source control for this, instead if you can extract a chunk of functionality (including this class) then you could create a separate project from that. The output of that project could then be included as a library in your main project, ie in Java I'd create a jar from the new project and included that in my main project. If/when this class and it's associated classes change you can recreate the library, but would have full control over when you decide to include those changes into your main project.

A: Typically Source Control Systems don't allow you to permanently lock classes.  That makes sense, since if you have a bug, you'd have to "unfreeze" the class, etc.
Subversion allows you to either tag or to branch your code, however.  Tagging allows you to get back to a specific version of your code, and branching allows you to work on multiple versions of your program at the same time.   Both allow you to "freeze" code in a way.
On large projects, before freezing a release, you typically will branch from HEAD, and continue putting in bug fixes into the branch (say v1)- that provides isolation from any new development that's going into HEAD for V2.

A: You can use the SVN lock feature, but instead of locking it with your own user name, use a specific user account (e.g. "ice-code" (pun intended)) to take the lock.  This way, when you commit, it won't try to release the lock.  When you want to release all the locks, use the separate user account to unlock it.


text:
Q: É ideal usar tipos primitivos em Java? O Java possui vários wrapper's que nos ajudam (Integer, Double, BigDecimal), e também nos dá a possibilidade de usar tipos primitivos (int, float, char).
Um professor disse à minha turma de faculdade que Java não deveria ter suporte a tipos primitivos de dados, tanto que a partir do Java 9 ficarão obsoletos (O professor disse, não sei se é verdade). Isso é fato? Por que não devo usar tipos primitivos nem mesmo em um laço de repetição?

A: Ele pode ter a opinião que quiser. Ele falou o por quê? Sempre tente entender o porquê, mais do que entender o que. Se ele discorda do que todo mundo faz ele deveria justificar. Algumas pessoas podem achar que é otimização prematura, mas acho muito academicismo achar isso.

*

*Os chamados tipos primitivos possuem melhor performance. Os tipos não primitivos são referências, possuem indireção no acesso (esse conceito muda um pouco com versões mais novas do Java). A diferença de performance é enorme. Faça um teste de laço com os dois.

*Possuem uma semântica esperada pela maioria das pessoas de que seu valor possui identidade própria e nem sempre fazem o que as pessoas estão acostumadas. Uma cópia não cria nova identidade.
Integer x = 1000;
Integer y = 1000;
x == y //dá falso já que as identidades são diferentes apesar dos valores serem iguais

Coloquei no GitHub para referência futura.

*

*Os tipos "não primitivos" alocam espaço no heap e coloca pressão no coletor de lixo. Os primitivos alocam na stack e o gerenciamento é simples e rápido. Inclusive desperdiçam muita memória por causa do overhead natural que objetos possuem. Novamente isso mudou um pouco em alguns casos.

*Os tipos primitivos não terão problemas de NullPointerException.

*No caso específico do Java a sintaxe dos tipos primitivos é mais conveniente do que os tipos não primitivos. Os tipos primitivos não precisam usar equals(), por exemplo, mas isso pode estar mudando, pelo menos em parte.
Tem outros problemas em não usar tipos primitivos que não estou lembrando. Provavelmente o uso de não primitivos dificultam a resolução de escolha de overload de métodos.
Então é ideal sim, sempre que possível. Inclusive C# possui uma forma de criar tipos por valor próprios - que são os primitivos - e Java tem proposta para ter o mesmo nas próximas duas versões (se já não foi implementado quando ler isso), de tão útil que é. E dará confusão quando isto acontecer, porque o termo ficará ambíguo dentro do que Java sempre usou e algumas das coisas que eu disse aqui nem serão 100% verdadeiras mais, não mudará o fato, mas a definição (por isso eu tive que editar para dizer que algumas coisas mudaram).
Use a forma encaixotada apenas quando houver um motivo para isso.
Algumas pessoas gostam de pensar de forma linear, outras são mais pragmáticas e escolhem a melhor ferramenta para o trabalho.
Se ele deu ou der uma justificativa posta aqui pra gente.
Descontinuação
Isso não tem o menor cabimento. Não sei se está expressando algo diferente do que ele realmente disse, mas se isso ocorresse praticamente 100% dos códigos escritos em Java parariam de funcionar. E sinceramente, uma afirmação dessas coloca em cheque a credibilidade da pessoa.
Não só não existe a proposta de descontinuar esse recurso da linguagem, como cogitar isso seria um completo absurdo. Ao contrário, conforme eu já disse, eles devem ser ampliados em versão futura (estava previsto no Java 10, mas mudou tudo no esquema de versões, quem sabe na 15) e você poderá criar seus próprios tipos por valor que são os tipos primitivos. Veja a proposta oficial.
Veja mais em O que é considerado primitivo em uma linguagem de programação?.

A: As características novas que foram adicionadas ao Java 9 são:

*

*Jshell - Um interpretador de comandos Java.

*Javadoc com HTML 5 e busca utilizando jQuery.

*Simplificação da compilação cruzada (cross-compiling) para versões mais antigas no compilador.

*Anotação @Deprecated melhorada.

*Melhorias no controle de processos do sistema operacional (por exemplo: suporte a kill).

*StackWalker para inspecionar a pilha de execução.

*Fábricas de coleções imutáveis.

*Cliente HTTP2 com websocket.

*Nova modularização com a introdução do conceito de módulos acima do de pacotes.

*Melhorias no locking.

*Arquivos de propriedades UTF-8.

*Implementação do protocolo de transporte DTLS.

*Unicode 7 e 8, incluindo suporte a vários novos emojis.

*Descontinuação das Applets.

*Logging unificado da JVM.

*Suporte a imagens TIFF já incluído por padrão.

*Compilação ahead-of-time.

*Strings compactas. No Java 9, as Strings usam internamente um array de byte (primitivos), ao invés de um array de char.

*Método privados em interfaces.

*Várias outras mudanças mais internas e obscuras.

Veja aqui a lista completa de features.
Em nenhum momento, ninguém falou sobre a possibilidade de se remover os tipos primitivos.
Inclusive, veja aqui no código-fonte da classe Integer, do Java 9, na linha 1101 que a classe Integer é implementada por meio de um objeto que contém um campo final do tipo int. Isso é assim desde os primórdios do Java quando ela ainda era chamada de Oak e não mudou até agora.
Além disso, se int estivesse descontinuado, então porque que o método int parseInt(String) não foi descontinuado também? A resposta é porque int não está descontinuado coisa nenhuma.
O que foi descontinuado sim foi o construtor de Integer que recebe um int como parâmetro. O motivo é que usar tal construtor é uma má prática de programação. O recomendável é usar o método Integer.valueOf(int). Casos análogos nas demais classes empacotadoras também ocorrem.
Há sim uma coisa interna na JVM onde ela consegue otimizar e simplificar alguns casos em que classes empacotadoras são usadas e transformá-las para uso de tipos primitivos. Com isso, a diferença entre a utilização de classes empacotadoras e primitivos diminui. Mas partir disso para dizer que os tipos primitivos ficarão obsoletos é bobagem.

A: Uma outra razão importante que deve ser levada em consideração ao utilizar ou não os boxed types (Integer, Float, etc), também conhecidos por Wrappers, é que suas classes são imutáveis (assim como a classe String). Isso significa que será instanciando um novo objeto para qualquer alteração de conteúdo que a variável sofrer (exceto para inteiros na faixa -128 a 127, ver final da resposta).  Assim, se você fizer isso:
Integer i = 0;
i++;

Então um novo objeto do tipo Integer será instanciado (quando você fizer i++), da mesma forma que ocorre com qualquer String quando você muda o conteúdo da variável. Portanto, o código acima é muito mais lento do que fazer o mesmo com um tipo primitivo.
Uma outra maneira de ver este problema da imutabilidade aplicada nesse contexto:
Execute o código abaixo:
    long start = System.currentTimeMillis();
    for (int i = 0; i < 1000000000; i++) ;
    long end = System.currentTimeMillis();
    System.out.println(end - start);

Depois execute esse:
    long start = System.currentTimeMillis();
    for (Integer i = 0; i < 1000000000; i++) ;
    long end = System.currentTimeMillis();
    System.out.println(end - start);

Note que a diferença de tempo é abismal.
Os boxed types não foram introduzidos para substituir os tipos primitivos, eles foram introduzidos como um mecanismo para facilitar que tipos primitivos sejam passados como parâmetro onde se espera sua classe correspondente. Um exemplo clássico é quando precisa-se adicionar um int em uma Collection de Integer.
@VictorStafusa fez uma observação importante. Caso o inteiro esteja na faixa entre -128 a 127, então uma nova instância não será criada, pois o Java faz cache para instâncias Integer nesse intervalo. Ver essa reposta: https://pt.stackoverflow.com/a/3381/3084


text:
Q: Select content from repository where id = ? for update Above query runs successfully on Oracle 10g. Now I have to implement same query(Application) using SQLSERVER 2005.
When I am running Above Query in SQLSERVER 2005 I am getting error "FOR UPDATE clause allowed only for DECLARE CURSOR".
Is above query supported by SQLSERVER 2005? Or is there any alternate?
Aim:
Basicaly I am updating ducument in my application. I am using chunked update and I have to append every time old content by new content.
CODE:
Blob bb = getDataAccess().executeScalar( "select content from Repository where id = ? for update", getId());
os = bb.setBinaryStream(startIndex + 1);

while ((read = content.read(buf)) > 0) {
    os.write(buf, 0, read);
    startIndex += read;

    //commit every megabate or every second so upload progress is visible
    //and we don't lose more than 1MB if something happens.

    if (startIndex - lastStartIndex > bufSize || (new Date().getTime() - lastUpdateTime) > UPDATE_INTERVAL) {
        os.close();
        os = null;
        getDataAccess().executeUpdate("UPDATE Repository SET LastChunkSaved = CURRENT_TIMESTAMP  WHERE ID = ?", getId());
        getDataAccess().commit();

        lastStartIndex = startIndex;
        lastUpdateTime = new Date().getTime();

        bb = getDataAccess().executeScalar( "select content from Repository where id = ? for update", getId());
        os = bb.setBinaryStream(startIndex + 1);

        totalSaved += startIndex - lastStartIndex;
    }
}
os.close();

A: I ran into a similar problem and for me it helped to add 'SelectMethod=Cursor' to the connection url:
jdbc:sqlserver://<server>\SQLEXPRESS:1433;databaseName=<db>;SelectMethod=Cursor;integratedSecurity=true;

Actually I couldn't find this very easily so I add it here where I would have found it much quicker.


text:
Q: XFCE suspend system command When I click on the exit icon there is a suspend option.  When I click this the computer suspends, which works really well.  I want to create a custom key mapping on the suspend command XK86Sleep (ThinkPad sleep button) which I can create using the keyboard settings.
I have seen pm-suspend from numerous sources, but this requires root and so does not work.  What command does XFCE use when pressing the Suspend option through the UI as described above?
XFCE 4.8, Ubuntu 12.04, ThinkPad T60

A: Try using this for the command
xfce4-session-logout -s

man xfce4-session-logout

The  xfce4-session-logout command allows you to programmatically
  logout
         from your Xfce session. It requests the session manager to display  the
         logout  confirmation  screen,  or,  if  given  one  of the command-line
         options below, causes the session manager to take the requested  action
         immediately.
--suspend
                Suspend without displaying the logout dialog

A: systemctl suspend

Also works for me.  As a bonus it works across xfce4 and cinnamon desktops.