text:
Q: Storing a *.png file to a cloud storage through API My java app generates some .png image which i want to store to any cloud storage through java API. I dont want any paid service if possible in free. Not getting a good answer for last 4 hours. Any suggestion?

A: Google Cloud Storage doesn't have a free tier, although for only a handful of PNG images you will likely be spending less than $1 per month.
Google Drive, however, is free for the first 15 GB or so (it's shared with your GMail account, your Google+ photos, etc). Google Drive also provides a Java API: https://developers.google.com/drive/quickstart-java
Dropbox and S3 also both have APIs and various quantities/time of free storage. If you're just looking to host images, and you're not trying to make money, and you don't need to host that many, you could look into image-specific services. Imgur.com, for example, provides an API.

A: Dropbox and Google Drive could meet your needs. You can download/upload files pragmatically to Dropbox and also to Google Drive. They have API to do it.
However, if you are really looking for really complete service where you can scale up your data storage until you want, you really want to take a look at Amazon S3. In fact, as far as I know, Dropbox works on the top of Amazon S3 to provide their services.
If you would like to have an idea about how to upload/download a file to Amazon S3, you can take a look to this application example. If you want the same thing on Dropbox or Google Drive, there are a lot of examples on Internet. However, on these two providers you need a token to upload files, what I don't like. I prefer the way in which it works for Amazon S3 (just for programming purposes - GUI is better on GD or Dropbox).
Amazon S3 is not totally free, but it is really, really cheap.
Be aware of the network latency between your app and your File storage provider if you don't use the same physical infrastructure.


text:
Q: JavaScript, AJAX, jQuery: Динамическое обновление контента Здравствуйте. Ситуация следующая: есть страничка на php поднятая на Apache, есть база данных на MySQL, на страничке имеется форма для отправления сообщений и обновление списка сообщений после отправки. Обновление сделал через AJAX, так же, на страничке стоит такой таймер:
  setInterval(function() {
    $("#refresh").load(location.href+" #refresh>*","");
  }, 2000);

Он каждые 2 секунды обновляет содержания div'a с id refresh, выводя сообщения из базы. Проблема в том, что он это делает даже если новые сообщения не появились в базе. Как можно сделать проверку на то, соответствует ли старое содержание, которое вернул сервер, новому, которое вернет сервер?
Скажу еще немного иначе. Как можно сделать обновление div'a refresh у каждого пользователя на странице, когда хоть один из них отправит сообщение?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Clarification On Write-Caching Policy, Its Underlying Options And How It Applies To Hard Drives And Solid-State Drives In last week after doing more research on subject matter, I have been wondering about what I have been neglecting all those years to understand write-caching policy, always leaving it on default setting. Write-caching policy improves writing performance and consists of write-back caching and write-cache buffer flushing.
This is how I understand all the above, but correct me if I erred somewhere:
Write-through cache / Write-through caching itself is not a part of write caching policy per se and it's when data is written to both cache and storage device so if Windows will need that data later again, it is retrieved from cache and not from storage device which means only improved read performance as there is no need for waiting for storage device to read required data again. Since data is still written to storage device, write performance isn't improved and represents no risk of data loss or corruption in case of power failure or system crash while only data in cache gets lost. This option seems to be enabled by default and is recommended for removable devices with no need to use function of "Safely Remove Hardware" on user's part.
Write-back caching is similar to above but without writing data to storage device, periodically releasing data from cache and writing to storage device when it is idle. In my opinion this option improves both read and write performance but represents risk if power failure or system crash occurs with the outcome of not only losing data eventually to be written to storage device, but causing file inconsistencies or corrupted file system. Write-back caching cannot be enabled together with write-through caching and it is not recommended to be enabled if no backup power supply is availabe.
Write-cache buffer flushing I reckon is similar to write-back caching but enables immediate release and writing of data from cache to storage device right before power outage occurs but I don't know if it applies also to occasional system crash. This option seem to be complementary to write-back cache reducing or potentially eliminating risk of data loss or corruption of file system.
I have questions about relevance of last 2 options to today's modern SSDs in order to get best performance and with less wear on SSDs:
I know that traditional hard drives come with onboard cache (I wonder what type of cache that is), but do SSDs also come with cache? Assuming they do, is this cache faster than their NAND flash and system RAM and worth taking the risk of utilizing it by enabling write-back cache? I read somewhere that generally storage device's cache is faster than RAM, but I want to be sure. Additionally I read that write-caching should be enabled since current data that is to be written later to NAND flash is kept for a while in cache and provided there is data that gets modified a lot before finally being written, holding of this data and its periodic release reduces its write times to SSD thereby reducing its wearing.
Now regarding to write-cache buffer flushing, I heard that SSD controllers are so fast by themselves that enabling this option is not required, because they manage flushing. However, once again, I don't know if SSDs have their own onboard cache and whether or not it is faster than their NAND flash and system RAM because if it is, keeping this option enabled would make sense.
Recently I have posted question about issue with my Intel 330 SSD 120GB which was main reason to do deeper research having suspicion of write-caching policy being the culprit of SSD's freezing issue assuming data being released is what causes freezes. Currently I have write-cache enabled and write-cache buffer flushing disabled because I believe SSD controller's management of write-cache flushing and Windows write-cache buffer flushing are conflicting with each other:

Since I want to troubleshoot in small steps to finally determine the source of issue, I have decided to start with write-caching policy and the move to drivers, switching to AHCI later on and finally disabling DIPM (device initiated power management) through registry modification thanks to @TomWijsman


text:
Q: Can I create a Singularity container which others cannot run with root privileges? I am not very experienced with the finer details of Singularity containers yet and I was wondering if an admin on a system can create Singularity containers which they can let ordinary users run, but preventing them from running with root privileges?
Normal practice on our system is to let users build their own Singularity containers inside which they are the king of their own castle. Now I am investigating the possibility of offering some pre-defined Singularity containers which are configured by an admin and which the users are allowed to instantiate themselves, but where they cannot have root privileges inside.

A: The default in singularity is that the images are run as/with the permissions of the user executing them and not as root. If you provide a pre-built image, that should be the case. The images themselves are RO (unless using sandboxes) and /etc/passwd and /etc/group are mounted in to ensure they're run based on the host account privs rather than any user that was created when the image was being built.
How are you giving them full privs in the singularity containers currently?  You can allow sudo access to just the singularity build command, which will let them build whatever containers they want, but when they run the containers they will have to do it as their current user. Example line from /etc/sudoers:
singularity-build ALL=(ALL) SETENV: /usr/bin/singularity build *, /usr/bin/singularity --debug build *, /usr/bin/singularity --verbose build *

SETENV allows the users to sudo -E singularity build, which is useful when using the special SINGULARITY_* variables instead of command line params.
If they're currently building sandbox / writable images with sudo, you can also add entries for singularity (--debug|--verbose) (run|exec|shell) --writable *. Using --writable with a read only image will cause a fatal error, so they will be unable to run pre-built images you provide with root privileges. That said, I would recommend against allowing users sudo privs with any singularity commands other than build. Privilege escalation is fairly trivial if they mount the host filesystem into a container they're running as root inside.


text:
Q: Custom Color for Captcha Well , first of all i need to tell you i'm noob with this .
I found a php file that generate captcha .
It worked but the background was always orange and the text was black .
Example Captcha : "3ab6de" . All I want to do is change the background color to another color and  to have the text with different colors ( 3ab in red , 6de in blue)  .
I tried but fail please help  me  guys !
This is the code:
    <?php
    session_start();
    $random_alpha = md5(rand());
    $captcha_code = substr($random_alpha, 0, 6);
    $_SESSION["captcha_code"] = $captcha_code;
    $target_layer = imagecreatetruecolor(70,30);
    $captcha_background = imagecolorallocate($target_layer, 255, 160, 119);
    imagefill($target_layer,0,0,$captcha_background);
    $captcha_text_color = imagecolorallocate($target_layer, 0, 0, 0);
    imagestring($target_layer, 5, 5, 5, $captcha_code, $captcha_text_color);
    header("Content-type: image/jpeg");
    imagejpeg($target_layer);
    ?>

Thanks !

A: I think should you split your captcha string to two difference, some like this.
<?php
session_start();
$random_alpha = md5(rand());
$captcha_code = substr($random_alpha, 0, 6);
$_SESSION["captcha_code"] = $captcha_code;
$leng1 = count($captcha_code)/2;

$captcha_code1 = substr($captcha_code, $leng1);
$captcha_code2 = substr($captcha_code,- count($captcha_code) + $leng1);

$target_layer = imagecreatetruecolor(70,30);
$captcha_background = imagecolorallocate($target_layer, 255, 160, 119);
imagefill($target_layer,0,0,$captcha_background);
$captcha_text_color1 = imagecolorallocate($target_layer, 0, 0, 0);
$captcha_text_color2 = imagecolorallocate($target_layer, 0, 0, 0);

imagestring($target_layer, 5, 5, 5, $captcha_code1, $captcha_text_color);
imagestring($target_layer, 5, 5, 5, $captcha_code2, $captcha_text_color2);

header("Content-type: image/jpeg");
imagejpeg($target_layer);
?>

A: You can try captcha.com library, there are several examples at https://captcha.com/captcha-examples.html

I hope this may help you.


text:
Q: Why does presence of value evaluate as "Truthy" in Python? [e.i. Types evaluate True in conditionals] Example:
if float: print('float is true?')

returns:

Why do all objects other than ones explicitly defined as False or "False" evaluate truthfully?

A: The Python language is strongly influenced by C. And C is a horrible language that didn't even have a boolean type until C99. Instead, it has integers. Anything that looks like a zero integer is false, anything else is true. It turns out that this is mightily convenient.
Wanna test for a null pointer? Unlike Java, you don't have to spell out if (thing != null) foo(thing); – a if (thing) foo(thing); suffices.
Wanna check if we reached the end of a string? Just dereference it in a conditional:
char c;
while ((c = *str++)) do_something(c);

Wanna check if an array contains any items? Just test for the length:
int n;
...;
if (n) we_have_items();

So conceptually, a conditional has two forms:

*

*a predicate form with some expression that evaluates to a boolean-interpretable value.

*a container form with a single variable to check that this container is not-empty.

While Python has actual boolean types rather than overloading integers, it keeps this very popular mechanism for collections. For example, None (Python's null equivalent), empty strings "", empty lists [], and empty dicts {} all evaluate to False in a boolean context. This usually does what you want, and if it doesn't, you can be explicit about your requirements. For example, you can specifically test that a variable is not None:
if x is not None:
  do_something_with(x)

However, if you know that name is an optional string, then writing
if name:
  print("hello, ", name)
else:
  print("name required!")

is much more comfortable than
if bool(name):  # manually force to-bool conversion
  ...

or
if name is not None and len(name):  # explicitly state your intent: at least one character
  ...

or
if name is not None and bool(len(name)): # what the above example really means
   ...

or
if name is not None and len(xs) > 0:  # even more explicit
  ...

It is important to note that these implicit conversions are not black magic that pull the comfy rug of type safety away from under your feet. In Python, these conversions always happen quite explicitly, but if you pass a function or a builtin some value, it may perform any such conversions on that argument. For example, you can explicitly request a bool conversion via bool(some_value). So if you want to, you can think of the if EXPRESSION: ... builtin as being implemented like:
def if(EXPRESSION, then, else):
  real_if bool(EXPRESSION):
    then()
  real_else:
    else()

You can also define your own to-bool conversion for your own classes, by implementing the special __bool__(self) method. But careful! Conversions and operator overloading can get quite confusing for a user unless the semantics are obvious and intuitive. In Python, it is considered sufficiently clear for a to-bool conversion to test whether a collection or container is empty. For non-containers, it might be a good idea to use an ordinary, named method instead.
So why does it make sense for values to evaluate to True even when no to-bool conversion has been defined? User-defined types generally have reference semantics, i.e. the variable holds a pointer to the value, not the value itself. As we have seen, the if (pointer) ... C idiom tests whether a pointer is not empty, so it makes some sense to extend it even to Python which does not have reified pointers. So the conditional here does not test whether the value is true or false, but whether the variable currently holds a value. If the type had value semantics, I would find such a to-bool conversion highly confusing, but that might just be the C++-programmer in me speaking.

A:
Why do all objects other than ones explicitly defined as False or "False" evaluate truthfully?

Simple explanation:
Because they do, by definition.  Sorry if that seems like a tautology, but that really is the correct answer: this is the arbitrary way it works because that is the arbitrary way it is specified to work in the arbitrary, canonical rules of the language.
Philosophical explanation:
Have a look at the Zen of Python, which states:

Special cases aren't special enough to break the rules.

If the rules are that "this specific set of values are falsy and everything else is truthy," then even though it seems nonsensical to have a reference to a type being either truthy or falsy, that's a special case, and it's not special enough to break the rules.
Flame bait explanation:
Because Python lacks a proper static type system, in which the only True and False values would be True and False, and anything else would be rejected at compile time.  And since you can't do that in a dynamic language, Python takes the easy way out instead of spending extra effort to do it "the right way" (and good luck defining that in this context!) even when it means accepting obviously-invalid and nonsensical code.
Take your pick ;-)


text:
Q: Is it possible to define custom android sourceSets for certain subsets of flavors? I have a project with 4 flavor dimensions, which is making it hard to share resources between some combinations of flavors.
FlavorA {dimension 'Dimension1'}
FlavorB {dimension 'Dimension1'}

FlavorC {dimension 'Dimension2'}
FlavorD {dimension 'Dimension2'}

FlavorE {dimension 'Dimension3'}
FlavorF {dimension 'Dimension3'}

FlavorG {dimension 'Dimension4'}
FlavorH {dimension 'Dimension4'}

In my project, I need every FlavorAFlavorC build variant to share some resource.
However, the only available source sets are in the following form:

*

*FlavorA

*FlavorB

*...

*FlavorH

*FlavorAFlavorCFlavorEFlavorG

*FlavorAFlavorCFlavorEFlavorH

*FlavorAFlavorCFlavorFFlavorG

*...

I tried having some custom folders, like a FlavorAFlavorC folder, and then in applicationVariants.all:
if(variant.name.contains('FlavorA') && variant.name.contains('FlavorC')){
    variant.mergeResourcesProvider.get().doFirst {
        android.sourceSets.debug.res.srcDirs += "src/FlavorAFlavorC/res"
        android.sourceSets.release.res.srcDirs += "src/FlavorAFlavorC/release/res"
    }
}

This solution, however, is extremely inconsistent. Upon further investigation I came to the conclusion that this inconsistency derives from setting android.nonTransitiveRClass=true on gradle.properties.
Is there a better way to share resources between certain subsets of flavors or to avoid the issue caused by the flag?


text:
Q: The xml layout created in the Android studio looks like this It looks good in the Android studio.
You can see from the image.
Relative layout or linear layout is not shown.
Use version 3.4.
For reference, Hangul is shown as a rectangle in 3.4.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/app_bar_main"
    tools:context=".MainActivity">

    <TextView

        android:id="@+id/textView2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="맞은 갯수 알아보기"
        android:textAppearance="@style/TextAppearance.AppCompat.Display1"
        tools:layout_editor_absoluteX="16dp"
        tools:layout_editor_absoluteY="40dp" />

    <EditText
        android:id="@+id/Score"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="여기에점수"
        android:inputType="textPersonName"
        android:textAppearance="@style/TextAppearance.AppCompat.Display1"
        tools:layout_editor_absoluteX="16dp"
        tools:layout_editor_absoluteY="104dp" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="맞은갯수"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        tools:layout_editor_absoluteX="16dp"
        tools:layout_editor_absoluteY="258dp" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="setResultOk"

        android:text="갯수보기"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        tools:layout_editor_absoluteX="16dp"
        tools:layout_editor_absoluteY="181dp" />

    <TextView
        android:id="@+id/resultOK"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="@style/TextAppearance.AppCompat.Display1"
        tools:layout_editor_absoluteX="16dp"
        tools:layout_editor_absoluteY="288dp" />

</android.support.constraint.ConstraintLayout>

I will make it in a long time.
I forgot the knowledge I already knew.
Help me.

A: You have missed the constraints in the child views of ConstraintLayout, which is why they all go back to (0,0) co-ordinates when the view is actually rendered. The reason being, layout_editor_absoluteX and layout_editor_absoluteY do not work in runtime.
Android Studio is giving me a very well defined error for these child views, explaining the cause. Refer the screenshot here


text:
Q: PHP Unzip Local File Hi I need to download a zip file using ftp and then unzip it on local computer. I can download the file using ftp_get but I need help on unzipping it to specific location.
        $ftpServer = "server";
        $ftpUser = "user";
        $ftpPassword = "password";

        $ftp_server = $ftpServer;
        $ftp_conn = ftp_connect($ftp_server);
        $ftp_login = ftp_login($ftp_conn, $ftpUser, $ftpPassword );

        if(!$ftp_conn)
            die("A connection to $ftpServer couldn't be established");
        else if(!$ftp_login)
            die("Your login credentials were rejected");
        else
        {
            $file = "C:/files/downloads/FILE_NAME.ZIP";

            $server_file = "/FILE_NAME.ZIP";

            if (ftp_get($ftp_conn, $file, $server_file, FTP_ASCII))
            {

                $zip = new ZipArchive;
                $res = $zip->open($file);

                if ($res === TRUE)
                {
                  $zip->extractTo('C:/files/Feeds/');
                  $zip->close();
                }

                unlink($file);
            }
            else
            {
                echo "There was a problem\n";
                $this->index();
            }
        }

Thank you for you help.

A: Try with this code
Unzip.php:-
<?php
$zip = new ZipArchive;
if ($zip->open('/sites/gallery.zip') === TRUE) {
    $zip->extractTo('/sites/New folder/test');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>

For your reference see this link Documentation

A: You can use the ZipArchive class for this
$archive = new ZipArchive;
if ($archive->open('my_zip_fil.zip') === TRUE) {
    $archive->extractTo('destination/dir');
    $archive->close();
}

ZipArchive documentation


text:
Q: SignIn Stored Procedure I'm designing a stored procedure for a website signin and have
IF EXISTS (SELECT Member where Email=@EMail and PW=@PW)
BEGIN
   Select MemberId . . .
END
ELSE
BEGIN
   UPDATE FailCount +1

How should I next check for FailCount >= FailLimit ?
Specifically I've searched the following:

*

*IF. . . THEN

*CASE . .  WHEN

*DECLARE variables and SELECT INTO those variables which are then compared (rather than comparing two SELECTS from the same table).

All suggestions appreciated!

A: SELECT @Fail = FailCount
FROM USER_TABLE
WHERE Email = @EMail;

IF @Fail >= @FailLimit THEN
BEGIN
     /*  PUT YOUR CODE HERE */
END

ELSE
BEGIN

    IF EXISTS (SELECT Member FROM USER_TABLE where Email=@EMail and PW=@PW)
    BEGIN
       Select MemberId . . .
    END

    ELSE
    BEGIN
       UPDATE USER_TABLE
       SET FailCount = FailCount + 1
       WHERE Email = @EMail;
    END
END


text:
Q: AppDomain.AssemblyResolve doesn't work (as expected) with MEF I have this error:

Runtime error CS0234: The type or namespace name 'StiOracleSource' does not exist in the namespace 'Stimulsoft.Report.Dictionary'

I developed (VS 2012) an application that uses MEF (.NET 4.5) to interconnect several binary assemblies loaded from a database. One of its separate plug-in assemblies (implemented as an stand-alone executable) has dependency on a third party DLL (Database adapter) that cannot be included in the main application. When I run the plug-in as a stand-alone application everything goes fine but if I load that assembly as a MEF part into the main application then I got CS0234 error runtime despite I provide the third party DLL reference using AppDomain.CurrentDomain.AssemblyResolve event approach. Referencing the third party DLL in the main application doesn't help.
Can anyone explain why the plug-in assembly runs smoothly as a stand-alone application and why it is broken when it is executed as a part of the MEF?


text:
Q: One object only in GET method in Django REST Framework I have a list of all my objects when I use get method by api/movies in my api, and this is ok. I want also to get only one, specyfic object when use get method by  api/movies/1 but now I still have a list of all my objects... What to change in my MoviesView or in urls?
My views.py:
class MoviesView(APIView):
    def get(self, request):
        movies = Movie.objects.all()
        serializer = MovieSerializer(movies, many=True)
        return Response(serializer.data)

My appurls.py:
urlpatterns = [
    url('movies', MoviesView.as_view(), name="MoviesView"),
]

And my project urls.py:
urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include("api.urls")),
]

When I use routers everythig crushes... Could you help me?

A: You can simply use viewsets.ModelViewSet that natively implements list and retrieve.
You declare something like router.register('movies', my_views.MoviesViewSet) in you urls.py and
class MoviesViewSet(viewsets.ModelViewSet):
    queryset            = Movie.objects.all()
    serializer_class    = MovieSerializer
    permission_classes  = [IsAuthenticated, ]

    def get_queryset(self):
        return self.queryset

    def get_object(self):
        movie_id = self.kwargs['pk']
        return self.get_queryset().filter(id=movie_id)

    def retrieve(self, request, *args, **kwargs):
        try:
            instance = self.get_object()
        except (Movie.DoesNotExist, KeyError):
            return Response({"error": "Requested Movie does not exist"}, status=status.HTTP_404_NOT_FOUND)
        serializer = self.get_serializer(instance)
        return Response(serializer.data)

    def list(self, request, *args, **kwargs):
        queryset    = self.get_queryset()
        serializer  = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

This approach implies that you declare a Serializer, just like:
class MovieSerializer(serializers.ModelSerializer):
    class Meta:
        model   = Movie
        fields  = '__all__'

Django simply maps HOST/movies/ to list (multiple objects) and HOST/movies/PK/ to retrieve method (one single object).
Docs:

*

*https://www.django-rest-framework.org/api-guide/viewsets/#modelviewset

*https://www.django-rest-framework.org/api-guide/serializers/#modelserializer
Hope it helps.
BR.
Eduardo

A: I would suggest you if you want to retrieve just 1 element to use a Generic View, i.e RetrieveAPIView
It would give you all you need for getting 1 element.
from rest_framework import generics

class MoviesView(generics.RetrieveAPIView):
    queryset = Movie.objects.all()
    serializer_class = MovieSerializer

but you need also to change urls.py
url(r'movies/(?P<pk>[0-9]+)/$', MoviesView.as_view(), name="MoviesView"),

A: When you make a GET request to "api/movies/1", the url is matched to the "api/movies" path (read more in the docs), and the MoviesView's get method is called. And your get() implementation just fetches all the movies (movies = Movie.objects.all()), serializes and returns them - that's why you get the entire list.
If you want to retrieve one specific object, you need to somehow specify which object you have in mind, using its primary key (in your case, id).
1. You have to define a separate path: movies/<int:pk>/ (btw, which Django version are you using? url has been deprecated, use path instead!)
2. You have to define a detail view to handle this new case, and pass it to the path function as the second argument.
This general problem can really be solved in many ways, and depending on your app you may want to use a ViewSet instead of views. Then you don't have to define paths (urls) separately - you can use a router. You can't use routers with your view, because router needs a viewset class as its argument.
If you provide more details, I could try to suggest something more specific.

A: My appurls.py:
 use path method
urlpatterns = [
path('movies', MoviesView.as_view(), name="MoviesView"),]

Maybe it works

A: Start by adding a format keyword argument to both of the views, like so
def snippet_list(request, format=None):
and
def snippet_detail(request, pk, format=None):
Now update the snippets/urls.py file slightly, to append a set of format_suffix_patterns in addition to the existing URLs
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views
urlpatterns = [
path('snippets/', views.snippet_list),

path('snippets/<int:pk>', views.snippet_detail),

]
urlpatterns = format_suffix_patterns(urlpatterns)


text:
Q: Why is my character string distance always 5? I have a project that has three requirements:

*

*Prompt user to enter 5 uppercase characters and save as
variable.

*Randomly generate a 5 character string and save as variable.

*Compute the distance between the two strings.
I thought I had it and it looked like it worked, but then I noticed that the computed distance between the two strings is always 5.
I am guessing that my stringLength is somehow being used for stringDist.
If you could look it over and lead me in the right direction as to what I'm missing, I would greatly appreciate it.
import java.util.Random;
import java.util.Scanner;

public class StringDiff {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        System.out.println ("Please enter 5 Uppercase letters.");
        String userString = scan.nextLine();

        int leftLimit = 48; // numeral '0'
        int rightLimit = 122; // letter 'z'
        int stringLength = 5;
        Random random = new Random();

        String randString = random.ints(leftLimit, rightLimit + 1)
          .filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97))
          .limit(stringLength)
          .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
          .toString();
        {
            int i = 0, stringDist = 0;
            while (i < userString.length())
            {
                if (userString.charAt(i) != randString.charAt(i))
                    stringDist++;
                    i++;
            }
             System.out.println ("The user string is: " + userString);
             System.out.println ("The random string is: " + randString);
             System.out.println ("The distance between " + userString + " and " + randString + " is " + stringDist);
}

A: Since you're comparing a five character user-entered string with a randomly generated string, there's a good chance that there no positions where the corresponding characters are the same, which would make the distance equal to five. So in that sense, there's nothing wrong with your code. If you repeatedly run the program, you'll eventually get a distance less than five.


text:
Q: Complement of a closed star-shaped subset in a Frechet space Let $U$ be the complement of a closed star-shaped subset in a separable
infinite-dimensional Frechet space. Since every
separable Frechet space is homeomorphic to $l_2$,
one knows that $U$ is a Hilbert manifold.
 Question:
what else can be said about the topology of $U$?

A: I guess you want to impose some additional conditions on $U$. If $U$ is unbounded, then the topology of $l_2\setminus U$ can be as complicated as you wish. For example if you take U to be the product of a complex hyperplane arrangement $A\subset \mathbb C^n$ with $l_2$, i.e $U= A\times l_2\subset \mathbb C^n\times l_2$ you get a manifold with a complicated fundamental group. You can also throw away from $l_2$ a countable set of planes of finite (but growing codimention), this will give you holomogy in all dimensions.
Of course all this is true even you ask your question for complements to closed star-shaped sets in finite dimensional spaces. So, it would be nice to know what kind of finite-dimensional phenomena you want to generalise.  Because obviously, if you assume that $U$ is bounded and contains a neighbourhood of $0$, then the complement $l_2\setminus U$ deformation retracts to $S^{\infty}$, so it is contractible.


text:
Q: How to set to XAML property a property value from another class I'm trying to set property value from another class to XAML UI element property .
I have XAML and static class called "Config".
In Config class I have public static class Theme.
In the class Theme I have property primaryColor.
So I need to set primaryColor to UI element in XAML.
I tried x:Static, but it doesnt work for me, cause the field in the Theme class is not static.
XAML:
<StackLayout BackgroundColor={x:Static config:Config.CurrentTheme.primaryColor}></StackLayout>

Config.cs:
public static class Config
{
    public static Theme CurrentTheme { get; set; }
}

Theme.cs:
public class Theme
{
    public Color primaryColor { get; set; } = Color.FromHex("#1D1E1F");
    public Color secondaryColor { get; set; } = Color.FromHex("#252625");
    public Color grayColor { get; set; } = Color.FromHex("#2F2F2F");
    public Color lightGrayColor { get; set; } = Color.FromHex("#626261");
    public Color goldColor { get; set; } = Color.FromHex("#CAA440");
    public Color lightGreenColor { get; set; } = Color.FromHex("#28A745");
    public Color darkRedColor { get; set; } = Color.FromHex("#F0373A");
}

A: When you read about x:Static it directly says:
x:Static accesses one of the following:

*

*a public static field

*a public static property

*a public constant field

*an enumeration member.

since your properties do not meet the criteria mentioned above it does not work!

A: Adding Static to Theme.cs , then can be used in Xaml :
public static class Theme
{
    public static Color primaryColor { get; set; } = Color.FromHex("#1D1E1F");
    public static Color secondaryColor { get; set; } = Color.FromHex("#252625");
    public static Color grayColor { get; set; } = Color.FromHex("#2F2F2F");
    public static Color lightGrayColor { get; set; } = Color.FromHex("#626261");
    public static Color goldColor { get; set; } = Color.FromHex("#CAA440");
    public static Color lightGreenColor { get; set; } = Color.FromHex("#28A745");
    public static Color darkRedColor { get; set; } = Color.FromHex("#F0373A");
}

Xaml :
<StackLayout BackgroundColor="{x:Static local:Theme.grayColor}"></StackLayout>

Don't forget to add local reference in xaml:
xmlns:local="clr-namespace:YourprojectNameSpace"

===================================Update====================================
If want to change color with binding property by viewmodel , have a try with IValueConverter:
public class StringToColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string valueAsString = value.ToString();
        switch (valueAsString)
        {
            case (""):
                {
                    return Color.Default;
                }
            case ("Accent"):
                {
                    return Color.Accent;
                }
            default:
                {
                    return Color.FromHex(value.ToString());
                }
        }
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return null;
    }
}

Config.cs should be modified as follow:
public class Config : INotifyPropertyChanged
{
    private string mycolor;

    public string MyColor
    {
        get { return mycolor; }
        set
        {
            mycolor = value;
            OnPropertyChanged("MyColor");
        }
    }

    public Config (){
        mycolor = "#00FF00"; // can set a defalut color here
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

And in Xaml :
<ContentPage.Resources>
   <ResourceDictionary>
        <local:StringToColorConverter x:Key="StringToColorConverter"/>
   </ResourceDictionary>
</ContentPage.Resources>

<StackLayout BackgroundColor="{Binding MyColor, Converter={StaticResource StringToColorConverter}}"></StackLayout>

Finally , ContentPage need to bind Model Config.cs:
public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
        Config config = new Config();
        this.BindingContext = config;

        //MyColor can be modified runtime
          config.MyColor = "#00FF00";
    }
}


text:
Q: PHP: is there difference between Index, Element, Key, Value of an Array?... are they the same thing? When dealing with PHP arrays, I quite often here terms such as:
Array Key,
Array Index,
Array Element,
Array Value
Can someone, PLEASE , in simple terms explain what each of these basically means?
Is there any difference?... are they all referring to the same thing?
Where do you use which? and when?
Any clarification with some simple use case examples will be highly appreciated.
i.e: in an array like: array($a,$b,$c,$d=>$e) What will be What?
Thanks in advance.

A: An array is a collection of Elements.
Every element has key & value. Key can be a integer(index) or a string.
In you case
array($a, $b, $c, $d=>$e)
can be rewritten as
array(0 => $a, 1 => $b, 2 => $c, $d => $e);

Where 0, 1, 2, $d are the keys of the array.
You can refer 0, 1, 2 as a  index for value $a,$b,$c respectively and $d is a key for $e.
.

A: Key == Index, Element == Value

A: That would be:
array(
    0  => $a, // index: 0, value : $a
    1  => $b, // index: 1, value : $b
    2  => $c, // index: 2, value : $c
    $d => $e  // index: $d, value : $e
)

A: In my experience most PHP documentation uses the key => value configuration, while index: element is more common in JavaScript and jQuery.
PHP docs:
http://us2.php.net/manual/en/language.types.array.php
JavaScript Docs (Mozilla):
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
They both apply to the same concept where objects in an array have an index or key, and subsidiary objects, elements or values attached to that key.


text:
Q: Date Conversion in SQL I have a date in following format in my DB.
10/16 - mm/yy
I need to convert it to:
October/16
Is this possible?
If it's not possible then please tell me why.

A: This is not a date, it's missing the day, it's a bad way to store year/month. There should be a 4 digit year to avoid confusion and the year should be listed first to enable correct sorting, e.g. '2016/10' or a numeric value 201610.
You can cast it to a DATE first and then use a FORMAT to disply only month/year:
set dateformat myd;
select format(cast(mystupidcolumn + '/1' as date), 'MMMM/yy')

Or SUBSTR the month part and use a CASE.

A: Yes you can, and it depend in what database you use to call date functions
If you column Datetime format

*

*SQL server DATENAME(Month, GETDATE())

*MySQL database MONTHNAME(now())
otherwise
 convert it will in your choice at database or you code logic
   split the value and lookup at month enum or fake the date to be accepted and complete date format like 01/10/16
so do something like SELECT  DATENAME(Month, datecolumn) + '/' + YEAR (datecolumn)
also you can use instead of Year function DATEPART(yy,datecolumn)
the way you do it with format will look like
CONVERT(VARCHAR(11),GETDATE(),106)
but excepted to get first 3 char of month JUN

A: try this format,
SELECT DATENAME(month, DATEADD(month, @mydate-1, CAST('2008-01-01' AS datetime)))

A: You can display date by using this code
select datename(month, YourColumnName) + '/' + right(YEAR(YourColumnName),2)
FROM   yourTableName

Simply change yourColumnName with name of your table column and yourTableName with name of table.


text:
Q: How to define XAML sample data for [] properties I'm trying to use XAML sample data where my 'item' class uses a form of dynamic properties by defining a property accessor for [].  It (PremiseObject) does so like this:
...
/// <summary>
/// Property accessor. Simulates a dynamic object.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public object this[string name] {
    get {
        PremiseProperty prop;
        if (_properties.TryGetValue(name, out prop))
            return prop.Value;

        // In XAML <Button Content="Trigger" Command="{Binding [TriggerCommand]}">
        // where 'Trigger' is the name of hte property that is momentary
        if (name.EndsWith("Command")) {
            string cmd = name.Substring(0, name.Length - "Command".Length);
            if (_properties.TryGetValue(cmd, out prop)) {
                return new PremiseCommand(this, cmd);
            }
        }

        return null;
    }
    set {
        SetMember(name, value);
    }
}
...

Never mind the goop in the middle. The key thing is that in my XAML I can do cool stuff like this:
<ListBox x:Name="DoorsListBox" Margin="0,0,-12,0"
         ItemsSource="{Binding Items}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal" Margin="0,0,0,35">
                <StackPanel>
                    <!-- We use Description instead of DisplayName because DisplayName changes for GDOs. -->
                    <TextBlock TextAlignment="Left" TextWrapping="NoWrap" Width="320"
                               Text="{Binding [Description]}" Style="{StaticResource PhoneTextTitle2Style}"
                                />
                    <TextBlock TextAlignment="Left" TextWrapping="NoWrap" Width="320"
                               Text="{Binding [GarageDoorStatus], Converter={StaticResource GDOStateFormatConverter}}"
                               Style="{StaticResource PhoneTextSubtleStyle}"

                               Foreground="{Binding [GarageDoorStatus], Converter={StaticResource GDOStateColorConverter}}"/>
                </StackPanel>
                <Button DataContext="{Binding}"
                        Content="Trigger"
                        IsEnabled="True"
                        Style="{StaticResource GDOButtonStyle}"
                        Command="{Binding [TriggerCommand]}">
                </Button>

            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

I'm super happy with the way this works. I've tried several forms of dynamic objects and until I've hit THIS problem, it's been working fantastic.
THIS problem is I have no idea how to specify sample XAML data for this.
<vm:GarageDoorsViewModel
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:vm="clr-namespace:PremiseWP.ViewModels"
    xmlns:prem="clr-namespace:PremiseWebClient"
    IsDataLoaded="False">

    <vm:GarageDoorsViewModel.Items>
        <prem:PremiseObject *** SOMETHING GOES HERE ***/>
    </vm:GarageDoorsViewModel.Items>

</vm:GarageDoorsViewModel>

I need some syntax for specifying the sample data that says "this is a dynamic property with this name and this value".
How would I do this? Is it even possible?

A: I'm not sure but I guess you need set ContentPropertyAttribute for your class. And than put your values to content of tag.
<vm:GarageDoorsViewModel.Items>
    <prem:PremiseObject>
        <object x:Key="key"/>
    </prem:PremiseObject>
</vm:GarageDoorsViewModel.Items>


text:
Q: Extra long braces with \begin{array}[t] the following is a snippet of a lecture note I am typing.
\[ \mathscr F=\left\{\{B_{\a}\}_{\a\in J}: \begin{array}[t]{rl}
            i)  &   B_{\a} \text{ are open}\\
            ii) &   \{B_{\a}\} \text{ is finitely inadequate}\\
            iii)&   I \subset J \text{ and } A_{\a}=B_{\a} \text{ whenever } \a\in I
        \end{array}\right\} \]

where \a is a macro for \alpha. This is producing the following output.

How to curb those extra-long top ends of the braces?

A: Here are two alternatives to your current setup:

*

*Put the construction inside another array.

*Use cases instead and a different layout.

\documentclass{article}

\usepackage{amsmath,mathrsfs}

\begin{document}

\[
  \mathscr F = \left\{
    \begin{array}{@{} l @{}}
      \{B_{\alpha}\}_{\alpha\in J}:
        \begin{array}[t]{r @{~} l}
          \textit{i})   &  B_{\alpha} \text{ are open}\\
          \textit{ii})  &  \{B_{\alpha}\} \text{ is finitely inadequate}\\
          \textit{iii}) &  I \subset J \text{ and } A_{\alpha}=B_{\alpha} \text{ whenever } \alpha\in I
        \end{array}
    \end{array}
  \right\}
\]

\[
  \mathscr F =
    \{B_{\alpha}\}_{\alpha\in J}:
    \begin{cases}
      \textit{i})   &  B_{\alpha} \text{ are open}\\
      \textit{ii})  &  \{B_{\alpha}\} \text{ is finitely inadequate}\\
      \textit{iii}) &  I \subset J \text{ and } A_{\alpha}=B_{\alpha} \text{ whenever } \alpha\in I
    \end{cases}
\]

\end{document}

A: I propose two other variants, built upon  Bmatrix , \parbox and an inline enumerate environment:
\documentclass{article}

\usepackage{amsmath,mathrsfs}
\usepackage[inline]{enumitem}

\begin{document}

\[
  \mathscr F =
    \begin{Bmatrix}
      \{B_{\alpha}\}_{\alpha\in J}:\:
        \parbox{75mm}{%
        \begin{enumerate*}[label =$ \roman*) $, itemjoin ={; \enspace}]
          \item $ B_{\alpha} $ are open
          \item $ \{B_{\alpha}\} $ is finitely inadequate
          \item$ I \subset J $ and $ A_{\alpha}=B_{\alpha} $ whenever $ \alpha\in I $.
        \end{enumerate*}}
    \end{Bmatrix}
 \]

\[
  \mathscr F =
    \begin{Bmatrix}
      \{B_{\alpha}\}_{\alpha\in J}:\;
        \parbox[t]{75mm}{%
        \begin{enumerate*}[label =$ \roman*) $, itemjoin ={; \enspace}]
          \item $ B_{\alpha} $ are open
          \item $ \{B_{\alpha}\} $ is finitely inadequate
          \item$ I \subset J $ and $ A_{\alpha}=B_{\alpha} $ whenever $\alpha\in I$.
        \end{enumerate*}}
    \end{Bmatrix}
 \]

\end{document}


text:
Q: Firestore Error: java.util.UnknownFormatConversionException: Conversion = 'F' When trying to use firebase admin on a java application, I received this error:
Exception in thread "main" com.google.cloud.firestore.FirestoreException: java.util.UnknownFormatConversionException: Conversion = 'F'
    at com.google.cloud.firestore.FirestoreException.networkException(FirestoreException.java:89)
    at com.google.cloud.firestore.FirestoreOptions$DefaultFirestoreRpcFactory.create(FirestoreOptions.java:92)
    at com.google.cloud.firestore.FirestoreOptions$DefaultFirestoreRpcFactory.create(FirestoreOptions.java:82)
    at com.google.cloud.ServiceOptions.getRpc(ServiceOptions.java:561)
    at com.google.cloud.firestore.FirestoreOptions.getFirestoreRpc(FirestoreOptions.java:385)
    at com.google.cloud.firestore.FirestoreImpl.<init>(FirestoreImpl.java:67)
    at com.google.cloud.firestore.FirestoreOptions$DefaultFirestoreFactory.create(FirestoreOptions.java:73)
    at com.google.cloud.firestore.FirestoreOptions$DefaultFirestoreFactory.create(FirestoreOptions.java:66)
    at com.google.cloud.ServiceOptions.getService(ServiceOptions.java:541)
    at firebase.Firebase.initialize(Firebase.java:30)
    at launch.Main.main(Main.java:33)
Caused by: java.io.IOException: java.util.UnknownFormatConversionException: Conversion = 'F'
    at com.google.cloud.firestore.spi.v1.GrpcFirestoreRpc.<init>(GrpcFirestoreRpc.java:137)
    at com.google.cloud.firestore.FirestoreOptions$DefaultFirestoreRpcFactory.create(FirestoreOptions.java:90)
    ... 9 more
Caused by: java.util.UnknownFormatConversionException: Conversion = 'F'
    at java.base/java.util.Formatter$FormatSpecifier.conversion(Formatter.java:2839)
    at java.base/java.util.Formatter$FormatSpecifier.<init>(Formatter.java:2865)
    at java.base/java.util.Formatter.parse(Formatter.java:2713)
    at java.base/java.util.Formatter.format(Formatter.java:2655)
    at java.base/java.util.Formatter.format(Formatter.java:2609)
    at java.base/java.lang.String.format(String.java:3292)
    at com.google.api.pathtemplate.ValidationException.message(ValidationException.java:91)
    at com.google.api.pathtemplate.ValidationException.<init>(ValidationException.java:86)
    at com.google.api.pathtemplate.PathTemplate.encodeUrl(PathTemplate.java:1093)
    at com.google.api.pathtemplate.PathTemplate.instantiate(PathTemplate.java:775)
    at com.google.api.pathtemplate.PathTemplate.instantiate(PathTemplate.java:702)
    at com.google.api.pathtemplate.PathTemplate.instantiate(PathTemplate.java:711)
    at com.google.firestore.v1.DatabaseRootName.toString(DatabaseRootName.java:122)
    at com.google.cloud.firestore.spi.v1.GrpcFirestoreRpc.<init>(GrpcFirestoreRpc.java:116)
    ... 10 more

For reference, here is the source:
package firebase;

import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.firestore.Firestore;
import com.google.cloud.firestore.FirestoreOptions;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class Firebase {
    private static boolean initialized = false;
    static Firestore db;

    static public void initialize() throws IOException {
        if(initialized)
            return;

        FirestoreOptions options = FirestoreOptions.getDefaultInstance().toBuilder()
                .setCredentials(GoogleCredentials.fromStream(new ByteArrayInputStream(System.getenv("firebase").getBytes(StandardCharsets.UTF_8))))
                .build();

        System.out.println(options.getCredentials());
        System.out.println(System.getenv("firebase"));

        db = options.getService();

        initialized = true;

        return;
    }
}

The System.getenv("firebase") prints the following:
{   "type": "service_account",   "project_id": "<PROJECT_ID>",   "private_key_id": "<PRIVATE_KEY_ID>",   "private_key": "-----BEGIN PRIVATE KEY----- xxxxxx -----END PRIVATE KEY-----\n",   "client_email": "xxxxxxxxx",   "client_id": "xxxxxxxxxxxxx",   "auth_uri": "https://accounts.google.com/o/oauth2/auth",   "token_uri": "https://oauth2.googleapis.com/token",   "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",   "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-s16j9%40xxxxxxx.iam.gserviceaccount.com" }

Even with the unobscured version, I could only find the % character once: at the end before the 4.
The options.getCredentials() prints what appears to be the correct data, so I think the issue has to do with an error accessing firebase.
I've already tried replacing the firebase key. Thank you for any help.


text:
Q: Is there a git personal server for sharing changes between machines? Is there a way to run a no frills git server just so I work on different machines at home?
The main reason for this is that my WiFi network is slow and I'd prefer to work locally and disconnected.
I assume there's something similar to the Mercurial command hg serve.

A: There's a minimalist git daemon server. (See here for basic info, and the man page for more.)

A: A good guide to the different methods is http://www.jedi.be/blog/2009/05/06/8-ways-to-share-your-git-repository/
My preferred method is to use the plain ssh server.

A: the easiest way is just to share disks/directories using the stand OS file sharing.
Otherwise you can run a git server git-daemon or export via http see Git documentation for public repository

A: As per the comments, this is an XY Problem.
Mat's answer tells you about a minimalist git daemon server. As do others.
I'm telling you that this is probably entirely unnecessary.
If your laptop and your desktop can share a filesystem (such as via NFS, CIFS or similar), you can clone the repository like this:
git clone /path/to/repository

If your laptop and your desktop can't share a filesystem but your desktop is running an SSH service, you can clone your repository like this:
git clone ssh://[user@]server/path/to/repository

You may even be able to use other sharing services such as FTP or HTTP, as per the manual page. Setting up a dedicated git server is usually an unnecessary overhead.
Hope this helps.

A: I am using gitolite, I find it easy enough.
Here is the Official documentation and my experience.


text:
Q: NSFileSize what Entity? I have a method which gives me the fileSize of a directory.
I looked up in the Documentation but it's not declared which entity NSFileSize has.

A: in NSFileManager doc:

NSFileSize
The key in a file attribute dictionary whose value
indicates the file's size in bytes. The corresponding value is an
NSNumber object containing an unsigned long long. Important If the
file has a resource fork, the returned value does not include the size
of the resource fork. Available in iOS 2.0 and later. Declared in
NSFileManager.h.

A: NSFileSize is a key in attribute dictionaries as returned by NSFileManager's attributesOfItemAtPath:error:. The object is an NSNumber from which you can get the POD value using unsignedLongLongValue.
You don't get NSFileSize for dictionaries. What method do you mean?

A: I solved it myself, thanks to the hint that a directory has no FileSize.
Here is my completed Code:
-(float)getSizeOfDirectory:(NSString *)directory{

    NSFileManager *filemgr;
    NSArray *filelist;
    int count;
    float cacheSize = 0;

    filemgr =[NSFileManager defaultManager];
    filelist = [filemgr contentsOfDirectoryAtPath:directory error:NULL];
    count = [filelist count];

    for (NSString *url in filelist) {
        NSData *data = [filemgr contentsAtPath:[NSString stringWithFormat:@"%@/%@",directory,url]];
        cacheSize = cacheSize + ([data length]/1000);
    }

    cacheSize = (cacheSize/1024);
    NSLog(@"cacheSize: %f MB",cacheSize);

    return cacheSize;
}


text:
Q: Design editor is unavailable Gradle sync failed: Could not create parent directory for lock file C:\Program Files\Android\Android Studio\gradle-6.3-all\gradle-6.3\wrapper\dists\gradle-5.6.4-all\ankdp27end7byghfw1q2sw75f\gradle-5.6.4-all.zip.lck
            Consult IDE log for more details (Help | Show Log) (1 s 119 ms)


text:
Q: How to calculate combinations of multiple variables which can assume multiple values I have 3 variables (A,B,C); each variable can assume 3 different values (1,2,3) .
I want to calculate ho many combinations there are which follow this rule:
let's fix A1, then cycle on all the others variables which can assume 3 values each; then let's move on to A2 and calculate again all the combinations by cycling over the 2 remaining variables (which can assume 3 values each); same thing for A3. Once I am done with A I repeat the same process with B and so on. The constrain is that the combinations must repeat only once over all:
in fact if I fix A1 and the combination I get is (A1 B3 C2 ), then when I fix for example B3 I must not count (A1 B3 C2) because it has been already found before.
So what I need is the mathematical formula that allows me to do this calculation with a generic number of variables which can assume a generic number of values

A: For clarification, I am assuming we are keeping it as an ordered pair (A,B,C) for whatever ABC happens to be.  (I.e. we are never concerned about a permutation of the letters such as (B,A,C))
You have 3 choices for the result of A, three choices for the result of B, and 3 choices for the result of C.  By multiplication principle it is then $3\cdot 3\cdot 3 = 3^3=27$.
In general, if you have $r$ variables, each of which can take $n$ values, (I.e. we have letters $(A_1, A_2,\dots, A_r)$ each of which can be any number from $\{1,2,\dots,n\}$, there will be $n\cdot n\cdots n = n^r$ total possibilities.
Even more generally, if you have $r$ variables, the $i^{th}$ of which can take on $n_i$ values, you will have $\prod\limits_{i=1}^r n_i$ number of possibilities.
For a simple example, you go to an icecream shop and would like to get a sundae.  A sundae consists of one flavor of icecream and any combination of toppings you'd like (some, all, or none).  If there are five flavors of icecream and four available toppings, how many different ice cream sundaes are possible?  Break it up via multiplication principle to first ask the question how many flavors of icecream there are (flavor 1, flavor 2,...).  Then to ask the question if you use the first topping (yes or no), yes or no to the second topping, yes or no to the third...
This is exactly the same problem as how many possibilities exist for (A,B,C,D,E) if $A\in\{1,2,3,4,5\}$, and each of B through E are either 1 or 2.  If for example, B is 1, then don't use that topping.
There are then $5\cdot 2\cdot 2\cdot 2\cdot 2=80$ possible sundaes.


text:
Q: Bootstrap 5/Flex: complex responsive menu I want a responsive menu which should always look like the image below. Overflown content shall simply add a scrollbar:

My current solution works until content is added:

Fixed height

                Fixed width

                Responsive Col 1

                Responsive Col 2

with added content it looks like this:

Is it possible to preserve the height as in image 1, and simply to add overflow-y: auto? I don't manage to get it work.

A: Yes it is possible, you just need to add specific height or max-height to that element and than add overflow-y:auto;
For example:

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

.random_content {
  background-color:red;
  width:400px;
  max-height:100px;
  overflow-y:auto;
}

JSfiddle example: https://jsfiddle.net/zL86q1th/

A: Specify your height of you container and then add the overflow on the children for the the right media query:
.flex-grow-1{
  height: calc(100vh - 30px);
}
@media only screen and (max-width: 1199px){
  .flex-grow-1 > .col-12 {
    height: 50%;
    overflow-y: auto;
  }
}

DEMO

.flex-grow-1{
  height: calc(100vh - 30px);
}
@media only screen and (max-width: 1199px){
  .flex-grow-1 > .col-12 {
    height: 50%;
    overflow-y: auto;
  }
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

Fixed height

              Fixed width

              Responsive Col 1
              Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas tincidunt, est quis dapibus consequat, nisi dui semper tortor, ut aliquet risus ipsum in leo. Phasellus lectus quam, sodales at ultrices vel, dignissim tristique sapien. Quisque eget tortor suscipit neque pharetra hendrerit in luctus leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris at consequat neque. Mauris sit amet ante nibh. Integer lobortis purus ut tristique fringilla. Nullam eget justo ligula. Vivamus ornare lorem fringilla aliquet laoreet. Duis ultricies, metus et porta suscipit, nunc mauris vulputate mi, in placerat lectus massa a nulla. Proin vulputate convallis dolor ultrices porta. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Curabitur tempor viverra felis vitae pharetra. Praesent consequat nulla arcu, non scelerisque orci egestas at.

Nullam volutpat tortor a ante maximus elementum. Integer interdum lectus enim, eu tempus nisl eleifend at. Donec vitae ornare ipsum, vitae rutrum mauris. Vivamus ornare, leo id malesuada sollicitudin, leo augue convallis nisi, ut porta risus tortor eget urna. Morbi laoreet, eros a sodales blandit, nulla lacus tempor felis, ac fringilla odio enim vel arcu. Nullam pellentesque nisi eu turpis sollicitudin lacinia. Donec ac dui non mauris laoreet pharetra ac eget mauris.

Pellentesque tincidunt tortor id sagittis egestas. Donec tincidunt dolor vitae lacus faucibus, sit amet dignissim ligula convallis. Ut bibendum massa quis malesuada auctor. Phasellus semper, mi ut maximus vestibulum, lacus leo facilisis elit, non ornare ex elit et sem. Fusce a felis ante. Ut elementum tempor lobortis. Morbi interdum eleifend enim. Nam pellentesque diam sit amet justo pellentesque placerat. Donec gravida, lorem at ullamcorper egestas, lectus purus posuere lacus, eget tincidunt quam orci id nisl. Morbi eleifend pretium orci in pulvinar.

Aenean eleifend eget dolor aliquam mollis. Nam lorem turpis, condimentum at nibh eu, scelerisque placerat enim. Integer porttitor risus nisl, porttitor imperdiet elit congue nec. Cras semper est tortor, sed feugiat massa interdum vel. Ut urna enim, rutrum non sem vitae, vulputate elementum nibh. Pellentesque quis pharetra risus. Proin nec bibendum sapien. Maecenas mi erat, pulvinar blandit libero id, posuere malesuada mauris.

              Responsive Col 2
              Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas tincidunt, est quis dapibus consequat, nisi dui semper tortor, ut aliquet risus ipsum in leo. Phasellus lectus quam, sodales at ultrices vel, dignissim tristique sapien. Quisque eget tortor suscipit neque pharetra hendrerit in luctus leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris at consequat neque. Mauris sit amet ante nibh. Integer lobortis purus ut tristique fringilla. Nullam eget justo ligula. Vivamus ornare lorem fringilla aliquet laoreet. Duis ultricies, metus et porta suscipit, nunc mauris vulputate mi, in placerat lectus massa a nulla. Proin vulputate convallis dolor ultrices porta. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Curabitur tempor viverra felis vitae pharetra. Praesent consequat nulla arcu, non scelerisque orci egestas at.

Nullam volutpat tortor a ante maximus elementum. Integer interdum lectus enim, eu tempus nisl eleifend at. Donec vitae ornare ipsum, vitae rutrum mauris. Vivamus ornare, leo id malesuada sollicitudin, leo augue convallis nisi, ut porta risus tortor eget urna. Morbi laoreet, eros a sodales blandit, nulla lacus tempor felis, ac fringilla odio enim vel arcu. Nullam pellentesque nisi eu turpis sollicitudin lacinia. Donec ac dui non mauris laoreet pharetra ac eget mauris.

Pellentesque tincidunt tortor id sagittis egestas. Donec tincidunt dolor vitae lacus faucibus, sit amet dignissim ligula convallis. Ut bibendum massa quis malesuada auctor. Phasellus semper, mi ut maximus vestibulum, lacus leo facilisis elit, non ornare ex elit et sem. Fusce a felis ante. Ut elementum tempor lobortis. Morbi interdum eleifend enim. Nam pellentesque diam sit amet justo pellentesque placerat. Donec gravida, lorem at ullamcorper egestas, lectus purus posuere lacus, eget tincidunt quam orci id nisl. Morbi eleifend pretium orci in pulvinar.

Aenean eleifend eget dolor aliquam mollis. Nam lorem turpis, condimentum at nibh eu, scelerisque placerat enim. Integer porttitor risus nisl, porttitor imperdiet elit congue nec. Cras semper est tortor, sed feugiat massa interdum vel. Ut urna enim, rutrum non sem vitae, vulputate elementum nibh. Pellentesque quis pharetra risus. Proin nec bibendum sapien. Maecenas mi erat, pulvinar blandit libero id, posuere malesuada mauris.


text:
Q: Consumer producer pattern where producer waits for all consumers to complete before retriggering itself? I'm trying to figure out the best approach in Java in this case (any version) to implement a single producer multiple consumer where I use ExecutorService (by preference, not need) where the producer needs to run "forever" but each time it runs, it needs to wait for everything to be fully processed, e.g. all consumer threads have terminated, the queue is empty and no items are left to be produced. The producer should only poll its data source at a fixed interval as well.
So as an example: every 30 minutes I want my producer to poll its data source for records and submit them to the queue. If the consumers are taking more than 30 minutes to process, I want the producer to wait until all the items have been processed before polling its data source again (which it would do so immediately since 30 minutes had elapsed).
Not looking for someone to write my code for me. Some basic hints/guidance would be really appreciated.
Here is a shortened example implementation I'm trying to work from. I've taken out all of my horrible attempts at solving the problem. Note that the hard coded parameters for constructing the ThreadPoolExecutor will eventually be dynamic.
import java.util.concurrent.*;
public class ItemProcessorService {
    public static void main(String args[]) throws InterruptedException {
        RejectedExecutionHandlerImpl rejectionHandler = new RejectedExecutionHandlerImpl();
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        int corePoolSize = 5,
                maxPoolSize = 10,
                keepAlive = 10,
                queueCapacity = 1;
        ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAlive, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(queueCapacity), threadFactory, rejectionHandler);

        for (int i = 0; i < 10; i++) {
            executor.execute(new ItemConsumer());
        }
        executor.shutdown();
        while (!executor.isTerminated()) {
        }
        System.out.println("Executor finished");
    }
}

class ItemConsumer implements Runnable {
    @Override
    public void run() {
        processItem();
    }

    private void processItem() {
        try {
            Thread.sleep(3000);
            System.out.println(Thread.currentThread().getName() + " - processed item");
        } catch (InterruptedException e) {
            //e.printStackTrace();
        }
    }
}

class RejectedExecutionHandlerImpl implements RejectedExecutionHandler {

    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
        System.out.println(r.toString() + " - rejected");
    }
}

A: Go for thread pool executor with future tasks. It will make your poducer wait before all the threads are completed. Below is the example:
 for (int job = 0; job < yourList.size(); job++) {
        Future<String[]> future = Service.getCompletionService().take();

        if (future.isDone()) {
        }
    }

A: Use a self-scheduling producer (see also here) combined with a CountDownLatch. I know you do not need the code, but I think in this case it does not hurt to have some code to experiment with:
import java.util.*;
import java.util.concurrent.*;

public class WaitForConsumers {

public static void main(String[] args) {

    try {
        new WaitForConsumers().demo();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static final int NUMBER_OF_SLEEP_TASKS = 100;

public void demo() throws Exception {

    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    Producer p = new Producer(scheduler, 1000L);
    p.start();
    try {
        Thread.sleep(3000);
        p.stop();
        System.out.println("Stopped.");
    } finally {
        scheduler.shutdownNow();
    }
}

public static List<Long> produce() {
    List<Long> items = new ArrayList<Long>();
    for (int i = 0; i < NUMBER_OF_SLEEP_TASKS; i++) items.add(i * 1L);
    return items;
}

public static void consume(List<Runnable> tasks, CountDownLatch consumersRunning) throws Exception {

    ExecutorService executor = Executors.newCachedThreadPool();
    for (Runnable r : tasks) executor.execute(r);
    try {
        consumersRunning.await();
    } finally {
        executor.shutdownNow();
    }
}

class Producer implements Runnable {

    ScheduledExecutorService scheduler;
    long frequencyMs;
    volatile boolean stop;
    ScheduledFuture<?> producerTask;

    Producer(ScheduledExecutorService scheduler, long frequencyMs) {
        this.scheduler = scheduler;
        this.frequencyMs = frequencyMs;
    }

    void start() {
        scheduler.execute(this);
    }

    void stop() {

        System.out.println("Stopping producer.");
        stop = true;
        if (producerTask != null) {
            producerTask.cancel(true);
        }
    }

    @Override public void run() {

        long startTime = System.currentTimeMillis();
        List<Long> items = produce();
        CountDownLatch consumersRunning = new CountDownLatch(items.size());
        List<Runnable> tasks = wrap(items, consumersRunning);
        try {
            System.out.println("Consuming " + tasks.size() + " tasks.");
            consume(tasks, consumersRunning);
            System.out.println("Consumed tasks.");
        } catch (Exception e) {
            e.printStackTrace();
            stop = true;
        } finally {
            if (stop) {
                System.out.println("Producer stopping.");
            } else {
                long waitTime = frequencyMs - (System.currentTimeMillis() - startTime);
                if (waitTime < 1L) {
                    scheduler.execute(this);
                } else {
                    System.out.println("Next run in " + waitTime + " ms.");
                    producerTask = scheduler.schedule(this, waitTime, TimeUnit.MILLISECONDS);
                }
            }
        }
    }

    List<Runnable> wrap(List<Long> items, final CountDownLatch consumersRunning) {

        List<Runnable> tasks = new ArrayList<Runnable>();
        for (Long l : items) {
            tasks.add(new SleepTask(l, consumersRunning));
        }
        return tasks;
    }
} // class Producer

class SleepTask implements Runnable {

    long sleepTime;
    CountDownLatch consumersRunning;

    public SleepTask(long sleepTime, CountDownLatch consumersRunning) {
        this.sleepTime = sleepTime;
        this.consumersRunning = consumersRunning;
    }

    @Override public void run() {

        try {
            Thread.sleep(sleepTime);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            consumersRunning.countDown();
        }
    }
} // class SleepTask
}

A: You can solve this problem nicely by creating an ExecutorService for every run of the producer. The producer creates it, shuts it down, and also waits for its termination.
For scheduling the producer, use either ScheduledExecutorService.scheduleWithFixedDelay(...) or ScheduledExecutorService.scheduleAtFixedRate(...), depending on what you want:

*

*scheduleWithFixedDelay(...) will keep the specified amount of time between two runs, so no matter how long a run lasts, the next will follow after the specified amount of time:
...|XXXXXX|.............|XXXXX|.............|XXXXXXXXX|.............|X
            <--- fix --->       <--- fix --->           <--- fix --->

*scheduleAtFixedRate(...) tries to keep the scheduling rate, so if a producer needs longer, the time between two runs will be reduced, but two runs will never overlap:
...|XXXXXXXX|...|XXXXX|......|XXXXXXXXXXXXXXX||XXX|....|XX
    <--- fix ---><--- fix ---><--- fix ---><--- fix ---><-
Simple example of how the producer may look like:
public class Producer implements Runnable {
    public void run() {
        ExecutorService executor = ... // create new executor

        // queue items
        for (Object item : itemSource) {
            executor.schedule(new Consumer(item));
        }

        // shutdown executor
        executor.shutdown();
        executor.awaitTermination(2, TimeUnit.HOURS);
    }
}

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

scheduler.scheduleWithFixedDelay(new Producer(), 30, 30, TimeUnit.MINUTES);
// or
scheduler.scheduleAtFixedRate(new Producer(), 30, 30, TimeUnit.MINUTES);

Of course you will have to do proper exception handling as every exception in a producer run that is not caught, will stop the scheduler from re-scheduling it.
Please note that creating an executor might be expensive, so this approach is only appropriate, if consuming the items is far more expensive than creating the executor (which, in your situation - seems to be the case).


text:
Q: Running installed python module directly from terminal I've just installed the tvrenamr module by running the following command:
pip install tvrenamr

No, when I try to use it by running it from terminal as specified here in the documentation:https://tvrenamr.readthedocs.org/en/latest/usage.html
I get the following error:
No command 'tvr' found, did you mean:
 Command 'tr' from package 'coreutils' (main)
 Command 'tar' from package 'tar' (main)
 Command 'tv' from package 'treeviewx' (universe)
 Command 'tdr' from package 'devtodo' (universe)
 Command 'tor' from package 'tor' (universe)
tvr: command not found

Please help me understand why the module is not running from the terminal and how to run it.
Edit: After uninstalling and reinstalling it, I got the following message:
Downloading/unpacking tvrenamr
  Downloading tvrenamr-3.6.2-py2.py3-none-any.whl (384kB): 384kB downloaded
Installing collected packages: tvrenamr
Compiling /tmp/pip-build-yZsRKH/tvrenamr/tvrenamr/vendor/yaml/__init__.py ...
  File "/tmp/pip-build-yZsRKH/tvrenamr/tvrenamr/vendor/yaml/__init__.py", line 284
    class YAMLObject(metaclass=YAMLObjectMetaclass):
                              ^
SyntaxError: invalid syntax

Successfully installed tvrenamr
Cleaning up...

A: It appears that you need to import tvrenamr.

A: Running Python from a terminal
you should be able to run from the terminal with
machine:user$ python tvr file


text: Q: iOS GET Request with a cookie I'm trying to send an HTTP GET request in order to load some data, and I'm only now realizing that it is completely different than a POST request. I am not entirely sure how I am supposed to construct the entire GET request. Additionally, I am being troubled because I need to add a cookie containing a string that is a user's session ID to the GET request.


text:
Q: How to update tick position depending on whether it's negative/positive in d3js v3 I have this (SOLVED) bar chart where I would like to update the position of the y-ticks when the data is updated from positive to negative and vice versa.
I've tried to update the .tick class in the update function and the filter
.filter(function(d, i) { return data[i]['value' + TEAM] < 0; });

and other various methods to update the position but I get nothing back.
Any help would be appreciated.

A: I found the solution myself, the problem was that the ticks that got adjusted in the filter function
.filter(function(d, i) { return data[i]['value' + TEAM] < 0; });

only adjusted the ticks that were less than 0, my updated filter
.filter(function(d, i){ if (data[i]['value' + TEAM] > 0)
{return true;}else if (data[i]['value' + TEAM] < 0){return true;}});

makes sure that all ticks gets included.
After that i just update the appended text & line in the update function like so
    tickPosNeg.select("line").transition().duration(600)
        .attr("x2",function(d, i){ if (data[i]['value' + TEAM] > 0)
{return -10;}else if (data[i]['value' + TEAM] < 0){return 10;}});

    tickPosNeg.select("text").transition().duration(600)
        .attr("x", function(d, i){ if (data[i]['value' + TEAM] > 0)
{return -25;}else if (data[i]['value' + TEAM] < 0){return 10;}});

If anyone has a better solution, feel free to still post your answer!
Here's the updated link


text:
Q: Twillio reply to message I have this code:
require dirname(__FILE__)."/twilio/services/Twilio.php";
$client = new Services_Twilio($option['twilioAccountSid'], $option['twilioAuthToken']);

$client->account->sms_messages->create($option['twilioFrom'],
    $to,
    'Will you attend?',
    array('StatusCallback'=>'http://domain.com/callback.php'));

callback.php:
file_put_contents('/twilio.log', print_r(array($_REQUEST), true) . PHP_EOL );

The scenario is the following. I send the message "Will you attend?" $to +155555555. When they reply back, I want to insert that answer into a database.
I thought that callback.php will be called when they reply with a message, and I'll have the variable $_REQUEST['body'] with their answer, along with other variables, but that's not the case. In twilio.log I have only a confirmation that I sent the message.
How to I grab the response message into a php file for latter use with a database?

A: No, its working the way its supposed to. The callback doesn't have anything to do with the user responding to the SMS, its Twilio's response to processing your outgoing message.
One solution for you might be to use cookies if you need to essential track a conversation.
https://www.twilio.com/docs/quickstart/php/sms/tracking-conversations
On the other hand, if the only communication you expect to get back is either a yes or no, having the calling number and the reply maybe enough for you, even without using cookies.

A: https://www.twilio.com/user/account/phone-numbers/ Select the number you use. Look next to Messaging for Request URL . There you have to put your callback and it will work.


text:
Q: JPA persist foreign key restriction violation I have a problem with persisting new objects to the database. I'm using Eclipselink and Postgresql. When I'm trying to add a new Merchandise, cascade adds also Price object.
Price.java
@Entity
@Table(name = "Prices")
public class Price implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(updatable = false)
private int id;
@Column(updatable = false, nullable = false)
private float value;
@Column(updatable = false, nullable = false)
private Date startDate;
@Column(updatable = false, nullable = true)
private Date endDate;
@ManyToOne(targetEntity=Merchandise.class,cascade=CascadeType.ALL)
@JoinColumn(name="id",nullable = false,updatable = false,insertable=false)
private Merchandise merchandiseId;
@Column(updatable = false, nullable = true)
private float valueBulk;
@Column(updatable = false, nullable = true)
private float valueRetail;
@Column(updatable = false, nullable = true)
private float makeupPercent;
@Column(updatable = false, nullable = true)
private float makeupForce;

Merchandise.java
@Entity
@Table(name="Merchandises")
public class Merchandise implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(updatable = false)
private int id;
@Column(updatable = false)
private int externalId;
@Column(unique = false, nullable = false, updatable = true)
private String name;
@Column(unique = false, nullable = true, updatable = true)
private int available;
@Column(unique = false, nullable = true, updatable = true)
private String description;
@OneToMany(targetEntity = Price.class, mappedBy = "merchandiseId",cascade = CascadeType.PERSIST)
private List<Price> prices;
@OneToMany(targetEntity = MerchandiseCategory.class, mappedBy = "merchandiseId",cascade = CascadeType.PERSIST)
private List<MerchandiseCategory> merchandiseCategories;
@OneToMany(targetEntity = MerchandiseOrder.class, mappedBy = "merchandiseId",cascade=CascadeType.PERSIST)
private List<MerchandiseOrder> merchandiseOrders;
@OneToMany(targetEntity = MerchandiseDiscount.class, mappedBy = "merchandiseId",cascade=CascadeType.PERSIST) //#61
private List<MerchandiseDiscount> discounts; //#61

my code in facede looks like this:
Dao dao = new DAO();//begins transaction etc.
Merchandise m = new Merchandise;
m.set..//setting all needed fields
List<Price> list = new ArrayList<Price>();
Price p = new Price();
p.set..//setting all needed fields
p.setMerchandiseID(m);
list.add(p);
m.setPrices(list);
dao.addMerchandise(m);//persisting

This gets mean error (in Polish base so I'll try to translate it): foreign key restriction violation - Key (id)=(356) is not present in merchandises.
I think this is problem with generating id, id fiels is always replaced by generated id, and i think they are different, but in this case should be the same

A: Your Price class uses its "id" field as the as the foreign key to Merchandise.  You have also marked the ID attribute mapping to be generated, so it will always be different than what is in Merchandise.  Did you intend Price to use its foreign key to Merchandise as the primary key?  If so, you need to remove the @GeneratedValue from Price and either
1) need to persist Merchandise first, flush so that its primary key is assigned, and then set the value into p.setId() as well as calling p.setMerchandiseID(m).
or
2) use JPA 2.0's derived ID capability and mark Price's merchandiseId attribute as either @Id (and remove the int id as it isn't needed), or use @MapsId.  @Mapsid will allow JPA to set the id value from Merchandise automatically when it is assigned a value.
Some info: http://wiki.eclipse.org/EclipseLink/Examples/JPA/2.0/DerivedIdentifiers
http://wiki.eclipse.org/EclipseLink/Development/JPA_2.0/mappedbyid
If you meant for Price to have its own independent primary key, you need to add a foreign key in the price table:
@ManyToOne(targetEntity=Merchandise.class,cascade=CascadeType.ALL)
@JoinColumn(name="fk_merchandiseid",nullable = false)
private Merchandise merchandiseId;


text:
Q: Splitting Arrays- is my implementation correct? I'm writing code for a hybrid data structure for school, and am debugging the code.  Basically, this structure is a combination of a Double Linked List and an Array, where each list node contains an array of set size.  Since this is an ordered structure, a provision has to be made to identify and split full arrays into equally into two nodes.
This is my code for splitting a node into two and then copying the latter half of the parent node's array values to the child node.
public Chunk<E> split(Chunk<E> node) {
  Chunk<E> newChunk= new Chunk<E>();
  newChunk.index= node.index++;

  //connect to previous node
  node.next= newChunk.next;
  newChunk.prev= node.prev;

  //connect to next node
  newChunk.next= node.next.next;
  node.next.prev= newChunk.prev;

  //adds the latter half of the array contents to the new node
  //and erases the same contents from the old node
  for (int i=chunkSize/2; i<node.numUsed; i++) {
   newChunk.items[i-chunkSize/2]= node.items[i];
   node.items[i]=null;
  }

  //update capacity counter for both chunks
  node.numUsed=chunkSize/2;
  newChunk.numUsed= chunkSize/2;

  return newChunk;

}

The toArray() method is returning null values from the list, so I think something is going on with this split method.
Questions I have are:

*Are the linking of the new node to the rest of the list correct?

*Is the the nulling of values inside the loop responsible for the null printout?

A: To answer this question thoroughly you should write some unit tests. For example:
package so3898131;

import static org.junit.Assert.*;

import org.junit.Test;

public class ChunkTest {

  /** Ensure that the simplest possible case works as expected. */
  @Test
  public void testEmptySplit() {
    Chunk<Object> old = new Chunk<Object>();
    Chunk<Object> split = old.split(old);
    assertEquals(0, split.chunkSize);
    assertEquals(0, split.items.length);
    assertEquals(0, split.index);
    assertEquals(1, old.index);
  }

  @Test
  public void testSplitWithOneItem() {
    // TODO: make sure that after splitting one of the chunks contains
    // one element, the other none.
  }

  @Test
  public void testSplitWithTwoItems() {
    // TODO: make sure that after splitting a chunk with two elements
    // each of the new chunks contains exactly one of the elements.
    // Use assertSame(..., ...) to check it.
  }
}

This throws NullPointerExceptions at me because node.next may be null, in which case you cannot access node.next.next. This probably means that your code does not work. At least it does not work as I expect it.
Update: Your code is not correct. I wrote a unit test like this:
@Test
public void testSplitLinkage() {
  Chunk<Object> old = new Chunk<Object>();
  assertNull(old.prev);
  assertNull(old.next);

  Chunk<Object> split = old.split(old);

  assertNull(old.prev);
  assertSame(split, old.next);
  assertSame(old, split.prev);
  assertNull(split.next);
}

And then I modified the code so that this test runs successfully. I had to replace some lines with:
// connect to previous and next node
Chunk<E> one = node, two = newChunk, three = node.next;
one.next = two;
two.prev = one;
two.next = three;
if (three != null)
  three.prev = two;

A: A better question would be: "How can I isolate (track down) the location of a bug in the source code by debugging?"
First you'll want to have a way to reproduce the problem. It appears you already have that. In a non-trivial code base, you will then want to do a binary search for the problem. Having two points A and B in program execution, where the program is in valid state in A, but not in B, choose a point C between A and B and check whether everything is correct at C. If it is, the bug is between C and B, else between A and C. Recurse until you have it narrowed down into a very small part of the code, where it is usually quite obvious.
This leaves the question of how verify whether execution was correct so far. There are various ways to do that, but it is probably most instructive to execute the program in a debugger, use a break point to suspend execution, and check that the variables contain the expected values.


text:
Q: Работа со строкой в С++ Как можно сделать следующее в С++? Ввожу первое слово, например "Help", затем второе, например "Lost" и чтобы он с заданной части слов уделяй их и потом склеивал их. Например у меня было "HelLo"? Склеивание я знаю как сделать, с помощью "strcat". Поможете как сделать такое?
A: string::erase
string::append
string::operator+=
string::replace

Еще можно здесь посмотреть
Если нужно использовать С-строки, то список функций можно увидеть здесь или в любом справочнике/учебнике по С или С++


text:
Q: My dynamic design doesn't appear. Why? My design doesnt appear in my screen. The method addHeaderAttendance() contains the header while the addSchedule(ArrayList mysched) contains the populating of table of my data.
ScheduleProf.java:
public class ScheduleProf extends Activity{
    String data = "";
    TableLayout tl;
    TableRow tr;
    TextView label;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_schedprof);
        tl = (TableLayout) findViewById(R.id.maintable);
        final BackgroundWorker bw = new BackgroundWorker(ScheduleProf.this,"ScheduleProf");
        Bundle get=getIntent().getExtras();

        final int profid=get.getInt("id"); //kunin ni schedpof from fragment
        new Thread(new Runnable() {
            public void run() {
                data = bw.getProfSched(profid);
                System.out.println(data);

                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        addHeaderAttendance();
                        ArrayList<Properties> mysched = parseSchedule(data);
                        addSchedule(mysched);
                    }

                });
            }
        }).start();
    }
public ArrayList<Properties> parseSchedule(String result) {

        ArrayList<Properties> mysched = new ArrayList<Properties>();
        try {
            JSONArray jArray = new JSONArray(result);
            for (int i = 0; i < jArray.length(); i++) {
                JSONObject json_data = jArray.getJSONObject(i);
                Properties user = new Properties();
                user.setRoom(json_data.getString("rooms_id"));
                user.setCourse(json_data.getString("course_id"));
                user.setSection(json_data.getString("sections_id"));

                DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
                String formatstart_time=json_data.getString("start_time");
                String formatend_time=json_data.getString("end_time");

                try {
                    Time startValue = new Time(formatter.parse(formatstart_time).getTime());
                     Time endValue = new Time(formatter.parse(formatend_time).getTime());
                     user.setStartTime(startValue);//error
                        user.setStartTime(endValue);//error
                        user.setDay("day");
                        mysched.add(user);
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }
        return mysched;
    }
@SuppressWarnings({ "rawtypes" })
public void addSchedule(ArrayList<Properties> mysched) {

    addHeaderAttendance();

    for (Iterator i = mysched.iterator(); i.hasNext();) {

        Properties p = (Properties) i.next();

        /** Create a TableRow dynamically **/
        tr = new TableRow(this);

        /** Creating a TextView to add to the row **/
        label = new TextView(this);
        label.setText(p.getStartTime() +"-"+p.getEndTime()+"
"+p.getDay());

        label.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        label.setPadding(10, 10, 10, 10);
        label.setBackgroundColor(Color.YELLOW);
        LinearLayout Ll = new LinearLayout(this);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT);
        params.setMargins(5, 2, 2, 2);
        //Ll.setPadding(10, 5, 5, 5);
        Ll.addView(label,params);
        tr.addView((View)Ll); // Adding textView to tablerow.

        TextView stats = new TextView(this);
        stats.setText(p.getCourseId()+" "+p.getSection()+" "+p.getRoom());
        stats.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        stats.setPadding(10, 10, 10, 10);
        stats.setBackgroundColor(Color.GREEN);
        Ll = new LinearLayout(this);
        params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT);
        params.setMargins(0, 2, 2, 2);
        //Ll.setPadding(10, 5, 5, 5);
        Ll.addView(stats,params);
        tr.addView((View)Ll); // Adding textview to tablerow.

         // Add the TableRow to the TableLayout
        tl.addView(tr, new TableLayout.LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
    }
}

void addHeaderAttendance(){

    /** Create a TableRow dynamically **/
    tr = new TableRow(this);
    /** Creating a TextView to add to the row **/
    label = new TextView(this);
    label.setText("Time and Day");
    label.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT));
    label.setPadding(10, 10, 10, 10);
    label.setBackgroundColor(Color.parseColor("#FFD700"));
    LinearLayout Ll = new LinearLayout(this);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
            LayoutParams.WRAP_CONTENT);
    params.setMargins(5, 5, 5, 5);
    //Ll.setPadding(10, 5, 5, 5);
    Ll.addView(label,params);
    tr.addView((View)Ll); // Adding textView to tablerow.

    /** Creating Qty Button **/
    TextView place = new TextView(this);
    place.setText("Course/Section/Room");
    place.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT));
    place.setPadding(10, 10, 10, 10);
    place.setBackgroundColor(Color.parseColor("#008000"));
    Ll = new LinearLayout(this);
    params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
            LayoutParams.WRAP_CONTENT);
    params.setMargins(5, 5, 5, 5);
    //Ll.setPadding(10, 5, 5, 5);
    Ll.addView(place,params);
    tr.addView((View)Ll); // Adding textview to tablerow.

     // Add the TableRow to the TableLayout
    tl.addView(tr, new TableLayout.LayoutParams(
            LayoutParams.FILL_PARENT,
            LayoutParams.WRAP_CONTENT));
}
}

This is my activity_schedprof.xml containing the maintable for dynamic population of data from my java class:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
        <TableLayout
            android:id="@+id/maintable"
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:stretchColumns="1,1,1" >
        </TableLayout>
</RelativeLayout>

A: try to add Tablelayout height like match_parent or some fixed size...


text:
Q: Why can't I import AAC files downloaded with youtube-dl into iTunes? When I download a song with youtube-dl into AAC, then I cannot import it into iTunes. iTunes doesn't give an error. It just ignores it.
youtube-dl -x --audio-format aac https://www.youtube.com/watch?v=abc123 --verbose

[download] 100% of 5.88MiB in 00:03
[debug] ffmpeg command line: ffprobe -show_streams "file:xxxxxx.webm"
[ffmpeg] Destination: xxxxxxxx-xxxxxxxxx.aac
[debug] ffmpeg command line: ffmpeg -y -loglevel "repeat+info" -i "file:xxxxxxxxxxxx.webm" -vn -acodec aac "-q:a" 5 -f adts "file:xxxxxxxx.aac"
Deleting original file xxxxxxxxxxxx.webm (pass -k to keep)

ffprobe xxxxxxxxxxxx.aac

[aac @ 0000006501ace3c0] Estimating duration from bitrate, this may be inaccurate
Input #0, aac, from 'xxxxxxxxx.aac':
  Duration: 00:12:39.84, bitrate: 249 kb/s
    Stream #0:0: Audio: aac (LC), 48000 Hz, stereo, fltp, 249 kb/s

It works with m4a.
iTunes Version 12.9.4.102

@nohillside Yes it happens with all AAC files I try to download with youtuble-dl. Yes it does work if I use mp3 also. Yes I am using Windows.
@slm I don't have any original AAC files to test with. All AAC files have been generated with ffmpeg/youtube-dl. I found this sample AAC file from http://samplephotovideo.com/2015/12/download-aac-mpeg-2-advanced-audio-coding-file/, http://cdn.online-convert.com/example-file/audio/example.aac, and was unable to import it into iTunes. Drag & Drop shows a red-circle-crossed and File > Add File to Library just ignores it.


text:
Q: Not sure how to solve... Solve for
$$ z= x+iy $$
$$ 5z+iz^*=9z-3iz^*+6i $$
where $z^*$ is $z$ conjugate.  I don't really understand what the problem here is asking for and am thoroughly confused as this is not covered in my materials. I have tried to just plug in the $z$ into the question and got
$$ 5x+5iy+ix+y=9x+9iy-3ix-3y+6i $$
but wasn't sure what to solve for...
edit: I tried to go further by only doing the reals alone and imaginaries by themselves
$$ 5x+y=9x-3y $$
and
$$ 5iy+ix=9iy-3ix+6i $$
Now I'm actually stuck and im not sure how to solve from here.
So I ended up using substitution to solve and i got that there is no solution.


text:
Q: Javascript appendChild if div not exists i've working in a big project, and that i want is
if div 1 not contain div 2 child{

div1.appendChild(div2)

}

But, i'm getting problem to solve this
My code
<script>
dc = document.createElement("div");
dc.className = "doctor_card doctor-"+o+" hidden";
dcc.appendChild(dc);
</script>

Thanks for advice :)

A: Try this:
<script>
var className = "doctor_card doctor-"+o+" hidden";

if (dcc.getElementsByClassName(className).length == 0) {
    dc = document.createElement("div");
    dc.className = className;
    dcc.appendChild(dc);
}
</script>

A: var dcc = document.getElementsByClassName('parentclass')[0];
if (!dcc.contains(dc)) {
 dcc.appendChild(dc);
}

You can use above code if u really want to use pure javascript.