text:
Q: Django - User Profile field won't change after form submit I'm trying to have a part of my user profile change after my form is submitted. The user profile has a discipline field, and I want the user to be able to modify it. When I click submit now, nothing changes.
I am a beginner at Django, so I am sure this is a minor fix. I've been trying to get this to work the past few days.
views.py
@login_required
def change_discipline(request):
    context = RequestContext(request)
    if request.method == 'POST':
    #     #create a form instance and populate it with data from the request
        form = DisciplineChoiceForm(request.POST)
        if form.is_valid():
             #process data in form.clean_data
            discipline = Discipline(name=form.cleaned_data['discipline'])
            request.user.profile.primaryDiscipline = discipline
            request.user.save()
            request.user.profile.save()
            return render_to_response('changediscipline.html', { 'form': form }, context)
else:
    form = DisciplineChoiceForm(request.POST)

return render_to_response('changediscipline.html', {'form': form}, context )

models.py
user profile
class UserProfile(models.Model):
    #this line is required. Links MyUser to a User Model
    user = models.OneToOneField(User, related_name ="profile")
#Additional Attributes we wish to include
date_of_birth = models.FloatField(blank=False)
phone = models.CharField(max_length=10, blank = True)
city = models.CharField(max_length=40, blank = True)
state = models.CharField(max_length=2, blank = True)
zipCode = models.CharField(max_length=5, blank = True)
admin = models.BooleanField(default=False, blank = True)
mentor = models.BooleanField(default=False, blank = True)
mentee = models.BooleanField(default=False, blank = True)
# profilepicture = models.ImageField()
#is_staff = True
tagline = models.CharField(max_length=70, blank = True, default="Let's do this!")
interests = models.ManyToManyField(Interest, related_name="interest", symmetrical = False)
primaryDiscipline = models.ForeignKey(Discipline, default=False, blank = True)
addtlDisciplines = models.ManyToManyField(Discipline, related_name="disciplines", symmetrical=False)

html

Choose a Discipline in {{interest}}

  <form action="{% url 'myapp:change_discipline'  %}" method="POST" id="discipline-select">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit" />
  </form>

forms.py
class DisciplineChoiceForm(forms.Form):
def __init__(self, interest, *args, **kwargs):
    super(DisciplineChoiceForm, self).__init__(*args, **kwargs)
    self.fields['discipline'] = forms.ChoiceField(choices = [(o.id, str(o)) for o in Discipline.objects.all()])

A: Ok should have read better. The first problem:
# this creates an unsaved Discipline instance
discipline = Discipline(name=form.cleaned_data['discipline'])
# and assign it to request.user.profile
request.user.profile.primaryDiscipline = discipline

Since your Profile.primary_discipline allows nulls, the call to request.user.profile.save() doesn't raise an IntegrityError, so nothing happens indeed.
Now you didn't post your DisciplineChoiceForm so we don't know what form.cleaned_data['discipline'] points to, but that's obviously not going to work - what you want is to get the actual (saved) Discipline instance.
If your form's discipline field is a forms.ChoiceField and has (id, name) tuples as choices, then form.cleaned_data['discipline'] will yield the discipline id, and you'll get the correct Discipline instance with Discipline.objects.get(id=form.cleaned_data['discipline']):
discipline = Discipline.objects.get(id=form.cleaned_data['discipline'])
request.user.profile.primaryDiscipline = discipline
request.user.profile.save()

but you might be better using a forms.ModelChoiceField instead which will directly return the selected Discipline instance in which case you can simplify your code to:
discipline = form.cleaned_data['discipline']
request.user.profile.primaryDiscipline = discipline
request.user.profile.save()


text:
Q: Prove that there must exist a measurable function $f$ on E and {$f_n$} converges to $f$ almost everywhere. Suppose $(X,R,\mu)$ is a measure space,{$f_n$} is a sequence of measurable function on E.If {$f_n$} is convergence almost everywhere on E. Prove that there must exist a measurable function $f$ on E and {$f_n$} converges to $f$ almost everywhere.
If $(X,R,\mu)$ is a complete measure space, I can find a measurable set $E_1$,where $\mu(E-E_1)=0$ and {$f_n$} convergent to a measurable function $f_1$ on $E_1$.We set $$f =
\begin{cases}
f_1,  & \text{if $x\in E_1$} \\
0, & \text{if $x\in E-E_1$ }
\end{cases}$$
So $f$ is the measurable function on E.However,if $(X,R,\mu)$ is only a measurable space,how to prove $E_1$ is a measurable set.

redpajama_set_name: RedPajamaStackExchange


text:
Q: "Until now I have been living in the city for a year" or "until now I had been living in the city for a year"? Could you tell what tense I use after until now in the following context: the present perfect continuous or the past perfect continuous?

I have finally moved to the countryside. Untill now I have been living in the city.
I have finally moved to the countryside. Untill now I had been living in the city.


text:
Q: Why are directional derivatives only defined with "line" vectors? We have been shown that the existence of all directional derivatives doesn't imply the continuity of a function, since they only measure changes of the function when moving through straight lines.
When I asked why we can't use other types of curves, the answer was not clear at all. So, why can't we consider directional derivatives with arbitrary vectors? For example, $(x,x^2)$ for a function of two variables.


text:
Q: How to exclude Microsoft.CodeAnalysis.* DLLs from publishing I've written .NET Standard 2.1 library component that relies on Microsoft.AspNetCore.Mvc v2.2.0 package, which indirectly references Microsoft.CodeAnalysis.CSharp.dll, MicrosoftCode.Analysis.dll, and Microsoft.CodeAnalysis.Razor.dll. When I reference my component from .NET Core 3.1 app site and publish the site, Microsoft.CodeAnalysis.* dlls are also published. Is there a way to exclude Microsoft.CodeAnalysis.* dlls from being published? I don't need them for production.
Here are my references from .NET Standard 2.1 CSPROJ file:
 <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Cryptography.KeyDerivation" Version="3.1.8" />
<PackageReference Include="Microsoft.AspNetCore.DataProtection.Abstractions" Version="3.1.8" />
<PackageReference Include="Microsoft.AspNetCore.Http.Features" Version="3.1.8" />
<PackageReference Include="Microsoft.AspNetCore.JsonPatch" Version="3.1.8" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Language" Version="3.1.8" />
<PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="3.3.0">
  <PrivateAssets>all</PrivateAssets>
  <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.DotNet.PlatformAbstractions" Version="3.1.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.8" />
<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="3.1.6" />
<PackageReference Include="Microsoft.Extensions.Identity.Core" Version="3.1.8" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />

Thanks in advance!

A: It looks like the issue comes from referencing the AspNetCore packages directly.
If you can change your class library to target netcoreapp3.1 instead of netstandard, you can replace those by using a FrameworkReference instead. Note that FrameworkReference is only valid for assemblies targetting Net Core 3.x and up. Reference
:
<ItemGroup>
  <FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>

Alternatively, if you need to support both netstandard and netcoreapp, you can use conditional references.
<!-- Framework reference for netcoreapp -->
<ItemGroup Condition=" '$(TargetFramework)' == 'netcoreapp3.1' ">
  <FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>

<!-- Common dependencies -->
<ItemGroup>
  <PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="3.3.0">
    <PrivateAssets>all</PrivateAssets>
    <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
  </PackageReference>
  <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.8" />
  <PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
</ItemGroup>

<!-- netstandard dependencies -->
<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' ">
  <PackageReference Include="Microsoft.AspNetCore.Cryptography.KeyDerivation" Version="3.1.8" />
  <PackageReference Include="Microsoft.AspNetCore.DataProtection.Abstractions" Version="3.1.8" />
  <PackageReference Include="Microsoft.AspNetCore.Http.Features" Version="3.1.8" />
  <PackageReference Include="Microsoft.AspNetCore.JsonPatch" Version="3.1.8" />
  <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
  <PackageReference Include="Microsoft.AspNetCore.Razor.Language" Version="3.1.8" />
  <PackageReference Include="Microsoft.DotNet.PlatformAbstractions" Version="3.1.6" />
  <PackageReference Include="Microsoft.Extensions.DependencyModel" Version="3.1.6" />
  <PackageReference Include="Microsoft.Extensions.Identity.Core" Version="3.1.8" />
</ItemGroup>

Note that I had to guess which package references your package library need, so you'll need to adapt as needed


text:
Q: UIAutomator viewer - incorrect UI XML Snapshoot I've downloaded the SDK to try the uiautomationviewer.bat. It is works fine with native apps like 'calculator':

But, it shows incorrect position of elements in some games, viewer just loose focus or so, for example:

Environment:

*

*OS - Windows 7 Pro / Android 7.0

*Real Device - Samsung A510F

*Java - 1.8.0_151

*Android Debug Bridge version - 1.0.39

*SDK version - 26.0.1

*uiautomatorviewer - 25.3.1

Is there some way to find out what is going on (probably logs)? How to get XML with correct position of elements on the not native apps in my case?


text:
Q: python - Match Everything except the string regex Data Set
Cider
631

Spruce
871

Honda
18813

Nissan
3292

Pine
10621

Walnut
10301

Code
#!/usr/bin/python
import re

text = "Cider\n631\n\nSpruce\n871Honda\n18813\n\nNissan\n3292\n\nPine\n10621\n\nWalnut\n10301\n\n"

f1 = re.findall(r"(Cider|Pine)\n(.*)",text)

print(f1)

Current Result
[('Cider', '631'), ('Pine', '10621')]

Question:
How do I change the regex from matching everything except several specified strings? ex (Honda|Nissan)
Desired Result
[('Cider', '631'), ('Spruce', '871'), ('Pine', '10621'), ('Walnut', '10301')]

A: You can exclude matching either of the names or only digits, and then match the 2 lines starting with at least a non whitespace char.
^(?!(?:Honda|Nissan|\d+)$)(\S.*)\n(.*)

The pattern matches:

*

*^ Start of string

*(?! Negative lookahead, assert not directly to the right

*

*(?:Honda|Nissan|\d+)$ Match any of the alternatives at followed by asserting the end of the string

*) Close lookahead

*(\S.*) Capture group 1, match a non whitespace char followed by the rest of the line

*\n Match a newline

*(.*) Capture group 2, match any character except a newline

Regex demo
import re

text = ("Cider\n"
            "631\n\n"
            "Spruce\n"
            "871\n\n"
            "Honda\n"
            "18813\n\n"
            "Nissan\n"
            "3292\n\n"
            "Pine\n"
            "10621\n\n"
            "Walnut\n"
            "10301")
f1 = re.findall(r"^(?!(?:Honda|Nissan|\d+)$)(\S.*)\n(.*)", text, re.MULTILINE)

print(f1)

Output
[('Cider', '631'), ('Spruce', '871'), ('Pine', '10621'), ('Walnut', '10301')]

If the line should start with an uppercase char A-Z and the next line should consist of only digits:
^(?!Honda|Nissan)([A-Z].*)\n(\d+)$

This pattern matches:

*

*^ Start of string

*(?!Honda|Nissan) Negative lookahead, assert not Honda or Nissan directly to the right

*([A-Z].*) Capture group 1, match an uppercase char A-Z followed by the rest of the line

*\n Match a newline

*(\d+) Capture group 2, match 1+ digits

*$ End of string

Regex demo

A: inverse it with  caret '^' symbol.
f1 = re.findall(r"(\s?^(Cider|Pine))\n(.*)",text)

Keep in mind that caret symbol (in regex) has a special meaning if it is used as a first character match which then would alternatively mean to be "does it start at the beginning of a line".
Thats why one would insert a "non-usable character" in the beginning.  I chosed an optional single space to use up that first character thereby rendering the meaning of the caret (^) symbol as NOT to mean "the beginning of the line", but to get the desired inverse operator.


text:
Q: UITableView reordering core data results my UITableView is reordering the results after you navigate away and them come back to the view. it only does it one time though - if you navigate away and then come back a second time the new order doesn't change.
does anyone know what could be causing this?
thanks for any help.

A: i fixed this issue by putting this code in my viewWillAppear: method.
if (self.resultsController != nil) {
   return;
}

I'm not sure why it worked. I noticed that it was missing when i compared it to other code I had.


text:
Q: Android activity stack management I have an "a-b-c-d" activity history.
I want to kill activities "c" and "d" and start a new "x" activity, so that the new order becomes "a-b-x".
Intent i = new Intent(D.this,B.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra("start_x", true);
startActivity(i);
if (getIntent().getBooleanExtra("start_x", false)) {
    Intent i = new Intent(B.this,X.class);
    startActivity(i);
}

That's how I'm doing it (and I use it a lot of times). Is there an easier way to do it?
EDIT: I forgot to write this: it's necessary to press the back key and go to the "c" activity while in "d".

A: You can do this in 2 ways.
First Way
In AndroidManifest.xml, for C and D activities add property android:noHistory="true"
Second Way
In C activity and D activity, at the time of click add a flag.
Ex:
Intent i = new Intent(C.this, D.class);
i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(i);

Do same for D activity also...

A: One option is that you can set Activity C & D to have same affinity and can call finishAffinity() to clear activities having same affinity from the current task stack. For more info refer to https://developer.android.com/reference/android/app/Activity.html#finishAffinity()

A: added to the above answer of @BHARADWAJ COUNDINYA
Thirds Way:
I will manipulate my activity stack like this:
From A to B:
//In A
Intent intent = new Intent(this, B.class);
startActivity(intent);

[Activity Stack: A->B]

From B to C:
//In B
Intent intent = new Intent(this, C.class);
startActivity(intent);

[Activity Stack: A->B->C]

From C to D(this time I will use finish();):
//In C
Intent intent = new Intent(this, D.class);
startActivity(intent);
finish();

[Activity Stack: A->B->D]

Then in D if my sole purpose is to start X when user navigate back:
//In D
 protected void onPause() {
    super.onPause();
    Intent intent = new Intent(this, X.class);
    startActivity(intent);
    finish();
}

[Activity Stack: A->B->X]

Now if user navigate back again from X it will land on B:

[Activity Stack: A->B]


text:
Q: NanoHttpd send binary response I'm working on a project using creating a game server, the game uses HTTP to communicate back and forth so I require to be able to send binary data as a HTTP response.
Preferably I'd like access to a DataOutputStream object to write to however I haven't found anything that would help without making the application more complicated than my hand rolled basic HTTP server
The game is made by some other company I have nothing to do with so I have to live with the HTTP implementation.


text:
Q: Read and Display Outlook Folder Names I am new to VB.net and appreciate any/all help.  Years ago I developed a VB6 Learning Edition app to read all the entries in all Outlook folders.
To get started, I need help establishing a VB.net connection to Outlook, and sample code to access folders.  Once I get that basic structure, I think I can accomplish my objective.
My ultimate objective is to add a creation date to  all non-email items.
Thanks in advance.
Marvin
I tried some sample code, but had reference issues trying to get to the outlook namespace.
The sample posts provided do net seem to address VB.net

A: The Outlook object model is common for all kind of applications. You just need to add a COM reference to your VB.NET application to be able to declare Outlook types and create a new Application instance. To create a new Outlook Application by using Automation from Visual Basic .NET, follow these steps:
Add a reference to the Microsoft Outlook Object Library. To do this, follow these steps:

*

*On the Project menu, click Add Reference.

*On the COM tab, locate the Microsoft Outlook Object Library and click Select.

Click OK in the Add References dialog box to accept your selections. If you receive a prompt to generate wrappers for the libraries that you selected, click Yes.
Vioal! Now you can use the Outlook object model in the code.


text:
Q: Unexpected token error when using Vue-pdf I'm creating an SPA with Laravel and Vue and am trying to use vue-pdf.  I've successfully integrated several npm packages, but this one is giving me the error:
Uncaught SyntaxError: Unexpected token '<'

When I click on the file (worker.js) in my console, it looks like it's trying to perform a get request for a regular page on my site instead of grabbing the javascript so my hunch is that webpack isn't correctly transpiling vue-pdf.  My current webpack config is:
const path = require('path')
const fs = require('fs-extra')
const mix = require('laravel-mix')
require('laravel-mix-versionhash')
// const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')

mix
  .js('resources/js/app.js', 'public/dist/js')
  .sass('resources/sass/app.scss', 'public/dist/css')
  .sass('resources/sass/flowy.scss', 'public/dist/css')

mix.babel([
  'resources/js/helpers/Date.js',
  'resources/js/helpers/LoginRedirect.js'
], 'public/assets/js/combined.js')

  .disableNotifications()

if (mix.inProduction()) {
  mix
    // .extract()
    // .version()
    .versionHash()
} else {
  mix.sourceMaps()
}

mix.webpackConfig({
  plugins: [
    // new BundleAnalyzerPlugin()
  ],
  resolve: {
    extensions: ['.js', '.json', '.vue'],
    alias: {
      '~': path.join(__dirname, './resources/js')
    }
  },
  output: {
    chunkFilename: 'dist/js/[chunkhash].js',
    path: mix.config.hmr ? '/' : path.resolve(__dirname, './public/build')
  }
})

mix.then(() => {
  if (!mix.config.hmr) {
    process.nextTick(() => publishAseets())
  }
})

function publishAseets () {
  const publicDir = path.resolve(__dirname, './public')

  if (mix.inProduction()) {
    fs.removeSync(path.join(publicDir, 'dist'))
  }

  fs.copySync(path.join(publicDir, 'build', 'dist'), path.join(publicDir, 'dist'))
  fs.removeSync(path.join(publicDir, 'build'))
}

Any help would be appreciated.


text:
Q: java for loop early termination This is the first half of my java program- to input certain values. I noticed that the first 'for loop'which takes in values of the answer key is getting terminated after 2 or 3 iterations instead of the expected 5, and I have, so far, had no luck in figuring out why. Any help would be appreciated, thanks!
public class quizscores
{ public void main()throws IOException
    { BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("enter no of participants");
        int n=Integer.parseInt(br.readLine());
        char arr[][]=new char[n][5];

        System.out.println("Please enter answer key");
        char ans[]=new char[5];

        for(int i=0;i<5;i++) //referring to this for loop
        {
         ans[i]=(char)(br.read());
        }

        System.out.println("please enter answers of participants ");
        for(int i=0;i<n;i++)
        {for(int j=0;j<5;j++)
            {arr[i][j]=(char)(br.read());
            }
       }

A: BufferedReader.read() method reads one character at a time so what will happen in your case that it will read the empty space or the enter when you are giving input on a new line try giving answer key input on a single line without spaces.
    System.out.println("Please enter answer key");
    char ans[]=new char[5];

    for(int i=0;i<5;i++) //referring to this for loop
    {
     ans[i]=(char)(br.read());
    }

Sample I/O
Please enter the answer key
ABCDE


text:
Q: Let $f: \mathbb{R} \rightarrow \mathbb{R}$ given by $f(x)=e^{\theta x}$. Show that $E[f(X)]=exp(\lambda (e^\theta -1))$ Let $f: \mathbb{R} \rightarrow \mathbb{R}$ given by $f(x)=e^{\theta x}$, where $\theta \in \mathbb{R}$ and suppose that $X ~ Po(\lambda)$ for some $\lambda >0$. Show that $E[f(X)]=exp(\lambda (e^\theta -1))$.

By theorem, $E[f(x)]=\sum_{x=1}^{\infty}{f(x)P(X=x)}=\sum_{x=1}^{\infty}{e^{\theta x}(\frac{\lambda^xe^{-\lambda}}{x!}})=e^{\theta-\lambda}\sum_{x=1}^{\infty}\frac{e^x\lambda^x}{x!}=e^{\theta-\lambda}(\sum_{x=1}^{\infty}e^x)(\sum_{x=1}^{\infty}\frac{\lambda^x}{x!})=e^{\theta-\lambda}(e^\lambda)(\sum_{x=1}^{\infty}e^x)=e^{\theta}(\sum_{x=1}^{\infty}e^x)$
First question, is my calculation correct? Second question, what is the infinite sum of $e^x$

A: The sum should start at $0$, and the third equality you have is wrong. Recall that
$
e^ae^b = e^{a+b}
$ (not $e^ae^b = e^{ab}$); and that $e^{ab} = (e^a)^b$.
 Using this, you have $$
\mathbb{E}[f(x)]=\sum_{x=0}^{\infty}{f(k)\mathbb{P}\{ X=k \}} =
e^{-\lambda}\sum_{x=0}^{\infty}{e^{\theta k} \frac{\lambda^k}{k!}} =
e^{-\lambda}\sum_{x=0}^{\infty}{\frac{(e^\theta\lambda)^k}{k!}}
= e^{-\lambda}e^{e^\theta\lambda} = e^{(e^\theta-1)\lambda}
$$
proving the result. (The last steps use the fact that $\sum_{x=0}^{\infty}{\frac{x^k}{k!}} = e^x$.)


text:
Q: Can sgen.exe be used for web.config file to improve performance and cold start? .NET cold start is a known issue, and it denotes the time necessary for the first time load an ASP.NET web site, which includes DLL loading, JIT compilation, w3wp.exe creation, and other stuff.
Does using sgen.exe on web.config files have an improvement effect on cold start?
More fundamentally, can we use this tool on web.config, and if yes, how?

A: I would have to say no. .config files are handled by the config api, so having used sgen on them, the api wouldn't know how to use your compiled code.
You'd be better off looking at aspnet_compiler.exe to pre-build the site. This would have a much greater impact on the cold start delay.
Simon


text:
Q: Get respective part from string Kindly let me know how to get the part Application6.docx from strings like  files/abcd/Application6.docx ?
In simple words I am just trying to get the file name along with its extension Application6.docx
Note: files/abcd/ can be different ppt/file/ so I cannot use the trick of replacing files/abcd/

A: You can use basename to get what you want.
$file = basename("files/abcd/Application6.docx");

A: Hope This Helps :)
<?php
     $url = "http://test.com/beta/files_images/file.php";
     $keys = parse_url($url); // Parse the url
     $data = explode("/", $keys['path']);
     $last = end($data);
 ?>


text:
Q: Hibernate - insert data with one to many relationship I am trying to insert data into a Patient table, which has a many-to-one relationship with Site. Site has a one-to-many relationship with Patient.
However, I get a org.postgresql.util.PSQLException: ERROR: insert or update on table "patients" violates foreign key constraint "fk_427e3ubwhw8n7a4id3mmrmjgj"
  Detail: Key (patient_id)=(31) is not present in table "sites".
I have tried to create a set of patients, add my patient to this set, create a site object, then use this object to set the patients. I am not sure which part of this is going wrong.
    Session session = this.getFactory().openSession();
    Transaction transaction = null;

    try{
        transaction = session.beginTransaction();

        Date parsedDob = Date.valueOf(dob);
        Date parsedDateReg = Date.valueOf(dateReg);

        Site site = new Site();
        site.setSiteId(1);

        IPatient p = new Patient();
        p.setFirstName(firstName);
        p.setLastName(lastName);
        p.setDob(parsedDob);
        p.setDateRegistered(parsedDateReg);
        p.setSite(site);

        Set<IPatient> patientSet = new HashSet<IPatient>();
        patientSet.add(p);

        site.setPatients(patientSet);

        session.save(site);
        session.save(p);
        transaction.commit();
    }catch(Exception e){
        e.printStackTrace();
    }

My Patient.hbm.xml file is:
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.example.model">
<class name="Patient" table="patients">
    <id name="patientId" column="patient_id">
        <generator class="sequence" />
    </id>
    <version name="version" column="version" />
    <property name="firstName" column="first_name" />
    <property name="lastName" column="last_name" />
    <property name="dob" column="dob" />
    <property name="gender" column="gender" />
    <property name="dateRegistered" column="date_registered" />
      <many-to-one name="site" class="com.example.model.Site" not-null="true" />
    <set name="visits" cascade="all">
        <key column="visit_id" />
        <one-to-many class="Visit" />
    </set>
</class>

My Site.hmx.xml is:
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.example.model">
<class name="Site" table="sites">
    <id name="siteId" column="site_id">
        <generator class="sequence" />
    </id>
    <version name="version" column="version" />
    <property name="name" column="name" />
    <set name="patients" cascade="all">
        <key column="patient_id" />
        <one-to-many class="Patient" />
    </set>
</class>

My Patient.java
public class Patient implements IPatient{

    private Integer version;
    private Integer patientId;
    private Set<IVisit> visits;
    private Site site;

    private String firstName;
    private String lastName;
    private Date dob;
    private Gender gender;
    private Date dateRegistered;

    public Patient(){

    }
}

My Site.java
public class Site {

    private Integer siteId;
    private Integer version;
    private Set<IPatient> patients;
    private String name;

    public Site(){

    }
}

A: After the line below you should save your site object to db;
 site.setSiteId(1);
 session.save(site);

After that you can set site object to patient;
 p.setSite(site);


text:
Q: Has Facebook replaced the fb_ref parameter? This morning I found out that Facebook is not returning the fb_ref parameter when you add it to links in actions or likes. Instead they seem to have replaced it with a series of new parameters: action_ref_map, action_object_map, ...
Could someone confirm me this change? This is breaking our software.
EDIT
This is an example that I've found:
http://uk.omg.yahoo.com/news/john-travoltas-year-gay-affair-pilot-revealed-122446486.html?fb_action_ids=10151047496853334&fb_source=other_multiline&action_object_map={%2210151047496853334%22%3A10151788645595106}&action_type_map={%2210151047496853334%22%3A%22news.reads%22}&action_ref_map={%2210151047496853334%22%3A%22type%3Aread%2Cuser%3A1k-WK59_Yk-EnPq2w1zMLBjX7nA%22}&code=AQCH-sq6XRSQCXj4QNkKlnusWLgIvBaZduNhGO0RNdiXgfCSGUOd1qinfHVw1iFQfs-0KVxFdPpWXD9nWrjEC1naU87H5W4GnxnTPL5j2raksea2pFxuy0rtgSpAa6ExZYCc7PkzIyjNnGTdK6N7g0Spb7qiqSboTgWZOojQJYbEF2XHenlROjhP8--NkvzrxU8#_=_

EDIT 2
It seems that Facebook has activated a new system for returning "fb_ref" in sandboxed FB apps.

A: https://developers.facebook.com/docs/fb_source/ is (and should be) the primary source of referral information and open graph actions have always had their own referral parameters showing which actions were present in the story/aggregation which triggered the click
fb_ref is provided when you had a 'ref' parameter on the source publish but as far as i know there hasn't been a change there
(e.g. like button with ref = foo results in a click back to your app with fb_ref=foo, fb_source=ticker or something like that)


text:
Q: How to update some data in SQL server into null for Classic ASP I want to make update function in a web based system using Classic ASP to enable the user to cancel their application. I'm not using delete function because some data should be maintained, and some data will be set into NULL. This function also allow the user to choose date range in a form to delete their application.
There is no error shown but the set of data is not updated when click on cancel button in the form.
This is the code :
<%param="keyid=" & session("keyid")
idkehadiran=request("idkehadiran")
nokpl=request("nokpl")

set SimpanRS=server.CreateObject("adodb.recordset")
sql="select * from tms_kehadiran where nokpl='"&nokpl&"' and (tarikh >= '"&tarikh&"' and tarikh <= '"&hinggaTarikh&"')"
SimpanRS.open sql,connehr,3,3

while not SimpanRS.EOF
SimpanRS("alasan")=""
SimpanRS("nokpPenyelia")=""
SimpanRS("kelulusan")=null
if isnull(SimpanRS("datecreated")) then
SimpanRS("datecreated")=now
end if
SimpanRS("lastupdate")=now

SimpanRS.update
SimpanRS.movenext
wend
SimpanRS.close
set SimpanRS=nothing
%>

I don't what are the error with this code. Can anyone help me ?

A: Instead of looping the RS. You should use GetRows().
After that you can update the data in the SQL server while looping the array.


text:
Q: Set custom HeaderView for each Column in NSTableView Is it possible to set a custom header view for each Column in NSTable ? When I drag drop a table to a view, I can see that there is only 1 header view for both the columns. I referred this answer and implemented same in my table class.
- (NSTableHeaderView *)headerView{
    CustomHeaderView *customHeader = [[CustomHeaderView alloc] initWithFrame: ...];
    return customHeader;
}

But this will add one view for all the table columns.
If my understanding is correct, TableHeaderView is only one view, and default header view looks like it contains 2 cells for both columns but its actually one view. ? If so how do I go about having separate views or mimic the same behaviour for custom header view ?


text: Q: how to create backup for update tables structures in existing DB? I have Sql Server DB, I know I can Create thru "Generate Scripts" backup for SP and Functions then I just replace inside the script the "CREATE" with "ALTER", that will update the target DB with the latest Functions And SP but how to do that for Tables structures  and "User Defined Tables" ?


text:
Q: angularjs constant code lint I'm using 02_jshint.js to code lint my Ionic project, everything goes well until I receive this error:
35:4 -> Missing semicolon. ->  })

and it's pointing to the last constant's bracket of my code:
angular.module('myApp.constants',['ionic'])

    .constant('A','2.1.4')
    .constant('B','1.1.3')

    .constant("c", {
          "d": "cost1",
          "e": "cost2",
          "f": "cost3"
     })

I would like to know if there is a way to avoid this warning or to correct the error, it's clear that the code is correct but I would like to build my project (it doesn't allow to do that if there are any errors).
Any advice?

A: Check jshint documentation jshint.com/docs.
In case you know why you don't want to put a semicolon there (which would be a good practice) try to put some ignore directives around it:
A directive for telling JSHint to ignore a block of code.
// Code here will be linted with JSHint.
/* jshint ignore:start */
// Code here will be ignored by JSHint.
/* jshint ignore:end */

Additionally, you can ignore a single line with a trailing comment:
ignoreThis(); // jshint ignore:line

A: angular.module('myApp.constants',['ionic']).whatevergoeshere() is a chained statement. In JavaScript you always should terminate statements using a semicolon.
I advice you not to switch this rule off but just add the semicolon.

The semicolon (;) character is used to separate statements in JavaScript code.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling

A: you missed semicolon in the last.
angular.module('myApp.constants',['ionic'])
   .constant('A','2.1.4')
   .constant('B','1.1.3')
   .constant("c", {
         "d": "cost1",
         "e": "cost2",
         "f": "cost3"
      });


text:
Q: Python - XY Scrolling of a Tkinter Frame deosn't load widgets effectively I have the current code (cut down from the original) - this snippet is also available here.
import tkinter as tk
import tkinter.ttk as ttk
class ScrolledFrame(tk.Frame):
    def __init__(self, master, **kw):
        tk.Frame.__init__(self, master, **kw)
        vsb = tk.Scrollbar(self, orient='vertical')
        vsb.grid(column=1, row=0, sticky='ns')
        hsb = tk.Scrollbar(self, orient='horizontal')
        hsb.grid(column=0, row=1, sticky='ew')

        self.canvas = canvas = tk.Canvas(self, bd=0, highlightthickness=0,
                        yscrollcommand=vsb.set, xscrollcommand=hsb.set)
        canvas.grid(row=0, column=0, sticky='nsew')
        #canvas.configure(scrollregion=canvas.bbox('all'))
        vsb.config(command=canvas.yview)
        hsb.config(command=canvas.xview)
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)

        # reset the view
        canvas.xview_moveto(0)
        canvas.yview_moveto(0)

        self.interior = interior = tk.Frame(canvas)
        interior_id = canvas.create_window(0, 0, window=interior,
                                           anchor='nw')

        def _configure_interior(event):
            size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
            canvas.config(scrollregion="0 0 %s %s" % size)
            if interior.winfo_reqwidth() != canvas.winfo_width():
                canvas.config(width=interior.winfo_reqwidth())
        interior.bind('<Configure>', _configure_interior)

        def _configure_canvas(event):
            if interior.winfo_reqwidth() != canvas.winfo_width():
                canvas.itemconfigure(interior_id, width=canvas.winfo_width())
        canvas.bind('<Configure>', _configure_canvas)

if __name__ == '__main__':
    root = tk.Tk()
    main_frame = ScrolledFrame(root)
    main_frame.grid(row=0, column=0, sticky='nsew')
    root.grid_rowconfigure(0, weight=1)
    root.grid_columnconfigure(0, weight=1)
    for i in range(100): tk.Button(main_frame.interior, text=f'test {i}').grid(row=0, column=i)
    root.geometry('360x240')
    root.mainloop()

The aim of the code is too have a frame that is scroll-able via both the x and y axis; however, an issue is occurring in which scrolling across the x axis results in the items not being drawn:

However, the y-axis seems to work perfectly - I have attempted to change by program with different scrollregion= settings (i.e. 'all') yet to no prevail, it seems to remove the functionality of the x-axis entirely.

A: You are explicitly setting the width of the interior frame to be the same as the width of the canvas. For example, when the program starts up, the canvas will be a little less than 360 pixels wide so you're setting the interior frame to be that size. On my machine that ends up being 309 pixels. Thus, when you scroll you'll only ever be able to see 309 pixels worth of buttons.
The whole point of scrolling is that you're trying to see something that is larger than the window, but you're artificially making the inner frame the same size as the window.
You should stop forcing the inner frame to be the same size as the canvas, or at least stop forcing it to be smaller than the canvas. It needs to be its natural size.


text:
Q: Write a generic method to replace a family of legacy API methods I'm writing code using a legacy API whose code I cannot change. There is a family of methods for supported datatypes (int, double, bool, string, APIObject) to do an operation in the API. These take a parameter of the same datatype as indicated in the name of the method. Sample usages as given below
GetIntExp(5)
GetStringExp("Hello")
GetDoubleExp(1.2)
GetDateExp(DateTime.Now)
GetAPIObjectExp(myObject)

The return type respectively, IntExp, StringExp, DoubleExp, DateExp and ObjectExp. All return types  inherit from a class (which interestingly is a generic type) StaticOperator<T> where T is the datatype.
Is it possible to write a generic method in my codebase which redirects calls to the suitable API method based on the datatype which is passed in?

A: Seems to me you don't need a generic method at all, just a wrapper method for each supported argument type:
public IntExp GetExpression(int value)
{
    return GetIntExp(value);
}

public StringExp GetExpression(string value)
{
    return GetStringExp(value);
}

and so on (assuming your goal is to use the same name for all the ways of getting an expression).

A: Something like
private Dictionary<Type, Func<object, object>> _funcMapping = new Dictionary<Type, Func<object, object>> {
    {typeof(Int), (input) => GetIntExp((int)input)},
    {typeof(string), (input) => GetStringExp((string)input)},
    ...
};

public StaticOperator<TType> GetExp<TType>(TType target) {
    Func<object, object> func;
    if (!_funcMapping.TryGetValue(typeof(TType), out func))
        throw new NotImplementedException();
    return (StaticOperator<TType>)func(target);
}

is totally possible, but certainly have scaling problems and quite unsafe as requires a lot of casting.
Of course you can rewrite it using if .. elseif .. elseif .. elseif .. else, but all in all it's just a checking if we have a suitable method.

A: What about something like this:
public T GetExp<T>(T obj)
{
    Type type = typeof(T);

    if (type == typeof(int))
        return GetIntExp(obj);
    if (type == typeof(string))
        return GetStringExp(obj);
    if (type == typeof(double))
        return GetDoubleExp(obj);
    if (type == typeof(DateTime))
        return GetDateExp(obj);
    if (type == typeof(APIObject))
        return GetAPIObjectExp(obj);

    throw new Exception("Invalid Type");
}

A: This is what I got compiling and working using suggestions from @J0HN and @Prescott,
private StaticOperator<T> GetValue<T>(T comparandValue)
{
    Type type = typeof(T);

    if (type == typeof(int))
    {
        return GetIntVal((dynamic)comparandValue);
    }

    if (type == typeof(double))
    {
        return GetDoubleVal((dynamic)comparandValue);
    }

    if (type == typeof(string))
    {
        return GetStringVal((dynamic)comparandValue);
    }

    if (type == typeof(DateTime))
    {
        return GetDateVal((dynamic)comparandValue);
    }

    if (type == typeof(APIbject))
    {
        return GetObjectVal(comparandValue as APIObject);
    }
    throw new NotSupportedException("The given type is not supported");
}

A: "Is it possible to write a generic method in my codebase which redirects calls to the suitable API method based on the datatype which is passed in."
You could write some IL-Code to do exactely that. Then again you'd probably not have a great time doing that. I've read an article on codeplex at home about it. I think i found it by googling "Replace method at runtime".
Maybe that's what you're looking for after all, though it might very well be the most difficult solution for your actual problem.
http://www.codeproject.com/Articles/37549/CLR-Injection-Runtime-Method-Replacer


text:
Q: How to add token from shared preferences to an interceptor After I authenticate and get JWT in header I want to add token to every request sent from person logged in with this token.
But I don't know how to pass token from shared preferences to my Api client class.
I tried defining sharedPref object, but it needs Context to use .getSharedPreferences method.
This is how I retrieve and save token from authentication endpoint: (this is in loginActivity class)
private void login() {

        LoginRequest loginRequest = new LoginRequest();
        loginRequest.setUsername(usernameLog.getText().toString().trim());
        loginRequest.setPassword(passwordLog.getText().toString().trim());
        Toast.makeText(getApplicationContext(), "Clicked", Toast.LENGTH_SHORT).show();

        Call<Void> loginResponseCall = ApiClient.getUserService().login(loginRequest);
        loginResponseCall.enqueue(new Callback<Void>() {
            @Override
            public void onResponse(Call<Void> call, Response<Void> response) {

                if (response.isSuccessful()) {

                    token = response.headers().get("Authorization");

                    SharedPreferences preferences = getSharedPreferences("logged", MODE_PRIVATE);
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putBoolean("isLogged", true);
                    editor.putString("token", token);
                    editor.apply();

                    Toast.makeText(getApplicationContext(), "User logged in successfully", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    finish();
                }
            }

            @Override
            public void onFailure(Call<Void> call, Throwable t) {
                Toast.makeText(getApplicationContext(), "User failed logging in: " + t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

And this is my ApiClient class, where I'm trying to use token saved from Shared Preferences.
    public class ApiClient {

        private static Retrofit getRetrofit() {

            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

            OkHttpClient client =  new OkHttpClient.Builder()
                    .addInterceptor(httpLoggingInterceptor)
                    .addInterceptor(chain -> {
                        Request newRequest  = chain.request().newBuilder()
                                .addHeader("Authorization", TOKEN)

//    Instead of "TOKEN" I need to somehow pass
//
//    SharedPreferences preferences = getSharedPreferences("logged", MODE_PRIVATE);
//    preferences.getString("token", "");

                                .build();
                        return chain.proceed(newRequest);
                    })
                    .build();

            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("http://192.168.1.60:8080/")
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(client)
                    .build();

            return retrofit;
        }

        public static UserService getUserService() {
            UserService userService = getRetrofit().create(UserService.class);

            return userService;
        }
    }

When I hard code it, it works. But It needs to pass token dynamically depending on which user is logged in.


text:
Q: Clojure deftype calling function in the same namespace throws "java.lang.IllegalStateException: Attempting to call unbound fn:" I'm placing Clojure into an existing Java project which heavily uses Jersey and Annotations.  I'd like to be able to leverage the existing custom annotations, filters, etc of the previous work.  So far I've been roughly using the deftype approach with javax.ws.rs annotations found in Chapter 9 of Clojure Programming.
(ns my.namespace.TestResource
  (:use [clojure.data.json :only (json-str)])
  (:import [javax.ws.rs DefaultValue QueryParam Path Produces GET]
           [javax.ws.rs.core Response]))

;;My function that I'd like to call from the resource.
(defn get-response [to]
  (.build
    (Response/ok
      (json-str {:hello to}))))

(definterface Test
  (getTest [^String to]))

(deftype ^{Path "/test"} TestResource [] Test
  (^{GET true
     Produces ["application/json"]}
  getTest
  [this ^{DefaultValue "" QueryParam "to"} to]
  ;Drop out of "interop" code as soon as possible
  (get-response to)))

As you can see from the comments, I'd like to call functions outside the deftype, but within the same namespace.  At least in my mind, this allows me to have the deftype focus on interop and wiring up to Jersey, and the application logic to be separate (and more like the Clojure I want to write).
However when I do this I get the following exception:
java.lang.IllegalStateException: Attempting to call unbound fn: #'my.namespace.TestResource/get-response

Is there something unique about a deftype and namespaces?

A: ... funny my hours on this problem did not yield an answer until after I asked here :)
It looks like namespace loading and deftypes was addressed in this post.  As I suspected the deftype does not automatically load the namespace.  As found in the post, I was able to fix this by adding a require like this:
(deftype ^{Path "/test"} TestResource [] Test
  (^{GET true
     Produces ["application/json"]}
    getTest
    [this ^{DefaultValue "" QueryParam "to"} to]
    ;Drop out of "interop" code as soon as possible
    (require 'my.namespace.TestResource)
    (get-response to)))


text:
Q: Correctly using hyperref package to underline href elements I'm interested in using hyperref package to highlight links typed as href elements, the links should be:

*

*Of the same colour as the remaining text (default, black)

*Underlined with single lines including spaces

*No other modifications are required in the future I would like to be able to easily change link fonts, colour or face. Ideally by changing the hyperref package load.

Document
% Define document class, font size
\documentclass[9pt]{extarticle}

% Tweak page margins
% Set left and right margin and compute the remaining ones
% https://www.sharelatex.com/learn/Page_size_and_margins#!#Paper_size.2C_orientation_and_margins
\usepackage{geometry}
\geometry{
    a4paper,
    total={170mm,257mm},
    left=20mm,
    top=20mm
}
% --

% Font settings using the fontspec package
% https://stackoverflow.com/a/1840608/1655567
\usepackage{fontspec}
\setmainfont{IBM Plex Sans}
% --

% Define PDF metadata and link colours
\usepackage{xcolor}
\usepackage[pdfauthor={Person},
            pdftitle={What a fancy title},
            pdfkeywords={Keyword},
            pdfproducer={LaTeX},
            pdfcreator={xelatex},
        colorlinks=false,           % hyperlinks will be black
        linkbordercolor=black,      % hyperlink borders will be red
        pdfborderstyle={/S/U/W 1}       % border style will be underline of width 1pt
        ]{hyperref}
% --

\begin{document}

% Place details side-by-side using minipage placeholder
% https://tex.stackexchange.com/a/157246/123504

% Minipage 1
\begin{minipage}{.5\textwidth}
    {\Large\textbf{ABC} \par}
    \textit{abc:} 111  \textit{Email:} \href{mailto:abc.abc@abc.com}{abc.abc@abc.com}
\end{minipage}
\hspace{0.5cm}
% Another minipage
\begin{minipage}{.5\textwidth}
    \textit{Search:} \href{https://www.google.com}{google.com}
\end{minipage}

\end{document}

Preview

Desired results
Desired results can be achieved with use of \underline{}:

\textit{Search:} \href{https://www.google.com}{\underline{google.com}}

I want to arrive at the same results via the hyperref settings, if possible.

A: Based on https://tex.stackexchange.com/a/311148/36296 you could do something like:
\documentclass{article}
\usepackage[
    hidelinks
]{hyperref}
\usepackage[normalem]{ulem}
\usepackage{xcolor}

\makeatletter
\begingroup
  \catcode`\$=6 %
  \catcode`\#=12 %
  \gdef\href@split$1#$2#$3\\$4{%
    \hyper@@link{$1}{$2}{\uline{$4}}% or \underline
    \endgroup
  }%
\endgroup

\begin{document}

\href{mailto:abc.abc@abc.com}{abc.abc@abc.com}

\href{https://www.google.com}{google.com}

\end{document}


text:
Q: Why can't you derive a HKDF key with with WebCrypto? I want to take a password and run it through PBKDF2 to create a master key. I then want to take that and run it through HKDF to create multiple keys. It seems as though crypto.subtle.deriveKey will not accept HKDF as a derivedKeyAlgorithm.
In other words I can't get something like this to work
const kd_algo = { name: "PBKDF2", hash: "SHA-256", salt: pbkdf2_salt, iterations: 100000 }
const master_key = await crypto.subtle.deriveKey(kd_algo, password, { name: "HKDF" }, false, ["deriveKey"])

but this will
const kd_algo = { name: "PBKDF2", hash: "SHA-256", salt: pbkdf2_salt, iterations: 1000000 }
const master_key_material = await crypto.subtle.deriveBits(kd_algo, password, 256)
const master_key = await crypto.subtle.importKey("raw", master_key_material, "HKDF", false, ["deriveKey"])

This makes no sense.


text:
Q: PHP avoid redirect I'm wondering if there's any possibility of avoid redirect with my problem below.
index.php
$select = new select();

if(!isset($_COOKIE['country']) || !isset($_COOKIE['language'])){
   $select->firstTime();
   $content = $select->clients(); // this will get clients according to the cookies
}

firstTime
public function firstTime(){
    $ip = $_SERVER['REMOTE_ADDR'];
    $xml = simplexml_load_file("http://freegeoip.net/xml/$ip");

    $locale    = $xml->CountryCode;

    $country_f   = "us"; // default
    $locale_f = "en_US"; // default

    /*
        ++ Select country from database according to the locale
        $country_f = $variable_database
    */

    setcookie('language', $locale_f, time() + (60*60*24*365), '/');
    setcookie('country', $country_f, time() + (60*60*24*365), '/');

    header('location: redirect.php');
    exit();
}

redirect.php
header('location: index.php'); exit(); // back to index.php

Well, the problem is this: when the user enters the page for the first time it has no cookies, so I check his ip and set the cookies. However, if the user does not refresh the page he will see the page content in the default language/country (English/United States), so I make this redirect to force the content to show according to user location.
The code $content = $select->clients(); // this will get clients according to the cookies, will select the clients according to his cookies. If I remove the redirect code the clients will be selected as default English/United States and shouldn't because the cookies were already stored with the function firstTime().
The function $select->clients() is read AFTER $select->firstTime(), so why doesn't detect the cookies?
clients
list($id_country, $id_language) = $this->get_country_language();
/*
  ... SELECT * FROM clients WHERE id_country = $id_country
*/

get_country_language
public function get_country_language(){
    $id_country = 2; // United States
    $id_language = 1; // English

    if(isset($_COOKIE['country'])){
        $id_country = $this->get_country_from_code($_COOKIE['country']);
    }
    if(isset($_COOKIE['language'])){
        $id_language = $load->get_language_from_code($_COOKIE['language']);
    }

    return array($id_country, $id_language);
}

I've tried to be the most explicit I could. I'm just asking if there's any possibility of doing this without redirect? Because google says to avoid redirects..and when I analyse my page with google pagespeed it also says that.

Your page has 2 redirects. Redirects introduce additional delays
before the page can be loaded.
mywebsite.com/
mywebsite.com/redirect.php
mywebsite.com/index.php

A: instead of redirect and exit() why dont you return the array($locale_f, $id_language);

A: setcookie sets the cookie information on the users browser, however current cookie information is only loaded at the start of the script.
A redirect/refresh is really the only way around this I believe.

A: Maybe you can try something like this
public function get_country_language(){
    $id_country = 2; // United States
    $id_language = 1; // English
    $ids = array();

    if(isset($_COOKIE['country']) && isset($_COOKIE['language'])){
        $id_country = $this->get_country_from_code($_COOKIE['country']);
        $id_language = $load->get_language_from_code($_COOKIE['language']);
        $ids = array($id_country, $id_language);
    }
    else{
        $ids = $this->firstTime();
    }
    return $ids;
    }

public function firstTime(){
    $ip = $_SERVER['REMOTE_ADDR'];
    $xml = simplexml_load_file("http://freegeoip.net/xml/$ip");

    $locale    = $xml->CountryCode;

    $country_f   = "us"; // default
    $locale_f = "en_US"; // default

    /*
    ++ Select country from database according to the locale
    $country_f = $variable_database
    */

    setcookie('language', $locale_f, time() + (60*60*24*365), '/');
    setcookie('country', $country_f, time() + (60*60*24*365), '/');

    return array($country_f, $locale_f);
    }

... after this you can parse the content.


text:
Q: shows an empty page and says you should login first to use the sandbox hi i am trying to integrating paypal standard in nop commerce 2.4. after i set required things in admin panel, when i don't use sandbox, the cart shows up alright. but, when i enabled "use sand box" and after proceeding to payment for paypal, the site redirect to paypal to show the paypal cart, it shows an empty page and says you should login first to use the sandbox, a message like that. but when I put the site in live mode, the redirect loads the paypal checkout page as usual. i don't understand what's the problem.
i searched the internet for past few days and i am stuck in the situation.. please help me out.
as i am not rep 10 i can't upload image:
please see the link for the screen appears for my cart

A: When you set your cart to the sandbox, this is used for testing.  You would need to set up a developer account with PayPal at PayPal's Developer Site.  Once you have your developer account set up, you need to set up a test sandbox seller and buyer account.  Then you would configure your shopping cart with your sandbox acct credentials if you are going to be testing with the sandbox.  Then in a separate tab, log into PayPal's Developer Account if you are not already logged in.  Then in a different tab, you can go through and test your checkout with the sandbox.


text:
Q: Want to get single database value I have a login form which if is success to login. I want to get a name of the logged, here see my code:
 try {
             if(jTextField1.getText().equals(""))
        {
              JOptionPane.showMessageDialog(null, "Pleass Input Username");
        }
        else if(jPasswordField1.getText().equals(""))
        {
              JOptionPane.showMessageDialog(null, "Please Input Password");
        }
        else
        {
            rs = con.executeQuery("SELECT * FROM MsEmployee WHERE EmployeeID='"+jTextField1.getText()+"' And Password='"+jPasswordField1.getText()+"'");
            if (rs.next())
            {
             help.IDemployee = jTextField1.getText();
             JOptionPane.showMessageDialog(null, "Login Success! welcome "+ help.IDemployee);
             MainMenu mm = new MainMenu(true);
             mm.setVisible(true);
             this.dispose();
            }else
            {
            JOptionPane.showMessageDialog(null, "Username not found!!");
            }
        }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null,ex.getMessage());
        }

So I want to display the EmployeeName from MSEmployee which it got from EmployeeID.
I think something like this:
String qry;
qry = "Select EmployeeName From MsEmplyee WHERE EmployeeID = '" + jtextField1.gettext() + "'" ;

But when I compile, its just print the text above, not get the value. Can anyone help please?

A: As suggested in a comment, please check which name, MsEmplyee/MsEmployee, is correct.
This is not related to your problem but I think there can be one (possible) improvement in your code.
Instead of using
if(jTextField1.getText().equals(""))

It is better to use trim() method before using equals() method. So if user enters a space in jTextField1, your check will be bypassed in this case. So better to use trim() method to remove all first and last space characters from the string.
if(jTextField1.getText().trim().equals(""))

Same can be done for password field.

A: You did not read the result set value.
// help.IDemployee = jTextField1.getText();
help.IDemployee = rs.getString(1);

The column index is from 1 for the first column. Not from 0

A: You Can Try This !
String EmployeeName = rs.getString("Column Label In Database (Like EmployeeName)");
System.out.println(EmployeeName);


text:
Q: Wrong email after failed gmail login on Windows 10? My stepmother was using her Windows 10 machine today, and accidentally attempted to log in to her gmail account with (name)@gmail.xom instead of (name)@gmail.com.  The interface will not allow me to change the email back to the appropriate extension, and therefore get in.
What are our options for this?


text:
Q: How to input a text file into a java program via terminal (like how it's done in C++)? If i do

$ java ProgramName string1 string2 string3

from the linux terminal, ProgramName gets string1 string2 string3 via main(String arg[]) using arg[i], and all is well.
Here's what I want to do:
Instead of typing string1 string2 string3 at the terminal, i want to type

$ java ProgramName < input.txt

where "input.txt" contains string1, string2, and string3
Edit:
"input.txt" has one word on a separate line with an 'enter' at the end of the line
string1

string2

stringn

This can be done it C++ ; can it be done similarly in Java?

A: You can do:
export parameters=`cat file.txt`
java programname $parameters

note the inverse ` (not ')
or even:
java programname `cat file.txt`

A: Since you are redirecting a file to the standard input of your program, you can try the following:
Scanner in = new Scanner(System.in);
String line = new String();
while(in.hasNext())//while there are lines on the file
{
    line = in.nextLine();//read the line
    //do stuff here
}

A: Please use this command:
java MyProg "$(cat file.txt | tr '\n' ' ')"

If its not working please check that arguments are properly defined in source file.


text:
Q: Dynamic grid filter pipe I have a generic grid like below

Where gridColumns will be array of display columns.
dt-column-header is a component which will contain textbox for search column. It has two-way binding property filter which will be filters in grid
filters will be like grdFilters = {LastName: "123", FirstName: "456"}
My pipe is like below. I have taken reference from https://www.code-sample.com/2018/07/angular-6-search-filter-pipe-table-by.html
@Pipe({
  name: 'filterColumn'
})
export class GrdFilterPipe implements PipeTransform {
  transform(items: any, filter: any, defaultFilter: boolean): any {
    if (!filter){
      return items;
    }

    if (!Array.isArray(items)){
      return items;
    }

    if (filter && Array.isArray(items)) {
      let filterKeys = Object.keys(filter);

      if (defaultFilter) {
        return items.filter(item =>
            filterKeys.reduce((x, keyName) =>
                (x && new RegExp(filter[keyName], 'gi').test(item[keyName])) || filter[keyName] == "", true));
      }
      else {
        return items.filter(item => {
          return filterKeys.some((keyName) => {
            return new RegExp(filter[keyName], 'gi').test(item[keyName]) || filter[keyName] == "";
          });
        });
      }
    }
  }
}

My first issue is pipe is not calling when gridFilters change. I had to make it impure which will have effect on performance.
Another issue is pipe works fine with {LastName: "123"} OR {FirstName: "456"}
But not working with {LastName: "123", FirstName: "456"} OR {LastName: "", FirstName: "456"} OR {LastName: "123", FirstName: ""}

A: Quick answer:
"My first issue is pipe is not calling when gridFilters change":
RECOMENDED: Leave your pipe as a pure pipe and reassign gridFilters instead of modifying it. In other words, instead of using ngModel in your dt-column-header component, use input event and reassign gridFilters variable.
OR (NOT RECOMMENDED): Make your pipe an impure pipe by adding pure: false in the @Pipe decorator:
@Pipe({
  name: 'searchFilter',
  pure: false
})

See this StackBlitz DEMO with a working example code.
"Another issue is pipe works fine with... But not working with":
The problem is with the pipe's code:
return items.filter(item => {
  return filterKeys.some((keyName) => {
    return new RegExp(filter[keyName], 'gi').test(item[keyName]) || filter[keyName] == "";
  });
});

Apparently you didn't get the outcome you've wanted to get. The problem that you didn't mentioned the result that you want to get, what do you mean working/not working? edit your question with your needs and I'll update my answer.
Detailed answer
explaining pure/impure pipes:
Your pipe is a pure pipe (default pipe type when not using metadata pure: false in @Pipe decorator). A pure pipe will execute only when there is either a change to a primitive input value (String, Number, Boolean, Symbol) or a changed object reference (Date, Array, Function, Object).
Angular Docs - Pure pipes
Therefore, you have 2 options as a solution:
Solution 1 (recomended):
In order for your pipe to call again when gridFilters changes, you need to reassign it instead of modifying it. In other words, instead of using ngModel in your dt-column-header component, use input event and reassign gridFilters variable.
Solution 2 (not recomended):
Make your pipe an impure pipe by adding pure: false in the @Pipe decorator:
@Pipe({
  name: 'searchFilter',
  pure: false
})

This time, your pipe will execute in every component change detection cycle.
This is also why this solution is not recommend because it will be called often, as often as every keystroke or mouse-move.
Angular Docs - Impure pipes says:

With that concern in mind, implement an impure pipe with great care. An expensive, long-running pipe could destroy the user experience.


text:
Q: Optimization of Java Stream API functional interfaces for highly loaded system We have methods with Java Stream API that are invoked very frequently, e.g. 10'000 - 20'000  times per second (a data streaming system). Let's review the following simple test method (intentionally simplified and doesn't make real value):
public void test() {
        Stream.of(1, 2, 3, 4, 5)
                .map(i -> i * i)
                .filter(new SuperPredicate())
                .sorted(Comparator.comparing(i -> -i + 1,  Comparator.nullsFirst(Comparator.naturalOrder())))
                .forEach(System.out::println);
 }

class SuperPredicate implements Predicate<Integer> {
    public SuperPredicate() {
        System.out.println("SuperPredicate constructor");
    }
    @Override
    public boolean test(Integer i) {
        return i % 3 != 0;
    }
}

On each invocation of test method, new instances of functional interfaces will be created (in our example, SuperPredicate and  Comparator.nullsFirst()). So for frequent method invocations, thousands of excess objects will be created. I understand that creation of an object takes few nanoseconds in Java, but still, if we are talking about high load, it might also increase load of GC, and, as a result, influence performance.
As I see, we could move creation of such functional interfaces into private static final variables inside the same class, as they are stateless, it slightly decreases load on the system. It's kind of micro-optimization. Do we need to do this? Does Java compiler / JIT compiler somehow optimize such cases? Or maybe the compiler has some options / optimization flags to improve such cases?

A: You can only store objects in static final fields for reuse, when they don't depend on variables of the surrounding context, not to speak of potentially changing state.
In that case, there is no reason to create a class like SuperPredicate at all. You can simply use    i -> i % 3 != 0 and get the behavior of remembering the first created instance for free. As explained in Does a lambda expression create an object on the heap every time it's executed?, in the reference implementation, the instances created for non-capturing lambda expressions will be remembered and reused.
There is no need for a new comparator either. Letting potential overflows aside, using the function i -> -i + 1 does just reverse the order due to the negation whereas +1 has no effect on the order. Since the result of the expression -i + 1 can never be null, there is no need for Comparator.nullsFirst(Comparator.naturalOrder()). So you can replace the entire comparator with Comparator.reverseOrder(), to the same result but not bearing any object instantiation, as reverseOrder() will return a shared singleton.
As explained in What is the equivalent lambda expression for System.out::println, the method reference System.out::println is capturing the current value of System.out. So the reference implementation does not reuse the instance that is referencing a PrintStream instance. If we change it to i -> System.out.println(i), it will be a non-capturing lambda expression which will re-read System.out on each function evaluation.
So when we use
Stream.of(1, 2, 3, 4, 5)
    .map(i -> i * i)
    .filter(i -> i % 3 != 0)
    .sorted(Comparator.reverseOrder())
    .forEach(i -> System.out.println(i));

instead of your example code, we get the same result, but save four object instantiations, for the predicate, the consumer, the nullsFirst(…) comparator and the comparing(…) comparator.

To estimate the impact of this saving, Stream.of(…) is a varargs method, so a temporary array will be created for the arguments, then, it will return an object representing the stream pipeline. Each intermediate operation creates another temporary object representing the changed state of the stream pipeline. Internally, a Spliterator implementation instance will be used. This make a total of six temporary objects, just for describing the operation.
When the terminal operation starts, a new object representing the operation will be created. Each intermediate operation will be represented by a Consumer implementation having a reference to the next consumer, so the composed consumer can be passed to the Spliterator's forEachRemaining method. Since sorted is a stateful operation, it will store all elements into an intermediate ArrayList (which makes two objects) first, to sort it before passing them to the next consumer.
This makes a total of twelve objects, as the fixed overhead of the stream pipeline. The operation System.out.println(i) will convert each Integer object to a String object, which consists of two objects, as each String object is a wrapper around an array object. This gives ten additional objects for this specific example, but more important, two objects per element, so using the same stream pipeline for a larger dataset will increase the number of objects created during the operation.
I think, the actual number of temporary objects created before and behind the scenes, renders the saving of four objects irrelevant. If allocation and garbage collection performance ever becomes relevant for your operation, you usually have to focus on the per element costs, rather than the fixed costs of the stream pipeline.


text:
Q: Anylogic - How to extract region & province data from a map using code I'm a student using AnyLogic 7 University 7.3.6 for a simulation project.
In my project, I want to be able to distribute agents (people) over a geographical area (a city, specifically Stockholm, the capital of Sweden), and place them at imaginary "homes". I know that you can use openstreetmaps for loading maps into anylogic, and I want to able to realistically distribute people with different locations of that map.
What I wonder is:
is it possible to load a geographical map of a city from openStreetMaps or any other similar source,  write code that can extract the different regions or municipalities in that geographical area, and save them as a collection?
My guess is that is is possible but difficult.
For example, Stockholm (capital of Sweden) consists of 26 municipalities. I want to be able to load a map of Stockholm, write code that can discover the name of the different municipalities within Stockholm (or whatever city map is being used), identify how many regions or municipalities there are in that map (26 in this case) and what their names are, save these to a collection, and then for each municipality, find all of the street names in that municipalitiy.
When I have all of the municipalities of a city along with all (or most) of the street names, I can then place my agents at different streets by using the street names.
I want to be able to place a different amount of agents (people) in each municipality, and they must not be placed at unrealistic locations (such as water or terrain), thus I reckon I need the street names, so that I can realistically place them at imaginary "homes".
I have not found any valuable information of this yet, but I'm trying to. If anyone has got any advice it would be greatly appreciated!

A: I have done something similar.
To do this you need to create a shapefile that contains all the information you need (municipalities will be one layer of the shapefile (polygons) and streets will be the other layer (polylines) ) and you will read that shapefile with AnyLogic and you can generate random homes based on that.
You need to find and expert in ArcGis to help you create the shapefile according to your needs. I'm not an expert in ArcGis, but I have had someone create shapefiles for me, so that would be the first step.
Later (Second step) you will have to learn how to read shapefiles once you load them into the map in AnyLogic and transform the shapefile layers into areas and lines visible on the map... You start using the getLayers() function... You have to transform the shapefile into markup that is easily usable in AnyLogic.
At the end of the day, your question requires a lot of things, so maybe this answer will point you into the right direction, make you quit the project or be useless... Or you can find a different and easier way to simplify your project without needing so much parafernalia.


text:
Q: AES/CFB encryption with Crypto++ not working I have a simple console program that should encrypt files with AES CFB algorithm from Crypto++ library. For some reason it is not working. Encoding part:
byte data[16] = { 0x88, 0x44, 0x88, 0x44,
                  0x88, 0x44, 0x88, 0x44,
                  0x88, 0x44, 0x88, 0x44,
                  0x88, 0x44, 0x88, 0x44 };

byte result[16] = { 0x88, 0x44, 0x88, 0x44,
                  0x88, 0x44, 0x88, 0x44,
                  0x88, 0x44, 0x88, 0x44,
                  0x88, 0x44, 0x88, 0x44 };

//Sample key
byte key[16] = { 0x88, 0x44, 0x88, 0x44,
                 0x88, 0x44, 0x88, 0x44,
                 0x88, 0x44, 0x88, 0x44,
                 0x88, 0x44, 0x88, 0x44 };

//Generate random Initialization Vector
byte iv[16];
CryptoPP::AutoSeededRandomPool rnd;
rnd.GenerateBlock(iv, CryptoPP::AES::BLOCKSIZE /*16*/);

//Through VisualStudio debug/watch functionality I have found out that Crypto++ randomizer works properly so at this point "iv" contains random values

CryptoPP::CFB_Mode<CryptoPP::AES>::Encryption tmp(key, 16, iv, 1);
tmp.ProcessData(data, result, 16);

The problem is that after last line of code in this part (tmp.ProcessData(data, result, 16);) nothing in result changes.
I was guided by this official tutorial:
https://www.cryptopp.com/wiki/Advanced_Encryption_Standard


text:
Q: How to detect Installed Browsers on a Mac Machine using Node.js? Need a node-js program which can detect the Installed Browsers(or Applications) on the local machine

A: I stumbled upon this question for a few days and found the following links:-

*

*Using Electron / Node.js, how can I detect all installed browsers on macOS? [Takes time; only gave me the names of the browser, and if I needed path & version, the headers were somehow incorrect to process]

*https://github.com/litixsoft/karma-detect-browsers [Seems legit, couldn't use]

Then I came up with my own version. This assumes that the browser/application is installed in the /Application directory.
var {
  spawn
} = require('child_process');

const fs = require("fs"); // Or `import fs from "fs";` with ESM

function detectAllBrowsers(callback) {
  const browsers = [
    'Chromium',
    'Firefox',
    'Google Chrome',
    'Opera',
    'Safari',
    'TextEdit'
  ]

  var detectedBrowsers = [];
  var promises = [];

  browsers.forEach(function(browserName, index) {
    // /Applications/Google\ Chrome.app/Contents/Info.plist
    var path = '/Applications/' + browserName + '.app';
    var aPromise = new Promise(function(resolve, reject) {
      if (fs.existsSync(path)) {
        var aBrowser = {
          name: browserName,
          path: path
        }

        var sp = spawn('/usr/libexec/PlistBuddy', ['-c', 'print :CFBundleShortVersionString', path + '/Contents/Info.plist']);
        sp.stdout.setEncoding('utf8')
        sp.stdout.on('data', data => {
          aBrowser.version = data.trim();
        });

        sp.on('close', code => {
          detectedBrowsers.push(aBrowser);
          resolve('done');
        });
      } else {
        resolve('done');
      }
    });

    promises.push(aPromise);
  });

  Promise.all(promises).then(data => {
    callback(detectedBrowsers);
  });
}

detectAllBrowsers(function(detectedBrowsers) {
  console.log(detectedBrowsers);
});


text:
Q: Issue with Saxum IP Logger in Joomla 3 I became interested in the Saxum IP Logger component for Joomla after reading this stackoverflow question: Joomla! 2.5.4 Hacked: Having trouble with diagnosis
I have a Joomla 3.2.2 site, and I installed the Saxum component through the integrated component installer.  The version is the current one: 4.0.1.
My problems is that the "Reports" and the "Statistics" links on the admin screen results in a "white page" - i.e. no content loads.  All of the other portions of the Saxum tool work fine.
Normally, on a "white screen" issue within Joomla, I go to the Global Config and turn on debugging.  This usually results in a "friendly error" instead of just a white page.  But that did not work in this case.
In my list of plugins, I have the following:

*

*(enabled) Saxum IPLogger - User Plugin

*(disabled) Saxum IPLogger - System Plugin

*(disabled) Saxum IPLogger - Block IPs

I see the following database tables:

*

*saxum_iplogger (already 30 records since I installed this about an
hour ago)

*saxum_iplogger_block

*saxum_iplogger_emails

*saxum_iplogger_excp

I can't post on their support forums because they charge $15 to join, and there hasn't been a post there in nearly 6 months.  I don't mind donating to anyone's project once I decide that I'm going to use it, but pay ahead of time for possibly non-existent support doesn't sit well with me.
I'm not sure where to begin troubleshooting from here.
Ideas or pointers welcome.
Thanks,
Jimmy

A: The problem was reported on the support forum of the extension and it is already resolved.


text:
Q: ES6 arrow / function equivalency I'm just getting around to changing some of my code to ES6 and I ran across some code where the arrow function did not work and I am not sure I understand why. The code is from a plugin for Hapi to decorate the reply interface.
ES5:
server.decorate('reply', 'test', function(schema, response) {
  return this.response(mask(schema, response));
});

ES6:
server.decorate('reply', 'test', (schema, response) => {
  return this.response(mask(schema, response));
});

The E66 doesn't work and throws an error:
Uncaught error: this.response is not a function

Why is this?

A: In this particular case, the library is changing what this refers to inside the callback for decorate. When using arrow functions (=>), this is equivalent to the this of the outer scope. This means that you're basically stuck using function for this.


text:
Q: Extracting postcode from address I have a housing data set with an address column. I want to visualize the correlation between postcode and price. However, the address is in the format (Norfolk Road, Edgbaston, Birmingham B15). How do I extract the postcode alone?
I have tried using
select substring_index(Address, ',', -1)

but it gave me an error:
File "<ipython-input-29-2b936e3b990e>", line 1
    select substring_index(Address, ',', -1)
                         ^
SyntaxError: invalid syntax

How do I extract only the postcode, in this case B15?
What is the best way to visualize this data, since its a categorical variable not continuous. I think I should group the postcodes, but do I create a dummy?

A: If your data are in a pandas DataFrame you can use the function extract() like this :
df["PostCode"] = df["Address"].str.extract(r"([A-Z]\d+)")
The function extract() uses the regexp to extract the first occurence of a capital letter followed by a one or several numbers representing the postcode you need.
Hope it helps


text:
Q: PHP Version of Laravel Does a Laravel project require 2 versions of PHP ?
I am working on a Laravel project. I have 2 versions of PHP in my computer. If I set PHP version 8.1 and run composer update I am getting below error.

If I set PHP version 7.4 and run composer update I am getting below error.

What will be the solution ?

A: No, it does not require more than one PHP version, yet you need to be consistent. In fact your problem is not Laravel related at all. It's solely a composer related thing.
For me it looks like you installed your project and alle the dependencies using PHP 8.1 in first place and now you want to lower the target version to 7.4. But composer update running on PHP 7.4 will fail (as you saw) because it simply cannot handle downgrade installed project to match new environment. Also some of your dependencies are already pulled in PHP 8 only version (as error message said) and composer do not handle such case either.
If your target version is 7.4 (note Laravel 8 is last version supporting PHP 7), then I'd suggest to simply remove completely vendor/ folder and composer.lock file, then run composer install using PHP 7.4 to re-set up the project and dependencies using that version of the environment. I'd then try stick to PHP 7.4 version for future composer invocations to avoid similar problems.
PS: I personally have set up wrappers like composer56, composer74, composer81 setup on my development machine specifically for that reason.


text:
Q: Who is using a SQL Server database user credential? I have a database user -- let's say "x" -- and I want to know how many Windows (desktop) users are using this database user (who2 or who is only give the current result, I want to know the entire history)?
Actually this question arise when you join any new organization and you don't know how many Windows or desktop users are using a specific database user. Is there any way to know this? How do you track all Windows users who are using this (x) user credential?

A: You could use a logon trigger perhaps, going forward (see here and here).
For historical information, by default, SQL Server doesn't even track successful logins (though this can be turned on - however it means you will need to parse the SQL Server log for some little bit of information). So while you might get some information (such as which workstations were using which logins) from the default trace, it would rely on them performing actions that get logged there (and would only go back as far as your default trace data goes anyway).
Also see this answer.

A: From a historical perspective, if login auditing was enabled on the server then you could see the logins in the SQL Log and use the IP to trace back to user's workstation or server. This is useless, however, if users are remoting into the SQL host and making a local connection to it (though they really shouldn't be...)
If that's not available to you, then either enable login auditing or setup an Extended Events trace to track user's workstations/IP as they login to the system.
If this is a "development box" (read: non-production) and you're concerned about too many users sharing a credential, a (potentially) drastic option would be to lock the account and see who comes to complain. This would allow you to easily assign new, individual credentials you can control to the users and is more likely to catch someone who logs in infrequently since you can keep the login disabled for an extended period of time but may not want to dig through Extended Event logs for days/weeks/months.
Finally, you could always send out an email blast and see who responds. It probably won't give you the full picture of who has the credentials, but could provide a good start and open a dialog with those who use them most frequently if you plan on making changes in the future.


text:
Q: Parse.js onResize() with rectangle I'm very new to Paper.js and not that familiar with JS (be happy, these are some easy rep points!)
I want to center a rectangle in a canvas and I succeed. The problem is that I'd like that this rectangle stays in the middle when onResize is called and the doc didn't explain that very well or, at least, I didn't find something consistant.
Here is my code:
createYearBar(1983, 2015);

function createYearBar(yearStart, yearEnd){
    var yearsToDraw = (yearEnd - yearStart);
    var topLeftX = view.center.x * 0.2;
    var topRightX = view.center.x * 1.8;
    var barSize = topRightX - topLeftX;
    var perYear = (barSize)/yearsToDraw;
    var topleft = new Point(topLeftX, 20);
    var size = new Size(barSize, 30);
    var rect = new Rectangle(topleft, size);
    var barPath = new Path.Rectangle(rect);
    barPath.strokeColor = 'black';
    barPath.fillColor = 'black'
}

So it draws a rectangle like I want but it does nothing when I resize. I do not get why because this view.center.x should come from the framework.
It is a bit better if I add:
function onResize(event) {
    createYearBar(1983, 2015);
}

because my bar can get bigger but not smaller because it just adds bars over the already existing ones.
My question is:
Do I need to that manually and delete and recreate the bar manually or did I miss something trivial (I assume that I missed something!)?

A: You're missing a couple of things, but you are correct in your guess: the easiest thing to do is destroy and recreate a bar on each resize event.
view.center just returns a regular coordinate when you call it. If a view is 300x400, view.center will return a new Point object at [150, 200]. It is not a dynamic point that updates the positions of objects when you resize the window.
The problem is that you aren't removing the barPath object when you resize the view. It's much easier to do this if your function returns an object instead of creating one anonymously inside a function scope:
var barPath = createYearBar(1983, 2015);

function createYearBar(yearStart, yearEnd){
    var yearsToDraw = (yearEnd - yearStart);
    var topLeftX = view.center.x * 0.2;
    var topRightX = view.center.x * 1.8;
    var barSize = topRightX - topLeftX;
    var perYear = (barSize)/yearsToDraw;
    var topleft = new Point(topLeftX, 20);
    var size = new Size(barSize, 30);
    var rect = new Rectangle(topleft, size);
    barPath = new Path.Rectangle(rect);
    barPath.strokeColor = 'black';
    barPath.fillColor = 'black';
    return barPath;
}

function onResize(event) {
    barPath.remove();
    barPath = createYearBar(1983, 2015);
}


text:
Q: Unmarshal mapped structure First of all I have one structure:
type times map[time.Time]struct{}

I need to write for it Marshal/Unmarshal methods for json converting. I've wrote MarshalJSON method, but do not understand how to write UnmarshalJSON method.
func (ts times) keys() []time.Time {
    res := make([]time.Time, 0, len(ts))
    for key := range ts {
        res = append(res, key)
    }
    return res
}

func (ts times) MarshalJSON() ([]byte, error) {
    return json.Marshal(ts.keys())
}

func (ts *times) UnmarshalJSON(b []byte) (error) {
    // ????
}

Any idea?

A: You can decode json with the same way as you encoded(by taking only keys):
func (ts *times) UnmarshalJSON(b []byte) error {
    var t []time.Time

    err := json.Unmarshal(b, &t)
    if err != nil {
        return err
    }

    for _, v := range t {
        (*ts)[v] = struct{}{}
    }

    return nil
}

See: https://play.golang.org/p/0ViEBX_5iLw
But, I highly recommend to use a slice type, not a map.
The decoded output is an array, so the type should also be an array too.


text:
Q: C++ access members and functions I'm fairly familiar with Java and C# and want to broaden my horizon with C++.
But I am having trouble to understand when to use the -> or the . operator when accessing a member or a method of an objcect.
I'm sure that I'm not the first one to ask this question. There are a lot of questions out there that tackle the same problem, but I just can't relate the provided answers to my special case.
I have a very simple class that is called Stock:
class Stock
{
public:
    int32_t value;
    string name;

    Stock(void);
    ~Stock(void);

    void doStuff();
};

I know that if the object is allocated on the heap I have to use -> and . when it resides in stack space.
But if I wanted to print the length of the name string of a Stock object I would need to do something like this:
Stock* bmw = new Stock;
bmw->name = "BMw";
cout << bmw->name.length() << endl;

The name of the stock is accessed via the "->" operator, the length of the name via the "." operator.
In my view, both of these objects (the stock and the string) reside in heap space, so i would only need the -> operator, right?
What am I missing here? How is it with strings? I thougt strings are always pointers...
Could you please explain the concepts that are working here a bit?
Thanks in advance for your replies.
Markus

A: -> is used when you have a pointer, . is used when you have an instance.
In your example, bmw is a pointer to a Stock instance, so you reference it's members by using the -> operator.  the name field is a string instance, so you use the . operator.
You could also write it as
(*bmw).name = "BMw";

Since *bmw returns the instance whose address is stored in the varialbe bmw
It's as simple as that - don't confuse yourself by bringing in the stack and heap.  Those are just memory allocation implementation details.

A: Just know that you use the arrow operator (->) when u point to an object.
in your case, the name member is not a pointer to std::string, so you can't use the arrow operator, instead you use the dot (.).
you could do something like this :
std::string* name;
Stock* sptr = new Stock;
sptr->name = new std::string("blah blah blah");
std::cout << sptr->name->length << std::endl;

A: bmw->name.length()

bmw is a pointer to your Stock object created on heap. So do access its member (like in your case name ) you have to use ->. After "bmw->name" would give you the string object. And that string object is not allocated using new means it's not on heap. So, do access it's member ( like length() in this case ) you have to use '.' .

A: "use "->" for object that allocated in heap" is not accurate.
Simply when you want access to members of an object via pointer,you must use"->".
For other situation use ".".

A: Welcome to the native world, ruled by C++ !
In C++, you need to use -> only when expression on left evaluates to a pointer of a class, struct or a union, otherwise use .. A function may also return a pointer to a object, and there you need to use -> operator:
Stock* GetStockByIndex(int);
GetStockByIndex(0)->value;

Usage of -> is not bound to new/heap, and usage of .is not bound to stack allocated object. It is just the context (expression on left).
In near future, you will also see that:
Stock s;
s->calculate();

How is that possible, you might wonder. It is because C++ allows -> to be overloaded!
Welcome!


text:
Q: Не могу понять почему выводит true данный код Был бы весьма благодарен за разъяснение, почему вывидит true и покакому принципу.
Условие такое:
Рассмотрим задачу о пересечении двух длительных по времени событий. Оба события характеризуются двумя числами - годами начала и конца. Необходимо определить, пересекались ли события во времени, при этом если одно событие началось в тот год, когда закончилось другое - они считаются пересекающимися.
Вот решение
start1 = int(input())
finish1 = int(input())
start2 = int(input())
finish2 = int(input())
answer = start1 <= finish2 and start2 <= finish1
print(answer)

Почему если ввести значения
start1 = 1(x1)
finish1 = 3(y1)
start2 = 2(x2)
finish2 = 4(y2)

то выводит true, а если поменять значение start2 на 5, то folse(но это понятно почему, т.к условие не выполняется), но хотя эти два отрезка идентичные, но в одном folse, а в другом true
Ведь отрезок 1,3 и 2,4 вообще не пересекаются если их отобразить на координате x и y

A: Давайте просто подставим значения:
answer = 1 <= 4 and 2 <= 3

Это равно:
answer = True and True
answer = True

Код у вас верный. Программа работает правильно.


text:
Q: Only displaying part of a returned MySQL Query? I am trying to filter out results of a MySQL query. I am pulling data from a Wordpress database. Specifically, I am trying to pull just the user role.
In Wordpress, the returned value is something like this:
a:1:{s:13:"administrator";s:1:"1";}

All I want to see returned is the "administrator", "author", "subscriber", etc, and not all the other information.
From my understanding (I am very much a beginner however), I can't use a substr() because the length of characters is different, and the information before the role varies as well.
Is there anyway to filter out all the other information and just return "administrator" in the MySQL query directly?
Here is my current query (I am also pulling names, email address, passwords, etc from another table):
SELECT wp_users.ID, wp_users.user_email, wp_users.user_pass, wp_users.display_name, wp_usermeta.user_id, wp_usermeta.meta_value
FROM wp_users
JOIN wp_usermeta
ON wp_users.ID = wp_usermeta.user_id
WHERE (wp_usermeta.meta_value LIKE '%admin%')
OR (wp_usermeta.meta_value LIKE '%author%')
OR (wp_usermeta.meta_value LIKE '%subscriber%')

A: The string is PHP serialized (serialized via serialize() PHP function).
At first you need it deserialize:
$dbValue = 'a:1:{s:13:"administrator";s:1:"1";}';
$arr = unserialize($dbValue)

print_r($arr);

Which outputs:
array(1) {
  ["administrator"]=>
  string(1) "1"
}

If you are sure, that the role/user group will be always first, you can get it like.
$role = array_keys($arr)[0];

Did I solve your problem?

A: That's PHP's serialization data format, so you can simply use unserialize to get it parsed back into a usable data structure.
(And if you are not totally sure what that data structure contains, then use var_dump to make a debug output of it.)


text:
Q: Why did my Herokuapp idle and shut down while in use? Why did my free-tier (but credit-card confirmed) Heroku app idle and shut down unexpectedly while being used?  I was watching it log my activity on an active connection to the app when it suddenly idled and shut down.
heroku[web.1]: Idling
heroku[web.1]: State changed from up to down
heroku[web.1]: Stopping all processes with SIGTERM
heroku[web.1]: Process exited with status 143
heroku[router]: at=info method=GET path="/socket.io/?...
heroku[web.1]: Unidling
heroku[web.1]: State changed from down to starting
heroku[web.1]: Starting process with command `npm start`
app[web.1]:
app[web.1]: > start /app<some other stuff>
app[web.1]: > node index.js $PORT
app[web.1]:
app[web.1]: Server running on port 45155.
2heroku[web.1]: State changed from starting to up

A: As stated by Heroku
If an app has a free web dyno, and that dyno receives no web traffic in a 30-minute period, it will sleep.
If your account has free dyno hours left then it will become active as soon as web traffic is received.
Personal accounts are given a base of 550 free dyno hours each month. In addition to these base hours, accounts that verify with a credit card will receive an additional 450 hours added to the monthly free dyno quota. This means you can receive a total of 1000 free dyno hours per month if you verify your account with a credit card.
Make sure you haven't utilized your free 1000 Hours!! which is pretty evident is not the case since your app restarted!!
The traffic might be the issue!


text:
Q: how to fetch a list from a SQlite database in flutter app I use SQlite database using sqflite package in my Flutter App.
I want to convert a map list to an announcement list, but I have a compilation error
    final Database db = await database;
    final List<Map<String, dynamic>> maps = await db.query('announcement');
    List<Announcement> announcements = List.generate(maps.length, (i) => {return Announcement.fromMap(maps[i]);});

The error is under return Announcement.fromMap(maps[i]): The return type 'Set<Announcement>' isn't a 'Announcement', as required by the closure's context.dartreturn_of_invalid_type_from_closure)
please help me to solve this error.

A: It seem you mistakenly placed some brackets around the final line which makes dart treat the argument inside like a set.
Replace
List<Announcement> announcements = List.generate(maps.length, (i) => {return Announcement.fromMap(maps[i]);});

with
List<Announcement> announcements = List.generate(maps.length, (i) => Announcement.fromMap(maps[i]););

For context: There are two ways you can write this line. Either with the (i) => ... syntax or via the more verbose (i) {return ...;} syntax. You mixed those two up.


text:
Q: Why pycharm can not find this attributes and methods reference? Why pycharm can not find this attributes and methods reference?
class A:
    def __init__(self):
        print("A.__init__")

        self.method_need_B()
        self.method_need_C()

        print(self.attr_need_B)
        print(self.attr_need_C)

class B(A):
    def __init__(self):
        print("B.__init__")
        self.attr_need_B = "I am 'attribute' and A need me, but live in B"
        A.__init__(self)

    def method_need_B(self):
        print("I am 'method' and A need me, but live in B")

class C(B):
    def __init__(self):
        print("C.__init__")
        self.attr_need_C = "I am 'attribute' and A need me, but live in C"
        B.__init__(self)

    def method_need_C(self):
        print("I am 'method' and A need me, but live in C")

c = C()

this code on picture, i am not undestand why pycharm not visible this attrs and methods
outputs without errors:
C.__init__
B.__init__
A.__init__
I am 'method' and A need me, but live in B
I am 'method' and A need me, but live in C
I am 'attribute' and A need me, but live in B
I am 'attribute' and A need me, but live in C

A: The script works without errors but it is very situational: it only works for the case displayed on your question.
What if, for instance, you call c = B()?
That's the output:
B.__init__
A.__init__
I am 'method' and A need me, but live in B
Traceback (most recent call last):
  File "C:\Users\xxx\Documents\test.py", line 29, in <module>
    c = B()
  File "C:\Users\xxx\Documents\test.py", line 15, in __init__
    A.__init__(self)
  File "C:\Users\xxx\Documents\test.py", line 6, in __init__
    self.method_need_C()
AttributeError: 'B' object has no attribute 'method_need_C'. Did you mean: 'method_need_B'?

Why it didn't worked on c = B(), but it worked on c = C()?
When you assign c an instance of class C, the class constructor calls B.__init__(self), which inside B constructor, it calls A.__init__(self).
So, c is an object with A, B and C methods and properties. As all of them have different function and variable names, they do not get overwritten once you inherit each parent's data.
Now, why does c = B() does not work?
It's because that on class A, you're trying to access class C methods and properties, and class C was never initialized inside class B instance. So basically, as C.__init__(self) is never called on this instance, then self.method_need_C() and self.attr_need_C are not allocated.
Now, you asked, why on c = C() these methods are visible? It's because that on python, self refers to the instance of the class that you created, which in this case is C.
Sure, the script being executed is inside class A, but have you tried to print self to see what is its type inside class A's constructor?
# By modifying your script, we now print self to see its type:
class A:
    def __init__(self):
        print("A.__init__: ", self)

        self.method_need_B()
        self.method_need_C()

        print(self.attr_need_B)
        print(self.attr_need_C)

This is the output:
C.__init__
B.__init__
A.__init__:  <__main__.C object at 0x0000029641A27B80>
I am 'method' and A need me, but live in B
I am 'method' and A need me, but live in C
I am 'attribute' and A need me, but live in B
I am 'attribute' and A need me, but live in C

As self refers to a class C instance, even inside class A it contains class B and class C methods and properties. So they are visible as long as you use self on the script.
Again, this only works because you're creating a class C instance. Instantiating another class type will get you lots of errors.
One thing you can do, if you really need to call class C and class B methods inside class A, is to use isinstance() function, as displayed below:
class A:
    def __init__(self):
        print("A.__init__: ", self)

        if (isinstance(self, B)):
            self.method_need_B()

        if (isinstance(self, C)):
            self.method_need_C()

        if (isinstance(self, B)):
            print(self.attr_need_B)

        if (isinstance(self, C)):
            print(self.attr_need_C)

class B(A):
    def __init__(self):
        print("B.__init__")
        self.attr_need_B = "I am 'attribute' and A need me, but live in B"
        A.__init__(self)

    def method_need_B(self):
        print("I am 'method' and A need me, but live in B")

class C(B):
    def __init__(self):
        print("C.__init__")
        self.attr_need_C = "I am 'attribute' and A need me, but live in C"
        B.__init__(self)

    def method_need_C(self):
        print("I am 'method' and A need me, but live in C")

c = B()

The output now does not give you any errors:
B.__init__
A.__init__:  <__main__.B object at 0x000001F82AA57F70>
I am 'method' and A need me, but live in B
I am 'attribute' and A need me, but live in B

That's because you're testing to see if self is an instance of class C or class B and prevent accessing methods and properties that do not exist, in case they are not instances of those classes.

A: Because they do not exist inside A class.
Not only pycharm cannot find references. The python interpreter would not be able to find it as well. If you will try such instruction:
a = A()
you will get error.
Why your code sample works though?
You are calling inside C.__init__ such instruction: B.__init__(self), the self object does have the method_need_C, and going down, you add second method the same way in the B class. So the self in the A class does have those two methods.