text:
Q: Android emulator can't find my Java class? I have started building an android app that uses the ZXing library to read barcodes. The app I am developing uses a standalone barcode scanner- it doesn't use the android Intent object to scan a barcode. I have included the "core.jar" file in my project and have created a java class that scans a bitmap. To do this I have had to use include another class called RGBLuminanceSource- that I found on the java2s.com website. This class can read android bitmaps and is used to help create a LuminanceSource object because android can't use the AWT "BufferedImage" class to create "LuminaceSource" objects. My project compiles and builds without any errors, but when I try to run the project on the emulator (avd android version 1.5) I get the dreaded "the application "x" has stopped working unexpectedly.Please try again" message! I have looked through the DDMS logs and the only thing I can understand is that the emulator can't find the "RGBLuminanceSource" class that I added to the project. This causes problems because in order to decode the bitmap I have to make an object from the RGBLuminaceSource class.
I don't know why this is happening especially when the project builds without any problems, I am quite new to android programming so any help would be much appreciated, thank you.
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.me.testgui;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Reader;
import com.google.zxing.common.HybridBinarizer;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 *
 * @author Gerrard
 */
public class TestClass
{
    protected static String scannedBarcode=null;
    private static InputStream is;

    protected static String testMethod()
    {
       String st = "THIS IS A TEST!!!!!!!!!!!";
       return st;
    }

    public static void readBarcode(String file) throws NotFoundException
    {

        try
        {
            //file = "D:\\NetBeansProjects\\TestGUI\\res\\drawable\\barcode1.jpg";
            is = new FileInputStream(file);

            // Create a BitMap object of the image to be worked with
            Bitmap bm = BitmapFactory.decodeStream(is);//create a bitmap from the imput stream "is" object
            RGBLuminanceSource rgbSource = new RGBLuminanceSource(bm);//create an object type RGBLuminanceSource so that the android type bitmap can be read by the ZXing LumincaceSource class
            System.out.println("RGBLuminance object created");

           LuminanceSource source = rgbSource;

            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

            Reader reader = new MultiFormatReader();

            com.google.zxing.Result result = reader.decode(bitmap);

            String barcode = String.format("Barcode text is: " + result.getText());
           scannedBarcode = barcode;

        }
        catch(Exception e)
        {
            //Toast.makeText(MainActivity,"ERROR: " +e.toString(), Toast.LENGTH_SHORT).show();
        }

    }
}

I have also included the DDMS logs to help track down the source of the problem
 10-12 20:27:07.126: DEBUG/AndroidRuntime(833): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<

    10-12 20:27:07.149: DEBUG/AndroidRuntime(833): CheckJNI is ON
    10-12 20:27:08.966: DEBUG/AndroidRuntime(833): --- registering native functions ---
    10-12 20:27:09.038: INFO/jdwp(833): received file descriptor 22 from ADB
    10-12 20:27:10.086: INFO/jdwp(833): Ignoring second debugger -- accepting and dropping
    10-12 20:27:12.115: DEBUG/AndroidRuntime(833): Shutting down VM
    10-12 20:27:12.135: DEBUG/dalvikvm(833): DestroyJavaVM waiting for non-daemon threads to exit
    10-12 20:27:12.175: DEBUG/dalvikvm(833): DestroyJavaVM shutting VM down
    10-12 20:27:12.185: DEBUG/dalvikvm(833): HeapWorker thread shutting down
    10-12 20:27:12.195: DEBUG/dalvikvm(833): HeapWorker thread has shut down
    10-12 20:27:12.206: DEBUG/jdwp(833): JDWP shutting down net...
    10-12 20:27:12.229: DEBUG/jdwp(833): +++ peer disconnected
    10-12 20:27:12.235: INFO/dalvikvm(833): Debugger has detached; object registry had 1 entries
    10-12 20:27:12.376: DEBUG/dalvikvm(833): VM cleaning up
    10-12 20:27:12.475: DEBUG/dalvikvm(833): LinearAlloc 0x0 used 629804 of 4194304 (15%)
    10-12 20:27:13.345: DEBUG/AndroidRuntime(843): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
    10-12 20:27:13.356: DEBUG/AndroidRuntime(843): CheckJNI is ON
    10-12 20:27:13.902: DEBUG/AndroidRuntime(843): --- registering native functions ---
    10-12 20:27:13.955: INFO/jdwp(843): received file descriptor 22 from ADB
    10-12 20:27:13.955: INFO/jdwp(843): Ignoring second debugger -- accepting and dropping
    10-12 20:27:16.821: DEBUG/PackageParser(554): Scanning package: /data/app/vmdl33973.tmp
    10-12 20:27:17.546: INFO/PackageManager(554): Removing non-system package:org.me.testgui
    10-12 20:27:17.595: DEBUG/PackageManager(554): Removing package org.me.testgui
    10-12 20:27:17.625: DEBUG/PackageManager(554):   Activities: org.me.testgui.MainActivity
    10-12 20:27:18.067: DEBUG/PackageManager(554): Scanning package org.me.testgui
    10-12 20:27:18.107: INFO/PackageManager(554): /data/app/vmdl33973.tmp changed; unpacking
    10-12 20:27:18.185: DEBUG/installd(559): DexInv: --- BEGIN '/data/app/vmdl33973.tmp' ---
    10-12 20:27:19.125: DEBUG/dalvikvm(849): DexOpt: load 155ms, verify 235ms, opt 2ms
    10-12 20:27:19.195: DEBUG/installd(559): DexInv: --- END '/data/app/vmdl33973.tmp' (success) ---
    10-12 20:27:19.205: DEBUG/PackageManager(554):   Activities: org.me.testgui.MainActivity
    10-12 20:27:19.375: INFO/installd(559): move /data/dalvik-cache/data@app@vmdl33973.tmp@classes.dex -> /data/dalvik-cache/data@app@org.me.testgui.apk@classes.dex
    10-12 20:27:19.417: DEBUG/PackageManager(554): New package installed in /data/app/org.me.testgui.apk
    10-12 20:27:19.705: DEBUG/AndroidRuntime(843): Shutting down VM
    10-12 20:27:19.715: DEBUG/dalvikvm(843): DestroyJavaVM waiting for non-daemon threads to exit
    10-12 20:27:19.785: DEBUG/ActivityManager(554): Uninstalling process org.me.testgui
    10-12 20:27:19.805: DEBUG/dalvikvm(843): DestroyJavaVM shutting VM down
    10-12 20:27:19.805: DEBUG/dalvikvm(843): HeapWorker thread shutting down
    10-12 20:27:19.815: DEBUG/dalvikvm(843): HeapWorker thread has shut down
    10-12 20:27:19.815: DEBUG/jdwp(843): JDWP shutting down net...
    10-12 20:27:19.815: DEBUG/jdwp(843): +++ peer disconnected
    10-12 20:27:19.815: INFO/dalvikvm(843): Debugger has detached; object registry had 1 entries
    10-12 20:27:19.825: DEBUG/dalvikvm(843): VM cleaning up
    10-12 20:27:19.935: DEBUG/dalvikvm(843): LinearAlloc 0x0 used 629572 of 4194304 (15%)
    10-12 20:27:20.497: WARN/ResourceType(554): No package identifier when getting value for resource number 0x7f060000
    10-12 20:27:20.538: WARN/ResourceType(554): No package identifier when getting value for resource number 0x7f060001
    10-12 20:27:20.585: DEBUG/HomeLoaders(620): application intent received: android.intent.action.PACKAGE_REMOVED, replacing=true
    10-12 20:27:20.615: DEBUG/HomeLoaders(620):   --> package:org.me.testgui
    10-12 20:27:20.635: DEBUG/HomeLoaders(620): application intent received: android.intent.action.PACKAGE_ADDED, replacing=true
    10-12 20:27:20.655: DEBUG/HomeLoaders(620):   --> package:org.me.testgui
    10-12 20:27:20.665: DEBUG/HomeLoaders(620):   --> update package org.me.testgui
    10-12 20:27:20.876: DEBUG/dalvikvm(554): GC freed 9144 objects / 423280 bytes in 323ms
    10-12 20:27:21.315: WARN/ResourceType(554): No package identifier when getting value for resource number 0x7f060000
    10-12 20:27:21.366: WARN/ResourceType(554): No package identifier when getting value for resource number 0x7f060001
    10-12 20:27:22.840: DEBUG/AndroidRuntime(854): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
    10-12 20:27:22.845: DEBUG/AndroidRuntime(854): CheckJNI is ON
    10-12 20:27:23.786: DEBUG/AndroidRuntime(854): --- registering native functions ---
    10-12 20:27:23.795: INFO/jdwp(854): received file descriptor 22 from ADB
    10-12 20:27:23.829: INFO/jdwp(854): Ignoring second debugger -- accepting and dropping
    10-12 20:27:25.965: INFO/ActivityManager(554): Starting activity: Intent { flags=0x10000000 comp={org.me.testgui/org.me.testgui.MainActivity} }
    10-12 20:27:26.876: DEBUG/AndroidRuntime(854): Shutting down VM
    10-12 20:27:26.886: DEBUG/dalvikvm(854): DestroyJavaVM waiting for non-daemon threads to exit
    10-12 20:27:26.936: DEBUG/dalvikvm(854): DestroyJavaVM shutting VM down
    10-12 20:27:26.947: DEBUG/dalvikvm(854): HeapWorker thread shutting down
    10-12 20:27:26.947: DEBUG/dalvikvm(854): HeapWorker thread has shut down
    10-12 20:27:26.947: DEBUG/jdwp(854): JDWP shutting down net...
    10-12 20:27:26.976: DEBUG/jdwp(854): +++ peer disconnected
    10-12 20:27:26.976: INFO/dalvikvm(854): Debugger has detached; object registry had 1 entries
    10-12 20:27:26.986: DEBUG/dalvikvm(854): VM cleaning up
    10-12 20:27:27.046: DEBUG/dalvikvm(854): LinearAlloc 0x0 used 639228 of 4194304 (15%)
    10-12 20:27:27.286: INFO/ActivityManager(554): Start proc org.me.testgui for activity org.me.testgui/.MainActivity: pid=862 uid=10024 gids={1006}
    10-12 20:27:27.809: INFO/jdwp(862): received file descriptor 10 from ADB
    10-12 20:27:28.055: INFO/jdwp(862): Ignoring second debugger -- accepting and dropping
    10-12 20:27:28.105: WARN/System.err(862): Can't dispatch DDM chunk 46454154: no handler defined
    10-12 20:27:28.146: WARN/System.err(862): Can't dispatch DDM chunk 4d505251: no handler defined
    10-12 20:27:29.375: WARN/Resources(862): Converting to string: TypedValue{t=0x12/d=0x0 a=2 r=0x7f050001}
    10-12 20:27:29.915: WARN/dalvikvm(862): Unable to resolve superclass of Lorg/me/testgui/RGBLuminanceSource; (30)
    10-12 20:27:29.925: WARN/dalvikvm(862): Link of class 'Lorg/me/testgui/RGBLuminanceSource;' failed
    10-12 20:27:29.925: ERROR/dalvikvm(862): Could not find class 'org.me.testgui.RGBLuminanceSource', referenced from method org.me.testgui.TestClass.readBarcode
    10-12 20:27:29.936: WARN/dalvikvm(862): VFY: unable to resolve new-instance 68 (Lorg/me/testgui/RGBLuminanceSource;) in Lorg/me/testgui/TestClass;
    10-12 20:27:29.936: WARN/dalvikvm(862): VFY:  rejecting opcode 0x22 at 0x000d
    10-12 20:27:29.936: WARN/dalvikvm(862): VFY:  rejected Lorg/me/testgui/TestClass;.readBarcode (Ljava/lang/String;)V
    10-12 20:27:29.955: WARN/dalvikvm(862): Verifier rejected class Lorg/me/testgui/TestClass;
    10-12 20:27:29.975: DEBUG/AndroidRuntime(862): Shutting down VM
    10-12 20:27:29.985: WARN/dalvikvm(862): threadid=3: thread exiting with uncaught exception (group=0x4000fe70)
    10-12 20:27:29.985: ERROR/AndroidRuntime(862): Uncaught handler: thread main exiting due to uncaught exception
    10-12 20:27:30.075: ERROR/AndroidRuntime(862): java.lang.VerifyError: org.me.testgui.TestClass
    10-12 20:27:30.075: ERROR/AndroidRuntime(862):     at org.me.testgui.MainActivity.onCreate(MainActivity.java:182)
    10-12 20:27:30.075: ERROR/AndroidRuntime(862):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
    10-12 20:27:30.075: ERROR/AndroidRuntime(862):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2231)
    10-12 20:27:30.075: ERROR/AndroidRuntime(862):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2284)
    10-12 20:27:30.075: ERROR/AndroidRuntime(862):     at android.app.ActivityThread.access$1800(ActivityThread.java:112)
    10-12 20:27:30.075: ERROR/AndroidRuntime(862):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1692)
    10-12 20:27:30.075: ERROR/AndroidRuntime(862):     at android.os.Handler.dispatchMessage(Handler.java:99)
    10-12 20:27:30.075: ERROR/AndroidRuntime(862):     at android.os.Looper.loop(Looper.java:123)
    10-12 20:27:30.075: ERROR/AndroidRuntime(862):     at android.app.ActivityThread.main(ActivityThread.java:3948)
    10-12 20:27:30.075: ERROR/AndroidRuntime(862):     at java.lang.reflect.Method.invokeNative(Native Method)
    10-12 20:27:30.075: ERROR/AndroidRuntime(862):     at java.lang.reflect.Method.invoke(Method.java:521)
    10-12 20:27:30.075: ERROR/AndroidRuntime(862):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:782)
    10-12 20:27:30.075: ERROR/AndroidRuntime(862):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:540)
    10-12 20:27:30.075: ERROR/AndroidRuntime(862):     at dalvik.system.NativeStart.main(Native Method)
    10-12 20:27:30.105: INFO/Process(554): Sending signal. PID: 862 SIG: 3
    10-12 20:27:30.105: INFO/dalvikvm(862): threadid=7: reacting to signal 3
    10-12 20:27:30.356: INFO/dalvikvm(862): Wrote stack trace to '/data/anr/traces.txt

A: To answer the question and others raised:

*

*RGBLuminanceSource is in zxing under androidtest/

*If you didn't set the package properly in your copy, it would not have compiled

*VerifyError means it didn't like the bytecode. Sometimes, using Proguard causes this. If you want to do that, use the Proguard optimizaiton built into Android. But that's probably not the case here.

*It's probably that you have not put core.jar into your project quite right. Usually you just leave it in libs/ and it works.

*(Don't forget to pay attention to the  Apache License 2.0 terms if you use our code in your app.)

A:
VerifyError means that the class file contains bytecode that is
  syntactically correct but violates some semantic restriction e.g. a
  jump target that crosses method boundaries.

.

java.lang.VerifyError can be the result when you have compiled against
  a different library than you are using at runtime.

EDIT:
.
Check this for more info:
Causes of getting a java.lang.VerifyError
EDIT2:
ok, according to what you say, I guess you did not properly set the package of RGBLuminanceSource file. Since you copied this file into your project it should be in your package.
So change this:
package com.google.zxing.client.androidtest;

To this:
package org.me.correct.package;


text:
Q: How often do cities refresh their job list? In Nimblebit's Pocket Trains for iOS, you create your train empire by setting up a railroad network and managing your trains to pick up and deliver jobs from one city to another. Gameplay-wise, Pocket Trains is similar to Nimblebit's earlier release, Pocket Planes.
I noticed that jobs aren't refreshed as regularly in Pocket Trains as in Pocket Planes, with the latter having a very visible timer telling you when new jobs are arriving in a city. When are jobs refreshed in a city in Pocket Trains?

A: A post on the Nimblebit support center would suggest that jobs are refreshed for a train each time that train enters a new station.

Each engine has its own set of jobs that are not visible to other engines in the same station (with the exception of those stored in the yard).  There is not a way to refresh jobs while a train is at a station.  Jobs are refreshed for a train each time it enters a new station.

http://support.nimblebit.com/customer/portal/articles/1304390-refreshing-sharing-and-laying-over-jobs

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problem object cannot be cast to another object I have method, which sorting my data from db by countries in class Teams. Hibernate return my data in List<>. TeamsDao my hibernate Dao method. Teams was defined in 1 dependency.
My error log:
There was an unexpected error (type=Internal Server Error, status=500).
class com.champions.league.model.Teams cannot be cast to class com.champions.league.model.Teams (com.champions.league.model.Teams is in unnamed module of loader 'app'; com.champions.league.model.Teams is in unnamed module of loader org.springframework.boot.devtools.restart.classloader.RestartClassLoader @169e859a)
java.lang.ClassCastException: class com.champions.league.model.Teams cannot be cast to class com.champions.league.model.Teams (com.champions.league.model.Teams is in unnamed module of loader 'app'; com.champions.league.model.Teams is in unnamed module of loader org.springframework.boot.devtools.restart.classloader.RestartClassLoader @169e859a)

My League champions league class:
@Controller
@RequestMapping("/teams")
public class ChampLeagueController {

@GetMapping
public String showDesignForm(Model model){
   List<Teams> teamsList = TeamsDao.findAll();
    Teams.Countries[] countries = Teams.Countries.values();
    for(Teams.Countries country: countries){
        model.addAttribute(country.toString().toLowerCase(), filterByCountry(teamsList, country));
    }
    model.addAttribute("ChampionsLeague", new ChampionsLeague());
    return "ChampionsLeague";
}

public ArrayList<Teams> filterByCountry(List<Teams> teamsList, Teams.Countries country){
    ArrayList<Teams> sortedList = new ArrayList<>();
    for (Teams teams : teamsList) {
        if (teams.getCountries() == country)
            sortedList.add(teams);
    }
    return sortedList;
}

My Teams class:
@Entity
@Table(name = "teams")
public class Teams {
@Id
private int id;
private String name;
@Enumerated(EnumType.STRING)
private Countries countries;
public enum Countries{
    SPAIN, ENGLAND, GERMANY, ITALY, FRANCE, NETHERLANDS
}
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public Countries getCountries() {
    return countries;
}
public void setCountries(Countries countries) {
    this.countries = countries;
}

}

A: I suggest you delete your compiled classes by hand, and let all your sources recompile. I think I ran into such a problem once or twice, too... might be rare compiler bug.


text:
Q: Can a class be aliased in C#? In a namespace, is it possible to provide an alias for a class?  And if not, why not?
By example, if I had several libraries of things that were derived from a contained, but named base class, but wanted to alias that as "BaseClass", while retaining its actual class name (i.e. "HtmlControl").
Then consumers could always come along and extend from HtmlControls.BaseClass, without having to figure out which class it really comes from.

A: using SomeClass = Large.Namespace.Other.FunkyClass;

class Foo : SomeClass
{
}

A: You could create a dummy class that just inherits HtmlControl without adding any other functionality:
public class BaseClass : HtmlControl {}

A: There really isn't an ideal way to do this in C#/.NET. What you can do is have a public BaseClass that inherits from an internal class. You can change this inheritance internally without breaking your consumers as long as the interface to the class remains intact.
public class PublicBaseClass : SomeInternalClass {

}

Consumers inherit from PublicBaseClass, and as long as you are careful, you can change what SomeInternalClass is as you wish.

A: The closest I know of is to customize your using statement:
using BaseClass = HtmlControls.BaseClass;

This is normally used to avoid ambiguity between classes with the same name in different used namespaces, without having to fully qualify one or the other. Your devs would have to include it in every code file, so probably not a good solution for what you're doing.
As far as deriving from BaseClass without knowing what you are actually deriving from, not possible. The compiler must, at some level, know what and where the parent class is, meaning it must be statically defined somewhere in code.


text:
Q: Django Shows Page Source Instead Of My Webpage I have found that when passing context and a title into my views it causes the page to only show its html source code instead of the actual frontend graphics. If i remove the title being passed in then it works again but i do want to have the title passed in so is there any way to have this work?
Views
def myPosts(request):

    context = {
        'products': Post.objects.all()
    }

    return render(request, 'create/my_posts.html', context, {'title_page': 'My Posts'})

class PostListView(ListView):
    model = Post
    template_name = 'my_posts.html'
    context_object_name = 'products'

A: when you are passing context yo can do something like this
context = {
'products': Post.objects.all(),
'title_page': 'My Posts'
}
and finally pass
return render(request, 'create/my_posts.html', context)
In the front end, you can use it as context.title_page


text:
Q: Open Google Maps (or alternative) navigation with multiple destinations or waypoints I'm working on a cross platform (iOS & Android) javascript app that requires the user to follow a path made of several destinations.
   open map

With this code when user click open map in my app it open google or yandex maps navigation gps app and start to navigation from origin coordinate to destination coordinate
Is there a way to navigation on multiple destinations in Google-yandex Maps?I want to navigate use from source location to destination 1,destination 2.....

A: Yes- it seems you can pass multiple waypoints into a Google Maps URL using pipes.  This is specified in the Google Maps Developer Guide in the section about Waypoints.


text:
Q: Undo @Sql after each test I have some junit tests where I want to pre-populate the DB with some data that actually makes sense for the test:
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("test")
public class MyTest {

@Sql("test_insert.sql")
@Test
public void testInsert(){
  ...performs some inserts...
}
@Sql("test_delete.sql") //makes inserts to the db so to delete them
@Test
public void testDelete(){
    ...
}

I noticed that junit executes the tests by reverse order, meaning that my testDelete will be executed first.
Test insert seems to fail for a "duplicate row constraint" and that happens because the test_delete.sql scripts actually adds that row.
Would it to be possible to rollback the operations made by the @Sql and the test itself so that one test does not influence the others?

A: You just need to add @Transactional on top of the JUnit test class. This will revert all changes made to the database after every test has ran.
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("test")
@Transactional           //  <-- @Transactional added
public class MyTest {

@Sql("test_insert.sql")
@Test
public void testInsert(){
  ...performs some inserts...
}
@Sql("test_delete.sql") //makes inserts to the db so to delete them
@Test
public void testDelete(){
    ...
}


text:
Q: 3D bar chart with pgfplots I want to draw a three-dimensional bar chart. I used this MWE code to draw two-dimensionally. Is it possible to draw in 3D like the last photo?
MWE:(Source)
\documentclass{standalone}

\usepackage{pgfplots}

\begin{document}

    \pgfplotstableread[row sep=\\,col sep=&]{
        interval    & carT  & carD  & carR \\
        Type A      & 10    & 15    & 20 \\
        Type B      & 8     & 6     & 12 \\
        Type C      & 5     & 8     & 10 \\
        }\mydata

    \begin{tikzpicture}
        \begin{axis}[
                ybar,
                bar width=.5cm,
                width=\textwidth,
                height=.5\textwidth,
                legend style={at={(0.5,1)},
                    anchor=north,legend columns=-1},
                symbolic x coords={Type A, Type B, Type C},
                xtick=data,
                nodes near coords,
                nodes near coords align={vertical},
                ymin=0,ymax=35,
            ]
            \addplot table[x=interval,y=carT]{\mydata};
            \addplot table[x=interval,y=carD]{\mydata};
            \addplot table[x=interval,y=carR]{\mydata};
            \legend{AA, BB, CC}
        \end{axis}
    \end{tikzpicture}
\end{document}

The result is:

I want this output:


text:
Q: Possibly bricked PC after overclocking and frequency change I helped my friend configure some settings on his BIOS from his custom build PC he made not too long ago, what we did was change the frequency of the RAM, which wasn't too large, and was good as my friend said, and he also overclocked the CPU, which he also said was ok.
We were stuck at trying to save the settings we changed, and after pressing a couple of buttons, we exited the BIOS, and a black screen, after a while we forcefully shut it down, and rebooted it, then nothing happened as well, not a single thing outputting to the screen. I do remember when we were dealing with the RAM, we saw a setting called voltage or smth, so my assumption is since we didn't regulate the voltage in the RAM, could that have possibly bricked our computer? the weirdest thing is that nor the mouse or keyboard light up anymore.


text:
Q: How to handle python unicode string in javascript? A dict in which the string values are unicode string like {'name': u'nav', 'school': u'mps'}
In javascript, i'm trying access that dict like
<script>
var poi = {{ dict }}  ........... //Line #1
alert( poi.name )
</script>

while rending the html page line #1 is rendered as (error):
{'lastname': u'yadav', 'age': 23, 'id': 2, 'firstname': u'sahenky'}

One python solution is to encode the unicode string into some other format like ascii or utf-8(preferred)
str = u'nav'
str.encode('utf-8, 'ignore')
>>str
nav

Is there any elegant way to encode unicode string in python or javascript?

A: Instead of passing the actual dict to the template, JSON encode it first:
import json
json.dumps(dict)


text:
Q: Accessing in between entity in phoenix template I'm making kind of school presence tracker but I have encountered an issue. I have two main entities User, Event and entity presence in between of them bounding them together. I'm accessing main entity in Template, but i need to access relevant in between entity to read the state (if presence state 1 green bg if 0 red)
User:
schema "users" do
    field :login, :string
    field :password, :string

    #stuff

    has_many :presences, Presence
    has_many :events, through: [:presences, :event]

    timestamps
  end

Events:
schema "events" do
    field :name, :string

    #Stuff

    has_many :presences, Presence, on_delete: :fetch_and_delete
    has_many :users, through: [:presences, :user]
end

Presence:
schema "presences" do
    field :state, :integer

    belongs_to :user, Kpsz.Model.User, foreign_key: :user_id
    belongs_to :event, Kpsz.Model.Event, foreign_key: :event_id

    timestamps
end

And my problem is that i have no idea how to access that state thing because I'm using data like this.
template:

        Nazwa:
        <%= @event.name %>

    <%= for user <- @event.users do %>

          <%= user.class %>

        <div user_id="<%= user.id %>" event_id="<%= @event.id %>">
          Potwierdz

    <%= end %>

And finally Action:
def show(conn, %{"id" => id}) do
    event = Repo.get!(Event, id) |> Repo.preload([:users])
    render(conn, "show.html", event: event)
end

A: You can change your for comprehension to use the presences (which will be preloaded when preloading the users.) Each presence will contain the user that you require.
<%= for presence <- @event.presences do %>

      <%= presence.user.class %>

    <%= presence.state %>
    <div user_id="<%= presence.user.id %>" event_id="<%= @event.id %>">
      Potwierdz

<%= end %>


text:
Q: Custom numpy type causes crash in numpy.mean I defined my own numpy type with basic functionality in C++. Array creation works and it is possible to add and divide arrays of this type. It is possible to reduce the array with np.sum but the interpreter crashes when using np.mean.
import numpy as np
from example import Dual

x = np.array([Dual(1, 2), Dual(1, 3), Dual(1, 1)])
print(x.dtype)  # dtype(Dual)  -- correct type

# Mean 1
m = x.sum() / x.size
print(m.x, m.y)  # 1.0 2.0  -- correct result

# Mean 2
x.mean()  # -- CRASH

By inserting debug output in my C++ code I verified that sum and division are correctly computed in my code (3/3 and 6/3 are actually performed). So the function crashes after computing my result. (Windows tells me that Python stopped working, so presumably there happens a SegFault under the hood.)
What is mean doing differently than sum()/n? How can I modify my type to make it work?
I attempted to boil my C++ code down to create a minimal and complete example. Unfortunately, minimal is still rather long when defining a working numpy type. Here is the implementation:
#include <Python.h>
#include <numpy/arrayobject.h>
#include <numpy/npy_math.h>
#include <numpy/ufuncobject.h>

#include "structmember.h"

#include <iostream>
#include <math.h>

struct Dual
{
public:
    double x;
    double y;

    Dual(double x, double y) : x(x), y(y) { }

    inline static Dual add(const Dual& a, const Dual& b) {
        return Dual(a.x + b.x, a.y + b.y); }

    inline static Dual div(const Dual& a, const Dual& b) {
        return Dual(a.x / b.x, a.y / b.y); }
};

typedef struct {
    PyObject_HEAD
    Dual ob_val;
} PyDual;

PyArray_Descr* dual_descr;

static PyObject *
PyDual_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    PyDual *self;

    self = (PyDual *)type->tp_alloc(type, 0);
    if (self == NULL) {
        return NULL;
    }

    double x = 0;
    double y = 0;

    static char *kwlist[] = {"x", "y", NULL};
    if(!PyArg_ParseTupleAndKeywords(args, kwds, "d|d", kwlist, &x, &y))
        return NULL;

    self->ob_val = Dual(x, y);
    return (PyObject *)self;
}

static PyTypeObject PyDual_Type = {
    PyVarObject_HEAD_INIT(NULL, 0)
    "example.Dual",               /* tp_name */
    sizeof(PyDual),                /* tp_basicsize */
    0,                             /* tp_itemsize */
    0,                             /* tp_dealloc */
    0,                             /* tp_print */
    0,                             /* tp_getattr */
    0,                             /* tp_setattr */
    0,                             /* tp_reserved */
    0,                             /* tp_repr */
    0,                             /* tp_as_number */
    0,                             /* tp_as_sequence */
    0,                             /* tp_as_mapping */
    0,                             /* tp_hash  */
    0,                             /* tp_call */
    0,                             /* tp_str */
    0,                             /* tp_getattro */
    0,                             /* tp_setattro */
    0,                             /* tp_as_buffer */
    Py_TPFLAGS_DEFAULT,            /* tp_flags */
    "Dual value/derivative",       /* tp_doc */
    0,                             /* tp_traverse */
    0,                             /* tp_clear */
    0,                             /* tp_richcompare */
    0,                             /* tp_weaklistoffset */
    0,                             /* tp_iter */
    0,                             /* tp_iternext */
    0,                             /* tp_methods */
    0,                             /* tp_members */
    0,                             /* tp_getset */
    0,                             /* tp_base */
    0,                             /* tp_dict */
    0,                             /* tp_descr_get */
    0,                             /* tp_descr_set */
    0,                             /* tp_dictoffset */
    0,                             /* tp_init */
    0,                             /* tp_alloc */
    PyDual_new,                    /* tp_new */
};

static int PyDual_Check(PyObject* obj)
{
    return PyObject_IsInstance(obj, (PyObject*)&PyDual_Type);
}

static PyObject*
PyDual_from_Dual(Dual d)
{
    PyDual *obj = (PyDual*)PyDual_Type.tp_alloc(&PyDual_Type, 0);
    if(obj)
        obj->ob_val = d;
    return (PyObject*)obj;
}

static PyMemberDef PyDual_members[] = {
    {"x", T_DOUBLE, offsetof(PyDual, ob_val) + offsetof(Dual, x), READONLY, "value"},
    {"y", T_DOUBLE, offsetof(PyDual, ob_val) + offsetof(Dual, y), READONLY, "derivative"},
    {NULL}
};

//----------------------------------------------------------------------------

static PyArray_ArrFuncs _PyDual_ArrFuncs;

static void
DUAL_copyswap(Dual *dst, Dual *src, int swap, void *NPY_UNUSED(arr))
{
  PyArray_Descr *descr;
  descr = PyArray_DescrFromType(NPY_DOUBLE);
  descr->f->copyswapn(dst, sizeof(double), src, sizeof(double), 2, swap, NULL);
  Py_DECREF(descr);
}

static int DUAL_setitem(PyObject* item, void* data, void* ap)
{
  Dual d(0, 0);
  if(PyDual_Check(item)) {
    memcpy(data, &(((PyDual *)item)->ob_val),sizeof(Dual));
  } else if(PySequence_Check(item) && PySequence_Length(item)==4) {
    auto element = PySequence_GetItem(item, 0);
    if(element == NULL) { return -1; } /* Not a sequence, or other failure */
    d.x = PyFloat_AsDouble(element);
    Py_DECREF(element);
    element = PySequence_GetItem(item, 1);
    if(element == NULL) { return -1; } /* Not a sequence, or other failure */
    d.y = PyFloat_AsDouble(element);
    Py_DECREF(element);
  } else {
    PyErr_SetString(PyExc_TypeError,
                    "Unknown input to DUAL_setitem");
    return -1;
  }
  return 0;
}

static PyObject *DUAL_getitem(void* data, void* arr)
{
  Dual d(0, 0);
  memcpy(&d, data, sizeof(Dual));
  return PyDual_from_Dual(d);
}

template<typename T>
scalar_to_dual(T* ip, Dual* op, npy_intp n,
               PyArrayObject *NPY_UNUSED(aip), PyArrayObject *NPY_UNUSED(aop))
{
    while(n--)
    {
        op->x = *ip++;
        op->y = op->x;
    }
}

static void register_cast_function(int sourceType, int destType, PyArray_VectorUnaryFunc *castfunc)
{
  PyArray_Descr *descr = PyArray_DescrFromType(sourceType);
  PyArray_RegisterCastFunc(descr, destType, castfunc);
  PyArray_RegisterCanCast(descr, destType, NPY_NOSCALAR);
  Py_DECREF(descr);
}

static void sum_ufunc(char** args, npy_intp* dimensions, npy_intp* steps, void* data)
{
    char *ip1 = args[0], *ip2 = args[1], *op1 = args[2];
    npy_intp is1 = steps[0], is2 = steps[1], os1 = steps[2];
    npy_intp n = dimensions[0];
    for(npy_intp i=0; i<n; i++, ip1+=is1, ip2+=is2, op1+=os1)
    {
        const Dual in1 = *(Dual*)ip1;
        const Dual in2 = *(Dual*)ip2;
        *((Dual*)op1) = Dual::add(in1, in2);
    }
}

static void div_ufunc(char** args, npy_intp* dimensions, npy_intp* steps, void* data)
{
    char *ip1 = args[0], *ip2 = args[1], *op1 = args[2];
    npy_intp is1 = steps[0], is2 = steps[1], os1 = steps[2];
    npy_intp n = dimensions[0];
    for(npy_intp i=0; i<n; i++, ip1+=is1, ip2+=is2, op1+=os1)
    {
        const Dual in1 = *(Dual*)ip1;
        const Dual in2 = *(Dual*)ip2;
        *((Dual*)op1) = Dual::div(in1, in2);

        std::cout << in1.x << "/" << in2.x << std::endl;
        std::cout << in1.y << "/" << in2.y << std::endl;
    }
}

//----------------------------------------------------------------------------

static struct PyModuleDef examplemodule = {
   PyModuleDef_HEAD_INIT,
   "example",   /* name of module */
   NULL, /* module documentation, may be NULL */
   -1,       /* size of per-interpreter state of the module,
                or -1 if the module keeps state in global variables. */
   NULL, NULL, NULL, NULL, NULL
};

PyMODINIT_FUNC PyInit_example(void)
{
    // initialize numpy
    import_array(); if(PyErr_Occurred()) return NULL;
    import_umath(); if(PyErr_Occurred()) return NULL;
    auto numpy = PyImport_ImportModule("numpy"); if(!numpy) return NULL;
    auto numpy_dict = PyModule_GetDict(numpy); if(!numpy_dict) return NULL;

    PyDual_Type.tp_members = PyDual_members;

    PyDual_Type.tp_base = &PyGenericArrType_Type;

    if( PyType_Ready(&PyDual_Type) < 0)
        return NULL;

    PyArray_InitArrFuncs(&_PyDual_ArrFuncs);
    _PyDual_ArrFuncs.copyswap = (PyArray_CopySwapFunc*)DUAL_copyswap;
    _PyDual_ArrFuncs.setitem = (PyArray_SetItemFunc*)DUAL_setitem;
    _PyDual_ArrFuncs.getitem = (PyArray_GetItemFunc*)DUAL_getitem;

    dual_descr = PyObject_New(PyArray_Descr, &PyArrayDescr_Type);
    dual_descr->typeobj = &PyDual_Type;
    dual_descr->kind = 'x';
    dual_descr->type = 'x';
    dual_descr->byteorder = '=';
    dual_descr->flags = 0;
    dual_descr->type_num = 0; // assigned at registration
    dual_descr->elsize = 8*2;
    dual_descr->alignment = 8;
    dual_descr->subarray = NULL;
    dual_descr->fields = NULL;
    dual_descr->names = NULL;
    dual_descr->f = &_PyDual_ArrFuncs;
    dual_descr->metadata = NULL;
    dual_descr->c_metadata = NULL;

    Py_INCREF(&PyDual_Type);
    auto dualNum = PyArray_RegisterDataType(dual_descr);
    if(dualNum < 0) return NULL;

    int AD = dual_descr->type_num;

    register_cast_function(NPY_BOOL, dualNum, (PyArray_VectorUnaryFunc*)scalar_to_dual<npy_bool>);
    register_cast_function(NPY_LONG, dualNum, (PyArray_VectorUnaryFunc*)scalar_to_dual<npy_long>);
    register_cast_function(NPY_DOUBLE, dualNum, (PyArray_VectorUnaryFunc*)scalar_to_dual<npy_double>);

    int arg_types[] = {AD, AD, AD};

    PyUFuncObject* ufunc = (PyUFuncObject*)PyObject_GetAttrString(numpy, "add");
    PyUFunc_RegisterLoopForType(ufunc, AD, sum_ufunc, arg_types, NULL);

    ufunc = (PyUFuncObject*)PyObject_GetAttrString(numpy, "true_divide");
    PyUFunc_RegisterLoopForType(ufunc, AD, div_ufunc, arg_types, NULL);

    auto module = PyModule_Create(&examplemodule);
    if( module == NULL )
        return NULL;

    Py_INCREF(&PyDual_Type);
    PyModule_AddObject(module, "Dual", (PyObject*)&PyDual_Type);
    return module;
}

A: In retrospect, the error was pretty much obvious and not related to the numpy part of the implementation but to the initialization of the Python object. Credit goes to @hpaulj's comment, which put me on the right track.
Both x.mean and np.mean call np.core._methods.mean, where the crash happens in the line
ret = ret.dtype.type(ret / rcount)

This is a redundant type conversion (at least in my case) which is equivalent to
Dual(dual_object)

In words, the Dual constructor is called with an instance of Dual as argument. However, the implementation of the constructor expects two doubles as arguments:
static char *kwlist[] = {"x", "y", NULL};
if(!PyArg_ParseTupleAndKeywords(args, kwds, "d|d", kwlist, &x, &y))
    return NULL;

PyArg_ParseTupleAndKeywords crashes when attempting to forcefully cast Dual to double. This is another issue to look into, but the original problem is solved by implementing the relevant conversions in the constructor.

A: maybe it is a silly observation, but did you try:
import numpy as np

###code

np.mean(x)  # instead of x.mean?

According to the documentation:


text:
Q: PHP - Same Page Call Back Using Post I have an array in php containing details to do with an application, for example an id, a name, a date created an invoice and so on.
I am currently displaying to the user the application name as a URL so that ideally when they click it they can see some other details that I can look up from the database based on the attributes above.
I recall during university a few years ago that I can use POST with an html form to send this - correct? However i am a little confused as I don't really need any information to be shown to the user in terms of a form - for example no input box is needed, the submit button really is the link I am providing and so on.
In this case how do I create a solution using my URL approach to call back to the current page
For example something like this works with GET
Click here

<?php
    if(isset($_GET["data"]) && isset($_GET["data2"]))
    {
        $data = $_GET["data"];
        $data2 = $_GET["data2"];
    }
?>

But using via GET is not ideal as it will allow others to guess personal information which would be an issue

A: try passing some parameters using $_GET. That way the user will be able to view some parameters in the ULR page, but you wont need another page to show this user their details.

A: You can use form with hidden element and only visible element is button...
<form method="post">
    <input type="hidden" />
</form>

Something like this...

A: Then try using jquery to show/hide some page content. for example:
click me

some hidden content. when you click the link, it will be visible


text:
Q: programmatically appending query params to route if queryparam is used I am prepared to spend the day researching this, but I hope you guys have answer as I think otherwise this would be an all day thing.
I have the following variables
  inputCity;
  inputGuestNumber;
  inputCapacitySelected;
  inputCuisineSelected;
  inputPrivacySelected;
  inputVenueTypeSelected;
  inputAmenitiesSelected;
  inputNeighborhoodSelected;

these variables may or may not be populated or defined depending on what information a user enters into a form.
I have the current router set up:
onSubmit(){
    this.router.navigate(['/venue-list',
    this.inputCity], {queryParams:{guestCount: this.inputGuestNumber, countOption: this.inputCapacitySelected,
    cuisineSelected:this.inputCuisineSelected, privacySelected:this.inputPrivacySelected,
      venueTypeSelected: this.inputVenueTypeSelected, amenitiesSelected: this.inputAmenitiesSelected,
    neighborhoodSelected: this.inputNeighborhoodSelected}

  });

I set it up this way hoping that if a queryparam was undefinded it would be ignored, instead all the queryparams are appended.
So now I am hoping to append the query params to the queryparams argument, if the query param is used. I have no idea how to do this and have started my research.
default values are not acceptable as it would still produce a gross url. Thank you all very much

A: This is quite tricky as there are lots of open issues for the same .
One such issue in git - https://github.com/angular/angular/issues/12347
Either you have to have optional routes like one for each type of query param eg
const routes: Routes = [
    { path: '', component: HomeComponent },
    { path: ':product', component: ProductComponent, resolve: { product: ProductResolver } },
    { path: ':product/:card', component: ProductComponent, resolve: { product: ProductResolver } },
    { path: ':product/:group/:card', component: ProductComponent, resolve: { product: ProductResolver } }];

Or you can take a look at this code i found in one of the gists on github . You can use in your router resolve. to get the params and check.
Link for the same - https://gist.github.com/e-oz/5a95f50336e68623f9e0
export class UrlParser
{
  getParameter(key) {
    return this.getParameters()[key];
  }

  getParameters() {
    // http://stackoverflow.com/a/2880929/680786
    var match,
      pl = /\+/g,  // Regex for replacing addition symbol with a space
      search = /([^&=]+)=?([^&]*)/g,
      decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
      query = window.location.search.substring(1);

    let urlParams = {};
    while (match = search.exec(query)) {
      urlParams[decode(match[1])] = decode(match[2]);
    }
    return urlParams;
  }

  setParameter(key:string, value) {
    let params = this.getParameters() || {};
    if (params[key]==value) {
      return true;
    }
    params[key] = value;
    let search = [];
    for (let k in params) {
      if (params.hasOwnProperty(k)) {
        search.push(encodeURIComponent(k)+"="+encodeURIComponent(params[k]));
      }
    }
    let query = '?'+search.join('&');
    let history = DOM.getHistory();
    if (history && history.replaceState) {
      history.replaceState(null, '', location.pathname+query);
    } else {
      return false;
    }
    return true;
  }
}

UPDATE
I think it has been handled in the new router as mentioned in one of tickets on GIT  - https://github.com/angular/angular/issues/3525
Now the optional routes are seperated by localhost:3000/heroes;id=15;foo=foo ";".
The id value appears in the URL as (;id=15;foo=foo), not in the URL path. The path for the "Heroes" route doesn't have an :id token.
The optional route parameters are not separated by "?" and "&" as they would be in the URL query string. They are separated by semicolons ";" This is matrix URL notation — something you may not have seen before.
Take a look at this link might help - https://angular.io/guide/router#route-parameters-required-or-optional

A: I'm not sure if there's any easy way to conditionally add the parameters, other than manually going through each one individually.  What would probably be easier is to build the whole object and then filter out and delete the ones that are missing.
onSubmit() {
    const queryParams = {
        guestCount: this.inputGuestNumber, countOption: this.inputCapacitySelected,
        cuisineSelected:this.inputCuisineSelected, privacySelected:this.inputPrivacySelected,
        venueTypeSelected: this.inputVenueTypeSelected, amenitiesSelected: this.inputAmenitiesSelected,
        neighborhoodSelected: this.inputNeighborhoodSelected
    }

    Object.keys(queryParams)
        .filter(key => queryParams[key] === null || queryParams[key] === undefined)
        .forEach(key => delete queryParams[key])

    this.router.navigate(['/venue-list', this.inputCity], {queryParams})
}


text:
Q: Lasso Regression - model predictions are not correct. low r-squared I am attempting to use Lasso to choose the best variables from a set of 20.
I have managed to construct a model using LassoCV, however when using the test data to compare the predicted returns to the actual returns they are very different. Predicted returns are much smaller.
I get a low MSE, however i get a negative R^2. My R^2 is for the actual returns against the predicted returns.
The diagram below shows the predicted returns via Lasso model and the actual returns. Green is the PREDICTED.

Am I doing something wrong upon constructing this model?
Model construction:
best_model = LassoCV(alphas=alphas_lasso,cv=5, max_iter=1000).fit(predictors, returns.values.ravel())
returns_pred = best_model.predict(predictors)


text:
Q: How to implement onClickListener inside DialogBox which is inside Fragment in android studio? I want to implement View.onClickListener inside DialogPlus but i dont know how to implement it inside Dialogbox .
I have implemented and overriden onClickListener in ExpenseFragment class and performed fab.setOnClickListener(this) it's working fine.
In the same way i also want to perform someIV.setOnClickListener(this) and perform required action in dialogView which is inside addNote().

Here's my code ....

public class ExpenseFragment extends Fragment implements View.OnClickListener {
    private TextView totalExpenseTV;
    private FloatingActionButton fab;
    private RecyclerView recyclerView;
    private ImageView filterIcon;
    private PieChart pieChart;

    private Animation rotateForward, rotateBackward;

    private FirebaseRecyclerOptions<ExpenseModel> options;
    private MyAdapter adapter;

    private int calendarImgClick = 0;

    public void onViewCreated(@NonNull View attachInParentView, Bundle savedInstanceState) {
        super.onViewCreated(attachInParentView, savedInstanceState);
        findViewByIDS(attachInParentView);
        setupRecyclerView();
        fabAnimation();
        fab.setOnClickListener(this);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_expense, container, false);
    }

    private void fabAnimation() {
        rotateForward = AnimationUtils.loadAnimation(getActivity(), R.anim.rotate_forward);
        rotateBackward = AnimationUtils.loadAnimation(getActivity(), R.anim.rotate_backward);
        rotateBackward.setDuration(300);
        rotateForward.setDuration(300);
    }

    @Override
    public void onClick(View view) {
        fab.startAnimation(rotateForward);
        rotateForward.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                addNote();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    private void addNote() {
        if (getActivity() != null) {
            DialogPlus dialog = DialogPlus.newDialog(getActivity())
                    .setContentHolder(new ViewHolder(R.layout.add_expense_layout))
                    .setExpanded(false)
                    .setOnDismissListener(new OnDismissListener() {
                        @Override
                        public void onDismiss(DialogPlus dialog) {
                            fab.startAnimation(rotateBackward);
                        }
                    })
                    .create();

            View myView = dialog.getHolderView();
            TextView expense_date = myView.findViewById(R.id.expense_date);
            EditText expense_title = myView.findViewById(R.id.expense_title);
            EditText expense_amount = myView.findViewById(R.id.expense_amount);
            Button add_note_button = myView.findViewById(R.id.add_note_btn);
            ImageView calendarImg = myView.findViewById(R.id.add_calendar);
            CalendarView calendarView = myView.findViewById(R.id.calenderView);
            LinearLayout linearLayout = myView.findViewById(R.id.linearCalenderLayout);

            ImageView grocery = myView.findViewById(R.id.grocery);
            ImageView bike = myView.findViewById(R.id.bike);
            ImageView rent= myView.findViewById(R.id.rent);
            ImageView foods = myView.findViewById(R.id.foods);
            ImageView beer= myView.findViewById(R.id.beer);
            LinearLayout categoryIconsLayout = myView.findViewById(R.id.categoryIconsLayout);
            TextView selectCategory_heading = myView.findViewById(R.id.selectCategory_heading);

            calendarImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    setCalendarVisibility(linearLayout, selectCategory_heading, categoryIconsLayout);
                }
            });

            dialog.show();
        }
    }

    private void setCalendarVisibility(LinearLayout setCalendarVisible, TextView setSelectCateVisible, LinearLayout iconsLayoutVisible) {
        calendarImgClick++;
        if (calendarImgClick >= 2) {
            setCalendarVisible.setVisibility(View.GONE);
            setSelectCateVisible.setVisibility(View.VISIBLE);
            iconsLayoutVisible.setVisibility(View.VISIBLE);
            calendarImgClick = 0;
        } else {
            setCalendarVisible.setVisibility(View.VISIBLE);
            setSelectCateVisible.setVisibility(View.GONE);
            iconsLayoutVisible.setVisibility(View.GONE);

        }

    }

    private void animateCalendarView(LinearLayout ll, CalendarView cv) {
        ll.animate().rotationBy(-180f).setDuration(500);
        cv.animate().rotationBy(180f).setDuration(400);

    }

    private void findViewByIDS(View v) {
        totalExpenseTV = v.findViewById(R.id.totalRsTitle);
        fab = v.findViewById(R.id.fab);
        recyclerView = v.findViewById(R.id.recyclerView);
        filterIcon = v.findViewById(R.id.filterIcon);
        pieChart = v.findViewById(R.id.pieChartHis);

    }

    private void setupRecyclerView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(null);
        if (getActivity() != null) {
            Query query = FirebaseReference.expenseReference(getActivity())
                    .orderByChild("milli");
            options = new FirebaseRecyclerOptions.Builder<ExpenseModel>()
                    .setQuery(query, ExpenseModel.class)
                    .build();

            adapter = new MyAdapter(options, getActivity());
            recyclerView.setAdapter(adapter);
        }
    }

    // OS operations starts here . . . . . . .
    @Override
    public void onStart() {
        super.onStart();
        adapter.startListening();
    }

    @Override
    public void onStop() {
        super.onStop();
        adapter.stopListening();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        adapter.stopListening();
    }

}


text:
Q: Create Audit Log Script w/ Custom Dates The following PowerShell script pulls all the content from a specified SharePoint site and creates an audit log for all versions and dates. My Question is how would I implement a Start/End date? For example I would like to view only the items between 10/3/2014 and 10/5/2014.
$web = Get-SPWeb http://<SharePoint Site>
ForEach($list in $web.Lists)
{
 ForEach($item in $list.Items)
 {
  ForEach($version in $item.Versions)
  {
    $fullURL = "$($web.URL)$($list.URL)/$($version.URL)"
    "{0}`t{1}`t{2}`t{3}`t{4}" -f $fullURL, $version.VersionLabel, $version.CreatedBy.User.UserLogin, $version.Created, $list.BaseType  | out-file Versions.csv -Append
  }
 }
}

A: Try this
$web = Get-SPWeb http://devintranet.tokiomillennium.com/operations/claims
$startDate = [datetime]::ParseExact("10/03/14", "dd/MM/yy", $null)
$endDate = [datetime]::ParseExact("10/05/14", "dd/MM/yy", $null)

ForEach($list in $web.Lists)
{
    ForEach($item in $list.Items)
    {
        ForEach($version in $item.Versions)
        {
            if($version.Created -ge $startDate -AND $version.Created -le $endDate)
            {
                $fullURL = "$($web.URL)$($list.URL)/$($version.URL)"
                "{0}`t{1}`t{2}`t{3}`t{4}" -f $fullURL, $version.VersionLabel, $version.CreatedBy.User.UserLogin, $version.Created, $list.BaseType  | out-file Versions.csv -Append
            }
        }
    }
}


text:
Q: Trying to control scaling for a nested SVG element An application I'm working on uses a simple SVG to represent a reported value within set upper and lower bounds as a square on top of a horizontal line. The elements are then rendered within an HTML  which has a fixed vertical dimension but adaptive horizontal. The SVG currently scales as a single object, meaning that the square can be squashed or stretched into a rectangle, which I'd like to avoid. I've been trying to use nested SVG elements with defined viewports and viewboxes so that I can control the aspect ratio of the square, but I'm having no luck.
Here's my latest attempt:

<svg class="va-kpv-graph-image" viewBox="0 0 400 50" preserveAspectRatio="none"
    xmlns="http://www.w3.org/2000/svg" xmlns:xlink= "http://www.w3.org/1999/xlink">

    <svg>
        <line x1="0" y1="25" x2="400" y2="25" style="stroke:black; stroke-width: 2px" />
        <line x1="1" y1="0" x2="1" y2="50" style="stroke:black; stroke-width: 2px" />
        <line x1="399" y1="0" x2="399" y2="50" style="stroke:black; stroke-width: 2px" />
    </svg>

    <svg x="154" y="0" width="42" height="50" viewbox="0 0 42 50" preserveAspectRatio="xMidYMid meet">
            <rect x="1" y="5" width="40" height="40" rx="10" ry="10" style="fill:blue; stroke:black;stroke-width:2px" />
    </svg>
</svg>

Can someone tell me what I'm doing wrong or if I'm just misunderstanding something about this?
Thanks in advance.
Edit: for clarification, the three lines should be allowed to scale without preserving the aspect ratio and the overall SVG should always fill the area taken up by the div. It's just the square that should keep its aspect.


text:
Q: In C++, is it possible to initialize an array directly from another? In C++, is it possible to initialize a built-in array directly from another? As far as I know, one can only have an array and then copy/move each element from another array to it, which is some kind of assignment, not initialization.

A: That is one of the new features of the std::array in C++ 11.
std::array <int, 5> a = {1, 2, 3, 4, 5};
std::array <int ,5> b = a;

The latter copies the array a into b.

A: Arrays have neither the copy constructor nor the copy assignment operator. You can only copy elements from one array to another element by element.
Character arrays can be initialized by string literals. Or strings can be copied using standard C functions like strcpy, strncpy, memcpy declared in header <cstring>.
For other arrays you can use for example standard algorithms std::copy, std::copy_if, std::transform declared in header <algorithm>.
Otherwise you can use either standard container std::array or std::vector that allow to assign one object of the type to another object of the same type or create one object from another object.


text:
Q: Count triangles (cycles of length 3) in a graph In an undirected graph with V vertices and E edges how would you count the number of triangles in O(|V||E|)? I see the algorithm here but I'm not exactly sure how that would be implemented to achieve that complexity. Here's the code presented in that post:
for each edge (u, v):
  for each vertex w:
     if (v, w) is an edge and (w, u) is an edge:
          return true
return false

Would you use an adjacency list representation of the graph to traverse all edges in the outer loop and then an adjacency matrix to check for the existence of the 2 edges in the inner loop?
Also, I saw a another solution presented as O(|V||E|) which involves performing a depth-first search on the graph and when you encounter a backedge (u,v) from the vertex u you're visiting check if the grandparent of the vertex u is vertex v. If it is then you have found a triangle. Is this algorithm correct? If so, wouldn't this be O(|V|+|E|)? In the post I linked to there is a counterexample for the breadth-first search solution offered up but based on the examples I came up with it seems like the depth-first search method I outlined above works.

A: Firstly, note that the algorithm does not so much count the number of triangles, but rather returns whether one exists at all.
For the first algorithm, the analysis becomes simple if we assume that we can do the lookup of (a, b) is an edge in constant time. (Since we loop over all vertices for all edges, and only do something with constant time we get O(|V||E|*1). ) Telling whether something is a member of a set in constant time can be done using for example a hashtable/set. We could also, as you said, do this by the use of the adjacency matrix, which we could create beforehand by looping over all the edges, not changing our total complexity.
An adjacency list representation for looping over the edges could perhaps be used, but traversing this may be O(|V|+|E|), giving us the total complexity O(|V||V| + |V||E|) which may be more than we wanted. If that is the case, we should instead loop over this first, and add all our edges to a normal collection (like a list).
For your proposed DFS algorithm, the problem is that we cannot be sure to encounter a certain edge as a backedge at the correct moment, as is illustrated by the following counterexample:
A -- B --- C -- D
      \   /     |
        E ----- F

Here if we look from A-B-C-E, and then find the backedge E-B, we correctly find the triangle; but if we instead go A-B-C-D-F-E, the backedges E-B, and E-C, do no longer satisfy our condition.

A: This is a naive approach to count the number of cycles.
We need the input in the form of an adjacency matrix.
public int countTricycles(int [][] adj){
        int n = adj.length;
        int count = 0;
        for(int i = 0; i < n ;i++){
            for(int j = 0; j < n; j++){
                if(adj[i][j] != 0){
                    for(int k = 0; k < n; k++){
                        if(k!=i && adj[j][k] != 0 && adj[i][k] != 0 ){
                             count++;
                        }
                    }
                }
            }
        }
        return count/6;
    }

The complexity would be O(n^3).


text:
Q: Poor Cluster Shared Volume performance when node is not CSV owner We have a 5 node Windows Server 2016 Failover Cluster setup using an HPE Nimble as shared storage. We're using the cluster for Hyper-V. All virtual machine VHDXs are stored on the cluster shared volume (CSV).
We're having a problems with disk performance within VMs when the VM is running on a node which does not own the CSV storage.
Transferring files via SMB between VMs when they are both running on a node which owns the CSV speeds are between 1.5GB/s and 2GB/s. If you take the storage ownership away from that node, speeds drop to ~100MB/s.
This seems like the storage traffic is going via the 1GB network, through the owner node then into the SAN. From what I understand this shouldn't be the case unless the CSV has been set to redirected mode. (I've not confirmed this with Wireshark or anything yet, working on that)
I've run the command Get-ClusterSharedVolumeState which returned the following:

BlockRedirectedIOReason      : NotBlockRedirected
FileSystemRedirectedIOReason : NotFileSystemRedirected
Name                         : Cluster Disk 1
Node                         : HyperV03
StateInfo                    : Direct
VolumeFriendlyName           : VM-CSV
VolumeName                   : \\?\Volume{9323278e-8374-474c-b9e7-1097305c0d1f}\

BlockRedirectedIOReason      : NotBlockRedirected
FileSystemRedirectedIOReason : NotFileSystemRedirected
Name                         : Cluster Disk 1
Node                         : Hyperv06
StateInfo                    : Direct
VolumeFriendlyName           : VM-CSV
VolumeName                   : \\?\Volume{9323278e-8374-474c-b9e7-1097305c0d1f}\

BlockRedirectedIOReason      : NotBlockRedirected
FileSystemRedirectedIOReason : NotFileSystemRedirected
Name                         : Cluster Disk 1
Node                         : hyperv05
StateInfo                    : Direct
VolumeFriendlyName           : VM-CSV
VolumeName                   : \\?\Volume{9323278e-8374-474c-b9e7-1097305c0d1f}\

BlockRedirectedIOReason      : NotBlockRedirected
FileSystemRedirectedIOReason : NotFileSystemRedirected
Name                         : Cluster Disk 1
Node                         : Hyperv04
StateInfo                    : Direct
VolumeFriendlyName           : VM-CSV
VolumeName                   : \\?\Volume{9323278e-8374-474c-b9e7-1097305c0d1f}\

BlockRedirectedIOReason      : NotBlockRedirected
FileSystemRedirectedIOReason : NotFileSystemRedirected
Name                         : Cluster Disk 1
Node                         : Hyperv02
StateInfo                    : Direct
VolumeFriendlyName           : VM-CSV
VolumeName                   : \\?\Volume{9323278e-8374-474c-b9e7-1097305c0d1f}\

According to this output redirection isn't the cause of the issue.
Can anyone think of a reason why else this might be happening?
Connections to the SAN have all been setup using HPE Windows Toolkit which configures the MPIO settings and various other bits for you. We've confirmed all nodes are able to hit transfers speeds of the expected 1GB/s+ but only when that node takes ownership of the CSV.
Thanks

A: You can check file system type under CSV volumes. It can be NTFS and ReFS. ReFS has this limitation that it is always redirecting traffic to owner hyperV node.


text:
Q: Fatal Exception: main - Streaming Android I'm trying to run an application from the book Pro Android Media to understand the functioning of streams. However, the following error is happening:
12-26 16:32:31.464: E/AndroidRuntime(508): FATAL EXCEPTION: main
12-26 16:32:31.464: E/AndroidRuntime(508): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.streaming/com.example.streaming.Streaming}: java.lang.ClassNotFoundException: com.example.streaming.Streaming in loader dalvik.system.PathClassLoader[/data/app/com.example.streaming-2.apk]
12-26 16:32:31.464: E/AndroidRuntime(508):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
12-26 16:32:31.464: E/AndroidRuntime(508):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
12-26 16:32:31.464: E/AndroidRuntime(508):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
12-26 16:32:31.464: E/AndroidRuntime(508):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
12-26 16:32:31.464: E/AndroidRuntime(508):  at android.os.Handler.dispatchMessage(Handler.java:99)
12-26 16:32:31.464: E/AndroidRuntime(508):  at android.os.Looper.loop(Looper.java:123)
12-26 16:32:31.464: E/AndroidRuntime(508):  at android.app.ActivityThread.main(ActivityThread.java:4627)
12-26 16:32:31.464: E/AndroidRuntime(508):  at java.lang.reflect.Method.invokeNative(Native Method)
12-26 16:32:31.464: E/AndroidRuntime(508):  at java.lang.reflect.Method.invoke(Method.java:521)
12-26 16:32:31.464: E/AndroidRuntime(508):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
12-26 16:32:31.464: E/AndroidRuntime(508):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
12-26 16:32:31.464: E/AndroidRuntime(508):  at dalvik.system.NativeStart.main(Native Method)
12-26 16:32:31.464: E/AndroidRuntime(508): Caused by: java.lang.ClassNotFoundException: com.example.streaming.Streaming in loader dalvik.system.PathClassLoader[/data/app/com.example.streaming-2.apk]
12-26 16:32:31.464: E/AndroidRuntime(508):  at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243)
12-26 16:32:31.464: E/AndroidRuntime(508):  at java.lang.ClassLoader.loadClass(ClassLoader.java:573)
12-26 16:32:31.464: E/AndroidRuntime(508):  at java.lang.ClassLoader.loadClass(ClassLoader.java:532)
12-26 16:32:31.464: E/AndroidRuntime(508):  at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
12-26 16:32:31.464: E/AndroidRuntime(508):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
12-26 16:32:31.464: E/AndroidRuntime(508):  ... 11 more
12-26 16:51:14.974: D/AndroidRuntime(1433): Shutting down VM
12-26 16:51:15.054: W/dalvikvm(1433): threadid=1: thread exiting with uncaught exception (group=0x4001d800)

The codes:
ViewTheVideo
package com.example.streaming;

import com.example.streaming.R;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;

public class ViewTheVideo extends Activity {
    VideoView vv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
        vv = (VideoView) this.findViewById(R.id.VideoView);
Uri videoUri = Uri.parse("rtsp://v2.cache2.c.youtube.com/CjgLENy73wIaLwm3JbT_� 9HqWohMYESARFEIJbXYtZ29vZ2xlSARSB3Jlc3VsdHNg _vSmsbeSyd5JDA==/0/0/0/video.3gp");
        vv.setMediaController(new MediaController(this));
        vv.setVideoURI(videoUri);
        vv.start();
}

}
Main.xml
            <?xml version="1.0" encoding="utf-8"?>
            <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:orientation="vertical"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                >
            <VideoView android:layout_width="wrap_content"
                       android:layout_height="wrap_content"
                       android:id="@+id/VideoView">
            </VideoView>
            </LinearLayout>

AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.streaming"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="8" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity android:name = ".Streaming"
              android:label = "@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name = "android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>

I will waiting to the answer to my question.
Thanks guys!

A: Change
public class ViewTheVideo extends Activity {
//....your code here

to
public class Streaming extends Activity {
//....your code here

because you are declaring Activity in AndroidManifest as .Streaming but in java Class name is ViewTheVideo
OR
you can also just change name in  AndroidManifest as :
 <activity android:name = ".ViewTheVideo"
              android:label = "@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name = "android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>


text:
Q: (Notepad++) How to replace a text that has certain word in that line? I have multiple lines like this:
{
"source": "Source A",
"target": "Source B",
"idTarget": "3,345",
"strength": "0.5",
"value": "633.5138"
}
{
"source": "Source C",
"target": "Source D",
"idTarget": "1,253",
"strength": "0.7",
"value": "5465.238"
}

I want to remove the . (dot) in line that has the word value, but not on other lines. So it would look something like this:
{
"source": "Source A",
"target": "Source B",
"idTarget": "3,345",
"strength": "0.5",
"value": "6335138"
}
{
"source": "Source C",
"target": "Source D",
"idTarget": "1,253",
"strength": "0.7",
"value": "5465238"
}

Any way to do this?

A: *

*Ctrl+H

*Find what: ^"value":[^.]+\K\.

*Replace with: LEAVE EMPTY

*UNcheck Match case

*check Wrap around

*check Regular expression

*DO NOT CHECK . matches newline

*Replace all
Explanation:
^           : begining of line
  "value":  : literally
  [^.]+     : 1 or more not dot
  \K        : forget all we have seen until this position
  .         : a dot

Result for given example:
{
"source": "Source A",
"target": "Source B",
"idTarget": "3,345",
"strength": "0.5",
"value": "6335138"
}
{
"source": "Source C",
"target": "Source D",
"idTarget": "1,253",
"strength": "0.7",
"value": "5465238"
}

A: Assuming your numbers are always formatted like 123.1234, you can use a regular expression to achieve this:
Find what: "value": "([0-9]+)\.([0-9]+)"
Replace with: "value": "$1$2"
Search mode: Regular expression
This search expression will find strings that match "value": "<numbers>.<numbers>" and put the numbers that it found in a "capture group", denoted with the round brackets. Both groups ($1, $2) are then added back into the replaced text without the dot.


text:
Q: Is there any possibility to circumvent the size of the packet sent to the datagram? [Errno 10040] I'm trying to create an app using python, to watch together movies, but I constantly getting errors with :
[Errno 10040] A message sent on a datagram socket was larger than the internal message buffer or some other network limit, or the buffer used to receive a datagram was smaller than the datagram itself
Server.py
BUFFOR_SIZE_DATA = 65536

# SERVER SETTINGS
server_socket_main = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket_main.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, BUFFOR_SIZE_DATA)

print(Fore.RED + 'UDP Server')
host_name = socket.gethostname()
print('HOST NAME:',host_name)
host_ip_adress = ''
print('HOST IP:',host_ip_adress)
host_port = 1337
socket_adress_main = (host_ip_adress, host_port)
print('PORT:',host_port)
server_socket_main.bind(socket_adress_main)
print(Fore.GREEN + 'Server is listening > > >')
print(Fore.WHITE + ' ')
print(Fore.WHITE + 'Connected devices: ')

# VIDEO U WANT TO WATCH TOGETHER
server_video_main = cv2.VideoCapture('movies/exmpl.mp4')

# MAIN LOOP
while True:
    msg, client_addres_obligatory = server_socket_main.recvfrom(BUFFOR_SIZE_DATA)
    print('Connected from ', client_addres_obligatory)
    WIDTH = 1024
    while(server_video_main.isOpened()):
        _,frame = server_video_main.read()
        frame = imutils.resize(frame, width=WIDTH)
        encoded, buffer = cv2.imencode('.jpg', frame, [cv2.IMWRITE_JPEG_QUALITY, 80])
        message = base64.b64encode(buffer)
        server_socket_main.sendto(message, client_addres_obligatory)
        cv2.imshow('HOST | Currently hosting', frame)
        key = cv2.waitKey(1) & 0xFF
        if key == ord('c'):
            server_socket_main.close()
            break

Client.py
client_socket_main.sendto(welcomemessage.encode(), (client_ip_adress, client_port))

while True:
    packet,_ = client_socket_main.recvfrom(BUFFOR_SIZE_DATA)
    data = base64.b85decode(packet,' /')
    npdata = np.fromstring(data, dtype=np.unit8)
    frame = cv2.imdecode(npdata, 1)
    cv2.imshow('Currently watching ', frame)
    key = cv2.waitKey(1) & 0xFF
    if key == ord('c'):
        client_socket_main.close()
        break

data = base64.b85decode(packet,' /')

TypeError: b85decode() takes 1 positional argument but 2 were given
Thanks in advance!

A: The 64KiB limit is determined not by UDP but by IP. Here's the IPv4 header from the original RFC:
    0                   1                   2                   3
    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |Version|  IHL  |Type of Service|          Total Length         |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |         Identification        |Flags|      Fragment Offset    |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |  Time to Live |    Protocol   |         Header Checksum       |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                       Source Address                          |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                    Destination Address                        |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                    Options                    |    Padding    |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

See that "Total Length" field? It's 16 bits, so its maximum value is 0xffff, which is 64Ki. That even includes headers, so the actual maximum size is smaller.
Additionally, the typical MTU on the internet is 1500 bytes, sometimes less (again, including headers). Sending packets larger than the MTU is a recipe for trouble because it means that IP fragmentation will take place, which is not desirable.
You need to break up the data into smaller chunks or use TCP which takes care of that for you.


text:
Q: How to create user page for each user from react and firebase I am new to react and firebase authentication. I wanted to know how to create a page for each user signed in, in my website. For example, a user named "Max" signed up in my webpage and the program should make a user page for him. So when another user goes to "Myapp.com/user/max" it should show Max's page.
Can you give me concept and idea for it?
My signup looks like this:-

import React from "react"
import { useHistory } from "react-router-dom"
import firebase from "firebase/app"
import "./firebase"
import fire from "./firebase"
function Signup(){
    const history = useHistory()
    function signUp(){
        let uEmail = document.getElementById("email").value;
        let uPassword = document.getElementById("password").value;
        let userName = document.getElementById("userName").value;
        async function send(email, password){
            await firebase.auth().createUserWithEmailAndPassword(email, password).then(()=>{
                console.log("successfull");
                let userID = firebase.auth().currentUser.uid;
                console.log(userID)
                firebase.database().ref("users/"+userID+"/praivate/login credentials").set({
                    "userName": userName,
                    "userId": userID,
                })
            })
            history.push("./login")
        }
        send(uEmail, uPassword);
    }
    return(
        <div id = "signUp">
               <input id = "email" placeholder = "email" />
               <input id = "password" placeholder = "password" />
               <input id = "userName" placeholder = "username" />
               <button onClick = {signUp}>Enter</button>
        </div>
    )
}
export default Signup

and my app js looks like this:-

import check from "./component/checkAt"
import './App.css';
import Nav from "./component/nav"
import Header from "./component/header"
import About from "./component/about"
import Home from "./component/home"
import Login from "./component/login"
import { Route, BrowserRouter as Router, Switch, Redirect } from 'react-router-dom';
import fire from "./component/firebase";
import Signup from "./component/Signup"
//import auth from "firebase/auth";
let log;

function App() {
  return (
    <>

      <Router>

      </Router>
      <Router>

        <Switch>
          <Route path="/" exact component = {Home} />
          <Route path="/about" exact component = {About} />
          <Route path="/login" exact component = {Login} />
          <Route path = "/Signup.js" exact component = {Signup} />
        </Switch>
      </Router>

    </>
  );

}

export default App;

A: You need to make a route that takes parameters.
<Route path="/user/:name" component={UserComponent} />
And same goes for the backend, make a public route.

A: Define a Route in your Switch that uses a dynamic path.
<Route path="/user/:userId" component={UserPage} />

The "UserPage" component will receive route props (history, location, and match). The path parameters are on the match prop at props.match.params.userId.
const UserPage = ({ match }) => {
  const { params: { userId } } = match;
  // do with `userId` what you need to load that user's data

  ...
};


text:
Q: Why is hyped Intel MKL Numpy build slower than ATLAS build on my PC? I "dual boot" Ubuntu 11.04, Ubuntu 12.04 and Windows XP SP3 all updated to date.
PC is rather old Intel Celeron D CPU 3.06GHz with 2GB RAM
In Ubuntu 11.04 I have Numpy compiled with ATLAS (ATLAS compiled from source)
In Ubuntu 12.04 I have Numpy build with latest available MKL, icc, ifort
In Windows XP I have Numpy with MKL (from kindly provided Python packages by Christoph Gohlke)
More details here: http://pastebin.com/raw.php?i=wxuFbyVg
I tried simple:
%timeit np.dot(np.ones((1000,1000)), np.ones((1000,1000)))
and got this results:
Ubuntu ATLAS: 1 loops, best of 3: 457 ms per loop
Windows MKL:  1 loops, best of 3: 680 ms per loop
Ubuntu MKL:   1 loops, best of 3: 1.04 s per loop

I thought above is bad example and I searched for one of many comparisons available, i.e. first Google hit: http://dpinte.wordpress.com/2010/01/15/numpy-performance-improvement-with-the-mkl/
I tested same functions:
%timeit test_eigenvalue()
Ubuntu Atlas: 1 loops, best of 3: 6.38 s per loop
Windows MKL:  1 loops, best of 3: 2.22 s per loop
Ubuntu MKL:   1 loops, best of 3: 3.58 s per loop

%timeit test_svd()
Ubuntu Atlas: 1 loops, best of 3: 2.13 s per loop
Windows MKL:  1 loops, best of 3: 2.06 s per loop
Ubuntu MKL:   1 loops, best of 3: 3.09 s per loop

%timeit test_inv()
Ubuntu Atlas: 1 loops, best of 3: 964 ms per loop
Windows MKL:  1 loops, best of 3: 1.02 s per loop
Ubuntu MKL:   1 loops, best of 3: 1.59 s per loop

%timeit test_det()
Ubuntu Atlas: 1 loops, best of 3: 308 ms per loop
Windows MKL:  1 loops, best of 3: 322 ms per loop
Ubuntu MKL:   1 loops, best of 3: 491 ms per loop

%timeit test_dot()
Ubuntu Atlas: 1 loops, best of 3: 1.5 s per loop
Windows MKL:  1 loops, best of 3: 1.77 s per loop
Ubuntu MKL:   1 loops, best of 3: 2.77 s per loop

So ATLAS compiled Numpy has best results for some reason.
Does anyone know what could be the problem?

A: Intel® MKL is designed and optimized primarily for server and high performance desktop and mobile processors. Celeron D was a relatively low performance processor so MKL was never optimized for it. For example, if you check the SVD performance on a recent Intel Core i7 desktop, MKL-enabled NumPy can run as much as 80% faster than ATLAS-enabled NumPy. See here: http://software.intel.com/en-us/articles/numpy-scipy-with-mkl/
By the way, to get faster responses to MKL related questions please join the Intel MKL forum: http://software.intel.com/en-us/forums/intel-math-kernel-library/

A: I have also used numpy with mkl on my desktop intel core i3 4th generation 2.3 GHz, 4GB ram.
I have tested dot products of two 4096x4096 matrix. i have tested them on anaconda distributions of python 3.5 64 bit (no mkl support till date), python 2.7 64 bit without mkl and python 2.7 64 bit with mkl and results were almost similar. They all took ~73 seconds (+- 0.5 sec) to compute this (for the case of integer datatype), for float64 data types they all took 260 ms (+- 5 ms) and for complex data types ~1 second (+- 100 ms) second by all of them.
I have also found that the numpy dot is the best even for complex matrix multiplications. They have already implemented the Gauss improvements.
I have tested for cython using blas, blas in python, einsum in python but dot is the best.
i need to multiply matrices fasster


text:
Q: Decoherence Tutorial on level of the Theoretical Minimum books I'm trying to understand decoherence and other issues in QM related to the Everettian interpretation. I have a BS in physics, but that was 37 years ago. I've read Susskind and Friedman's book, The Theoretical Minimum: Quantum Mechanics, and really liked it, but it didn't discuss these topics. I'm reading David Wallace's book, The Emergent Multiverse, but I'm struggling with it. Can anyone suggest a good treatment of decoherence on a similar level to the Theoretical Minimum books? Or anything else that would be a bridge between TTM:QM and Wallace's book?

A: What I understand about decoherence I learned mainly from this paper:
Joos and Zeh, The emergence of classical properties through interaction with the environment, Z Phys B 59 (1985) 223.
It's long but somewhat readable.
Another treatment is in this book:
Pade, Quantum Mechanics for Pedestrians, vol. 2
See ch. 24. I found it a little abstract and hard to absorb, but it is intended as a pedagogical treatment.
Unfortunately neither of these is open access, and neither is easy going. You can get them (probably in violation of your country's copyright laws) through sci-hub and Library Genesis. I would love to see a super-super-super-simple presentation that was open access.


text:
Q: Graph connected does not imply $f$ is continuous Show an example of a function $\newcommand{\R}{\mathbb{R}} f: \R \times \R\to \R$ such that $f$ is not continuous, but its graph
$$
\Gamma_f := \left\{\bigl((x, y), f(x, y)\bigr) \mid \text{$(x, y)$ is in the domain of $f$}\right\}
$$
is connected (in $\R \times \R \times \R$).

A: Hint: Choose a function such that the overall limit at $(0,0)$ does not exist (but the limit along some path does).
Example: take
$$
f(x,y) =
\begin{cases}
\frac{x^2}{x^2 + y^2} & (x,y) \neq (0,0)\\
0 & x = y = 0
\end{cases}
$$
Verify that $\Gamma_f$ is path-connected, but $f$ is not continuous at $(0,0)$.

A: Let:
$$f(x,y)=\sin\left(\frac{1}{x^2+y^2}\right)$$
for $(x,y) \neq (0,0)$
and $f(0,0)=0$
Then graph of this function is:
$$\{(x,y,\sin\left(\frac{1}{x^2+y^2}\right))|(x,y) \neq (0,0)\} \cup \{(0,0,0)\}$$
Closure of this graph is:
$$\{(x,y,\sin\left(\frac{1}{x^2+y^2}\right))|(x,y) \neq (0,0)\} \cup \{(0,0,x): x \in [-1,1]\}$$
There is a theorem that if closure of set is connected then set is connected. You can check by definition that closure is connected.

A: Define
$$
f(x, y) = \begin{cases}
\sqrt{x^{2} + y^{2}} & \text{if $x \neq 0$ and $y/x$ is rational,} \\
0 & \text{otherwise.}
\end{cases}
$$
Theorem: The function $f$ has (path-)connected graph, but is continuous at precisely one point.
Proof: The graph of $f$ is the union of:

*

*Lines (through the origin) of irrational slope in the $(x, y)$-plane;

*The $y$-axis;

*Absolute value graphs over lines (through the origin) of rational slope in the $(x, y)$-plane.
Since each of these sets is (path-)connected and contains the origin, their union is (path-)connected.
Since lines (through the origin) of irrational slope are dense in the plane, $f$ is continuous at $(x, y)$ if and only if $\sqrt{x^{2} + y^{2}} = 0$, if and only if $(x, y) = (0, 0)$.


text:
Q: Add dynamic maps to a list in a for loop I am having few maps (which are dynamic). I want to add those to a list (List<Map<String,dynamic>>) -> like this. I tried to add by using .add but throwed an error
Error:
type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'List<Map<dynamic, dynamic>>' of 'function result'

Dart Code:
    final List<Map<String, dynamic>> teamName = [{'teamName': 'Spartans'}, {'teamName': 300}];
    final List<Map<String, dynamic>> captainName = [{'captainName': 'ABC'}, {'captainName': 'XYZ'}];
    final List<Map<String, dynamic>> correctValue = [];
        for (var i = 0; i < teamName.length; i++) {
          for (var j = i; j < captainName.length; j++) {
            final Map<String, dynamic> currentValue = {
              'teamname': teamName[i]['teamName'],
              'captainname': captainName[j]['captainName']
            };
            correctValue.add(currentValue);
            break;
          }
        }
        print('end result is $correctValue');

I want my result to be like
[{teamName: Spartans, captainName: ABC}, {teamName: 300, captainName: XYZ}]

A: void main() {
List<Map<dynamic, dynamic>> correctValue = [];
var teamName = [
    {"teamName": "Spartans"},
    {"teamName": "300"}
];
var captainName = [
    {"captainName": "ABC"},
    {"captainName": "XYZ"}
];
for (var i = 0; i < teamName.length; i++) {
    for (var j = i; j < captainName.length; j++) {
        var currentValue = {
            'teamname': teamName[i]['teamName'],
            'captainname': captainName[j]['captainName']
        };
        correctValue.add(currentValue);
        break;
    }
}
print('end result is $correctValue');
}

Your code works for me after a few modifications.


text:
Q: How to add a membership cards to my website that can member downloaded I have a website with Wordpress and I want to add members cards that they can fill their information and can download it from the website, but not sure how to do it I look for a plugin but I did not find.
also, I have 2 data on my website 'Event and Users' could I add them in one excel sheet or no?
I tried to look for a plugin

A: you need to separate your questions and add more information about your problem.
I'll try to help you:
** members cards **

*

*You can use a form plugin to let the user fill the data (for example: name, surname, birth date, ecc..) that you need to print in the card. I suggest you to use this: https://formidableforms.com

*the difficult way: you can intercept the form submission with formidable specific function "https://formidableforms.com/knowledgebase/frm_after_create_entry/" and with the collected data you can create image in the fly with php and imagemagik (or GD or other) https://www.php.net/manual/en/book.imagick.php. This part need that you have a little bit of experience in development. Check next point for a much simpler alternatives

*the simple way: With formidable you can create a post (or better custom post) with the collected data without working on code:
https://formidableforms.com/knowledgebase/create-posts/ then you can redirect user to that page.

*Invite the user to print that page and setup a specific css for print: https://benfrain.com/create-print-styles-using-css3-media-queries/


text:
Q: How to setup custom api for Magento with SOAP V2? I am on Magento 1.4.1.1 and I am trying to setup a custom function in the API using SOAP v2. I have it working for SOAP v1 but I need v2 so that C# can use it. For v2 the function shows up in the WSDL but alwasy returns this error: Procedure 'testFoo' not present.
Here are my files:
/app/etc/modules/ABT_Test.xml
<?xml version="1.0"?>
<config>
    <modules>
        <ABT_Test>
            <active>true</active>
            <codePool>local</codePool>
        </ABT_Test>
    </modules>
</config>

/app/code/local/ABT/Test/etc/config.xml
<?xml version="1.0"?>
<config>
    <modules>
        <ABT_Test>
            <active>true</active>
            <codePool>local</codePool>
            <version>1.0</version>
        </ABT_Test>
    </modules>
    <global>
        <models>
            <test>
                <class>ABT_Test_Model</class>
            </test>
        </models>
    </global>
</config>

/app/code/local/ABT/Test/etc/api.xml
<?xml version="1.0"?>
<config>
    <api>
        <resources>
            <test>
                <model>test/api</model>
                <title>ABT Test Api</title>
                <methods>
                    <foo translate="title" module="test">
                        <title>Foo Test</title>
                        <method>foo</method>
                        <acl>test/foo</acl>
                    </foo>
                </methods>
            </test>
        </resources>
        <v2>
            <resources_function_prefix>
                <test>test</test>
            </resources_function_prefix>
        </v2>
    </api>
</config>

/app/code/local/ABT/Test/etc/wsdl.xml
<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns:typens="urn:{{var wsdl.name}}" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
    xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns="http://schemas.xmlsoap.org/wsdl/"
    name="{{var wsdl.name}}" targetNamespace="urn:{{var wsdl.name}}">
    <types>
        <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:Magento">
            <import namespace="http://schemas.xmlsoap.org/soap/encoding/" schemaLocation="http://schemas.xmlsoap.org/soap/encoding/" />
        </schema>
    </types>
    <message name="testFooRequest">
        <part name="sessionId" type="xsd:string" />
    </message>
    <message name="testFooResponse">
        <part name="result" type="typens:boolean" />
    </message>
    <portType name="{{var wsdl.handler}}PortType">
        <operation name="testFoo">
            <documentation>Test Foo</documentation>
            <input message="typens:testFooRequest" />
            <output message="typens:testFooResponse" />
        </operation>
    </portType>
    <binding name="{{var wsdl.handler}}Binding" type="typens:{{var wsdl.handler}}PortType">
        <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http" />
        <operation name="testFoo">
            <soap:operation soapAction="urn:{{var wsdl.handler}}Action" />
            <input>
                <soap:body namespace="urn:{{var wsdl.name}}" use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
            </input>
            <output>
                <soap:body namespace="urn:{{var wsdl.name}}" use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
            </output>
        </operation>
    </binding>
</definitions>

/app/code/local/ABT/Test/Model/API.php
<?php
class ABT_Test_Model_Api extends Mage_Api_Model_Resource_Abstract
{

    public function foo()
    {
        return true;
    }
}
?>

/app/code/local/ABT/Test/Model/API/V2.php
<?php
class ABT_Test_Model_Api_V2 extends ABT_Test_Model_Api
{
}
?>

And here is the code I use to test the API:
<?php
    $mageUser   = '########';
    $mageApiKey = '########';

    //SOAP V1
    echo "SOAP V1
";
    $mageUrl    = 'http://www.########.com/api/soap/?wsdl';
    $soap = new SoapClient($mageUrl, array('cache_wsdl' => 0));

    try {
        $sessionID = $soap->login($mageUser, $mageApiKey);
        var_dump($soap->call($sessionID, 'test.foo', array()));
    } catch (Exception $e) {
        echo 'Exception: ' . $e->getMessage() . '
';
    }

    //SOAP V2
    echo "SOAP V2
";
    $mageUrl2    = 'http://www.########.com/api/v2_soap/?wsdl';
    $soap2 = new SoapClient($mageUrl2, array('cache_wsdl' => 0));

    try {
        $sessionID2 = $soap2->login($mageUser, $mageApiKey);
        var_dump($soap2->testFoo($sessionID2));
    } catch (Exception $e) {
        echo 'Exception: ' . $e->getMessage() . '
';
    }
?>

I obscured the username, password and url. The function shows up in the v2 WSDL and the php code recognizes that it is in the WSDL but I still get the error: Procedure 'testFoo' not present.
So what am I missing?
EDIT:
I did what Zyava suggested and it got my example working. I then copied the folder and did an exact (case sensitive) find and replace to use a meaningful Module name and function name. I was careful to pick names that I didn't think would be reserve words. On the new module the call on the v1 WSDL works fine but the v2 gives the same "Procedure 'xxx' not present" message. I then went and renamed the method on the test from 'Foo' to 'Fooz' and I got this message: "Resource path is not callable." I find it interesting that I get a different message. This leads me to believe there is some cache/configuration/something that is causing the problem. Any ideas?

A: At first I should warn you that Magento doesn't support SOAP v2 format for now, api/v2_soap/?wsdl is just second version of soap api.
1.
<models>
    <test>
        <class>ABT_Test_Model</class>
    </test>
</models>

Because you are writing module which isn't core, you should write <abt_test>
2.<model>test/api</model>. Should be <model>abt_test/api</model> in your case.
3.<acl>test/foo</acl>.
Does this acl section exist in your adminhtml.xml?

A: bygrace,
your code is so perfect!
add

....
  <resources_alias>
      <test>test</test>
  </resources_alias>
.....

same level with
<resources> and <v2>

on Api.xml
and it'll be working good.

A: I has having the same issue and i tried clearing the tmp file as i had hosted it using xampp it didnt work i was getting Procedure ххх not present exception, I had to disable the cache management in the admin page of the server.
How to disable Cache in Admin page
In the admin page under the system there is a section called cache management disable everything during the development phase or else any change you do wont be reflected in the wsdl.


text:
Q: How to combine multiple event data into one object or variable suitable for use with fullcalendar? I am getting data from a DB for populating events in fullcalendar.js
I get this information prior to initiating $('#calendar').fullCalendar({})
If I knew how many events I was going to have I could create the calendar with the code below
events: [
            eventz[0],
            eventz[1]
        ]

Where eventz contain information like
eventz[eventcounter]={
                    className: title[counter],
                    title: title[counter],
                    start: new Date(y, m, weekday, result[hour1], result[minute1]),
                    end: new Date(y, m, weekday, result[hour2], result[minute2]),
                    allDay: false
                                };

EDIT: More information-events would normally contain information written like below
events:[
        {//event1
        title: 'TENTATIVE',
        start: new Date(y, m, monday, 0, 30),
        end: new Date(y, m, monday, 1, 0),
        allDay: false
        },
        {//event2
        title: 'TENTATIVE',
        start: new Date(y, m, monday, 0, 30),
        end: new Date(y, m, monday, 1, 0),
        allDay: false
        }
]

Unfortunately, I don't know how many events I'm going to get.
I thought that prior to initiating the calendar, I could combine the events into one object or variable (something like the code below-where allevents={eventz[0]},{eventz[1]}).
events: [
            allevents
        ]

QUESTIONs
Is it possible to combine events into one object or variable like above? If yes, how? If no, I'd be interested in alternative methods for entering dynamic event data into fullcalendar. Thanks :)
WHAT I have tried
//combine all events into one
        for (var i=0;i<=counter;i++)
        {
            allevents+=eventz[i];
            if (i!=counter)
            {
                allevents+=',';
            }
        }

I've tried quite a few things, but this feels like I'm doing ridiculous stuff and this seems like an easy question (for people other than me).

A: I think this is what you are looking for.
Instead of using 'events' attribute use 'eventSources' attribute.
Before:
events : eventArrayFirst

After:
eventSources: [
    eventArrayFirst,
    eventArraySecond
]

A: I used array concatenation to solve my problem.
//Combines all events into one
        if (eventcounter>0) //Check that there is an event!
        {
            var allevents=[eventz[0]];
            for (var varname=1; varname<=eventcounter; varname++)
            {
                allevents=allevents.concat([eventz[varname]]);
            }
        }

A: If your final array after combining all the events in single array looks like
var eventz = [
        {//event1
        title: 'TENTATIVE',
        start: new Date(y, m, monday, 0, 30),
        end: new Date(y, m, monday, 1, 0),
        allDay: false
        },
        {//event2
        title: 'TENTATIVE',
        start: new Date(y, m, monday, 0, 30),
        end: new Date(y, m, monday, 1, 0),
        allDay: false
        }
];
Then this example may help you


text:
Q: Get Data from firebase for swift I have below code to get data from my firebase database
db.collection("users").getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            print("starting name display")
            for document in (querySnapshot?.documents)! {
                let documentUserId = document.get("uid") as?String
                let temp = document.data()["displayName"]
                print(temp)
            }
          }
        }

The print statement displays as optional("test name")
Why am i keep getting optional in my string. Same displays on the screen as well.

A: You need to un-wrap because it's an Optional. Means it could have a value or it could not have a value. So this is one method to handle it:
let temp = document.data()["displayName"] ?? ""
print(temp)

You could also use if let or guard let statements if you need to handle the cases where the value is actually empty.
Note: Take a look at the basics of swift. There is a separate section for Optionals.


text:
Q: what is exactly a predictable process? Let $(\Omega ,\mathcal F,\mathbb P)$ a probability space. A stochastic process is predictable with refer to the filtration $(\mathcal F_n)_n$ if $X_{n+1}\in \mathcal F_n$.
Could someone tel me what it mean exactly ? (except the fact that $X_{n+1}$ is $\mathcal F_n-$measurable). What is the intuition behind ? Would it be a sort of "simple function" for stochastic process ?