text:
Q: clickble dropdown responsive with js im having trouble with the js in this code. I have 2 clickble dropdowns, but only one of them (the first dropdown) is working. I dont know how to fix it.
here's the html part:

<button type="button" class="btn-hamburger" data-action="nav-toggle">

</button>

עמוד ראשי

עיסויים

רפואי
שוודי
רקמות עמוקות
ניקוז לימפטי
אבנים חמות

טיפולי פנים

קלאסי
יופי
אקנה
פילינג
מיצוק
פיגמנטציה
אנטי אייג׳ינג

מזותרפיה

מיקרובליידינג

הזמינו תור

צרו קשר

and here's the js part:
let nav = document.querySelector('nav');
let dropdown = nav.querySelector('.dropdown');
let dropdownToggle = nav.querySelector("[data-action='dropdown-toggle']");
let navToggle = nav.querySelector("[data-action='nav-toggle']");

dropdownToggle.addEventListener('click', () => {
if (dropdown.classList.contains('show')) {
dropdown.classList.remove('show');
} else {
dropdown.classList.add('show');
}
})

navToggle.addEventListener('click', () => {
if (nav.classList.contains('opened')) {
nav.classList.remove('opened');
} else {
nav.classList.add('opened');
}
})

what should I do from here? I know the problem ia in the js but I dont know how to keep going from here, im stuck.

A: In your code, you are using the querySelector method to select a single .dropdown element, which is why only the first dropdown is working.
You need to use the querySelectorAll method instead, which will return a list of all elements that match the given selector. You can then loop through this list and add the click event listener to each dropdown menu.
let nav = document.querySelector('nav');
let dropdowns = nav.querySelectorAll('.dropdown');
let dropdownToggles = nav.querySelectorAll("[data-action='dropdown-toggle']");
let navToggle = nav.querySelector("[data-action='nav-toggle']");

dropdownToggles.forEach(function(toggle, index) {
  toggle.addEventListener('click', function() {
    let dropdown = dropdowns[index];
    if (dropdown.classList.contains('show')) {
      dropdown.classList.remove('show');
    } else {
      dropdown.classList.add('show');
    }
  });
});

navToggle.addEventListener('click', () => {
  if (nav.classList.contains('opened')) {
    nav.classList.remove('opened');
  } else {
    nav.classList.add('opened');
  }
});

A: Problem is here
let dropdown = nav.querySelector('.dropdown');

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
querySelector() returns only first element that matches the specified selector!
Thats why only one dropdown works.
You should use
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
And loop through every element to add event listener to them - just like you did in your code.


text:
Q: how to Preview a file content in java? I want to display a list of paths of multiples files and when a user click on selected path,the file of that path should be opened and display the content of the file (preview a file).so how do this on java???anyone know any idea?
help me please.
and I want do display the list of files like the search in windows (command +F).so i want to display the files in same form of displayed files in search in windows
which component in java do this form?

A: You can open a file with the (operating system) default application using the Desktop class, for example:
Desktop.getDesktop().open(new File("somewhere/xyz.pdf"));

If you want to very safe, you can do this:
if (Desktop.isDesktopSupported() && Desktop.isSupported(Desktop.Action.OPEN)) {
    Desktop.getDesktop().open(new File("somewhere/xyz.pdf"));
}

Opening various filetypes yourself would be a huge thing, requiring a huge amount of libraries, so I don't recommend it (unless you want to specify which file types you want to preview a little bit more exactly).

redpajama_set_name: RedPajamaStackExchange


text:
Q: JPA/Glassfish 3.0.1 java.lang.IllegalStateException: During synchronization My class model contains a class that has relationship tagged with annotations. I took care to use them correctly by adding the famous "cascade=cascadeType.PERSIST". Sometimes it works, but, very often not, I get this error message :
"java.lang.IllegalStateException: During synchronization a new object was found through a relationship that was not marked cascade PERSIST: Model.Donation[id=null]."
I found on several web sites that comes from the library but without more explication...
Thank you for your help
@OneToOne(optional=true, cascade=CascadeType.ALL)
private Localisation localisation;
@ManyToOne(cascade=CascadeType.ALL)
private Device device;
@ManyToOne(cascade=CascadeType.ALL)
private Project project;

A: As my relationships are bi-directional, I though I only need to set cascadeType to the relationship that manages the relation. But it isn't. By adding cascadeType.ALL to the both sides, it works perfectly!


text:
Q: SharePoint modern view formatting with JSON: URL returns void I'm trying to format a List in SharePoint modern view.
When clicking on the the URL "Bekijk recept" I get a javascript:void(0); instead of opening the URL.

Here you can see some of the code:
"elmType": "a",
        "txtContent": "Bekijk recept",
        "style": {
          "border": "none",
          "padding-top": "32px",
          "background-color": "transparent",
          "color": "#0078d7",
          "padding-left": "0px",
          "text-align": "left",
          "cursor": "pointer"
        },
        "attributes": {
          "target": "_blank",
          "href": "[$Linkrecept]"

[$Linkrecept] refers to a hyperlink column.
Any ideas why this doesn't work? How can I make the navigation work?

A: Based on MS Document at here, Column formatting Supports for static hyperlinks that do not launch script.
You may need to use Field Customizer with SPFx that Supports for any hyperlink, including those that invoke custom script

A: I can see that there is no error in your code. Few thinks to check:

*

*Make sure you are using correct internal name of your hyperlink field at [$Linkrecept].

*Make sure there is value in your hyperlink field. If field is blank then it will show a link as javascript:void(0);.

Workaround for 2nd case is to make your hyperlink field required OR you can set the default URL in your code if hyperlink column is blank.
Sample code:
{
    "$schema": "https://developer.microsoft.com/json-schemas/sp/view-formatting.schema.json",
    "rowFormatter":{
        "elmType": "div",
            "children": [
            {
                "elmType": "a",
                "txtContent": "Click here",
                "attributes": {
                    "target": "_blank",
                    "href": "[$HyperlinkCol]"
                }
            }
        ]
    }
}

Workaround if hyperlink field is empty - Set default redirection link:
{
    "$schema": "https://developer.microsoft.com/json-schemas/sp/view-formatting.schema.json",
    "rowFormatter":{
        "elmType": "div",
            "children": [
            {
                "elmType": "a",
                "txtContent": "Click here",
                "attributes": {
                    "target": "_blank",
                    "href": "=if([$HyperlinkCol], [$HyperlinkCol], 'https://sharepoint.stackexchange.com/')"
                }
            }
        ]
    }
}

Microsoft documentation: Use view formatting to customize SharePoint


text:
Q: Why so many FeatureDetector and DescriptorExtractor are not supported in OpenCV Contrib Repo 3.0.0? I just compiled the OpenCV 3.0.0 with extra modules from the contrib repo release.
Many Feature Detector and Descriptor Extractor are commented out as below:

I remember they are included in OpenCV 2.4.10. Why they are removed?

A: most of them exist
some of the trasferred to xfeatures2d module
https://github.com/Itseez/opencv_contrib/tree/master/modules/xfeatures2d


text:
Q: Using OpenX to serve text links that search engines can see? I am currently using OpenX to serve rotating text links. However, the invocation code is javascript so I don't think search engines can spider these links. Is there another solution or a way to modify OpenX to serve links that search engines can index. An example ad is here http://www.glumbo.com/ad.html

A: There is what's called a "Local Mode Tag" invocation type in the self-hosted version of OpenX which it looks like you are using. However, this requires the ad server to be on the same physical host as the website. However even if this works (I've not used it, so I can't speak for how it works), or if you use the JS or iframe invocations, then the URL OpenX will generate for the link still won't be direct (it'll redirect via the ad server) otherwise you'll have no way to track the number of clicks on a link.
Finally, it's against Google's rules to sell "search friendly" links on a website, and you could be penalised in search results if Google catches you selling links in that way. So if the aim of this is to sell Google friendly links I would advise against it anyway. Good luck!


text:
Q: Apache Logfile full of 'wp-login.php' not found or unable to stat because is not WP site the server has no sites with WP and I am aware of what those lines in the log files mean, so in order to reduce requests to wp-login.php as soon as possible the question is: let the server respond with 404 as does it currently or is it better to give a 202 answer with a fake wp-login.php?
Thank you all.

A: Presenting a fake WordPress login page will only increase the number of requests further because the vulnerability scan scripts will then run through their collection of WordPress attacks against the pretended WordPress site. One possible countermeasure is to deploy fail2ban in order to temporarily block IP addresses that cause an excessive number of 404s.

A: fail2ban as suggested by Tilman is a good one. Using a blacklist of known hackers/malware ip adresses is another good one.
What i always do is set a servername on the virtualhosts for all sites and have a default block all. Normal people connect by hostname, hackers/scanners connect by ip (since they most likely scan ip ranges and don't know your hostname). This will stop 90% of the attacks. See Have apache return 403 for everything that isn't a virtual host


text:
Q: Como usar el permiso "Draw over othre apps" para obtener esta informacion quería saber como hacen las aplicaciones como pokegenie o calcy iv para obtener datos del pokemon go, he buscado por google y noo encuentro como hacerlo, solo que tengo que usar el "Draw over other apps"

La idea es desde una app con un botón flotante siempre delante del juego, poder extraer el CP, el nivel de la barra blanca(arco blanco), el nombre del pokémon y las barras naranjas.


text:
Q: Can't install Perl DBD module on Ubuntu (for Bugzilla) Trying to install bugzilla-4.2.2 on Ubuntu 12.04. When I run checksetup.pl I get the following error:
YOU MUST RUN ONE OF THE FOLLOWING COMMANDS (depending on which database
you use):

PostgreSQL: /usr/bin/perl install-module.pl DBD::Pg
MySQL: /usr/bin/perl install-module.pl DBD::mysql
SQLite: /usr/bin/perl install-module.pl DBD::SQLite
Oracle: /usr/bin/perl install-module.pl DBD::Oracle

To attempt an automatic install of every required and optional module
with one command, do:

/usr/bin/perl install-module.pl --all

I have installed MySQL via XAMPP so I run:
/urs/bin/perl install-module.pl DBD::mysql

And get the following error:
perl Makefile.PL --testuser=username

Can't exec "mysql_config": No such file or directory at Makefile.PL line 479.
Can't find mysql_config. Use --mysql_config option to specify where mysql_config is located
Can't exec "mysql_config": No such file or directory at Makefile.PL line 479.
Can't find mysql_config. Use --mysql_config option to specify where mysql_config is located
Can't exec "mysql_config": No such file or directory at Makefile.PL line 479.
Can't find mysql_config. Use --mysql_config option to specify where mysql_config is located
Failed to determine directory of mysql.h. Use

perl Makefile.PL --cflags=-I<dir>

to set this directory. For details see the INSTALL.html file,
section "C Compiler flags" or type

perl Makefile.PL --help
Warning: No success on command[/usr/bin/perl Makefile.PL  LIB="/opt/lampp/htdocs/bugzilla/4.2.2/bugzilla-4.2.2/lib" INSTALLMAN1DIR="/opt/lampp/htdocs/bugzilla/4.2.2/bugzilla-4.2.2/lib/man/man1" INSTALLMAN3DIR="/opt/lampp/htdocs/bugzilla/4.2.2/bugzilla-4.2.2/lib/man/man3" INSTALLBIN="/opt/lampp/htdocs/bugzilla/4.2.2/bugzilla-4.2.2/lib/bin" INSTALLSCRIPT="/opt/lampp/htdocs/bugzilla/4.2.2/bugzilla-4.2.2/lib/bin" INSTALLDIRS=perl]
CAPTTOFU/DBD-mysql-4.021.tar.gz
/usr/bin/perl Makefile.PL  LIB="/opt/lampp/htdocs/bugzilla/4.2.2/bugzilla-4.2.2/lib" INSTALLMAN1DIR="/opt/lampp/htdocs/bugzilla/4.2.2/bugzilla-4.2.2/lib/man/man1" INSTALLMAN3DIR="/opt/lampp/htdocs/bugzilla/4.2.2/bugzilla-4.2.2/lib/man/man3" INSTALLBIN="/opt/lampp/htdocs/bugzilla/4.2.2/bugzilla-4.2.2/lib/bin" INSTALLSCRIPT="/opt/lampp/htdocs/bugzilla/4.2.2/bugzilla-4.2.2/lib/bin" INSTALLDIRS=perl -- NOT OK
Skipping test because of notest pragma
Running make install
Make had some problems, won't install
Could not read metadata file. Falling back to other methods to determine prerequisites

So then I tried checksetup.pl's suggestion and ran:
/usr/bin/perl install-module.pl --all

And it seems to have installed DBD::SQLite without any problems, but again I see a warning that says it's skipping tests because of notest pragma.
When I re-run checksetup.pl It shows 3 of the 4 original DB drivers in the "not found" list:
PostgreSQL: /usr/bin/perl install-module.pl DBD::Pg
MySQL: /usr/bin/perl install-module.pl DBD::mysql
Oracle: /usr/bin/perl install-module.pl DBD::Oracle

So running it with --all seems to have installed the SQLite driver without any problems, but for some reason I can't seem to install the MySQL driver. Again I need MySQL because thats what XAMPP uses and because I prefer MySQL regardless. I have a feeling it has something to do with this notest pragma error. Any ideas? Thanks in advance!

A: Why not just install Bugzilla 4 from a PPA and save yourself a whole lot of trouble?

A: I know it sounds possibly stupid to say, but as I just did this myself, it probably deserves a mention here.
If you get an error saying that make (or anything else that obviously should be available) isn't isn't available in the repos, and you're on a fresh install, make sure you have run sudo apt-get update. I did a fresh install an hour ago and was installing bugzilla and hadn't restarted or run apt-get update and freaked out when I didn't see make available.. ran apt-get update, then ran sudo apt-get install make and it installed no problems.
Hope this helps the sidetracked/forgetful people like me out there.


text:
Q: Java parsing last part of a string I have three strings.
0:0:0-0:0:1
0:0:0-3:0:0-1:2:0
0:0:0-3:0:0-3:2:0-3:2:1

I am trying to do an exercise where I am parsing the string to output only the last part after the -, i.e. respectively:
0:0:1
1:2:0
3:2:1

I have tried of doing it by getting all the characters from the end of the string up until -5, but that won't always work (if the numbers are more then 1 integer). lastStateVisited is my string
lastStateVisited = lastStateVisited.substring(lastStateVisited.length() - 5);

I thought of splitting the string in an array and getting the last element of the array, but it seems inefficient.
String[] result = lastStateVisited.split("[-]");
lastStateVisited = result[result.length - 1];

What is a way I could do this? Thanks

A: Try this:
String l = "your-string";
int temp = l.lastIndexOf('-');
String lastPart = l.substring(temp+1);

A: Since your requirement concentrate around your need of acquiring the sub-string from the end till - appears first time.
So why not first get the index of last - that appeared in string. And after than extract the sub-string from here till end. Good option. :)
String str = "0:0:0-3:0:0-3:2:0-3:2:1";
String reqStr = str.substring(str.lastIndexOf('-')+1);

reqStr contains the required string. You can use loop with this part of code to extract more such strings.


text:
Q: Best rational approximation in a special sense Let $\alpha$ be an irrational number, $n\geq 1$ and
$ X_n=\lbrace (x,y) \in {\mathbb Z}^2 | |y| \leq n, \ x+y\alpha >0 \rbrace$
Now let $(x_n,y_n)$ minimize the quantity $x+y\alpha$ on $X_n$. This
pair is unique because $\alpha$ is irrational.
  Now the problem is to deduce all the "location" of $\alpha$ from
the three integers $n,x_n$ and $y_n$ only.
The two simplest cases are :
$x_n=0,y_n=1$. This is equivalent to $0 < \alpha < \frac{1}{n+1}$.
$x_n=1,y_n=-2$. This is equivalent to $\frac{1}{2}-\frac{1}{2m} < \alpha
< \frac{1}{2}$ (where $m$ is the smallest odd integer $>n$).
More generally, it seems that for any triple $(n,x,y)$, the set $Y(n,x,y)$
of all irrationals $\alpha$ yielding $x_n=x,y_n=y$, is either empty
or an interval $[A(n,x,y),B(n,x,y)] \setminus {\mathbb Q}$. Is that true,
and are there recursive formulas to compute $A(n,x,y)$ and $B(n,x,y)$ ?
This problem is certainly related to continued fractions and best approximations
in the usual sense, but I don't see how to make the connection effective.

A: The dots $\{ x+ y \alpha \colon |y|\leq n \}$ move continuously with $\alpha$, so we should consider when $x_n+y_n \alpha$ can stop being the smallest positive dot. First, note that $y_n = 0$ is impossible. We need $x_n+y_n \alpha > 0$, so that $\alpha > - x_n/y_n$ if $y > 0$ and $\alpha < -x_n /y_n$ if $y_n < 0$. At the other extreme, $x_n+y_n\alpha$ can lose its crown if two of the dots are equal $x_n+y_n \alpha = x' + y' \alpha$, i.e., if $\alpha$ is fraction with denominator at most $n-1$. Note that the minimizer really does change when we get equality since the slopes are different.
So, for $y_n > 0$, you get $A(n,x_n,y_n) = -x_n / y_n$ and $B(n,x_n,y_n)$ is the smallest fraction that is both larger than $-x_n/y_n$ and has a denominator less than $n$. If $y_n < 0$, then $B(n,x_n,y_n)= -x_n/y_n$ and $A(n,x_n,y_n)$ is the largest fraction that is both smaller than $-x_n/y_n$ and has denominator less than $n$.
Example: say $n=102, x_n=52, y_n = 37$. This happens if and only if $\alpha$ is in the interval $(-52/37, a/b)$, where $a/b$ is only slightly larger than -52/37 and $0 < b < 102$. To find $a,b$, we first translate -52/37 so that it lies in (0,1): it translates to 22/37. Now from the theory of Farey fractions, we know that the fraction after 22/37 (call it $c/d$) in $F_{101}$ satisfies $22d-37c=\pm 1$, and also $37+d > 101$. Solving this modulo 101 (cleverly chosen to be prime, so that the solutions are unique) gives $c/d=41/69$ or $c/d=82/69$ (which is clearly wrong, since $c/d<1$). Translating back gives $a/b=41/69-2=-97/69$. So the final conclusion is that $\alpha$ is in $(-52/37,-97/69)$.


text:
Q: Naming convention for Visual Studio solutions and projects We were thinking about organizing our BIG project this way:

\trunk
  [CompanyName]
    [Product1]
        [Project1]
          CompanyName.Product1.Project1.csproj
        [Project2]
          CompanyName.Product1.Project2.csproj
        CompanyName.Product1.sln
    [Product2]

We were trying to follow Microsoft's recommendation that namespace names follow folder structure, but are there any drawbacks for making it this way?
What is the naming convention for solutions and projects that you apply?

A: An alternative that I've used is to have all my solution files in the same directory.
\trunk
  [CompanyName]
    CompanyName.Product1.sln
    CompanyName.Product2.sln
    [Product1]
        [Project1]
          CompanyName.Product1.Project1.csproj
        [Project2]
          CompanyName.Product1.Project2.csproj
    [Product2]
        [Project3]
          CompanyName.Product2.Project3.csproj

A: With respect to file names - I prefer that my project file name match the output assembly name because it makes it much easier to know what produces what.  Doing a directory listing is much faster than searching the csproj files in a tree for the one that produces the assembly I care about.
I don't get worked up about solution files because they don't influence our build environment so I end up making my own to have the exact scope I want (and the specific per-solution items, like test metadata, that I want).
With respect to folder structure - I don't worry too much if the folders leading down the project files match the namespaces.  I want my code to sit on disk in a way that makes the most sense for the project.  Sometimes this means the test code and product code are in sibling directories - sometimes it means they are much further apart.  Sometimes there is a namespace that is contributed to by multiple teams (not advocating that design, just a reality) - but those teams want to life in their own folders for whatever reason.
Don't forget the importance of version control branching strategies in your overall project design.  The Company and Product boundaries may be branches and therefore would not necessarily need to represented as directories on disk.
Don't let this be a source of analysis paralysis though.  Make a reasonable choice.  Use version control.  You can always change later if you are wrong.

A: Looks like taken from the school book. That's usually how my solutions get set up, and I have found it to work quite well over the years.

A: Looks good to me.
It's a point to note that by default, the default namespace in a Visual Studio project is just the project name. Surely that indicates that naming your projects like your namespaces is "the Visual Studio Way".
Solutions are most naturally named after the product/project. Like you indicate.

A: That looks pretty good if you ask me. Especially naming your projects by their full name including full name space part.  I've found this helpful when there are numerous projects, especially if there happens to be similar projects across different products.
How and whether you split on product and project (where I assume project is more like an application than a solution project) is very much down to the size of your organisation, it's make-up and your preferences.

A: I consider this is better
\trunk
  [CompanyName]
    [Product1]
      CompanyName.Product1.sln
      [Main] --Optional
        CompanyName.Product1.csproj
      [Project1]
        CompanyName.Product1.Project1.csproj
      [Project2]
        CompanyName.Product1.Project2.csproj
    [Product2]
      CompanyName.Product2.sln
      [Main] --Optional
        CompanyName.Product2.csproj
      [Project1]
        CompanyName.Product2.Project3.csproj
      [Project2]
        CompanyName.Product2.Project2.csproj
      [Project3]
        CompanyName.Product2.Project2.csproj

Why? Because when you get the code from repository you get, by example, "Product1" directory, it contains all you need to work. The [Main] directory contains the default base namespace, usually the exe or main project. It is optional.

A: Downsides to naming projects / solutions with name spacing are that:
1. Your solution project will not build due to Windows ( my version and previous ) imposing a max limits on the length of path ( not a problem on <cough><cough> mac ).  Two solutions are:
 1. Changing an operating system setting.
 2. Configure build to shorten path.

2. Various apps important to you like say, SourceTree, may encounter problems.  I figure this is due to the assumption as to filepath length.   This problem is detailed in this Stack Overflow question:Filename too long in Git for Windows
Regarding Problem (1)
Visual Studio might warn you

I don't yet know how to enact (2).
If you choose (1), then this will have an affect on your downstream environments: build OS, dev OS, qa build OS, qa OS, production OS as you will either need to make changes to the OS. Stack overflow question with answer describing change to operating system: Could not write lines to file "obj\Debug\net5.0\SolutionName.GeneratedMSBuildEditorConfig.editorconfig exceeds the OS max path limit
Code MSB3491
https://www.google.com/search?q=Code+MSB3491+max+path+limit
Could not write lines to file "obj\Debug\net5.0\------------my namespace------------..GeneratedMSBuildEditorConfig.editorconfig". Path: obj\Debug\net5.0\------------my namespace------------.GeneratedMSBuildEditorConfig.editorconfig exceeds the OS max path limit. The fully qualified file name must be less than 260 characters.
-------------my namespace--------------------------------
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Roslyn\Microsoft.Managed.Core.targets

Regarding Problem (2)
To fix, possible solutions are:
(1) Tell SourceTree to use the git installed on the system.  I only had Atlassian's version of git with which to work.

(2) Tell Atlassian's git to work with long file paths.  Run cmd as administrator, then run this command:
c:\Users\{theuser}\AppData\Local\Atlassian\SourceTree\git_local\cmd\git.exe config --system core.longpaths true
If you choose either of these resolutions, then you should expect to make changes to systems / processes down the line from your development machine.


text:
Q: High Charts Column Chart - Y axis Label Formatting I am using high-charts column chart. Here is my chart options ( y axis portion ).
        yAxis: {
            allowDecimals: false,
            min: 0,
            max: 100,
            tickInterval: 25,
            title: {
                text: ''
            }
//                labels: {
//                    formatter: function () {
//
//                    }
//                }
        },

Currently, it is displaying y axis label from 0 to 100. But, I would like to append '%' symbol to only '0' and leave rest of the labels as is. I tried sing label formatter, couldn't figure which values to use. Can any one suggest me any idea ?
Thanks

A: You can try:
       labels: {
            formatter: function() {
                return this.value === 0 ? '0%' : this.value;
            }
        }

http://jsfiddle.net/6huhbqhj/

A: Figured it.
                 labels: {
                formatter: function () {
                    if (this.value == 0)
                        return this.value + "%";
                    else
                        return this.value;
                }
            }


text:
Q: Tracing Core Animation performance using instruments in Xcode 4.5 later I had been going through a iOS reference book. Its basically on iOS 5 and the author explained tracing the core animation performance using Instruments.

Problem is I'm not finding the Graphics option in the Xcode version 4.5.2. Could somebody tell me if I can measure the graphics performance in some other way?

A: Graphics profiling is only available (and, if you think about it) only makes sense on the device. Any frame rates you get on the simulator won't really mean anything in terms of device performance.


text:
Q: Find_in_set taking too much time in mysql query My Query performance is very very bad. It is taking around.
SELECT t1.from_state_id fromStateId,GROUP_CONCAT(t3.state_name) fromState
FROM tbl_vendor_workstations as t1
Left JOIN tbl_states as t3 ON find_in_set(t3.id,t1.from_state_id)
where t1.vendor_id=1717 and enterprise_user_id=703
group by t1.id

issue is in that function find_in_set(t3.id,t1.from_state_id)
Column t1.from_state_id: 1,2,3,4,5,...,45147 it contains 50,000 separated by comma


text:
Q: Max-Width Paragraph in Absolute Container I want a paragraph inside an absolutely positioned element to break the text at a specified max-width, but not fill the entire space if the content is smaller.

Text
Reference
    A long sentence that needs to have a line break.
.
Text
Reference
    Short

Text.

.cite {
    position: relative;
}
.cite .citeBox {
    position: absolute;
    max-width: 400px;
    left: 0;
    /*...*/
}

http://jsfiddle.net/8ebsLc6L/1/
That is, the Short-Box should only be small and the Big-Box should break at 400px. All boxes need to dynamically move with the reference span.
The current code does not expand the Big-Box to 400px.
The solution should not require Javascript.
Would much appreciate your help!

A: Here is one way of doing it.
Wrap your text in a span element, .citeWrap, and assign the background color, border-radius and so on. Note that you do not need the max-width property anymore.
For .citeBox, set width: 400px.
What will happen is that the .citeWrap will use the 400px as the working width to lay out the text and the line box will be no longer than 400px.
However, if the text is shorter than 400px, the span, being an inline element, will have a shrink-to-fit width, so you will get the background color just covering the text.

.cite {
    position: relative;
    color: blue;
}
.cite .citeBox {
    position: absolute;
    width: 400px;
    left: 0;
    bottom: 20px;
}
.cite .citeWrap {
    padding: 5px 15px;
    background-color: rgba(0, 0, 0, .6);
    border-radius: 5px;
    color: #fff;
    font-size: 1.2rem;
    display: inline-block;
}
p {
  margin-top: 4.0em; /* for demo only */
)

To visualize an algorithm, we don't merely fit data to a chart; there is no primary dataset. Instead there are logical rules that describe behavior. This may be why algorithm visualizations are so unusual, as designers experiment with novel forms to better communicate. Here is Brets wonderful
    ReferenceA long sentence that needs to have a line break. Make it a bit longer and you see multiple lines..
To visualize an algorithm, we don't merely fit data to a chart; there is no primary dataset. Instead there are logical rules that describe behavior. This may be why algorithm visualizations are so unusual, as designers experiment with
    ReferenceShort
 novel forms to better communicate. Here is Brets.

A: I believe it is not possible to achieve what you want by only modifying your CSS.
However, I think I managed it by adding another  element.
The problem here is that the width of .cite is passed down to its children.
But you can work around that by adding another element between them with
position: absolute;
with: 400px;

Such an element will be invisible by default, but it will catch mouse events, so you might want to prevent that, using
pointer-events: none;

From the most inner element, you can now remove the position, left and bottom attributes, but instead add
display: inline-block;

This is necessary in order to display the box as a block in case the text requires more than one line, but still keep it at the lowest width and height possible.
And you might want to re-enable pointer events on the most inner element too:
pointer-events: all;

All the above packed into a fiddle: http://jsfiddle.net/8ebsLc6L/4/


text:
Q: How to achieve common unit test logging best practices in jest/create-react-app? I'm experiment with the unit testing experience in a plain create-react-app (i.e. Jest) context. Let's assume I have tests like:
test('someTest', () => {
  // test something here...
  console.log("debug detail in some test")
  expect(true).toEqual(true);
});

test('someOtherTest', () => {
  // test something here...
  console.log("debug detail in some other test")
  expect(true).toEqual(false);
});

Running npm test results in a report like:

I find it very difficult to apply my TDD approaches from other languages with this kind of reporting. What I would like to achieve is a test reporting style like it is the standard in many other programming languages / ecosystems:

*

*I'd like a console.log statement to only use 1 line of vertical space, not 5 lines, without any magic indentation or decoration just like a normal print/echo in other languages. Having a log statement use up 5 lines is very impractical when having to console.log a bit more than a few lines.

*In other test ecosystems, it is standard to capture the output per test case, and only show the output of a failed test. This is extremely helpful, because test cases can actually be enriched with helpful debug output, which doesn't clutter the output at all on successful runs, but if a test fails, it immediately includes helpful information about its internals, which often helps to identify the failure cause right away. Jest does neither filter out successful console.log's nor does it show them in context of the failed test, which mainly turns them into a nuisance.

Can this be achieved with Jest, or am I facing a fundamental limitation?
If the limitation is console.log itself, is there some other way of "enriching tests with output to be displayed in case of a failure"?


text:
Q: Issue with Wordpress and Varnish breaking loadscript.php I've hit a snag with a Varnish - Nginx - Wordpress set up. The server is running multiple Joomla based sites (all fine) and should be running one Wordpress one too apart from it breaks with Varnish.
Basically when Varnish is enabled I get the following error:
Uncaught ReferenceError: _ is not defined on the Dashboard and various JQuery not defined errors elsewhere.
With Varnish off it all works perfectly. I'm scratching my head now as to where the issue lies with my Varnish set up. I can't find anything on the web that is a similar issue and any help would be appreciated!

A: I just stumbled on this issue today. You didn't post your configuration, but my guess is that you might be using querysort to normalize your query parameters.
I found that querysort really doesn't like the load-scripts.php URLs. In a lot of cases, it ends up truncating the URLs. If you're using it, I recommend either not using it or making a special condition for it like:
if (req.url !~ "load-scripts\.php") {
  set req.url = std.querysort(req.url);
}

A: Further to Carl's answer I found that stopping querysort for the whole wp-admin helped with this error within other plugins.
if (req.url !~ "wp-admin") {
  set req.url = std.querysort(req.url);
}


text:
Q: My iphone application crashes when i use table view - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *theCell=[UITableViewCell alloc];
     theCell=[theCell initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];

      NSLog(@"%i",[table count]);

         theCell.textLabel.text=[table objectAtIndex:[indexPath row]];

    return theCell;
}

There are three values inserted in a file Values.plist and they populate the NSArray "table" in the function viewDidLoad() but my application crashes at
" theCell.textLabel.text=[table objectAtIndex:[indexPath row]];  "
But the line "NSLog(@"%i",[table count]);" works and shows me 3
please help .

A: This is the standard implementation:
 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        static NSString *cellIdentifier = @"Cell";

        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }

       cell.textLabel.text = [table objectAtIndex:indexPath.row];
        return cell;
    }

As a side note this is the ARC implementation. If your not using ARC just add an  autoRelease:
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]autoRelease];

also make sure your dataSource numberOfSections is set right:
return 1;

and numberOfRows is set to the array:
return [table count];

A: Please take care of following issues:
1) Make sure that NSArray has values i.e it is populated.
2) Also try NSLog(@"%d",[table count]);
I think you should better go with %d and not %i.
Hope this helps you.


text:
Q: Forgetful functors from categories of algebra create limits? After Leinster states the following lemma (on p. 139):

Let $F:\mathscr A\to\mathscr B$ be a functor and $I$ a small category. Suppose that $\mathscr B$ has, and $F$ creates, limits of shape $I$. Then $\mathscr A$ has, and $F$ preserves, limits of shape $I$.

he gives a couple of remarks:

Since $\mathbf {Set}$ has all limits, it follows that all our categories of algebras have all
  limits, and that the forgetful functors preserve them.

First, how does the italicized part follow? If he deduces it from the lemma, then he should mention what functor he means in the italicized part. It is only later that he mentions the functor (the forgetful functor), which is a little confusing, but I'm assuming that he means the same functor when he deduces the italicized part from the lemma - is that right? If so, then is it supposed to be obvious that forgetful functors from categories of algebras always create limits?

Remark 5.3.7 There is something suspicious about Definition 5.3.5. It refers
  to equality of objects of a category, a relation that, as we saw on page 31,
  is usually too strict to be appropriate. It is almost always better to replace
  equality by isomorphism. If we replace equality by isomorphism throughout
  the definition of 'creates limits', we obtain a more healthy and inclusive notion.
In the notation of Definition 5.3.5, we ask that if F ◦ D has a limit then there
  exists a cone on D whose image under F is a limit cone, and that every such
  cone is itself a limit cone.
[... (omitted) ...]

How is the second paragraph related to the question of having equality insted of isomorphism in the definition of limit creation?


text:
Q: Name conflicts between tags as classes and Tumblr theme's style classes I can apply styles to different posts based on their "#tags" using {TagsAsClasses}:

div.tag {
    /* whatever styling */
}

This works fine, however if I already have a class in the theme with styling and then apply the tag with the same name as that class, the theme breaks. For example, the theme uses the class ".cover", and a post has the tag "#cover".
This would usually be fine because I would just change the class name, however I need to make sure that this same code works for about 65 students so I need to be able to define specific tags that the styling will affect.

A: To ensure there are no conflicts between your theme's styling classes and any post's tag classes, you could add a prefix to all of your tag classes.
For example, instead of using {TagsAsClasses}, you have:

The "Plaintext" prefix makes the theme variable {Tag} safe to include in HTML attributes.


text:
Q: How to do a get request to SpringBoot java with an Array>? I am doing a get request in angular with typescript and here it is:
this.http.get("http://localhost:8080/data-management/data-users/getAllGeneralInfoCV/"+this.listAllCharacteristicsToFind);

The attributte "listAllCharacteristicsToFind" is an Array<Array<string>>. For example, in this case, listAllCharacteristicsToFind[0] will be an array of two strings: [B2,C1].  I have in the controller in Java with SpringBoot this method:
@GetMapping("data-users/getAllGeneralInfoCV/{listAllCharacteristicsToFind}")
    public List<DataCV2> getAllGeneralInfoCV(@PathVariable ArrayList<ArrayList<String>> listAllCharacteristicsToFind){
        System.out.println(listAllCharacteristicsToFind);
        return findUserDataCVService.findAllGeneralCV(listAllCharacteristicsToFind.get(0),listAllCharacteristicsToFind.get(1), listAllCharacteristicsToFind.get(2), listAllCharacteristicsToFind.get(3), listAllCharacteristicsToFind.get(4), listAllCharacteristicsToFind.get(5));
}

In the system.out.println I can see that the array it gets to the controller is [[B2], [C1], [], [], [], [], []]. However, it should be [[B2, C1], [], [], [], [], []]. In Angular it is okey, so what's the problem?


text:
Q: How to set the value of a select dropdown in javascript dynamically in reactjs I have a select tag which looks like this:
    <select id="bookName"
     onChange={(event) => this.props.handleShelfChange(this.props.book, event.target.value)}>
        <option value="moveTo" disabled>Move to...</option>
        <option value="currentlyReading">Currently Reading</option>
        <option value="wantToRead">Want to Read</option>
        <option value="read">Read</option>
        <option value="none">None</option>
   </select>

So,here I am receiving props from another component. So, one of the prop is {this.props.book.shelf} .This prop has 4 values :

*

*currentlyReading,

*wantToRead,

*read and

*none.

So, what I want is according to the value that is coming through the props from the parent component, the value of the select option should be selected by default. How can this be done?

A: Just pass a selected attribute to all option tags like this
<option selected={this.props.book.shelf === "read"} value="read">Read</option>

A: I would suggest component-like approach.
const elems = ['read', 'wantToRead', 'currentlyReading', 'moveTo'];

export default ({ name, value, book: { shelf } }) => (
  <select>
    {elems.map((v) => (
      <Option value={v} selected={shelf} /> // value coming from prop
    ))}
  </select>
);

const Option = ({ value, selected }) => (
  <option value={value} selected={value === selected}>{value}</option>
);

Codesandbox link: https://codesandbox.io/s/x9m9nx5ynp


text:
Q: Thread concurrency C program I wrote a C program with two threads. The first thread incrementing a counter as fast as it can, while the second thread occasionally read the counter value and print its value. Is posible to check if there is concurrency between threads ?
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstdlib>

int counter = 0;
void* do_nothing(void *null) {
    while(true) {

        counter = counter % 10000000;
        counter++;
    }
}

void* do_nothing1(void *null) {
    while(true) {
        if(rand()%10000000 == 5) printf("counter %d\n", counter);
    }
}

int main(int argc, char *argv[]) {

    pthread_t tid, tid1;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

    if (pthread_create(&tid, &attr, do_nothing, NULL)) {
        printf("ERROR; return code from pthread_create()");
        exit(-1);
    }

    if (pthread_create(&tid, &attr, do_nothing1, NULL)) {
        printf("ERROR; return code from pthread_create()");
        exit(-1);
    }

    if (pthread_join(tid, NULL)) {
        printf("ERROR; return code from pthread_join()");
        exit(-1);
    }

    /*if (pthread_join(tid1, NULL)) {
        printf("ERROR; return code from pthread_join()1");
        exit(-1);
    }*/

    pthread_attr_destroy(&attr);
    pthread_exit(NULL);
    exit(0);

}

A: Simplest way is to use printf() in do_nothing().
BTW, you have a few bugs in there but I can tell you are still learning.


text:
Q: Is there a PDF viewer to be used in a DART/Angulardart Chrome Packaged App ? I am trying to find a suitable PDF viewer to simply display PDF URLs ( external ) / or files ( after creating blobs to the external URLs) in my Chrome packaged app. Tried various things , webview/sandbox pages and using pdf.js. but no luck so far. I am able to get the PDF show up with the webview for the first time but not able to dynamically change the webview's src; as I believe there is an issue with that. Is there anyone displaying dynamic external PDF URLs in a chrome packaged app / how ?

A: I ended up using webview element which loads the PDF using chrome's default viewer, but if I do display ="none", and display ="block", it encounters CSP security issues, so as work around I move the PDF window out of visible and bring it back after updating the src link dynamically.


text:
Q: Logstash Config file at an endpoint Is there a way to have the logstash config file be served from a HTTP endpoint?
I want to be able to share the configs from say a S3 bucket endpoint...
And just want to have them in one place.
I thought I saw somewhere I could...but cannot find it in the docs-
Thanks

A: It is little* unsecure to change your configs from web end-point...
But just for sake of curiosity you can do it.
You cant use nginx + php-fpm and from php you can call bash script which will perform all what you want!)
Also you must set appropriate file modes.
Maybe this approach little bit sophisticated - but it possible to achieve your aim.
PS: Anyway it is bad practice. Better use something like CodeDeploy or Jenkins etc.


text:
Q: Read-only filesystem after adding userquota,groupquota to fstab When  I add option userquota,groupquota to the main (/) partition of my Debian 6 DirectAdmin server, it mounts that partition in read-only mode.
Wat  I did:

*

*nano /etc/fstab

*add userquota,groupquota after errors=continue in the 'options' column to the / mount-point

*save the file and exit nano

*reboot the server

On reboot it shows a lot of errors, all related to read-only filesystem.
Doen someone know what I perhaps did wrong? Thanks a lot!
Edit: my fstab looks like:
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
proc            /proc           proc    defaults        0       0
# / was on /dev/vda1 during installation
UUID=aca09b50-554b-45b6-b3b6-e4444f1f80b6 /               ext3    errors=continue,userquota,groupquota 0       1
# swap was on /dev/vda5 during installation
UUID=628fb534-f3e4-4c44-93ad-f9f7992feff6 none            swap    sw              0       0
/dev/scd0       /media/cdrom0   udf,iso9660 user,noauto     0       0

A: The correct options are usrquota and grpquota. Also, after enabling quotas, you should run quotacheck -uvg /path/to/your/device in order to create the aquota.{user,group} files.
However, I would suggest to set up journalled quota as described in this tutorial.


text: Q: Trouble import Java Github projects to Eclipse When I import my project to Eclipse, I can only work on it as a text file. It doesn't read it as a java project. It doesn't read nonsense words as errors and it only appears as a file system. I tried opening my project through netbeans but the same thing happened.


text:
Q: Deprecated errors while converting app compatible with new IOS I am developing an application.
The main thing is that i have to make compatible it with latest IOS.So, I just want to know

*

*whether i need to install latest xcode sdk for that ? or

*i can make it with sdk lower than latest?

Thanks for Helping .

A: The only reason you would need to use the latest SDK would be to take advantage of the latest iOS 5 changes (new API's and features like Storyboarding).
But anything that is built under older SDK's (such as iOS 4.3) is supposed to run just fine on iOS 5. In reality, that isn't always the case though.

A: You can/should make the target SDK be the lowest "target" device you want to handle (eg, 3.2), though you can compile/build with either iOS 4 or iOS 5. If you don't build with Xcode 4, though, you'll need a physical iOS 5 device to test on. (Good to have one anyway, but it's inconvenient having to do all your testing on a device.) If you do build on Xcode 4 be sure to test both against iOS 5 and a lower version (if you want compatibility with a lower version).


text:
Q: Anylogic: assemble multiple agents at once in assmbler block Is it possible to assemble multiple agents at once in an "assembler" block. I mean that if an agent is composed of two types of parts, and there are three parts of each type, and we have enough resources (e.g. 3 workers) is it possible to assemble these three products simultaneously. in my model they are assembled one by one and there is no option like queue capacity which does the same in "service" block.
Any Idea?

A: Assembler always works one-at-a-time. To have this work in parallel, the model would need to contain 3 separate assemblers with some sort of routing logic to ensure that parts are spread across the assemblers and don't all end up in one block to be processed serially.


text: Q: True Wireless Headphones Lenovo HT10 not working with Ubuntu My Lenovo HT10 True Wireless Headphones work perfectly on windows, but they disconnect in less than 5 seconds on Ubuntu. They have BlueTooth 5.0. Please Help.


text:
Q: How to correctly chain imported interceptors I am using angular-oauth2-oidc, Angular 7. I believe it imports an interceptor with its import
OAuthModule.forRoot({
       resourceServer: {
         allowedUrls: [environment.backendUrl],
         sendAccessToken: true
       }
     })

Additionally I have an interceptor completing an url, which allows me to use only relative paths within httpClient calls of services. e.g.
this.httpClient.get('/resource/' + id)

Which is then intercepted to a complete url to the backend
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (!req.url.startsWith('/') || req.url.startsWith('/assets')) {
            return next.handle(req);
        }

        const modifiedUrl: string = environment.backendUrl + req.url;
        const modifiedRequest = req.clone({ url: modifiedUrl });

        return next.handle(modifiedRequest);
    }

Before the url is intercepted the imported Interceptor obviously can't work.
How can I ensure, that the imported interceptor is coming after the own interceptor in chain?
As a temporary solution I added '/' to the allowedUrls, but I don't like this workaround.

A: Well angular applies interceptor in the order that you provided them. From the doc:

Angular applies interceptors in the order that you provide them. If you provide interceptors A, then B, then C, requests will flow in A->B->C and responses will flow out C->B->A.
You cannot change the order or remove interceptors later. If you need
to enable and disable an interceptor dynamically, you'll have to build
that capability into the interceptor itself.

So i guess you need to tell to your module to not provide the interceptor and declare it yourself.
Taking a quick look at the lib documentation you have no choice than using sendAccessToken to false and implement a custom interceptor that do the job.
import { Injectable, Inject, Optional } from '@angular/core';
import { OAuthService, OAuthStorage } from 'angular-oauth2-oidc';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import { OAuthResourceServerErrorHandler } from "./resource-server-error-handler";
import { OAuthModuleConfig } from "../oauth-module.config";

import 'rxjs/add/operator/catch';

@Injectable()
export class DefaultOAuthInterceptor implements HttpInterceptor {

    constructor(
        private authStorage: OAuthStorage,
        private errorHandler: OAuthResourceServerErrorHandler,
        @Optional() private moduleConfig: OAuthModuleConfig
    ) {
    }

    private checkUrl(url: string): boolean {
        let found = this.moduleConfig.resourceServer.allowedUrls.find(u => url.startsWith(u));
        return !!found;
    }

    public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        let url = req.url.toLowerCase();

        if (!this.moduleConfig) return next.handle(req);
        if (!this.moduleConfig.resourceServer) return next.handle(req);
        if (!this.moduleConfig.resourceServer.allowedUrls) return next.handle(req);
        if (!this.checkUrl(url)) return next.handle(req);

        let sendAccessToken = this.moduleConfig.resourceServer.sendAccessToken;

        if (sendAccessToken) {

            let token = this.authStorage.getItem('access_token');
            let header = 'Bearer ' + token;

            let headers = req.headers
                                .set('Authorization', header);

            req = req.clone({ headers });
        }

        return next.handle(req).catch(err => this.errorHandler.handleError(err));

    }

}


text:
Q: Best E-books and online-resources for Probability and its applications(especially games of chance) I am very much interested in studying games of chance and the probabilities related to our daily life instances but I need an online resource or some e-book to study them. I am a self-learner.

*

*Can you tell me some of the best e-books online which has some good in depth matter and its parallel applications(You can also tell me about two different books one for the matter and other for its applications).

*Is there any prerequisite for this thing (Do I need to study sets and relations in a deeper way or I need just a jist of it).

*How much matter do you need to completely apply my tools of probability to the daily life.
Thank you for your help.

A: This e-book is rather interesting: Introduction to Probability, by Grinstead & Snell, at Dartmouth. Have also a look at their "Chance" web site.
If you are intereseted in statistical applications, those may help:

*

*NIST Engineering Statistics Handbook

*Statistics Textbook from StatSoft

A: Mathematics for Computer Science by Eric Lehman and Tom Leighton
This ebook has an excellent chapter on probability, it's not rigorous, but it builds very good intuition.


text:
Q: remove function on mobile I have this function in my < head > which puts a 'shrink' class onto 'header' class when scrolled 100px.
$(function(){
 var shrinkHeader = 100;
$(window).scroll(function() {
var scroll = getCurrentScroll();
  if ( scroll >= shrinkHeader ) {
       $('header').addClass('shrink');
    }
    else {
        $('header').removeClass('shrink');
    }
});

I want it not to work when the screen is mobile screen size. But I'm not sure how to adjust it for that.
EDIT - Looking for a responsive option (screen size shrinks/grows)

A: Mohammad's answer should have worked, but doesn't anticipate changes in screen size.  I would suggest this:
$(function(){
    var shrinkHeader = 100;
    var hasClass = $('header').hasClass('shrink');

    $(window).scroll(function() {
        if (window.innerWidth > 700) {
            var scroll = document.body.scrollTop;

            if ( scroll >= shrinkHeader ) {
                if (!hasClass) {
                  $('header').addClass('shrink');
                  hasClass = true;
                }
            } else {
                if (hasClass) {
                    $('header').removeClass('shrink');
                    hasClass = false;
                }
            }
        } else {
            if (hasClass) {
                $('header').removeClass('shrink');
                hasClass = false;
            }
        }
    });
});

It keeps track if the class has been added or not to be more efficient (and so that it can be removed if the window is resized so that it's within the mobile threshold).  Be careful of doing unnecessary work onScroll.
I hope you ignore the answers that suggested using userAgent, that's a terrible way to determine if the screen is large enough.

A: You can do this by restricting the function to desktop resolutions ( ex. > 1200px or > 1050px ) only.
$(function(){

    if ($(window).width() > 1200) {
        var shrinkHeader = 100;

        $(window).scroll(function() {
            var scroll = getCurrentScroll();

            if ( scroll >= shrinkHeader ) {
                $('header').addClass('shrink');
            } else {
                $('header').removeClass('shrink');
            }
        });
    }
});

A: You can detect manually if you are on mobile browser. Wrap you code with
(it will only be ran on not mobile browsers):
if(! /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
 // your code
}

A: You could use the solution provided here to end up with something like that:
function isMobile() {
    var check = false;
    (function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))check = true})(navigator.userAgent||navigator.vendor||window.opera);
    return check;
}
if (isMobile()) {
    $(function(){
        var shrinkHeader = 100;
        $(window).scroll(function() {
            var scroll = getCurrentScroll();
            if ( scroll >= shrinkHeader ) {
                $('header').addClass('shrink');
            } else {
                $('header').removeClass('shrink');
            }
        });
    });
}


text:
Q: Windows azure free tier background processing? I'm trying out Windows Azure free trial - as I understand, you can host up to 10 websites on the free account.
My question is: is there any way of hosting a website along with some kind of background processing or scheduled task with the free account on Azure? I'm almost sure that it's not because Web roles support that and not Web sites.
Is there any other alternative to host an ASP.NET MVC website with some kind of background processing on Azure for free? Everything would be purely for educational or personal purposes.

A: The free sites in Windows Azure Web Sites can technically run some background operations because you can spin up a background thread in the application start up; however, there are a several issues with this approach:
Idle sites will be shut down.  This means that if the site isn't seeing a lot of traffic the process can be shut down.  I'm not sure that the background processing would keep it alive, or even if it did how reliable that would be kicking off.  It will depend heavily on the type of background processing I would think.
The web sites at the free level have CPU and memory quotas.  Running something a lot in the background may cause you to hit these quota more often than if the site is more idle.  Hitting the quota will shut down the site until a specific time period has past.  Be very aware of these quotas if you are using the free or shared levels.  If you were planning to have this background processing working a queue for instance this likely won't work out well.
You could use something like the free level of the Scheduler in the Windows Store app to kick off some work by having it call in to your web site and asynchronously kick off the back ground work.  This might work and avoid the CPU quota if the amount of background work is pretty small and is completed quickly and with little resources used.  Note that there is also a scheduler available with Mobile Services.  For educational purposes this may just fine.
Don't forget that with the free trial you get $200 worth of Azure for 30 days.  If you are really just trying things out you can easily spin up full cloud services, VMs or even shared web sites during the trial.  If you shut them down when not actively working on them the $200 can give you a decent amount of time to try things out.


text:
Q: Disable macro caching only for backoffice I need to disable macro caching only for my back office. How can I do that?
I have some macros on my page and I've enabled macro caching for them. But I don't want the back office to be the same, and cached.
Now it is caching the macro for the page each time I want to access it no matter if I am in the back office or on the public view, it will give me the cached version.

A: Unfortunately the caching is either on or off and must be set on the macro itself, I don't believe there's a way to vary it just for the back office.
You might be able to get round it by having the macro call a partial, and do the caching in the partial by calling another cached partial. In the first partial, you could check if you're in the back office by checking if the partial is being rendered by the macro preview like this:
if (Request.Url.ToString().Contains("GetMacroResultAsHtmlForEditor"))
{
    //do something that avoids that cache here
}
else
{
    //do something cached here
}


text:
Q: TypeError: but.getAttribute is not a function - react component Решил сделать по типу https://github.com/learn-co-students/React-Pizza-atlanta-web-042219, ограничился 1 категорией и когда решил присваивать значение абзацу из input, следуя тактике "Если повторяешь 1 и тот же код более 3 раз, то оптимизируй его, балван" сортирнул массив со сравниванием атрибута абазаца и кнопки и вводом в абзац input.value.
Проблема - TypeError: but.getAttribute is not a function
OnDoing () {
        let bascet = document.getElementsByClassName('basc');
        let input = document.getElementById('topper');
        let but = document.getElementsByClassName('pizza-but');
        let i;
        for (i=0; i<=bascet.length; i++) {
            if (bascet[i].getAttribute('data-tab') == but.getAttribute('data-tab')) {
                bascet[i].innerHTML = bascet[i].innerHTML;
            }
        }

    }

    OnRemaster () {
        let bascet = document.getElementsByClassName('basc');
        //let attr = this.getAttribute('data-tab');
        let input = document.getElementById('topper');
        let but = document.getElementsByClassName('pizza-but');
        let i;
        for (i=0; i<=bascet.length; i++) {
            console.log(bascet[i]);
            if (bascet[i].getAttribute('data-tab') == but.getAttribute('data-tab')) {
                bascet[i].innerHTML = input.value;
                console.log(bascet[i]);
            }
        }
    }

    render () {
        return (

            Welcome to School Pizza
            <input id="topper"></input>
            <button onClick={this.OnRemaster} className="pizza-but">Submit</button>

Topping

Peperoni

Topping

Peperoni

            <button onClick={this.OnDoing} data-tab="1" id="first" className="pizza-but">Edit Pizza</button>
            <button onClick={this.OnDoing} data-tab="2" id="second" className="pizza-but">Edit Pizza</button>

        );
    }

A: Объекты, возвращаемые методом getElementsByClassName не содержат свойства getAttribute. Атрибуты можно проверить в свойстве attributes. Условие следует записать так:
if (bascet[i].attributes['data-tab'].value == but.attributes['data-tab'].value) {
  bascet[i].innerHTML = input.value;
  console.log(bascet[i]);
}


text:
Q: update a mysql table by joining on four columns I am trying to update a table of about 2.5 million transactions by adding a budget_id column that's stored in a separate table. Where four fields match, I want to set the budget_id column in the transactions table equal to the budget_id field in the budget table:
update transactions t
join budget b on t.field_1 = b.field_1
and t.field_2 = b.field_2
and t.field_3 = b.field_3
and t.field_4 = b.field_4
set t.budget_id = b.budget_id;

There are about 6,900 rows in the budget table, each with a unique budget_id. So I am trying to match these 6,900 rows to the 2.5 million rows in my transactions table by joining on four columns. Every time I run this query I lose my connection. Each column is indexed in both tables and I am using a google cloud instance with 8 GB RAM. My innodb_buffer_pool_size is 6 GB. Would really appreciate it if someone can tell me why this is happening or how I can do this more efficiently so that it won't crash. Thanks very much.

A: "Each column is indexed".  Actually, you want a composite index.  The best for this query would be:
create idx_budget_field1_field2_field3_field4_budget_id
    on budget(field_1, field_2, field_3, field_4, budget_id);


text:
Q: Spring Security with Java EE Restful Service I have created a Java EE 6 restfull service and tried to integrate that with Spring Security. But, all the time I get different weird exceptions. Which doesn't make any sense or may be make sense but at least not for me.
Direction structure of my application is something like this:
com.security
    UserDetailsSecurityConfig.java
com.service
    ApplicationConfig.java
    UserFacadeREST.java
com.config
    AppConfig.java

My entities are auto generated so no error seems to be there. But, yes the three files seems fishy to me as UserFacadeREST is working fine when I don't integrate my application with Spring Security.

com.UserDetailsSecurityConfig.java

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class UserDetailsSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService( userDetailsService() );
    }
    @Override
    protected void configure( HttpSecurity http ) throws Exception {
        http
           .httpBasic().and()
           .sessionManagement().sessionCreationPolicy( SessionCreationPolicy.STATELESS ).and()
           .authorizeRequests().antMatchers("/**").hasRole( "USER" );
    }
    @Bean
    public UserDetailsService userDetailsService() {
        return new UserDetailsService() {
            @Override
            public UserDetails loadUserByUsername( final String username )
                    throws UsernameNotFoundException {
                if( username.equals( "admin" ) ) {
                    return new User( username, "password", true, true, true, true,
                            Arrays.asList(
                            new SimpleGrantedAuthority("ROLE_USER" ),
                            new SimpleGrantedAuthority( "ROLE_ADMIN" )
                        )
                    );
                } else if ( username.equals( "user" ) ) {
                    return new User( username, "password", true, true, true, true,
                        Arrays.asList(
                            new SimpleGrantedAuthority( "ROLE_USER" )
                        )
                    );
                }

                return null;
            }
        };
    }

}

com.service.ApplicationConfig.java

@javax.ws.rs.ApplicationPath("webresources")
public class ApplicationConfig extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> resources = new java.util.HashSet<>();
        addRestResourceClasses(resources);
        return resources;
    }

    /**
     * Do not modify addRestResourceClasses() method.
     * It is automatically populated with
     * all resources defined in the project.
     * If required, comment out calling this method in getClasses().
     */
    private void addRestResourceClasses(Set<Class<?>> resources) {
        resources.add(com.service.UserFacadeREST.class);
    }

}

com.service.UserFacadeREST.java

@Stateless
@Path("user")
public class UserFacadeREST extends AbstractFacade<UpUser> {
    @PersistenceContext(unitName = "PU")
    private EntityManager em;

    public UserFacadeREST() {
        super(User.class);
    }

    @POST
    @Override
    @Consumes({"application/xml", "application/json"})
    public void create(User entity) {
        super.create(entity);
    }
    @GET
    @Path("count")
    @Produces("text/plain")
    public String countREST() {
        return String.valueOf(super.count());
    }

}

com.config.AppConfig.java

@Configuration
@Import( UserDetailsSecurityConfig.class )
public class AppConfig {
    @Bean
    public ApplicationConfig applicationConfig() {
        return new ApplicationConfig();
    }
        @Bean
    public UserFacadeREST userRestService() {
        return new UserFacadeREST();
    }

}

In whole code I have made few changes for hit and trial. And currently, I am getting an exception.

java.lang.IllegalStateException: No WebApplicationContext found: no
  ContextLoaderListener registered?

Before that I was getting another exception which was

WebSecurityConfigurers must be unique. Order of 100 was already used

I am not getting what I am doing wrong in integrating Spring Security with Java EE 6. I am new to Spring so may be I am doing a blunder which seems obvious to me.
My web.xml file is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="rest-sec" version="3.0">

    <display-name>rest</display-name>

    <!-- Spring security -->
    <listener>
        <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
    </listener>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>etagFilter</filter-name>
        <filter-class>org.springframework.web.filter.ShallowEtagHeaderFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>etagFilter</filter-name>
        <url-pattern>/api/*</url-pattern>
    </filter-mapping>

    <!-- rest -->
    <servlet>
        <servlet-name>rest</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextClass</param-name>
            <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
        </init-param>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>com.labs.entities</param-value> <!-- won't find anything -->
        </init-param>
        <init-param>
            <param-name>dispatchOptionsRequest</param-name>
            <param-value>true</param-value>
        </init-param>

        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>rest</servlet-name>
        <url-pattern>/api/*</url-pattern>
    </servlet-mapping>

    <!-- Disables servlet container welcome file handling. Needed for compatibility
        with Servlet 3.0 and Tomcat 7.0 -->
    <welcome-file-list>
        <welcome-file />
    </welcome-file-list>

</web-app>

A:
java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered?

You need to tell the filter where to look for your context (it's default is to look in a place that is not used by the servlet you created). In your filter add an init param:
    <init-param>
        <param-name>contextAttribute</param-name>
        <param-value>org.springframework.web.servlet.FrameworkServlet.CONTEXT.spring</param-value>
    </init-param>

WebSecurityConfigurers must be unique. Order of 100 was already used

Do you have 2 beans of type WebSecurityConfigurerAdapter? Or is your UserDetailsSecurityConfig being loaded twice?


text:
Q: Estimating $\int_0^1 x^{2n}(1-2x)^{2n}e^xdx$ To find a bound for $\int_0^1 x^{2n}(1-2x)^{2n}e^xdx$ I did the following:
\begin{align}
&x(1-2x)\leq\text{max}[x(1-2x)]\\
&x(1-2x)\leq\  1/8 \:\:\: \text  { the maximum occurs at $x=1/4$ }\\
&x^{2n}(1-2x)^{2n}\leq  \left( 1/8 \right)^{2n}\\
& x^{2n}(1-2x)^{2n} e^x \leq  \left( 1/8 \right)^{2n} e^x\\
& \int_0^1 x^{2n}(1-2x)^{2n} e^x dx\leq \left( 1/8 \right)^{2n} \int_0^1 e^xdx\\
& \int_0^1 x^{2n}(1-2x)^{2n} e^x dx\leq \left( 1/8 \right)^{2n} (e-1)
\end{align}
I believe something is terrible wrong with that.

A: When $x\in [0,1]$, $(1-2x)^{2n}\le 1$ and $e^x\le e$, by first mean value theorem for definite integrals,
\begin{align*}
I_n&\le\max_{x\in[0,1]}\{(1-2x)^{2n}e^x\}\int_0^1x^{2n}~\mathrm dx\\
&=\frac{e}{2n+1}\to0.
\end{align*}


text:
Q: How to create a root certificate for application gateway? I have a webapp hosted in Azure app service and has a certificate associated with its domain and the certificate is stored in the keyvault.
I want to create one application gateway with web application firewall(WAF v2 tier). In that application gateway, I need to use one certificate in the backend setting.
I tried to use the same certificate which is present is the keyvault here, but I am getting the error of "ApplicationGatewayTrustedRootCertificateInvalidData".
So which root certificate should I use in the application gateway and use it in app service too?
I tried to create one self signed root certificate but due to this the health of backend servers are coming as unhealthy with the error message -
The Common Name (CN) of the backend server certificate does not match the host header entered in the health probe configuration (v2 SKU) or the FQDN in the backend pool (v1 SKU). Verify if the hostname matches with the CN of the backend server certificate. To learn more visit - https://aka.ms/backendcertcnmismatch.


text:
Q: Node.JS using Sails.JS Framework -- Passport: no strategy registered under name: facebook I'm using the Sails.JS framework for Node.JS . I have written a config/middleware.js that has a verify handler and makes the initial connection. The page is currently erroring on the AuthController that is being pushed by config/routes.js.
Console Log:

Fired Facebook
error: Error: no strategy registered under name: facebook
at attempt (/project/node_modules/passport/lib/passport/middleware/authenticate.js:237:37)
at Passport.authenticate (/project/node_modules/passport/lib/passport/middleware/authenticate.js:244:7)
at AuthController.facebook (/project/api/controllers/AuthController.js:35:4)

Authcontroller.js function
   'facebook': function(req, res, next) {
    console.log("Fired Facebook");
    passport.authenticate('facebook', {
    failureRedirect: '/auth',
    scope: 'email'
    }, function(err, user) {
       console.log("Fired Login Attempt");
            req.logIn(user, function(err) {
                    if (err) {
                    console.log(err);
                    res.view('500');
                    return;
                    }

            res.redirect('home/index');
            return;
            });
    })(req, res, next);

Passport-facebook and passport are both in the node-modules.
package.json
 "dependencies": {
    "sails": "0.9.4",
    "grunt": "0.4.1",
    "sails-disk": "~0.9.0",
    "ejs": "0.8.4",
    "optimist": "0.3.4",
    "passport": "latest",
    "passport-local": "latest",
    "passport-facebook":"latest",
    "sails-mongo":"latest",
    "bcrypt": "0.7.6"
},

A: Issue Resolved -- Conflicting node_modules of passport were installed.


text:
Q: What is the oldest version of rubygems that is supported? What is the oldest version of rubygems that still allows you to download gems from rubygems.org?

A: When the transition from http://Gems.RubyForge.Org/ to http://RubyGems.Org/ was made, all backwards-compatibility features that were removed had already been replaced before RubyGems 1.0. So, you should be fine at least as far back as 1.0, possibly even further.
I'm not 100% sure, though. But I think that all that was removed was the YAML index format and bulk updating, both of which have been obsolete for years.


text:
Q: Switching themes in Drupal without the web interface I'm in the process of learning php and creating themes.
Unfortunately, while I was editing a theme that i was currently using in drupal, I made a mistake in the theme such that nothing shows up anymore, even if i were to hit drupal/index.php. I want to change my broken drupal theme to a working one but i'm unable to do so because I can't even view the administration section.

A: The easiest way to change your frontend theme is to set it in your sites/default/settings.php:
$conf['theme_default'] = 'minelli';

A: In terms of sorting your current problem, here's a simple way to do it that should work... Let's say your current theme is called "custom_theme".

*

*Go to your theme directory ("sites/default/themes" probably)

*Backup your development theme (i.e. move it elsewhere, if you're using Linux command line do something like "mv custom_theme custom_theme.bak")

*Copy the garland theme to here and name it the same as your broken theme (if using LInux command line, something like this should work "cp -a ../../../themes/garland ./custom_theme"

*Try viewing your site now. It should now use garland instead of your broken theme.

As others have said before, it's also highly recommended that you use a different theme for admins as you do for normal users (in case you break stuff). Select a safe admin theme (like garland) and then you can nearly always get to the admin interface if you're playing with theming.

A: Or if you are using Drupal 6, removing/moving the broken theme folder will make Drupal change the theme to the default theme (Garland).

A: The How To reset your theme via the database page on Drupal.org has instructions for changing your theme directly from the SQL prompt.
It's not immediately clear whether this will work in the most recent version of Drupal, so back up your database before attempting this.

A: Maybe using two themes in parallel will help.
Set one for the "user frontend" - the one you are developing at /admin/build/themes, another one standard, like garland, which you are NOT going to change, as a "administration backend": /admin/settings/admin.
If you happen to break the theme you're developing, you just go to the admin area (/admin), it will switch back to garland.

A: you can also insert a new login form in your theme by including this code:
 `<?php
    if(!user_is_logged_in() ){
        print drupal_render(drupal_get_form('user_login'));
    }else{
        print "You are already logged in!";
   }?>`

anywhere in the page.tpl.php file of your broken theme, then register with your admin credentials ;)

A: Please also see the following stack over flow issue.
it is related to them

*

*Changing Drupal's theme and keeping Garland as the admin theme?

*Changing the Admin Theme in Drupal 6 Directly in Database
Now here is solution :
Remove the files of the bad theme and clear the cache. After clearing the cache you will be able to login again.
The main difficulty is that you have to clear the cache without being logged in.
Try one of the methods for clearing the cache described in
Clearing Drupal's cache
IF Not then Try this one :
If you have drush, the command to type would be
drush vset theme_default garland

Either on the commandline, or via an administration interface (eg PHPMyAdmin) enter the following query
UPDATE system SET status=1 WHERE name = 'garland';

Then either:
UPDATE variable SET value='s:7:"garland"' WHERE name = 'theme_default';
TRUNCATE cache;
TRUNCATE cache_bootstrap;
TRUNCATE cache_block;

Note that 's:7' refers to the length of the following string. Modify as needed. This is database surgery, tricky stuff.
OR
If you are using per-user themes, and you've just messed it up for yourself as admin, try
UPDATE users SET theme='garland' WHERE uid = '1';

Be careful, as getting either of those lines wrong can mess things up just as badly.
Cheers!
Mudassar Ali

A: As far as I know, theme settings are stored in the database, as well for each individual user. The quickest way to get rid of a theme is probably removing it from the theme path.
Just move it onto your desktop and Drupal should be able to detect that your requested theme is missing and point you to the default instead.
Update: Tried this on my Drupal 5 installation, it turned out 'clean'. I suggest copying a working Drupal theme into your theme directory (make a copy first).

A: It's worth mentioning that if you're using the "Sections" module to apply different themes to different parts of the site, the instructions given on the Drupal site won't necessarily work — you may find that moving the problem theme directory out of the way is the only method of seeing the admin interface properly.


text:
Q: Fast RC4 cipher stream for Python? I'm trying to write an app that needs large numbers of cryptographic strength pseudorandom bytes.
The RC4 cipher would be ideal for this; it's lightweight and simple to understand conceptually. So, I got the spec and wrote an RC4 algorithm in Python.
It works exactly as expected, but, it's slow as molasses. On my Core i7 2.2GHz, I can only get about 1MB/sec out of the algorithm.
Clearly the interpreted nature of Python is not the best suited for this sort of task. My problem is I'm not well versed in C coding - the best I've done with C is some Hello World stuff and some experiments with file reading and writing. Either way, I certainly am not good enough with C to use the Python-C APIs.
I do know .NET/C#, and I wrote the same algorithm in Windows on C#, and I Was able to easily get over 60MB/sec out of it. So .NET's CLR is a lot more optimized. But, the target platform for the Python app is Unix/Linux.
Ideally, I don't want to have to go through tons of middle-layers just to get an optimized RC4 cipher into a Python app.
Since RC4 depends on state, ideally I'd do this with a class (That's how I did it with my Python-only implementation.) So, here's a small snippet of what I want to be able to do:
rc4 = RC4Encrypter()
rc4.seed(myKey) # seed the RC4 algorithm with bytes from string myKey
rc4.getRC4Bytes(1048576) # get the next 1MB of RC4 cryptostream bytes as a binary string
rc4.encryptWithRC4(myString) # encrypt myString's bytes with RC4 bytes using xor and return

Any advice? I'd love to learn C but it's a big learning curve right now for just this simple project.

A: I believe PyCrypto has an RC4 implementation, check it out here


text:
Q: What's the alternative for a web service/distributed system if it is not using a stub? I'm currently learning about web services, and if I understood correctly as an example for an RPC, a stub is generated based on a WSDL and the stub converts methods, data etc. into  a form that the remote process can use (the whole marshalling and demarshalling thing, I think I got the gist of it). I think a big part of why a stub is generated is also to make the whole thing function across different adress spaces and operating systems. Correct me if I'm wrong.
My main question: are there alternatives that don't generate stubs, and if so, how do they bridge the gap between the local system and remote system?

A: You have two major ways to design communication - contract first or contract last.
In your example, you do contract first - you write WSDL and then code is generated out of it. The benefit for this approach is decoupling the development process - both sides (server and clients) can be developed based on the contract.
Contract last is when you define your apis in code and then framework generate WSDL from those methods. Arguably this is faster far smaller teams as they can change apis on the go before the first public release.
As for: alternatives that don't generate stubs, and if so, how do they bridge the gap between the local system and remote system - I would recommend to have a dedicated communication layer, which abstracts the actual on-wire communication.
For example, let's say a remote system has two api's - getNameById and getEmailById. Your business case requires both name and email, hence you would have a data access layer with an api - getNameAndEmailById. In that case you would stub this data access layer for testing purposes. But there is nothing inherently wrong with using stubs/mocks for the remote service.


text:
Q: DB design relation - product, category, attribute I have 2 tables:

*

*products (id,name,category_id)

*categories (id,name)

I want to add third with products attributes, but attributes are specified by category. So it will be like this?

*

*attributes (id,name)

*attribute_product (attribute_id,product_id,value)

*attribute_category (attribute_id,category_id)

A: Assumptions made from your question:

*

*a Product can have 1 and only 1 category

*you said attributes are specified by category

So, link the attributes to the category.  A Product of category X will inherit the attributes automatically.

However, this forces the value as well as the attribute.  So all products get the same attribute value (ex. all products in the Cagetory Clothes would be the same color!)  So, you want attribute values to be different from Product to Product in the same category:

This way, the attribute's name (it's existence if you want) is linked to a category, and the value is linked to an object.  I assumed that you want multiple attributes per object, and 1 category per attribute.
Ex:

*

*Category: Clothes

*Product: Shirts

*Attributes of Clotes: size and color

*Value of attributes: L and blue

So, all this to say that your initial idea was good (!).

A: You have 3 "entiities" (so far) -- Products, Categories, Attributes.  These are tables.
There are essentially two "relationships" you can have:  "one-to-many" and "many-to-many".  The former just needs an id in one table to link to the other.  The latter needs an extra table with pairs of ids.
Decide what relationships you have between your entities.
Job done.


text:
Q: SQL-Case Statement/Maybe a Loop would work? Novice coder here, so any advice is greatly appreciated.
Edited:
I have a table with thousands of ongoing projects. There are at least 10 different dates/milestones per project (which are recorded as dates, hence date1, date2 and so forth). I need to create a calculated field where depending on the max date for that one project (based on ALL the date columns), I have to set it at a specific stage in the project (see Phase column--this is the calculated field I'm trying to produce with my code). Here's the breakdown:

Not all the dates in a specific stage will be available. For example, in Project #1, date1 is filled in but not date2 or date3, and so that symbolizes that the project is still in Stage1. If date2 or date3 are also filled in, the project will still be in Stage1 because date4, date5, date6, date7, date8, date9, date10 are all nulls.
So I'm writing case statement in the select statement, but it is getting a little convoluted. The following is what I drafted for Stage 2:
SELECT *
    FROM datatable
    CASE WHEN date5 >= date4
          AND date5>date3
          AND date5>date2
          AND date5>date1
          AND date6=NULL
          AND date7=NULL
          AND date8=NULL
          AND date9=NULL
          AND date10=NULL
     THEN 'Stage2'

And that's just for stage 2. I haven't written out the other stages. Does anyone have an easier way to do this?
Thank you!

A: It seems you want to set the stage according to the last date column set in the row. As the first match in a CASE expression wins, this would be:
SELECT t.*,
  CASE
    WHEN date10 IS NOT NULL THEN 'Stage5'
    WHEN date9 IS NOT NULL THEN 'Stage4'
    WHEN date8 IS NOT NULL THEN 'Stage4'
    WHEN date7 IS NOT NULL THEN 'Stage3'
    WHEN date6 IS NOT NULL THEN 'Stage3'
    WHEN date5 IS NOT NULL THEN 'Stage2'
    WHEN date4 IS NOT NULL THEN 'Stage2'
    WHEN date3 IS NOT NULL THEN 'Stage1'
    WHEN date2 IS NOT NULL THEN 'Stage1'
    WHEN date1 IS NOT NULL THEN 'Stage1'
    ELSE 'Stage0'
  END AS stage
FROM datatable t
ORDER BY project#;


text:
Q: Connect to IBM DB2 database using SQLAlchemy I am trying to connect to a cloud based IBM DB2 database using SQLAlchemy. Using the base ibm_db python library this works :
connection_string = 'DRIVER={DB2};DATABASE=BLUDB;HOSTNAME=host.databases.appdomain.cloud;PORT=port;PROTOCOL=TCPIP;UID=user;PWD=pass;SECURITY=SSL;'
conn = ibm_db.connect(connection_string, '', '')

However, trying to do the same using SQLAlchemy, the connect part just hangs/timeouts
from sqlalchemy import create_engine
import ibm_db_sa

user = "user"
password = "pass"
host = "host.databases.appdomain.cloud"
port = "port"
database = "BLUDB"

db2_connection_string = (
    f'db2+ibm_db://{user}:{password}@{host}:{port}/{database}'
    ':SECURITY=SSL'
)

engine = create_engine(db2_connection_string)
connection = engine.connect() # timeouts here

Any suggestions ?

A: Only use a connection string like this:
db2_connection_string = (
    f'db2://{user}:{password}@{host}:{port}/{database}'
    ':SECURITY=SSL;PROTOCOL=TCPIP;'
)

In this line of code in ghstats.ps is a working sample. The code is from this IBM Cloud solution tutorial which has a Python app with SQLAlchemy connecting to Db2 on Cloud.
As alternative, you can also try ibm_db_sa as driver prefix instead of db2. Make sure to import the right modules (ibm_db, ibm_db_sa).


text:
Q: laravel resource route not generating named routes So I just created a resource route as follow:
Route::group(['prefix' => 'control-panel'], function () {
   Route::resource('changelog', 'admin\ChangelogController');
});

Yet when I try and use any named route in blade it says that the route does not exits. Note that I do have a grouped - prefix route around it.
{{ route('changelog.create') }}

I really rather not write all routes seperate as I've done now for a quick fix.
I use Laravel 5.2.

A: You are using route prefix so the route name will have that prefix too. This must be working:
{{ route('control-panel.changelog.create') }}

you can override these names by passing a names array with your options:
Route::group(['prefix' => 'control-panel'], function () {

   Route::resource('changelog', 'admin\ChangelogController', ['names' => [
        'create' => 'changelog.create'
    ]]);

});


text:
Q: How does one implement drop caps in plain TeX? How might one implement a simple drop cap in plain TeX without additional packages?

A: Here's a very basic approach showing two possibilities; the first one using \hangindent and the second one (more flexible), \parshape:
\font\lettrine=cmssdc10 at 30pt
\font\scfont=cmcsc10
\hsize=24pc

\noindent{\lettrine L}

\vskip-2.15\baselineskip\hangindent=1.8pc \hangafter-2 \noindent{\scfont orem} ipsum dolor sit amet, consectetuer adipiscing elit. Ut purus elit, vestibulum ut, placerat ac,
adipiscing vitae, felis. Curabitur dictum gravida mauris. Nam arcu libero, nonummy eget,
consectetuer id, vulputate a, magna. Donec vehicula augue eu neque. Pellentesque
habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Mauris ut
leo. Cras viverra metus rhoncus sem. Nulla et lectus vestibulum urna fringilla ultrices.
Phasellus eu tellus sit amet tortor gravida placerat. Integer sapien est, iaculis in, pretium
quis, viverra ac, nunc. Praesent eget sem vel leo ultrices bibendum.

\vskip\baselineskip

\noindent{\lettrine L}

\vskip-2.15\baselineskip\parshape 3 1pc 23pc 1.5pc 22.5pc 0pc 24pc \noindent{\scfont orem} ipsum dolor sit amet, consectetuer adipiscing elit. Ut purus elit, vestibulum ut, placerat ac,
adipiscing vitae, felis. Curabitur dictum gravida mauris. Nam arcu libero, nonummy eget,
consectetuer id, vulputate a, magna. Donec vehicula augue eu neque. Pellentesque
habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Mauris ut
leo. Cras viverra metus rhoncus sem. Nulla et lectus vestibulum urna fringilla ultrices.
Phasellus eu tellus sit amet tortor gravida placerat. Integer sapien est, iaculis in, pretium
quis, viverra ac, nunc. Praesent eget sem vel leo ultrices bibendum.

\bye


text:
Q: react context not working when provider placed at certain parts of the element tree I'm using a react context to manage a large input form, and I want the provider to be placed just around that input form. But it throws the following error: "A context consumer was rendered with multiple children, or a child that isn't a function. A context consumer expects a single child that is a function. If you did pass a function, make sure there is no trailing or leading whitespace around it." This is my context:
import React from "react";
import { useState } from "react";

const AddHeaderContext = React.createContext({
    headerType: "",
})

export const AddHeaderContextProvider = (props) => {
    const [headerType, setHeaderType] = useState("noimage")

    const headerTypeChangeHandler = (type) => {
        setHeaderType(type)
    }

    const contextValue = {
        headerType: headerType,
    }

    return (
        <AddHeaderContext.Provider value={contextValue}>
            {props.children}
        </AddHeaderContext.Provider>
    )
}

export default AddHeaderContext

This is when there is an error:
import AddHeaderContextProvider from './store/AddHeaderContext'

<AddHeaderContextProvider>
    <AddHeaderSection />
</AddHeaderContextProvider>

But weirdly the error disappears when I move the context up into my index.js top level element and wrap everything in it.
Any idea why that could be? Also, I tap into this context usinig "useContext" hooks and not .Consumer.

A: I figured it out:
I just needed to use curly brackets around the contextProvider since it wasn't the main export from that file:
import { AddHeaderContextProvider } from './store/AddHeaderContext'

<AddHeaderContextProvider>
    <AddHeaderSection />
</AddHeaderContextProvider>

A: You have this export default AddHeaderContext in AddHeaderContext.js, so when you do import AddHeaderContextProvider from './store/AddHeaderContext'
you are actually getting AddHeaderContext (the default export), not AddHeaderContextProvider.
Either change your import to import {AddHeaderContextProvider} from './store/AddHeaderContext' or your exports as below:
import React from "react";
import { useState } from "react";

export const AddHeaderContext = React.createContext({
  headerType: "",
});

const AddHeaderContextProvider = (props) => {
  const [headerType, setHeaderType] = useState("noimage");

  const headerTypeChangeHandler = (type) => {
    setHeaderType(type);
  };

  const contextValue = {
    headerType: headerType,
  };

  return (
    <AddHeaderContext.Provider value={contextValue}>{props.children}</AddHeaderContext.Provider>
  );
};

export default AddHeaderContextProvider;


text:
Q: Unable to Execute VLC from PHP I am running uBuntu 12.04.3, 32 bit OS on a 8 CPU, 8GB RAM 64-bit Intel Xeon machine. I have installed all backports as well.
I have this problem which is eating my head for the last 3 days. I created a play.sh file with the following code...
Code:
#! /bin/sh

vlc -vvv sasural.ts

Where sasural.ts is a video file that resides under home and in the same level as Apache. I am invoking the .sh file by using the following PHP code...
Code:
shell_exec('play.sh');
I also tried both the exec() / system() methods to invoke the .sh file.
Whenever I do so, I get the following message...
VLC media player 2.2.0-git Weatherwax Command Line Interface initialized. Type `help' for help. > Shutting down.

play.sh works if I execute it from the terminal command prompt outside of the PHP code. I guess I am doing something wrong when I invoke it from within PHP.
I have performed the following tasks...

*

*Given Apache Root Access

*Linked all folders to Apache

A: Done it :)
That was fun :D
prerequisites: vlc must already be running
fifo file must exist
The below will set this up:
mkfifo /tmp/vlcfifo
chmod a+rw /tmp/vlcfifo
tail -f /tmp/vlcfifo | nohup vlc --intf rc &

in the php file:
<?php
passthru('echo "add /path/to/video.avi" | tee /tmp/vlcfifo');
?>

Give that a try :)

A: In your script, before you launch vlc, have the line: export DISPLAY=:0
This should launch it in your primary X session, assuming the webserver is running on the same box as your X session.
You will also need to do something with sound if you require it. Like a remote ALSA or Pulseaudio server.

A: Gentlemen,
I have been able to solve this issue by using the following steps...

*

*Install vlc nox version

*In the PHP file:
  echo shell_exec("sh /var/www/play1.sh");

*In the play1.sh file:
  #!/bin/sh
  vlc -Idummy /var/www/media.ts --sout '#standard{access=http,mux=ts,dst=:1935/}'

*Invoke the PHP file via a browser and VLC will start streaming to port 1935
To access the file from the client end...
1) Point VLC or any media player to the URL + Port. Ex. http://www.something.com:1935
2) The client player will start to receive the file and play it back.
Now the next step is to enable this file on demand. Will post how I did that as well so stay tuned!!
Thank you everybody who have helped me in solving this problem. I have added +reps wherever it was possible.


text:
Q: Java Grpc: invalidate dns cache I have a grpc client pointing to a url which resolves to 2 IP addresses.
The problem is when one server node goes down and then gets back, it's not picked by the grpc client and all the load goes to a single node.
I tried recommendation to change networkaddress.cache.ttl propetty but it didn't help.
My code (in Scala)
java.security.Security.setProperty("networkaddress.cache.ttl", "30")
System.setProperty("networkaddress.cache.ttl", "30")
val channel = NettyChannelBuilder.forAddress(host, port).nameResolverFactory(
      new DnsNameResolverProvider).usePlaintext().build
val client = MyServiceGrpc.newStub(channel)

grpc version: 1.32.1

A: Assuming that DNS returns both IPs all the time (probably shuffled), then the problem is not the DNS cache. The problem is that gRPC has a working connection and so won't choose to reconnect and won't perform DNS queries.
You should configure your server with MAX_CONNECTION_AGE to force clients to reconnect occasionally to rebalance the load. When clients are disconnected from the server they trigger a new DNS resolution, so this can also be used to find new addresses (although reconnections do not wait for the DNS resolution to complete).
In Java, MAX_CONNECTION_AGE is available via NettyServerBuilder.maxConnectionAge():
NettyServerBuilder.forPort(yourPort)
    .maxConnectionAge(30, TimeUnit.MINUTES)
    ....

You want to use as large of age as you can accept. With a time like 30 minutes, then each client will rebalance every 30 minutes. So after 15 minutes of the server restarting that server would have ¼ of the load and after 30 minutes it would have roughly ½.

A: Seems that configuring load-balancing policy does the job:
NettyChannelBuilder.forAddress(host, port).defaultLoadBalancingPolicy("round_robin").usePlaintext().build()