text:
Q: Laravel Form Input not required I'm trying to make a simple contact form for my users and IF they have an order id to put it in a field. Or else i put it by default as "0" (lets say that they have a question)
So this is my code
Controller
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\ContactUS;

class ContactUSController extends Controller
{
    public function contactUS()
    {
        return view('contactUS');
    }

    public function contactUSPost(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required|email',
            'message' => 'required'
        ]);

        ContactUS::create($request->all());

        return back()->with('success', 'Thanks for contacting us! We will get back shortly.');
    }
}

View

Contact US Form

        @if(Session::has('success'))

                {{ Session::get('success') }}

        @endif

        {!! Form::open(['route'=>'contactus.store']) !!}

has('name') ? 'has-error' : '' }}">
            {!! Form::label('Name:') !!}
            {!! Form::text('name', old('name'), ['class'=>'form-control', 'placeholder'=>'Enter Name']) !!}
            {{ $errors->first('name') }}

has('email') ? 'has-error' : '' }}">
            {!! Form::label('Email:') !!}
            {!! Form::text('email', old('email'), ['class'=>'form-control', 'placeholder'=>'Enter Email']) !!}
            {{ $errors->first('email') }}

            {!! Form::label('Order ID:') !!}
            {!! Form::number('orderId', old('orderId'), ['class'=>'form-control no-spinners', 'placeholder'=>'Do you have and order id?']) !!}

has('message') ? 'has-error' : '' }}">
            {!! Form::label('Message:') !!}
            {!! Form::textarea('message', old('message'), ['class'=>'form-control', 'placeholder'=>'Enter Message']) !!}
            {{ $errors->first('message') }}

            <button class="btn btn-success">Contact US!</button>

        {!! Form::close() !!}

Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ContactUS extends Model
{
    public $table = 'contact_us';

    public $fillable = ['name','email','message'];
}

Migration

class CreateContactUsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('contact_us', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email');
            $table->text('message');
            $table->integer('orderId')->default('0');
            $table->boolean('solved')->default(false);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('contact_us');
    }
}

So the issue is that when I don't put any value on field OrderId it takes the default value 0
But if i put any number value 1 or 2 etc it still saves 0 at my database.
Any idea why is this reaction made?

A: Allow mass assignment for orderId field in your model,
 public $fillable = ['name','email','message','orderId'];

A: As Deepak stated in the comments, you can check the value for null in your controller:
$data=$request->all();
$data['orderId'] = $data['orderId'] == '' ? 'No Order ID Entered' : $data['orderId'];

Alternatively, pass something falsy
$data=$request->all();
$data['orderId'] = $data['orderId'] == '' ? 0 : $data['orderId'];


text:
Q: Adjust Text Field Size Based on current language iOS Is it possible to dynamically set the size of a text field, button or other visual atributes based on the current user selected language?
Code sample would be great! Thanks for the help

A: You can easily adjust the size of a text field, for example depending on the text it contains.
NSString *localizedText;
textField.text = localizedText;
[textField sizeToFit];
textField.text = @"";

You can generate localizedText dynamically with methods such as stringFromDate etc. or keep an NSDictionary with appropriate strings and the locales as keys.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Convert month(name) year to date in dataframe My date column has values like
Date
1971 FEB
1971 MAR
.
.

How to convert this into YYYY-MM-DD format?
This is what I tried
df['Date'] = pd.to_datetime(df['Date'] , format='%y%b')

but I get an error message
ValueError: time data '1971 FEB' does not match format '%y%b' (match)

A: Try with format '%Y %b' instead of '%y%b':
df['Date']=pd.to_datetime(df['Date'],format='%Y %b',errors='coerce')

For more info regarding format codes visit here


text:
Q: Configuring Default Params with .Open with Microsoft Word COM Object in PowerShell I'm converting a "hybrid" batch/vbs script to PowerShell and converting the "batch" portion was delightfully straightforward, but I'm struggling a bit with the VBS Conversion.
I can open a word document, but when I try to pass extra params I continually get errors. I want to define each optional param, and ideally, if not passed as a param use default. I read about ISMISSING online and something about System_Call but I couldn't get it to work so I defined my own "default" values, but they seem all over the place.
Sometimes it was $true other times it wants True and sometimes I can use $wdOpenFormatAuto other times it wants wdOpenFormatAuto and other times it requires the enumeration. I feel like I may be just "getting it to work" and want to understand better before I start working more on this project. This is my "open" statement for MS Word as it stands. Can anybody help improve it, help me set If not Defined, use Default for most everything.
I found this thread, which mentioned [Type]::Missing}, and that worked for the first few params, but when I get to $PasswordDocument it throws an error.
Open a word document and specify encoding with PowerShell
 #Start Word
 $ObjWord = New-Object -comobject Word.Application
 $ObjWord.Visible  = $OPENUI
 $ObjWord.Documents.Open($FILEPATH)

#.Open
 $FILENAME = $FILEPATH
 IF (!$ConfirmConversions){$ConfirmConversions = $FALSE}
 $ReadOnly = $TRUE
 IF (!$AddToRecentFiles){$AddToRecentFiles = $FALSE}
 IF (!$PasswordDocument){$PasswordDocument = 'str'}
 IF (!$PasswordTemplate){$PasswordTemplate = 'str'}
 $Revert = $FALSE
 IF (!$WritePasswordDocument){$WritePasswordDocument = 'str'}
 IF (!$WritePasswordTemplate){$WritePasswordTemplate = 'str'}
 IF (!$Format){$Format = 'wdOpenFormatAuto'}
 IF (!$Encoding){$Encoding = 'str'}
 IF ($OPENUI -eq "FALSE"){$Visible = $FALSE}ELSE{$Visible = $TRUE}
 IF (!$OpenConflictDocument){$OpenConflictDocument = $TRUE}
 IF (!$OpenAndRepair){$OpenAndRepair = $TRUE}
 IF (!$DocumentDirection){$DocumentDirection = $wdLeftToRight}
 IF (!$NoEncodingDialog){[string]$NoEncodingDialog = 'TRUE'}
 $ObjDoc=$ObjWord.documents.open($FILENAME,$ConfirmConversions,$ReadOnly,$AddToRecentFiles,$PasswordDocument,$PasswordTemplate,$Revert,$WritePasswordDocument,$WritePasswordTemplate,$Format,$Encoding,$Visible,$OpenConflictDocument,$OpenAndRepair,$DocumentDirection,$NoEncodingDialog)

Update: I was able to set "Most" to default, but it's such a game of just "trial and error" that I don't like it, I wish I understood what was going on, how to know if a value can accept missing.
Here is where I'm at now, with errors listed by values that won't take $missing.
 #.Open
 $missing = [System.Type]::Missing
 $str = ''
 $FILENAME = $FILEPATH
 IF (!$ConfirmConversions){$ConfirmConversions = $missing}
 IF (!$ReadOnly){$ReadOnly = $TRUE}
 IF (!$AddToRecentFiles){$AddToRecentFiles = $missing}
 IF (!$PasswordDocument){$PasswordDocument = $str} #Exception setting "Open": Cannot convert the "TRUE" value of type "string" to type "Object". # Doesn't Accept $Missing
 IF (!$PasswordTemplate){$PasswordTemplate = $str} #Exception setting "Open": Cannot convert the "TRUE" value of type "string" to type "Object". # Doesn't Accept $Missing
 IF (!$Revert){$Revert = $False} #Parameter value was out of acceptable range # Doesn't Accept $Missing
 IF (!$WritePasswordDocument){$WritePasswordDocument =  $str} #Exception setting "Open": Cannot convert the "TRUE" value of type "string" to type "Object". # Doesn't Accept $Missing
 IF (!$WritePasswordTemplate){$WritePasswordTemplate =  $str} #Exception setting "Open": Cannot convert the "TRUE" value of type "string" to type "Object". # Doesn't Accept $Missing
 IF (!$Format){$Format = 'wdOpenFormatAuto'} #Command failed # Doesn't Accept $Missing
 IF (!$Encoding){$Encoding = $missing}
 IF ($OPENUI -eq "FALSE"){$Visible = $FALSE}ELSE{$Visible = $TRUE}
 IF (!$OpenConflictDocument){$OpenConflictDocument = $missing}
 IF (!$OpenAndRepair){$OpenAndRepair = $missing}
 IF (!$DocumentDirection){$DocumentDirection = $missing}
 IF (!$NoEncodingDialog){[string]$NoEncodingDialog = 'TRUE'}  #Object reference not set to an instance of an object. # Doesn't Accept $Missing
 $ObjDoc=$ObjWord.documents.open($FILENAME,$ConfirmConversions,$ReadOnly,$AddToRecentFiles,$PasswordDocument,$PasswordTemplate,$Revert,$WritePasswordDocument,$WritePasswordTemplate,$Format,$Encoding,$Visible,$OpenConflictDocument,$OpenAndRepair,$DocumentDirection,$NoEncodingDialog)

Interestingly, I can put PasswordDocument/PasswordTemplate & WritePasswordDocument/WritePasswordTemplate as missing if I OMIT NoEncodingDialog, but if I include that param, I have to set the above to a random string???
I do understand that some of these fundamentally are related, so something can't be null if another is set etc etc, but there still seems like I should be able to do this better.


text:
Q: Prevent Changes from being merged to develop I have a common question regarding Git-Flow.
For normal the finishing of a release says, that all changes from the release should be merged to develop and master.
What If there are changes that are not allowed to be merged to develop? E.g. one-time hotfix scripts that have been introduced last minute within the release-branch?
Is release-branching the wrong place for such files? Should they be extracted to a specific hotfix-branch which then will NOT be finished using git-flow?
I know a lot of you will say "don't introduce throw away code" but it is necessary sometimes (to prevent e.g. a too complex code-logic)


text:
Q: Read line-delimited data in VB6 So I have a number of text files that I'm trying to read with Visual Basic. They all have the same formatting:
[number of items in the file]
item 1
item 2
item 3
...etc.

What I'm trying to do is declare an array of the size of the integer in the first line, and then read each line into corresponding parts of the array (so item 1 would be array[0], item 2 would be array[1], etc. However, I'm not sure where to start on this. Any help would be appreciated.

A: Pretty basic stuff (no pun intended):
Dim F As Integer
Dim Count As Integer
Dim Items() As String
Dim I As Integer

F = FreeFile(0)
Open "data.txt" For Input As #F
Input #F, Count
ReDim Items(Count - 1)
For I = 0 To Count - 1
    Line Input #F, Items(I)
Next
Close #F

A: try this for VB6
Dim file_id As Integer
Dim strline as string
Dim array_item() as string

'Open file
file_id = FreeFile
Open "C:\list.txt" For Input AS #file_id

Dim irow As Integer
irow = 0

'Loop through the file
Do Until EOF(file_id)

    'read a line from a file
    Line Input #file_id, strline

    'Resize the array according to the line read from file
    Redim Preserve array_item(irow)

    'put the line into the array
    array_item(irow) = strline

    'move to the next row
    irow = irow + 1
Loop

Close #file_id

A: The VB function you're looking for is "split":
http://www.vb-helper.com/howto_csv_to_array.html

A: Try this:
Dim FullText As String, l() As String
'''Open file for reading using Scripting Runtime. But you can use your methods
Dim FSO As Object, TS As Object
Set FSO = createbject("Scripting.FileSystemObject")
Set TS = createbject("Scripting.TextStream")
Set TS = FSO.OpenTextFile(FilePath)
TS.ReadLine 'Skip your first line. It isn't needed now.
'''Reading the contents to FullText and splitting to the array.
FullText = TS.ReadAll
l = Split(FullText, vbNewLine) '''the main trick

Splitting automatically resizes l() and stores all data.
Now the l() array has everything you want.


text:
Q: Updating state array using Spread operator in React? I am trying to update a state array after accepting the input from Form. State already has events object in it with data and I want to accept data from the form and append to the existing list. I'm able to do console log of the newEvents (data from form in another component), but using the spread operator unable to update the existing  state by appending it.

//getting newEvent object from form in another component. // events is
an array in state which has data  //priniting the existing array
without appending newEvent //printing data from form (newEvent)
properly

testmethodfornow = (newEvent) => (
    { ...this.state.events, events: [newEvent, ...this.state.events] },
    console.log(this.state.events),
    console.log(newEvent)
)

I want newEvent to be added to event :( Can anyone please help ?
NewEvent structure:
const newEvent = { IdText: uuid(), EventName, Venue, Time };
events array structure in state:
state = {
    flag: false,
    title: "State Check",
    events: [
        {
            IdText: '1',
            EventName: 'New Year Party 2022',
            Venue: 'The Social',
            Time: '8:00 PM- 1:00AM',
            Date: ''
        },
        {
            IdText: '2',
            EventName: 'StandUp Comedy',
            Venue: 'ShilpaRamam',
            Time: '8:00 PM- 1:00AM',
            Date: ''

        }]
}

A: If you are using class components, use setState to update the state. In this case events is a field of the state. So you can spread rest of the state instead of state.events.
  addNewEvent(){
    setState({...this.state, events: [newEvent, ...this.state.events]})
  }


text:
Q: How can I get the XUL as a string from a Mozilla add-on at run-time using JavaScript? I'm trying to get a window's XUL text as a String in Javascript. I need it to be done at runtime because the window adds/removes UI elements dynamically.
I have tried the following:
document.toXML()

document.xml

document.documentElement.toXML()

Among other things. Nothing works! Can anyone help?

A: You use XMLSerializer:
new XMLSerializer().serializeToString(document);

A: I don't think there is a function or field to get xul text, but you can work around by reading the content from xul url
function getContentFromURL(url) {
  var Cc = Components.classes;
  var Ci = Components.interfaces;
  var ioService = Cc['@mozilla.org/network/io-service;1'].getService(Ci.nsIIOService);
  var scriptableStream = Cc['@mozilla.org/scriptableinputstream;1'].getService(Ci.nsIScriptableInputStream);

  var channel = ioService.newChannel(url, null, null);
  var input = channel.open();
  scriptableStream.init(input);
  return scriptableStream.read(input.available());
}

so you can call getContentFromURL(document.location) to get the XUL content


text:
Q: How is the Borel-Cantelli lemma used in this proof on $\psi$-approximable numbers? I'm trying to understand a paper called "Almost no points on a Cantor set are very well approximable". In the proof the author uses the Borel-Cantelli Lemma (in the eighth line at the beginning of the proof on the second page). There are more than one version of it, but I think that the following is used:

It seems the lemma is used when we consider $(A_q:q\in\mathbb{Z}_+)$ given by $A_q=B(p/q,\psi(q)/q)$, however $p$ is not fixed. So could someone explain how is the Borel-Cantelli lemma used in this proof?
Thanks.

A: Just reading (5) one sees that the authors consider the family $(B(p/q,\psi(q)/q))_{p,q}$ where $(p,q)$ runs over every pair such that $p\in\mathbb Z$, $q\in\mathbb Z_+$, $(p,q)=1$, $p/q\in I$. Since this collection of pairs is (at most) countable, one can order it as $\{B(p/q,\psi(q)/q)\mid p,q\}=\{A_n\mid n\geqslant1\}$ and apply simple Borel-Cantelli lemma to the sequence $(A_n)_{n\geqslant1}$.


text:
Q: javascript DOMContentLoaded event listeners I have several scripts in html document and all of them have one DOMContentLoaded event listener. Will javaScript keep a relative order of listeners executions or execute them synchron?

A: Yes, if you're using addEventListener. As of DOM3 (several years ago), the order in which addEventListener handlers are called on the same source was defined: It's the order in which they were attached. (And of course, they're executed in series, not parallel, because the main UI script in browsers runs on a single thread. JavaScript isn't single-threaded, not even on browsers, but there's only a single main UI thread; if you want to use other threads, you have to do something on purpose [e.g., web workers and such].)


text:
Q: Does meta_value (array) work with 'orderby'? My goal here is to query posts by a meta_key, with the values falling in between 1-100. When pulled, it is suppose to be ordered by ascending starting from 1 to 100.
$post = array(
    'posts_per_page' => 10,
    'post_type' => 'post',
    'tax_query' => array(
        'taxonomy' => 'category',
        'field' => 'slug',
        'terms' => 'category-1'
    ),
    'meta_query' => array(
        'meta_key' => 'custom-key',
        'meta_value' => array(1,100),
        'meta_compare' => 'BETWEEN'
    ),
    'order' => 'ASC',
    'orderby' => 'meta_value_num',
);

When looking at the page, it works of getting posts w/ meta-values '1-100', but it is not ordering correctly. It looks random (i.e. 1, 21, 5, 20, 6, 7, 8 , 3, 9, 19) saying in this order even when the page is constantly refreshed.
Any help will be appreciated.
Thanks!

A: Researching more, I got it to work with the following code
$post = array(
    'posts_per_page' => 10,
    'post_type' => 'post',
    'tax_query' => array(
        'taxonomy' => 'category',
        'field' => 'slug',
        'terms' => 'category-1'
    ),
    'meta_query' => array(
        array(
            'key' => 'custom-key',
            'value' => array(1,100),
            'compare' => 'BETWEEN',
            'type' => 'NUMERIC'
        )
    ),
    'meta_key' => 'custom-key',
    'orderby' => 'meta_value',
    'order' => 'ASC'
);

Reference: http://www.wphub.com/use-meta_query-query-posts-postmeta/


text:
Q: How do I get text that someone has entered into a text field and input this into my SQLite database? So, I'm creating the log in activity for my new app. If a user is signing up, I will need to store the info that they enter into the sign up form to be stored inside of my SQLite database. How do I go about doing this? This is what I have so far:
public class DatabaseHelper extends SQLiteOpenHelper {
    private static final String DB_NAME = "USERS";
    private static final int DB_VERSION = 1;

    DatabaseHelper(Context context){
        super(context,DB_NAME,null,DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE DATABASE USERS("
                + "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
                + "USERNAME TEXT, "
                + "EMAIL_ADDRESS TEXT, "
                + "PASSWORD TEXT); ");
        insertUser(db, "");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    private static void insertUser (SQLiteDatabase db, String username, String email, String password){
        ContentValues userValues = new ContentValues();
        userValues.put("USERNAME", username);
        userValues.put("EMAIL_ADDRESS", email);
        userValues.put("PASSWORD", password);
        db.insert("USERS", null, userValues);
    };
}

A: You have make a query to fetch the records from SQLite database.
Here is a simple example to fetch all users:
public List<User> getAllUsers() {
    SQLiteDatabase db = this.getReadableDatabase();

    List<User> users = new ArrayList<>();

    Cursor cursor = db.query("USERS", null, null, null, null, null, null);
    if (cursor.moveToFirst()) {
        do {
            User user = new User();
            user.setUsername(cursor.getString(1));
            user.setEmail(cursor.getString(2));
            users.add(user);
        } while (cursor.moveToNext());
    }

    return users;
}

You can read more about it in the following link:
http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/


text:
Q: Nested Route link_to helper working in one place but not another I have a nested routes problem that I can not figure out.  I have an app that has nested routes like so:
resources :events do
  resources :sessions
end

I am trying to use the following link_to in my code:
<%= link_to "New Session", new_event_session_path %>

When I run rake routes, it will show the proper URL with a GET method existing:
new_event_session GET    /events/:event_id/sessions/new(.:format)      {:action=>"new", :controller=>"sessions"}

When I try to use the link_to in one place it works, when I try to use it in another place it does not, it instead will give me this error:
No route matches {:controller=>"sessions", :action=>"new"}

The only difference between the two files is the location of the files in the app (one is under views/events the other is under views/sessions and the url being called:
/events/1 --vs-- /events/1/sessions
I am still a noob with rails, so this is probably a stupid question, but I have hit a bit of a wall.  Any help is appreciated.

A: You just need to pass event object to path helper:
new_event_session_path(@event)


text:
Q: Underline text inside Editbox As I enter text in editText it should automatically underline the text I entered. I need like as I continue to enter text in editText it draw like in background.
Can someone help me.

A: Use view with 1 dp of height and custom width with green background , inside framelayout over your editText, and handle custom_width same as you are handling image_width.

A: For underline effect in EditText you need to add this
//initialize edittext before
editText.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);


text:
Q: Apply Touches to Custom Control I made a Custom Circle Control, Were i am Sending values by Slider from my RootView Controller. Can You help me out, how to Apply touches to Circle Control were i can change the values, like making custom slider around my Custom Circle.
#import "RKCustomCircle.h"

@implementation RKCustomCircle
@synthesize sliderPerccentageValue;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        xPos = 320/2;
        yPos = 250;
        radius = 80;
        rotationAngle = 0;
    }
    return self;
}

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    [self drawCircleChart: context];

}

- (void) drawCircleChart:(CGContextRef) context
{
    CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
    CGContextFillRect(context, CGRectMake(0, 0, 320, 480));
    float a = rotationAngle;
    [self drawCirclewithStartingAngle:a withContext:context];
}

- (void) drawCirclewithStartingAngle:(float)startAngle withContext:(CGContextRef) context
{
    float endAngle = startAngle + (sliderPerccentageValue/ 100) * (M_PI*2);
    float adjY = yPos;
    float rad = radius;
    CGContextSetFillColorWithColor(context, [UIColor greenColor].CGColor);
    CGContextSetStrokeColorWithColor(context,[UIColor blackColor].CGColor);
    CGContextSetLineWidth(context, 1.0);
    CGContextBeginPath(context);
    CGContextMoveToPoint(context, xPos, adjY);
    CGContextAddArc(context, xPos, adjY, rad, startAngle, endAngle, 0);
    CGContextClosePath(context);
    CGContextDrawPath(context, kCGPathFillStroke);
}

RootView is,
@implementation RKViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    circleView = [[RKCustomCircle alloc] initWithFrame:CGRectMake(0, 100, 320, 360)];

    [circleView addTarget:self action:@selector(newValue:) forControlEvents:UIControlEventValueChanged];

    [self.view addSubview:circleView];

}

- (IBAction)sliderValueChangedInPercentage:(UISlider *)sender {

    circleView.sliderPerccentageValue =sender.value;

    [circleView setNeedsDisplay];

}

A: Use UITapGestureRecognizer.
 UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(oneTap:)];
    [singleTap setNumberOfTapsRequired:1];
    [singleTap setNumberOfTouchesRequired:1];
    [circleView addGestureRecognizer:singleTap];

Add this method
- (void)oneTap:(UIGestureRecognizer *)gesture
{
    NSLog(@"Touch occur");

}

A: All your things are correct, but only the following part is incorrect.
- (IBAction)sliderValueChangedInPercentage:(UISlider *)sender {

    circleView.sliderPerccentageValue =sender.value;

    [circleView setNeedsDisplay];

}

The above code doesn't supply any value because you have attached to your control that implements UIControl, not UISlider. You don't have to either, your UIControl will work..
Instead you can have touch events inside your control itself no need to add any action from outside, and you have to detect circular touch and keep track of values, see this app here it will help you to get values when touched circular.
Hope it will help you. All the best.

A: You need to override the pointInside:withEvent: method of the circle view. Refer to this for more information.


text:
Q: Set "type the same" in csv by python I am a beginner at python. I have file structure CSV

year
make
model
text

1997
Acura
cl
abcd

1998
Acura
cl
abcd

1999
Elle
cl
abcd

2006
Audi
A7
abxyz

2007
Audi
A8
abxyz

2008
Audi
A6
abxyz

2017
buick
casada
zzxxyy

2007
buick
casada
zzxxyy

2018
buick
casada
zzxxyy

...
...
...
...

I will change to new_csv file: (read input csv file, and write new_csv file)

year
make
model
text
type

1997
Acura
cl
abcd
type_0001

1998
Acura
cl
abcd
type_0001

1999
Elle
cl
abcd
type_0001

2006
Audi
A7
abxyz
type_0002

2007
Audi
A8
abxyz
type_0002

2008
Audi
A6
abxyz
type_0002

2017
buick
casada
zzxxyy
type_0003

2007
buick
casada
zzxxyy
type_0003

2018
buick
casada
zzxxyy
type_0003

...
...
...
...
...

I have remove duplicates and set 'type'. And VLOOKUP 'type' by 'text'. But 'text' column have len() > 2000 characters. Excel VLOOKUP not match 'type'.
Please help code TUT by python. Thank you so much.
I use csv lib: I new python 7 days.
import csv

with open('link1.csv', newline='') as csvfile:
    #reader = csv.reader(csvfile)
    reader = csv.reader(csvfile, delimiter = ',', skipinitialspace = True)
    array = []
    for row in reader:
        print (row)
        print ('------------')
        print (row[3])
        print ('++++++++++++++')
        #????

header = ['year','make','model','text','type']
with open("data.csv", 'w', newline='') as csvfile:
    csvwriter = csv.writer(csvfile)
    csvwriter.writerow(header)
    csvwriter.writerows(array)

A: For this problem I would use Pandas instead of the csv library.
Have a look at something like this.
# Importing the libraries.
import pandas as pd

# Creating a Pandas DataFrame.
df = pd.DataFrame([{'year': 1997, 'make': 'Acura', 'model': 'cl', 'text': 'abcd'},
               {'year': 1998, 'make': 'Acura', 'model': 'cl', 'text': 'abcd'},
               {'year': 1999, 'make': 'Elle', 'model': 'cl', 'text': 'abcd'},
               {'year': 2006, 'make': 'Audi', 'model': 'A7', 'text': 'abxyz'},
               {'year': 2007, 'make': 'Audi', 'model': 'A8', 'text': 'abxyz'},
               {'year': 2008, 'make': 'Audi', 'model': 'A6', 'text': 'abxyz'},
               {'year': 2017, 'make': 'buick', 'model': 'casada', 'text': 'zzxxyy'},
               {'year': 2017, 'make': 'buick', 'model': 'casada', 'text': 'zzxxyy'},
               {'year': 2018, 'make': 'buick', 'model': 'casada', 'text': 'zzxxyy'}])
# Printing out our dataset.
print(df)
# Getting unique `text` values.
list_unique_text = list(df['text'].unique())
# Creating a dictionary to map the `text` values to `type` values.
dict_text_to_type_mapper = {text: 'type_{0:0>4}'.format(index + 1) for index, text in enumerate(list_unique_text)}
# Let's see what our mapper looks like.
print(dict_text_to_type_mapper)
# Let's now create a new column in our data and fill it with values.
df['type'] = df.apply(lambda row: dict_text_to_type_mapper[row['text']], axis=1)
# Here's our new DataFrame.
print(df)

In your case, instead of creating your DataFrame by hand, you will need to read your CSV file.
df = pd.read_csv(PATH_TO_YOUR_CSV)

Using the code above I have transformed this data
    make   model    text  year
0  Acura      cl    abcd  1997
1  Acura      cl    abcd  1998
2   Elle      cl    abcd  1999
3   Audi      A7   abxyz  2006
4   Audi      A8   abxyz  2007
5   Audi      A6   abxyz  2008
6  buick  casada  zzxxyy  2017
7  buick  casada  zzxxyy  2017
8  buick  casada  zzxxyy  2018

into this
    make   model    text  year       type
0  Acura      cl    abcd  1997  type_0001
1  Acura      cl    abcd  1998  type_0001
2   Elle      cl    abcd  1999  type_0001
3   Audi      A7   abxyz  2006  type_0002
4   Audi      A8   abxyz  2007  type_0002
5   Audi      A6   abxyz  2008  type_0002
6  buick  casada  zzxxyy  2017  type_0003
7  buick  casada  zzxxyy  2017  type_0003
8  buick  casada  zzxxyy  2018  type_0003


text:
Q: How to set variable value inside the remote server Inside the remote server i have a condition statement.If that condition passes
status value should be set as success.
But here i am always getting Failure response while i print status variable
status='Success';
status='Success';
# !/bin/bash

declare -a server_PP=('XXXXX' 'YYYYYYY' );
declare -A results_map;

function process(){
serverList=$1[@];
servers=("${!serverList}");
status='Failure';
for  serverName in "${servers[@]}"
do
    ssh  $serverName  <<  EOF
          if [ -f /app/Release/abc.war ]; then
            echo "available - success"
            status='Success';
          fi
echo "***********status-inside******$status"
        exit
EOF
echo "***********status-outside******$status"
results_map+=([$serverName]=$status);
done

}

process 'server_PP'

for i in "${!results_map[@]}"
do
  echo "key :" $i
  echo "value:" ${results_map[$i]}
done

Status variable should set as success when that condition get satisfied.

A: As written in pcarter's comment, the variables on both systems are independent from each other and don't get passed via ssh. Instead of setting a variable  (or printing and reading the value as proposed in the comment, which is a working solution) you can use the exit code which gets passed automatically by ssh.
The following script is close to the original. For further improvements see below.
# !/bin/bash

declare -a server_PP=('XXXXX' 'YYYYYYY' );
declare -A results_map;

function process(){
serverList=$1[@];
servers=("${!serverList}");
status='Failure';
for  serverName in "${servers[@]}"
do
    if ssh  $serverName  <<  EOF
        if [ -f /app/Release/abc.war ]; then
            echo "available - success"
            exit 0;
        fi
        echo "error"
        exit 1
EOF
    then
        status='Success'
    else
        status='Failure'
    fi
echo "***********status-outside******$status"
results_map+=([$serverName]=$status);
done
}

process 'server_PP'

for i in "${!results_map[@]}"
do
  echo "key :" $i
  echo "value:" ${results_map[$i]}
done

As you no longer need the variable assignments you can even omit the if ... and exit in the remote commands.
    if ssh  $serverName  <<  EOF
        [ -f /app/Release/abc.war ]
EOF
    then
...

Your approach of using a heredoc as
ssh hostname <<EOF
# commands ...
EOF

has the disadvantage that you run an interactive shell on the remote system, which may print some system information or welcome message before executing your commands. You can further simplify the script (and removing the welcome message) by specifying the command or a script as command line arguments for ssh.
    if ssh  $serverName  [ -f /app/Release/abc.war ]
    then
...

If your command sequence is longer you can create a script on the remote system and run this script in the same way as ssh hostname scriptname. You could also create the script on the remote system using ssh or scp.


text:
Q: Comparing articles with composite PK in ASP.NET WebAPI Before I take a POST request, the application should compare the input object whether it exists in the database table. The problem for my intention is, that the db table has two primary keys and when I'm try to compare it, then it tells me the article is not exist because the first PK Id will automatically increased. So, important for me is the second PK isin.
The following code doesn't work:
[HttpPost]
[ResponseType(typeof(Fon))]
public async Task<IHttpActionResult> PostFond(Fon fon)
{
  if (!ModelState.IsValid)
  {
     return BadRequest(ModelState);
  }

  var fonds = db.Fon.Find(fon.Id, fon.isin);
  if (fonds.isin != null)
  {
     return BadRequest(ModelState); //ISIN already exists.
  }

  db.Fon.Add(fon);
  await db.SaveChangesAsync();

  return CreatedAtRoute("DefaultApi", new { id = fon.Id }, fon);
}

How can I check whether the isin is existing or new?!

EDIT: (SOLUTION)
I've tried many things and come to the correct solution. The following code illustrates it:
var fonds = db.Fon
              .Where(f => f.isin == fon.isin)
              .FirstOrDefault();

if (fonds != null)
{
    return Conflict();
}

db.Fon.Add(fon);
await db.SaveChangesAsync();


text:
Q: What is best approach to write VBA script to Launch recorded macros on the AS400? I am new to connecting to the AS400 using Windows Client Access emulator. I have written VBA scripts in Excel to load data to the AS400. Could someone suggest how to launch a AS400 macro using VBA. I have tried "STRPCO" and "STRPCCMMD", and "StartMacro" without success. I can select recorded macros from the CL menu, but I want to program the same in VBA. Any guidance would be appreciated.
Thanks


text:
Q: EXCEL VS TSQL MODULUS I'm working on some code to convert some packed IP addresses out of an existing database.  I have succeeded in creating a solution in Excel, but not getting consistent results with creating a TSQL function.  While I can do it in Excel, I'm stubborn and want to figure this out. I've distilled this down to the following difference between the platforms:
--= MOD(-1062674156,256) = 20
--SELECT -1062674156 % 256 = -236
Excel 2013, SQL Server 2017 Standard
An explanation would be great, a fix would be even better!  BTW the answer I'm getting with Excel is what I'm after (20)


text:
Q: Is it possible to use handlebars inside handlebars path? I have an object like this:
{
    "var1": "x",
    "var2": {
        "x":
        "y":
        "z":
    }
}
I want something like {{var2.{{var1}} }}

A: The lookup built-in helper (Under "The lookup helper" section) can handle this.
var obj =  {
  "var1": "z",
  "var2":
  {
    "x": 'x value',
    "y": 'y value',
    "z": 'z value'
  }
}
var output =  Handlebars.compile('{{lookup var2 var1}}')(obj)
// output would be 'z value' in this case

It basically allows you to "lookup" property (var1) in object (var2)


text:
Q: How to create a "kind class" in Haskell, or ad-hoc polymorphism at the type-level using type families I'm studying the type family features of Haskell, and type level computation.
It appears it's quite easy to get parametric polymorphism at the type-level using PolyKinds:
{-# LANGUAGE DataKinds, TypeFamilies, KindSignatures, GADTs, TypeOperators, UndecidableInstances, PolyKinds, MultiParamTypeClasses, FlexibleInstances #-}

data NatK = Z | S NatK
data IntK = I NatK NatK

infix 6 +
type family (x :: NatK) + (y :: NatK) :: NatK where
    Z     + y = y
    (S x) + y = S (x + y)

-- here's a parametrically polymorphic (==) at the type-level
-- it also deals specifically with the I type of kind IntK
infix 4 ==
type family (a :: k) == (b :: k) :: Bool where
    (I a1 a2) == (I b1 b2) = (a1 + b2) == (a2 + b1)
    a == a = True
    a == b = False

I can do things like :kind! Bool == Bool or :kind! Int == Int or :kind! Z == Z and :kind! (I Z (S Z)) == (I (S Z) (S (S Z))).
However I want to make type + ad-hoc polymorphic. So that it's constrained to the instances I give it. The 2 instances here, would be types of kind NatK and types of kind IntK.
I first tried making it parametrically polymorphic:
infix 6 :+
type family (x :: k) :+ (y :: k) :: k where
    Z         :+ y = y
    (S x)     :+ y = S (x :+ y)
    (I x1 x2) :+ (I y1 y2) = I (x1 :+ y1) (x2 :+ y2)

This works, as I can do :kind! (I (S Z) Z) :+ (I (S Z) Z).
However I can also do :kind! Bool :+ Bool. And this doesn't make any sense, but it allows it as a simple type constructor. I want to create a type family that doesn't allow such errant types.
At this point I'm lost. I tried type classes with a type parameter. But that didn't work.
class NumK (a :: k) (b :: k) where
    type Add a b :: k

instance NumK (Z :: NatK) (b :: NatK) where
    type Add Z b = b

instance NumK (S a :: NatK) (b :: NatK) where
    type Add (S a) b = S (Add a b)

instance NumK (I a1 a2 :: IntK) (I b1 b2 :: IntK) where
    type Add (I a1 a2) (I b1 b2) = I (Add a1 b1) (Add a2 b2)

It still allows :kind! Add Bool Bool.
Does this have something to do with the ConstraintKinds extension, where I need to constrain the :+ or Add to some "kind class"?

A: The simplest solution is to use open type families for ad-hoc overloading and closed type families for implementation:
data NatK = Z | S NatK
data IntK = I NatK NatK

type family Add (x :: k) (y :: k) :: k

type family AddNatK (a :: NatK) (b :: NatK) where
  AddNatK Z b = b
  AddNatK (S a) b = S (AddNatK a b)

type family AddIntK (a :: IntK) (b :: IntK) where
  AddIntK (I a b) (I a' b') = I (AddNatK a a') (AddNatK b b')

type instance Add (a :: NatK) (b :: NatK) = AddNatK a b
type instance Add (a :: IntK) (b :: IntK) = AddIntK a b

If we want multiple type-level and term-level methods grouped together, we can write kind classes using using KProxy from Data.Proxy:
class NumKind (kproxy :: KProxy k) where
  type Add (a :: k) (b :: k) :: k
  -- possibly other methods on type or term level

instance NumKind ('KProxy :: KProxy NatK) where
  type Add a b = AddNatK a b

instance NumKind ('KProxy :: KProxy IntK) where
  type Add a b = AddIntK a b

Of course, associated types are the same as open type families, so we could have also used open type families with a separate class for term-level methods. But I think it's generally cleaner to have all overloaded names in the same class.
From GHC 8.0, KProxy becomes unnecessary since kinds and types will be treated the exact same way:
{-# LANGUAGE TypeInType #-}

import Data.Kind (Type)

class NumKind (k :: Type) where
  type Add (a :: k) (b :: k) :: k

instance NumKind NatK where
  type Add a b = AddNatK a b

instance NumKind IntK where
  type Add a b = AddIntK a b

A: (This should be a comment but I need more space)
I tried something like
class GoodK (Proxy k) => NumK (a :: k) (b :: k) where ...

but I failed. I have no idea if what you ask is achievable.
The best approximation I got is making Add Bool Bool kind-check, but generate an unsolvable constraint, so that if we ever use it we'll get an error anyway.
Perhaps this could be enough for your purposes (?).
class Fail a where

instance Fail a => NumK (a :: *) (b :: *) where
    type Add a b = ()


text:
Q: UI automator file not included in the latest AndroidStuio or ZIP file with all SDK-tools I have been spent 3 days with google and other sites but didn't find an answer on my question.
After installing Android Studio and download the all SDK tool via tools/SDK manager/SDK tools I'm still unable to find file "uiautomatorviewer.bat".
1) At first, I have not a standard path which described on other tutorial sdk/tools, in latest Android Studio new path to .bt file is here -> C:\Users\Alex*AppData\Local\Android\sdk\cmdline-tools\latest\bin**
2) I tried to installed the SDK tools zip file with all SDK tools, but ZIP file had a folder with the same tools which I had in this path -> AppData\Local\Android\sdk\cmdline-tools\latest\bin
apkanalyzer
avdmanager
lint
screenshot2
sdkmanager
3) I also tried to find the uiautomatorviewer manually by using search in paths:
- C:\Users\Alex**AppData\Local\Android\sdk\cmdline-tools\latest\bin**
- C:\Program Files\Android\Android Studio
But found only the java/jar files
enter image description here


text:
Q: Calculate leaves from table for more than 1 leave entry I have a database table in which leave will be updated.
It has the following columns:
id | empno | startdate | enddate | status | duration

Now I have to calculate the leave in a given month and year where the month and year will come from user input. I have a code which will retrieve the no. of leaves in the given month if the leave entry is 1.
The problem is that if the user has taken leave more than 1 time, the function is calculating only the last row from database. Any help would be appreciated.
<?PHP
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "lms";
$conn = mysqli_connect($servername, $username, $password, $dbname);
$empid    = (isset($_POST['empid'])    ? $_POST['empid']    : '');
$month = (isset($_POST['month'])    ? $_POST['month']    : '');

$month = "2015-sep";

$month1 = date('F', strtotime('$month'));
//echo $month1;

$year = date('Y',strtotime('$month'));

$monthStart = date("Y-m-1") . "
";
$num = cal_days_in_month(CAL_GREGORIAN, date("m"), date("Y"));
$monthEnd = date("Y-m-".$num)."
";
//echo "$num";
$months = date('M');
$years = date ('Y');
$leave = 0;

if ($conn->connect_error)  {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT  `startdate`, `enddate`,`duration` FROM `leaves` WHERE `employee` = '2' AND `status` = '3'
AND `startdate` > '01-09-2015' AND `enddate` < '30-09-2015' ";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc())  {
        $start = ($row['startdate']);
        $end =  ($row['enddate']);
        $startcount = ['COUNT(`employee`)'];
        //$durationlvs =  ($row['duration']);
           echo "sdate:$start,edate:$end
";
          //echo "lvsdur:$durationlvs";
    }

    function getLeavesInPeriod($start, $end) {
        $date = new DateTime($start);
        $endDate = new DateTime($end);
        $leaves = array();

        while( $date <= $endDate ) {
            $year = $date->format('Y');
            $month = $date->format('M');

            if(!array_key_exists($year, $leaves))
                $leaves[$year] = array();
            if(!array_key_exists($month, $leaves[$year]))
                $leaves[$year][$month] = 0;

            $leaves[$year][$month]++;
            $date->modify("+1 day");
        }
    return $leaves;
}
$leaves = getLeavesInPeriod($start,$end);
$noofleaves=$leaves[$years][$months];
echo $noofleaves;
$conn->close();
}
?>

A: Just changed the SQL Query to

$sql = "SELECT   SUM(DATEDIFF(LEAST(enddate, '2015-09-30'),
  GREATEST(startdate, '2015-09-01'))+1) days
  FROM leaves WHERE
  startdate<='2015-09-30' AND enddate>='2015-09-01' AND employee='2'
  AND status='1'";

ufff!!! got the result.


text:
Q: Create a dynamic horizontal repeating table in Infopath 2013 based on a previously given number? Problem:
You have a regular repeating table when it comes to the rows but need the columns to repeat as well based on the difference between two fields.
Ex. The difference field has the value 4 so the table needs to have 4 columns (The number of rows is already variable because of the repeating table control).
The problem also lies in the fact that there is no maximum difference, it can be any value, so creating all the columns and adding formatting rules to hide them isn't a feasible solution.
Is there any way that using C# we can create a new field or table, or access a previously created table in the Infopath form?
https://docs.google.com/spreadsheets/d/1nj5xOuveD-CHTSJkgJOm_qnxKf5KTBr4OTdSJMMUKKw/edit?usp=sharing
The link above is an excel sheet with a small demonstration of the expected output.
Thanks.


text:
Q: How to make chainable function in JavaScript? Lets imagine function like this:
function foo(x) {
    x += '+';
    return x;
}

Usage of it would be like:
var x, y;
x = 'Notepad';
y = foo(x);
console.log(y); // Prints 'Notepad+'.

I'm looking for a way to create function that's chainable with other functions.
Imagine usage:
var x, y;
x = 'Notepad';
y = x.foo().foo().toUpperCase(); // Prints 'NOTEPAD++'.
console.log(y);

How would I do this?

A: Sure, the trick is to return the object once you're done modifying it:
String.prototype.foo = function() {
    return this + "+";
}

var str = "Notepad";
console.log(str.foo().foo().toUpperCase());

http://jsfiddle.net/Xeon06/vyFek/
To make the method available on String, I'm modifying it's prototype. Be careful not to do this on Object though, as it can cause problems when enumerating over their properties.

A: If I remember correctly, you can use "this" as a context of a function (object it belongs to) and return it to make the function chainable. In other words:
var obj =
{
    f1: function() { ...do something...; return this;},
    f2: function() { ...do something...; return this;}
}

then you can chain the calls like obj.f1().f2()
Keep in mind, you won't be able to achieve what you are expecting by calling obj.f1().toUpperCase() - it will execute f1(), return "this" and will try to call obj.toUpperCase().

A: Here's a way to do it without messing with String.prototype, by returning an object similar to a string, with an additional method foo(). However, there are some downsides to this approach related to it not returning an actual string.

// Returns an object similar to a string, with an additional method foo()
function foo(str) {
  return Object.assign(`${str ?? this}+`, {
    foo
  });
}

var str = "Notepad";
console.log(
  "EXAMPLE - foo(str).foo().toUpperCase():",
  foo(str).foo().toUpperCase()
);

console.log("---");

console.log("Some issues with this solution:");
console.log("typeof foo(str):", typeof foo(str));
console.log("foo(str).foo():", foo(str).foo());

console.log(
  "You may need to use toString() - foo(str).foo().toString():",
  foo(str).foo().toString()
);
.as-console-wrapper { min-height: 100% }

A: You can also achieve this using class


text:
Q: Считывание файла в массив Java Есть файл, содержавший число: test.txt
1234523432

Как считать число в массив, посимвольно, и определить, есть ли в данном числе четные цифры и сколько их?

A: Можно использовать Stream Api, файл res.txt должен находиться в ресурсах:
 public static void main(String[] args) throws URISyntaxException, IOException {

        List<Integer> list = Files.lines(Paths.get(Main.class.getResource("res.txt").toURI()), StandardCharsets.UTF_8)
                .map(s -> s.split(""))
                .flatMap(Arrays::stream)
                .map(Integer::valueOf)
                .collect(Collectors.toList());
        list.forEach(System.out::println);
        int chet = (int) list.stream().filter(s -> s % 2 == 0).count();
        System.out.println(chet!=0?"Число четных: " + chet:"Нет четных");
    }

A: Это можно сделать следующим образом:

import java.io.*;

public class script {
    public static void main(String[] args) throws Exception{
  FileInputStream io = new FileInputStream("test.txt");
  int countOfEven = 0;
  BufferedReader r = new BufferedReader(new InputStreamReader(io));
  String line;
  while( (line = r.readLine()) != null ){
   for(char ch : line.toCharArray()){
    if(Integer.parseInt(String.valueOf(ch)) % 2 == 0){
     countOfEven++;
    }
   }
  }
  if(countOfEven != 0){
   System.out.println("Число имеет четные цифры");
   System.out.println("Количество - " + countOfEven);
  }else{
   System.out.println("Число не имеет четных цифр");
  }

 }
}


text:
Q: std::bind and std::weak_ptr I have a class that creates a wrapper functor to deal with a weak_ptr to an object.  When the functor executes, it will test the weak_ptr before invoking the object functor.
Additionally, the wrapper functor can return a default value if the object no longer exists.
This is an excerpt of a class that compiles under GCC 4.4.7...
class Bind
{
public:

    // non-void weak-functor
    template <typename R>
    struct Wrapper<R, typename std::enable_if<!std::is_void<R>::value>::type>
    {
        using result_type = R;

        template <typename O>
        R operator()(const std::weak_ptr<O> && obj,
                     std::function<R()> && func, R && ret)
        {
            if (auto ptr = obj.lock())
            {
                return func();
            }

            return std::forward<R>(ret);
        }
    };

    // weak from shared - non-void return
    template <typename R, typename F, typename O, typename... A>
    static std::function<R()> Weak(R && ret,
                                   F func,
                                   const std::shared_ptr<O> && obj,
                                   A&&... args)
    {
        return std::bind(Wrapper<R>(),
                         std::weak_ptr<O>(obj),
                         std::function<R()>(std::bind(func, obj.get(),
                                            std::forward<A>(args)...)),
                         ret);
    }

    // ...
};

The class can be used like this...
auto x = std::make_shared<X>();
auto f = Bind::Weak(false, &X::foo, x, 1, 2, 3);

f();   // returns x::foo(1, 2, 3)

x.reset()

f();   // returns false

Unfortunately, after upgrading the compiler to GCC 4.8.3 it no longer compiles.  The error starts like this...
error: could not convert 'std::bind(_Func&&, _BoundArgs&& ...)

...with the usual mountain of template crud.  The jist is that it can no longer convert the result of std::bind() inside Bind::Weak() into the return type of Bind::Weak().
I've fiddled with this for a few hours now and haven't been able to resolve the issue.

A: The problem is that you cannot do perfect forwarding using a std::function because the std::function is required to be copyable, so the bound values have to be copiable, too.
Changing the operator() prototype to:
template<typename O>
R operator()(const std::weak_ptr<O>& obj, const std::function<R()>& func, const R& ret)
{
    //...
}

Should be more or less enough to make this work (it is difficult to be sure because your posted code is not complete).
But now that your forwarding into the binding is destroyed, all those std::forward and && do not make much sense, IMO.


text:
Q: Update value in object array with useState I have an array of objects and I want to update a value within those objects using the useState hook, but unclear on how to format this and get it working.
setCarUnsubscribeList(carUnsubscribeList => (carUnsubscribeList.forEach((car:CarSelections) => {
  car.checked = true;
})));

A: spread the original object and change the propert you want
setAllChecked(prev => prev.map(car =>({
    ...car,
    checked : true
})))


text:
Q: Insert XML data into the existing posts I have nba videos news website and I want to insert xml data into the existing posts.
For ex I have this post Pacers vs Timberwolves Match report and I want to import data from this xml: http://developer.sportradar.us/files/nba_v3_game_boxscore_example.xml
I know how to echo and get data from xml feeds but my problem is how to assign automatically these xml feeds based on each posts (match reports) .

*

*I need to collect data first and store it at my local DB?

*Retrieve a specific field from taxonomy term OR custom field term and use it on xml url's ex http(s)://api.sportradar.us/nba/[season]/games/[game_id]/summary.xml?api_key=[api_key] ?
Also as alternative I can use JSON feeds.


text:
Q: Skip property in iteration while copying array I am building a new array from the one returned to me out of my database. My original array consists of many objects and several objects can be the same like this one:
object(stdClass)[26]
  public 'id' => string '6' (length=1)
  public 'title' => string 'Something' (length=41)
  public 'excerpt' => string '
Something
' (length=104)
  public 'content' => string '
Lorem Ipsum
' (length=18)
  public 'location' => string '' (length=0)
  public 'author' => string '' (length=0)
  public 'date' => string '2015-09-28' (length=10)
  public 'publish' => string '1' (length=1)
  public 'top' => string '0' (length=1)
  public 'post_id' => string '0' (length=1)
  public 'news_image_path' => string '14545819551_gallery.jpg' (length=23)
  public 'news_main_image' => string '0' (length=1)

The only difference in this same objects is in "news_image_path" property and in "news_main_image" property which is either "0", "1" or NULL. According to that "news_main_image" I want to merge that same objects and I want that only the one with 'news_main_image' => string '1' survives the process if there is neither the property of 'news_image_path' should be NULL or if there is 'news_main_image' => string '0' property 'news_image_path' should also be null.
In short:
if 'news_main_image' => string '1' then 'news_image_path' => string '14545819576_main.jpg'
if 'news_main_image' => string '0' then 'news_image_path' => NULL
if 'news_main_image' => NULL then 'news_image_path' => NULL
But every other property should stay the same!
My code so far but it is overriding itself and if there was news_image_path set in previous iteration it copies NULL over it:
foreach ($result as $key => $value)
{
   if ($value->news_main_image == '1')
   {
       $tmp[$value->id] = $value;
       $tmp[$value->id]->news_image_path = $value->news_image_path;
   }
   elseif ($value->news_main_image == '0')
   {
       // DO SOMETHING HERE that will copy to the new array but it wont copy over the existing $tmp[$value->id]->news_image_path
       $tmp[$value->id] = $value;
       $tmp[$value->id]->news_image_path = NULL;
   }
   else
   {
      $tmp[$value->id] = $value;
   }

}
$result = $tmp;

A: I slightly improved your code and tried it, and work fine.
    foreach ($itemArray as $item)
    {
       $tmp[$item->id] = $item;

       if ($item->news_main_image == '0'){
           $tmp[$item->id]->news_image_path = NULL;
       }

    }
    $result = $tmp;

But it should does exactly the samy as yours...

A: Assuming you have an array of objects that looks like this if I understood you :
array(2) {
  [0]=>
  object(stdClass)#22 (2) {
    //....
    ["news_image_path"]=>
    string(23) "14545819551_gallery.jpg"
    ["news_main_image"]=>
    string(1) "1"
  }
  [1]=>
  object(stdClass)#23 (2) {
    //...
    ["news_image_path"]=>
    string(23) "14545819552_gallery.jpg"
    ["news_main_image"]=>
    int(0)
  }
}

you can try this code below
 //$o is the array of objects you have
 //$res will be your result array of objects
 $res = array();
 foreach ( $o as $a ){
    //$tmp will be your new object
    $tmp = $a;
    if (! $a->news_main_image ){
        $tmp->news_image_path = null;
    }
    $res[] = $tmp;
 }

and your output will look like this
array(2) {
  [0]=>
  object(stdClass)#22 (2) {
    ["news_image_path"]=>
    string(23) "14545819551_gallery.jpg"
    ["news_main_image"]=>
    string(1) "1"
  }
  [1]=>
  object(stdClass)#23 (2) {
    ["news_image_path"]=>
    NULL
    ["news_main_image"]=>
    int(0)
  }
}

hope that helps

A: Though I hate to use two foreach statements here is the solution. If someone can write this better please tell me:
        foreach ($result as $key => $value)
        {
            if ($value->news_main_image == '1')
            {
                $news_image_path[$value->id] = $value->news_image_path;
            }
            else
            {
                $value->news_image_path = NULL;
            }

            $tmp[$value->id] = $value;
        }

        foreach ($news_image_path as $key => $value)
        {
            $tmp[$key]->news_image_path = $value;
        }

        $result = $tmp;


text:
Q: Android Toast.Set Gravity Causing App To Crash I don't understand why my toast is crashing the app.
I have two sets of code, the one I originally did which is crashing and one that I found that is working.
The one the is working creates the toast object and declares the text at the same time.
Toast toast =
Toast.makeText(QuizActivity.this,R.string.incorrect_toast, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();

The one I made creates the object in the context, sets the text then the gravity and tries to show it.
Toast toast = new Toast(QuizActivity.this);
toast.makeText(QuizActivity.this,
               R.string.correct_toast,
               Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();

Why is this crashing my app?

A: you can try this
Toast toast = Toast.makeText(QuizActivity.this,"your string", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();

A: Your
Toast toast = new Toast(QuizActivity.this);

constructs an empty Toast object. You must call setView(View) before you can call show().
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
            (ViewGroup) findViewById(R.id.custom_toast_container));

TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("This is a custom toast");

Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();

as it stated in Android docs.

A: You can create a toast object like this.
Toast toast = new Toast(QuizActivity.this);

This line of code construct an empty Toast object.
Then you have to call the setView() , setDuration() on your own. makeText() method is a static method. So, you can't call it from a toast object.
You can initialize a Toast object by calling the method makeText() method.
For this reason, the first code is working properly and the second is not.

A:  This is crashing because you are not called setView() method before calling show mehod.
 Calling constructor(Toast toast = new Toast(QuizActivity.this);) will construct an empty Toast object.This object will not contain a default view to show,So you have to call setView() method to set a view for the toast.Then only this will work.

A: Most probably you are getting RuntimeException.

'java.lang.RuntimeException: setView must have been called'

You are just creating an instance of Toast uisng "new Toast(QuizActivity.this)" and you did not set any view for it. You have to set your own custom layout to Toast.
SOLUTION:
LayoutInflater inflate = (LayoutInflater)
        this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

// Custom layout
View view = inflate.inflate(R.layout.custom_toast, null);
TextView tv = (TextView) view.findViewById(R.id.textView);
tv.setText("Hello world!");

// Toast
Toast toast = new Toast(QuizActivity.this);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);

// Set the Toast custom layout
toast.setView(view);
toast.show();

Here is custom_toast.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_margin="5px"
    android:padding="10dp"
    android:layout_gravity="center_horizontal">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/imageView"
            android:src="@mipmap/ic_launcher"
            android:layout_width="50dp"
            android:layout_height="50dp"/>

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="3dp"
            android:text="Android Tutorial Custom Toast"
            android:textColor="#fff"
            android:textSize="16dp"
            android:layout_gravity="center_vertical"/>

    </LinearLayout>
</LinearLayout>

Hope this will help~


text:
Q: :action/* element is giving missing controller error <?php
Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));
/**
* ...and connect the rest of 'Pages' controller's URLs.
*/
Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display'));
Router::connect('/blog/:action/*', array('controller' => 'posts', 'action' =>'index'));
/**
* Load all plugin routes. See the CakePlugin documentation on
* how to customize the loading of plugin routes.
*/
CakePlugin::routes();

/**
* Load the CakePHP default routes. Only remove this if you do not want to use
* the built-in default routes.
*/
require CAKE . 'Config' . DS . 'routes.php';
?>

here is my route.php file when i try to access website/blog it would throw me an error saying blog controller is missing.
but when i change "/blog/:action/*" to "/blog" it wil work fine what am i doing wrong ??
please help thanks.

A: Ok, based on your comments, try this
//redirects "website/items/view/1" to "website/blogs/view/1"
Router::connect('/items/:action/*', array('controller' => 'blogs'));

//redirects "/blog" to "website/items/index"
Router::connect('/blog', array('controller' => 'items', 'action' =>'index'));

But it seems awfully confusing? why redirect blog to items ("website/blog it redirect me to website/Item/index") and items to blog ("website/Items/view/1 it redirects me to website/blog/View/1")? Shouldn't you just change those actions to the controller where you want to have them?
And please read the routing docs.


text:
Q: How to select element text with react+enzyme Just what it says. Some example code:
let wrapper = shallow(
<button class='btn btn-primary'>OK</button>
);

const b = wrapper.find('.btn');

expect(b.text()).to.be.eql('OK'); // fail

Also the html method returns the contents of the element but also the element itself plus all the attributes, e.g. it gives <button class='btn btn-primary'>OK</button>. So I guess, worst case, I can call html and regex it, but...
Is there a way to just get the contents of the element, so I can assert on it.

A: I think @louis-barranqueiro has probably answered your underlying question. That is, you want a CSS selector and so you should have been using className not class.
However, to try and answer the question of how to select an element's text using the actual example you gave:
let wrapper = shallow(
<button class='btn btn-primary'>OK</button>
);
you'd need to use something like an object property selector, e.g.:
expect(wrapper.find({ class: "btn btn-primary" }).text()).to.equal('OK');
or prop syntax:
expect(wrapper.find('[class="btn btn-primary"]').text()).to.equal('OK');
(or even more explicitly):
expect(wrapper.find('button[class="btn btn-primary"]').text()).to.equal('OK');

A: If you found this while looking for "includes text", try:
it('should show correct text', () => {
  const wrapper = shallow(<MyComponent />);
  expect(wrapper.text().includes('my text')).toBe(true);
});

A: Don't forget that you are passing a node (ReactElement) to shallow function, and there is no HTML attribute class in React. You have to use className.
From React documentation

All attributes are camel-cased and the attributes class and for are
  className and htmlFor, respectively, to match the DOM API
  specification.

This test should works

const wrapper = shallow(
<button className='btn btn-primary'>OK</button>
);
const button = wrapper.find('.btn');
expect(button.text()).to.be.eql('OK');

A: I ran into this post when searching for ways to select all/some of the text within a textarea within jest and enzyme. For those who are looking for the same thing, you do can the following to select some text (provided you already know the length):
let wrapper;
let textareaNode;
beforeEach(() => {
    wrapper = mount(<Textarea value="Hello world" />);
    textareaNode = () => wrapper.find("textarea").getDOMNode();
});

it("selects all of the select within the given range", () => {
    textareaNode().setSelectionRange(0, 6);
    wrapper.find("button").simulate("click"); // this would delete the selection via a ref
    expect(wrapper.find("textarea").props().value).toEqual("world");
});


text:
Q: Getting Digits from twilio Gather I am trying to get the digits entered into phone. I thought res.Digits in Pin function would be the way but I get an undefined error
exports.Say = function(req, res)
{
    var resp = new twilio.TwimlResponse();

    resp.gather(
    {
        action:'http://pap-papdemo.rhcloud.com/api/Phone/Pin',
        finishOnKey:'#',
        method:"POST"
    }, function()
    {
        this.say('Please enter your Phone and Pin number followed by the hash key');
    });

    //Render the TwiML document using "toString"
    res.writeHead(200,
    {
          'Content-Type':'text/xml'
    });

    res.end(resp.toString());

};

     exports.Pin = function(req, res)
        {
            var resp = new twilio.TwimlResponse();
            console.log("***** PIN *****");

            console.log("Pin: Response " +  res.body.Digits);

            //Render the TwiML document using "toString"
            res.writeHead(200,
            {
                  'Content-Type':'text/xml'
            });

            res.end(resp.toString());

        };

any idea what I need to do as I need to store pin number in db

A: Megan from Twilio here. I saw you answered your own question but figured I'd update as an answer for others who land here.
Twilio will pass Digits as a parameter in addition to the standard TwiML Voice request parameters with its request to the 'action' URL.
Thus var pin = JSON.stringify(req.body.Digits); worked in this case.


text:
Q: Things I have tried to fix Failed to Connect to MySQL at 127.0.0.1:3306 with user root I have exhausted myself for the past 2 hours reading and troubleshooting the problem on the MySQL workbench.
Anyway, this is what I did:
googled "MySQL workbench"
installed MySQL workbench 6.3.9 using the MSI file.
set-up new connection and manage server connections (tried both)
Connection Name: MyFirstConnection
Connection Method: Standard (TCP/IP)
Hostname: 127.0.0.1
Port: 3306
Username: root
then I pressed "test connection"... guess what:
Failed to Connect to MySQL at 127.0.0.1:3306 with user root
Things I have tried so far:
1a.) Go to "cmd" -> type mysql -u root -p
1b.) Go to "cmd" -> type mysql -u root -p -h 127.0.0.1 -P 3306
Result:
'mysql' is not recognizable as an internal or external command, operable program or batch file.
2.) Start workbench as administrator
Result:
Failed to Connect to MySQL at 127.0.0.1:3306 with user root
3.) "my.cnf" file
Result:
Cannot find it in installation directory at all or in search ("my.cnf" or even "my")
4a.) Search services.msc then Activate the MySQL server manually.
Result:
services.msc panel
Okay.. "MySQL" as stated is not even there.
Only SQL
This is the closest thing to MySQL I can find and I don't even know what it does so okay. I just pressed "reset" for the heck of it.
Result: Failed to Connect to MySQL at 127.0.0.1:3306 with user root
5a.) Change hostname to localhost
5b.) Change hostname to netBiosName (or Asus-PC in my case)
Results:
Failed to Connect to MySQL at localhost with user root
and
Failed to Connect to MySQL at Asus-PC with user root
6.) Change 3306 to 3307
Results:
Failed to Connect to MySQL at 127.0.0.1:3306 with user root
7.) Check my internet connection
Results: Okay i'm writing this thing and publishing it.
So what else have I not tried. I just started using workbench today and is already extremely difficult to navigate through.

A: You know that MySQL Workbench is only a client? And a client needs a server. Where is your server? Did you install one (doesn't look so)? I recommend the MySQL Installer For Windows which comes with everything to get you started easily.


text:
Q: Fatal error: glibc detected an invalid stdio handle when using kotlin-native I was playing around with kotlin-native, trying to open a file. The file is opened and created correctly, however, when printing to the file I get the error "Fatal error: glibc detected an invalid stdio handle
Process finished with exit code 134 (interrupted by signal 6: SIGABRT)"
Am I doig something wrong here? Or is this a kotlin configuration issue? The same code does work in C
import kotlinx.cinterop.*
import platform.posix.*

fun main(args: Array<String>) {
    val home = getenv("HOME")?.toKString() ?: "NONE"
    val fopen: FILE = fopen("$home/checkinTime", "w")?.pointed ?: throw RuntimeException()
    val readValue: CValue<FILE> = fopen.readValue();
    fprintf(readValue,"String")
}

A: This code does the job:
import kotlinx.cinterop.*
import platform.posix.*

fun main(args: Array<String>) {
    val home = getenv("HOME")?.toKString() ?: "NONE"
    val f = fopen("$home/checkinTime", "w") ?: throw RuntimeException()
    fprintf(f, "String")
    fclose(f)
}


text:
Q: how to upload multiple files using flask in python Here is my code for multiple files upload:
HTML CODE:
Browse <input type="file" name="pro_attachment1" id="pro_attachment1" multiple>

PYTHON CODE:
pro_attachment = request.files.getlist('pro_attachment1')

for upload in pro_attachment:
    filename = upload.filename.rsplit("/")[0]
    destination = os.path.join(application.config['UPLOAD_FOLDER'], filename)
    print "Accept incoming file:", filename
    print "Save it to:", destination
    upload.save(destination)

But it uploads a single file instead of multiple files.

A: Your code looks perfect.
I think the only mistake your making is splitting and taking the first value.
And also i dont know about the rsplit(), but the split() works perfect for me.
HTML CODE

<input id="upload_img" name="zip_folder"  type="file" multiple  webkitdirectory  >

PYTHON CODE
@app.route('/zipped',methods = ['GET', 'POST'])
def zipped():
    if request.method == 'POST':
        f = request.files.getlist("zip_folder")
        print f
        for zipfile in f:
            filename = zipfile.filename.split('/')[1]
            print zipfile.filename.split('/')[1]
            zipfile.save(os.path.join(app.config['ZIPPED_FILE'], filename))
        return render_template('final.html')

A: How to
In the template, you need to add mulitple attribute in upload input:
<form method="POST" enctype="multipart/form-data">
    <input type="file" name="photos" multiple>
    <input type="submit" value="Submit">
</form>

Then in view function, the uploaded files can get as a list through request.files.getlist('photos'). Loop this list and call save() method on each item (werkzeug.datastructures.FileStorage) will save them at given path:
import os

from flask import Flask, request, render_template, redirect

app = Flask(__name__)
app.config['UPLOAD_PATH'] = '/the/path/to/save'

@app.route('/upload', methods=['GET', 'POST'])
def upload():
    if request.method == 'POST' and 'photo' in request.files:
        for f in request.files.getlist('photo'):
            f.save(os.path.join(app.config['UPLOAD_PATH'], f.filename))
        return 'Upload completed.'
    return render_template('upload.html')

Furthermore, you may need to use secure_filename() to clean filename:
# ...
from werkzeug.utils import secure_filename
# ...
    for f in request.files.getlist('photo'):
        filename = secure_filename(f.filename)
        f.save(os.path.join(app.config['UPLOAD_PATH'], filename))
        # ...

You can also generate a random filename with this method.
Full demo
View:
import os

from flask import Flask, request, render_template
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.config['UPLOAD_PATH'] = '/the/path/to/save'

@main.route('/upload', methods=['GET', 'POST'])
def upload():
    form = UploadForm()
    if form.validate_on_submit() and 'photo' in request.files:
        for f in request.files.getlist('photo'):
            filename = secure_filename(f.filename)
            f.save(os.path.join(app.config['UPLOAD_PATH'], filename))
        return 'Upload completed.'
    return render_template('upload.html', form=form)

Form:
from flask_wtf import FlaskForm
from wtforms import SubmitField
from flask_wtf.file import FileField, FileAllowed, FileRequired

class UploadForm(FlaskForm):
    photo = FileField('Image', validators=[
        FileRequired(),
        FileAllowed(photos, 'Image only!')
    ])
    submit = SubmitField('Submit')

Template:
<form method="POST" enctype="multipart/form-data">
    {{ form.hidden_tag() }}
    {{ form.photo(multiple="multiple") }}
    {{ form.submit }}
</form>

More
For better upload experience, you can try Flask-Dropzone.


text:
Q: Сanvas fabricjs рамка изоражения Привет, парни, подскажите как сделать, что бы рамка изображения не исчезала, когда я ее увожу за фон другого изображения?
То есть, есть пример - jsfiddle.net/gorelov/hLj6tmq8 Когда текст передвигаю за рамку телефона, то у меня пропадает изображение и сама рамка, а нужно что бы она осталась, как тут jsfiddle.net/gorelov/m8ac9nhn - но этот пример мне не подходит, мне нужно модифицировать первый пример, подскажите, пожалуйста, кто знает!

A: Все, решил. Проблема была вот в чем.
У меня в примере картинка телефона накладывалась через метод setOverlayImage. И он не давал возможности сделать что мне нужно.
Я поменял его на  setBackgroundImage. И готово, пример, который мне помог jsfiddle.net/gs1L69fj/9


text:
Q: Better approach to write query with group by I have two sql queries to query email domain count as follow. which is a better approach to follow?
It also seems that both queries return the exact same execution plan but I do not understand why is it so.
First
SELECT emaildomain,
       Count(email) AS Total
FROM   (SELECT email,
               Substring(email, Charindex('@', email) + 1,
               Len(email) - Charindex('@',
                            email))
               AS EmailDomain
        FROM   [dbo].[tbluser]) A
GROUP  BY emaildomain

Second
Select substring(email, charindex('@', Email) + 1,
Len(Email) - charindex('@', Email)) as EmailDomain,
count (Email) as Total
from [dbo].[tblUser]
GROUP BY substring(email, charindex('@', Email) + 1,
Len(Email) - charindex('@', Email))

A: The execution plans should be the same.  Which is better depends on multiple factors, but either should be fine.
I want to suggest another alternative:
SELECT v.emaildomain, count(*) as total
FROM dbo.tbluser u CROSS APPLY
     (VALUES (substring(u.email, Charindex('@', u.email) + 1,
                        Len(u.email) - Charindex('@', u.email)
                       )
             )
     ) v(EmailDomain)
GROUP BY vemaildomain ;

APPLY implements something called a "lateral join".  This has many uses.  But one use is to define new column aliases that do not require subqueries/CTEs.
Note that you can also simplify this logic as:
     (VALUES ( stuff(u.email, 1, charindex('@', u.email) + 1, '') )
     ) v(EmailDomain)

A: If the Execution Plan is the same for both, for me, the first query is cleaner than the second, personally, I prefer to use Common Table Expression (CTE), but it is equivalent to use a derived table.
The next time you can share the Execution Plan with this tool:
https://www.brentozar.com/pastetheplan/


text:
Q: Disable/enable commandbutton on ajax event I want to be able to disable the commandbutton below once it's hit and enable it once the event listener runs and msg1 is rendered.
<h:commandButton value="Submit">
  <f:ajax execute="@form" render="msg1" listener="{bean.method}" />
</h:commandButton>

How could I do this?
UPDATE: I found out that I can attach onclick event to the commandButton element itself to disable it. How can I detect the listener method has returned so I can enable the button again?

A: You could do it with help of the onevent attribute of <f:ajax> which points to a JavaScript function which handles the JSF Ajax events.
E.g.:
<h:commandButton value="Submit">
  <f:ajax execute="@form" render="msg1" listener="#{bean.method}" onevent="handleDisableButton" />
</h:commandButton>

(note that I fixed the wrong EL in listener as well)
with this JS:
function handleDisableButton(data) {
    var buttonElement = data.source; // The HTML DOM element which invoked the ajax event.
    var ajaxStatus = data.status; // Can be "begin", "complete" and "success".

    switch (ajaxStatus) {
        case "begin": // This is called right before ajax request is been sent.
            buttonElement.disabled = true;
            break;

        case "complete": // This is called right after ajax response is received.
            // We don't want to enable it yet here, right?
            break;

        case "success": // This is called when ajax response is successfully processed.
            buttonElement.disabled = false;
            break;
    }
}

A: If you use richfaces, the a4j:commandButton has the status attribute which prevent this.


text:
Q: What is the default ColorFunction for 3D plots? This should be a really simple question, but it isn't in the documentation for some perverse reason. I like the default ColorFunction that Mathematica uses for Plot3D and the like. I'd like to use the same color scheme for other Mathematica plots that don't have it as the automatic default. However, after looking through all of the Color Gradients listed by ColorData["Gradients"] I can't find any that match the effect of just setting ColorFunction->Automatic.
My question: What does Mathematica call its default color palette, why isn't it listed in ColorData, and how can I access it to apply it to other plots?

A: I think the default color scheme comes from PlotStyle -> White, Lighting -> Automatic, without setting any ColorFunction.
Please compare the results of these two commands:
Row[{
    Plot3D[Sin[x y], {x, 0, 3}, {y, 0, 3}, ImageSize -> 200],
    Plot3D[Sin[x y], {x, 0, 3}, {y, 0, 3}, ImageSize -> 200,
           PlotStyle -> White,
           Lighting -> Automatic]
   }]

Also, the documentation for Lighting states "If a color function is given to a plot, then neutral lighting is used automatically". Please compare the results of the following commands:
Row[{
    Plot3D[Sin[x y], {x, 0, 3}, {y, 0, 3}, ImageSize -> 200,
           ColorFunction -> (White &)],
    Show[
         Plot3D[Sin[x y], {x, 0, 3}, {y, 0, 3}, ImageSize -> 200,
                ColorFunction -> (White &)],
         Lighting -> Automatic]
  }]

A: The howto/ChangeTheLightingOfPlots section of the documentation centre specifies the default lighting settings:
Graphics3D[Sphere[],
 Lighting -> {{"Ambient",
    RGBColor[{0.312, 0.188, 0.4}]}, {"Directional",
    RGBColor[{0.8, 0., 0.}], ImageScaled[{2, 0, 2}]}, {"Directional",
    RGBColor[{0., 0.8, 0.}], ImageScaled[{2, 2, 2}]}, {"Directional",
    RGBColor[{0., 0., 0.8}], ImageScaled[{0, 2, 2}]}}]

So, the object coloring derives from using colored lights, not from a coloring function.

A: Using Trace I extracted the default PlotStyle for many of the 3D plots:
Directive[Specularity[GrayLevel[1], 3], RGBColor[0.880722, 0.611041, 0.142051],   Lighting -> {{"Ambient", RGBColor[      0.30100577, 0.22414668499999998`, 0.090484535]}, {"Directional",      RGBColor[0.2642166, 0.18331229999999998`, 0.04261530000000001],      ImageScaled[{0, 2, 2}]}, {"Directional", RGBColor[      0.2642166, 0.18331229999999998`, 0.04261530000000001],      ImageScaled[{2, 2, 2}]}, {"Directional", RGBColor[      0.2642166, 0.18331229999999998`, 0.04261530000000001],      ImageScaled[{2, 0, 2}]}}, AbsoluteThickness[2]],
Directive[Specularity[GrayLevel[1], 3], RGBColor[   0.368417, 0.506779, 0.709798],   Lighting -> {{"Ambient", RGBColor[      0.19699838300000003`, 0.252204821,       0.33320940200000004`]}, {"Directional", RGBColor[      0.15473514000000002`, 0.21284718000000002`,       0.29811516000000005`], ImageScaled[{0, 2, 2}]}, {"Directional",      RGBColor[      0.15473514000000002`, 0.21284718000000002`,       0.29811516000000005`], ImageScaled[{2, 2, 2}]}, {"Directional",      RGBColor[      0.15473514000000002`, 0.21284718000000002`,       0.29811516000000005`], ImageScaled[{2, 0, 2}]}},   AbsoluteThickness[2]],
Directive[Specularity[GrayLevel[1], 3], RGBColor[   0.560181, 0.691569, 0.194885],   Lighting -> {{"Ambient", RGBColor[      0.1830429875, 0.21424763749999998`,       0.0962851875]}, {"Directional", RGBColor[      0.14004525, 0.17289224999999997`, 0.048721249999999994`],      ImageScaled[{0, 2, 2}]}, {"Directional", RGBColor[      0.14004525, 0.17289224999999997`, 0.048721249999999994`],      ImageScaled[{2, 2, 2}]}, {"Directional", RGBColor[      0.14004525, 0.17289224999999997`, 0.048721249999999994`],      ImageScaled[{2, 0, 2}]}}, AbsoluteThickness[2]],
Directive[Specularity[GrayLevel[1], 6], RGBColor[   0.922526, 0.385626, 0.209179],   Lighting -> {{"Ambient", RGBColor[      0.30756835, 0.18676585, 0.147065275]}, {"Directional", RGBColor[      0.2306315, 0.0964065, 0.05229475],      ImageScaled[{0, 2, 2}]}, {"Directional", GrayLevel[0.3],      ImageScaled[{2, 2, 2}]}, {"Directional", RGBColor[      0.2306315, 0.0964065, 0.05229475], ImageScaled[{2, 0, 2}]}},   AbsoluteThickness[2]],
Directive[Specularity[GrayLevel[1], 6], RGBColor[   0.528488, 0.470624, 0.701351],   Lighting -> {{"Ambient", RGBColor[      0.41139519999999996`, 0.3882496, 0.4805404]}, {"Directional",      RGBColor[0.264244, 0.235312, 0.3506755],      ImageScaled[{0, 2, 2}]}, {"Directional", Hue[0.7, 1, 1],      ImageScaled[{2, 2, 2}]}, {"Directional", RGBColor[      0.264244, 0.235312, 0.3506755], ImageScaled[{2, 0, 2}]}},   AbsoluteThickness[2]],
Directive[Specularity[GrayLevel[1], 6], RGBColor[   0.772079, 0.431554, 0.102387],       Lighting -> {{"Ambient", RGBColor[      0.35441579999999995`, 0.2863108, 0.2204774]}, {"Directional",      RGBColor[0.19301974999999993`, 0.1078885, 0.02559675],      ImageScaled[{0, 2, 2}]}, {"Directional", GrayLevel[0.3],      ImageScaled[{2, 2, 2}]}, {"Directional", RGBColor[      0.19301974999999993`, 0.1078885, 0.02559675],      ImageScaled[{2, 0, 2}]}}, AbsoluteThickness[2]],
Directive[Specularity[GrayLevel[1], 6], RGBColor[   0.363898, 0.618501, 0.782349],   Lighting -> {{"Ambient", RGBColor[      0.28733552, 0.34844024, 0.38776376]}, {"Directional", RGBColor[      0.10916940000000003`, 0.1855503, 0.2347047],      ImageScaled[{0, 2, 2}]}, {"Directional", RGBColor[      0.10916940000000003`, 0.1855503, 0.2347047],      ImageScaled[{2, 2, 2}]}, {"Directional", RGBColor[      0.10916940000000003`, 0.1855503, 0.2347047],      ImageScaled[{2, 0, 2}]}}, AbsoluteThickness[2]],
Directive[Specularity[GrayLevel[1], 3], RGBColor[1, 0.75, 0],   Lighting -> {{"Ambient", RGBColor[      0.334, 0.2755000000000001, 0.1]}, {"Directional", RGBColor[      0.26, 0.19500000000000006`, 0.],      ImageScaled[{0, 2, 2}]}, {"Directional", GrayLevel[0.1],      ImageScaled[{2, 2, 2}]}, {"Directional", RGBColor[      0.26, 0.19500000000000006`, 0.], ImageScaled[{2, 0, 2}]}},   AbsoluteThickness[2]],
Directive[Specularity[GrayLevel[1], 6], RGBColor[   0.647624, 0.37816, 0.614037],   Lighting -> {{"Ambient", RGBColor[      0.40723968, 0.3210112, 0.39649184000000004`]}, {"Directional",      RGBColor[0.2590496, 0.151264, 0.24561480000000002`],      ImageScaled[{0, 2, 2}]}, {"Directional", GrayLevel[0.3],      ImageScaled[{2, 2, 2}]}, {"Directional", RGBColor[      0.2590496, 0.151264, 0.24561480000000002`],      ImageScaled[{2, 0, 2}]}}, AbsoluteThickness[2]],
Directive[Specularity[GrayLevel[1], 6], RGBColor[   0.571589, 0.586483, 0.],   Lighting -> {{"Ambient", RGBColor[      0.36004492, 0.36421523999999994`, 0.2]}, {"Directional",      RGBColor[0.20005615, 0.20526904999999995`, 0.],      ImageScaled[{0, 2, 2}]}, {"Directional", RGBColor[      0.20005615, 0.20526904999999995`, 0.],      ImageScaled[{2, 2, 2}]}, {"Directional", RGBColor[      0.20005615, 0.20526904999999995`, 0.], ImageScaled[{2, 0, 2}]}},   AbsoluteThickness[2]]


text:
Q: Linux .NET remote debugging from Visual Studio I would like to remote debug a C# console application running on Linux from Visual Studio. Here's what I found so far:
http://www.mono-project.com/Debugger

The Mono runtime implements a debugging interface that allows
  debuggers and IDEs to debug managed code. This is called the Soft
  Debugger and is supported by both MonoDevelop, Xamarin Studio and
  Visual Studio (when the appropriate plugins are installed) as well as
  the command line SDB client.
Mono provides an API to communicate with the debugger and create your
  own debugging UIs via the Mono.Debugger.Soft.dll assembly.

The page below discusses some issues of the current MonoVS debugger implementation, but they are all fine with me.
http://mono-project.com/Visual_Studio_Integration
The page also links to the Getting started guide for MonoVS:
http://mono-project.com/GettingStartedWithMonoVS
Which contains a download link for MonoTools:
http://mono-tools.com/download/
However, the download link now redirects to:
http://xamarin.com/download/
Where I'm offered to download Xamarin Studio Starter Edition. Clicking the Pricing link I see that I need at least the Business edition for Visual Studio Support, at $999 per year. Well, no thank you.
This is where I'm stuck. Some specifics of my environment:
Development environment:

*

*Windows 7 64-bit

*Visual Studio Pro 2013 (might use 2010 if that works better)

Target environment:

*

*Raspberry Pi

*Raspbian Wheezy

*Mono 3.2.8

*Running console application over SSH

A: I found this guide explaining how to perform remote debugging on Linux, from Windows, using Xamarin Studio which is now free except for iOS & Android development. I've expanded it with fixes for the problems I encountered while testing it on a Raspberry Pi Zero W running Raspbian Jessie Lite (2017-04-10).

*

*Download and install Xamarin Studio, GTK# for .NET and .NET Framework 4.6.2. Xamarin Studio requires .NET 4.5 but GTK# requires .NET 4.6. I used Xamarin Studio version 6.1.2 (build 44) and GTK# version 2.12.44.

*I installed Xamarin Studio on a virtual machine different from my VS2015 machine, so I needed to download and install MSBuild Tools 2013 and MSBuild Tools 2015 as well.

*Create an environment variable MONODEVELOP_SDB_TEST = 1 (My Computer -> Properties -> Advanced System Settings -> Environment Variables).

*Start Xamarin Studio. If no window is shown, check the log files in the folder %localappdata%\XamarinStudio-6.0\Logs to see what failed.

*I created a .NET 4.6 Console Application in Visual Studio 2015 and added the NuGet package Mono.Unofficial.pdb2mdb, I used version 4.2.3.4. The package  Mono.pdb2mdb version 0.1.0.20130128 does not seem to work with assemblies built by VS2015 (PdbDebugException: Unknown custom metadata item kind: 6).

*Load the .sln or .csproj file from Visual Studio into Xamarin Studio. Build the solution and use the pdb2mdb tool from the NuGet packages folder to create a .mdb file: pdb2mdb MyProgram.exe

*I used WinSCP to copy MyProgram.exe and MyProgram.exe.mdb to my Raspberry Pi.

*I logged in with Putty using SSH and installed Mono version 3.2.8 on the Pi: sudo apt-get install mono-complete.

*Start the Mono runtime with debugger flags: mono --debug --debugger-agent=transport=dt_socket,address=0.0.0.0:12345,server=y /path/to/MyProgram.exe. This will start the program but halt execution until the Xamarin Studio debugger has connected.

*Set a breakpoint in Xamarin Studio and select the menu item Run -> Run with -> Custom Configuration... and select Run Action = Debug - Custom Command Mono Soft Debugger. Click Debug.

*Fill in the IP and Port fields with the IP address of your linux system and port 12345 as specified in the Mono command line. Click Connect and execution will begin, stopping at the breakpoint set.

It is possible to set conditional breakpoints, step into/out of/over code, watch primitives and objects etc and it's quite fast as well. I'd rather debug directly from Visual Studio, but this seems like a fully working solution.

A: I have finally found a good way to perform remote debugging of C# code running on my Raspberry Pi. I have switched from Mono to .NET Core and can now use Visual Studio to debug code running on the Raspberry Pi almost as easy as when running on my development machine.
The following steps were tested using Windows 10 version 1909, Visual Studio 2019 version 16.4.3, Raspbian Buster Lite version 2020-02-13 and a Raspberry Pi 2 Model B. .NET Core requires an ARMv7 CPU, so it will not run on Raspberry Pi 1 and Zero.

*

*Go to https://dotnet.microsoft.com/download/dotnet-core and select .NET Core 3.1 (or later). Click the link for Linux ARM32 runtime binaries and copy the direct link displayed on the next page. (Do not right-click the ARM32 link and select copy link address, as you will end up with a webpage if you download that link.)

*Open a SSH session to the Raspberry Pi, download and install the binaries:
ssh pi@192.168.0.xxx
wget https://download.visualstudio.microsoft.com/download/pr/c11e9248-404f-4e5b-bd99-175079419d6f/83902a43e06f9fb4e45a4c6a6d5afc0b/dotnet-runtime-3.1.3-linux-arm.tar.gz
sudo mkdir /opt/dotnet
sudo tar zxf dotnet-runtime-3.1.3-linux-arm.tar.gz -C /opt/dotnet
sudo ln -s /opt/dotnet/dotnet /usr/bin/dotnet

*Add the following line to ~/.bashrc, logout and login again to activate:
export DOTNET_ROOT=/opt/dotnet

*Check that .NET Core has been installed correctly:
dotnet --info

*Create a *.NET Core Console App```lang-none in Visual Studio. Set Target framework = .NET Core 3.1 (or the version you downloaded to the Raspberry Pi). Make sure that Project → Properties → Build → Output → Advanced → Debugging information = Portable.

*Build the project in Visual Studio and copy all *.dll, *.pdb, *.deps.json and *.runtimeconfig.json files from the development machine to the Pi. PuTTY's pscp command can be used:
cd bin\Debug\netcoreapp3.1
pscp -pw <password> *.dll *.pdb *.deps.json *.runtimeconfig.json pi@192.168.0.xxx:/home/pi

*Open a SSH session to the Raspberry Pi and run the program, or start it from the development machine using SSH:
ssh pi@192.168.0.xxx dotnet /home/pi/MyProgram.dll

*Attach to the remote process by selecting the Debug → Attach to Process menu item in Visual Studio. Select Connection type = SSH and in the Connection target textbox, type pi@192.168.0.xxx and press Enter.

*Enter password and click the Connect button.

*Click the Select button.

*Select Managed (.NET Core for Unix) and click the OK button.

*Select the dotnet MyProgram.dll process and click the Attach button. The first connection might take several minutes, but subsequent connections are much faster.
Enjoy setting breakpoints, adding watches, stepping through code and even using "Set Next Statement" - almost as fast as when debugging on the local machine. The only thing I'm missing so far is Edit and Continue, but not enough to investigate if it is possible to achieve.

A: I found this Visual Studio 2015 extension which works like a charm: MonoRemoteDebugger for Visual Studio 2015
See MonoRemoteDebugger v1.0.4 to fix conflict with Xamarin Visual Studio extension on Visual Studio 2015 update2.

A: The solution that you need is coming this year with MonoDebugger.NET. The developer(s) "promises" that we can deploy to any Mono device, and debug it within Visual Studio (2010 to 2015).

A: Building on Gutemberg Ribeiro's answer, I managed to get MonoRemoteDebugger working with VS2015 on a Raspberry Pi Zero W running Raspbian Jessie Lite (2017-04-10). The trick was to install a Mono version later than 3.2.8:

*

*Install the MonoRemoteDebugger Visual Studio extension, I used version 1.2.0.

*Create a .NET 4.6 Console Application in Visual Studio.

*If an older Mono version has been installed on the Raspberry Pi, remove it using the commands:

sudo apt-get purge mono-complete
sudo apt-get autoremove

*Install Mono version 4.0.2:

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
echo "deb http://plugwash.raspbian.org/mono4 jessie-mono4 main" | sudo tee -a /etc/apt/sources.list
sudo apt-get update
sudo apt-get install mono-complete

*Install MonoRemoteDebugger server:

wget https://github.com/techl/MonoRemoteDebugger/releases/download/v1.2.0/MonoRemoteDebugger.Server.zip
unzip -d MonoRemoteDebugger.Server MonoRemoteDebugger.Server.zip

*Start MonoRemoteDebugger server:

mono MonoRemoteDebugger.Server/MonoRemoteDebugger.Server.exe

*Set a breakpoint in Visual Studio and select the menu item MonoRemoteDebugger -> Debug with Mono (remote) in Visual Studio.

*Set Remote-IP to the IP address of the Raspberry Pi and click Connect. MonoRemoteDebugger will compile and transfer the program to the Raspberry Pi. No need to run pdb2mdb manually, the .mdb file will be created by the MonoRemoreDebugger server.

To be honest, the debugging capabilities are quite limited. Simple breakpoints and step into/out of/over code seems to work somewhat ok. Setting a breakpoint in a function and then stepping over that function call will not stop at the breakpoint.
Primitive types can be watched, but the objects I tried to watch can not be displayed. The Call Stack view is quite limited and the Threads view is empty. Exceptions are not catched but causes an "[ERROR] FATAL UNHANDLED EXCEPTION" message from the MonoRemoteDebuggerServer. But if you can live with these limitations, the setup is simpler than the Xamarin Studio route.

A: There is a plugin for Xamarin Studio/MonoDevelop
https://github.com/logicethos/SSHDebugger


text:
Q: Simulating clicks, focus, and data entry by JAVASCRIPT (ONLY && incl. jQuery if required) such that the website thinks it's an actual human operator? Is there a way to simulate user clicks, focus, and data entry on a website by JAVASCRIPT (ONLY && including jQuery if required) such that the website truly believes that it is an actual human operator at work?
I do not want to use a third party software and I have already tried the following methods to no avail:

*

*jQuery's $('#input-field').click()

*var press = $.Event("keypress");
        press.bubbles = true;
        press.cancelable = true;
        press.charCode = 97;
        press.currentTarget = $("#_eo_ctl00_ContentPlaceHolder1_XX")[0];
        press.eventPhase = 2;
        press.keyCode = 97;
        press.returnValue = true;
        press.srcElement = $("#_eo_ctl00_ContentPlaceHolder1_XX")[0];
        press.target = $("#_eo_ctl00_ContentPlaceHolder1_XX")[0];
        press.type = "keypress";
        press.view = Window;
        press.which = 97;
        press

*$("#_eo_ctl00_ContentPlaceHolder1_XX").mousedown(function() {  console.log("mousedown"); })
                  .mouseup(function() { console.log("mouseup"); })
                  .click(function() { console.log("click"); return false; });
3.1
$('#_eo_ctl00_ContentPlaceHolder1_XX').val('18/04/2014');

3.2 $('#_eo_ctl00_ContentPlaceHolder1_XX').trigger('blur');

*

*function eventFire(el, etype){
          if (el.fireEvent) {
            (el.fireEvent('on' + etype));
          } else {
            var evObj = document.createEvent('Events');
            evObj.initEvent(etype, true, false);
            el.dispatchEvent(evObj);
          }
        }eventFire(document.getElementById('_eo_ctl00_ContentPlaceHolder1_XX'),'click')
Thanks :-)


text:
Q: jest.config.ts: "registerer.enabled is not a function" error when running jest from Github Actions When running jest locally, it instantiates my app and runs tests without any issues.
When running jest inside github actions, I'm getting this error:
Error: Jest: Failed to parse the TypeScript config file /home/runner/work/myproject/myproject/jest.config.ts

TypeError: registerer.enabled is not a function
    at readConfigFileAndSetRootDir (/home/runner/work/myproject/myproject/node_modules/@jest/core/node_modules/jest-config/build/readConfigFileAndSetRootDir.js:118:13)

the package.json script entry is just:"test": "jest"
and the jest.config.ts file is:
import tsJestUtils from 'ts-jest/utils'
import tsConf from './tsconfig.json'

const rootDir = __dirname
const { pathsToModuleNameMapper } = tsJestUtils
const {
  compilerOptions: { paths },
} = tsConf

const config = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  roots: [`${rootDir}/src`],
  transform: {
    '^.+\\.tsx?$': 'ts-jest',
  },
  moduleNameMapper: pathsToModuleNameMapper(paths, {
    prefix: `${rootDir}/src`,
  }),
}

export default config

A: So I just bypassed use of typescript for my jest config entirely, and went with an equivalent jest.config.js file based on the docs. Works in Github Actions now, runner does not fail! \o/

I am still not sure what the issue was, but I think ts-node just wasn't processing the config file properly. I feel like the actual failure was with the attempt to load a .ts config file, specifically at this point in the source code when it tries to call registerer.enabled().

A: It can be fixed by upgrading to "ts-node": "^8.5.0"