text:
Q: Is it really impossible to protect Android apps from reverse engineering? As we know, Android apps are written in Java. In Java, no matter what you do, it is impossible to protect compiled code from decompilation or reverse-engineering, as the Stack Overflow question How to lock compiled Java classes to prevent decompilation? suggests.
How would one go about protecting an app that contains algorithmic trade secrets from reverse-engineering?
By "how" I mean not only software techniques, but also other creative approaches.

A: The first stop for me would be to optimise and obfuscate the code with ProGuard which is known to work with byte code targeted at Android's Dalvik VM (via Dex). It's a really great tool and can increase the difficulty of 'reversing' your code while shrinking your code's footprint (in some cases dramatically: a recent applet of mine went from about 600 KB down to about 50 KB).
Like others are saying, you will never get 100% security of your algorithm's details while its implementation is being distributed to clients. For that, you'd need to keep the code on your servers alone. Attempts to near 100% percent security for client code effectively amount to DRM and can make your client code fragile in the face of network outages and just generally frustrate (legitimate) users.
The Android developers blog has some useful articles on the matter of 'tamper resistant' Android apps (and they recommend the use of ProGuard as part of the overall approach).
With regards to 'creative' approaches: some developers employ debugger detection techniques to prevent run-time analysis and combine this with encryption of portions of binary code (to deter static analysis), but to be honest, a determined enough attacker can circumvent these, while it can cause legitimate user frustration as illustrated by the Windows KB article Games: Error Message: A Debugger Has Been Detected: Unload the Debugger and Try Again. My girlfriend's 'Learn to drive' DVD software will not run under VirtualBox for this reason, but she blames Linux of course!
OpenRCE and Wikipedia's article on obfuscated code may be good starting points if you want to look into this further. But be warned, you may lose more through over zealous use of these techniques frustrating your users than you would through loss of trade secrets by reverse engineering. Like Anton S says, maybe the most 'creative' approach lies with tweaking the business model rather than the technology.
The latest Android SDK update on 6th Dec 2010 (coinciding with Android 2.3 Gingerbread release):

Integrated ProGuard support: ProGuard is now packaged with the SDK Tools. Developers can now obfuscate their code as an integrated part of a release build.

A: Make it so cheap to bother and don't build your business model on top of secrets that are executed on the client side. In other words, don't share your secrets.

A: It is impossible to protect any client side code from reverse engineering. You can just use more or less efficient ways of obfuscating your code. And optimized x86 assembler happens to be a pretty good obfuscation.
So if you have algorithmic secrets put them on the server-side.

A:
How to lock compiled Java Classes to prevent decompilation

You can't.  Any scheme can be defeated by someone with sufficient skills, time and motivation.
(Incidentally, this also applies to software that is compiled to binary.  The only difference is in the amount of effort involved in decompiling.)

My question is how one would go about protecting an app that contains algorithmic trade secrets from reverse-engineering?

Simply don't install the app on the user's phone.  Or (more usefully), run the code that contains the trade secrets on a remote (properly secured) server.

A: You can't protect your application completely, as there will always be someone who will crack it...
However you could hinder them doing this by making your application free, or at least dirt cheap so people won't be bothered.
Alternative, try to keep your Android application "dumb", as in keep all the secretive business logic on a backend server, and just have you app display data using some form of exposed service.

A: If it's a possibility: remote procedure calls to a well-protected server (the server has the code you want to protect).

A: No matter what you do, maybe at least you can make it very hard to decompile, but: If something gets executed/calculated in a program, the information about the algorithm has to be there, and there will always be a possibility to find out how to get that (enough skill and motivation on you opponents side assumed). Always.

A: I have my algorithm on a server and I invoke that service from my smartphone app. A perpetrator can reverse engineer my smartphone app to see my protocol with my server. I can protect my algorithm but I can not protect against unauthorized use of my service. I have to accept this reality without a solution. I have to be content that as long as I am making money with my own service, then I have to live with the potential of others siphoning my service.

A: You want a creative approach, here's one.
What is the main program on phones that haven't been decompiled today? Radio firmwares. Why? It doesn't run on the ARM chipset of the phone but instead on a separate Qualcomm Hexagon that is more and more present in smartphones. It's not x86, it's not ARM, it uses a Qualcomm proprietary architecture and instructions.

*

*Java decompilation is easy.

*ARM decompilation is more difficult (Hex-Rays Decompiler licences
start at 1129 USD... and the mix between thumb code and standard ARM code in binaries is a pain) => you could try compiling with the Android
NDK.

*There is currently no Hexagon decompilers! And QDSP specifications are not publicly available, even pirated versions.
Question is, can an independant software vendor use the Hexagon firmware included in the mass-market phones? It seems to be the direction Qualcomm takes. Check out their website and the SnapDragon products.
NB: I'm not pro-Qualcomm nor pro-closed-source. But this thread appeals to this kind of solution.

A: You can't 100% secure you android code from reverse engineering.
If you want to secure some key then you can take help from integrating server that give you encrypted key while calling web service and use that key into your code.


text:
Q: Read the return value from VBScript into SAS I have a SAS program which requires many input files whose names vary each month.  Rather than update the individual file names in Windows Explorer to hardcoded aliases in SAS or copy and paste the new file names into macro variables, I want SAS to initiate a file prompt where I may select the inputs. I am using SAS 9.4 on Windows 7.
To this end, I have written a VBScript which opens a dialog and returns either the path of a selected file or a blank string if the dialog is canceled or closed.
' GetFilePath.vbs

Option Explicit

Function GetFilePath()

    Dim objExec, strMSHTA, wshShell

    GetFilePath = ""

    strMSHTA = "mshta.exe ""about:<input type=file id=FILE>" _
          & "<script>FILE.click();new ActiveXObject('Scripting.FileSystemObject')" _
          & ".GetStandardStream(1).WriteLine(FILE.value);close();resizeTo(0,0);</script>"""

    Set wshShell = CreateObject( "WScript.Shell" )
    Set objExec = wshShell.Exec( strMSHTA )

    GetFilePath = objExec.StdOut.ReadLine( )

    Set objExec = Nothing
    Set wshShell = Nothing

End Function

'WScript.Echo GetFilePath()

GetFilePath()

Ideally, I would like to assign the return value of GetFilePath.vbs to a macro variable.  However, it's not clear to me how to I would do that.  The only relevant information I've found deals with reading I/O streams into a data set using an unnamed pipe.  I figure that if I can do that, then I could at least use CALL SYMPUT to then assign the return value to a macro variable.  However, I cannot get SAS to read in the return value.
An example of what I've been trying is,
filename getfile pipe "C:\temp\GetFilePath.vbs";

data test;
  infile getfile;
  input path $;
run;

The prompt opens, but the return value is not assigned to path.

A: Just replace the last line of your vbscript file as follows:
WScript.StdOut.Write GetFilePath()

And adjust your sas code like so (no need to declare a filename):
data test;
  infile "cscript.exe C:\temp\GetFilePath.vbs" pipe;
  input path:$100.; /* adjust length as appropriate */
run;

The 'trick' was to write the output to STDOUT, rather than echo.  In addition, as per this answer, the cscript.exe was necessary (for me, in Windows 2012) when calling the .vbs, to keep the output in the console - rather than bounce it back as a window.
By the way, kudos for a neat approach. I hadn't appreciated how SAS could be used to launch (and read back from) graphical apps in this way!
Here is the minimal working example I used for testing:
' GetFilePath.vbs
Option Explicit
Function GetFilePath()
  GetFilePath  =  InputBox("Provide a value for SAS")
End Function
WScript.StdOut.Write GetFilePath()

On the SAS side:
data _null_;
  infile "cscript.exe C:\Temp\aaa.vbs" pipe;
  input; putlog _infile_;
run;

redpajama_set_name: RedPajamaStackExchange


text:
Q: TypeError: iteration over a 0-d array, using numpy I'm using this code, straight from the scikit-learn page. It creates a dictionary:
symbol_dict = {
    'TOT': 'Total',
    'XOM': 'Exxon',
    'CVX': 'Chevron',}
symbols, names = np.array(symbol_dict.items()).T

But I get an error:
TypeError: iteration over a 0-d array

This code is straight from the example code, so I have no idea what's going wrong.

A: As user2357112 said, in Python 3 dict.items() returns a dictionary view object rather than a list of key-value pairs (the difference is explained here). Wrapping it in list() creates a list which is something NumPy can turn into an array:
np.array(list(symbol_dict.items()))


text:
Q: Why CUDA Occupancy is defined in terms of number of active warps over max warps supported The occupancy is defined to be the number of active warps over the number of max warps supported on one Stream Multiprocessor. Let us say I have 4 blocks running on one SM, each block has 320 threads, i.e., 10 warps, so 40 warps on one SM. The Occupancy is 40/48, assuming max warps on one SM is 48 (CC 2.x).
But in total I have 320 * 4 threads running on one SM, and there are only 48 CUDA cores on one SM. Why the occupancy is not 100%? I am using all CUDA cores...
I am pretty sure I am missing something...

A: Because occupancy has nothing to do with cores. CUDA is a pipelined SIMD style architecture. Your 48 cores are fed per warp instructions from a pipeline (dual issued, in fact). You need a lot of warps to keep the instruction pipeline full, otherwise all the cores will stall. That is why occupancy is a somewhat useful metric for quantifying the ability of a given kernel to supply enough parallel work to achieve reasonable performance.


text:
Q: Will my page get unindexed by google if i delete it's link from my website I am working on a website which is an online webinar training . As the link is removed from the website will it effect the index page?will that page be unindexed by google?

A: Your page will be ranked higher the more links refer to your page.
Which link do you want to remove?
Do You want to delete www.google.com from your page?


text:
Q: Can I route request based on operation? I have an endpoint that accepts two different operations, GET and DELETE.
Can I route requests to the same endpoint to different services based on operation in my dispatch.yaml?
This is how I would like to do in my dispatch.yaml:
dispatch:

  - url: "*/customer/example/uri/"
    operation:GET
    service: aservice

  - url: "*/customer/example/uri/"
    operation:DELETE
    service: anotherservice

A: No, dispatch.yaml can only route based on url.


text:
Q: What is the definition of $I(Z)$ when $Z \subseteq Proj S$ Let $S$ be a graded ring. In the notes of Ravi Vakil,
he only says "define $I(Z) \subseteq S_+$", when $Z \subseteq Proj S$, where
$S_+$ is all the elements in $S$ that are sum of positive degree homogenous elements in $S$.
He doesn't give the exact definition. Could someone please tell me
how $I(Z)$ is defined? Thanks!


text:
Q: Increase first load speed in laravel project i am new in laravel. I did worked in codeigniter for more than 40 projects but did not faced any load issue. Now in new project we are working in laravel, where i just setup and checked laravel then it founds that it load some time in first load. Once load then it works ok, but each time when new session is start after open browser then it takes some time approx 2 seconds evenif there is simple hello page.  Any suggestion to improve this ?

A: 1- check the console for any errors , maybe there is a loop not closed.
2- second : you can install some debugging packages like
https://github.com/barryvdh/laravel-debugbar


text:
Q: Python: Cast time module as string I have a string in a piece of python code which I want to add a time stamp too. However, when I try to cast the timestamp to a string I get the data type, rather than  a string representation of the timestamp.
The code looks like this,
timeStamp = "TIME-" + str(time)
print timeStamp

>>> Time-<module 'time' (built-in)>

How do you cast a timestamp as a string to allow it to be concatenated with another string?

A: You imported just the time module and turned that into a string; you need to call the time.time() function:
timeStamp = "TIME-" + str(time.time())

A: Maybe You or someone else will use this answer:
from datetime import time

timeStamp = "TIME-" + str(time())
print timeStamp

time() is actually datetime.time()
Cheers.


text:
Q: How do I check the memory used by an activeX control in IE? There is an aspx page which uses the  OWC Spread Sheet Active X control which loads an excel sheet,  but sometimes the browser becomes busy/slow.
I would like to see the stats of this ActiveX control like memory used, CPU load... etc
I tried using Process Explorer and NTSD but could not trace it.
Can anybody give me a hand please?

A: I don't know if this helps as you're asking about IE, but you might want to take a look at Google Chrome. In Chrome, ActiveXs run as a separate process. Using the browser's build-in task manager you can see exactly how much memory the ActiveX is consuming (as well as how much CPU and networking).
As for IE, you can try creating a version of the web page that does not include the ActiveX, and see how much memory IE uses. Then, load the original page that does contain the ActiveX, and see the difference in memory consumption. It will not be accurate, but it could give you the hint you need.

A: As ActiveX controls generally (and in this case always) run in-process, there's no way to directly tell how much memory a given control is using.  You have to run side-by-side experiments.  You probably could try to track allocations and frees using a profiler, but this would be a painstaking process to put it mildly.


text:
Q: How do I restrict access to a static s3 website to a VPN I'm trying to secure access to an internal static website.
Everyone in the company is using a VPN to access our Amazon VPC so I would like to limit access to that site if you're using the VPN.
So I found out this documentation on AWS to use VPC endpoint which seems to be what I'm looking for.
So I created a VPC endoint with the folowing policy.
{
  "Statement": [
    {
        "Action": "*",
        "Effect": "Allow",
        "Resource": "*",
        "Principal": "*"
    }
  ]
}

On my S3 bucket, I verified that I could access index.html both from the regular Web and from the VPN.
Then I added the following bucket Policy to restrict to only the VPC Endpoint.
{
  "Id": "Policy1435893687892",
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1435893641285",
      "Action": "s3:*",
      "Effect": "Allow",
      "Resource": "arn:aws:s3:::mybucket/*",
      "Principal": {
        "AWS": [
          "arn:aws:iam::123456789:user/op"
        ]
      }
    },
    {
       "Sid": "Access-to-specific-VPCE-only",
       "Action": "s3:*",
       "Effect": "Deny",
       "Resource": ["arn:aws:s3:::mybucket/*"],
       "Condition": {
         "StringNotEquals": {
           "aws:sourceVpce": "vpce-1234567"
         }
       },
       "Principal": "*"
     }
  ]
}

Now Regular Web gets a 403 but I also get a 403 when I'm behind the company VPN.
Am I missing something?

A: @Michael - sqlbot is right.
It seems what you are doing is restrict access to the S3 bucket where you store that static web content to requests coming from a particular AWS VPC, using a VPC endpoint.
VPC endpoints establish associations between AWS services, to allow requests coming from INSIDE the VPC.
You can't get what you want with VPC and S3 ACL configuration, but you can get it with ACL and some VPN configuration.
Let's assume connecting to your company's VPN doesn't mean that all the traffic, including Internet traffic between the VPN clients and AWS S3 will be routed through that VPN connection, because that's how sane VPN configuration usually works. If that's not the case, ommit the following step:

*

*Add a static route to your S3 bucket to your VPN server configuration, so every client tries to reach the bucket through the VPN instead of trying to establish a direct internet connection with it. For example, on OpenVPN, edit server.conf, adding the following line:
push "route yourS3bucketPublicIP 255.255.255.255"
After that you will see that when a client connects to the VPN it gets an extra entry added to its routing table, corresponding to the static route that tells it to reach the bucket trough the VPN.

*Use S3 bucket ACLs "IpAddress" field to set the configuration you want. It should look something like this:

.
{
  "Version": "2012-10-17",
  "Id": "S3PolicyId1",
  "Statement": [
    {
      "Sid": "IPAllow",
      "Effect": "Allow",
      "Principal": "*",
      "Action": "s3:*",
      "Resource": "arn:aws:s3:::examplebucket/*",
      "Condition": {
         "IpAddress": {"aws:SourceIp": "54.240.143.0/24"},
         "NotIpAddress": {"aws:SourceIp": "54.240.143.188/32"}
      }
    }
  ]
}

You use IpAddress field to allow an IP or range of IPs using CIDR notation, and NotIpAddress field the same way for restricting an IP or range of IPs (you can ommit that one). That IP (or range of IPs) specified on IpAddress should be the public address(es) of the gateway interface(s) that route(s) your company's VPN Internet traffic (the IP address(es) S3 sees when somebody from your VPN tries to connect to it).
More info:
http://www.bucketexplorer.com/documentation/amazon-s3--access-control-list-acl-overview.html
http://aws.amazon.com/articles/5050/
http://docs.aws.amazon.com/AmazonS3/latest/dev/example-bucket-policies.html#example-bucket-policies-use-case-3
https://openvpn.net/index.php/open-source/documentation/howto.html

A: Actually, @Michael - sqlbot was right until until May 15, 2015. What you do is correct. You found the documentation (again, correctly) that allows you to set up S3 bucket within VPC (probably with no access from outside world), the same way you set up your EC2 machines. Therefore,

On my S3 bucket, I verified that I could access index.html both from the regular Web and from the VPN.

is a problem. If you didn't make mistakes, you shouldn't be able to access the bucket from regular Web. Everything that you did afterwards is irrelevant - because you didn't create S3 bucket inside your VPN-connected VPC.
You don't give much details as to what you did in your very first step; the easiest is probably to delete this bucket and start from the beginning. With the need to set up route tables and what not it is easy to make a mistake. This is a simper set of instructions - but it doesn't cover as much ground as the document that you followed.
But any links that predate this capability (that is, any links before May 2015) are irrelevant.


text:
Q: Recommended way to transform map after using groupBy in Scala? I have a Java enum being used from a dependency, and want to create a map from it.
Let's say the enum is called "SomeEnum1":
BLUE(SomeEnum1.builder()
    .someOtherIdentifier("ABC")
    .someImportantField("DEF")), ...
RED( //etc

I am able to use groupby and get a Map from the "someImportantField" value to a list of SomeEnum1:
SomeEnum1.values.groupBy(x => x.someImportantField)

But upon doing this, I get a Map[String, Array[SomeEnum1]] when what I want is a Map[String, Array[String]]. I've tried using:
SomeEnum1.values.groupBy(_.getSomeImportantField).mapValues(_.name)

But I get an error that name does not a member of Array[....SomeEnum1].
Is there some other way I can transform the resulting arrays to contain the enum names instead of the enum itself?

A: You're missing a loop:
SomeEnum1.values.groupBy(_.getSomeImportantField).mapValues(_.map(_.name))

mapValues iterates over each Map value, which is an array of enums. For each of these arrays you want to convert each element to a String.


text:
Q: How to create a folder to store files generated in a loop? I need to do the following in my program:
a) Ask the user to enter the name of a folder to be created in my directory
b) create the folder
c) generate the files inside the folder
The files to be generated are different texts extracted from a book using REGEX. I want the program to loop throughout the REGEX matches and automatically put each match in a file (each text matched in a file). These text files need to be stored in this newly created folder named by the user.
My program creates the folder but only the first text was written to a file inside this new folder. It seems that the error is in the loop. The warning message is:

Chapter1.txt Traceback (most recent call last):   File
  "/Users/nataliaresende/Dropbox/PYTHON/word_concatenator_final.py",
  line 375, in
      menu()   File "/Users/nataliaresende/Dropbox/PYTHON/word_concatenator_final.py",
  line 365, in menu
      separate_chapters()   File "/Users/nataliaresende/Dropbox/PYTHON/word_concatenator_final.py",
  line 224, in separate_chapters
      os.makedirs(folder)   File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/os.py",
  line 221, in makedirs
      mkdir(name, mode) FileExistsError: [Errno 17] File exists: '/Users/nataliaresende/Dropbox/PYTHON/folder'

Does anyone have an idea of what's going on? Maybe identation?
us=input('\n\nEnter the name of the book or file: ')

    pat = re.compile(r'(?<=\[@CHAPST@\]).+?(?=\[@CHAPFN@\])')
    my_chapters=[]

    with open(us, 'r', encoding="utf-8") as file:
        for i in pat.findall(file.read()):
            my_chapters.append(i)

    print('\n\nThis book contains',len(my_chapters), 'chapters')

    user2=input('\n\nWrite chapters to a file? | Y/N: ')

    if user2 =='Y':
    folder_name=input("Name your folder. E.g. 'Texts': ")
    folder=os.path.join('/Users/nataliaresende/Dropbox/PYTHON/', folder_name)
    os.makedirs(folder)

    for j in range(len(my_chapters)):
        chap='Chapter'+str(j+1) +'.txt'.format(folder_name)
        file = os.path.join(folder, chap)

        with open(file, "w") as f:
            for item in my_chapters[j]:
                f.write("%s" % str(item))
        print('\n\n', chap)

print('\n\nChapters 1 -',len(my_chapters), 'written to a file separately. Check your folder named "Chapters" in your directory')

A: You need to check if that folder exists, and if exists skip creating it:
if not os.path.exists(folder):
    os.makedirs(folder)


text:
Q: Generic Types, compiler and dynamic languages In a public tender was the following statement:
"The use of generic types in object-oriented programming helps type checking at compile time."
it's true or false?
I believe it is false because the type checking compiler does not improve and this not have relation with object-oriented but in the type of language (weak-typing or strong-typing).
Someone please help me explain why this statement is false.

A: The statement is true.  With generic types you specify a type when you instantiate the object and its use may be checked at compile time.  Without a type parameter on a class there is no way to check.


text:
Q: com.sun.faces.config.ConfigurationException: no web.xml present I programmed an application with JSF and some other fraeworks. Then I destroyed my metadata with maven and then I created a new project and imported all my classes and config files into the new project. So that I have clean metadata. The Project can be built without problems now. But when I want to start it onto tomcat I get the following exception:
com.sun.faces.config.ConfigurationException: no web.xml present
 at com.sun.faces.config.ConfigureListener$WebXmlProcessor.scanForFacesServlet(ConfigureListener.java:785)
 at com.sun.faces.config.ConfigureListener$WebXmlProcessor.<init>(ConfigureListener.java:745)
 at com.sun.faces.config.ConfigureListener.contextInitialized(ConfigureListener.java:173)
 at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4135)
 at org.apache.catalina.core.StandardContext.start(StandardContext.java:4630)
 at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
 at org.apache.catalina.core.StandardHost.start(StandardHost.java:785)
 at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
 at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:445)
 at org.apache.catalina.core.StandardService.start(StandardService.java:519)
 at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
 at org.apache.catalina.startup.Catalina.start(Catalina.java:581)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
 at java.lang.reflect.Method.invoke(Method.java:597)
 at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
 at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)

But there is definitely a web.xml in that project. Has somebody an idea where my mistake could be? Thank you

Update

*

*Yes I am using m2Eclipse!

*My directory tree looks like:
OLD
My Servlet is there as well:
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>
      javax.faces.webapp.FacesServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

UPDATE2

*

*Directories (after BalusC Commend):
Here I have found a good Manual about Maven Web Projects. But unfortunately the problem stayed the same.
My directory structure looks like:

UPDATE3
Response to Pascal's comment:

*

*mvn clean compile is successfull

*mvn install throws a build error:
[INFO] Error assembling WAR: webxml attribute is required (or pre-existing WEB-INF/web.xml if execut ing in update mode)
I executed those commands from windows console

Maybe the problem is something else. There is another Warning while starting the server:
27.08.2010 09:04:52 org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNUNG: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.j2ee.server:studentportal' did not find a matching property.

Maybe that helps?

A: Some pointers. Is the web.xml placed at WEB-INF/web.xml ?
From the source code, this particular exception is thrown at:
InputStream in = context.getResourceAsStream(WEB_XML_PATH);
            if (in == null) {
                if (context.getMajorVersion() < 3) {
                    throw new ConfigurationException("no web.xml present");
                }
            }

and it's looking for web.xml at
private static final String WEB_XML_PATH = "/WEB-INF/web.xml";

So it did not find the web.xml.
Also for some reason it's expecting Servlet 3.0 which is only available with Tomcat 7.0 - but I think the main issue should be the presence of web.xml
Finally, it will also be looking for the defined servlet in the web.xml like below
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

A: I started a new project and moved one part at once. After that it works. Unfortunately I have no idea where the problem was -.-
But creating a new empty project and moving all the files (except config files, I wrote them again) is a reasonable approach..


text:
Q: Query timing out, how can I optimize this? This query is timing out
SELECT s.TriggeredSendCustomerKey,
COUNT(s.TriggeredSendCustomerKey ) as TotalOpens
FROM [01_Individual_Emails_Sent_Last_Month_SDV] s with (NOLOCK)
JOIN _Open o with (NOLOCK)
ON s.SubscriberKey = o.SubscriberKey
AND s.TriggeredSendCustomerKey = o.TriggeredSendCustomerKey
GROUP BY s.TriggeredSendCustomerKey

I tried writing it like this, but this produced the ever so helpful generic 'System Error'
SELECT o.TriggeredSendCustomerKey,
COUNT(o.TriggeredSendCustomerKey ) as TotalOpens
FROM _Open o with (NOLOCK)
WHERE o.SubscriberKey IN (
SELECT SubscriberKey FROM [01_Individual_Emails_Sent_Last_Month_SDV] s with (NOLOCK)
)
GROUP BY o.TriggeredSendCustomerKey

The 01_Individual_Emails_Sent_Last_Month_SDV is a Data Extension that contains about 3.3 million records from October. I pull this first to narrow down results. I don't want to add any date logic here, because it will screw up the TotalOpens number I get if I run later in the month (opens continue to get added to the _Open table and associated with a send even if the open occurs in the next month)
Any thoughts?

A: You are best limiting the query on _Open within a date range as it's otherwise a very heavy table to go querying. You will be limited to 180 days of the query anyway.
Also consider counting only unique opens, rather than every one - this will reduce your load.
Your first query (Join) will likely be more performant that your 2nd query -
The SQL query process time is limited to 30 mins - however you can raise a support request to have this increased (by exception). It wouldn't be advisable tough to increase beyond 120 mins.
You could also try something like below:
Select DISTINCT
SubscriberKey,
TotalOpens
FROM (

SortOrder = Row number() over (PARTITION by s.SubscriberKey ORDER BY TotalOpens DESC)
,s.SubscriberKey
,COUNT(s.TriggeredSendCustomerKey) as TotalOpens

FROM [01_Individual_Emails_Sent_Last_Month_SDV] s with (NOLOCK)
LEFT JOIN _Open o with (NOLOCK) ON s.SubscriberKey = o.SubscriberKey

Where DateDiff(d,o.EventDate,GetUTCDate()) between 0 and 30
And o.SubscriberKey is not null

) z
where SortOrder = 1


text:
Q: Can't find templatefile I have a beego project in IdeaProject. The structure is like this:
MathApp
├── conf
│   └── app.conf
├── main.go
├── main_test.go
└── views
    ├── invalid-route.html
    └── result.html

However, it shows the error can't find templatefile in the path:views/result.html. I have set the gopath as C:/gopath.
Any suggestion?

A: You can see the code producing this error in template.go
This issue mentions:

Please use the bee run, as go get install the binary into the gopath/bin, while the static file still in the gopath/src/myproject.


text:
Q: Angular 9 Locale data for 'en-US' cannot be found. No locale data will be included for this locale I am getting this strange warning
Locale data for 'en-US' cannot be found.  No locale data will be included for this locale
 when running ng build --configuration=prod --localize
here is my angular.json
// omitted
"i18n": {
    "sourceLocale": "en-US",
    "locales": {
      "sr-Latn": {
        "translation": "src/locale/messages.sr.xlf",
        "baseHref": "/sr/"
      }
    }
  },
// omitted

The documentation clearly states en-US is imported by default.
To make things worse, when i change sourceLocale to any other language (say 'de'), warning message goes away.
Manually registering en-US locale data doesnt help either

A: It is working if you set sourceLocale to en.

*

*But i cant figure out why the default value en-US dosnt work.

"i18n": {
    "sourceLocale": "en",
    "locales": {...}
}

A: With the most recent version 9.0.2 you can specify the sourceLocale baseHref
"i18n": {
    "sourceLocale": {
      "baseHref": "/",
      "code": "en"
    },
    "locales": {
      "fr": "src/locale/messages.fr.xlf",
      "de": "src/locale/messages.de.xlf",
      "es": "src/locale/messages.es.xlf",
      "it": "src/locale/messages.it.xlf",
      "ja": "src/locale/messages.ja.xlf",
      "ko": "src/locale/messages.ko.xlf",
      "zh": {
        "translation": "src/locale/messages.cn.xlf",
        "baseHref": "/cn/"
      }
    }

A: This is annoying indeed. The compiler expects to have en-US resource and even compiles the application using en-US and base-href.
This is how I solved this.
1) I just ignore the warning and en-US output directory.
2) I compile the application twice. First without --localized option. This compiles the original application, uses \ as base-href and does not used any translation files. Then I compile another time with --localized and that compiles all my languages with base-href matching the language codes.
ng build --prod --outputPath=dist/original
ng build --prod --outputPath=dist/localized --localize

3) I deploy the original build from dist/original and all the other builds from dist/localized except the en-US directory.

A: I have the same problem.
Like you said, the default for LOCALE_ID seems to be en-US, as this is what it represents when nothing is specified.
Further, looking at @angular/common/locales/* it seems like, the default for registerLocaleData is en. @angular/common/locales/en exists, @angular/common/locales/en-US does not exist!
Same with de-DE: @angular/common/locales/de-DE does not exist, but @angular/common/locales/de does.
For now, I have switched everything to en/de and it works:

Example localising for English and German:
angular.json
[...]
      "i18n": {
        "sourceLocale": "en",
        "locales": {
          "de": "src/locale/messages.de.xlf"
        }
      }
[...]

app.module.ts
[...]
import { registerLocaleData } from '@angular/common';
import localeDe from '@angular/common/locales/de';
import localeEn from '@angular/common/locales/en';

registerLocaleData(localeDe, localeEn);
[...]

A: Maybe it has to do with that fact that the file is named en-US-POSIX as seen here https://github.com/angular/angular/blob/master/packages/common/locales/en-US-POSIX.ts
Trying to dynamically import('@angular/common/locales/en-US-POSIX') works.
So trying this might work
"i18n": {
    "sourceLocale": "en-US-POSIX",
    "locales": {...}
}


text:
Q: Button underline text on hover I am working with JavaFX, and I have a Scene object I created in SceneBuilder with a bunch of Button objects. I want the text of each of these Button objects to be underlined when the mouse cursor enters their area in the window, and to remove the underlining when the cursor leaves.
I know I can just type:
public class Controller {

    @FXML
    private Button exitButton;

    public void exitButtonMouseEntered() {

       this.exitButton.setUnderline(true);
    }

    public void exitButtonMouseLeft() {

       this.exitButton.setUnderline(false);
    }

}

However, doing this for each Button object is time-consuming, and it seems like there must be an easier way to force all the Button objects to have the same behavior given the same conditions.
How can I make a controller method that will affect all the Buttons in the Scene?

A: Apply the following css:
Button:hover{
    -fx-underline: true;
}


text:
Q: xlsxwriter unable to write more than 1,048,576 rows to multiple tables and worksheets I have found that xlsxwriter supports the limits set by Excel Total number of       1,048,576 rows by 16,384 columns rows and columns on a worksheet.
https://support.office.com/en-us/article/excel-specifications-and-limits-1672b34d-7043-467e-8e27-269d656771c3
https://xlsxwriter.readthedocs.io/worksheet.html?highlight=1%2C048%2C576
As my data is more than 1048576 row I am writing it to a unique table in a unique worksheet, I have tried setting the limit to 1000000 rows per table per worksheet and I get multiple tables and worksheets but only up to 1,048,576 rows.
I guess the question is can the workbook support more than 1,048,576 rows? If so there seems to be a problem, anybody any experience in writing beyond that?
Thanks

A:
can the workbook support more than 1,048,576 rows?

No. That is the maximum row number that Excel supports per worksheet.
Update:
Here is an example that creates 1,048,576 rows in 2 worksheets:
import xlsxwriter

workbook = xlsxwriter.Workbook('row_file.xlsx')

for _ in range(2):
    worksheet = workbook.add_worksheet()

    for row in range(1048576):
        worksheet.write(row, 0, 'Hello')

workbook.close()

Output:


text:
Q: sending message in android two times instead of once I want to send SMS after call ends, my app sends the SMS but the problem is that it is sending it twice in every call and I don't know where the problem is (I want to send one sms every time not twice)
Here is my code:
public class Receiver extends BroadcastReceiver {
  SmsManager smsmanager=SmsManager.getDefault();
  public void onReceive(Context context, Intent intent) {

  if (phoneNumber != null){

     telephonyService.endCall();
     smsmanager.sendTextMessage(phoneNumber, null, "message", null, null);

  }
}

on Manifest:
<receiver  android:name=".Receiver">
        <intent-filter  android:priority="100" >
            <action android:name="android.intent.action.PHONE_STATE" />
        </intent-filter>
    </receiver>

A: Your Receiver will be called every time the phone state changes (ringing, in call, ...).
You must filter the corresponding action:
  // Keep track of the previous state
  String previousState;

  public void onReceive(Context context, Intent intent) {
    String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
    if (CALL_STATE_IDLE.equals(state) && CALL_STATE_OFFHOOK.equals(previousState) {
      // send sms here
    }
    previousState = state;
  }


text:
Q: Defer all script-Tags Is there a way to add a defer-Attribute to ALL <script>-tags without doing it manually?
Because I want to defer an included external js-file, but this is required for other function on the website.


text:
Q: Hibernate - how to load different view of same object How is this called and how to solve my next problem on API. I have to return same object with different views. Some data should not be returned to user. Here is example:
Parent:
public class OrginalObject{
    private int id;
    private String name;
    private String surname;
    private int age;
    private String school;
    private String secret;
    private Address Address;

child:
public class Address{
    private int id;
    private String street;
    private String zipCode;
    private String Country;

If i want to load list of complete objects i would call:
session.createCriteria(OrginalObject.class).list();

1.) But if don't want someone to know my property secret, i need to hide it. But i don't know how to call it from database the way it would have every other property. Something like:
session.createCriteria(OrginalObjectPublic.class).list();

2.) Also I would like to have option to load only "important" data. That means only properties id, name, school.
session.createCriteria(OrginalObjectImportant.class).list();

Is there a way to do an adapter/"custom view" to directly load it from database? I know i can write pure sql, but i would like to use it on objects with 20+ properties that have nested lists/objects.
3.) Also how to use this transformation to load only few properties of nested object with those from orginal. Example json (only id, name, school from OrginalOBject and id, street from Address:
{
    "id": 1,
    "name": "testname",
    "school": "testschool",
    "Address": {
    {
        "id": 33,
        "street": "testStreet 33"
    }
}

4.) also how to use it on nested Lists if Address would be array:
public class OrginalObject{
    ...
    private List<Address> AddressList;

A: Since hibernate is a persistence-framework and you can not save/persist to a view, this is not possible. Yes you can make a view having the name like the table and preferr the view but you will not be able to store to that entity anymore.

*

*You can remove the getter (getSecret) from the entity. So the database still have the field but your entity is not aware of it. This may cause problems if you try to store data using that entity, you may not be able to set the secret.

*You can make the getter default (package-level-access) and seal the package to let noone else than the sealed projects access the getter.

*You can use spring's method authorization mechanism

A: First no one have access to your secret,
only you the programmer who is supposed to see it.
Second if no one is supposed to have it why store it.
And if you want to pull it out you can use inheritance.
something like
public abstract PublicObject {
    ...
}

public OriginalObject extends PublicObject {
    String secret;
}

Edit:
2nd & 4th questions you can solve them with hql:
String hql = "SELECT O.id, O.name, O.school FROM OrginalObject O";
Query query = session.createQuery(hql);
List results = query.list();

as for your 3th question it depends on your api. if you're using jackson for example you can use @JsonIgnore

A: You can map more than one entity to the same table, each one with the set of properties you want to expose.
Take a look to this question.


text:
Q: SPARQL Parse Error: unexpected terminal I've been using gruff to create and execute some simple SPARQL queries, but have run into some trouble. The following query works (prefixes have been left out):
SELECT ?k
WHERE
{ ?k  rdf:type  uw:pcservice . }

However, when I introduce the COUNT function, as seen below, I get the following error in gruff:
Error: Parse error: unexpected terminal ( (value: :|(|).
Expected terminals: (* varname reduced distinct).
[condition type: sparql-parse-error-unexpected-terminal]
SELECT (COUNT(?k) AS ?count)
WHERE
{ ?k  rdf:type  uw:pcservice . }

Not sure what is causing this. Any clues would be appreciated. Thanks.

A: Given the error it sounds like this tool doesn't support SPARQL 1.1. It's expecting a vanilla SELECT [*|varname|reduced|distinct], excluding aggregates and assignment.


text:
Q: BroadcastReceiver not working when app is installed on sd card I am creating a EventsManager app in which i have a BroadcastReciver which executes for BOOT_COMPLETED broadcast.this receiver has been used to re-register all the events with AlarmManager.If the app is installed on phone's memory the it works fine but in the case of sd card  BOOT_COMPLETED broadcast is not being delivered to broadcast receiver.
pls help..

A: Quoting the documentation:

In order for your application to consistently behave as expected, you should not allow your application to be installed on the external storage if it uses any of the following features... The system delivers the ACTION_BOOT_COMPLETED broadcast before the external storage is mounted to the device. If your application is installed on the external storage, it can never receive this broadcast.

Hence, you cannot allow your app to be installed to external storage.


text:
Q: Do `normalize_entity()`, `add_relationships()` are logically same in featuretools? Example:
buy_log_df = pd.DataFrame(
    [
        ["2020-01-01", 0, 1, 2, 2, 200],
        ["2020-01-02", 1, 1, 1, 3, 100],
        ["2020-01-02", 2, 2, 1, 1, 100],
        ["2020-01-03", 3, 3, 3, 1, 300],
    ],
    columns=['date', 'sale_id', 'customer_id', "item_id", "quantity", "price"]
)

es = ft.EntitySet(id="sale_set")
es = es.entity_from_dataframe(
    "sales",
    dataframe=buy_log_df,
    index="sale_id",
    time_index='date'
)
es = es.normalize_entity(
    new_entity_id="items",
    base_entity_id="sales",
    index="item_id",
    additional_variables=["price"],
)

buy_log_df = pd.DataFrame(
    [
        ["2020-01-01", 0, 1, 2, 2],
        ["2020-01-02", 1, 1, 1, 3],
        ["2020-01-02", 2, 2, 1, 1],
        ["2020-01-03", 3, 3, 3, 1],
    ],
    columns=['date', 'sale_id', 'customer_id', "item_id", "quantity",]
)
item_df = pd.DataFrame(
    [
        [1, 100],
        [2, 200],
        [3, 300],
    ],
    columns=['item_id', 'price']
)

es = ft.EntitySet(id="sale_set")
es = es.entity_from_dataframe(
    "sales",
    dataframe=buy_log_df,
    index="sale_id",
    time_index='date'
)
es = es.entity_from_dataframe(
    "items",
    dataframe=item_df,
    index="item_id",
)
from featuretools import Relationship
es = es.add_relationships(
    [Relationship(es['items']['item_id'], es['sales']['item_id'])],
)

It looks like the es of the above two are the same.
I'd like to know whether there is a specific case where ONLY normalize_entity() is allowed or so.

A: Thanks for the question. That's correct. The two entity sets are the same. There aren't cases where only normalize_entity() can be used. Changes made by this method such as adding relationships can also be done manually.


text:
Q: How to Create multiple Dependent beans for a class Without using XML File? I have created a Spring Project With 2 Model classes, one dependent on other With @Autowired.
How can I Inject fully created Son Object in the John Class.
Currently I am getting Null Value for the other class.
package com.example.demo;

import org.springframework.stereotype.Component;

@Component
public class Son {

    private String sonAge;

    public String getNewsName() {
        return sonAge;
    }

    public void setNewsName(String sonAge) {
        this.sonAge = sonAge;
    }

    @Override
    public String toString() {
        return "Son [sonAge=" + sonAge + "]";
    }

}

    package com.example.demo;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    import org.springframework.stereotype.Controller;

    @Component
    public class John {

        private Son son;

        public Son getSon() {
            return son;
        }
        @Autowired
        public void setSon(Son son) {
            this.son = son;
        }
        public John() {

        }
        @Override
        public String toString() {
            return "John [son=" + son + "]";
        }

}

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
public class NewTestDependApplication {

    public static void main(String[] args) {
        SpringApplication.run(NewTestDependApplication.class, args);

          ApplicationContext context = new AnnotationConfigApplicationContext(NewTestDependApplication.class);
          John john = (John)context.getBean("john");
         System.out.println(john);

    }

}

The Output I am getting is "John [son=Son [sonAge=null]]"
sonAge is coming null, how to create a son object and inject it.
I want to create 10 Different object of John with 10 Different object of Son, all will have a different value.
I don't want to use XML or @Bean Method to Create the Object.
I am new to the Concept so cut me some slack.

A: If you want to give Son an age you could set during initialization of the field:
private String sonAge = "thousand";. Other than that I don't see any other option if @Bean is not liked from your side.
If you want to have multiple instances of these you will need to use some Qualifiers.
Here an example:
@Configuration
public class SonConfig {

    @Bean
    @Qualifier("son1")
    public Son son1() {
        // Set what ever you like here
        final Son son = new Son();
        return son;
    }
}

Which then could be used in John using the qualifier:
@Component
public class John {
    ...

    @Autowired
    @Qualifier("son1")
    public void setSon(final Son son) {
        this.son = son;
    }
    ...
}

If you are not only doing this for learning purpose I'd suggest using some kind of persistence solution or something similar. Hard to say without knowing any use case but using dependency injection for models usually does not really add up.
Hope it helps.


text:
Q: Can I have a user database synced with SugarCRM and use it mostly for emailing? I work for a company that has a website with about 700,000 users, it would need a tool that would:

*

*List all users

*Email users, create templates, send a newsletter

*Show products a user has purchased

*If you find a user, show which emails have been sent to the user

*Create automated tasks, example: send an email to every user that has a product expiring in 30 days

I'm not sure a CRM can do all theses things, I wanted to try a CRM to figure out how close can I get to having a tool that can do all this. I read that SugarCRM is pretty good, and its free so I'm going to try it out.
What I wanted to know is, using the REST or SOAP api of SugarCRM, can I synchronise all my users with the SugarCRM database ? Or for example each time a user is created on our website, insert it in the database.
And then each time we send an email with our website, use SugarCRM instead to send a mail, and store the data. So that we can view which emails have been sent to specific users.
Thank you

A: Yes you can do all that but it may require some customisation to suit it exactly to your needs. By 'users' I assume you are referring to Customer 'Accounts' as known on the SugarCRM?

A: Add custom fields to the Contacts module using Studio. The easiest and quickest way to get your data in will be directly to the database.
The standard fields in Sugar Contacts go in the contacts table. Your custom fields will have "_c" appended to their names and be created in the contacts_cstm table. The two tables are related by contacts.id = contacts_cstm.id_c, which is generally a GUID field (but can be any string value if you need it to be).
Then you need to have a process to add new users in your website into sugar. I suggest polling your user db periodically to look for new records and using the SOAP/REST API (good luck though, it's fairly horrible) to insert them into Sugar.
Other than that your use case is pretty much standard Sugar. For automated tasks which happen whenever an email is sent/received or when a new contact is created, you'll want to look at logic hooks, search for logic_hooks.php in the Sugar documentation.


text:
Q: JFoenix Drawer .hide(); and .drawer(); functions are not working I am tired on this point, JFoenix Drawer .hide(); and .drawer(); functions are not working
try {
    VBox box = FXMLLoader.load(getClass().getResource("/chatroom/ui/chatingwindow/DrawerContent.fxml"));
    drawer.setSidePane(box);

    HamburgerBackArrowBasicTransition arrowBasicTransition = new HamburgerBackArrowBasicTransition(hamburger);
    arrowBasicTransition.setRate(-1);
    hamburger.addEventHandler(MouseEvent.MOUSE_PRESSED, (e) -> {
        arrowBasicTransition.setRate(arrowBasicTransition.getRate() * -1);
        arrowBasicTransition.play();

        if (drawer.isShown()) {
            drawer.hide();
        } else {
            drawer.draw();
        }
    });

} catch (IOException ex) {
    Logger.getLogger(ChatingWindowController.class.getName()).log(Level.SEVERE, null, ex);
}

why is that, any Jfoenix tutorials are used that functions, but I couldn't use that?

A: It is because they do not exist it should be:
if (drawer.isOpened()) {
        drawer.close();
    } else {
        drawer.open();
    }


text:
Q: How to Send Attachment Data w/ Ionic Cordova EmailComposer I am trying to send an email with an attachment in my Ionic app, using the Phonegap plugin found here. One of the features of this plugin is to attach a file or file as Base64.
The email is sending fine, but it never attaches a file so it makes me think im doing something wrong forming my string. Specifically, I'm attempting to create a CSV, and attach it as a string.
Here's what my call looks like:
if(window.plugins && window.plugins.emailComposer) {
        window.plugins.emailComposer.showEmailComposerWithCallback(function(result) {
            //success callback
        },
        "Feedback for your App", // Subject
        "",                      // Body
        ["whatever@whatever.com"],    // To
        null,                    // CC
        null,                    // BCC
        false,                   // isHTML
        null,                    // Attachments
        [["filename1","data:text/csv;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAA8CAYAAAA6/..."]] // Attachment Data
      );
    }

  };

A: I've been struggling with a similar issue.
Looking in the EmailComposer source for Android the attachmentsData array is treated as follows:
JSONArray fileInformation = attachmentsData.getJSONArray(i);
String filename = fileInformation.getString(0);
String filedata = fileInformation.getString(1);
byte[] fileBytes = Base64.decode(filedata, 0);

So the data part should be pure base64 data.  If you change your line:
[["filename1","data:text/csv;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAA8CA...

to
[["filename1","iVBORw0KGgoAAAANSUhEUgAAADwAAAA8CAYAAAA6/..."]]

you might find it works.


text:
Q: Grails unit tests and cobertura xml file conflict (bug?) To generate xml report from all unit tests in grails (2.1) u will only need tu run grails test-app. This command creates \target\test-reports\TESTS-TestSuites.xml file. I installed Cobertura plugin for coverage reports. By default cobertura creates html report, but I need xml report for jenkins. To get XML file for cobertura u must use -xml option, so the full command looks like: test-app -coverage -xml.
After executing this command, file TESTS-TestSuites.xml was not created and as far as I checked it, this -xml option for cobertura interfere with test-app command.
How to run all tests and generate both xml files for unit tests and cobertura coverage? Is this a bug?


text:
Q: Powershell "Move-Item : The process cannot access the file because it is being used by another process" in ForEach-Object loop I am trying to search through all my photo folders and any images with specific dimensions (1125x2436 - i.e. screen captures on iphone) get moved to a seperate folder which I can review and most likely delete after.
I have taken the script from Writing a script to copy images of certain dimensions as below. This copies the images, but when I change this to Move-Item I get "Move-Item : The process cannot access the file because it is being used by another process." Im guessing because it is still open by System.Drawing.Image in the ForEach-Object loop.
I have tried tweaking this and closing the image before deleting or passing to a variable to use outside the loop but with no success.
This is what I have
$source = Get-Location
$destination = "C:\Users\USER\Desktop\Output\"
$maxWidth    = 1125
$maxHeight   = 2436

# if the destination path does not exist, create it
if (!(Test-Path -Path $destination -PathType Container)) {
    New-Item -Path $destination -ItemType Directory | Out-Null
}

# Add System.Drawing assembly
Add-Type -AssemblyName System.Drawing

Get-ChildItem -Path $source -File -Recurse | ForEach-Object {
    # capture the full filename so we can use it in the catch block
    $fileName = $_.FullName
    # Open image file
    try {
        $img = [System.Drawing.Image]::FromFile($fileName)
        # use '-ge'  if you want to copy files with a width and/or height Greater Or Equal To the max dimensions
        # use '-and' if you want to copy files where both the Width and the Height exceed the max dimensions
        if ($img.Width -eq $maxWidth -and $img.Height -eq $maxHeight) {
    $_ | Move-Item -Verbose -Destination $destination -Force
        }
    }
    catch {
        Write-Warning "Could not open file '$fileName' - Not an image file?"
    }
}

I should say Im a nood to powershell and posting stackoverflow so any advice greatly appreciated. Thanks in advance.

A: After a bit more digging, it was as simple as adding $img.dispose() before the move.
Answered incase useful to anyone else.


text:
Q: How does one target all divs of any webpage but differentiate them in javascript? So I am trying to create an extension in Chrome (a prototype for a project that I am doing) that targets all of the
 tags of any web page, hides them or rather doesn't display them until the user clicks the mouse (further explained below).  So typing a url into the browser yields a white page.  The person clicks, and the first
 appears (probably the mast head or menu).  The user clicks again and the second
 appears.
I have gotten to the point where I can hide or show all
's (the obvious easy part) but I am not sure how to go about targeting each since every website has different id's for them while still using the
 tag. This is what I need the most help with.
This is part of a grander operation called the Web Crank. It's just a physical crank that controls the speed by which a web page loads. Each time you make one full rotation of the crank, one section (the first
) of the web page loads. The faster you go, the quicker the page loads.
I hope this is clear enough.  I am a newbie when it comes to this, but I have done some minor coding in the past and it's not such a big deal.
Thanks for your help!

A: Using just the DOM without any libraries, iterate over this:
document.getElementsByTagName("div")

gets you all the
s on the page. To iterate over them, use a for loop:
var divs = document.getElementsByTagName("div");
for (var i = 0; i < divs.length; i++) {
  /* stuff */
}

In jQuery (which you probably ought not to use in a Chrome plugin...):
$("div").each(function(i) { /* whatever */ });

What you basically want to do is iterate through all the
s and hide them all, then as you crank the crank, have that call an iterator that goes through and adds things back in. Probably what I'd do is create a FIFO queue (like this?) of 'to-be-cranked' elements as you are hiding them, and then as the crank operation fires (however you do that), start pulling items off the queue and showing them again.
As a side issue, why
s though and not just all block-level elements? You probably want to search for
,
,
,
,
,
 and
 elements too.

A: If you can get every div on a page, just stick them in an array and now you can index them.

A: if you can use jQuery then use the .each keyword. that will allow you to itterate through the collection and gather data about them, show/hide etc.


text:
Q: уникальный идентификатор создал класс с выводом данных о пользователе. как мне сделать так, чтобы идентификатор являлся уникальным и работал только на положительные числа, а на отрицательные программа переставала бы работать?
public class User {
int id;
String login;
String password;

public User(int id, String login, String password){
    this.id = id;
    this.login = login;
    this.password = password;
}

}
public class MainUser {
public static void main(String[] args) {

   User[] u = new User[2];
   u[0] = new User(1, "shiva", "ppp");
   u[1] = new User(2, "papa", "gggg");
    for (int i = 0; i < u.length; i++) {
        System.out.println("id = " + u[i].id + ";" + " login = " + u[i].login + ";" + " password = " + u[i].password);
    }

}

}

A: class IdGenerator {
    private static int id = 0;

    public static int generate(){
       return id++;
    }

}

    ...
public class User {

    private id = IdGenerator.generate();
    ....


text:
Q: Windows 10 Pro -version 1803 bluetooth Profiles Access We are looking to access and use Bluetooth profiles in our WPF application using C# in Visual Studio 2017.
Issue details:
Platform: Windows 10 Pro - version 1803.
Issue brief: We are trying to access Bluetooth profiles via desktop(c#) of connected phones, however on windows 10 the profile show enable but the profiles are not working eg: HFP connects, however, the voice is not heard
We have tested this on following Bluetooth devices:
1.Bluetooth CSR 4.0 Dongle (CSR8510 A10) (Note: this Bluetooth connects and show HFP and works as expected, however, the Bluetooth does not show on the device list and hence we cannot connect programmatically using c#)
2.IOGEAR's Bluetooth 4.0 (Model GBU521W6) (Shows on device list and our application can detect a device, however, HFP is not working as expected both from the application or from normal device section)
Required Profiles:
1.Hands-Free Profile (HFP)
2.Message Access Profile (MAP)
3.Phone Book Access Profile (PBAP)
We have Already Tried with following:

*

*Updating drivers

*Tried uninstall install many times

*Used android, ios, and windows phone's

Side note: Our application with same code works on windows 7

A: MAP abd PBAP is not a problem because both are OBEX based (which is RFCOMM).
However there can be some problems with HandsFree. It works great with BlueSoile drivers. But with standard microsoft may not work.
The first step it to use BluetoothSetServiceState with HFP UUID to tell windows to install drivers for your device's HFP profile. If function succeed you should see 2 audio devices appeared in your system: one is Inout and other is Output. You can find them using any media API (DirectSound, legacy API).
To be able to work with PBAP and MAP you need anyhow connect to your device through RFCOMM. WinSock or any other way is good.
Please note that the method above works only with Microsoft Bluetooth drivers. Other drivers (BlueSoleil, Toshiba) have absolutely different API so you have to add it into your application if need to support them.
Or you can simple take a look on BluetoothFramework


text:
Q: How to insert values in certain row from PHP I have the following array that is describing my table header:
$aColumns = array( 'time1.Time', 'time2.Time' , 'time1.id' , 'time1.Signal' , 'v.Name' , 'v.Lastname'  );

I want to insert new values in the time1.id column.
When I process the following code I got my data shown in the first column which is time1.Time and I need it to be in column time1.id why is this happening?
Here is the code:
if ( mysql_num_rows( $rResult ) > 0 )
    {
        $aCols = array_keys( mysql_fetch_assoc( $rResult ) );
        mysql_data_seek($rResult, 0);
        $id= array_search( 'time1.id', $aCols );
        $value= "NEW_VALUE";

        while ( $aRow = mysql_fetch_row( $rResult ) )
        {
            $aRow[$id] = $value;
            $aOutput['aaData'][] = $aRow;
        }
    }

A: Try using id as the column name instead of time1.id. Usually only the column names are returned as keys in the result array , even if you have specified the table names in the select fields.
$id= array_search( 'id', $aCols );


text:
Q: Android : Auto resize view for small screen There is a solution to resize automatically the views of my android app?
I've optimized it for 7" screen.
But now I want to use it on 3.2" screen and it's looking horrible!
I've you got some ideas or I have to do it manually?

A: This would be the first stop I would recommend:
http://developer.android.com/guide/practices/screens_support.html
This document explains the screens-support features provided by the platform and how you use them in your application. By following the practices described here, you can easily create an application that displays properly on all supported device screens and that you can deploy to any device as a single .apk."to any device as a single .apk.
and check this pdf: http://www.vanteon.com/downloads/Scaling_Android_Apps_White_Paper.pdf

A: Define sizes/dimensions in the dimens folder, and set sizes to your Views programatically through Java.
Or, you could set the size based on some ratio, according to the screen size. I mean, you can calculate the width/height of the screen during runtime and make the dimensions of your view screenwidth/x.

A: Please read this tutorials from Android developers:

*

*Supporting Multiple Screens

*Designing for Multiple Screens


text:
Q: how to check the valid Youtube url using jquery In Jquery i want to check the specific url from youtube alone and show success status and others i want to skip by stating it as not valid url
var _videoUrl = "youtube.com/watch?v=FhnMNwiGg5M";
if (_videoUrl.contains("youtube.com"))
{
  alert('Valid');
}
else
{
  alert('Not Valid');
}

how to check with contains. or any other option to check the valid youtube url alone.

A: Typically, the thing that most people want is the youtube video ID.  To simply match this, use the following regex.
var matches = _videoUrl.match(/watch\?v=([a-zA-Z0-9\-_]+)/);
if (matches)
{
    alert('valid');
}

Naturally, the regex could be expanded to include the entire youtube url, but if all you need is the ID, this is the most surefire way I've found.

A: You may try using a regular expression:
var url = 'youtube.com/watch?v=FhnMNwiGg5M';
var isyouTubeUrl = /((http|https):\/\/)?(www\.)?(youtube\.com)(\/)?([a-zA-Z0-9\-\.]+)\/?/.test(url);

A: I found this from the closure library, might be handy:
/**
 * A youtube regular expression matcher. It matches the VIDEOID of URLs like
 * http://www.youtube.com/watch?v=VIDEOID.
 * @type {RegExp}
 * @private
 */
goog.ui.media.YoutubeModel.matcher_ =
    /https?:\/\/(?:[a-zA_Z]{2,3}.)?(?:youtube\.com\/watch\?)((?:[\w\d\-\_\=]+&(?:amp;)?)*v(?:<[A-Z]+>)?=([0-9a-zA-Z\-\_]+))/i;

A: I will give some extra :
For both Youtube and Vimeo to checking those IDs are really vaild or not
var GoogleKey = 'XXXXXXXXXX';
function GetVideoById(id) {
    var site = !isNaN(id) ? 'vimeo' : 'youtube';
    var data = false;
    if(site==='youtube') {
        $.ajax({
            async: false,
            url: 'https://www.googleapis.com/youtube/v3/videos?id='+id+'&key='+GoogleKey+'&part=snippet',
            success: function(r) {
                if(r['items'].length) {
                    data = {'type':'youtube','data':r['items'][0]['snippet']};
                }
            }
        });
    } else {
        $.ajax({
            async: false,
            url: 'http://vimeo.com/api/v2/video/'+id+'.json',
            success: function(r) {
                data = {'type':'vimeo','data':r[0]};
            }
        });
    }
    return data;
}

So Example runs :
if(GetVideoById('YykjpeuMNEk')) {
   // youtube + data
}

if(GetVideoById('162334918')) {
   // vimeo + data
}
if(GetVideoById('999999')) {
   // nothing (because false)
}
if(GetVideoById('abcdefg')) {
   // nothing (because false)
}

A: Assuming you want a Youtube video URL rather than any YouTube URL, you can do it using a regex:
var url = 'youtube.com/watch?v=FhnMNwiGg5M';
var matches = url.match(/^(https?:\/\/)?([^\/]*\.)?youtube\.com\/watch\?([^]*&)?v=\w+(&[^]*)?/i);

A: You can check if URL contains the word "http://www.youtube.com" using .indexOf()
var url = 'http://www.youtube.com/channel/UChh-akEbUM8_6ghGVnJd6cQ';
if (url.indexOf('http://www.youtube.com') > -1) {
  alert( "true");
} else {
  alert( "false");
}

A: you Want to validate your URL:

Please pass the URL in this function then this will give you true OR false
See Function :
<script>
function isValidUrl(s) {
    var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
    return regexp.test(s);
}

isValidUrl(yourURL);
</script>

A: var regexp = /^(?:https?:\/\/)?(?:www\.)?youtube\.com\/watch\?(?=.*v=((\w|-){11}))(?:\S+)?$/;

var matches_array = video_url.match(regexp);

if(matches_array == null)

{

                alert("Enter youtube url");

                return false;

}


text:
Q: Django - can I add a form on changelist_view? I have a model admin with a simple custom change view page, can I add a form on it?
class MyForm(forms.Form):
    user_input_field = forms.CharField(widget=forms.Textarea, required=True)

class MyModelAdmin(admin.ModelAdmin):
    change_list_template = 'custom_template.html'

    def changelist_view(self, request, extra_content=None):
        # How do I link the form to this view ?

        # logic of handling data from the form
        return super(MyModelAdmin, self).changelist_view(request, extra_context=None)


text:
Q: MFC Rich Edit TOM -- InsertTable; cannot add more than one column? May you please help, I can only insert a table with any number of rows, but not columns; I get an E_INVALIDARG when cols > 1 in ITextRange2::InsertTable(cRow,cCol,AutoFit)??
IRichEditOle* pREOle = NULL; // rCtrl is my derived CRichEditView in MFC
HRESULT hr = rCtrl.SendMessage(EM_GETOLEINTERFACE, 0,
(LPARAM)&pREOle);
CComQIPtr<ITextDocument2> pITextDoc;
hr = pREOle->QueryInterface(__uuidof(ITextDocument2), (void*)&pITextDoc);
CComPtr<ITextRange2> range;
pITextDoc->Range2(start, start, &range);
hr = range->InsertTable(3,3, 1); // get hr = E_INVALIDARG here

A: Below is code, that will insert a table for editing rows or inserting a new table. The function is declared in my derived view class CMHMView. I added fields such as ITextRange2* m_ptr2, HRESULT m_hr.
Initialization is done in my CRichEditView::OnInitialUpdate:
CRichEditCtrl& re = GetRichEditCtrl();
m_pREOle = re.GetIRichEditOle();
m_hr = m_pREOle->QueryInterface(IID_PPV_ARGS(&m_ptd2));

This is the function I use to add the table(s)
void CMHMView::InsertTableRow(long index, long& start, long& end, long ncells,
long cellwidths[], long skip, LPCTSTR* sText, BOOL bAppend){

if (SUCCEEDED(m_hr))
{
    long lDelta{};

    CComPtr<ITextFont> pFont;

    m_hr = m_ptr2->GetFont(&pFont);

    CComPtr<ITextRow> pRow;
    CComPtr<ITextFont> pFontDuplicate;

    m_hr = m_ptr2->GetRow(&pRow);
    m_hr = pFont->GetDuplicate(&pFontDuplicate);

    if (pRow && pFontDuplicate)
    {
        CComPtr<ITextPara> pPara, pParaDuplicate;
        m_ptr2->GetPara(&pPara);
        pPara->GetDuplicate(&pParaDuplicate);

        pFontDuplicate->SetName(CComBSTR(L"Courier New"));
        pFontDuplicate->SetSize(12.0f);

        m_ptr2->MoveStart(tomTable, start, &lDelta);
        m_ptr2->Collapse(tomEnd);
        if (bAppend)
        {
            pRow->SetCellCount(ncells);
            for (int i = 0; i < ncells; i++)
            {
                pRow->SetCellIndex(i);
                pRow->SetCellWidth(cellwidths[i]);
            }

            pRow->Insert(1);
            m_ptr2->SetIndex(tomTable, index, 0);

            for (int i = 0; i < skip; i++)
            {
                if (i > 0)
                    m_ptr2->MoveStart(tomCell, 1, &lDelta);
                m_ptr2->SetText(CComBSTR(L""));
            }
            for (int i = 0; i < ncells; i++)
            {
                if (i > 0)
                    m_ptr2->MoveStart(tomCell, 1, &lDelta);

                m_ptr2->SetText(CComBSTR(sText[i]));
                m_ptr2->SetFont(pFontDuplicate);
                m_ptr2->SetPara(pParaDuplicate);

            }

            m_ptr2->EndOf(tomTable, tomMove, &lDelta);

            m_ptr2->GetEnd(&end);
        }
        else
        {
            m_ptr2->SetText(CComBSTR(L"\r"));
            m_ptr2->Collapse(tomEnd);

            pRow->SetCellCount(ncells);
            for (int i = 0; i < ncells; i++)
            {
                pRow->SetCellIndex(i);
                pRow->SetCellWidth(cellwidths[i]);
                /*pRow->SetCellMergeFlags(tomHStartCell)*/
            }

            pRow->Insert(1);
            m_ptr2->SetIndex(tomTable, index, 0);

            for (int i = 0; i < ncells; i++)
            {
                if (i > 0)
                    m_ptr2->MoveStart(tomCell, 1, &lDelta);

                m_ptr2->SetText(CComBSTR(sText[i]));
                m_ptr2->SetFont(pFontDuplicate);
                m_ptr2->SetPara(pParaDuplicate);

            }

            m_ptr2->EndOf(tomTable, tomMove, &lDelta);
            m_ptr2->GetEnd(&end);

        }
    }
}
m_pREOle->Release();}

I hope this will help others!


text:
Q: what are the rules for spaces in swift I practicing in swift's playground and I couldn't figure out why swift is too specific about where programmer should provide spaces and where not. I asked this question on many sites and chatrooms but didn't got any answer.
var j: Int = 34 // Right
var j:Int=23 //Wrong

Also, In class
self.variable-= 5 //Wrong. Error: Consecutive statements must be followed by ;
self.variable-=5 // Right
self.variable -= 5 // Right

;
Even this ":" creates some issues with spaces sometimes.
I think spaces should have absolutely no effect on the code. It's usually just for a programmer's benefit. It just makes the code more readable nothing else. What's the best resource to read all swift rules about spaces.

A: Answer to the second part of your question can be found here swift docs

The whitespace around an operator is used to determine whether an operator is used as a prefix operator, a postfix operator, or a binary operator. This behavior is summarized in the following rules:
If an operator has whitespace around both sides or around neither side, it is treated as a binary operator. As an example, the + operator in a+b and a + b is treated as a binary operator.
If an operator has whitespace on the left side only, it is treated as a prefix unary operator. As an example, the ++ operator in a ++b is treated as a prefix unary operator.
If an operator has whitespace on the right side only, it is treated as a postfix unary operator. As an example, the ++ operator in a++ b is treated as a postfix unary operator.
If an operator has no whitespace on the left but is followed immediately by a dot (.), it is treated as a postfix unary operator. As an example, the ++ operator in a++.b is treated as a postfix unary operator (a++ .b rather than a ++ .b).
etc... (read the docs for more on this)

As for the first part of your question, I didn't see any issue with either way of declaring the variables.
var j: Int = 34
var j:Int=23

The only issue with that provided code is that you declare j twice in the same scope. Try changing one of the j's to an x or y or something else.
If you were wondering about
var j:Int =10

or
var j:Int= 10

look at the rules above. = is an operator so if you were to do either of those, it would be treated as prefix or postfix, and you would get the error that prefix/postfix = is reserved
These rules are important due to the existence of operators such as the unary plus and unary minus operators. The compiler needs to be able to distinguish between a binary plus and a unary plus operator. List of operators


text:
Q: Android: Kernel Debugging with KGDB I'm trying to do kernel debugging for my Nexus One, and have been following instructions from http://bootloader.wikidot.com/android:kgdb. I was wondering if someone has actually got this to work? And has anyone done a more up to date solution for using KGDB to debug the kernel?

A: I found this post when I was looking for information of KGDB on Android so, despite it being a few years old, I thought it worth posting a link to some work I did to get this up and running on the Nexus 6.
http://www.contextis.com/resources/blog/kgdb-android-debugging-kernel-boss/
I hope this helps anyone else looking for similar answers.
Edited following feedback (thanks all):
To get this working I had to make a UART debug cable based on this Accuvant blog. This is quite a simple circuit which consists of a FTDI 3.3v basic breakout (available from SparkFun at the time of writing), as well as 4 resistors (2 x 1K Ohm, 1 x 1.2K Ohm and 1 x 100Ohm), and a 4-element Tip-Ring-Ring-Sleeve (TRRS) headphone jack. The resistors are essentially providing a voltage divider to reduce the 3.3v down to something a little safer for your phone. By inserting the audio jack with the other end connected to your circuit board, the audio subsystem recognises that a voltage (~2.8V) on the one of the pins and it knows to provide a UART interface via that cable. The FTDI breakout plugs into your PC via USB and from here you can access console messages via a terminal emulator like minicom. However, you now have a serial interface through the same mechanism and that's what we can use for a KGDB connection.
So at this point some relatively minor changes are required to the Nexus 6's serial driver (msm_serial_hs_lite.c) to support KGDB (specifically, the ability to perform atomic character I/O operations). I just ported these changes from the Linux Kernel mainline code as a chap called Stephen Boyd had done the hard work to the full MSM (Qualcomm) serial driver msm_serial.c. His changes can be found here or just search for "msm_serial: add support for poll_" on Google. The port wasn't difficult and my code can be found on github.
Aside from that you need to be able to build a custom kernel for your N6 which google provides lots of information on. You then need to create a boot image which contains the KGDB modifications in the github repo. I took the stock kernel from https://developers.google.com/android/nexus/images, extracted it (using abootimg -x) and then used the following command to repack it with my custom kernel (zImage-dtb) and additional command line params to ensure KGDB would be loaded and point to my serial port like so:
abootimg -u boot.img -k zImage-dtb -c 'cmdline=console=ttyHSL0,115200,n8 kgdboc=ttyHSL0,115200 kgdbretry=4'

With my boot.img created I could boot into it using the command fastboot boot boot.img, open an adb shell and then trigger a breakpoint in the Android kernel using the command:
echo -n g > /proc/sysrq-trigger

It is worth mentioning for completeness that you need superuser privileges to access /proc/sysrq-trigger so you need to have root.
With the phone halted, and your debug cable connected, launch a version of GDB for ARM on your host PC with your uncompressed kernel as an argument (e.g. arm-eabi-gdb ./vmlinux). Note: I'm running Ubuntu 14.04 and using arm-eabi-gdb from the 'prebuilts' directory in my AOSP source repository. Finally, enter the following commands:
set remoteflow off
set remotebaud 115200
target remote /dev/ttyUSB0

All being well this should immediately break into the kgdb breakpoint (that your write to /proc/sysrq-trigger produced) and you can start debugging.

A: I know that you've already asked a question at the Android Kernel Dev list and got no answers, but did you search through the archives for posts about kgdb and debugging?: http://groups.google.com/group/android-kernel/search?group=android-kernel&q=kgdb&qt_g=Search+this+group
In particular, you might want to look at this post: http://groups.google.com/group/android-kernel/browse_thread/thread/5233e03391867c98/320beef11e737a62
Here's a few other random links that might be helpful:

*

*http://www.cs.gmu.edu/~astavrou/courses/ISA_673/Android_Debugging/Android_GDB.pdf

*http://www.cs.columbia.edu/~nieh/teaching/w4118/ubb/Forum6/HTML/000122.html

*http://wiki.ncl.cs.columbia.edu/wiki/AndroidVirt:Guides:Kernel_Debugging

*http://source.android.com/porting/debugging_gdb.html
Anyhow, this is an interesting question, and I'm really having a hard time finding anything on it. You might want want to try hopping on IRC sometime (#android-dev or #android-root on freenode) and asking some people there for pointers (please post up what you find here), or maybe asking on the xda-developers Android forums.


text:
Q: Criteria collection-field access i have problem with access to Collection-field in my class with Criteria.
I have 2 entity:
First, that mapped to other entity
@Table(name = "MAIN_ENTITY")
public class MainEntity {

    @Id
    @Column(name = ID_MAIN, nullable = false, precision = 38, scale = 0)
    private BigDecimal id;

    @OneToMany(mappedBy = "mappedField")
    private Set<SecondEntity> secondEntities = new HashSet<>(0);

    ...................
}

And second, that loaded to first entity.
@Table(name = "SECOND_ENTITY")
public class SecondEntity {

    @Id
    @Column(name = ID_SECOND, nullable = false, precision = 38, scale = 0)
    private BigDecimal id;

    @Column(name = SOME_FLAG, nullable = false, precision = 38, scale = 0)
    private BigDecimal someFlag;

    @ManyToOne
    @JoinColumn(name = MAIN_ENTITY_FK, nullable = false)
    private MainEntity mainEntity;

    ...................
}

I want to get count of secondEntities in MainEntity records, where field someFlag = 0
For this i have class that extends MainEntity and have field count
public class MainEntityDto extends MainEntity {
    private MainEntity entity;
    private Integer count;
    ...................
}

then i'm trying to build query, i write this:
Path secondEntitiesPath = root.<Set>get("secondEntities");
cq.select(cb.construct(MainEntityDto.class, root, cb.size(secondEntitiesPath)));

It's working good if i want to get count of all second entities, for example if i have 100 entities, i will get count = 100, and I can work with this entity later in my code.
BUT I want to get count of entities where field Flag = 0.
I was trying to write something like
cq.select(cb.construct(MainEntityDto.class, root,
    cb.size(secondEntitiesPath))).where(cb.equal(
    secondEntitiesPath.<BigDecimal>get("Flag"), BigDecimal.ZERO)

but this just create another join, and have no effect on count, and it still returns 100.
I just can't get access to the elements of the Set in my queries. I was trying it in hundred different ways, but i always have something like
SELECT COUNT(t.id)
FROM SECOND_ENTITY se
WHERE (se.MAIN_ENTITY_FK = mainEntity.ID)

and after it i have another join that have conditional that i wrote.
Sorry guys, if it looks like a mess, and you can't understand anything. I got stuck on it for 3 days, and maybe can't think clearly. I will update this topic if someone asks for more code or etc. I will very appreciate all comments, thanks you very much!

A: You are on the right track with the sub query.  In JPQL it would look something like:
 "SELECT new MainEntityDto(entity, (select count(secondEntities) from SecondEntity secondEntities where secondEntities.mainEntity = entity and secondEntities.flag=0)) from MainEntity entity"
Using criteria API would look something like:
Subquery sq = cb.subquery(SecondEntity.class);
Root<SecondEntity> second= sq.from(SecondEntity.class);
sq.select(cb.count(second));
sq.where(cb.and(cb.equal(second.get("mainEntity"), root), cb.equal(second.get("flag"), 0));

cq.select(cb.construct(CodeSubjectDto.class, root, sq));

A: I have had some advice, and now count with some conditional criteria query should be look like
final Join<MainEntity, SecondEntity> secondEntityJoin =
    root.join(secondEntities, JoinType.LEFT);
secondEntityJoin.on(cb.equal(secondEntityJoin.<BigDecimal>get("someFlag"), BigDecimal.ZERO)));
cq.select(cb.construct(CodeSubjectDto.class, root, cb.count(secondEntityJoin)));

But now new problem has appeared in SQL query, because I have to use group by with count. This problem will be solved later and i will post out final decision. To solve this problem, i can use multiselect, or make second query, but it's not appropriate for our high-load application architecture. Also we have found that weight of this query is too high and maybe it will be redesigned
UPD some important info, why i haven't found it at the start:
cb.size returns type int -> In MainEntityDto I have to have constructor with parameters(MainEntity, int)
cb.count returns type long -> In MainEntityDto I have to have constructor with parameters (MainEntity, !!LONG!!)
This's why i couldn't build this at the start. That query returns error, but i didn't understand, that there was problem with constructor.


text:
Q: Logic to determine whether two number sequences are order equivalent I want to determine if two sequences are "order equivalent", where what I mean by that is two sequences a and b are order equivalent if they have the same number of elements and they both contain less than two numbers or if for all i, j, 1 <= i, j <= n where n is the length of a sequence a[i] <= a[j] if and only if b[i] <= b[j]
I have written a small program in C along with a set of test cases
include <stdio.h>

int main() {
    // Should be true, and is
//    int a[1] = {12};
//    int b[1] = {8};

    // Should be true, and is
//    int a[3] = {1, 2, 3};
//    int b[3] = {12, 32, 43};

    // Should be true, and is
//    int a[3] = {12, 45, 78};
//    int b[3] = {1, 2, 3};

    // Should be true, and is
//    int a[6] = {7, 5, 9, 13, 12};
//    int b[6] = {4, 2, 25, 33, 26};

    // Should be true, and is
//    int a[3] = {1, 1, 1};
//    int b[3] = {1, 1, 1};

    // Should be false, and is
//    int a[4] = {12, 1, 2, 3}; // because there is a decrease between 12 and 1
//    int b[4] = {3, 4, 5, 6}; // but an increase between 3 and 4

    // Should be true, but for some reason is not
    int a[6] = {23, 55, 22, 33, 9, 18};
    int b[6] = {21, 43, 11, 22, 7, 11};

    int size_of_arrays = 6; // set this to the correct value depending on values being tested

    int are_equivalent = 1;
    for (int m = 0; m < size_of_arrays; m = m + 1){
        for (int n = 0; n < size_of_arrays; n = n + 1){
            if ((a[m] <= a[n]) != (b[m] <= b[n])){
                are_equivalent = 0;
            }
        }
    }
    if (are_equivalent == 1) {
        printf("The two sequences are order equivalent.");
    } else {
        printf("The two sequences are not order equivalent.");
    }
    return 0;
}

but the last test case in particular is throwing me for a loop (pun intended). There is some case my logic is not covering but I am unable to see it. Any ideas what I might be missing?


text:
Q: Binding to a dictionary in Silverlight with INotifyPropertyChanged In silverlight, I can not get INotifyPropertyChanged to work like I want it to when binding to a dictionary. In the example below, the page binds to the dictionary okay but when I change the content of one of the textboxes the CustomProperties property setter is not called. The CustomProperties property setter is only called when CustomProperties is set and not when the values within it are set. I am trying to do some validation on the dictionary values and so am looking to run some code when each value within the dictionary is changed. Is there anything I can do here?
C#
public partial class MainPage : UserControl
{

    public MainPage()
    {
        InitializeComponent();

        MyEntity ent = new MyEntity();
        ent.CustomProperties.Add("Title", "Mr");
        ent.CustomProperties.Add("FirstName", "John");
        ent.CustomProperties.Add("Name", "Smith");

        this.DataContext = ent;
    }

}

public class MyEntity : INotifyPropertyChanged
{

    public event PropertyChangedEventHandler System.ComponentModel.INotifyPropertyChanged.PropertyChanged;
    public delegate void PropertyChangedEventHandler(object sender, System.ComponentModel.PropertyChangedEventArgs e);

    private Dictionary<string, object> _customProps;
    public Dictionary<string, object> CustomProperties {
        get {
            if (_customProps == null) {
                _customProps = new Dictionary<string, object>();
            }
            return _customProps;
        }
        set {
            _customProps = value;
            if (PropertyChanged != null) {
                PropertyChanged(this, new PropertyChangedEventArgs("CustomProperties"));
            }
        }
    }

}

VB
Partial Public Class MainPage
    Inherits UserControl

    Public Sub New()
        InitializeComponent()

        Dim ent As New MyEntity
        ent.CustomProperties.Add("Title", "Mr")
        ent.CustomProperties.Add("FirstName", "John")
        ent.CustomProperties.Add("Name", "Smith")

        Me.DataContext = ent
    End Sub

End Class

Public Class MyEntity
    Implements INotifyPropertyChanged

    Public Event PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged

    Private _customProps As Dictionary(Of String, Object)
    Public Property CustomProperties As Dictionary(Of String, Object)
        Get
            If _customProps Is Nothing Then
                _customProps = New Dictionary(Of String, Object)
            End If
            Return _customProps
        End Get
        Set(ByVal value As Dictionary(Of String, Object))
            _customProps = value
            RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("CustomProperties"))
        End Set
    End Property

End Class

Xaml
<TextBox Height="23" Name="TextBox1" Text="{Binding Path=CustomProperties[Title], Mode=TwoWay}" />
<TextBox Height="23" Name="TextBox2" Text="{Binding Path=CustomProperties[FirstName], Mode=TwoWay}" />
<TextBox Height="23" Name="TextBox3" Text="{Binding Path=CustomProperties[Name], Mode=TwoWay}" />

A: Here is a one (somewhat oversimplified) solution.
public class MyEntity : INotifyPropertyChanged
{

    public event PropertyChangedEventHandler PropertyChanged;

    private readonly Dictionary<string, object> _customProps = new Dictionary<string, object>();

    public void AddCustomProperty(string key, object value)
    {
        _customProps.Add(key, value);
    }

    public object this[string key]
    {
        get { return _customProps[key]; }
        set
        {
            // The validation code of which you speak here.
            _customProps[key] = value;
            NotifyPropertyChanged("Item[" + key "]");
        }
    }

    private void NotifyPropertyChanged(string name)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(name));
    }
}

MainPage:-
    public MainPage()
    {
        InitializeComponent();

        MyEntity ent = new MyEntity();
        ent.AddCustomProperty("Title", "Mr");
        ent.AddCustomProperty("FirstName", "John");
        ent.AddCustomProperty("Name", "Smith");

        this.DataContext = ent;

    }

MainPage Xaml:-
        <TextBox Height="23" Name="TextBox1" Text="{Binding [Title], Mode=TwoWay}" />
        <TextBox Height="23" Name="TextBox2" Text="{Binding [FirstName], Mode=TwoWay}" />
        <TextBox Height="23" Name="TextBox3" Text="{Binding [Name], Mode=TwoWay}" />

The important thing for your issue is that your code is involved in the assigning the property value into the dictionary.  Originaly your code exposed the Dictionary, all the assignment work went through framework component code.  In this version MyEntity has a string indexer where the custom properties are assigned directly and the Dictionary is made private.
Note the implementation of INotifyPropertyChanged is not strictly necessary to answer your specific question but I suspect you will need it.  If for example you re-assign a new value to a custom property you would want the UI to be notified.

A: A collection needs to implement the INotifyCollectionChanged interface in addition to the INotifyPropertyChanged interface to support data binding. The ObservableCollection class implements them for a List-like collection, but I believe there is no dictionary-like collection in the .NET Framework that does this. You likely have to implement it yourself.


text:
Q: Change AngularJS urls with ng-model Is there any way to change AngularJS urls  with ng-model?

var scotchApp = angular.module('scotchApp', ['ngRoute']);

scotchApp.controller('mainController', function($scope) {
    $scope.gettext = function (){

    };
});

<!DOCTYPE html>

        <meta charset="utf-8">
        <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" />
        <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css" />

Search

<input type="text" class="form-control" ng-model="search" ng-change="gettext()">

I need to change the URL into something like this http://localhost/angulRoute/search=myVal when user type 'myVal' in the search box (actually inside gettext() function with search value)

A: You can do something like this in your controller:
$scope.query = $location.search().q;

$scope.$watch('query', function(newValue) {
    $location.search('q', newValue);
});

You'd need to inject $location into your controller, and make sure in your route config includes:
reloadOnSearch: true

That would result in a URL like http://localhost/myRoute?q=myVal
Note: I would also add ng-model-options="{updateOn:'blur'}" to your input, to prevent updating the URL on every key press.
EXAMPLE
Here is a working example of how to do this: http://plnkr.co/edit/tphqPeJ0dO74Ux7WpXlU?p=preview
Note that, because of the way plnkr.co works, you won't see the URL changes in the address bar on that site. If you download the code and run it locally, the URL would be updated in the address bar.

A: Hi I found a javascript solution for that.
 $scope.gettext = function (search){
    window.history.pushState("object or string", "Title", "/angulRoute/search="+search);
};

with <input type="text" class="form-control" ng-model="search" ng-change="gettext(search)" > worked for me. However anyone have an AngulerJs solution they are welcome :D


text:
Q: Probability density function within [0,1] with specifiable mode I needed a probability density function which worked on the interval $[0,1]$, had kind of a bell shape, and had an adjustable mode / peak $p$.
I thought of a pdf $f(x|p)$, given by
\begin{equation}
f(x|p) = \left\{
\begin{array}{l l l }
 \frac{ (x^{- \ln 2/\ln p})^2 \cdot (1-x^{- \ln 2/\ln p})^2 }{ \log(p)
 \left(
\frac{x^{1-\frac{4 \log 2}{\log p}}}{\log(p) - 4\log(2)}
-\frac{2 x^{1-\frac{3 \log 2}{\log p}}}{\log(p) - 3\log(2)}
+\frac{x^{1-\frac{2 \log 2}{\log p}}}{\log(p) - 2\log(2)}
  \right) } &\quad \text{ for } 0<x<1 \\
0  &\quad \text{ otherwise}
\end{array} \right.
\end{equation}
which

*

*has a peak at $x=p$ for $0<p<1$.

*$P(X\le 0) = P(X\ge 1) = 0$

*has a shape similar to the bell shape

*looks skewed to the left for $p>1$ and to the right for $0<p<1$

Or equivalently:
\begin{equation}
f(x|p) = \left\{
\begin{array}{l l l }
 \frac{ (x^a)^2 \cdot (1-x^a)^2 } { (4a+1)^{-1} - 2(3a+1)^{-1} + (2a+1)^{-1} } &\quad \text{ for } 0<x<1 \\
0  &\quad \text{ otherwise}
\end{array} \right.
\end{equation}
which
which has its peak at $p=-\frac{\log 2}{\log x}$
Is there a similar pdf (or exactly this one) used in literature?
What is it called?
PS: note that the given pdf is not symmetric: $f(x|1-p) \neq f(1-x |p) $

A: That pdf is similar to the generalized Beta distribution of the first kind, which is obtained by raising a Beta variable to a power.


text:
Q: How to get innerText (selected text not the value) from TextField as select I am using material-ui for my project and I have a need to get the selected text (not the value) and do some parsing. I can't seem to find a way to do this.
Here is what my component looks like:
                    <TextField
                        select
                        margin="dense"
                        label="Name"
                        variant="outlined"
                        className={classes.textField}
                        value={values.nameId}
                        onChange={handleChange('nameId')}
                    >
                        {names.map(row => (
                            <MenuItem key={row.Id} value={row.Id}>{row.Name}</MenuItem>
                        ))}
                    </TextField>

handler looks like this:
const handleChange = name => event => {

    setValues({ ...values, [name]: event.target.value });
};

Obviously event.target.value gets my selected value, but I want to also get the selected innerText of the selected index.  Any ideas?

A: Have you tried using event.target.innerText?  The target prop of the event should contain the data for the entire element which you can access in your change handler.

A: In handleChange, use Array.find() to search for the desired element, and than extract it's name:
 const handleChange = name => event => {
    const innerText = names
    .find(name => name.Id === event.target.value)
    .Name;

    console.log('inner text: ', innerText);

    setValues({ ...values, [name]: event.target.value });
  };

You can check working example at CodeSandbox

A: I did more poking around and was able to get to the inner text using the following property:
event._targetInst.child.alternate.memoizedProps[0]
event.target.innerText does not work for material-ui <TextField> component. Might work for native select component however.
I am not sure if this is the best approach but it seems to work for now.


text:
Q: Using one of objects properties value as type TS beginner. Here
let test = <T,>(x:T, c:{[k in keyof T]:(p:T[k])=>void})=>{

}

test({name:"john"}, {name:(functionParam)=>null})

The functionParam is resolved as string. But I used T[k] which  refers to "john". So is it correct that it got inferred as string?
Where can I read more about this?

A: I'm not aware of a specific name of this features. It's the keyof operator you apply here.

The keyof operator takes an object type and produces a string or numeric literal union of its keys.

Your object type T is { name: "john" }. The result of keyof is hence "name" and T[k] returns therefore "john", which is widened to string.

A: Yes, this is correct. In TypeScript, you can index a type to get the type of the property of that key (see Indexed Access Types). Basing a type on the value of an object's property is impossible, as TypeScript runs at compile time and values are determined at runtime. If you had a type "john" then that is what would show up:
type John = {name: "john"};

let yourName: John["name"];

TypeScript Playground
You can see that the type of yourName is then "john". By default, TypeScript assumes that the object will change, so the type of
let me = {name: "john"};

is inferenced as {name: string} (TypeScript Playground). If it was {name: "john"} by default, then you couldn't change it to something else. Most of the time, when you declare an object, you're going to change it, so this is the safe assumption to make.

A: You are observing type widening which happens in this case because there is no constraint on T and T also does not directly infer the string type. You can read more about the specifics in this Pull request.
To solve this, add an extra generic type S which extends string (or any other primitive type which may be valid here). T will be constrained to Record<string, S>.
let test = <
  T extends Record<string, S>,
  S extends string
>(x: T, c:{ [K in keyof T] : (p:T[K]) => void })=> {}

test({ name:"john" }, { name:(functionParam) => null })
//                             ^? "john"

Now, the parameter functionParam is correctly inferred to the string literal type "john".

Playground