text:
Q: NavigationDrawer code Unable to Instantiate Fragment I've taken the exact code from a navigation drawer tutorial but when I placed the code into my own project, it immediately crashes when it runs. But when I run it from the sample project I downloaded, it works perfectly fine: http://manishkpr.webheavens.com/android-navigation-drawer-example-using-fragments/
Could it be the build path and how could I fix that?
Any suggestions would be greatly appreciated!
LogCat
09-07 17:46:34.102: D/ActivityThread(13870): setTargetHeapUtilization:0.25
09-07 17:46:34.102: D/ActivityThread(13870): setTargetHeapIdealFree:8388608
09-07 17:46:34.102: D/ActivityThread(13870): setTargetHeapConcurrentStart:2097152
09-07 17:46:34.212: D/AbsListView(13870): Get MotionRecognitionManager
09-07 17:46:34.222: W/dalvikvm(13870): threadid=1: thread exiting with uncaught         exception (group=0x41221438)
09-07 17:46:34.222: E/AndroidRuntime(13870): FATAL EXCEPTION: main
09-07 17:46:34.222: E/AndroidRuntime(13870): java.lang.RuntimeException: Unable to     start activity ComponentInfo{com.example.testnavdrawer/com.example.testnavdrawer.MainActivity}: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.example.navigationdrawer.FragmentOne: make sure class name exists, is public, and has an empty constructor that is public
09-07 17:46:34.222: E/AndroidRuntime(13870):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
09-07 17:46:34.222: E/AndroidRuntime(13870):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
09-07 17:46:34.222: E/AndroidRuntime(13870):    at android.app.ActivityThread.access$700(ActivityThread.java:143)
09-07 17:46:34.222: E/AndroidRuntime(13870):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1241)
09-07 17:46:34.222: E/AndroidRuntime(13870):    at android.os.Handler.dispatchMessage(Handler.java:99)
09-07 17:46:34.222: E/AndroidRuntime(13870):    at     android.os.Looper.loop(Looper.java:137)
09-07 17:46:34.222: E/AndroidRuntime(13870):    at android.app.ActivityThread.main(ActivityThread.java:4961)
09-07 17:46:34.222: E/AndroidRuntime(13870):    at java.lang.reflect.Method.invokeNative(Native Method)
09-07 17:46:34.222: E/AndroidRuntime(13870):    at java.lang.reflect.Method.invoke(Method.java:511)
09-07 17:46:34.222: E/AndroidRuntime(13870):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
09-07 17:46:34.222: E/AndroidRuntime(13870):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
09-07 17:46:34.222: E/AndroidRuntime(13870):    at dalvik.system.NativeStart.main(Native Method)
09-07 17:46:34.222: E/AndroidRuntime(13870): Caused by: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.example.navigationdrawer.FragmentOne: make sure class name exists, is public, and has an empty constructor that is public
09-07 17:46:34.222: E/AndroidRuntime(13870):    at android.support.v4.app.Fragment.instantiate(Fragment.java:409)
09-07 17:46:34.222: E/AndroidRuntime(13870):    at android.support.v4.app.Fragment.instantiate(Fragment.java:377)
09-07 17:46:34.222: E/AndroidRuntime(13870):    at com.example.testnavdrawer.MainActivity.onCreate(MainActivity.java:46)
09-07 17:46:34.222: E/AndroidRuntime(13870):    at android.app.Activity.performCreate(Activity.java:5179)
09-07 17:46:34.222: E/AndroidRuntime(13870):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
09-07 17:46:34.222: E/AndroidRuntime(13870):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074)
09-07 17:46:34.222: E/AndroidRuntime(13870):    ... 11 more
09-07 17:46:34.222: E/AndroidRuntime(13870): Caused by: java.lang.ClassNotFoundException: com.example.navigationdrawer.FragmentOne
09-07 17:46:34.222: E/AndroidRuntime(13870):    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
09-07 17:46:34.222: E/AndroidRuntime(13870):    at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
09-07 17:46:34.222: E/AndroidRuntime(13870):    at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
09-07 17:46:34.222: E/AndroidRuntime(13870):    at android.support.v4.app.Fragment.instantiate(Fragment.java:399)
09-07 17:46:34.222: E/AndroidRuntime(13870):    ... 16 more

MainActivity.java
package com.example.testnavdrawer;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends FragmentActivity {
    final String[] data ={"one","two","three"};
    final String[] fragments ={
            "com.example.navigationdrawer.FragmentOne",
            "com.example.navigationdrawer.FragmentTwo",
            "com.example.navigationdrawer.FragmentThree"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);

         ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActionBar().getThemedContext(), android.R.layout.simple_list_item_1, data);

         final DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_layout);
         final ListView navList = (ListView) findViewById(R.id.drawer);
         navList.setAdapter(adapter);
         navList.setOnItemClickListener(new OnItemClickListener(){
                 @Override
                 public void onItemClick(AdapterView<?> parent, View view, final int pos,long id){
                         drawer.setDrawerListener( new DrawerLayout.SimpleDrawerListener(){
                                 @Override
                                 public void onDrawerClosed(View drawerView){
                                         super.onDrawerClosed(drawerView);
                                         FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
                                         tx.replace(R.id.main, Fragment.instantiate(MainActivity.this, fragments[pos]));
                                         tx.commit();
                                 }
                         });
                         drawer.closeDrawer(navList);
                 }
         });
         FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
         tx.replace(R.id.main,Fragment.instantiate(MainActivity.this, fragments[0]));
         tx.commit();
    }

}

activity_main.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <FrameLayout
        android:id="@+id/main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </FrameLayout>

    <ListView
        android:id="@+id/drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#FFF"
        android:choiceMode="singleChoice"/>

</android.support.v4.widget.DrawerLayout>

FragmentOne.java
package com.example.testnavdrawer;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FragmentOne extends Fragment {

    public static final Fragment newInstance(Context context) {
        FragmentOne f = new FragmentOne();

        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_one, null);
        return root;
    }

}

FragmentTwo.java
package com.example.testnavdrawer;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FragmentTwo extends Fragment {

    public static Fragment newInstance(Context context) {
        FragmentTwo f = new FragmentTwo();

        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_two, null);
        return root;
    }

}

FragmentThree.java
package com.example.testnavdrawer;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FragmentThree extends Fragment {

    public static Fragment newInstance(Context context) {
        FragmentThree f = new FragmentThree();

        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_three, null);
        return root;
    }

}

A: Typo in your code. Main Activity is this:
final String[] fragments ={
        "com.example.navigationdrawer.FragmentOne",
        "com.example.navigationdrawer.FragmentTwo",
        "com.example.navigationdrawer.FragmentThree"};

But should be this:
final String[] fragments ={
        "com.example.testnavdrawer.FragmentOne",
        "com.example.testnavdrawer.FragmentTwo",
        "com.example.testnavdrawer.FragmentThree"};

And you would add some type safety if you did it like this:
final String[] fragments ={
        FragmentOne.class.getName(),
        FragmentTwo.class.getName(),
        FragmentThree.class.getName()};


text:
Q: how to access bytecode of some file/function in android I want to access bytecode of some file/function from dex file in Android. Please suggest me the suitable way.
 Thanks!

A: first you need a tool called dex2jar,. it will translate dex to jar file. then you can use jd-gui, the source code is quite readable as dex2jar makes some optimizations.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Importing Excel data to python with openpyxl With openpyxl
With
if sheet.cell(j, i).value
i am testing if a certain cell in an excel sheet has a value.
The Problem: If there is a "0" in that cell the request give output "no"
Question: How do I change it, so that my request gives "Yes" as output if there is a "0" in that cell

A: If you use only if sheet.cell(j, i).value as the logical check, it will give False for both 0 and blank. So, you need to use if sheet.cell(j, i).value is None, in which case, it will return TRUE only when the cell is blank. A working example.
import openpyxl
wb=openpyxl.load_workbook('Sample.xlsx')
sheet=wb['Sheet2']
j=10
for i in range(1, 9):
    print("Data in cell is : ", sheet.cell(j, i).value)
    if sheet.cell(j, i).value is None:
        print("This is blank")
    else:
        print("This is not blank")

Output
Data in cell is :  1
This is not blank
Data in cell is :  2
This is not blank
Data in cell is :  3
This is not blank
Data in cell is :  None
This is blank
Data in cell is :  4
This is not blank
Data in cell is :  5
This is not blank
Data in cell is :  0
This is not blank
Data in cell is :  8
This is not blank


text:
Q: HSQLDB AS keyword is being ignored I'm not having any luck with Google or SO searches, so here goes.
I have the following SQL statement that I'm trying to run against HSQLDB 2.3.0.
select
tr.id as training_request_id,
s.id as student_id,
s.first_name as student_first_name,
s.last_name as student_last_name,
s.title as student_title,
c.id as customer_id,
c.name as customer_name,
trs.status
from training_request tr
left outer join student s on tr.student_id = s.id
left outer join customer c on tr.customer_id = c.id
left outer join training_request_status trs on tr.id = trs.training_request_id
where tr.slot_id is not null
order by tr.id, trs.date_entered DESC

When it comes back, the colums are:
ID, ID, FIRST_NAME, LAST_NAME, TITLE, ID, NAME, STATUS
Why isn't the AS keyword having any effect?
UPDATE:  Here's a screenshot from SQuirreL.  Quoting the student_id column has no effect.

A: Figured it out.
There's a connection property called "get_column_name".  Set it to false.  The default is true.
http://hsqldb.org/doc/2.0/guide/dbproperties-chapt.html
jdbc:hsqldb:hsql://localhost/enrolments;get_column_name=false


text:
Q: How to install/upgrade to newest WiFi driver from wireless.wiki.kernel.org? I have problems with the iwlwifi network driver, and I want to try upgrading it to the newest available version. On AskUbuntu, I found a suggestion to download a driver from https://wireless.wiki.kernel.org. I found a page there for the iwlwifi driver, at:
https://wireless.wiki.kernel.org/en/users/drivers/iwlwifi?s[]=iwlwifi
My adapter is an Intel Wireless 3160. The "Firmware" section on the kernel.org page has multiple entries for the 3160 card for different kernels, e.g.:

*

*3.10+ → iwlwifi-3160-ucode-22.1.7.0.tgz

*...

*4.1+ → iwlwifi-3160-ucode-25.30.13.0.tgz

*4.3+ → iwlwifi-3160-ucode-16.242414.0.tgz

I'm on Ubuntu 16.04 LTS, checking the kernel version:
$ uname -a
Linux akavel-lenovo 4.4.0-137-generic #163-Ubuntu SMP Mon Sep 24 13:14:43 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

My kernel is 4.4 — so, which one of the above drivers should I choose? My first thought was to use the 4.3+ — but then I noticed the driver version is apparently 16.x, while 4.1+ has 25.x — so can I use the 4.1+? Is the driver really newer, or the ucode numbers mean something else? Or do I have to use the 4.3+? Or something else? I'm confused :( Or should I maybe just compile a driver on my own? If yes, then how? To add the confusion, the page also has a section like below (emphasis mine):

7260, 3160, 7265, 7265D, 3165 and 3168 support
Those devices will not be supported by the newest firmware versions: the last firmware that was released for 3160, 7260 and 7265 is -17.ucode. Bug fixes will be ported to -17.ucode.

Looking into the linux-firmware.git repository mentioned somewhere else on the page indeed seems to show an iwlwifi-3160-17.ucode as the one with the highest number. But when I downloaded the iwlwifi-3160-ucode-16.242414.0.tgz, it only has a iwlwifi-3160-16.ucode inside...
To summarize: the "Firmware" section on the wireless.wiki.kernel.org website is confusing to me, I don't really know which version should I download?
edit 1: Hm; after downloading the iwlwifi-3160-ucode-25.30.13.0.tgz and looking into it, it has an iwlwifi-3160-13.ucode file inside, so at least it seems to clear part of the confusion, in that the internal ordering follows the kernel version ordering, and I should probably just ignore the weird versioning in the tgz names. Still not sure what is it about the ucode-17 mentioned as the "newest version" but not being present in the newest tarball.

A: First of all, what you are looking at here are the firmware files, not the driver. All newer Intel devices use the same driver, iwlwifi. The features particular to the exact chip, such as your 3160, are enabled by the firmware files.
You have already linked the firmware discussions at kernel.org. Of further interest is the firmware discussion at Intel, the manufacturer of the hardware and the author of the driver and firmware: https://www.intel.com/content/www/us/en/support/articles/000005511/network-and-i-o/wireless-networking.html
As you can see, kernel.org suggests that the correct firmware for your device is -16. Intel says it is -14. In contrast, modinfo says it is -13. In fact, the driver iwlwifi and the package linux-firmware load -17!
What have we learned here? I think we have learned that there is no consensus and that there is no need and no place to download a newer firmware file.
In my experience, having used many Intel devices myself over 15 years, the firmware and driver iwlwifi are seldom the issue. In the spirit of "I'm trying to solve it on my own first", I suggest that the solution is likely related to either:

*

*Power saving;

*The device wants to roam from among several SSIDs with the same name; for example, eduroam;

*The router is set to auto select the encryption; that is WPA or WPA2, and the wireless device stumbles at the changeover;

*The router is set to autoselect the channel and the device also stumbles at the changeover; or

*The router is set to TKIP.

Should you wish to update the actual iwlwifi driver, first address these issues. I suspect that no update will then be required.


text:
Q: Match multi-line text between two tags I am trying match some multi-line text that changes, between two tags. The only that doesn't change is the img and url tags. The number of lines change and is not the same every time.
Is it possible? Can you help me with the pattern?
Bellow is an example of what I have. With bold is the text that I want to match.
[img]http://image.jpg[/img]text text text text text text
text text text text text text text text text text
text text text text text text text text text text text text
text text text text text text text text
text text text text text text text text text text text text text text text text
text text text text text text text text text text text text text text
text text text text [url=http://url[/url]
text text text text
Thank you for your help!

A: you can try this regex
^[^<>[][a-zA-Z\s]+

https://regex101.com/r/iZTMwY/1


text:
Q: Create Gradient in View With locations from zeplin I am working on a project where i need to apply gradients to the view. I am having sketch file and have colors which i am going to use for gradient with the locations but i am unable to get the exact view.
Can anyone please help how to get that?
I have created a function to apply gradient:-

func applyGradient(colours: [UIColor]) -> Void {
        let gradient: CAGradientLayer = CAGradientLayer()
        gradient.frame = self.bounds
        gradient.colors = colours.map { $0.cgColor }
        self.layer.insertSublayer(gradient, at: 0)
    }

func applyGradientToView(){
        let firstColor = UIColor(red: 26/255, green: 169/255, blue: 186/255, alpha: 1.0)
        let secondColor = UIColor(red: 26/255, green: 97/255, blue: 157/255, alpha: 1.0)
        let thirdColor = UIColor(red: 27/255, green: 65/255, blue: 144/255, alpha: 1.0)
        self.applyGradient(colours: [firstColor, secondColor, thirdColor])
    }

Here array UIcolor is a combination of colors to be used, I used all three but still, I didn't get the same as in the sketch
What I created :-

Gradient colors in sketch file:-

The view in sketch file is like this:-

A: Couple issues...
1) Your "Gradient colors in sketch file:" image does not match your Sketch file output image. However you applied the gradient in sketch, it is not a full top-to-bottom (or, in this case, bottom-to-top) gradient fill.
2) When working with colors in different applications and/or devices, you have to be aware of "color spaces". Take a quick search on google for sketch colors don't match and you'll find lots of material explaining it, along with tips on using sketch for iOS targets.
So, an easy way to get close to your desired output is to use OS X Digital Color Meter - which should be installed by default on your Mac (if it's not, it's easy to find). That tool allows you to hover over a point on your image and get the RGB values based on different color spaces. SRGB should be a match.
Also, there is a better way to code your custom view for reuse. Take a look at this approach:
class MyGradientView: UIView {

    override class var layerClass: AnyClass {
        return CAGradientLayer.self
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    func commonInit() -> Void {

        let gradientLayer = layer as! CAGradientLayer

        let firstColor = UIColor(red: 25/255, green: 138/255, blue: 173/255, alpha: 1.0)
        let secondColor = UIColor(red: 27/255, green: 163/255, blue: 184/255, alpha: 1.0)

        let colours = [firstColor, secondColor]

        gradientLayer.colors = colours.map { $0.cgColor }

        gradientLayer.shadowColor = UIColor.black.cgColor
        gradientLayer.shadowOffset = CGSize(width: 0.0, height: 1.0)
        gradientLayer.shadowRadius = 2.0
        gradientLayer.shadowOpacity = 0.5

        gradientLayer.masksToBounds = false

    }

}

Gradient layers in iOS by default go from Top-To-Bottom, so you only need your top and bottom colors defined. This approach also includes your shadow (as shown in your sketch output image). And it will maintain the gradient and shadow when using the custom view with auto-layout:
    let v = MyGradientView()
    view.addSubview(v)

    v.translatesAutoresizingMaskIntoConstraints = false

    v.topAnchor.constraint(equalTo: view.topAnchor, constant: 100.0).isActive = true
    v.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -100.0).isActive = true
    v.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 40.0).isActive = true
    v.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -40.0).isActive = true

Result:

A: According to the documentation of CAGradientLayer (https://developer.apple.com/documentation/quartzcore/cagradientlayer) to specify a location of colors you can use locations property(in your case [0, 0.68, 1]):
var locations: [NSNumber]? { get set }

but as @Alladinian wrote in the comment in your example, it looks like your gradient was drawn from bottom to top and start before view and end far after view so you see only a part


text:
Q: "\end\end" causes "TeX capacity exceeded" I know this is invalid LaTeX code, but the code \end\end results in the following error:
! TeX capacity exceeded, sorry [input stack size=5000].
\end #1->\csname end#1
                      \endcsname \@checkend {#1}\expandafter \endgroup \if@e...
l.1 \end\end

Why does this result in "TeX capacity exceeded" when this is simply invalid syntax?

A: It's not simply invalid syntax it is an infinite loop.
\end\end

is
\end{\end}

so it is the end environment call and it expands its argument
\end is more or less \csname end#1\endcsname  so that \end{table} executes \endtable.
so
\csname end\end\endcsname

so we have to expand the \end and get
\csname end\csname end\endcsname\endcsname

which is
\csname end\end\endcsname

and we loop and so on 500 times until you fill the input stack, each time \endcsname is taken as the argument of \end and re-inserted.


text:
Q: jQuery Validation - Cannot call method 'call' of undefined Not sure why this isn't working.
I'm sure you all know what I'm trying to achieve here.
When the script is run I get an Uncaught TypeError: undefined is not a function on jquery.validate.js line:366 which refers to this hunk of code:
function delegate( event ) {
            var validator = $.data( this[ 0 ].form, "validator" ),
                eventType = "on" + event.type.replace( /^validate/, "" ),
                settings = validator.settings;
            if ( settings[ eventType ] && !this.is( settings.ignore ) ) {
                settings[ eventType ].call( validator, this[ 0 ], event );
            }
        }                           ^^^^ HERE

I'm using codeigniter2 framework so apologies if my form page doesn't make sense to some.
new_page.php (The relevant bit)
<?php echo form_open(site_url('admin/manage_pages/new_page'),
                            array('id' => 'new-page-form')) . PHP_EOL; ?>

        <?php echo form_label('Page Title', 'page-title',
                                'class="control-label"') . PHP_EOL; ?>
        <?php echo form_input(array(
                                'name' => 'page-title',
                                'id' => 'input-page-title',
                                'max-length' => '255',
                                'placeholder' => 'Enter Page Title',
                                'class' => 'form-control')) . PHP_EOL; ?>

        <?php echo form_label('Url', 'slug', 'class="control-label"'); ?>

            <?php echo site_url(); ?>
            <?php echo form_input(array(
                                    'name' => 'slug',
                                    'id' => 'input-slug')); ?>

and in new_page.validation.js
$(document).ready(function() {

    //--------------------------------------------------------------------------------------
    //
    //  New Page Client Side Validation
    //
    //--------------------------------------------------------------------------------------

    $('#new-page-form').validate({

        onkeyup:true,

        rules: {
            'page-title': {
                required: true,
                remote: {
                    url: 'new_title_exists',
                    type: 'post',
                    data: {
                        'page-title': function() { return $("#input-page-title").val(); }
                    }
                }
            },
            'slug': {
                required: true,
                remote: {
                    url: 'new_slug_exists',
                    type: 'post',
                    data: {
                        'slug': function() { return $('#input-slug').val(); }
                    }
                }
            }
        },
        messages: {
            'page-title': {
                required: 'Page Title is required.',
                remote: 'Page Title must be unique.'
            },
            'slug': {
                required: 'A URL slug is required',
                remote: 'The URL must be unique.'
            }
        }
    })
})

Any help would be grateful! Cheers guys

A: $('#new-page-form').validate({
    // onkeyup:true, // REMOVE THIS
    rules: {
        'page-title': {
            required: true,
            remote: {  // element's value IS always sent
                url: 'new_title_exists',
                type: 'post',
                data: {  // MUST send the CSRF Token Value
                    'csrftoken': function() {
                        return $('input[name="csrftoken"]').val();
                    }
                }
            }
        },
        ....

*

*onkeyup: true could potentially break the normal functioning of the plugin. As per documentation, "a boolean true is not a valid value". That's because the onkeyup ability is already the default.

*Whenever using jQuery Validate remote method, or any ajax(), in a CodeIgniter project, you also have to send the CSRF token within the data, otherwise you will get a 500 server error. You can pick this up from the hidden input element on your form. You do not need to send the value of the input element being evaluated, however, because that data is already being sent by default.  Change the name above to match what's showing in the rendered source code of your form.


text:
Q: Checking For Existence of Getters in Java Without Triggering Exception Trying to use reflection to see if a class has a getter defined for each of its fields:
Arrays.stream(entityClass.getDeclaredFields()).forEach(field -> {
    try {
        PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(entityClass, field.getName());

        if(null == PropertyUtils.getReadMethod(pd)) {
            // no getter found, this is what I need to act on
        }
    } catch(Exception e) {
        //
    }
});

Problem is, BeanUtils.getPropertyDescriptor throws an exception if a field does not have both a getter and a setter defined and that breaks the logic flow of this piece of code.  I understand that this is because it expects the class to adhere to the Java bean spec which requires getters/setters... however in this case the classes don't necessarily do so (they're not strictly Java beans).  So I suppose this approach won't work.  Are there alternatives?  3rd party e.g. Apache commons would be fine.

A: If would use Java's build in Reflection functionality for this:
public Optional<Method> findGetter(Field field) {

  Class<?> fieldType = field.getType();
  String methodPrefix;
  if (fieldType == boolean.class) {
    methodPrefix = "is";
  } else {
    methodPrefix = "get";
  }

  String methodName = methodPrefix + field.getName();
  Class<?> declaringClass = field.getDeclaringClass();

  for (Method method : declaringClass.getDeclaredMethods()) {

    String name = method.getName();
    int modifiers = declaringClass.getModifiers();
    if (Modifier.isStatic(modifiers) || !Modifier.isPublic(modifiers) || method.getParameterCount() != 0) {
      continue;
    }
    if (fieldType.equals(method.getReturnType()) && methodName.equalsIgnoreCase(name)) {
      return Optional.of(method);
    }
  }
  return Optional.empty();
}

This code ignores capitalization rules for getter methods. So if you want to be closer to the JavaBeans spec you would need to extend this. If you should plan to do more reflection stuff I recommend to have a closer look on the Reflections library. Just for this simple task I wouldn't introduce a complete library + this way you can define precisely what you allow as getter method and what not.


text:
Q: What is the command used to associated the work-item while check-in your code in TFVC for TFS 2017? I am trying to write a PowerShell script which help developer to check-in their changes via PowerShell ISE and link the changeset to work item. I have TFS 2017 and TVFC is configured.

A: This can't be dont through tc vc commands, but since PowerShell can load the TFS Client Object Model, it's easy to use that to set some properties on the pending changes. You can use the VersionControlServer class to access the WorkSpace and associate the workitems using the WorkspaceCheckinParameters.AssociatedWorkItems class.
var checkinParameters = new WorkspaceCheckInParameters(changes, comment)
{
    AssociatedWorkItems = ... <- Associate your work items here
};

return _workspace.CheckIn(checkinParameters);


text:
Q: Check if a process is running using Python on Linux I am trying to find if the process is running based on process id. The code is as follows based on one of the post on the forum. I cannot consider process name as there are more than one process running with the same name.
def findProcess( processId ):
    ps= subprocess.Popen("ps -ef | grep "+processId, shell=True, stdout=subprocess.PIPE)
    output = ps.stdout.read()
    ps.stdout.close()
    ps.wait()
    return output
def isProcessRunning( processId):
    output = findProcess( processId )
    if re.search(processId, output) is None:
        return true
    else:
        return False

Output :
1111 72312 72311   0   0:00.00 ttys000    0:00.00 /bin/sh -c ps -ef | grep 71676
1111 72314 72312   0   0:00.00 ttys000    0:00.00 grep 71676

It always return true as it can find the process id in the output string.
Any suggestions? Thanks for any help.

A: You could check if the folder /proc/[process_id] exists.
 >>> import os.path
 >>> os.path.exists("/proc/0")
 False
 >>> os.path.exists("/proc/12")
 True

See this SO: How do you check in Linux with Python if a process is still running?

A: This is a bit of a kludge, but on *nix you can use os.getpgid(pid) or os.kill(pid, sig) to test the existence of the process ID.
import os

def is_process_running(process_id):
    try:
        os.kill(process_id, 0)
        return True
    except OSError:
        return False

EDIT: Note that os.kill works on Windows (as of Python 2.7), while os.getpgid won't.  But the Windows version calls TerminateProcess(), which will "unconditionally cause a process to exit", so I predict that it won't safely return the information you want without actually killing the process if it does exist.
If you're using Windows, please let us know, because none of these solutions are acceptable in that scenario.

A: I know this is old, but I've used this and it seems to work; you can do a quick adaptation to convert from process name to process id:
 try:
    if len( os.popen( "ps -aef | grep -i 'myprocess' | grep -v 'grep' | awk '{ print $3 }'" ).read().strip().split( '\n' ) ) > 1:
        raise SystemExit(0)
 except Exception, e:
        raise e

A: If you don't mind using external module I'd suggest psutil. It is cross-platform and easier to use than spawning subshell only for purpose of finding a running process.

A: Try:
os.kill(pid, 0)

Should succeed (and do nothing) if the process exists, or throw an exception (that you can catch) if the process doesn't exist.

A: If that process belongs to the same user the checking process, you can just try to kill it. If you use signal 0, kill will not send anything but still allow you to tell if the process is available.
From kill(2):

If sig is 0, then no signal is sent, but error checking is still
  performed; this can be used to check for the existence of a process ID
  or process group ID.

This should propagate appropriately to python's methods.

A: On Windows another option is to use tasklist.exe:
Syntax: tasklist.exe /NH /FI "PID eq processID"
def IsProcessRunning( processId ):
    ps= subprocess.Popen(r'tasklist.exe /NH /FI "PID eq %d"' % (processId), shell=True, stdout=subprocess.PIPE)
    output = ps.stdout.read()
    ps.stdout.close()
    ps.wait()
    if processId in output:
       return True
    return False

A: On Windows, you can use WMI.
from win32com.client import GetObject
GetObject('winmgmts:').ExecQuery("Select * from Win32_Process where ProcessId = " + str(pid)).count

You can also use other filters.  For example, I'm much more likely to just want to tell if a process is running by name and take action.  For example, if DbgView isn't running, then start it.
if not GetObject('winmgmts:').ExecQuery("Select * from Win32_Process where Name = 'dbgview.exe'").count:
    subprocess.Popen(r"C:\U\dbgview.exe", shell=False)

You can also iterate and do other interesting things.  Complete list of fields is here.

A: The simplest answer in my opinion (albiet maybe not ideal), would be to change your
ps -ef | grep <pid>

To:
ps -ef | grep <pid> | grep -v grep

This will ignore the process listing for the grep search containing the PID of the process you are trying to find.
It seems user9876's answer is far more "pythonic" however.

A: Recently I had to list the running processes and did so:
def check_process(process):
  import re
  import subprocess

  returnprocess = False
  s = subprocess.Popen(["ps", "ax"],stdout=subprocess.PIPE)
  for x in s.stdout:
      if re.search(process, x):
          returnprocess = True

  if returnprocess == False:
      print 'no process executing'
  if returnprocess == True:
      print 'process executing'

A: You have to find it twice..
Like this :
ps -ef | grep 71676 | sed 's/71676//' | grep 71676
If this returns True then this is actually running !!


text:
Q: CreateView неправильно работает с загрузкой файла, почему? Мне нужно сохранить файл через форму, делаю так:
models.py
class Post(models.Model):
    title = models.CharField(max_length=255)
    image = ImageField(upload_to='images')

forms.py
class PostForm(forms.ModelForm):
    class Meta:
        model = Post

views.py
class PostCreateView(CreateView):
    form_class = PostForm
    template_name = 'create.html'
    success_url = '/'

Например, если я выбрал файл и не заполнил title, то перезагружается страница, над title пишется, что поле обязательное, а выбранный файл не отображается, я заполняю тайтл и не выбираю заново файл, перезагружается страница и пишется, что файл не выбран, но если заново выберу файл, то сохранится...
Мне интересно, это CreateView некорректно работает с файлами или я что-то делаю неправильно?
A: Все верно, файловые поля в браузерах не сохраняют загруженный файл из соображений безопасности. Если нужно сохранять, используйте специальный виджет вроде https://github.com/un1t/django-file-resubmit


text:
Q: Android studio 'Error running 'app': Default Activity not found I don't understand why the error not disappeared
I was thinking it is error from Manifest.xml because it show after i adjust manifest file
but i can't find what was my mistake
can you teach me?

A: File -> Invalidate Caches / Restart...


text:
Q: Add new Link to Quick Launch Navigation clientContext.Load(web);

NavigationNodeCollection oNavNodeCollection = web.Navigation.QuickLaunch;

NavigationNodeCreationInformation oNewNaviNode = new NavigationNodeCreationInformation();
oNewNaviNode.Title = txtDisplayText.Text;
oNewNaviNode.Url = txtLinkAddress.Text;
oNewNaviNode.AsLastNode = true;

oNavNodeCollection.Add(oNewNaviNode);

clientContext.Load(oNavNodeCollection);
clientContext.ExecuteQuery();

This code executed successfully but no result on Quick Launch Navigation!
SharePoint 2013.

A: Please try below code. It works perfectly for me.
var quickLaunchNodeCollection = null;
var oNewNaviNode = null;

function addNavigationNodes() {

    var context = new SP.ClientContext.get_current();

    if (context != undefined && context != null) {

        var web = context.get_web();

        //this.navigationNodeCollection = web.get_navigation().get_topNavigationBar();
        this.quickLaunchNodeCollection = web.get_navigation().get_quickLaunch();

        // Set properties for a new navigation node.
        this.oNewNaviNode = new SP.NavigationNodeCreationInformation();
        oNewNaviNode.set_title("NewNavigationNode");
        oNewNaviNode.set_url("http://www.google.com");

        oNewNaviNode.set_asLastNode(true);
        this.quickLaunchNodeCollection.add(oNewNaviNode);

        context.load(this.quickLaunchNodeCollection);
        context.executeQueryAsync(addNavigationNodesSuccess, addNavigationNodesFailed);
    }
}

function addNavigationNodesSuccess() {
    alert("New node added...");
}

function addNavigationNodesFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}


text:
Q: Group by pandas dataframe and impute missing values I am creating a new calculated pandas column, however, I'd like to exclude certain rows, and calculate the value for the new column. And then to fill the values for excluded rows, I'd like to subset the dataframe by df1.groupby['City'] and calculate the mean value to apply back to new col in original dataframe.
   df1 = pd.DataFrame({
                        'City': ['SF','NYC','SF','NYC','SF','CHI','LA','LA','CHI'],
                        'Val': [2,4,0,0,7,4,3,5,6],
                        'Val1': [1,1,1,1,1,1,1,1,1]
                       })

   df1['new col'] = np.nan

   for name, group in df.groupby(['City']):

       # Create Boolean Index
       m = group['Val'] != 0

       # Calculate rev_per_unit from grouped dataframe `group`
       stat = group.loc[m, 'Val'] / group.loc[m, 'Val1']

       # Assign stat to `df` at index locations where `Val` is 0 in group
       df.loc[group[~m].index, ''] = group['new col'].mean()

Expected output:
df1 = pd.DataFrame({
                        'City': ['SF','NYC','SF','NYC','SF','CHI','LA','LA','CHI'],
                        'Val': [2,4,0,0,7,4,3,5,6],
                        'Val1': [1,1,1,1,1,1,1,1,1],
                        'new_col: [2,4,4.5,2,7,4,3,5,6]
                       })

The new column is a calculated column of df1['Val] / df1['Val1'] excluding the df['Val'] == 0 and then I impute the new_col for rows where df['Val'] == 0 as grouped means.

A: First set new_col to Val/Val1:
df1['new_col'] = df1['Val'] / df1['Val1']

Then use groupby.transform to compute the grouped means (set 0 to nan to ignore those rows):
means = df1['new_col'].replace(0, np.nan).groupby(df1['City']).transform('mean')

# [4.5, 4.0, 4.5, 4.0, 4.5, 5.0, 4.0, 4.0, 5.0]
# Length: 9, dtype: float64

Lastly impute the 0 locations with the grouped means:

*

*Either use DataFrame.loc:
df1.loc[df1['Val'].eq(0), 'new_col'] = means

*Or Series.mask:
df1['new_col'] = df1['new_col'].mask(df1['Val'].eq(0), means)

*Or Series.fillna:
df1['new_col'] = df1['new_col'].replace(0, np.nan).fillna(means)

So altogether:
df1['new_col'] = df1['Val'] / df1['Val1']
means = df1['new_col'].replace(0, np.nan).groupby(df1['City']).transform('mean')
df1.loc[df1['Val'].eq(0), 'new_col'] = means

#   City  Val  Val1  new_col
# 0   SF    2     1      2.0
# 1  NYC    4     1      4.0
# 2   SF    0     1      4.5
# 3  NYC    0     1      4.0
# 4   SF    7     1      7.0
# 5  CHI    4     1      4.0
# 6   LA    3     1      3.0
# 7   LA    5     1      5.0
# 8  CHI    6     1      6.0


text:
Q: How to solve error of node-gyp running yarn install I'm trying to run yarn install on a project and I got the following issue and have no clue what to do.
My versions:
- node -v v15.2.1
- npm -v 6.14.10
- node-gyp -v v7.1.2

error /Users/jake/Dropbox/My Mac (Jakub's MacBook Pro)/Desktop/Trialbee/admin-frontend/node_modules/deasync: Command failed.
Exit code: 1
Command: node ./build.js
Arguments:
Directory: /Users/jake/Dropbox/My Mac (Jakub's MacBook Pro)/Desktop/Trialbee/admin-frontend/node_modules/deasync
Output:
gyp info it worked if it ends with ok
gyp info using node-gyp@7.1.2
gyp info using node@15.2.1 | darwin | x64
gyp info find Python using Python version 2.7.16 found at "/System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python"
gyp info spawn /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python
gyp info spawn args [
gyp info spawn args   '/usr/local/Cellar/node/15.2.1/libexec/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py',
gyp info spawn args   'binding.gyp',
gyp info spawn args   '-f',
gyp info spawn args   'make',
gyp info spawn args   '-I',
gyp info spawn args   '/Users/jake/Dropbox/My Mac (Jakub's MacBook Pro)/Desktop/Trialbee/admin-frontend/node_modules/deasync/build/config.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/usr/local/Cellar/node/15.2.1/libexec/lib/node_modules/npm/node_modules/node-gyp/addon.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/Users/jake/Library/Caches/node-gyp/15.2.1/include/node/common.gypi',
gyp info spawn args   '-Dlibrary=shared_library',
gyp info spawn args   '-Dvisibility=default',
gyp info spawn args   '-Dnode_root_dir=/Users/jake/Library/Caches/node-gyp/15.2.1',
gyp info spawn args   '-Dnode_gyp_dir=/usr/local/Cellar/node/15.2.1/libexec/lib/node_modules/npm/node_modules/node-gyp',
gyp info spawn args   '-Dnode_lib_file=/Users/jake/Library/Caches/node-gyp/15.2.1/<(target_arch)/node.lib',
gyp info spawn args   '-Dmodule_root_dir=/Users/jake/Dropbox/My Mac (Jakub's MacBook Pro)/Desktop/Trialbee/admin-frontend/node_modules/deasync',
gyp info spawn args   '-Dnode_engine=v8',
gyp info spawn args   '--depth=.',
gyp info spawn args   '--no-parallel',
gyp info spawn args   '--generator-output',
gyp info spawn args   'build',
gyp info spawn args   '-Goutput_dir=.'
gyp info spawn args ]
gyp info spawn make
gyp info spawn args [ 'BUILDTYPE=Release', '-C', 'build' ]
  CXX(target) Release/obj.target/deasync/src/deasync.o
/bin/sh: -c: line 0: syntax error near unexpected token `('
/bin/sh: -c: line 0: `c++ -o Release/obj.target/deasync/src/deasync.o ../src/deasync.cc '-DNODE_GYP_MODULE_NAME=deasync' '-DUSING_UV_SHARED=1' '-DUSING_V8_SHARED=1' '-DV8_DEPRECATION_WARNINGS=1' '-DV8_DEPRECATION_WARNINGS' '-DV8_IMMINENT_DEPRECATION_WARNINGS' '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DOPENSSL_NO_PINSHARED' '-DOPENSSL_THREADS' '-DBUILDING_NODE_EXTENSION' -I/Users/jake/Library/Caches/node-gyp/15.2.1/include/node -I/Users/jake/Library/Caches/node-gyp/15.2.1/src -I/Users/jake/Library/Caches/node-gyp/15.2.1/deps/openssl/config -I/Users/jake/Library/Caches/node-gyp/15.2.1/deps/openssl/openssl/include -I/Users/jake/Library/Caches/node-gyp/15.2.1/deps/uv/include -I/Users/jake/Library/Caches/node-gyp/15.2.1/deps/zlib -I/Users/jake/Library/Caches/node-gyp/15.2.1/deps/v8/include -I/Users/jake/Dropbox/My Mac (Jakub's MacBook Pro)/Desktop/Trialbee/admin-frontend/node_modules/node-addon-api  -O3 -gdwarf-2 -mmacosx-version-min=10.7 -arch x86_64 -Wall -Wendif-labels -W -Wno-unused-parameter -std=gnu++1y -stdlib=libc++ -fno-rtti -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/deasync/src/deasync.o.d.raw   -c'
make: *** [Release/obj.target/deasync/src/deasync.o] Error 2
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/usr/local/Cellar/node/15.2.1/libexec/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:194:23)
gyp ERR! stack     at ChildProcess.emit (node:events:329:20)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:277:12)
gyp ERR! System Darwin 19.6.0
gyp ERR! command "/usr/local/Cellar/node/15.2.1/bin/node" "/usr/local/Cellar/node/15.2.1/libexec/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/jake/Dropbox/My Mac (Jakub's MacBook Pro)/Desktop/Trialbee/admin-frontend/node_modules/deasync
gyp ERR! node -v v15.2.1


text:
Q: Receiving UDP broadcast datagrams My system has 3 active network interfaces:

*

*192.168.1.7    (Wireless adapter)

*192.168.247.1  (virtual VMWare Ethernet adapter)

*169.254.54.231 (another VMWare Ethernet adapter)

I'm trying to set up an UDP socket listening for SSDP broadcasts on port 1900 on all interfaces, however I don't seem to receive all broadcast datagrams but only some.
This is my code:
static void Main(string[] args) {
    IPEndPoint broadcastEP =
        new IPEndPoint(IPAddress.Parse("239.255.255.250"), 1900);

    using (var udp = new UdpClient(broadcastEP.Port)) {
        udp.JoinMulticastGroup(broadcastEP.Address);
        while (true) {
            IPEndPoint remoteEP = null;
            Console.WriteLine("Listening for data on port " + broadcastEP.Port);
            byte[] buffer = udp.Receive(ref remoteEP);
            Console.WriteLine("Received " + buffer.Length + " data bytes from " + remoteEP);
        }
    }
}

If I now sent a broadcast datagram from another process, the above code should pick it up, right?
However when I execute this code in another process, the first process will only pick up the broadcast, if it's been sent from the 192.168.1.7 interface. If I send a broadcast from one of the other interfaces, the first process simply won't receive it. I can see that the broadcast is actually being sent in Wireshark...am I missing something?
static void Main(string[] args) {
    var ifs = new IPAddress[] {
            IPAddress.Parse("192.168.1.7"),
            IPAddress.Parse("192.168.247.1"),
            IPAddress.Parse("169.254.54.231")
        };
    IPEndPoint broadcastEP =
        new IPEndPoint(IPAddress.Parse("239.255.255.250"), 1900);

    using (UdpClient cli = new UdpClient(new IPEndPoint(ifs[0], 0))) {
                IPEndPoint ep = new IPEndPoint(broadcastEP.Address, broadcastEP.Port);
                int n = cli.Send(new byte[] { 1, 2, 3, 4 }, 4, ep);
                Console.WriteLine("Sent " + n + " bytes to " + ep);
    }
}

I know Windows runs a service (called SSDPSRV) listening for SSDP broadcasts on port 1900. Could that possibly "swallow" datagrams, so that they won't be delivered to my process? If so, is there anything I can do about this?
Thanks


text:
Q: Text classification CNN nan loss I'm attempting to train a neural network for text classification (sarcasm detection on reddit comments). I have the comment itself, its parent comment, and the subreddit in which these comments were made.
I engineer features such as the positivity, negativity, and neutrality of the comment, the same for the parent comment, and engineer 2 more numerical features based on the subreddit. This is a total of 8 engineered features.
The neural network I use is structured as such: I run a bunch of filters over my (word-embedding translated) comment, a bunch of filters over my parent comment (word-embedding translated), using a 1D CNN. I subsequently do some pooling and feed the outputs to a fully connected layer.
This works fine.
However, I wish to add in those 8 engineered features to my inputs to the fully connected layer. But when I do so, the loss decreases (rather quickly), and suddenly I see the loss turn to nan and accuracy decrease.
Below is the code within my function to produce the model: -
embedding_layer = Embedding(num_words,
                        embedding_dim,
                        weights=[embeddings],
                        input_length=max_sequence_length,
                        trainable=False)

parent_embedding_layer = Embedding(parent_num_words,
                        embedding_dim,
                        weights=[parent_embeddings],
                        input_length=max_sequence_length,
                        trainable=False)

sequence_input = Input(shape=(2, 205))
// some tensor manipulation

comment_sequence_input:= length 200 tensor of words in comment
parent_sequence_input:= length 200 tensor of words in comment

non_text_comment_input:= length 5 tensor with 5 engineered features
non_text_parent_input:= length 5 tensor with 5 engineered features

embedded_sequences = embedding_layer(comment_sequence_input)
parent_embedded_sequences = parent_embedding_layer(parent_sequence_input)

convs = []

// Convolutions

for filter_size in filter_sizes:
    l_conv = Conv1D(filters=filters, kernel_size=filter_size,
                    activation='relu')(embedded_sequences)
    l_pool = GlobalMaxPooling1D()(l_conv)
    convs.append(l_pool)

for filter_size in parent_filter_sizes:
    parent_l_conv = Conv1D(filters=parent_filters, kernel_size=filter_size,
                           activation='relu')(parent_embedded_sequences)
    parent_l_pool = GlobalMaxPooling1D()(parent_l_conv)
    convs.append(parent_l_pool)

// End of convolutions

//Inclusion of engineered features
convs.append(non_text_comment_input)
convs.append(non_text_parent_input)

l_merge = concatenate(convs, axis=1)
// end of section

x = Dropout(0.30)(l_merge)

// Start of fully connected layer

x = Dense(128, activation='relu')(x)
x = Dense(64, activation='relu')(x)
preds = Dense(labels_index, activation='sigmoid')(x)
adam_optimizer = Adam(learning_rate=0.000001)
model = Model(sequence_input, preds)
model.compile(loss='binary_crossentropy',
              optimizer=adam_optimizer,
              metrics=['acc'])
model.summary()
return model

The input provided is a (batch_dim, 2, 205) size tensor. 200 for the number of words in each entry, and 5 for the 3 sentiment engineered features and 2 subreddit engineered features. The 2 dimensions are for comment and parent comment.
Things I have tried:

*

*Lowering the learning rate

*Adding dropout

*Normalising inputs

*Normalising inputs and scaling them down by a factor of 100

*Different optimizers (RMSprop, Nadam, etc)

*Adding regularization (bias reg, kernel reg, activity reg) of various levels to my layers.

I tried testing this by setting all my engineered feature values to 0, and the network trains perfectly fine. Not sure what I should do here.


text:
Q: How to disable the dismissal of UIAlertController in swift How can i run the action for the "keep" button without dismissing the UIAlertController ?
I found solutions for disabling the button but it's not what i need.
newItemPrompt = UIAlertController(title: "title", message: "message", preferredStyle: UIAlertControllerStyle.Alert)

let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: nil)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
 println("ok")
 })
let keepAlert = UIAlertAction(title: "keep", style: .Default) {  (action) -> Void in
println("keep alert view")
}
newItemPrompt.addAction(okAction)
newItemPrompt.addAction(keepAlert)
newItemPrompt.addAction(cancelAction)
self.presentViewController(newItemPrompt, animated: true, completion: nil)

A: You may want to create your own View Controller where you decide what all the buttons do. However, if you really want to use UIAlertController, you could show the same alert again when the user clicks on the "keep" button:
let keepAlert = UIAlertAction(title: "keep", style: .Default) {  (action) -> Void in
self.presentViewController(newItemPrompt, animated: true, completion: nil)
println("keep alert view")
}

The alert will disappear for a second and re-appear then. It's not ideal, but it's a workaround.

A: Disabling the button is probably the only way to disable that method, either that or delete the code. I'll do more research but thats all you can do for now :)


text:
Q: Bash - How to combine duplicate rows and sum the values of a csv file? I have this csv file:
Apple,5
Apple,2
Banana,3
Banana,7
Avocado,1
Grapefruit,9

And I want to combine the duplicate rows on the left and sum the values on the right. This is the end result that I want:
Apple,7
Banana,10
Avocado,1
Grapefruit,9

I know this is more of Ms Excel stuff but I want to learn how to do it with the bash script. So far I can only sort it like this:
sort -u file.csv

I don't know how to sum the values on the right based on each fruit on the left. How do I do this ?
EDIT: The answer provided below doesn't work with my actual file so here's the complete csv file
Order Date,Username,Order Number,No Resi,Quantity,Title,Update Date,Status,Price Per Item,Status Tracking,Alamat
05 Jun 2018,Mildred@email.com,205583995140400,,2,Gold,05 Jun 2018 – 10:01,In Process,Rp3.000.000,Done,Syahrul Address
05 Jun 2018,Mildred@email.com,205583995140400,,1,Gold,05 Jun 2018 – 10:01,In Process,Rp3.000.000,Done,Syahrul Address
05 Jun 2018,Martha@email.com,205486016644400,,2,Gold,05 Jun 2018 – 10:01,In Process,Rp3.000.000,Done,Faishal  Address
05 Jun 2018,Martha@email.com,205486016644400,,2,Gold,05 Jun 2018 – 10:01,In Process,Rp3.000.000,Done,Faishal  Address
05 Jun 2018,Misty@email.com,205588935534900,,2,Gold,05 Jun 2018 – 10:01,In Process,Rp3.000.000,Done,Rutwan Address
05 Jun 2018,Misty@email.com,205588935534900,,1,Gold,05 Jun 2018 – 10:01,In Process,Rp3.000.000,Done,Rutwan Address

I want the end result to be like this:
Order Date,Username,Order Number,No Resi,Quantity,Title,Update Date,Status,Price Per Item,Status Tracking,Alamat
05 Jun 2018,Mildred@email.com,205583995140400,,3,Gold,05 Jun 2018 – 10:01,In Process,Rp3.000.000,Done,Syahrul Address
05 Jun 2018,Martha@email.com,205486016644400,,4,Gold,05 Jun 2018 – 10:01,In Process,Rp3.000.000,Done,Faishal  Address
05 Jun 2018,Misty@email.com,205588935534900,,3,Gold,05 Jun 2018 – 10:01,In Process,Rp3.000.000,Done,Rutwan Address

I only want to sum the Quantity row while leaving the rest as it is. How do I do it with awk?


text:
Q: How to properly design game state machine with internal conditional transitions I am having the following states which are designed to simulate game states
enum GameStates{ Bet, CompleteBet, Bonus,CompleteBonus, Jackpot, CompleteJackpot }

Only Bet state is external for the game (can be triggered from outside). Every other state is internal, that is triggered by the game itself.
If I am in CompleteBet state, the game can proceed to Bonus state, but also can be returned back to Bet state (this is per game configuration).
The same situation is repeated when in CompleteBonus state. The game can transit itself to Bet or Jackpot state.
Right now I am handling this situation with the following if - else logic
    // In CompleteBet state
    if (bonus.isEnabled) {
        setState(Bonus);
    } else {
        if (jackpot.isEnabled) {
            setState(Jackpot);
        } else {
            setState(Bet);
        }

        // in CompleteBonus state
        if (jackpot.isEnabled) {
            setState(Jackpot);
        } else {
            setState(Bet);
        }
    }

But obviously that's not good solution. Maybe I need to redesign my state machine? Any suggestions are appreciated
Edit:
 Actually GameState enum is defined like so:
enum GameState implements TransferState {
    WITHDRAW {
        @Override
        public void initiateStep(final GameContext context) {
            //some logic which triggers complete transfer
        }
    },

    COMPLETE_WITHDRAW {
        @Override
        public void completeTransfer(final GameContext context) {
            // if bonus is enabled;
            if (true) {
                context.setState(BONUS);
            } else {
                // if remote gaming is on
                if (true) {
                    context.setState(REMOTE_GAME);
                } else {
                    context.setState(WITHDRAW);
                }
            }
        }
    }
    // ...
}

initiateTransfer and completeTransfer are defined as default methods in TransferState interface.

A: In this case I would have use the State Patter with a chain of responsibility pattern, and example for your case
The your game
public class Game{

    private IState state = new StateReady();

    public void play(){
        state.play(this);
    }

    public void setState(IState state){
        this.state = state;
    }

}

A state
public StateReady implements IState{

        private List<IGameHeadler> headler = new ArrayList<>();

        public StateReady(){
            headler.add(new BonusHeadler());
            headler.add(new JackpotHeadler());
        }

        public void play(Game game){
            //Your operation
            //an example the operation is
            Iterator iterator = headler.iterator();
            boolean flag = false;
            while(iterator.hasNext() && !flag){
                IGameHeadler headler = (IGameHeadler)iterator.next();
                flag = headler.doChain();

            }
            game.setState(new WaitState(game));
        }
}

Common interfaces
public interface IGameHeadler{

    boolean doChain();
}

public interface IState{

    void play(Game game);
}

But the state of the game would change to

*

*An external thread

*The Game class

*The another state

*Any object, the pattern is an idea that offers a solution to a known problem but this idea can be extended depending on the case

Also, the chain of responsibility pattern is a cool mode for divide the your logic in more headler, in your case one headler is If()
Also, I preferer used another patter for create a state, one state is unique and the flyweight pattern resolve this problem I would have removed the enum


text:
Q: Is the Higgs boson not responsible for most mass? The video "Your Mass is NOT from Higgs Boson?" argues that almost all the mass that we are made of doesn't come interaction with the Higgs field, but rather that most of a nucleus's mass comes from the space between quarks (the quark-gluon plasma).
If the video is correct, then there really needs to be an easy-to-understand explanation for mass because science popularizers make us laypeople think that the Higgs mechanism is responsible for all the mass in the atoms and that would be of course very misleading.

A: The experimentalist's answer:
1) Experimental physics has established with very many experiments that the underlying framework of nature is quantum mechanical, and this includes special relativity, when the energies are appropriate. It is dependent on a very small number of elementary particles out of which all matter that we have observed and experimented with  in our laboratories is composed.
2) The definition of mass that you are worrying about is the everyday one described well by  classical mechanics, as the resistance to a force applied.

Inertial mass measures an object's resistance to changes in velocity m=F/a. (the object's acceleration).

In the regime of relativistic physics an elementary particle as seen  in this table has a rest mass:$\hspace{50px}$.

Elementary particles included in the Standard Model

They have a mass given in the table, except  for the two top ones in the column in red, which are massless particles. These particles in various bound states compose the protons (quarks and gluons) and neutrons, the protons and neutrons bound make the nuclei of the atoms and gather around them the electrons  and the atoms make up the solids.
If you look at the masses they could never sum up to the mass of the proton $\left(1\frac{\mathrm{GeV}}{c^2}\right).$
What happens is that the addition is not of scalar masses, but of four vectors, the three dimensional momenta that we know plus the energy as the fourth component in the special metric of special relativity. The mass, in this framework is the corresponding  "length" of three dimensions  and is called the "invariant mass" : For the elementary particles this "length" is identical with the mass of the table . When two elementary particles form another particle, or come out of a particle , the mass of the composite particle  is a function of the four dimensional vector addition of the individual elementary particles composing it .
For example there exists a particle called pion $\left(\pi^0\right)$, of mass $135 \frac{\mathrm{MeV}}{c^2}.$ It decays into two massless photons. The two photon system has the invariant mass of the ${\pi}^0$ even though  each photon has mass zero.
A hierarchy is built up then, elementary particles, (quarks, gluons) combine to compose the protons and neutrons, protons and neutrons combine to compose nuclei, electrons plus nuclei compose atoms.The composite invariant mass at one level becomes the rest mass of the next level's basic particles. Each level has less kinetic energy in the combination than the previous level ,  so the masses start to resemble the classical mechanics masses. When we reach solids and liquids of dimensions larger than nanometers, the relativistic effects can be  ignored .
Where does the Higgs field come in, in this saga? It only affects the invariant masses of the elementary particles in the table , their rest masses. The bulk of the masses we measure macroscopically are a build up, level by level, on these elementary particles and their binding energies. The high energies that bind the under lying layers become macroscopically  the classical mechanics masses.
A good point is to think of the binding energy curve and  nuclear reactions where we see the opposite process: classical mass turning into energy by destroying the level of compositeness.

A: A particle physicist told me that Higgs fields explains just a small part of the mass, while most of the mass is due to the energy binding de protons in the nucleus (which is described using QCD).
So I think that what the video says is right.

A: There is a clear mistake in what he says : the mass does not come from the interaction with the higgs particles in it self. In essence, for the mass due to the Higgs mechanism, the Lagrangian contains originally massless particles. This is due to the requirement of gauge symmetry. Mass terms are not gauge invariant.
The higgs mechanism is a dynamical mechanism in which originally massless fields acquire mass. The (scalar) field associated with the Higgs acquires a non zero vacuum value, as we say, by spontaneous symmetry breaking. The symmetry breaking part comes from the fact that if the vacuum state of the Higgs don't contain the same symmetry as the original, unbroken, Lagrangian then the gauge bosons will acquire a mass. The non-zero vacuum of the higgs will give the terms corresponding to a mass.
But the higgs particles, as we can produce them in the LHC, are small excitations of the higgs field. These small perturbations are done around the vacuum state of the field, and can also interact with the particles of the theory, but are not responsible for the mass.

A: Higgs mechanism is not the universal mass-responsible detail, but the ultimate. Other mechanisms could give you large quantities of mass - and in fact they do - but there is still some part which they are unable to explain. And that's why the Higgs mechanism is needed.
Numbers for you:
For the atom of hydrogen:
Total mass - about 1 GeV
Electromagnetic field - several eV (billionth parts)
Nuclear force field - none
Masses of electron and quarks - by Higgs mechanism - about 20 MeV
The rest is due to gluons (and virtual quarks) tension and motion.
For other atoms:
Total mass - about 1 GeV per nucleon (proton or neutron)
Electromagnetic field - up to keV per proton (not the field inside the nucleus itself)
Nuclear force field - up to several MeV per nucleon
Electromagnetic field inside the nucleus - up to the same as nuclear force field's part
Masses of electrons and quarks - by Higgs mechanism - about 20 MeV per nucleon
The rest is due to ... see above.


text:
Q: Perform simple operation on single column in panda dataframe without using .apply I have a panda dataframe df. I would like to transform the values of one of the columns col_X such that ;
if col_X_value < 0:
    col_X_value = 0

I can do that if I write a separate python function, then use the apply function.
This link describes how it can be done with .apply.
http://jonathansoma.com/lede/foundations/classes/pandas%20columns%20and%20functions/apply-a-function-to-every-row-in-a-pandas-dataframe/
However, I do not want to write a python function for such a simple operation. How can I do this without writing a separate python function and using apply?
I am using python v3.6

A: Use the pandas version of where
df.col_X_value.where(df.col_X_value > 0, 0)

This will fill return 0 if the value is less than 0 and the value if not

A: You can use .loc to slice the DataFrame and set portions accordingly. First, create a boolean Series where df['col_X_value'] < 0 and where that is True set 'col_X_value' to 0
df.loc[df['col_X_value'] < 0, 'col_X_value'] = 0

And in this case, you can actually use one of the pandas functions .clip_lower to achieve what you want.
df['col_X_value'] = df.col_X_value.clip_lower(0)

A: Using clip
df = df.clip(lower=0)


text:
Q: How to make active class for url while using external header file I created general header file that included all nav links and includes that file in each html page. While doing so I want to know if there is a way to make active page identification like background for the link and so on?

A: If you're going the vanilla route with the JS and no framework you can use location.pathname and match that with an href on a.
Let's say you're at https://example.com/about.
So, you can do:
document.documentElement.setAttribute('data-path', location.pathname)

Then with your CSS do something like:
[data-path="/about"] a[href="/about"] {
  background-color: yellow;
}

Which would match this link on a page.
About

Though, if you're using a framework of some sort this might be a lot more straight forward.

A: The easies way to do this is by using php. In the external file instead of writing class=active using php script if($page=='home'){echo "active"} then it will work


text:
Q: File sometimes got uploaded successfully & sometimes it disappears from the /tmp directory I am running a Laravel 5.2 application with PHP 5.5 and nginx on Ubuntu 14.04.
Sometimes it got uploaded successfully without any error, also sometimes out of nowhere it produces this error.

I don't know what the problem is or what is happening. I can't reproduce the error every time. It just happens randomly!

Here is what I've tried (already configured):
php.ini:
post_max_size: 20M
upload_max_filesize: 20M
memory_limit: -1
max_execution_time: 60
max_input_time: 60

nginx configuration:
client_max_body_size 100m;

A: i don't know how it happen..!!you can try below code and may be help you..!
$bannerimage = $req->file('uploadusers');
                    if($bannerimage!='')
                    {
                        $destination = 'public/uploadimage/';
                        $newname = str_random(5);
                        $ext = $bannerimage->getClientOriginalExtension();
                        $filename = $newname.'-original.'.$ext;
                        $newFilename = $newname.'.'.$ext;
                        if($bannerimage->move($destination, $filename))
                        {
                            copy($destination . $filename, $destination . $newFilename);
                        }
                    }

A: I posted my question on Laracasts Forums here & that is what i got:
It got removed in the 5.2.14 release, here is the commits of UploadedFile Class.


text:
Q: How to refer to several titled individuals, "Mr x,y,z PhD"? How does one abbreviate "Mr Adams PhD, Mr Benson PhD, Mr Charles PhD" to use just one salutation and one title.

A: I believe you are seeking "Messrs." which is an abbreviation of the French 'Messieurs' and is commonly used in English as a plural for "Mr."
Example usage:

Dear Messrs. Jones, Adams and Jefferson,

See Merriam-Webster and Cambridge Online Dictionary for further details.


text:
Q: How to write unit test for this particular use case in python? I have a python file which is being used to modify an XML file. This python file can take inputs from the user and thus modify XML based on the inputs, here is a overview --
a, b, c = input("Enter three values: ").split()

if a is not None:
   modify_a()
else:
   pass
   #don't modify anything in the XML

def modify_a():
  #modify the XML in a certain way eg: add certain attributes, tags etc and then write the contents back to xml file
  tree.write("new.xml")

#similarly for inputs b and c

How to write unit test to the above scenario - I need to test two things

*

*Content of the XML should change based on the input in the python file

*Whether each function is working acc to the requirement.

XML looks something like this
<A>
            <TASK>
                <INSTALL softwareType="aaa" />
                <INSTALL softwareType="qqq" />
                <!--If this input(a) is given, one more tag would be added here-->
            </TASK>
</A>
<B>
            <TASK>
                <INSTALL softwareType="bbb" />
                <INSTALL softwareType="qqq" />
                <!--If this input(b) is given, one more tag would be added here-->
            </TASK>
</B>
<C>
            <TASK>
                <INSTALL softwareType="ccc" />
                <INSTALL softwareType="qqq" />
                <!--If this input(c) is given, one more tag would be added here-->
            </TASK>

</C>


text:
Q: Why Router link does not work in Firefox and IE but working fine in Safari and Chrome in vue js?

Here is my html code :
  <button type="button"  class="btn btn-default btn-block" v-for="x in filterName" v-on:click="passuserid(x.rsid)"> <router-link v-bind:to="'/combo/'">{{x.last_name}} {{x.first_name}}

            </router-link></button>

And Here is the routes code:

export const routes =[
    { path:'', component: ContentArea},
    { path:'/combo/', component: Comparison }
  ];

A: Try to use li instead of the button.

               <router-link to="/combo">{{x.last_name}} {{x.first_name}}</router-link>


text:
Q: Run selenium webdriver via powershell on ubuntu? Made a Powershell script, which is using Selenium webdriver, and it's currently running from an Windows machine.
I'm now looking to change from running the script on Windows, to instead be using a Ubuntu distro.
As I'm now (on Windows) using .NET dll's in the code to get Selenium started I need to find alternative language for this on Ubuntu. That's also compatible with Powershell.
Wondering if there's any such alternative for Powershell?


text:
Q: Shared arraylists between classes Java How do i share arraylists between two classes. I have a Main class that sets the GUI of the application, and i'm trying to make a Database class that executes mysql statements to store, update and retrieve the data into the arraylists of the Main Class.
Here is what i am wanting to do...
Main class
public class Main
{
   public static ArrayList<Animal> animal = new ArrayList<Animal>();
   public static ArrayList<Farm> farm = new ArrayList<Farm>();
   Database db;

   public Main() {
      db = new Database();
   }

   private void addAnimal() {
      db.animal.add(new Animal(specie, age));
      db.addAnimal();
   }

   private void addFarm() {
       db.farm.add(new Farm(address));
       db.addFarm();
   }
}

Database class
import java.sql.*;

public class Database
{
   public static ArrayList<Animal> animal;
   public static ArrayList<Farm> farm;

   private Connection con = null;
   private Statement st = null;
   private ResultSet rs = null;

   public Database()
   {
       try
       {
           con = DriverManager.getConnection(url, user, pw);
           //load database entries into arraylists
       } catch(SQLException e) {
           e.printStackTrace();
       }
   }

   public addAnimal()
   {
       try
       {
           con = DriverManager.getConnection(url, user, pw);
           //add new animal to animal table
       } catch(SQLException e) {
           e.printStackTrace();
       }
   }

   public addFarm()
   {
       try
       {
           con = DriverManager.getConnection(url, user, pw);
           //add new farm to farm table
       } catch(SQLException e){
           e.printStackTrace();
       }
   }
}

A: You need to pass a reference to an instance of your Main class into your Database class via its constructor:
So you need to change your Database constructor to
public Database(Main m);

So, when you create a Database instance from your Main class, you'll use:
db = new Database(this);

Then, you can access your ArrayLists, and any other instance variables in your Main class, using:
 m.animal.add() / m.animal.remove() etc.

NOTE - you'll also need to make sure Main m is an instance variable in your Database class, and in its constructor you'll need to call
 this.m = m;

But I'm guessing I don't need to tell you that :)


text:
Q: MySQL [Bad handshake] error after update I have MASTER-SLAVE configuration on 2 servers. The MySQL replication is set over SSL (I use self-signed certificates).
Everything had been working well. But today some packages (mysql also) were updated via apt update, upgrade. Current version is: mysql  Ver 14.14 Distrib 5.7.28, for Linux (x86_64)
Both server and client have the same mysql version now, but slave can't connect to the master. In master's log I see the following error repeating many times:
2019-11-19T16:49:55.109509Z 1130 [Note] Bad handshake
2019-11-19T16:50:55.296184Z 1432 [Note] Bad handshake

What should I check in order to fix this problem? I've already tried to reissue certificates, but it didn't help.
Thanks.

A: MySQL 5.7.28 dropped support for yaSSL. On some platforms, such as RHEL and presumably Ubuntu, that resulted in a change from yaSSL to OpenSSL. There are a variety of things that would have worked under yaSSL but no longer work under OpenSSL. For example, yaSSL could not handle certificate chains, but OpenSSL both sends and verifies full chains.
Among other troubleshooting techniques, try taking a packet capture of the TLS handshake with tcpdump and decoding it in Wireshark.

A: Okay, the reason was that new version of mysql refuses to accept certs with the same Common Name etc.
I reissued certs for server and client using different metadata this time, updated my.cnf on both master and slave servers and now it works again.
Do not forget to login into MySQL
mysql -u root -p

and update master host details if necessary (MASTER_SSL_CA, MASTER_SSL_CERT MASTER_SSL_KEY)!
CHANGE MASTER TO MASTER_HOST='HOSTIP', MASTER_USER='SLAVEUSER', MASTER_PASSWORD='PWD', MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=112233, MASTER_SSL=1, MASTER_SSL_CA = '/etc/mysql/new-ca-cert.pem', MASTER_SSL_CERT = '/etc/mysql/new-client-cert.pem', MASTER_SSL_KEY = '/etc/mysql/new-client-key.pem';


text:
Q: Is it possible to get a reference to MyList if the listname is a string "myList" I have some lists of the type ObservableCollection<SampleObject>
They all end with a letter of the alphabet: lista, listb, listc...
Now i want to make a loop which runs through the alphabet and at every letter it should add an item to the current list.
Example:
for (char i = 'a'; i < 'z'; i++)
{
    string name = "list" + i;
    name.Add(.....);
}

The "name" in this example should be the list where i want to add an item.

A: You want a Dictionary<char, ObservableCollection<SampleObject>>, which will have a different collection for each char.

A: If your lists are declared at class level then reflection can be used to get a reference to them (I still think a Dictionary is a better choice).
Simple example:
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private List<string> lista = new List<string>();

    private void button1_Click(object sender, EventArgs e)
    {
        Console.WriteLine("Before:");
        foreach (string value in lista)
        {
            Console.WriteLine(value);
        }

        for (char i = 'a'; i < 'z'; i++)
        {
            string name = "list" + i;
            System.Reflection.FieldInfo fi = this.GetType().GetField(name, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public);
            if (fi != null && fi.FieldType.Equals(typeof(List<string>)))
            {
                List<string> referenceToList = (List<string>)fi.GetValue(this);
                referenceToList.Add("Hello!");
            }
        }

        Console.WriteLine("After:");
        foreach (string value in lista)
        {
            Console.WriteLine(value);
        }
    }
}


text:
Q: Double overflow I have some problems with double type.
At MSDN i read about double max value following:

The result of an operation that exceeds Double.MaxValue is Double.PositiveInfinity.

I wrote some tests:
Console.WriteLine(double.MaxValue + 100000 - double.MaxValue);
Console.WriteLine(double.MaxValue);
Console.WriteLine(double.MaxValue + 100000);
Console.WriteLine(double.IsPositiveInfinity(double.MaxValue + 100000));

And saw this result:
0
1,79769313486232E+308
1,79769313486232E+308
False

I don't understand, double.MaxValue + 100000 isn't Positive infinity, but equal to double MaxValue. I think it should be PositiveInfinity, according to msdn documentation.
I tested it in VS2012, .NET 4.5

A: This is rounding / precision; from the perspective of a number that is 309 digits long (before the decimal place), 100000 is essentially zero. You might as well add 0.
If you try double.MaxValue * 2 - i.e. something that will actually be noticeable to it, then it will show as positive infinity.

A: Double only has about 15 decimal digits of precision thus when you add Double.MaxValue to 100000D there is no overflow because the 1 in 100000D has to be added after the 300th digit of Double.MaxValue and this is the same as adding 0.
If you perform the following calculation
Double.MaxValue + Double.MaxValue/1e16

you do get positive infinity.


text:
Q: Convert lines to columns in SQL I would like to convert, by using a SQL-statement, the following table:
**Itemcode**   | **Number** | **Description**
001            |  1         | blue
001            |  2         | M
002            |  1         | yellow
002            |  3         | Nike
003            |  1         | blue
003            |  2         | L
003            |  3         | Adidas

into
Itemcode       | 1      | 2         | 3
001            | blue   | M         |
002            | yellow |           | Nike
003            | blue   | L         | Adidas

I tried using Pivot in my statement, but it didn't work. Who could help me?

A: You can use aggregation :
select code,
       max(case when number = 1 then Description end) as one,
       max(case when number = 2 then Description end) as two,
       max(case when number = 3 then Description end) as three
from table t
group by code;


text:
Q: Composer autoload.php AWS 500 error Hey everyone I am trying to deploy my website to AWS and I am getting an error (500 (Internal Server Error)) when it reaches the require line in my php, which is supposed to include Composer's vendor file, autoload.php. Weird thing is, it works fine on my local instance (and my group member's local instances) . Any ideas? Could aws be setting some sort of permissions? I tried including other php files that are outside of the vendor folder and they seem to work fine.
I test this by echoing before and after each line to figure out how far it compiles. It gets to "above require"
Thanks!
UPDATE: After the suggestion below, I am getting an error to read now, it is just below.

Warning:
  require(/var/app/current/vendor/composer/../facebook/graph-sdk/src/Facebook/polyfills.php):
  failed to open stream: No such file or directory in
  /var/app/current/vendor/composer/autoload_real.php on line 66 Fatal
  error: require(): Failed opening required
/var/app/current/vendor/composer/../facebook/graph-sdk/src/Facebook/polyfills.php'
  (include_path='.:/usr/share/pear7:/usr/share/php7') in
  /var/app/current/vendor/composer/autoload_real.php on line 66

<?php
    echo "above session";
    session_start();
    echo "above require ";
    include '../vendor/autoload.php';
    //Testing this passed ->> include 'db.inc.php';
    //require_once __DIR__ . '/vendor/autoload.php';
    echo "under require\n";
    $fb = new Facebook\Facebook([
        'app_id' => '',
        'app_secret' => '',
        'default_graph_version' => 'v2.5',
    ]);
    echo "under facebook class dec\n";

A: I wasn't able to figure out what exactly was causing this issue, but to get the SDK to work I just did what Facebook recommended developers not to do, which is install it manually.
For anyone with this problem in the future, make sure to update all your requires or includes(threw some more errors ). Also remove your old composer dependency using built in composer functions!


text:
Q: Remove "Category:" from Post meta I need to remove the word "Category:" from in front of the actual category name/link. I have checked every answer here and on other sites, and none of the answers work on my site...I have tried many different snippets in my functions.php file and none have worked.
Site URL is
https://robinreport.staging.wpengine.com/
Theme is Bizbudding Mai Lifestyle
Thanks for any help you can provide me.


text:
Q: Segfault upon instantiation of object with vector > member In Multidimensional arrays as class member with arbitrary bounds I was advised I should use a vector of vectors of ints to represent a dynamic 2D array in my array-backed graph object. However, I'm getting segmentation faults whenever I try to run my code. GDB points to the line where a variable is defined as the arraygraph type; I presume that means I did something wrong specifying the type of edges. Here is the class definition:
class arraygraph {
private:

public:
    void open(char *filename);
    bool exists(int nodeid);
    int node_count(void);
    int weight(int nodea, int nodeb);
    void print();
private:
    int count;
    vector <vector <int> > edges; //A vector of vectors! [Inception Noise]
};

All the methods of this object are defined (funny how you can compile with prototypes that haven't been filled out...). The code compiles without errors or warnings. Why's it segfaulting?
EDIT:
Here's some disassembler output:
163       int main(int argc, char *argv[]) {
          main(int, char**):
00401c86:   lea 0x4(%esp),%ecx
00401c8a:   and $0xfffffff0,%esp
00401c8d:   pushl -0x4(%ecx)
00401c90:   push %ebp
00401c91:   mov %esp,%ebp
00401c93:   push %ebx
00401c94:   push %ecx
00401c95:   sub $0x20,%esp
00401c98:   mov %ecx,%ebx
00401c9a:   call 0x402350 <__main>
164         arraygraph thegraph;
00401c9f:   lea -0x18(%ebp),%eax  (this is where the problem occured according to GDB)
00401ca2:   mov %eax,%ecx
00401ca4:   call 0x403e90 <arraygraph::arraygraph()>

So apparently the segfault happened before the arraygraph was constructed? I don't know what to make of this.
EDIT:
The entirety of main() is as such:
int main(int argc, char *argv[]) {
    arraygraph thegraph;
    thegraph.open(argv[1]);
    return 0; //Added this after I noticed I'd omitted it - didn't fix anything
}

And here's arraygraph::open():
//Only call .open() once. A second call will leave the old graph's dessicated corpse around the edges of the new one.
void arraygraph::open(char *filename){
    int count;
    int x, y;
    tomgraph loader;

    loader.open(filename);

    count=loader.node_count();

    //delete edges;
    //edges = new vector <vector <int> >;

    for (x=1; x <= count; x++) {
        for (y=1; y <= count; y++) {
            int weight;
            if (loader.is_connected(x,y,&weight) || loader.is_connected(y,x,&weight)) {
                edges[x-1][y-1]=weight;
            } else {
                edges[x-1][y-1]=0; //0 represents "no edge"
            }
        }
    }
}

But according to the disassembler this never gets called anyway.
EDIT:
Full code here. Umm... I think it's saying it worked? Lemme try a different machine...
EDIT:
Nope. Similar segfault after compiling on a completely separate Linux machine.
EDIT:
Just to confirm, I commented out the call to thegraph.open(). Didn't fix it.

A: You never resize edges or push_back to it. So its size is 0 and doing edges[x-1][y-1] you go out of bounds. You probably have to do something like this before the loop in arraygraph::open:
edges.resize(count, std::vector<int>(count));


text:
Q: How to convert ULONG64 to PCSTR? I am quite new to C++, because I normally use C#.
Here is the code I am currently using (although I have tried plenty of other things):
template <class T>
inline PCSTR to_string (const T& t)
{
std::stringstream ss;
ss << t;
return ss.str().c_str();
}

ULONG bugCheckCode = 0;
ULONG64 bugCheckArgs[4] = {0};
Control->ReadBugCheckData(&bugCheckCode, &bugCheckArgs[0], &bugCheckArgs[1], &bugCheckArgs[2], &bugCheckArgs[3]);

CHAR arg2[sizeof(bugCheckArgs[1])];
ZeroMemory(arg2, sizeof(bugCheckArgs[1]));

memcpy(arg2, &bugCheckArgs[1], sizeof(bugCheckArgs[1]));

Control->CallExtension(NULL, "function", arg2);

Basically, ReadBugCheckData returns a PULONG64, which I give an address to a ULONG64. I am pretty sure that this bit is alright, but since I am new to all this memory stuff, I shall post it just in case the mistake lies here.
So I now have a ULONG64 (typedef unsigned long long ULONG64) which I need to convert to a PCSTR (typedef CONST CHAR *PCSTR), which, if I understand correctly, is a char array??? So I tried the to_string function posted at the top of the code snippet, and I tried memcpy, but I can't get it to work.
But all I can get is nothingness or junk data. I am finding this particularly difficult to debug because this is an extension, and I can't step through the code properly.
Any ideas on how to do this conversion?
Thanks a lot.

A: This code:
template <class T>
inline PCSTR to_string (const T& t)
{
    std::stringstream ss;
    ss << t;
    return ss.str().c_str();
}

returns a pointer to memory that is owned by a temporary returned by str() and thus getting destroyed as soon the the functions exits. Instead use:
template <class T>
inline std::string to_string (const T& t)
{
    std::stringstream ss;
    ss << t;
    return ss.str();
}

And at the call site retrieve the const char* as:
CallSomething(to_string(x).c_str());

A: have a look at these functions:
Conversion functions Visual C++ Runtime
for secure version:
Conversions functions CRT_SECURE
scroll down to bottom of box, look for...
radix means numerical base (10 for common, 2 for binary, 16 for hexadeciamlic system)
char * _ui64toa(
   unsigned _int64 value,
   char (&str)[size],
   int radix
); // C++ only

errno_t _i64toa_s(
   __int64 value,
   char *buffer,
   size_t sizeInCharacters,
   int radix


text:
Q: A majority of us are hiding THEIR or OUR feelings? I'm not sure which is the correct option in sentences like these ones:

*

*Each of us has to learn how to express their/ our feelings.

*majority of us are hiding their/ our feelings.
"Their" sounds slightly better to me, but still I am confused.
Any help will be greatly appreciated!

A: In normal usage, the determiner (e.g. your, our, their) must match the object pronoun (you, us, them):

Some of us express our feelings.
Half of them hate their teachers.
Most of you have eaten your lunch.


text:
Q: React-Native: How to make Talkback recognize Touchable components as interactive? I'm trying to make my React Native app accessible.
In native, when I have a Button, TalkBack says my content description, then the component type and then a hint like:

Double tap to activate.

How can I make Talkback read my React-Native button and place a hint like that?

A: There is a detailed page on react-native docs about Accessibility.

A:   <TouchableOpacity
    accessible={true}
    accessibilityRole={"button"}
    accessibilityLabel={"sent an e-mail"}
  >

You could use accessible={true} to make it as a group. So the a11y frame would indicate this touchableOpacity.
Also providing role as "button", to make sure the talkback would say "double tap to activate".


text:
Q: Is there a way to play .flv video files in android app? Is it possible out of the box or via a library?

A: you can play FLV using flash plugin inside a WebView. see here: http://www.synesthesia.it/playing-flash-flv-videos-in-android-applications
Often when you create an app displaying web contents in a mobile device you have to deal with FLV videos, still widely used in the web (until HTML5 will rule the world). The best thing to do is to convert them with some converter (like ffmpeg), but if you don'have access to original videos or for some other reasons you can't do the conversion in some other suitable format, here you can find a quick tutorial on how to embed and play Flash FLV Videos in an Android application.
This is done by using a WebView, a SWF player capable of playing FLVs, and of course the Flash plugin for Android installed.
First, create a layout xml with a WebView, like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android">

<WebView android:layout_width="fill_parent" android:id="@+id/webview" android:layout_height="fill_parent"></WebView>    </LinearLayout>

then, create the Activity class, here is an extract:
package it.synesthesia.flvplayer;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;

public class ViewVideo extends Activity {

    WebView webView;
    String htmlPre = "<!DOCTYPE html><meta charset=\"utf-8\">";
    String htmlCode =
            " <embed style='width:100%; height:100%' src='http://www.platipus.nl/flvplayer/download/1.0/FLVPlayer.swf?fullscreen=true&video=@VIDEO@' " +
            "  autoplay='true' " +
            "  quality='high' bgcolor='#000000' " +
            "  name='VideoPlayer' align='middle'" + // width='640' height='480'
            "  allowScriptAccess='*' allowFullScreen='true'" +
            "  type='application/x-shockwave-flash' " +
            "  pluginspage='http://www.macromedia.com/go/getflashplayer' />" +
            "";
    String htmlPost = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_video);

        webView = (WebView)findViewById(R.id.webview);

        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setPluginsEnabled(true);
        webView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY); //thanks Patrick!

        htmlCode = htmlCode.replaceAll("@VIDEO@", video_link);
        webView.loadDataWithBaseURL("fake://fake/fake", htmlPre+htmlCode+htmlPost, "text/html", "UTF-8", null);
    }

    @Override
    protected void onPause(){
        super.onPause();

        callHiddenWebViewMethod("onPause");

        webView.pauseTimers();
        if(isFinishing()){
            webView.loadUrl("about:blank");
            setContentView(new FrameLayout(this));
        }
    }

    @Override
    protected void onResume(){
        super.onResume();

        callHiddenWebViewMethod("onResume");

        webView.resumeTimers();
    }

    private void callHiddenWebViewMethod(String name){
        // credits: http://stackoverflow.com/questions/3431351/how-do-i-pause-flash-content-in-an-android-webview-when-my-activity-isnt-visible
        if( webView != null ){
            try {
                Method method = WebView.class.getMethod(name);
                method.invoke(webView);
            } catch (NoSuchMethodException e) {
                Lo.g("No such method: " + name + e);
            } catch (IllegalAccessException e) {
                Lo.g("Illegal Access: " + name + e);
            } catch (InvocationTargetException e) {
                Lo.g("Invocation Target Exception: " + name + e);
            }
        }
    }

}

Some explanation:

*

*as said, you need a FLV player. I used the great & free FLVPlayer   http://www.platipus.nl/flvplayer/download/1.0/

*FLV player must reside on a website on the net. I tried putting the .swf in the /assets folder of the app and calling it from there, but it failed to load the FLV video. if someone can fix this please let me know!

*htmlCode contains the code to show the video as "fullscreen" (filling to full size of the webview).

*callHiddenWebViewMethod is very important, otherwise the video will    continue playing when the activity is not visible any more (and audio    as well). Credis to this goes to the sliseshare poster linked in the    comment. Thanks! WARNING: this is mostly an hack! beware, things could not work as expected, or can stop working in the future. Btw, it worked very well for me.

A: No, it's not possible. The OpenCORE media library that's providing the media playback on Android doesn't support .flv files.
You can find a list of supported media formats here. These formats are supported on generic Android. On the same page you will find some additional formats that the T-Mobile G1 supports.
Of course, support for additional media formats might be possible on specific devices. But this can vary from device to device.

A: Try vitamio. It is a library similar to mediaplayer which can be imported into your project very easily. The only thing is that it supports flv video files too.


text:
Q: Javascript: How to secure your code if you render your page with JS and need to implement a security feature, it comes down to something such as this:
var userID = getUserID();
if (userID == 1) {
   html += renderDeleteButton();
}

But won't the user be able to just open the debugger and change the value of userID ?

A: Yes they will. With JS, the user can do whatever the heck they want. This is why security stuff should go in your server-side code (PHP / ASP / etc.), as users cannot modify it.

A: Do not trust anything from a client side script like JS. All client side scripts can be manipulated by the user. Any secure type of code should reside in a server side script.

A: Validation/security checks in javascript are always only done to save the user the time of a trip to the server and back. They are strictly for performance only.
If you want actual security, it must be implemented on the server.


text:
Q: What's the most popular compression algorithm inside voip projects? What's the most popular compression algorithm inside voip projects, or what's the most popular voice compression algorithm for internet transfer?

A: The use of the open source speex codec seems very common.