text:
Q: ListView not binding When I run the app, I get two tabs (Im using Tabbed Page) but they are blank.
I have a somewhat complex ViewModel:
        public partial class NowPlayingView
{
    const string NowPlayingUrl = "http://api.myserver.com";
    public static List<MoviesItem> MoviesLst { get; set; }

    public NowPlayingView()
    {
        InitializeComponent();
        BindingContext = new MoviesViewModel();
    }
    public class MoviesViewModel
    {
        public MoviesViewModel()
        {
            Action<Dictionary<string, string>> initAction = initialize;
            initAction(new Dictionary<string, string>()
                {
                    {"$format", "json"},
                    {"AccessKey", "f54tg5gf54g-fgs3452-324asdf4"},
                    {"CineplexLanguage", "en-us"}
                });
        }

        public async void initialize(Dictionary<string,string> parameters)
        {
            var data = await (new ApiUtilities().CallGetData<MoviesNowPlaying>(NowPlayingUrl, "/api.svc/MoviesNowPlaying", parameters));
            MoviesLst = data.d.results.Select(x => new MoviesItem() {Header = x.Title, Text = x.MediumPosterImageURL}).ToList();
        }
    }
    public class MoviesItem
    {
        public string Header { get; set; }
        public string Text { get; set; }
    }
}

My XAML file look like this:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                       xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                       x:Class="XamPlex.MainCategories.NowPlayingView"
             Title="Now Playing">
    <ListView x:Name="MoviesListView" RowHeight="80" BackgroundColor="Transparent" ItemsSource="{Binding MoviesLst}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <ViewCell.View>
                        <StackLayout Orientation="Vertical" Spacing="0" Padding="10">
                            <Label Font="Bold,20" Text="{Binding Header}" TextColor="Indigo"/>
                            <Label Font="16" Text="{Binding Text}" TextColor="Indigo"/>
                        </StackLayout>
                    </ViewCell.View>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage>

I checked the contents of MoviesLst and it contains plenty of data, any ideas what could be wrong?

A: I do not do a lot of MVC, but I believe the View should have this form:
public ActionResult Index() {
    return View();
}

I would think your View should be structured something like...
public ActionResult Index() {
    var data = await (new ApiUtilities().CallGetData<MoviesNowPlaying>(NowPlayingUrl, "/api.svc/MoviesNowPlaying", parameters));
    var list = data.d.results.Select(x => new MoviesItem() {Header = x.Title, Text = x.MediumPosterImageURL}).ToList();
    return View(list);
}

Again, though, I have only worked through the basic tutorials on MVC. I could be misunderstanding your model.
I don't see where you are posting your View anywhere. What I see appears to be the Model.


text:
Q: Linking error using soci 3.2.3 instead of 3.2.2 I have a project which uses soci for DB access. The project was originally developed with soci 3.2.2.
Now I switched to soci 3.2.3 and get the following linker error messages:
error LNK2001: unresolved external symbol "public: class soci::details::once_temp_type & __thiscall soci::details::once_temp_type::operator,(class soci::details::type_ptr<class soci::details::use_type_base> const &)" (??Qonce_temp_type@details@soci@@QAEAAV012@ABV?$type_ptr@Vuse_type_base@details@soci@@@12@@Z)

error LNK2001: unresolved external symbol "public: void __thiscall  soci::details::statement_impl::exchange_for_rowset(class soci::details::type_ptr<class soci::details::into_type_base> const &)" (?exchange_for_rowset@statement_impl@details@soci@@QAEXABV?$type_ptr@Vinto_type_base@details@soci@@@23@@Z)

error LNK2001: unresolved external symbol "public: class soci::details::prepare_temp_type & __thiscall soci::details::prepare_temp_type::operator,(class soci::details::type_ptr<class soci::details::use_type_base> const &)" (??Qprepare_temp_type@details@soci@@QAEAAV012@ABV?$type_ptr@Vuse_type_base@details@soci@@@12@@Z)

I use Visual Studio 2010 on a Windows machine.
Does somebody has an idea what could be the issue?
Bests

A: The Solution was using the newest error corrected Soci library from github and not the stable download version.
Bests

redpajama_set_name: RedPajamaStackExchange


text:
Q: unable to find weblogic.management.mbeanservers.domainruntime I am using a code from internet to get server's health status. weblogic.management.mbeanservers.domainruntime is used in that code and I am unable to find its jar. I am not using maven so please don't suggest maven. How can i get this jar

A: First of all, make sure your monitoring application is connecting to AdminServer as it's the only server in WebLogic domain that has domainruntime MBean server running. Then, try adding WebLogic client jar(i.e. wlthint3client.jar/wlfullclient.jar/wljmxclient.jar) to your monitoring application classpath.
More on WebLogic Stand-alone clients can be found on: https://docs.oracle.com/middleware/1213/wls/SACLT/basics.htm#SACLT125


text:
Q: Alternative approaches for Debugging a Visual Studio .net application using azure service bus In the past when I develop SharePoint Provider-Hosted apps which implement remote event receivers, i use the Azure Service Bus to debug the code, as mentioned in this https://blogs.msdn.microsoft.com/kaevans/2014/02/26/attaching-remote-event-receivers-to-lists-in-the-host-web/ , where inside Azure i create a new service bus >> i copy the primary connection string, as follow:-

then inside the Visual Studio project >> Properties >> SharePoint >> i add the above service bus's primary connection string, as follow:-

this was allowing me to debug my code. but last week when i tried to do so, I got these errors inside Visual studio after running the project:-

One or more services were unregistered from the Microsoft Azure
Service Bus. Cannot register Services/AppEventReceiver.svc on
Microsoft Azure Service Bus: Unable to connect to the remote server

as follow:-

so i read that using azure service bus has been retired by Microsoft starting from september 2018. but at the same time i did not find any alternative for using Azure Service Bus for debugging the sharepoint provider hosted app. So can anyone advice on this please?

A: You can use ngrok as a proxy to debug your application locally without using Service Bus.
The issue with passing localhost to Sharepoint is that Sharepoint cannot talk to it as you have pointed out. ngrok provides you with a public URL that Sharepoint can reach that is then is routed to your local machine via the ngrok service.This is the same thing that Service Bus was doing- offering a public URL routed to your local.
Instead of registering localhost:44332/Services/AppEventReceiver.svc with Sharepoint, you would register {id}.ngrok.io/Services/AppEventReceiver where id is the id generated when you start the local ngrok service.


text:
Q: C - conflicting error messages "implicit declaration of" and "nested extern declaration" for an existing and defined macro ++=UPDATE 1=++
Running through with -E returns the following:
# 100 "/usr/include/sys/byteorder.h" 3
#define BSWAP_64(x) (((uint64_t)(x) << 56) | (((uint64_t)(x) << 40) & 0xff000000000000ULL) | (((uint64_t)(x) << 24) & 0xff0000000000ULL) | (((uint64_t)(x) << 8) & 0xff00000000ULL) | (((uint64_t)(x) >> 8) & 0xff000000ULL) | (((uint64_t)(x) >> 24) & 0xff0000ULL) | (((uint64_t)(x) >> 40) & 0xff00ULL) | ((uint64_t)(x) >> 56))
...
#define _LP64 1
...
# 86 "LALCityHash.c" 2
#define bswap_32(x) BSWAP_32(x)
#define bswap_64(x) BSWAP_64(x)
# 117 "LALCityHash.c"
#define UINT4_in_expected_order(x) (bswap_32(x))
#define UINT8_in_expected_order(x) (bswap_64(x))

It appears to make it through the CPP.
Full content at https://pastebin.com/u6VU9sie
LALCityHash.c source at https://pastebin.com/GfQ3CxBX
--=UPDATE 1=--
I am compiling LIGO software packages for SPARC/Solaris and run into errors. LALCityHash.c provides an alias for BSWAP_64 which doesn't seem to be getting through with the necessary #includes provided in the unmodified code.
I have tried to see if redefining the defines elsewhere helps just in case the "#if defined(__sun) || defined(sun)" lines are not being parsed. Even stripping out the .h includes using the required code locally to the file does not work. I just can't figure out what I am overlooking.
The LALCityHash.c includes the following lines:
#elif defined(__sun) || defined(sun)

#define bswap_32(x) BSWAP_32(x)
:87 =>  #define bswap_64(x) BSWAP_64(x) <=
...
:118 => #define UINT8_in_expected_order(x) (bswap_64(x)) <=
...
static UINT8 Fetch64(const char *p) {
:133 =>   return UINT8_in_expected_order(UNALIGNED_LOAD64(p)); <=
}

Produces both errors below:
implicit declaration of function 'BSWAP_64'
nested extern declaration of 'BSWAP_64'
The OS include file for Solaris is sys/byteorder.h and is defined as the following:
#if defined(_LP64) || defined(_LONGLONG_TYPE)
#if (!defined(__i386) && !defined(__amd64))
#define BSWAP_64(x) (((uint64_t)(x) << 56) | \
            (((uint64_t)(x) << 40) & 0xff000000000000ULL) | \
            (((uint64_t)(x) << 24) & 0xff0000000000ULL) | \
            (((uint64_t)(x) << 8)  & 0xff00000000ULL) | \
            (((uint64_t)(x) >> 8)  & 0xff000000ULL) | \
            (((uint64_t)(x) >> 24) & 0xff0000ULL) | \
            (((uint64_t)(x) >> 40) & 0xff00ULL) | \
            ((uint64_t)(x)  >> 56))
#else /* x86 */
#define BSWAP_64(x) htonll(x)
#endif  /* !__i386 && !__amd64 */
#else /* no uint64_t */
#define BSWAP_64(x) ((BSWAP_32(x) << 32) | BSWAP_32((x) >> 32))
#endif  /* _LP64 || _LONGLONG_TYPE  */

Making all in utilities
gmake[4]: Entering directory '/export/home/tidytibs/ligo/lal-6.19.2/src/utilities'
  CC       LALCityHash.lo
LALCityHash.c: In function 'Fetch64':
LALCityHash.c:87:21: error: implicit declaration of function 'BSWAP_64' [-Werror=implicit-function-declaration]
 #define bswap_64(x) BSWAP_64(x)
                     ^
LALCityHash.c:118:37: note: in expansion of macro 'bswap_64'
 #define UINT8_in_expected_order(x) (bswap_64(x))
                                     ^~~~~~~~
LALCityHash.c:133:10: note: in expansion of macro 'UINT8_in_expected_order'
   return UINT8_in_expected_order(UNALIGNED_LOAD64(p));
          ^~~~~~~~~~~~~~~~~~~~~~~
LALCityHash.c:87:21: error: nested extern declaration of 'BSWAP_64' [-Werror=nested-externs]
 #define bswap_64(x) BSWAP_64(x)
                     ^
LALCityHash.c:118:37: note: in expansion of macro 'bswap_64'
 #define UINT8_in_expected_order(x) (bswap_64(x))
                                     ^~~~~~~~
LALCityHash.c:133:10: note: in expansion of macro 'UINT8_in_expected_order'
   return UINT8_in_expected_order(UNALIGNED_LOAD64(p));
          ^~~~~~~~~~~~~~~~~~~~~~~
LALCityHash.c: In function 'Fetch32':
LALCityHash.c:86:21: error: implicit declaration of function 'BSWAP_32' [-Werror=implicit-function-declaration]
 #define bswap_32(x) BSWAP_32(x)
                     ^
LALCityHash.c:117:37: note: in expansion of macro 'bswap_32'
 #define UINT4_in_expected_order(x) (bswap_32(x))
                                     ^~~~~~~~
LALCityHash.c:137:10: note: in expansion of macro 'UINT4_in_expected_order'
   return UINT4_in_expected_order(UNALIGNED_LOAD32(p));
          ^~~~~~~~~~~~~~~~~~~~~~~
LALCityHash.c:86:21: error: nested extern declaration of 'BSWAP_32' [-Werror=nested-externs]
 #define bswap_32(x) BSWAP_32(x)
                     ^
LALCityHash.c:117:37: note: in expansion of macro 'bswap_32'
 #define UINT4_in_expected_order(x) (bswap_32(x))
                                     ^~~~~~~~
LALCityHash.c:137:10: note: in expansion of macro 'UINT4_in_expected_order'
   return UINT4_in_expected_order(UNALIGNED_LOAD32(p));
          ^~~~~~~~~~~~~~~~~~~~~~~
cc1: all warnings being treated as errors
gmake[4]: *** [Makefile:586: LALCityHash.lo] Error 1

A: Solved: It appears that LALCityHash.c includes the Solaris sys/byteorder.h which has a define of
#define BSWAP_32(x) (((uint32_t)(x) << 24) | (((uint32_t)(x) << 8) & 0xff0000) | (((uint32_t)(x) >> 8) & 0xff00) | ((uint32_t)(x) >> 24))
#define BSWAP_64(x) (((uint64_t)(x) << 56) | (((uint64_t)(x) << 40) & 0xff000000000000ULL) | (((uint64_t)(x) << 24) & 0xff0000000000ULL) | (((uint64_t)(x) << 8) & 0xff00000000ULL) | (((uint64_t)(x) >> 8) & 0xff000000ULL) | (((uint64_t)(x) >> 24) & 0xff0000ULL) | (((uint64_t)(x) >> 40) & 0xff00ULL) | ((uint64_t)(x) >> 56))

and does another define as an alias
# 86 "LALCityHash.c" 2
#define bswap_32(x) BSWAP_32(x)
#define bswap_64(x) BSWAP_64(x)

Building here doesn't like this.
Instead, replacing the LALCityHash.c "bswap_32/64" definitions with sys/byteorder.h's "BSWAP_32/64" definitions work:
86,87c86,97
< #define bswap_32(x) BSWAP_32(x)
< #define bswap_64(x) BSWAP_64(x)
---
> #define bswap_32(x) (((uint32_t)(x) << 24) | \
>                         (((uint32_t)(x) << 8) & 0xff0000) | \
>                         (((uint32_t)(x) >> 8) & 0xff00) | \
>                         ((uint32_t)(x)  >> 24))
> #define bswap_64(x) (((uint64_t)(x) << 56) | \
>                         (((uint64_t)(x) << 40) & 0xff000000000000ULL) | \
>                         (((uint64_t)(x) << 24) & 0xff0000000000ULL) | \
>                         (((uint64_t)(x) << 8)  & 0xff00000000ULL) | \
>                         (((uint64_t)(x) >> 8)  & 0xff000000ULL) | \
>                         (((uint64_t)(x) >> 24) & 0xff0000ULL) | \
>                         (((uint64_t)(x) >> 40) & 0xff00ULL) | \
>                         ((uint64_t)(x)  >> 56))

I still do not see how a valid #define alias of a #define doesn't work here.


text:
Q: How to override css style of shadow dom I am using the fluent ui web component for autocomplete drop-down. I want to change the background of the drop-down box but there is a #shadow-root(open) created which I am not able to override. So please help me how to override this shadow dom.
I attached the image of my inspect where I want to override .control class inside the #shadow-root

A: Div content has part attribute. It make your work done.
Add this line in your css file
fluent-combobox::part(control) {
    //add your css properties
}

Read more at MDN ::part


text:
Q: Python : sending a hyperlink Windows network path that contains white spaces in email I'm facing an issue to send a full network path of Windows as a hyperlink in email using Python, when I send it, users receive a broken link at the first white space in the path :
toaddr = ['mail1@exemple.com']
to_cc = ['mail2@exemple.com', 'mail3@exemple.com']
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = ','.join(toaddr)
msg['CC'] = ','.join(to_cc)
msg['Subject'] = "The report"
path = "\\\\windows_Server\\golobal_directory\\the folder\\file yyymm.xlsx"
body = 'this the body text of the mail'+ path
msg.attach(MIMEText(body, 'plain'))
...

after sending my email, the users receive something like this :
\\windows_Server\golobal_directory\the folder\file yyymm.xlsx
have you any ideas how can fix this ?
thanks !

A: I have a strong feeling that you might have to enclose the entire path in double quotes.
path = "\"\\\\windows_Server\\golobal_directory\\the folder\\file yyymm.xlsx\""

A: This solution of enclosing the entire path worked for me.  I was running into similar issue sending as a hyperlink in the email.
In addition to adding double quotes around shared drive path:
email_body ='Report! Weve successfully created a report!!  Go to the link : click here'

msg = MIMEText(email_body,'html')


text:
Q: Stratos 1.6.0 - Messaging between Storage Server and Data Service Service I am configuring Stratos 1.6.0 and trying get the following scenario working.

*

*Create a database in Storage Server

*Create a user in Storage Server

*Assign the user to the database

*Generate datasource for the user/database combination in the Storage Server

*Create DataService in Data Service Server and use the data source above

From what I can see in the code... when one creates a datasource in a Carbon application, the org.wso2.carbon.ndatasource.core.DataSourceRepository will notify the member's in the cluster of the new DataSource. These members will then invalidate the registry cache.
The problem comes is that in the default clustering configuration in Stratos 1.6.0, the Storage Server and the Data Service Server are in different Tribe domains, so messaging using Tribe is not possible between the two types of applications.
How can one get the Data Service Server to update its datasource configuration when datasources are created in the Storage Server?

A: What you've mentioned in your query itself is exactly what's expected from providing the option to create a datasource via WSO2 Storage Server. However, there are certain technical complexities associated with sharing datasources across nodes/clusters of different Carbon products (other than the type of Carbon product in which the datasources are created) and we're currently in the middle of attending to them. Therefore, all considered, a better way to integrate SS with DSS would be, first create your database/database user in WSO2 SS, then create datasources with that information (connection strings, user credentials, etc) in WSO2 DSS and consume them.
Regards,
Prabath
P.S. You can refer http://sparkletechthoughts.blogspot.in/2013/04/relational-storage-solution-using-wso2.html which provides you with a comprehensive guide for creating databases/database users/privilege templates.


text:
Q: Creating truth tables I want to write a module in Mathematica that receives a Boolean function f. The module should write on screen:

*

*Truth table of function f

*Boolean expression which contains only operator NOR

*Minimization in DNF for the function f

This is my try
n = Input["Insert function"]
Module[{t},
  t = n;
  Print[t]]
TableForm[
  BooleanTable[{t}],
  TableHeadings -> {None, {t}}]

Table[BooleanConvert[{t}, fm], {fm, {"NOR"}}]

expr = t

BooleanMinimize[expr = t, "DNF"]

A: First I will define function that produces the output you want given a Boolean function.
boolStuff[f_Function] :=
  (Clear[x, y];
   Column[{
     TableForm[BooleanTable[{x, y, f[x, y]}, {x, y}],
       TableHeadings -> {None, {x, y, f[x, y]}}],
     BooleanConvert[f[x, y], NOR],
     BooleanMinimize[f[x, y]]}])

then
boolStuff[Function[{x, y}, Implies[x, y]]]

gives

You can also enter functions in the more concise pure function from:
boolStuff[#1 && #2 &]

which gives

If you want to enter the function interactively, you can evaluate
boolStuff[Input["Insert function"]]


text:
Q: Identifying the whitespaces string in android I have a series of strings where I have to identify the strings having only white spaces. Following is the regex that I have used, but it is returning only false.
  private fun isOnlySpaces(deviceFriendlyName: String) : Boolean{
        val whiteSpaces = Pattern.compile("/^\\s+\$/")
        return whiteSpaces.matcher(deviceFriendlyName).matches()
    }

Could you please let me know how to identify whitespaces without using isEmpty().

A: There is no need to use regex for this. Use CharSequence.isBlank() method for verifying whitespaces presence.
Note that isBlank() method will return true when the string you are verifying is empty. If such behaviour is not expected you can always write your own extension function that takes string length into consideration:
fun CharSequence.allWhitespace(): Boolean =
    length > 0 && indices.all { this[it].isWhitespace() }

And then use it your code
if (deviceFriendlyName.allWhitespace()) {
  ...
}

A: The regex you used is not correct, it contains this character /, this should be removed, here is the right regex:
private fun isOnlySpaces(deviceFriendlyName: String) : Boolean{
    val whiteSpaces = Pattern.compile("^\\s+$")
    return whiteSpaces.matcher(deviceFriendlyName).matches()
}


text:
Q: PIL Clipboard Image to Base64 string I want to get the image in the clipboard and convert its data into a base64 encoded string so that I can put that into a HTML img tag.
I've tried the following:
from PIL import ImageGrab
from base64 import encodestring
img = ImageGrab.grabclipboard()
imgStr = encodestring(img.fp.read())

Plus some other combinations, all of which give me incorrect representations of the image.
I'm struggling with the docs on this one; does anyone have an idea on how to accomplish this?

A: ImageGrab.grabclipboard() returns an Image object. You need to convert it to a known image format, like jpeg or png, then to encode the resulting string in base64 to be able to
use it within an HTML img tag:
import cStringIO

jpeg_image_buffer = cStringIO.StringIO()
image.save(jpeg_image_buffer, format="JPEG")
imgStr = base64.b64encode(jpeg_image_buffer.getvalue())

(answer has been edited to fix the typo).


text:
Q: Can I use the eigenvectors of a principal component for gene discovery? I am working on a microarray dataset with n samples x m genes, with metadata including a grouping of interest and other summary statistics, e.g. age, bmi. My objective is to find genes that may be related to my grouping of interest (cancer vs. control).
My question is: would it be valid to conduct PCA on the dataset and then correlating/testing each PC with my grouping of interest and other metadata to determine whether any of them are related to a PC?
Then, if I do find a PC that is significantly associated with my grouping, would it be valid to take the eigenvectors (the V matrix in SVD) of that PC sorted from greatest to smallest (absolute values) to determine the genes that may be driving that PC and therefore related to my metadata of interest?


text:
Q: html ws text emails - how to show html version in gmail? I added plain text version to system generated emails, because email without text version is considered as spam. Here is my code:
MailMessage mm = new MailMessage(
new MailAddress(from, msg.FromName), new MailAddress(msg.ToEmail, msg.ToName));
mm.Subject = msg.Subject;
mm.Body = msg.Body;
mm.IsBodyHtml = 1;
mm.Priority = MailPriority.Normal;
ContentType plainContentType = new ContentType("text/plain");
AlternateView plainTextView = AlternateView.CreateAlternateViewFromString(msg.BodyTxt, plainContentType);
mm.AlternateViews.Add(plainTextView);

It works great, but now my problem is that such systems as gmail show back up text version, not main html version!
So far i discovered that email consist from 2 parts:
Content-Type: ***text/plain***; charset=utf-8
Content-Transfer-Encoding: base64

and
Content-Type: text/plain
Content-Transfer-Encoding: base64

First one is larger and it must be the HTML version  (as you see, I set IsBodyHtml to true).
Any ideas?

A: Solution was to put text version to Body, and add text/html version as ALternateView


text:
Q: Move last command in PyCharm interactive shell to script I basically want a workflow that goes like this:
I'm working on a script and run into some issues so I:

*

*Move the script to the interactive console (shift+alt+e on Mac)

*Run a few queries against my variables to figure things out. This step is over when I find a line of code that works.

*Use a keyboard shortcut to add it to the end of the file I have open.

*Repeat as necessary until I feel good about just editing the file directly again.

Options I'm aware of (that I don't care for)

*

*Scroll up, copy, paste.

*Use shortcut to open up history panel.  Select line, copy, close panel, click on script, paste.

I feel it would be a lot smoother for my workflow if I could just hit some key combo and BAM! the last line of code I executed is just put at the bottom of the current file.
Can it be done?  Anyone have some insight?

A: If you've just typed a statement, hit enter, seen that it looks right, and have an empty prompt waiting, you can:

*

*Press the up arrow key to bring back the last statement

*Press Cmd+A to select the whole statement

*Press Cmd+C to copy

If the whole statement fits on a single line, you can skip step 2: in general if nothing is selected then Cmd+C copies the whole line at the cursor.
The prompt >>> or In[x] will not be copied.
You still have to click in the editor to paste, and I don't see a way around that. But at least for the copying you can save on some mouse movement.


text:
Q: Django-rest-frame work get details of oneToOne Filed I am building userprofile functionality,below are the details of  Models, ModelSerializer and ModelViewSet.
When I send GET request to UserProfile, I am getting only fields that are in UserProfile Model.But I also wants to get firstname, lastname, email etc which are exist in User model.
 class UserProfile(models.Model):
    user= models.OneToOneField(User,on_delete=models.CASCADE,related_name='userprofile');
    state= models.CharField(max_length=200)
    city= models.CharField(max_length=200)
    add1= models.CharField(max_length=200)
    add2= models.CharField(max_length=200)
    postalcode= models.IntegerField()
    country= models.CharField(max_length=200)

class UserProfileSerializer(serializers.ModelSerializer):

   class Meta:
      model = UserProfile
      fields = ('state','city','country')

class UserProfileViewSet(viewsets.ModelViewSet):
      queryset = UserProfile.objects.all()
      serializer_class = UserProfileSerializer

     def get_queryset(self):
       if self.action == 'list':
          return self.queryset.filter(user=self.request.user)
       return self.queryset

Please let me know how can I get the details of OneToOneField from userProfile model.

A: Create a user serializer and add it to the user profile serializer and  in the fields.
class UserSerializer(serializers.ModelSerializer):

    class Meta:
      model = User
      fields = '__all__'

class UserProfileSerializer(serializers.ModelSerializer):
    user=UserSerializer(read_only=True)

    class Meta:
      model = UserProfile
      fields = ('state','city','country','user')


text:
Q: How to avoid files selected in JetBrains change list (Git) to also include new changes on the same file? So this is the thing: I'm migrating from VSCode to JetBrains products and I would like to get a behavior similar to VSCode regarding source control.
In VSCode, when you see all your changes to your files and mark them for commit, they are indeed git staged and therefore, new changes to an already marked file (staged) will not be marked by default (those changes are not staged yet).
However, JetBrains "changes lists" concepts does not work that way, as marking a file for commit (checking the checkbox near it) does not stage that file nor does nothing regarding git. It's all handled by the IDE. So if I change a file, checks it in the changes list, and the updates it, new changes are already checked as the whole file was checked before.
I hope I've explained myself correctly.
How can a get a behavior like VSCode regarding source control?

A: You can enable Git staging area Preferences | Version Control | Git.
Check Enable Staging area
But prior to this, please, make sure that Use non-modal commit interface is enabled under Preferences | Version Control | Commit
Otherwise, if you can keep Changelists feature enabled, you may find useful a feature Allow putting changes within one file into different changelists under Preferences | Version Control | Changelists


text:
Q: How to constrain by country using Google Places API textSearch? Currently the Google Places API does not support componentRestrictions, so you are not able to constrain a Places API search to a specific country. This can create all sorts of unexpected behavior, such as searching for "rivervale" being found in the US (River Vale) instead of Singapore (Rivervale) (see Codepen).
My current solution is to rely on region biasing by appending the country to the search string (e.g., "rivervale singapore"). However, this method is also not fool-proof as any location that has the name of the country in its name can also turn up in the results outside of the intended country.
Is there another way to reliably contrain a Places API search to find only locations within a specified country?
UPDATE: I'm aware that you can add componentRestrictions via the Place Autocomplete widget, e.g.:
var autocomplete = new google.maps.places.Autocomplete(input, {
  componentRestrictions: {
    country: 'SG'
  }
}

This does constrain the autocomplete drop-down list to find Rivervale within Singapore, but if the user presses Enter without selecting from the autocomplete list, then the marker for River Vale in the US gets returned instead.


text:
Q: OpenSSL in php and curl not update after upgrading OpenSSL in linux My PHP program worked fine until several days ago. I suddenly got an error "SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure" from using curl in my php program. I searched on the net and found it may be because my openssl is too old (0.9.8e) and not support the TLS.
I tried "yum update openssl" but it doesn't help as the Openssl hasn't been upgraded and is still 0.9.8e. So, I downloaded and installed a newer version (1.0.2j) from the net. And now, it does displays the new version number by the command "openssl version", but it still displays the old version number by phpinfo() and "curl -V". And of course, it still shows the SSL error while running the php program.
I am very new in server setting. How can I update openssl version in php and curl?

A: You have to update php itself, as it comes with ssl compiled in. The libssl on the system is not used by php. It might also be encapsulated in the php-curl package.

A: I finally solve the problem by "downloading and installing" the latest version of OpenSSL, cUrl and PHP, and setting the configure for the new paths of OpenSSL and cUrl for PHP.


text:
Q: Importing node modules once for whole project Scenario
So, I have initialised a Node project with npm. I have setup my package.json accordingly. I am using typescript, so I have also setup tsconfig.json.
I have a few dependencies (npm packages) that I will need to use multiple times in multiple files of my project.
index.ts is the root of my project. I can import these libraries in index.js and other files also.
Problem
Is there any way to include or import these libraries in the project only once so that I can use them in any file of the project without having to import a single thing anywhere.
I tried searching for various ways to do this using -
CommonJS module syntax, NodeJS module syntax, global modules - but none of it can provide me the way I want it.
For Ex -
Most of the answers or solutions I got were like this

*

*Export all the libraries through a single file
import abc from 'abc';
import xyz from 'xyz';

module.exports = {
    abc, xyz
};

*Use these libraries in other files like
import modules from 'src/modules.ts'

var wantSome = modules.abc.getSome();

But, this still has an overhead of importing modules file and accessing it like modules.abc.
Do we have any way to make these imports available globally through out the project.
P.S. - This scenario is somewhat similar to ngModules in Angular 2+, where we can import whatever we want inside ngModules and it is then available to all the components under that module.

A: Doing this is going to cause you all sorts of problems in the long run.

*

*you'll end up with one monolithic file containing all your exports, which will become onerous to maintain

*if you decide to modularise your code, it will be more difficult since you won't explicitly know which modules a file uses

*if you were able to include to the point where you simply use the modules with no reference, code clarity will suffer

*name clashes might occur

The best I believe you'll get in node is to declare all the includes in a single module, and then destructure within your own file.
import abc from 'abc';
import xyz from 'xyz';

module.exports = {
    abc, xyz
};

Then
import modules from 'src/modules.ts'
{ abc: { getSome } } = modules

But I strongly suggest using the standard patterns for importing. It will make your code much cleaner and easier to maintain

A:

N/B - Thats a bad way to design your app.

In node, you can set global variables via the "global" or "GLOBAL" object:
You could import all your dependencies in your app entry file, and store them in a Global variable
index.js
import abc from 'abc';
import xyz from 'xyz';

global.abc = abc
global.xyz = xyz

someotherfile.js
//access abc import
global.abc

A: Export all the libraries through a single file
import abc from 'abc';
import xyz from 'xyz';

module.exports = {
    abc, xyz
};

Use these libraries in other files like
import {abc, xyz} from 'src/modules.ts'

var wantSome = abc.getSome();


text:
Q: ES cluster node without load balancer I have a 3 ES nodes cluster. all of them are data and master nodes. In my api (JAVA) i am using transport communication. I am using xxx.yy.zz.aaa  IP address to access/query the ES index. But i just wanted to know, If that xxx.yy.zz.aaa machine is down then i have to reconfigure the API to point to any one of the machine available in cluster. But is there a way to

*

*how to utomatically detect the node failure and point query to other node ?

*How to avoid this single point of failure.

A: You should add all 3 IP addresses to your client, so it will connect to other node in case of one node failure. Your connector might look like this:
Settings.Builder settings =  Settings.settingsBuilder();
        settings.put("cluster.name", "elasticsearchcluster");
         List<String> hosts = new LinkedList<String>();
         ArrayList<ElasticSearchHost> esHosts = elasticSearchConfig.esHostsConfig.esHosts;
         for (ElasticSearchHost host : esHosts) {
            hosts.add(host.host + ":" + host.port);
         }
        settings.put("discovery.zen.ping.multicast.enabled", "false");
        settings.put("discovery.zen.ping.unicast.hosts", StringUtils.join(hosts, ","));
        //settings.put("discovery.zen.ping.unicast.hosts","xxx.yy.zz.aaa:9300, xxx.yy.zz.bbb:9300, xxx.yy.zz.ccc:9300");
        client =   TransportClient.builder().settings(settings).build();
        for (ElasticSearchHost host : esHosts) {
            ((TransportClient) client).addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress(host.host, host.port)));

        }
        ClusterHealthResponse clusterHealth = client.admin().cluster().health(clusterHealthRequest().waitForGreenStatus()).actionGet();


text:
Q: JS/jQuery - Массив из Dom-элементов Есть такой код в HTML:

Как сделать из этих изображений массив на JS/JQ?

A: *

*JavaScript

var container = document.getElementById("slider");
console.log(Array.from(container.children));

*jQuery

console.log($("#slider").children().toArray())

A: var imgArray = [];

$.each($('div#slider img'), function (index, element){
 imgArray.push($(element).attr('src'));
});

console.log(imgArray);


text:
Q: Solvable Schrödinger operator I am currently looking for an example of a 1-dimensional Schrödinger Operator $-\frac{d^2}{dx^2} + V(x)$ with the following properties:
1) V(x) must be integrable
2) $-\frac{d^2}{dx^2} +V(x)$ must have some negative eigenvalues
3) The operator should be solvable, i.e. the (negative) eigenvalues should be exactly (i.e. analytically) known.
I want to test a numerical method for the computation of eigenvalues of such operators, but unfortunately I am lacking a solvable example for these tests (and searching for one didn't get me anywhere). I would appreciate any help.


text:
Q: How to read messages on iphone with xamarin? How to read messages on iphone with xamarin?
If not permission access. can I jailbreak iphone to read message ?
Please,give me a solution
Thanks u

A: You can't.  Apple doesn't expose any public API that allows you to access a users messages.


text:
Q: Why does my async task handler for a sqlite database trigger postExecute immediately I have an async class that opens up an sqlite database and if is the first time running the database will be populated with data that takes about 10 seconds to complete. Even though there is still working being done in the background the async task finishes immediately. I think it has something to do with the sqlite's oncreate method possibly doing another async task or something
class BuildDatabase extends AsyncTask<Void, Void, Void> {

    ProgressDialog loading;

    @Override
    protected void onPreExecute() {
        loading = ProgressDialog.show(ctx, "Please wait...", "Building database, this may take a few seconds", true);
    }

    @Override
    protected Void doInBackground(Void... params) {
        // open up the database, if its the first time running the data will
        // be populated
        db = new SQLiteWrapper(ctx); //takes 1-10 seconds
        return null;

    }

    @Override
    protected void onPostExecute(Void result) {
        Log.d(TAG,"post execute");
        loading.dismiss();
    }
}

The sqlite helper class main methods look like this
public class SQLiteWrapper extends SQLiteOpenHelper {
public SQLiteWrapper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    ctx = context;

}

@SuppressWarnings("deprecation")
@Override
public void onCreate(SQLiteDatabase database) {
    database.execSQL(DATABASE_CREATE);

    // populate our database with data from the zones file
    try {
        database.setLockingEnabled(false);
        buildDatabase(database);
    }
    finally {
        database.setLockingEnabled(true);
    }

}
}

If you are familiar with this class onCreate is only called and the database doesn't exist.
If I manually call onCreate() within the database constructor the progress dialog will show.
thoughts?

A: onCreate will only be called if you actually open the database (and it doesn't yet exist).
Add this.getWritebleDatabase() to the SQLiteWrapper constructor, like so:
public SQLiteWrapper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    ctx = context;
    this.getWritableDatabase();
}


text:
Q: Multiply in bash script according to mathrules So I have an exercise in which I need to calculate a certain string.
For example the string "|| x ||| + ||". The vertical lines represent a 1. So the solution to this string needs to be 8. So I made this script:
#!/bin/bash
result=$(echo $1 | tr -d ' ' | sed 's/|/1+/g' | sed 's/++/+/g' | sed 's/+x/x/g' | sed 's/ sed 's/x/*/g' | sed 's/+$//' | sed 's/$/\n/' | bc)

But when I executed this script on the string example, the solution I got was 6.
Then I figured out it's because the script executes this: 1+1*1+1+1+1+1. So I need a way to make parenthesis between (1+1)*(1+1+1)+(1+1) but I can't figure it out.
Can anybody help me?
Thanks in advance!

A: If you want to stick to sed then the best is to put in the parens before doing the rest:
result=$(echo $1 | tr -d ' ' | sed -e 's/\(|*\)/(\1)/g' -e 's/|/1+/g' -e 's/+)/)/g' -e 's/x/*/g' | bc)

A: This seems to work quite well:
{
echo "|x|+|"
echo "| x | + |"
echo "|| x ||| + ||"
echo "||x ||| +||"
echo "((|||x|||||-||||||)+|)/||"
echo "(((|||x|||||-||||||)+|)/||)^|||||"
} |
sed -e 's/||*/&)/g' \
    -e 's/|\(|*\)/(1\1/g' \
    -e 's/|/+1/g' \
    -e 's/x/*/g' |
tee converted.log |
bc

Sample output:
$ bash calc.sh
2
2
8
8
5
3125
$

Contents of converted.log:
(1)*(1)+(1)
(1) * (1) + (1)
(1+1) * (1+1+1) + (1+1)
(1+1)* (1+1+1) +(1+1)
(((1+1+1)*(1+1+1+1+1)-(1+1+1+1+1+1))+(1))/(1+1)
((((1+1+1)*(1+1+1+1+1)-(1+1+1+1+1+1))+(1))/(1+1))^(1+1+1+1+1)

The sed script replaces each sequence of one or more pipe symbols with the same sequence and a close parenthesis; then it replaces the pipe at the start of a sequence of pipe symbols with (1; then it replaces each remaining pipe with +1; and finally it replaces the x's with *'s.  It only requires that the pipes are consecutive with no spaces between them.  Even that constraint can be removed by simply deleting all the spaces before doing the rest of the work.

A: Here's one that works on your sample data:
echo "|| x ||| + ||" | tr -d ' ' | \
awk -F "+" '{out="("$1; for(i=2;i<=NF;i++){out=out")+("$i}; print out")"}' | \
awk -F "x" '{out="("$1; for(i=2;i<=NF;i++){out=out")*("$i}; print out")"}'| \
sed 's/|/1+/g' | \
sed 's/+)/)/g' | \
bc

I used awk to separate things and wrap them in parens; usually it uses a space as a separator, but I overrode it the -F flag.

A: You don't need parentheses if you translate the | groups into decimal numbers first - then the arithmetic operator precedence will work as usual:
# Assign string to $1
set -- '|| x ||| + ||'

result=$(echo "$1" |
  awk '{
        for(i=1; i<=NF; ++i) {
          if ($i ~ /^\|+$/) { $i = length($i) }
          else if ($i == "x") { $i = "*" }
        }
        print
      }' | bc)

*

*Only a single (awk) command is needed for the transformation: it translates the input into 2 * 3 + 2, which bc then evaluates as desired (contrast this with the OP's solution attempt and miken32's solution, which use 6 and 5 intermediate commands, respectively).

*

*for(i=1; i<=NF; ++i) loops over all whitespace-separated fields in the input line.

*if ($i ~ /^\|+$/) { $i = length($i) } replaces each run of | chars. with its length, effectively replacing it with the number it represents.

*else if ($i == "x") { $i = "*" } replaces x with *, because bc expects * as the multiplication symbol.

*by assigning to the input fields ($i), the input line is rebuilt with the new values, and print simply prints the resulting line.

A: EDITED to follow the suggestion in the comment (by mklement0).
Here is how I would do it:
#!/bin/bash

read -ra flds <<< '|| x ||| + ||'

# for each substring in string
for c in "${flds[@]}"
    do
        # compute string length
        len=${#c}
        # if the first char in c is a | then the corresponding length is the number, append it to a string
        if [[ "${c:0:1}" == "|" ]]; then str=$str"$len"
        # check for + and * and append them to the string
        elif [ "${c:0:1}" == "+" ]; then str=$str"+"
        elif [ "${c:0:1}" == "x" ]; then str=$str"*"
        fi
    done
#evaluate the string via bc
echo "$str"|bc


text:
Q: DotNet Core Console Application: AutoMapper Hello I am using AutoMapper in DotNet Core Console Application
StartUp file:
public class StartUp
{
    public  void ConfigureServices(IServiceCollection services) {
    services.AddAutoMapper();
}
}

Mapping File:
public class MappingProfile: Profile {
    public MappingProfile() {
         CreateMap < Employee, EmployeeModel > ().ForMember(dest => dest.Address, opts => opts.MapFrom(src => new Address {
            City = src.City, State = src.State   }));
    }
}

UnitTest Class:
 public class UnitTest1
    {
         private readonly IMapper _mapper;
        public UnitTest1(IMapper mapper)
        {
             _mapper = mapper;
        }

        [Fact]
        public void Test1()
        {

            Employee  emp = new Employee ();
            emp.Id=1;
            emp.Name="Test";
           var empmodel = _mapper.Map < Employee, EmployeeModel > (emp);
           Assert.Equal(empmodel.Name,"Test");
            Assert.Equal(empmodel.Id,1);

        }
    }

Reference Link: https://www.c-sharpcorner.com/article/how-to-implement-automapper-in-asp-net-core-mvc-application/
I am Getting below error on running test file:
Error Message:

The following constructor parameters did not have matching fixture
  data: IMapper mapper

Thank you

A: It's not quite clear to me exactly what you are trying to do, but if you use the automapper in a test project, then it might be useful:
[Fact]
    public void Test1()
    {

        var employee = new Employee
        {
            AddressEmployee = new Address
            {
                City = "SomeCity"
            }
        };

        //initialize automapper and register mapping profile
        var mockMapper = new MapperConfiguration(cfg => cfg.AddProfile(new EmployeeProfile()));

        //create new mapper
        var mapper = mockMapper.CreateMapper();

        //map
        var employeeModel = mapper.Map<EmployeeModel>(employee);

        // do assert or another stuff
    }

By the way, if the names of the fields in the classes are the same, you do not need to specify from where and to what map. It is enough to specify the classes.
CreateMap<Employee, EmployeeModel>();

A: Because your unit tests are not starting up the same as you normally would, your dependency injection is not set up or being used. So when your unit tests run you get a null reference exception because no-one is passing in Imapper.
If you want to use a constructor I'm your unit tests you will want to do
public test() {
    _mapper = new Mapping profile();
}

Then you would have an instance of the object you're trying to test. In unit tests I try to avoid calling the abstraction of the class I'm trying to test because I'm testing the actual workings of that class behind the interface


text:
Q: Not only DID he exceed/he EXCEEDED, but he HAD also drank alcohol. (Past tense) How come sentence1 is more correct than sentence2, in terms of BETTER FIT with its relative clause?

*

*Not only DID he exceed the speed limit, but he HAD also drank alcohol. (From a website)

Vs.

*Not only he EXCEEDED the speed limit, but he HAD also drank alcohol. (My construction)

Both introductory clause (sentence 1 & 2) are in the past, aren't they? BUT, how come, if I were to construct a sentence, the sentence#2 would be incorrect?

Source: Grammaring: Test your grammar #47
(scroll to reach #47)

A: Neither sentence is grammatical—or at least stylistically acceptable based on parallelism.
They can be made grammatical if you rephrase them:

Not only did he exceed the speed limit, but he [] also drank alcohol.
  He not only exceeded the speed limit, but he [] also drank alcohol.

If you want to keep had you will need to make some different changes:

Not only had he exceeded the speed limit, but he had also drunk / had also been drinking alcohol.
  He had not only exceeded the speed limit, but he had also drunk alcohol.

After addressing the construction of the sentences, there is really no essential difference between them in terms of meaning. (And after addressing the issue with parallelism, the second sentence is not incorrect.)
However, the first version in the question can be interpreted as having a sense of something habitual rather than referring to a one-time event.


text:
Q: Writing Correct Xpath In Selenium Python Here is the link of what I am trying to work on:
https://www.supremenewyork.com/shop/all/jackets
For example I want to find and click on the Wool Suit Black Pinstripe:
driver.find_element_by_xpath('//*[contains(text(),"Wool Suit Black Pinstripe")]').click()

This is what I've used, but selenium keeps throwing an exception. Could anyone point me in the right direction as to why this is?

A: You should try to change this to
driver.find_element_by_xpath("//*[text()[contains(.,'Black Pinstripe')]]").click()

Edit.: I've just realized that the text you send as example ("Wool Suit Black Pinstripe") is not all inside the same web element on the website
When you inspect the page, you can find out that "Wool Suit" is inside an div and "Black Pinstripe" is inside another div. This may be tricky but some websites just work this way.
Nevertheless, I've updated my answer to use only "Black Pinstripe" text, this way it will recognize the WebElement and click where you want.
If it still doesn't work you can also try link text methods.
driver.find_element_by_link_text("Black Pinstripe")

and
driver.find_element_by_partial_link_text("Black Pinstripe")


text:
Q: cellForRowAtIndexPath doesn't trigger Can't understand why cellForRowAtIndexPath is never called, even though numberOfRowsInSection is called
I call this ViewController with
ServerDataController *dataController = [[ServerDataController alloc] initWithNibName:@"ServerDataController" bundle:nil];
[self presentModalViewController:dataController animated:YES];
here is my code:
Header file:
#import <UIKit/UIKit.h>

@interface ServerDataController : UIViewController <NSXMLParserDelegate, NSURLConnectionDelegate, UITableViewDataSource>
{
...
    NSMutableArray *items;
    UITableView *docsTableView;

}
@property (retain, nonatomic) IBOutlet UITableView *docsTableView;

@property (nonatomic, readonly) NSMutableArray *items;

@end

Implementation file:
#import "ServerDataController.h"

@implementation ServerDataController
@synthesize docsTableView;
@synthesize items;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (id)init
{
    self = [super init];

    if (self)
    {

    }

    return self;
}

- (void)dealloc {

    [items release];
    [docsTableView release];
    [super dealloc];
}

- (void)viewDidAppear:(BOOL)animated
{
    [self fetchEntries];
    animated = YES;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    if (self) {
        items = [[NSMutableArray alloc] init];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[self items] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    NSString *cellTitle = [[[[items objectAtIndex:indexPath.row] docUrl] lastPathComponent] stringByDeletingPathExtension];

    cell.textLabel.text = cellTitle;
    return cell;
}

Any suggestions?

A: I don't see where you add items to your array, only an init in your viewDidLoad, I think it is empty, so that is why the function is never called. There simply aren't any items to be displayed.


text:
Q: When to index a Core Data attribute? In which cases should I index a Core Data attribute?

*

*When I'm sorting by it?
fetchRequest.sortDescriptors =
[NSArray arrayWithObject:[NSSortDescriptor
                          sortDescriptorWithKey:@"name" ascending:YES
                          selector:@selector(localizedStandardCompare:)]];

*When I'm filtering by it?
fetchRequest.predicate = [NSPredicate predicateWithFormat:
                          @"name BEGINSWITH[cd] %@", searchString];

*Any other cases?

A: I think, you can do it in both cases, presuming that you will work a lot with that attribute and it is itself big and will cost a lot to make a fetch without indexed column.


text:
Q: (index out of bounds) I wrote a hangman game program with java I am sure that there are many other problems with my program but I am currently stuck on this issue and focusing on solving this first.
My aim is to loop the game according to the number of inputted words while changing the game number.
My problem is that the "display banner" part kept looping until it is met with an error of "out of boundary".It displayed following when I inputted "java Hangman 123 test":
========
Game: 1
========
Game: 2
========
Game: 3
========
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at Hangman.main(Hangman.java:121)

Here is my program:
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.Scanner;

public class Hangman {

    //validation of raw questions
    public static boolean isValidQuestion(String rawQuestion){
        rawQuestion = rawQuestion.toUpperCase();
        boolean vQuestion = true;
        for(int i=0; i<rawQuestion.length(); i++){
            char c = rawQuestion.charAt(i);

            if(!(c>='A' && c<='Z'))
            vQuestion = false;
        }
        return vQuestion;
    }

    //show invalid tries
    public static String formatCharArray(char[] ca){
        String output = "";
        for(int i=0; i<ca.length; i++){
            output += ca[i] + " ";
        }
        return output;
    }

    public static void main(String args[]){

        if(args.length==0){
            System.out.println("Usage: java Hangman word_to_guess [more_word_to_quess]...");
            return;
        }

        List<String> validQuestions = new ArrayList<>();
        for (int i = 0; i < args.length; i++){
            String rawQuestion = args[i];
            boolean b = isValidQuestion(rawQuestion);
            if (b){
                validQuestions.add(rawQuestion);
            }else{
                System.out.println("Error: " + rawQuestion + ", input must be a word consist of a-z or A-Z");
            }
        }

        // store valid questions into an array
        String questions[] = validQuestions.toArray(new String[validQuestions.size()]);

        // shuffle the questions
        for(int i=0; i<7; i++){
            int x = (int)(Math.random()*validQuestions.size());
            int y = (int)(Math.random()*validQuestions.size());
            String temp = questions[x];
            questions[x] = questions[y];
            questions[y] = temp;
        }

        // game

        // initiallize
        int noInvalidTry = 0;
        int count = 0;
        char[] invalidTries = new char[6];
        int j = 0;
        char[] userGuess = new char[questions[j].length() ];
        boolean isCorrect = false;

        for(int i=0; i<invalidTries.length; i++){
            invalidTries[i] = '_';
        }

        for(int k=0; k<userGuess.length; k++){
            userGuess[k] = '_';
        }

This is the part where I messed up.
        // display banner

        while( j<= args.length){
            System.out.println( "========" );
            System.out.println( "Game: " + ++j );
            System.out.println("========");

        }

above
        // game loop

        while( noInvalidTry<6 && count<questions[j].length() ){
            Scanner sc= new Scanner(System.in);

            System.out.print("Please input your guess: ");
            String s = sc.nextLine().trim();

            // check input length
            while(s.length()==1 && isValidQuestion(s)){

                //start guess
                char inputChar = s.charAt(0);
                inputChar = Character.toUpperCase(inputChar);

                boolean c = false;
                for(int i=0; i<questions[j].length(); i++){
                    if((s.equals(questions[j].charAt(i))) && (userGuess[i] == '_')){
                        //update userGuess
                        userGuess[i] = questions[j].charAt(i);
                        c = true;
                        count++;
                        System.out.println( "Good try!" );
                        // show status
                        System.out.printf("No of Invalid try: %d/6\t\tInvalid tries: ",noInvalidTry);
                        System.out.println( formatCharArray(invalidTries) );

                    }
                }
                if(!c){
                    noInvalidTry++;
                    System.out.println( "Oops..." );
                    // show status
                    System.out.printf("No of Invalid try: %d/6\t\tInvalid tries: ",noInvalidTry);
                    System.out.println( formatCharArray(invalidTries) );
                }
            }
        }
        if( noInvalidTry==6 && count<questions[j].length()){
            System.out.println("Game over, the answer is " + questions[j] );
            j=j++;
        }
        if( noInvalidTry<6 && count==questions[j].length()){
            System.out.println("Congratulation!");
            j=j++;
        }
        //final status
        if(j==args.length){
            double temp = 0;
            double score = 0;
            double total = args.length;
            System.out.println("-------------------------------------------------------------------------------------------------------------------");
            System.out.println("Summary");
            System.out.println("-------------------------------------------------------------------------------------------------------------------");
            while(j<=args.length && isCorrect ){
                System.out.println(++j + ". " + questions[j] + "\t" + "Correct" + "\t" + count + "/" + questions[j].length() + " Correct guesses" + "\t" + noInvalidTry + "/" + questions[j].length() + " Incorrect guesses" );
                temp++;
            }
            while(j<=args.length && !isCorrect) {
                System.out.println(++j + ". " + questions[j] + "\t" + "Incorrect" + "\t" + count + "/" + questions[j].length() + " Correct guesses" + "\t" + noInvalidTry + "/" + questions[j].length() + " Incorrect guesses" );
            }
            score = temp/total;
            System.out.println("Final result: " + score + " / 100 marks");
            System.out.println("-------------------------------------------------------------------------------------------------------------------");
        }

    }
}

A:     if(j==args.length){

        // ...

        while(j<=args.length && isCorrect ){
            System.out.println(++j + "" + questions[j] + "\t" + "Correct" + "\t" + count + "/" + questions[j].length() + " Correct guesses" + "\t" + noInvalidTry + "/" + questions[j].length() + " Incorrect guesses" );
            temp++;
        }
        while(j<=args.length && !isCorrect) {
            System.out.println(++j + ". " + questions[j] + "\t" + "Incorrect" + "\t" + count + "/" + questions[j].length() + " Correct guesses" + "\t" + noInvalidTry + "/" + questions[j].length() + " Incorrect guesses" );
        }

if j is the array length, then questions[j] will raise an error (the last element is length-1).
But, even worse, you are still increasing j even more (the 2 j++ statements) !
They are also many other j++ in your while loop.

As a good practice to help you handle arrays : when you do some iteration on a value that is an index :

*

*prefer for loops

*loop for the correct values of your parameter (between 0 and length-1)

*do not increase the array randomly, you should be sure that your array index (j) is increased once and only once for each iteration. To help you doing that, you should have only one line stating j++ or ++j in your loop, not some j++ at different places nested in some if blocks.

*(that's why using a for loop is recommended : there is some place to do the j++, and you should not do it elsewhere without a very good reason.

Also, as stated in comments, you should learn to analyze your error (What is a stack trace, and how can I use it to debug my application errors?), and use debugging tools and go  through your program step by step and see what you are doing with all your variables.


text:
Q: How to run two instances of the same app for two Kinects? I want to ask is there any way to check whether a Kinect is being used at the moment (sensor.start) so that we can use another Kinect for another application or in the same application? I tried using Kinect.IsRunning but it's not working.
Here is the case: I have an application that runs on one Kinect, but I want to run this application two times. I have two Kinects connected to my PC. The problem is whenever I ran the second application, it will detect the same Kinect to be used causing the second application to crash. I want this application can know if the first Kinect sensor already start, it will go for the next one. I have read this article but it doesn't help me to solve this problem.
http://social.msdn.microsoft.com/Forums/en-US/e8e96d97-ec02-430e-b80c-a40ae6b92604/running-two-instances-of-the-same-app-for-two-kinects?forum=kinectsdknuiapi
So far I hard-coded the Kinect ID into my application, but that means I need to have two applications which is not efficient. If I need to change the Kinect I need to change the ID again inside the codes. Anyone can help me. please? I thought it should be not difficult, but I still haven't found any function to do that. I'm writing my codes in VB.Net

A: I would do something like this:
For Each _sensor As KinectSensor In KinectSensor.KinectSensors
    sensor = _sensor

    ...//setup event handlers and such

    Try
        sensor.Start() //If it gets past this, then we can exit as it has
                       // successfully started a kinect
        Exit For

    Catch ex As ApplicationException
        MsgBox("That Kinect is being used in another application, moving to the next")
    Catch ex2 As IOException
        MsgBox("Error")
    End Try
Next

This will search all the kinects, try to start them, and if an ApplicationException is thrown, then it moves onto the next kinect.


text:
Q: Determine start and end of street, based on (latitude, longitude) points Let's assume I have many (latitude, longitude) points, and all of them are on one street. However, I have no information about house numbers.
Is there any way to deduce which two points correspond to the "first" and "last" point of this street respectively? Keep in mind that a street could be straight, curved, or almost any shape really.
What I want to do is find a way to split a street into 30-meter segments. If I'm not mistaken, there's no way to sort/rank the (latitude, longitude) points, even in the context of one street.
Just one thing: I have too many points to use the Google Maps API (many streets); instead, I'm using a local installation of Nominatim (OpenStreetMap). Please either suggest something that can be done with Nominatim or a general algorithm.


text:
Q: how to add text to jfree polar plot? Starting from the java code below , is there a way to add text on jfree plot ?
The aim is to obtain a plot like posted with "aa" "bb "cc" .
"filling text ................."
Thank you
tinitus
package jfreechart;

import javax.swing.JFrame;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

public class JFreeChartPolarChartExample2 extends JFrame {

   private static final long serialVersionUID = 1L;
   public JFreeChartPolarChartExample2(String applicationTitle) {
       super(applicationTitle);

       XYSeriesCollection  dataSet1 = new XYSeriesCollection();
       JFreeChart jfreeChart = ChartFactory.createPolarChart(null, dataSet1, true, true, false);

       final XYSeries series = new XYSeries(" serie1");
           series.add(10, 0.90);
           series.add(100, 0.10);
           series.add(195, 0.50);
           series.add(295, 0.50);
           dataSet1.addSeries(series);

       PolarPlot polarPlot = (PolarPlot) jfreeChart.getPlot();

       ChartPanel chartPanel = new ChartPanel(jfreeChart);
       chartPanel.setPreferredSize(new java.awt.Dimension(500, 500));
       setContentPane(chartPanel);

   }

   public static void main(String[] args) {
       JFreeChartPolarChartExample2 chart = new JFreeChartPolarChartExample2(null);
       chart.pack();
       chart.setVisible(true);
   }
}


text:
Q: How to get substring from string without split? String str = "internet address : http://test.com Click this!";

I want to get "http://test.com", so I wrote like this.
String[] split = str.split(" ");
for ( int i = 0 ; i < split.length ; i++ ) {
    if ( split[i].contains("http://") ) {
        return split[i];
    }
}

but I think this is ineffective. how to get that more easily?

A: Assuming you always have the same format (some text : URL more text) this can work:
public static void main(String[] args) throws IOException {
    String str = "internet address : http://test.com Click this!";
    String first = str.substring(str.indexOf("http://"));
    String second = first.substring(0, first.indexOf(" "));
    System.out.println(second);
}

But better is regex as suggested in different answer

A: Usually, this is either done with a regular expression or with indexOf and substring.
With a regular expression, this can be done like that:
    // This is using a VERY simplified regular expression
    String str = "internet address : http://test.com Click this!";
    Pattern pattern = Pattern.compile("[http:|https:]+\\/\\/[\\w.]*");
    Matcher matcher = pattern.matcher(str);
    if (matcher.find()) {
        System.out.println(matcher.group(0));
    }

You can read here why it's simplified: https://mathiasbynens.be/demo/url-regex - tl;dr: the problem with URLs is they can have so many different patterns which are valid.
With split, there would be a way utilizing the URL class of Java:
   String[] split = str.split(" ");

    for (String value : split) {
        try {
            URL uri = new URL(value);
            System.out.println(value);
        } catch (MalformedURLException e) {
            // no valid url
        }
    }

You can check their validation in the OpenJDK source here.

A: My try with regex
String regex = "http?:\\/\\/(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%_\\+.~#?&//=]*)";
String str = "internet address : http://test.com Click this!";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
    System.out.println(matcher.group(0));
}

result:
http://test.com

source: here

A: Find the http:// in the string, then look forwards and backwards for the space:
int pos = str.indexOf("http://");
if (pos >= 0) {
  // Look backwards for space.
  int start = Math.max(0, str.lastIndexOf(' ', pos));

  // Look forwards for space.
  int end = str.indexOf(' ', pos + "http://".length());
  if (end < 0) end = str.length();

  return str.substring(start, end);
}

A: It is not clear if the structure of the input string is constant, however, I would do something like this:
    String str = "internet address : http://test.com Click this!";
    // get the index of the first letter of an url
    int urlStart = str.indexOf("http://");
    System.out.println(urlStart);
    // get the first space after the url
    int urlEnd = str.substring(urlStart).indexOf(" ");
    System.out.println(urlEnd);
    // get the substring of the url
    String urlString = str.substring(urlStart, urlStart + urlEnd);
    System.out.println(urlString);

A: I just made a quick solution for the same. It should work for you perfectly.
package Main.Kunal;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class URLOutOfString {

    public static void main(String[] args) {
        String str = "internet address : http://test.com Click this!, internet address : http://tes1t.com Click this!";
        List<String> result= new ArrayList<>();
        int counter = 0;
        final Pattern urlPattern = Pattern.compile(
                "(?:^|[\\W])((ht|f)tp(s?):\\/\\/|www\\.)"
                        + "(([\\w\\-]+\\.){1,}?([\\w\\-.~]+\\/?)*"
                        + "[\\p{Alnum}.,%_=?&#\\-+()\\[\\]\\*$~@!:/{};']*)",
                Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);

        Matcher matcher = urlPattern.matcher(str);

        while (matcher.find()) {
            result.add(str.substring(matcher.start(1), matcher.end()));
            counter++;
        }

        System.out.println(result);

    }

}

This will find all URLs in your string and add it to arraylist. You can use it as per your business need.

A: You could use regex for it
String str = "internet address : http://test.com Click this!";
Pattern pattern = Pattern.compile("((http|https)\\S*)");
Matcher matcher = pattern.matcher(str);
if (matcher.find())
{
    System.out.println(matcher.group(1));
}


text:
Q: How to run an SQL script against a MDF file? I've created a database model with model-first method using Entity Framework 4.0. I then created an sql script using the Generate Database from Model... I've also created an SQL Server Database file in my App_Data folder. How do I now run the SQL file against this MDF file?
I'm using Visual Studio 2010.

A: I ran into this same problem and here is what worked for me.
When I selected "Generate Database from Model..." I created a new MDF file.  This process worked fine and Visual Studio generated the needed SQL Script. However, I did not know how to connect to the same MDF file to run the script.
It turned out to be quite easy.

*

*Right-click on the script and choose Connection > Connect

*The server name and authentication should already be set for the local SQLEXPRESS instance.

*Click the Options button

*Click the Additional Connection Parameters tab

*Paste in the the path to your database file using the following as a guide:
AttachDBFilename=C:\Path\To\Database\LocalData.mdf;database=LocalData;

*Click the Connect button
If you still have trouble connecting it may be because there is already an open connection.  Check Server Explorer and if connection is open, Right-click and choose Close Connection.
This process will also create a persistent connection as long as the SQL Script remains connected.  You will want to close the script or choose Right-click > Connection > Disconnect.
More information can be found at this question:
EF4 Generate Database

A: I found a solution, but it's a bit hacky.
I have SQL Server Express (2008 R2). So when generating the database from the model I connect to it and let it build a database there. Then I go to C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA. The 10_50 part is because of the version and can be different for you. So in this folder there's a .mdf file named just like the database - .mdf. There's also a _log.ldf file. I copied these to into the App_Data folder of my project.
This works but is very time consuming to generate a new .mdf database for every change in the model. So I do this just before shipping.
If you find a better answer please do share.

A: I encountered the same problem, Model First approach in mvc4 using EF5. What I did was create project, add a new model, add entities and associations on the edmx diagram. Right click on diagram and select 'Generate database from model'. This generates the sql file.
Now add a mdf file, say, Database1.mdf (Add > New item > Data > SQL Server Database) in the App_Data folder in solution explorer.
Right click > Open on this mdf file. Now in properties pane you have the connection string. Just copy that as it is.
Revert back to your generated SQL script, right click > Exeecute. A pop-up asks for connection parameters. Make sure you have correct value in Server name (use your PC name, or 127.0.0.1).
Now in options, Click the Additional Connection Parameters tab and paste the connection string copied from properties of mdf file.
This worked perfectly from me and is quite logical. There is no need to directly play around with the SQL Server installation directory.

A: Great Answers above but I had to do a few more steps in VS2013 but I did resolve with the help here as follows.

*

*I created a ADO.NET Model from existing .mdf

*Right Clicked -> Generate Database from model

*Right click the .mdf in Solution Explorer and Open

*In the properties pane copy Connection String to clipboard

*In the SQLQuery window created by ADO Model click change connection

*In the new Connect to Server window -> Additional Connection Parameters -> paste connection string from clipboard

*In Server Explorer right click the Database -> New Query

*Copy and Paste the Query from ADO Generated script to new Query Window

*Change USE [yourdatabase.mdf] to USE [longPath] where longPath is the very long path listed in the drop down at top. The easiest way is to start typing and CTRL-SPACE it.

*Run the Query

*Save the longPath because you can just paste it into the USE[] on any new Query generated by ADO.

I hope this helps someone - Happy Coding!


text:
Q: Keith Wood's jQuery SVG plugin does not display Y axis properly I set my Y axis max as 1, min as 0 and tick as 0.1. The graph displays as 0, 0.1, 0.2, 0.30000000000004, 0.4 etc. What I mean here is that it does not display 0.3 properly and also some other values in a the similar style. But once I set the tick to more than 0.2, it will display everything properly. So anyone else have experienced the same problem or just myself doing something wrong?
Thanks.

A: I actually figured it out myself.
In the jquery.svggraph.js file which comes with the plugin, line 493, it adds the tick value to the previous value, so in my case the previous value was 0.2 when it adds 0.1 to it, the result becomes 0.3000000004. I don't know why it does that, maybe it stores the value as float number. What I did to solve this is to add major = Math.round( major * 100 ) / 100 under line 498. Hope this might help someone else who had same problem as I did.


text:
Q: JavaScript - Assigning Array Index to Return Value not working I am trying to assign a return value to an element in an array, and for some reason it is overwriting both elements in the array to the same value instead of just the second element.
The datepicker I'm using for this can be found here, for reference.
http://www.eyecon.ro/datepicker/
function AddDays(date, days)
{
  var newDate = new Date(date.setTime( date.getTime() + days * 86400000 ));
  return newDate;
}

$('#nights').on('change', function(){
  var $dp = $('#date');
  var t = $dp.DatePickerGetDate();
  console.log(t);  // Output 1
  t[1] = AddDays(t[0], $(this).val());
  console.log(t); // Output 2
});

Output 1 : [Mon Jan 02 2017 00:00:00 GMT-0600 (Central Standard Time), Sun Jan 08 2017 23:59:59 GMT-0600 (Central Standard Time)]
Output 2 : [Mon Jan 09 2017 00:00:00 GMT-0600 (Central Standard Time), Mon Jan 09 2017 00:00:00 GMT-0600 (Central Standard Time)]
As you can see, when I try to assign the second element t[1] to equal the return of AddDays(t[0], $(this).val()) both dates get set the same exact date. However, the second element is supposed to be equal to the first element plus the number of days specified.
I also verified that the element $(this).val() is not zero.  In my case that is in fact returning 7 when I run console.log($(this).val()); right before the assignment of t[1].
What am I doing wrong here?

A: Your function modifies the date that is passed in when you call setTime. You can remove the call to setTime to solve your problem.
function addDays(date, days) {
  return new Date(date.getTime() + (days * 86400000));
}

Or make a brand new date object and call setDate or setTime on the copy.
function addDays(date, days) {
  var result = new Date(date);
  result.setDate(result.getDate() + days);
  return result;
}


text:
Q: Not detecting invisible item values if it is in horizontalrecyclerview i have my scrollview items horizontally from sunday to saturday with checkboxes, in mobile view it is showing sunday to saturday if i scroll,if not scroll it shows sunday to wednesday,
coming to point when i update my subscription it takes values from sunday to wednesay,remaining values not coming they coming as null what should i do?
here is my adapterclass code:
public class SubscriptionRecyclerViewAdapter extends RecyclerView.Adapter<SubscriptionRecyclerViewAdapter.MyViewHolder> {

private List<DaysOfDelivery> daysOfDeliveryList;
 public static String[] daylist;

public class MyViewHolder extends RecyclerView.ViewHolder {
    CheckBox checkBox;
    TextView textViewPrice;

    public MyViewHolder(View view) {
        super(view);
        checkBox = (CheckBox) view.findViewById(R.id.deliveryname_checkbox);
        textViewPrice = (TextView) view.findViewById(R.id.period_price);
    }
}

public SubscriptionRecyclerViewAdapter(List<DaysOfDelivery> daysDeliveryList) {
    this.daysOfDeliveryList = daysDeliveryList;
    daylist = new String[daysOfDeliveryList.size()];

}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.horizontal_listview_availability, parent, false);

    return new MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    DaysOfDelivery days = daysOfDeliveryList.get(position);
    holder.checkBox.setText(days.getAvailabilityDays());
    holder.checkBox.setChecked(days.getCheckbox());
    holder.textViewPrice.setText(days.getPrice());
    if (days.getCheckbox())
        daylist[position]="1";
    else
        daylist[position]="0";

}

@Override
public int getItemCount() {
    return daysOfDeliveryList.size();
}

}
and my activity class update functionality:
update1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String[] days= SubscriptionRecyclerViewAdapter.daylist;

            if(isConnected)
                new EditSubscription().execute();
            else
                Toast.makeText(Subscription.this, "No Internet Connection", Toast.LENGTH_LONG).show();
        }
    });

in days i'm getting only sunday to wednesday values,remaining are not coming

A: maintain the daylist array in your activity/fragment, and when you want to update that list from adapter use callback for update.
In recyclerView views that are not visible in screen, are not been initialize until they comes in screen.
OR initialize that list too in constructor:
public SubscriptionRecyclerViewAdapter(List<DaysOfDelivery> daysDeliveryList) {
    this.daysOfDeliveryList = daysDeliveryList;
    daylist = new String[daysOfDeliveryList.size()];

    for (int i = 0; i < daysDeliveryList.size(); i++) {
        daylist[i] = daysDeliveryList.get(i).getCheckbox() ? "1" : "0";
    }

}


text:
Q: Vectorisation of nearest neighbour I'm looking for a way to improve the performance of my simple nearest neighbour function but I'm not very well versed when it comes to vectorisation with numpy. Any help would be appreciated!
def knn_search(pts_a, pts_b, k):
    """
    Finds the k nearest neighbours of each point in pts_a in pts_b
    :param pts_a:
    :param pts_b:
    :param k:
    :return dist, idx:
    """

    dist = np.empty((pts_b.shape[0], pts_a.shape[0]))
    for i in range(pts_b.shape[0]):
        dist[i, :] = np.linalg.norm(pts_a - pts_b[i, :], axis=1)

    idx = np.argsort(dist, axis=1)
    dist = np.sort(dist, axis=1)

    return dist[:, :k], idx[:, :k]

a = np.random.rand(10, 2)
b = np.random.rand(10, 2)

distance, indices = knn_search(a, b, 5)

A: You can replace your loop with an outer difference using broadcasting:
def knn_search(pts_a, pts_b, k):
    """
    Finds the k nearest neighbours of each point in pts_a in pts_b
    :param pts_a:
    :param pts_b:
    :param k:
    :return dist, idx:
    """

    dist = np.linalg.norm(pts_a - pts_b[:, None], axis=-1)
    idx = np.argsort(dist, axis=1)
    dist = np.sort(dist, axis=1)

    return dist[:, :k], idx[:, :k]


text:
Q: Get all DISTINCT items in the List with LINQ I am quite new to LINQ, I have the following script which returns me the first item in the table if condition meets, however, I would like to get all distinct items not only the first one. I am relatively new on this platform.
public LG GetLG (int WID)
{
    lock (locker) {
      return database.Table<LG> ().FirstOrDefault (x => x.id == WID);
    }
}

A: Is .Distinct() what you're looking for?
return database.Table<LG>.Where(x => x.id == WID).Distinct()

The following link contains useful material:
Example:
List<int> ages = new List<int> { 21, 46, 46, 55, 17, 21, 55, 55 };

IEnumerable<int> distinctAges = ages.Distinct();

Console.WriteLine("Distinct ages:");

foreach (int age in distinctAges)
{
  Console.WriteLine(age);
}

This code produces the following output:

Distinct ages:
  21
  46
  55
  17

A: in your LG object, you'll need to override the Equals and the GetHashCode methods.
Once you've done that, you can use the Distinct() function in LINQ
database.Table<LG>.Where(x => x.id == WID).Distinct()


text:
Q: Java iText There is no associate PdfWriter for making indirects I have the following method that scales an image to A4
   void scale(PdfDocument pdfDocument, Rectangle pageSize, Rectangle pageBodySize) {
    int n = pdfDocument.getNumberOfPages();

    for (int i = 1; i <= n; i++) {
        PdfPage page = pdfDocument.getPage(i);

        MarginFinder marginFinder = new MarginFinder();
        PdfCanvasProcessor pdfCanvasProcessor = new PdfCanvasProcessor(marginFinder);
        pdfCanvasProcessor.processPageContent(page);
        Rectangle boundingBox = marginFinder.getBoundingBox();
        if (boundingBox == null || boundingBox.getWidth() == 0 || boundingBox.getHeight() == 0) {
            System.err.printf("Cannot scale page %d contents with bounding box %s\n", i, boundingBox);
            continue;
        } else {
            // Scale and move content into A4 with margin
            double scale = 0, xDiff = 0, yDiff = 0;
            double xScale = pageBodySize.getWidth() / boundingBox.getWidth();
            double yScale = pageBodySize.getHeight() / boundingBox.getHeight();
            if (xScale < yScale) {
                yDiff = boundingBox.getHeight() * (yScale / xScale - 1) / 2;
                scale = xScale;
            } else {
                xDiff = boundingBox.getWidth() * (xScale / yScale - 1) / 2;
                scale = yScale;
            }

            AffineTransform transform = AffineTransform.getTranslateInstance(pageBodySize.getLeft() + xDiff, pageBodySize.getBottom() + yDiff);
            transform.scale(scale, scale);
            transform.translate(-boundingBox.getLeft(), -boundingBox.getBottom());

            new PdfCanvas(page.newContentStreamBefore(), page.getResources(), pdfDocument)
                    .concatMatrix(transform);

        }
        page.setMediaBox(pageSize);
        page.setCropBox(pageSize);
    }
}

This method is invoked/called in this snippet :
  ByteArrayOutputStream mergedPdfStream = new ByteArrayOutputStream();
    PdfDocument mergedPdf = new PdfDocument(new PdfWriter(mergedPdfStream));

    for (PdfDocument doc : pdfDocuments) {
        int n = doc.getNumberOfPages();

        for (int i = 1; i <= n; i++) {

            PdfPage page = doc.getPage(i).copyTo(mergedPdf);
            mergedPdf.addPage(page);

        }
        Rectangle pageSize = PageSize.A4;
        Rectangle pageBodySize = pageSize.clone().applyMargins(72, 72, 72, 72, false);
        scale(doc, pageSize, pageBodySize);
    }

    mergedPdf.close();

However , when it performs this code at the end
 new PdfCanvas(page.newContentStreamBefore(), page.getResources(), pdfDocument)
                .concatMatrix(transform);

It throws an PDF Exception There is no associate PdfWriter for making indirects:
 com.itextpdf.kernel.PdfException: There is no associate PdfWriter for making indirects.
at com.itextpdf.kernel.pdf.PdfObject.makeIndirect(PdfObject.java:228) ~[kernel-7.1.1.jar:?]
at com.itextpdf.kernel.pdf.PdfObject.makeIndirect(PdfObject.java:248) ~[kernel-7.1.1.jar:?]
at com.itextpdf.kernel.pdf.PdfPage.newContentStream(PdfPage.java:1186) ~[kernel-7.1.1.jar:?]
at com.itextpdf.kernel.pdf.PdfPage.newContentStreamBefore(PdfPage.java:244) ~[kernel-7.1.1.jar:?]

How can I fix this problem? Am I doing something wrong ?

A: You call
scale(doc, pageSize, pageBodySize);

for each PdfDocument doc in pdfDocuments. So after copying the pages to mergedPdf you try to scale the pages in your source documents. You cannot scale the pages in your source PdfDocument instances as they are opened read-only (i.e. only with a PdfReader, without a PdfWriter), and doing so after copying also doesn't make sense as you surely want to scale what's in the result mergedPdf, not in the sources.
Thus, move the block
Rectangle pageSize = PageSize.A4;
Rectangle pageBodySize = pageSize.clone().applyMargins(72, 72, 72, 72, false);
scale(doc, pageSize, pageBodySize);

out of the outer for loop body, after it, and replace the last line by
scale(mergedPdf, pageSize, pageBodySize);

to scale the resulting merged PDF.


text:
Q: How to intuitively understand this algebraic topology theorem? In discussing the Homology group of CW-complexes:

Theorem: Let $X^*$ be a space obtained by appropriately attaching a collection of $n$-cells $\{e^n_\lambda | \lambda \in \Lambda\}$ to $X$. Then $H_q(X^*,X) = 0$ for all $q \neq n$. For each index $\lambda \in \Lambda$, the characteristic map $f_\lambda$ induces a monomorphism of relative homology groups $$f_{\lambda *} : H_n(E^n, S^{n-1}) \to H_n(X^*,X)$$
  and $H_n(X^*,X)$ is the direct sum of the image subgroups.

Intuitively, I can understand the first part $H_q(X^*,X) = 0$ for all $q \neq n$ as follows: $H_q(X^*,X)$ is kind of like the homology group of the space $X^*$ if we 'trivialise' the subspace $X$. But if we are ignoring $X$ from $X^*$, then what we are left with are the $n$-cells $e^n_\lambda$ that we pasted onto $X$ to make $X^*$. These are all $n$-dimensional balls, so if we are considering the homology of a higher dimension $q > n$ then $H_q(X^*,X) = 0$ because nothing of higher dimension can be fit into these balls, and if we are considering the homology of a lower dimension $q < n$ then $H_q(X^*,X) = 0$ because all lower dimension 'paths' get trivialised (the way I imagine it in my head is like how the fundamental group of $S^2$ is trivial?)
Firstly, is this an acceptable 'intuitive' understanding of the first statement? And how would I go about understanding the rest of the theorem? It seems 'intuitive' that $H_n(E^n,S^{n-1})$ is just $\mathbb{Z}$ (I think) because effectively we are starting off with a closed $n$-dimensional ball, then we are identifying its boundary together, which sort of "zips it up" into an $n$-dimensional sphere, which has exactly one hole in it. I'm not sure how to go ahead and think about the characteristic map though...

A: I do not think that it is a good idea to think of trivialization of paths. Homology is more about cycles and boundaries. Remember for a CW complex $(X,\{X^{n}\}_n)$ cellular chain groups are defined as
$$ C_n(X) = H_n(X^{n},X^{n-1})$$
In the question we have $C_{n}(X^{\ast}) = H_n(X^{\ast}, X) \cong \mathbb{Z}^{\text{number of n-cells}}$. You are right for the case $q>n$ but it might be better to obtain the result by observing all cellular chain groups are zero for $q>n$ by definition of chain groups. For the case $q <n$, you can think of cellular approximation theorem((image of every singular $q$-chain can be homotoped to $(q+1)$-skeleton) and conclude that all $q$-cycles lies in $(q+1)$-skeleton (here recall that relative singular chains groups are defined as $S_q(X^{\ast},X)= S_q(X^{\ast})/S_q(X)$) or using the fact that $(X^{\ast},X)$ is a good pair and this gives $H_q(X^{\ast},X) \cong \tilde{H}_q(X^{\ast}/X)= \tilde{H}_q(\vee_{\lambda \in \Lambda} S^n)=0$ when $q <n$.
Your intuition about $H_n(E^n,S^{n-1})= \mathbb{Z}$ is right $(E^{n},S^{n-1})$ is a good pair and $H_n(E^{n},S^{n-1}) \cong \tilde{H}_n( E^{n}/S^{n-1}) \cong \tilde{H}_n(S^n) \cong \mathbb{Z}$.
For the characteristic maps recall that $f_{\lambda}|_{int{E^{n}}} : int(E^{n}) \to X^{\ast}$ is a homeomorphism onto its image and $f_{\lambda}|_{S^{n-1}} (S^{n-1}) \subset X$ (Image of attaching map lies in $(n-1)$-skeleton.) Hence, we can conclude that $f_{\lambda}$ is a map of pairs $(E^n ,S^{n-1}) \to (X^{\ast},X)$ and since it restricts to a homeomorphism on interior of $E^{n}$, it induces an injection(monomorphism) on homology
$$f_{\lambda \ast} : H_n(E^n,S^{n-1}) \to H_n(X^{\ast},X)$$


text:
Q: where tag value of UIButton in interface builder is gone in xcode 5? I was just updated my xcode to xcode 5 , now i need to set the tag value of UIBUTTON in interface builder , but i can't see any tag textfield in xcode 5 , Please tell me where it is gone ?

A: On the attribute pane, scroll down to View. Hover over it and you'll see on the right it shows Show. Click on it and it will expand and show you the Tag value.


text:
Q: FacetWP is braking masonry layout I'm using FacetWP to build a filter form. Unfortunately, my masonry layout is braking when I select any option in the form. Results are presenting as a single column, instead of 3. Weird is that F5 makes the order (3 columns) right.
I was trying to use these methods: https://facetwp.com/documentation/template-configuration/ and this one: https://facetwp.com/using-facetwp-with-existing-template-files/
My code is
        <div id="primary" class="content-area col-md-9 <?php echo sydney_blog_layout(); ?>">

        <?php
        $args = array(
            'post_type' => 'nieruchomosci',
            'posts_per_page' => 12,
        );
        $query = new WP_Query( $args );?>
        <?php if ( $query->have_posts() ) : ?>

Szukaj nieruchomości

<?php echo facetwp_display( 'facet', 'rodzaj' ); ?><?php echo facetwp_display( 'facet', 'typ' ); ?><?php echo facetwp_display( 'facet', 'lokalizacja' ); ?>

            <?php while ( $query->have_posts() ) : $query->the_post(); ?>

                <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

    <?php if ( has_post_thumbnail() && ( get_theme_mod( 'index_feat_image' ) != 1 ) ) : ?>

            <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail('sydney-large-thumb'); ?>

    <?php endif; ?>

        <?php the_title( sprintf( '
', esc_url( get_permalink() ) ), '
' ); ?>

                <?php the_field('cena'); ?> PLN | <?php the_field('powierzchnia'); ?> m2

                <?php echo get_the_term_list( $post->ID, 'rodzaj', '', ', ', '' ) ?> na <?php echo get_the_term_list( $post->ID, 'typ', '', ', ', '' ) ?> w miejscowości <?php echo get_the_term_list( $post->ID, 'lokalizacja', '', ', ', '' ) ?>
        <?php
            wp_link_pages( array(
                'before' => '
' . __( 'Pages:', 'sydney' ),
                'after'  => '
',
            ) );
        ?>

        <?php sydney_entry_footer(); ?>

            <?php endwhile; ?>

            <?php the_posts_navigation(); ?>

        <?php else : ?>

            <?php get_template_part( 'content', 'none' ); ?>

        <?php endif; ?>

Any advice will be very nice.

A: Try reload layout on facetwp-loaded event. From your question it is unclear how a masonry layout was created. Assuming it is masonry.js, you can do layout when FacetWP finishes loading like this:
$(document).on('facetwp-loaded', function() {
    // do layout when FacetWP finishes
    $grid.masonry('layout');
});

Check more here
https://facetwp.com/documentation/facetwp-loaded/

A: Actually I got his to work (using Masonry PACKAGED v4.1.1 & imagesLoaded PACKAGED v3.1.8):
$(document).on('facetwp-loaded', function() {
    var $grid = $( '.grid' ).imagesLoaded( function() {
        $grid.masonry("reloadItems");
        $grid.masonry( {
            itemSelector : '.loop-entry',
            gutter       : 30,
            columnWidth  : 240,
            isAnimated   : true,
            animationOptions : {
                duration : 300,
                easing   : 'easeInOutCirc',
                queue    : false
            }
        });
    });
});


text:
Q: Overriding Scope in Go I'm actually new to go and I'm unable to find how to override scope of the variable in Go
consider this...
package main

import (
    "fmt"
)

var x = 10
var a int = 10

func main() {
    var a int = 20
    fmt.Println(a)
}

When I run it the output is 20 which means it actually prints the local scope variable
How can I display the global variable 'a' inside the main function

A: What you're doing is called "variable shadowing".  If you want to access the global variable, the only option is simply to not shadow it!
var a int = 10

func main() {
    var localA int = 20
    fmt.Println(a) // 10
    fmt.Println(localA) // 20
}

Of course, you could preserve the global value in a different local variable before shadowing. I can't imagine when this would actually be useful:
var a int = 10

func main() {
    globalA := a
    var a int = 20
    fmt.Println(a) // 20
    fmt.Println(globalA) // 10
}


text:
Q: Matlab: save string in a txt file I have a long string with a lot of information, some empty rows and combined numbers and text in it. I tried to save it into txt file but it writes me a txt file with strange/unreadable characters:
Here is my code which does not work:
name_log = TPR_E01;
filename = strcat('New_',name_log);
save ( filename,'newCleanMarker')

Thank you!

A: save writes binary data by default. You can try the '-ascii' flag, or better still you can print the string to file
fid = fopen( ['New_', name_log], 'w' ); %// open file to writing
fprintf( fid, '%s', newCleanMarker ); %// print string to file
fclose( fid ); %// don't forget to close the file

Please see the following man pages

*

*fopen - how to open a file in Matlab.

*fullfile - a good practice to create file names and paths.

*save - saving binary data, and the use of '-ascii' flag.


text:
Q: What is a $G$-Galois Branched Cover What is, in the language of Schemes, a $G$-galois branched cover?

A: I don't think this phrase has a single precise translation into the general language of schemes, but it will mean something like the following:
a finite surjective morphism $X \to Y$ of integral schemes such that the corresponding extension of function fields $K(Y) \subset K(X)$ is Galois with Galois group $G$.
It would also be reasonable to require that $X$ and $Y$ be normal.
To understand what it means geometrically, one should imagine that $X$ and $Y$ are projective varieties over some field.  What this will mean then is that $X \to Y$ is surjection with finite fibres, that $G$ acts as a group of automorphisms of $X$ over $Y$,
and that if we remove the branch locus (i.e. the closed subset of $Y$ along
which the fibres contain points with multiplicity $> 1$) then each fibre is acted on
faithfully and transitively by $G$ (so, away from the ramification locus, there
are $|G|$ sheets of $X$ over $Y$, which are permuted by $G$).
A concrete example is given by (the projectivization of) the map $(x,y) \mapsto x$
from the elliptic curve $E$ defined by $y^2 = x^3 - x$ to $\mathbb P^1$.
The group $G$ is cyclic of order two, acting by $(x,y) \mapsto (x,-y)$, and
the branch points are precisely the points where $y = 0$ (four of them; three
three finite points $(0,0), (\pm 1,0)$, and also one at infinity).
In this context, an important result is the Zariski--Nagata purity theorem, which says
(under mild hypotheses, e.g. that $Y$ and $X$ are smooth, or more generally,
that $Y$ is smooth and $X$ is normal) that the set of branch points has pure codimension one,
i.e. is a divisor.


text:
Q: Ядро jquery Привет. В принципе разобраться в работе jQuery можно ( и нужно). Вот даже пишу (в целях самообучения) свою библиотеку. Вопрос интересует по поводу таких конструкций, как
$('
this is a new div
');

Не могу сообразить реализацию. Неужели jQuery регуляркой парсит такие выражения, вытаскивая из него название элемента, атрибуты, innerHTML и т.д., а потом создает элемент? Можно ли сразу каким-то образом превратить выражение в скобках в html-код? Ведь, если использовать метод innerHTML необходимо создавать дополнительный элемент и в него загружать html-фрагмент.
Что бы разобраться в самой библиотеке jquery наверное мне не хватит мозгового вещества. Если кто-нибудь знает, подскажите пожалуйста!
A: JSFiddle
var createDocumentFragment = (function ()
{
    var frag  = document.createDocumentFragment(),
        elem  = document.createElement('div'),
        range = document.createRange && document.createRange();
    frag.appendChild(elem);
    range && range.selectNodeContents(elem);
    return range && range.createContextualFragment ?
        function (html)
        {
            if (!html) return document.createDocumentFragment();
            return range.createContextualFragment(html);
        } :
        function (html)
        {
            if (!html) return document.createDocumentFragment();
            elem.innerHTML = html;
            var frag = document.createDocumentFragment();
            while (elem.firstChild)
                frag.appendChild(elem.firstChild);
            return frag;
       };
}());


text:
Q: Different download tools result in different MP3 checksums I wrote some code for downloading podcasts and noticed that the checksums of files I downloaded with it didn't match those of files downloaded using other methods.
Initially I thought there was a bug in my code but through testing I've noticed that files downloaded using wget, curl and Invoke-WebRequest also differ from each other. I've tested on my Windows 10 PC and an Ubuntu 16.04 VPS I have and the same thing happens on both.
Does anybody have any idea what might be causing this?

A: This is most likely due to the website delivering slightly different streams to each downloader.
The difference could be due to watermarks (in case of copyrighted material often used to unique identify each download), DRM, different codecs used for encoding the audio stream, different meta-data (e.g timestamps like "downloaded on date/time") embedded in the file, etc.