Just add the <mat-icon>
inside mat-button
or mat-raised-button
. See the example below. Note that I am using material icon instead of your svg for demo purpose:
<button mat-button>
<mat-icon>mic</mat-icon>
Start Recording
</button>
OR
<button mat-raised-button color="accent">
<mat-icon>mic</mat-icon>
Start Recording
</button>
Here is a link to stackblitz demo.
the problem is in the MatInputModule:
exports: [
MatInputModule
]
I had this issue. I imported MatFormFieldModule
at my main module, but forgot to add MatInputModule
to the imports
array, like so:
import { MatFormFieldModule, MatInputModule } from '@angular/material';
@NgModule({
imports: [
MatFormFieldModule,
MatInputModule
]
})
export class AppModule { }
More info here.
I had a similar issue and solved after running these instructions!
npm install npm -g
npm install --save-dev @angular/cli@latest
npm install
npm start
setForeground
is added in API level 23. Leverage the power of RevealAnimator
in case u need to relay on foreground
property !
<View
android:id="@+id/circular_reveal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/primaryMilk_22"
android:elevation="@dimen/margin_20"
android:visibility="invisible" />
With kotlin ext function, it's way osm !
fun View.circularReveal() {
val cx: Int = width / 2
val cy: Int = height / 2
val finalRadius: Int =
width.coerceAtLeast(height)
val anim: Animator = ViewAnimationUtils.createCircularReveal(
this,
cx,
cy,
0f,
finalRadius.toFloat()
)
anim.interpolator = AccelerateDecelerateInterpolator()
anim.duration = 400
isVisible = true
anim.start()
anim.doOnEnd {
isVisible = false
}
}
For TypeScript users:
toggle(event: Event): void {
let elementId: string = (event.target as Element).id;
// do something with the id...
}
I had a similar problem but in my case some line had the value NULL.
so first I update the table:
update `my_table`set modified = '1000-01-01 00:00:00' WHERE modified is null
problem solved, at least in my case.
for circle ripple :
android:background="?attr/selectableItemBackgroundBorderless"
for rectangle ripple :
android:background="?attr/selectableItemBackground"
This is a general answer for future visitors. The various ways to update the adapter data are explained. The process includes two main steps every time:
#Insert single item
Add "Pig" at index 2
.
String item = "Pig";
int insertIndex = 2;
data.add(insertIndex, item);
adapter.notifyItemInserted(insertIndex);
#Insert multiple items
Insert three more animals at index 2
.
ArrayList<String> items = new ArrayList<>();
items.add("Pig");
items.add("Chicken");
items.add("Dog");
int insertIndex = 2;
data.addAll(insertIndex, items);
adapter.notifyItemRangeInserted(insertIndex, items.size());
#Remove a single item
Remove "Pig" from the list.
int removeIndex = 2;
data.remove(removeIndex);
adapter.notifyItemRemoved(removeIndex);
#Remove multiple items
Remove "Camel" and "Sheep" from the list.
int startIndex = 2; // inclusive
int endIndex = 4; // exclusive
int count = endIndex - startIndex; // 2 items will be removed
data.subList(startIndex, endIndex).clear();
adapter.notifyItemRangeRemoved(startIndex, count);
#Remove all items
Clear the whole list.
data.clear();
adapter.notifyDataSetChanged();
#Replace old list with the new list
Clear the old list then add a new one.
// clear old list
data.clear();
// add new list
ArrayList<String> newList = new ArrayList<>();
newList.add("Lion");
newList.add("Wolf");
newList.add("Bear");
data.addAll(newList);
// notify adapter
adapter.notifyDataSetChanged();
The adapter
has a reference to data
, so it is important that I didn't set data
to a new object. Instead, I cleared the old items from data
and then added the new ones.
#Update single item
Change the "Sheep" item so that it says "I like sheep."
String newValue = "I like sheep.";
int updateIndex = 3;
data.set(updateIndex, newValue);
adapter.notifyItemChanged(updateIndex);
#Move single item
Move "Sheep" from position 3
to position 1
.
int fromPosition = 3;
int toPosition = 1;
// update data array
String item = data.get(fromPosition);
data.remove(fromPosition);
data.add(toPosition, item);
// notify adapter
adapter.notifyItemMoved(fromPosition, toPosition);
#Code
Here is the project code for your reference. The RecyclerView Adapter code can be found at this answer.
MainActivity.java
public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {
List<String> data;
MyRecyclerViewAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// data to populate the RecyclerView with
data = new ArrayList<>();
data.add("Horse");
data.add("Cow");
data.add("Camel");
data.add("Sheep");
data.add("Goat");
// set up the RecyclerView
RecyclerView recyclerView = findViewById(R.id.rvAnimals);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
layoutManager.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);
adapter = new MyRecyclerViewAdapter(this, data);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}
@Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
}
public void onButtonClick(View view) {
insertSingleItem();
}
private void insertSingleItem() {
String item = "Pig";
int insertIndex = 2;
data.add(insertIndex, item);
adapter.notifyItemInserted(insertIndex);
}
private void insertMultipleItems() {
ArrayList<String> items = new ArrayList<>();
items.add("Pig");
items.add("Chicken");
items.add("Dog");
int insertIndex = 2;
data.addAll(insertIndex, items);
adapter.notifyItemRangeInserted(insertIndex, items.size());
}
private void removeSingleItem() {
int removeIndex = 2;
data.remove(removeIndex);
adapter.notifyItemRemoved(removeIndex);
}
private void removeMultipleItems() {
int startIndex = 2; // inclusive
int endIndex = 4; // exclusive
int count = endIndex - startIndex; // 2 items will be removed
data.subList(startIndex, endIndex).clear();
adapter.notifyItemRangeRemoved(startIndex, count);
}
private void removeAllItems() {
data.clear();
adapter.notifyDataSetChanged();
}
private void replaceOldListWithNewList() {
// clear old list
data.clear();
// add new list
ArrayList<String> newList = new ArrayList<>();
newList.add("Lion");
newList.add("Wolf");
newList.add("Bear");
data.addAll(newList);
// notify adapter
adapter.notifyDataSetChanged();
}
private void updateSingleItem() {
String newValue = "I like sheep.";
int updateIndex = 3;
data.set(updateIndex, newValue);
adapter.notifyItemChanged(updateIndex);
}
private void moveSingleItem() {
int fromPosition = 3;
int toPosition = 1;
// update data array
String item = data.get(fromPosition);
data.remove(fromPosition);
data.add(toPosition, item);
// notify adapter
adapter.notifyItemMoved(fromPosition, toPosition);
}
}
#Notes
notifyDataSetChanged()
, then no animation will be performed. This can also be an expensive operation, so it is not recommended to use notifyDataSetChanged()
if you are only updating a single item or a range of items.#Further study
If you have a Floating Action Button with no drawable you can change the tint programmatically using:
fab.getBackground().mutate().setTint(ContextCompat.getColor(yourContext, R.color.anyColor));
As your content is 24dp x 24dp you should use 24dp icon. And then set android:scaleType="center"
in your ImageButton to avoid auto resize.
For those searching for a solution to the issue of the ripple effect not working on a programmatically created CardView (or in my case custom view which extends CardView) being shown in a RecyclerView, the following worked for me. Basically declaring the XML attributes mentioned in the other answers declaratively in the XML layout file doesn't seem to work for a programmatically created CardView, or one created from a custom layout (even if root view is CardView or merge element is used), so they have to be set programmatically like so:
private class MadeUpCardViewHolder extends RecyclerView.ViewHolder {
private MadeUpCardView cardView;
public MadeUpCardViewHolder(View v){
super(v);
this.cardView = (MadeUpCardView)v;
// Declaring in XML Layout doesn't seem to work in RecyclerViews
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int[] attrs = new int[]{R.attr.selectableItemBackground};
TypedArray typedArray = context.obtainStyledAttributes(attrs);
int selectableItemBackground = typedArray.getResourceId(0, 0);
typedArray.recycle();
this.cardView.setForeground(context.getDrawable(selectableItemBackground));
this.cardView.setClickable(true);
}
}
}
Where MadeupCardView extends CardView
Kudos to this answer for the TypedArray
part.
Programmatically applying the colors:
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
ColorStateList colorStateListRipple = new ColorStateList(
new int[][] {{0}},
new int[] {Color.WHITE} // ripple color
);
RippleDrawable rippleDrawable = (RippleDrawable) myButton.getBackground();
rippleDrawable.setColor(colorStateListRipple);
myButton.setBackground(rippleDrawable); // applying the ripple color
}
ColorStateList colorStateList = new ColorStateList(
new int[][]{
new int[]{android.R.attr.state_pressed}, // when pressed
new int[]{android.R.attr.state_enabled}, // normal state color
new int[]{} // normal state color
},
new int[]{
Color.CYAN, // when pressed
Color.RED, // normal state color
Color.RED // normal state color
}
);
ViewCompat.setBackgroundTintList(myButton, colorStateList); // applying the state colors
I made a simple class that makes ripple buttons, i never needed it in the end so its not the best, But here it is:
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Button;
public class RippleView extends Button
{
private float duration = 250;
private float speed = 1;
private float radius = 0;
private Paint paint = new Paint();
private float endRadius = 0;
private float rippleX = 0;
private float rippleY = 0;
private int width = 0;
private int height = 0;
private OnClickListener clickListener = null;
private Handler handler;
private int touchAction;
private RippleView thisRippleView = this;
public RippleView(Context context)
{
this(context, null, 0);
}
public RippleView(Context context, AttributeSet attrs)
{
this(context, attrs, 0);
}
public RippleView(Context context, AttributeSet attrs, int defStyleAttr)
{
super(context, attrs, defStyleAttr);
init();
}
private void init()
{
if (isInEditMode())
return;
handler = new Handler();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
paint.setAntiAlias(true);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
super.onSizeChanged(w, h, oldw, oldh);
width = w;
height = h;
}
@Override
protected void onDraw(@NonNull Canvas canvas)
{
super.onDraw(canvas);
if(radius > 0 && radius < endRadius)
{
canvas.drawCircle(rippleX, rippleY, radius, paint);
if(touchAction == MotionEvent.ACTION_UP)
invalidate();
}
}
@Override
public boolean onTouchEvent(@NonNull MotionEvent event)
{
rippleX = event.getX();
rippleY = event.getY();
switch(event.getAction())
{
case MotionEvent.ACTION_UP:
{
getParent().requestDisallowInterceptTouchEvent(false);
touchAction = MotionEvent.ACTION_UP;
radius = 1;
endRadius = Math.max(Math.max(Math.max(width - rippleX, rippleX), rippleY), height - rippleY);
speed = endRadius / duration * 10;
handler.postDelayed(new Runnable()
{
@Override
public void run()
{
if(radius < endRadius)
{
radius += speed;
paint.setAlpha(90 - (int) (radius / endRadius * 90));
handler.postDelayed(this, 1);
}
else
{
clickListener.onClick(thisRippleView);
}
}
}, 10);
invalidate();
break;
}
case MotionEvent.ACTION_CANCEL:
{
getParent().requestDisallowInterceptTouchEvent(false);
touchAction = MotionEvent.ACTION_CANCEL;
radius = 0;
invalidate();
break;
}
case MotionEvent.ACTION_DOWN:
{
getParent().requestDisallowInterceptTouchEvent(true);
touchAction = MotionEvent.ACTION_UP;
endRadius = Math.max(Math.max(Math.max(width - rippleX, rippleX), rippleY), height - rippleY);
paint.setAlpha(90);
radius = endRadius/4;
invalidate();
return true;
}
case MotionEvent.ACTION_MOVE:
{
if(rippleX < 0 || rippleX > width || rippleY < 0 || rippleY > height)
{
getParent().requestDisallowInterceptTouchEvent(false);
touchAction = MotionEvent.ACTION_CANCEL;
radius = 0;
invalidate();
break;
}
else
{
touchAction = MotionEvent.ACTION_MOVE;
invalidate();
return true;
}
}
}
return false;
}
@Override
public void setOnClickListener(OnClickListener l)
{
clickListener = l;
}
}
EDIT
Since many people are looking for something like this i made a class that can make other views have the ripple effect:
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
public class RippleViewCreator extends FrameLayout
{
private float duration = 150;
private int frameRate = 15;
private float speed = 1;
private float radius = 0;
private Paint paint = new Paint();
private float endRadius = 0;
private float rippleX = 0;
private float rippleY = 0;
private int width = 0;
private int height = 0;
private Handler handler = new Handler();
private int touchAction;
public RippleViewCreator(Context context)
{
this(context, null, 0);
}
public RippleViewCreator(Context context, AttributeSet attrs)
{
this(context, attrs, 0);
}
public RippleViewCreator(Context context, AttributeSet attrs, int defStyleAttr)
{
super(context, attrs, defStyleAttr);
init();
}
private void init()
{
if (isInEditMode())
return;
paint.setStyle(Paint.Style.FILL);
paint.setColor(getResources().getColor(R.color.control_highlight_color));
paint.setAntiAlias(true);
setWillNotDraw(true);
setDrawingCacheEnabled(true);
setClickable(true);
}
public static void addRippleToView(View v)
{
ViewGroup parent = (ViewGroup)v.getParent();
int index = -1;
if(parent != null)
{
index = parent.indexOfChild(v);
parent.removeView(v);
}
RippleViewCreator rippleViewCreator = new RippleViewCreator(v.getContext());
rippleViewCreator.setLayoutParams(v.getLayoutParams());
if(index == -1)
parent.addView(rippleViewCreator, index);
else
parent.addView(rippleViewCreator);
rippleViewCreator.addView(v);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
super.onSizeChanged(w, h, oldw, oldh);
width = w;
height = h;
}
@Override
protected void dispatchDraw(@NonNull Canvas canvas)
{
super.dispatchDraw(canvas);
if(radius > 0 && radius < endRadius)
{
canvas.drawCircle(rippleX, rippleY, radius, paint);
if(touchAction == MotionEvent.ACTION_UP)
invalidate();
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event)
{
return true;
}
@Override
public boolean onTouchEvent(@NonNull MotionEvent event)
{
rippleX = event.getX();
rippleY = event.getY();
touchAction = event.getAction();
switch(event.getAction())
{
case MotionEvent.ACTION_UP:
{
getParent().requestDisallowInterceptTouchEvent(false);
radius = 1;
endRadius = Math.max(Math.max(Math.max(width - rippleX, rippleX), rippleY), height - rippleY);
speed = endRadius / duration * frameRate;
handler.postDelayed(new Runnable()
{
@Override
public void run()
{
if(radius < endRadius)
{
radius += speed;
paint.setAlpha(90 - (int) (radius / endRadius * 90));
handler.postDelayed(this, frameRate);
}
else if(getChildAt(0) != null)
{
getChildAt(0).performClick();
}
}
}, frameRate);
break;
}
case MotionEvent.ACTION_CANCEL:
{
getParent().requestDisallowInterceptTouchEvent(false);
break;
}
case MotionEvent.ACTION_DOWN:
{
getParent().requestDisallowInterceptTouchEvent(true);
endRadius = Math.max(Math.max(Math.max(width - rippleX, rippleX), rippleY), height - rippleY);
paint.setAlpha(90);
radius = endRadius/3;
invalidate();
return true;
}
case MotionEvent.ACTION_MOVE:
{
if(rippleX < 0 || rippleX > width || rippleY < 0 || rippleY > height)
{
getParent().requestDisallowInterceptTouchEvent(false);
touchAction = MotionEvent.ACTION_CANCEL;
break;
}
else
{
invalidate();
return true;
}
}
}
invalidate();
return false;
}
@Override
public final void addView(@NonNull View child, int index, ViewGroup.LayoutParams params)
{
//limit one view
if (getChildCount() > 0)
{
throw new IllegalStateException(this.getClass().toString()+" can only have one child.");
}
super.addView(child, index, params);
}
}
For socket.io version 1.4.5:
On server:
socket.on('end', function (){
socket.disconnect(0);
});
On client:
var io = io();
io.emit('end');
I had this problem after enabling a new service API on the Google console and trying to use the previously made credentials.
To fix the problem, I had to go back to the credential page, clicking on the credential name, and clicking "Save" again. After that, I could authenticate just fine.
To add to the other answers, I think the acronyms were derived to show a scale between the two terms to distinguish how reliable transactions or requests where between RDMS versus Big Data.
From this article acid vs base
In Chemistry, pH measures the relative basicity and acidity of an aqueous (solvent in water) solution. The pH scale extends from 0 (highly acidic substances such as battery acid) to 14 (highly alkaline substances like lie); pure water at 77° F (25° C) has a pH of 7 and is neutral.
Data engineers have cleverly borrowed acid vs base from chemists and created acronyms that while not exact in their meanings, are still apt representations of what is happening within a given database system when discussing the reliability of transaction processing.
One other point, since I work with Big Data using Elasticsearch. To clarify, an instance of Elasticsearch is a node and a group of nodes form a cluster.
To me from a practical standpoint, BA (Basically Available), in this context, has the idea of multiple master nodes to handle the Elasticsearch cluster and it's operations.
If you have 3 master nodes and the currently directing master node goes down, the system stays up, albeit in a less efficient state, and another master node takes its place as the main directing master node. If two master nodes go down, the system still stays up and the last master node takes over.
Flash still has the ASO file, which is the compiled byte code for your classes. On Windows, you can see the ASO files here:
C:\Documents and Settings\username\Local Settings\Application Data\Adobe\Flash CS4\en\Configuration\Classes\aso
On a Mac, the directory structure is similar in /Users/username/Library/Application Support/
You can remove those files by hand, or in Flash you can select Control->Delete ASO files
to remove them.
VBA stands for Visual Basic For Applications and its a Visual Basic implementation intended to be used in the Office Suite.
The difference between them is that VBA is embedded inside Office documents (its an Office feature). VB is the ide/language for developing applications.
When a class implements an interface,it is creating instance for the interface members. While a static type doesnt have an instance,there is no point in having static signatures in an interface.
Note: this is not an answer because I could not find a solution. But I think the information may be useful for others (and it wouldn't be practical as a comment). I have tried all of the steps detailed in the various docs but I could not get Android Emulator to work on my AMD Ryzen 7 :(
Most answers work only for Intel CPUs. If you have an AMD CPU (like me, an AMD Ryzen 7) you need to know about some restrictions and you have to use WHPX instead of HAXM.
I found this on MS's site: Because the Android emulator currently supports AMD hardware acceleration only on Linux, hardware acceleration is not available for AMD-based computers running Windows.
Fortunatelly there is a way to make it work but configuring hardware acceleration for an AMD CPU is a bit more complex:
Requirements and recommendations: - AMD CPU recommendation: AMD Ryzen CPU - Android Studio 3.2 Beta 1 or higher - Android Emulator version 27.3.8 or higher - Windows 10 with April 2018 Update or higher
To use WHPX acceleration on Windows, you must enable the Windows Hypervisor Platform option in the Turn Windows features on or off dialog box. For changes to this option to take effect, restart your computer.
Additionally, the following changes must be made in the BIOS settings: - AMD CPU: Virtualization or SVM must be enabled.
Note that there are further restrictions as well:
- You can't run a VM-accelerated emulator inside another VM, such as a VM hosted by VirtualBox, VMWare, or Docker. You must run the emulator directly on your system hardware.
- You can't run software that uses another virtualization technology at the same time that you run the accelerated emulator. For example, VirtualBox, VMWare, and Docker currently use a different virtualization technology, so you can't run them at the same time as the accelerated emulator.
Some more info: Android Emulator - AMD Processor & Hyper-V Support
This recommendation did not help either:
Please note: More recent versions of the emulator (27.2.8, 27.3.0, or later), require an emulator flag while the feature is in the preview. To do this, create or edit the file C:\Users\.android\advancedFeatures.ini and add the line “WindowsHypervisorPlatform = on”, or start the emulator from the command line with “-feature WindowsHypervisorPlatform”.
You can use:
$('#table').dataTable().fnClearTable();
$('#table').dataTable().fnAddData(myData2);
Update. And yes current documentation is not so good but if you are okay using older versions you can refer legacy documentation.
~dp0
: d=drive, p=path, %0=full path\name of this batch-file.
cd /d %~dp0
will change the path to the same, where the batch file resides.
See for /?
or call /
for more details about the %~...
modifiers.
See cd /?
about the /d
switch.
we can use \b as a word boundary and then; \b\d+\b
Simply create a Class Name and define your style there like this :
table.tdfont td {
font-size: 0.9em;
}
The difference between echo, print, print_r and var_dump is very simple.
echo
echo is actually not a function but a language construct which is used to print output. It is marginally faster than the print.
echo "Hello World"; // this will print Hello World
echo "Hello ","World"; // Multiple arguments - this will print Hello World
$var_1=55;
echo "$var_1"; // this will print 55
echo "var_1=".$var_1; // this will print var_1=55
echo 45+$var_1; // this will print 100
$var_2="PHP";
echo "$var_2"; // this will print PHP
$var_3=array(99,98,97) // Arrays are not possible with echo (loop or index value required)
$var_4=array("P"=>"3","J"=>"4"); // Arrays are not possible with echo (loop or index value required)
You can also use echo statement with or without parenthese
echo ("Hello World"); // this will print Hello World
Just like echo construct print is also a language construct and not a real function. The differences between echo and print is that print only accepts a single argument and print always returns 1. Whereas echo has no return value. So print statement can be used in expressions.
print "Hello World"; // this will print Hello World
print "Hello ","World"; // Multiple arguments - NOT POSSIBLE with print
$var_1=55;
print "$var_1"; // this will print 55
print "var_1=".$var_1; // this will print var_1=55
print 45+$var_1; // this will print 100
$var_2="PHP";
print "$var_2"; // this will print PHP
$var_3=array(99,98,97) // Arrays are not possible with print (loop or index value required)
$var_4=array("P"=>"3","J"=>"4"); // Arrays are not possible with print (loop or index value required)
Just like echo, print can be used with or without parentheses.
print ("Hello World"); // this will print Hello World
print_r
The print_r() function is used to print human-readable information about a variable. If the argument is an array, print_r() function prints its keys and elements (same for objects).
print_r ("Hello World"); // this will print Hello World
$var_1=55;
print_r ("$var_1"); // this will print 55
print_r ("var_1=".$var_1); // this will print var_1=55
print_r (45+$var_1); // this will print 100
$var_2="PHP";
print_r ("$var_2"); // this will print PHP
$var_3=array(99,98,97) // this will print Array ( [0] => 1 [1] => 2 [2] => 3 )
$var_4=array("P"=>"3","J"=>"4"); // this will print Array ( [P] => 3 [J] => 4 )
var_dump
var_dump function usually used for debugging and prints the information ( type and value) about a variable/array/object.
var_dump($var_1); // this will print int(5444)
var_dump($var_2); // this will print string(5) "Hello"
var_dump($var_3); // this will print array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) }
var_dump($var_4); // this will print array(2) { ["P"]=> string(1) "3" ["J"]=> string(1) "4" }
To change the connect mode selection try Settings -> Wireless & Networks -> USB Connection. You can shoose to Charging, Mass Storage, Tethered, and ask on connection.
This feature has been added in dplyr v0.3. You can now pass a named character vector to the by
argument in left_join
(and other joining functions) to specify which columns to join on in each data frame. With the example given in the original question, the code would be:
left_join(test_data, kantrowitz, by = c("first_name" = "name"))
Here is my understanding of it so far, in case it helps someone.
core.autocrlf=true
and core.safecrlf = true
You have a repository where all the line endings are the same, but you work on different platforms. Git will make sure your lines endings are converted to the default for your platform. Why does this matter? Let's say you create a new file. The text editor on your platform will use its default line endings. When you check it in, if you don't have core.autocrlf set to true, you've introduced a line ending inconsistency for someone on a platform that defaults to a different line ending. I always set safecrlf too because I would like to know that the crlf operation is reversible. With these two settings, git is modifying your files, but it verifies that the modifications are reversible.
core.autocrlf=false
You have a repository that already has mixed line endings checked in and fixing the incorrect line endings could break other things. Its best not to tell git to convert line endings in this case, because then it will exacerbate the problem it was designed to solve - making diffs easier to read and merges less painful. With this setting, git doesn't modify your files.
core.autocrlf=input
I don't use this because the reason for this is to cover a use case where you created a file that has CRLF line endings on a platform that defaults to LF line endings. I prefer instead to make my text editor always save new files with the platform's line ending defaults.
Neither <iostream>
nor <iostream.h>
are standard C header files. Your code is meant to be C++, where <iostream>
is a valid header. Use g++
(and a .cpp
file extension) for C++ code.
Alternatively, this program uses mostly constructs that are available in C anyway. It's easy enough to convert the entire program to compile using a C compiler. Simply remove #include <iostream>
and using namespace std;
, and replace cout << endl;
with putchar('\n');
... I advise compiling using C99 (eg. gcc -std=c99
)
Gosh, NO!!! You're asking for a world of hurt if you store formatted dates in SQL Server. Always store your dates and times and one of the SQL Server "date/time" datatypes (DATETIME, DATE, TIME, DATETIME2, whatever). Let the front end code resolve the method of display and only store formatted dates when you're building a staging table to build a file from. If you absolutely must display ISO date/time formats from SQL Server, only do it at display time. I can't emphasize enough... do NOT store formatted dates/times in SQL Server.
{Edit}. The reasons for this are many but the most obvious are that, even with a nice ISO format (which is sortable), all future date calculations and searches (search for all rows in a given month, for example) will require at least an implicit conversion (which takes extra time) and if the stored formatted date isn't the format that you currently need, you'll need to first convert it to a date and then to the format you want.
The same holds true for front end code. If you store a formatted date (which is text), it requires the same gyrations to display the local date format defined either by windows or the app.
My recommendation is to always store the date/time as a DATETIME or other temporal datatype and only format the date at display time.
NodeJs is a JavaScript based server, so you can do the way you do that in pure JavaScript...
Imagine you have this Json in NodeJs...
var details = '{ "name": "Alireza Dezfoolian", "netWorth": "$0" }';
var obj = JSON.parse(details);
And you can do above to get a parsed version of your json...
Try this without the code: (x-SQRT(x^2))/(2*x)
The code below removes remove grid lines from chart area only not the ones in x&y axis labels
Chart.defaults.scale.gridLines.drawOnChartArea = false;
First add your item to mItems
and then use:
mAdapter.notifyItemInserted(mItems.size() - 1);
this method is better than using:
mAdapter.notifyDataSetChanged();
in performance.
This is for Color
to Brush
....
you can't convert it, you have to make a new brush....
SolidColorBrush brush = new SolidColorBrush( myColor );
now, if you need it in XAML, you COULD make a custom value converter and use that in a binding
Through Programming:
btn.setBackgroundColor(getResources().getColor(R.color.colorOffWhite));
and your colors.xml must contain...
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorOffWhite">#80ffffff</color>
</resources>
EL expression:
${requestScope.Error_Message}
There are several implicit objects in JSP EL. See Expression Language under the "Implicit Objects" heading.
<Image Source="MyRessourceDir\images\addButton.png"/>
(?<!1\.2\.3\.4).*Has exploded
You need to run this with -P to have negative lookbehind (Perl regular expression), so the command is:
grep -P '(?<!1\.2\.3\.4).*Has exploded' test.log
Try this. It uses negative lookbehind to ignore the line if it is preceeded by 1.2.3.4
. Hope that helps!
You're running bundle exec
on a program. The program's creators wrote it when certain versions of gems were available. The program Gemfile specifies the versions of the gems the creators decided to use. That is, the script was made to run correctly against these gem versions.
Your system-wide Gemfile may differ from this Gemfile. You may have newer or older gems with which this script doesn't play nice. This difference in versions can give you weird errors.
bundle exec
helps you avoid these errors. It executes the script using the gems specified in the script's Gemfile rather than the systemwide Gemfile. It executes the certain gem versions with the magic of shell aliases.
See more on the man page.
Here's an example Gemfile:
source 'http://rubygems.org'
gem 'rails', '2.8.3'
Here, bundle exec
would execute the script using rails version 2.8.3 and not some other version you may have installed system-wide.
In Java 8:
Map<String, Long> counts =
list.stream().collect(Collectors.groupingBy(e -> e, Collectors.counting()));
Just to post a little addition to all the great answers so far: If you are using [innerHTML]
to render Angular components and are bummed about it not working like me, have a look at the ngx-dynamic-hooks library that I wrote to address this very issue.
With it, you can load components from dynamic strings/html without compromising security. It actually uses Angular's DOMSanitizer
just like [innerHTML]
does as well, but retains the ability to load components (in a safe manner).
See it in action in this Stackblitz.
You can't refer to a property of an object before you have initialized that object; use an external variable.
var key1 = "it";
var obj = {
key1 : key1,
key2 : key1 + " works!"
};
Also, this is not a "JSON object"; it is a Javascript object. JSON is a method of representing an object with a string (which happens to be valid Javascript code).
What worked for me was adding the position relative to the html tag.
html {
min-height:100%;
position:relative;
}
body {
margin-bottom:60px;
}
footer {
position:absolute;
bottom:0;
height:60px;
}
I would suggest separating your code based on the functionality and purpose specific to each sheet or module. In this manner, you would only put code relative to a sheet's UI inside the sheet's module and only put code related to modules in respective modules. Also, use separate modules to encapsulate code that is shared or reused among several different sheets.
For example, let's say you multiple sheets that are responsible for displaying data from a database in a special way. What kinds of functionality do we have in this situation? We have functionality related to each specific sheet, tasks related to getting data from the database, and tasks related to populating a sheet with data. In this case, I might start with a module for the data access, a module for populating a sheet with data, and within each sheet I'd have code for accessing code in those modules.
It might be laid out like this.
Module: DataAccess:
Function GetData(strTableName As String, strCondition1 As String) As Recordset
'Code Related to getting data from the database'
End Function
Module: PopulateSheet:
Sub PopulateASheet(wsSheet As Worksheet, rs As Recordset)
'Code to populate a worksheet '
End Function
Sheet: Sheet1 Code:
Sub GetDataAndPopulate()
'Sample Code'
Dim rs As New Recordset
Dim ws As Worksheet
Dim strParam As String
Set ws = ActiveSheet
strParam = ws.Range("A1").Value
Set rs = GetData("Orders",strParam)
PopulateASheet ws, rs
End Sub
Sub Button1_Click()
Call GetDataAndPopulate
End Sub
Others have already properly compared delete
with splice
.
Another interesting comparison is delete
versus undefined
: a deleted array item uses less memory than one that is just set to undefined
;
For example, this code will not finish:
let y = 1;
let ary = [];
console.log("Fatal Error Coming Soon");
while (y < 4294967295)
{
ary.push(y);
ary[y] = undefined;
y += 1;
}
console(ary.length);
It produces this error:
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory.
So, as you can see undefined
actually takes up heap memory.
However, if you also delete
the ary-item (instead of just setting it to undefined
), the code will slowly finish:
let x = 1;
let ary = [];
console.log("This will take a while, but it will eventually finish successfully.");
while (x < 4294967295)
{
ary.push(x);
ary[x] = undefined;
delete ary[x];
x += 1;
}
console.log(`Success, array-length: ${ary.length}.`);
These are extreme examples, but they make a point about delete
that I haven't seen anyone mention anywhere.
You can't really "launch an application" in the true sense. You can as you indicated ask the user to open a document (ie a PDF) and windows will attempt to use the default app for that file type. Many applications have a way to do this.
For example you can save RDP connections as a .rdp file. Putting a link on your site to something like this should allow the user to launch right into an RDP session:
<a href="MyServer1.rdp">Server 1</a>
Checkout this jquery window plugin: http://fstoke.me/jquery/window/
// create a window
sampleWnd = $.window({
.....
});
// resize the window by passed w,h parameter
sampleWnd.resize(screen.width, screen.height);
yes use \n, unless you are generating html code, in which you want to use <br />
work on all major browsers
html {
overflow: scroll;
overflow-x: hidden;
}
::-webkit-scrollbar {
width: 0px; /* Remove scrollbar space */
background: transparent; /* Optional: just make scrollbar invisible */
}
Decide a width and check how many characters one line could hold, and then for each key pressed you call a function that looks something like:
function changeHeight()
{
var chars_per_row = 100;
var pixles_per_row = 16;
this.style.height = Math.round((this.value.length / chars_per_row) * pixles_per_row) + 'px';
}
Havn't tested the code.
Switch in combination with variable variables will give you more flexibility:
<?php
$p = 'home'; //For testing
$p = ( strpos($p, 'users') !== false? 'users': $p);
switch ($p) {
default:
$varContainer = 'current_' . $p; //Stores the variable [$current_"xyORz"] into $varContainer
${$varContainer} = 'current'; //Sets the VALUE of [$current_"xyORz"] to 'current'
break;
}
//For testing
echo $current_home;
?>
To learn more, checkout variable variables and the examples I submitted to php manual:
Example 1: http://www.php.net/manual/en/language.variables.variable.php#105293
Example 2: http://www.php.net/manual/en/language.variables.variable.php#105282
PS: This example code is SMALL AND SIMPLE, just the way I like it. It's tested and works too
For Intellij 15, use the checkbox in File > Settings > Editor > General
option Show quick documentation on mouse move.
You can also get there by typing "quick" or something similar in the search box:
I would like to expand on Martin's answer there...
His solution is rather nice, but it can be tweaked so any "variable type" can be printed like that.(It's actually Value Type, more on the topic). That said, "tweaked" may be a strong word for this. Regardless, it may be helpful.
Martins Solution:
a.getClass().getName()
However, If you want it to work with anything you can do this:
((Object) myVar).getClass().getName()
//OR
((Object) myInt).getClass().getSimpleName()
In this case, the primitive will simply be wrapped in a Wrapper. You will get the Object of the primitive in that case.
I myself used it like this:
private static String nameOf(Object o) {
return o.getClass().getSimpleName();
}
Using Generics:
public static <T> String nameOf(T o) {
return o.getClass().getSimpleName();
}
I followed these steps (for Mac).
In /etc/ssh/sshd_config
change
#ChallengeResponseAuthentication yes
#PasswordAuthentication yes
to
ChallengeResponseAuthentication no
PasswordAuthentication no
Now generate the RSA key:
ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa
(For me an RSA key worked. A DSA key did not work.)
A private key will be generated in ~/.ssh/id_rsa
along with ~/.ssh/id_rsa.pub
(public key).
Now move to the .ssh folder: cd ~/.ssh
Enter rm -rf authorized_keys
(sometimes multiple keys lead to an error).
Enter vi authorized_keys
Enter :wq
to save this empty file
Enter cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
Restart the SSH:
sudo launchctl stop com.openssh.sshd
sudo launchctl start com.openssh.sshd
In typical compiler implementations, you can think of the code as "print out the value of the memory block with adress that used to be occupied by a". Also, if you add a new function invocation to a function that constains a local int
it's a good chance that the value of a
(or the memory address that a
used to point to) changes. This happens because the stack will be overwritten with a new frame containing different data.
However, this is undefined behaviour and you should not rely on it to work!
If you use the following CSS
<link href="~/Content/common/bootstrap.css" rel="stylesheet" type="text/css" />
<link href="~/Content/common/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/common/site.css" rel="stylesheet" type="text/css" />
just change it into the following style by adding media="screen"
<link href="~/Content/common/bootstrap.css" rel="stylesheet" **media="screen"** type="text/css" />
<link href="~/Content/common/bootstrap.min.css" rel="stylesheet" **media="screen"** type="text/css" />
<link href="~/Content/common/site.css" rel="stylesheet" **media="screen"** type="text/css" />
I think it will work.
the former answers like
@media print {
a[href]:after {
content: none !important;
}
}
were not worked well in the chrome browse.
Try this:
DateTime.Now.ToString("yyyy-MM-ddThh:mm:sszzz");
zzz
is the timezone offset.
You could use 'vi' and then the following command:
:16224,16482w!/tmp/some-file
Alternatively:
cat file | head -n 16482 | tail -n 258
EDIT:- Just to add explanation, you use head -n 16482 to display first 16482 lines then use tail -n 258 to get last 258 lines out of the first output.
Now we can use:
sales['time_hour'] = sales['timestamp'].apply(lambda x: x.hour)
Data for last month-
select count(distinct switch_id)
from [email protected]
where dealer_name = 'XXXX'
and to_char(CREATION_DATE,'MMYYYY') = to_char(add_months(trunc(sysdate),-1),'MMYYYY');
I like Orion Adrian's answer, but there is another aspect to it.
The same question was posed decades ago about assembly language vs. "human" languages like FORTRAN. And part of the answer is similar.
Yes, a C++ program is capable of being faster than C# on any given (non-trivial?) algorithm, but the program in C# will often be as fast or faster than a "naive" implementation in C++, and an optimized version in C++ will take longer to develop, and might still beat the C# version by a very small margin. So, is it really worth it?
You'll have to answer that question on a one-by-one basis.
That said, I'm a long time fan of C++, and I think it's an incredibly expressive and powerful language -- sometimes underappreciated. But in many "real life" problems (to me personally, that means "the kind I get paid to solve"), C# will get the job done sooner and safer.
The biggest penalty you pay? Many .NET and Java programs are memory hogs. I have seen .NET and Java apps take "hundreds" of megabytes of memory, when C++ programs of similar complexity barely scratch the "tens" of MBs.
iText is a great Java PDF library. They also have an API for creating barcodes. You don't need to be creating a PDF to use it.
This page has the details on creating barcodes. Here is an example from that site:
BarcodeEAN codeEAN = new BarcodeEAN();
codeEAN.setCodeType(codeEAN.EAN13);
codeEAN.setCode("9780201615883");
Image imageEAN = codeEAN.createImageWithBarcode(cb, null, null);
The biggest thing you will need to determine is what type of barcode you need. There are many different barcode formats and iText does support a lot of them. You will need to know what format you need before you can determine if this API will work for you.
Try one of these other mime-types (from here: http://filext.com/file-extension/CSV )
Also, the mime-type might be case sensitive...
Try to see if the following commands can help you:
sudo su - yourdbuser
psql
\i yourbackupfile
I think that you can bind the load
event of the iframe, the event fires when the iframe content is fully loaded.
At the same time you can start a setTimeout, if the iFrame is loaded clear the timeout alternatively let the timeout fire.
Code:
var iframeError;
function change() {
var url = $("#addr").val();
$("#browse").attr("src", url);
iframeError = setTimeout(error, 5000);
}
function load(e) {
alert(e);
}
function error() {
alert('error');
}
$(document).ready(function () {
$('#browse').on('load', (function () {
load('ok');
clearTimeout(iframeError);
}));
});
Demo: http://jsfiddle.net/IrvinDominin/QXc6P/
It is because you miss the parens in the inline function call; try change this:
<iframe id="browse" style="width:100%;height:100%" onload="load" onerror="error"></iframe>
into this:
<iframe id="browse" style="width:100%;height:100%" onload="load('Done func');" onerror="error('failed function');"></iframe>
the easiest way to do this is to wrap your sockets in ObjectInput/OutputStreams and send serialized java objects. you can create classes which contain the relevant data, and then you don't need to worry about the nitty gritty details of handling binary protocols. just make sure that you flush your object streams after you write each object "message".
This should work, but there is a little trick. After you enter the formula, you need to hold down Ctrl+Shift while you press Enter. When you do, you'll see that the formula bar has curly-braces around your formula. This is called an array formula.
For example, if the Months are in cells A2:A100
and the amounts are in cells B2:B100
, your formula would look like {=SUM(If(A2:A100="January",B2:B100))}
. You don't actually type the curly-braces though.
You could also do something like =SUM((A2:A100="January")*B2:B100)
. You'd still need to use the trick to get it to work correctly.
Git stash clear will clear complete stash,
cmd: git stash clear
If you want to delete a particular stash with a stash index, you can use the drop.
cmd: git stash drop 4
(4 is stash id or stash index)
Just like @mark 's answer, we can create a Snippets in Chrome DevTools, to override
the default JavaScript. Finally, we can see what effects they have on the page.
For those who are still looking for a simple answer to this; You can remove your file extension by using .htaccess
but this solution is just saving the day maybe even not. Because when user copies the URL from address bar or tries to reload or even coming back from history, your standart Apache Router will not be able to realize what are you looking for and throw you a 404 Error
. You need a dedicated Router for this purpose to make your app understand what does the URL actually means by saying something Server and File System has no idea about.
I leave here my solution for this. This is tested and used many times for my clients and for my projects too. It supports multi language and language detection too. Read Readme file is recommended. It also provides you a good structure to have a tidy project with differenciated language files (you can even have different designs for each language) and separated css
,js
and php
files even more like images
or whatever you have.
with virtual env activate
export FLASK_DEBUG=true
you can configure
export FLASK_APP=app.py # run.py
export FLASK_ENV = "development"
to start
flask run
the result
* Environment: development
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: xxx-xxx-xxx
and if you change
export FLASK_DEBUG=false
* Environment: development
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
You need to commit or destroy any unsaved changes before you switch branch.
Git won't let you switch branch if it means unsaved changes would be removed.
There is a dynamic filter pipe that I use
Source data:
items = [{foo: 'hello world'}, {foo: 'lorem ipsum'}, {foo: 'foo bar'}];
In the template you can dinamically set the filter in any object attr:
<li *ngFor="let item of items | filter:{foo:'bar'}">
The pipe:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter',
})
export class FilterPipe implements PipeTransform {
transform(items: any[], filter: Record<string, any>): any {
if (!items || !filter) {
return items;
}
const key = Object.keys(filter)[0];
const value = filter[key];
return items.filter((e) => e[key].indexOf(value) !== -1);
}
}
Don't forget to register the pipe in your app.module.ts
declarations
Can't you just use <span contenteditable="true" spellcheck="false">
element in place of <input type="text">
?
<span>
(with contenteditable="true" spellcheck="false"
as attributes) distincts by <input>
mainly because:
<input>
.value
property, but the text is rendered as innerText
and makes part of its inner body. <input>
isn't although you set the attribute multiline="true"
.To accomplish the appearance you can, of course, style it in CSS, whereas writing the value as innerText
you can get for it an event:
Here's a fiddle.
Unfortunately there's something that doesn't actually work in IE and Edge, which I'm unable to find.
Use sum()
in place of count()
Try below:
SELECT
ccc_news . * ,
SUM(if(ccc_news_comments.id = 'approved', 1, 0)) AS comments
FROM
ccc_news
LEFT JOIN
ccc_news_comments
ON
ccc_news_comments.news_id = ccc_news.news_id
WHERE
`ccc_news`.`category` = 'news_layer2'
AND `ccc_news`.`status` = 'Active'
GROUP BY
ccc_news.news_id
ORDER BY
ccc_news.set_order ASC
LIMIT 20
See in the android sdk directory.
In \platforms\android-X\data\res\values\themes.xml
:
<item name="textAppearanceLarge">@android:style/TextAppearance.Large</item>
<item name="textAppearanceMedium">@android:style/TextAppearance.Medium</item>
<item name="textAppearanceSmall">@android:style/TextAppearance.Small</item>
In \platforms\android-X\data\res\values\styles.xml
:
<style name="TextAppearance.Large">
<item name="android:textSize">22sp</item>
</style>
<style name="TextAppearance.Medium">
<item name="android:textSize">18sp</item>
</style>
<style name="TextAppearance.Small">
<item name="android:textSize">14sp</item>
<item name="android:textColor">?textColorSecondary</item>
</style>
TextAppearance.Large
means style is inheriting from TextAppearance
style, you have to trace it also if you want to see full definition of a style.
Link: http://developer.android.com/design/style/typography.html
you could try using Pandas to retrieve information and get it as dataframe
import pyodbc as cnn
import pandas as pd
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=SQLSRV01;DATABASE=DATABASE;UID=USER;PWD=PASSWORD')
# Copy to Clipboard for paste in Excel sheet
def copia (argumento):
df=pd.DataFrame(argumento)
df.to_clipboard(index=False,header=True)
tableResult = pd.read_sql("SELECT * FROM YOURTABLE", cnxn)
# Copy to Clipboard
copia(tableResult)
# Or create a Excel file with the results
df=pd.DataFrame(tableResult)
df.to_excel("FileExample.xlsx",sheet_name='Results')
I hope this helps! Cheers!
If it is disabled, go to Control Panel->Administrative Tools->Services, and look for the SQL Server Agent. Right-click, and select Properties From the Startup Type dropdown, change from Disabled to Automatic.
In my opinion, jQuery's animate
is a bit overused, compared to the CSS3 transition
, which performs such animation on any 2D or 3D property. Also I'm afraid, that leaving it to the browser and by forgetting the layer called JavaScript could lead to spare CPU juice - specially, when you wish to blast with the animations. Thus, I like to have animations where the style definitions are, since you define functionality with JavaScript. The more presentation you inject into JavaScript, the more problems you'll face later on.
All you have to do is to use addClass
to the element you wish to animate, where you set a class that has CSS transition
properties. You just "activate" the animation, which stays implemented on the pure presentation layer.
.js
// with jQuery
$("#element").addClass("Animate");
// without jQuery library
document.getElementById("element").className += "Animate";
One could easly remove a class with jQuery, or remove a class without library.
.css
#element{
color : white;
}
#element.Animate{
transition : .4s linear;
color : red;
/**
* Not that ugly as the JavaScript approach.
* Easy to maintain, the most portable solution.
*/
-webkit-transform : rotate(90deg);
}
.html
<span id="element">
Text
</span>
This is a fast and convenient solution for most use cases.
I also use this when I want to implement a different styling (alternative CSS properties), and wish to change the style on-the-fly with a global .5s animation. I add a new class to the BODY
, while having alternative CSS in a form like this:
.js
$("BODY").addClass("Alternative");
.css
BODY.Alternative #element{
color : blue;
transition : .5s linear;
}
This way you can apply different styling with animations, without loading different CSS files. You only involve JavaScript to set a class
.
You can also use:
\usepackage{anyfontsize}
The huge advantage of the anyfontsize
package over scalefnt
is that one does not need to enclose the entire {tikzpicture}
with a \scalefont
environment.
Just adding \usepackage{anyfontsize}
to the preamble is all that is required for the font scaling magic to happen.
If the table you are deleting from has BEFORE/AFTER DELETE triggers, something in there could be causing your delay.
Additionally, if you have foreign keys referencing that table, additional UPDATEs or DELETEs may be occurring.
I can recommend jOOQ. It provides a lot of great features, also a intuitive DSL for SQL and a extremly customable reverse-engineering approach.
jOOQ effectively combines complex SQL, typesafety, source code generation, active records, stored procedures, advanced data types, and Java in a fluent, intuitive DSL.
I stumbled upon this old listing pondering this same question. My band-aid for this same question was to make my header text into a link. I then changed the color and removed text decoration with CSS. Now to make the entire header picture a link, I expanded the padding of the anchor tag until it reached close to the edge of the header image.... This worked to my satisfaction, and I figured i would share.
Blanket.js works perfect too.
npm install --save-dev blanket
in front of your test/tests.js
require('blanket')({
pattern: function (filename) {
return !/node_modules/.test(filename);
}
});
run mocha -R html-cov > coverage.html
You can also use dictionaries that allows you to have more control over the plots:
import matplotlib.pyplot as plt
# plot 0 plot 1 plot 2 plot 3
x=[[1,2,3,4],[1,4,3,4],[1,2,3,4],[9,8,7,4]]
y=[[3,2,3,4],[3,6,3,4],[6,7,8,9],[3,2,2,4]]
plots = zip(x,y)
def loop_plot(plots):
figs={}
axs={}
for idx,plot in enumerate(plots):
figs[idx]=plt.figure()
axs[idx]=figs[idx].add_subplot(111)
axs[idx].plot(plot[0],plot[1])
return figs, axs
figs, axs = loop_plot(plots)
Now you can select the plot that you want to modify easily:
axs[0].set_title("Now I can control it!")
Of course, is up to you to decide what to do with the plots. You can either save them to disk figs[idx].savefig("plot_%s.png" %idx)
or show them plt.show()
. Use the argument block=False
only if you want to pop up all the plots together (this could be quite messy if you have a lot of plots). You can do this inside the loop_plot
function or in a separate loop using the dictionaries that the function provided.
It seem like your Resort
method doesn't declare a compareTo
method. This method typically belongs to the Comparable
interface. Make sure your class implements it.
Additionally, the compareTo
method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String
argument, but rather a Resort
.
Alternatively, you can compare the names of the resorts. For example
if (resortList[mid].getResortName().compareTo(resortName)>0)
I get this a lot. I'm on a Galaxy S too. I unplug the cable from the phone, plug it back in and try launching the app again from Eclipse, and it usually does the trick. Eclipse seems to lose the connection to the phone occasionally but this seems to kick it back to life.
Yeah first method will work on any element called from elsewhere since it will always take the target element irrespective of id.
check this fiddle
You can use a nested Array.prototype.some call. This has the benefit that it will bail at the first match instead of other solutions that will run through the full nested loop.
eg.
var arr = [1, 2, 3];
var match = [2, 4];
var hasMatch = arr.some(a => match.some(m => a === m));
You don't need to change the delimiter to display the right part of the string with cut
.
The -f
switch of the cut
command is the n-TH element separated by your delimiter : :
, so you can just type :
grep puddle2_1557936 | cut -d ":" -f2
Another solutions (adapt it a bit) if you want fun :
Using grep :
grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or still with look around regex
grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with perl :
perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or using ruby (thanks to glenn jackman)
ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with awk :
awk -F'puddle2_1557936:' '{print $2}' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with python :
python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or using only bash :
IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2
js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2
php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
When you upload a file using FileField
, the file will have a URL that you can use to point to the file and use HTML download
attribute to download that file you can simply do this.
models.py
The model.py looks like this
class CsvFile(models.Model):
csv_file = models.FileField(upload_to='documents')
views.py
#csv upload
class CsvUploadView(generic.CreateView):
model = CsvFile
fields = ['csv_file']
template_name = 'upload.html'
#csv download
class CsvDownloadView(generic.ListView):
model = CsvFile
fields = ['csv_file']
template_name = 'download.html'
Then in your templates.
#Upload template
upload.html
<div class="container">
<form action="#" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.media }}
{{ form.as_p }}
<button class="btn btn-primary btn-sm" type="submit">Upload</button>
</form>
#download template
download.html
{% for document in object_list %}
<a href="{{ document.csv_file.url }}" download class="btn btn-dark float-right">Download</a>
{% endfor %}
I did not use forms, just rendered model but either way, FileField is there and it will work the same.
Turn out to be some SQL service was stopped somehow on server. Restarting SQL Server service manually was the solution.
I know this is foolish but worked anyway. Thanks @PareshJ for the useful comment.
import yaml
data = dict(
A = 'a',
B = dict(
C = 'c',
D = 'd',
E = 'e',
)
)
with open('data.yml', 'w') as outfile:
yaml.dump(data, outfile, default_flow_style=False)
The default_flow_style=False
parameter is necessary to produce the format you want (flow style), otherwise for nested collections it produces block style:
A: a
B: {C: c, D: d, E: e}
Good afternoon, you could always use a little LINQ to get the selected list items and then do what you want with the results:
var selected = CBLGold.Items.Cast<ListItem>().Where(x => x.Selected);
// work with selected...
MYSQL_HOME:
C:\Program Files\MySQL\MySQL Server 5.0
Path:
%MYSQL_HOME%\bin;
You may need read this https://developer.android.com/guide/topics/resources/drawable-resource.html#Shape
and below there is a Note.
Note Every corner must (initially) be provided a corner radius greater than 1, or else no corners are rounded. If you want specific corners to not be rounded, a work-around is to use android:radius to set a default corner radius greater than 1, but then override each and every corner with the values you really want, providing zero ("0dp") where you don't want rounded corners.
Although standard action results FileContentResult or FileStreamResult may be used for downloading files, for reusability, creating a custom action result might be the best solution.
As an example let's create a custom action result for exporting data to Excel files on the fly for download.
ExcelResult class inherits abstract ActionResult class and overrides the ExecuteResult method.
We are using FastMember package for creating DataTable from IEnumerable object and ClosedXML package for creating Excel file from the DataTable.
public class ExcelResult<T> : ActionResult
{
private DataTable dataTable;
private string fileName;
public ExcelResult(IEnumerable<T> data, string filename, string[] columns)
{
this.dataTable = new DataTable();
using (var reader = ObjectReader.Create(data, columns))
{
dataTable.Load(reader);
}
this.fileName = filename;
}
public override void ExecuteResult(ControllerContext context)
{
if (context != null)
{
var response = context.HttpContext.Response;
response.Clear();
response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
response.AddHeader("content-disposition", string.Format(@"attachment;filename=""{0}""", fileName));
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dataTable, "Sheet1");
using (MemoryStream stream = new MemoryStream())
{
wb.SaveAs(stream);
response.BinaryWrite(stream.ToArray());
}
}
}
}
}
In the Controller use the custom ExcelResult action result as follows
[HttpGet]
public async Task<ExcelResult<MyViewModel>> ExportToExcel()
{
var model = new Models.MyDataModel();
var items = await model.GetItems();
string[] columns = new string[] { "Column1", "Column2", "Column3" };
string filename = "mydata.xlsx";
return new ExcelResult<MyViewModel>(items, filename, columns);
}
Since we are downloading the file using HttpGet, create an empty View without model and empty layout.
Blog post about custom action result for downloading files that are created on the fly:
https://acanozturk.blogspot.com/2019/03/custom-actionresult-for-files-in-aspnet.html
Considering your code snippet, please note that you can only pass Native objects to the findBy### method, lets say you want to load a list of accounts that belongs certain costumers, one solution is to do this,
@Query("Select a from Account a where a."#nameoffield"=?1")
List<Account> findByCustomer(String "#nameoffield");
Make sue the name of the table to be queried is thesame as the Entity class. For further implementations please take a look at this
This is what you are looking for. A complete TTS solution for the Mac. You can use this standalone or as a co-location Mac server for web apps:
So, what output does this code produce?
fruits = [ 'apple', 'pear', 'carrot', 'banana' ]
found = False
try:
for i in range(len(fruit)):
if fruits[i] == 'apple':
found = true
except:
pass
if found:
print "Found an apple"
else:
print "No apples in list"
Now imagine the try
-except
block is hundreds of lines of calls to a complex object hierarchy, and is itself called in the middle of large program's call tree. When the program goes wrong, where do you start looking?
As of jQuery 1.5, there is a headers
hash you can pass in as follows:
$.ajax({
url: "/test",
headers: {"X-Test-Header": "test-value"}
});
From http://api.jquery.com/jQuery.ajax:
headers (added 1.5): A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.
Your code works with Python 3.2.1 on Win7 x64
a = set(["Blah", "Hello"])
a = list(a)
type(a)
<class 'list'>
select Id, StartDate,
Case IsNull (StartDate , '01/01/1800')
When '01/01/1800' then
'Awaiting'
Else
'Approved'
END AS StartDateStatus
From MyTable
There are two options depending what you want to achieve :
You can use the hidden directive to show or hide an element
<div [hidden]="!edited" class="alert alert-success box-msg" role="alert">
<strong>List Saved!</strong> Your changes has been saved.
</div>
You can use the ngIf control directive to add or remove the element. This is different of the hidden directive because it does not show / hide the element, but it add / remove from the DOM. You can loose unsaved data of the element. It can be the better choice for an edit component that is cancelled.
<div *ngIf="edited" class="alert alert-success box-msg" role="alert">
<strong>List Saved!</strong> Your changes has been saved.
</div>
For you problem of change after 3 seconds, it can be due to incompatibility with setTimeout. Did you include angular2-polyfills.js library in your page ?
Just remove the slash after Data
and prepend the root:
<xsl:variable name="myVarA" select="/root/DataSet/Data[@Value1='2']/@Value2"/>
Here is an extension of @Trasp's answer that has additional logic for handling the corner case of a file that has only one line. It may be useful to handle this case if you repeatedly want to read the last line of a file that is continuously being updated. Without this, if you try to grab the last line of a file that has just been created and has only one line, IOError: [Errno 22] Invalid argument
will be raised.
def tail(filepath):
with open(filepath, "rb") as f:
first = f.readline() # Read the first line.
f.seek(-2, 2) # Jump to the second last byte.
while f.read(1) != b"\n": # Until EOL is found...
try:
f.seek(-2, 1) # ...jump back the read byte plus one more.
except IOError:
f.seek(-1, 1)
if f.tell() == 0:
break
last = f.readline() # Read last line.
return last
Simply you can do this:
public void CheckNull(int? item)
{
if (item != null)
{
//Do Something
}
}
The strings that contain \xF0
are simply characters encoded as multiple bytes using UTF-8.
Although your collation is set to utf8_general_ci, I suspect that the character encoding of the database, table or even column may be different. They are independent settings. Try:
ALTER TABLE database.table MODIFY COLUMN col VARCHAR(255)
CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;
Substitute whatever your actual data type is for VARCHAR(255)
This one worked for me. using the srcset. I have just learnt about it so i dont know if browsers support it but it has worked for me. Try it and later give me your feed back.
<img src="smiley.gif" srcset="alternatve.gif" width="32" height="32" />
I guess now we can use plain iloc
with range
for this.
chunk_size = int(df.shape[0] / 4)
for start in range(0, df.shape[0], chunk_size):
df_subset = df.iloc[start:start + chunk_size]
process_data(df_subset)
....
You can specify one or more table arguments to the .dump special command, e.g.sqlite3 db ".dump 'table1' 'table2'"
.
Instead of explicitly writing the class name you could use
this.getClass().getResource("/unibo/lsb/res/dice.jpg");
I solved this problem, which occured for me after manually installing the ADT (4.2/api 17) bundle on Windows 7 64 bit in C:\Program Files.
The steps I had to take:
JAVA_HOME
environment variable to the installation directory of the (64 bit) JDK, C:\Program Files\Java\jdk1.7.0_11
in my case.In properly extending dimsuz's answer by providing a real code situation, see the following code snippet:
Drawable buttonDrawable = button.getBackground();
buttonDrawable = DrawableCompat.wrap(buttonDrawable);
//the color is a direct color int and not a color resource
DrawableCompat.setTint(buttonDrawable, Color.RED);
button.setBackground(buttonDrawable);
This solution is for the scenario where a drawable is used as the button's background. It works on pre-Lollipop devices as well.
You can make use of Flexbox layout. You need to set flex: 1
on the element that needs to have dynamic width or height for flex-direction: row and column
respectively.
Dynamic width:
HTML
<div class="container">
<div class="fixed-width">
1
</div>
<div class="flexible-width">
2
</div>
<div class="fixed-width">
3
</div>
</div>
CSS
.container {
display: flex;
}
.fixed-width {
width: 200px; /* Fixed width or flex-basis: 200px */
}
.flexible-width {
flex: 1; /* Stretch to occupy remaining width i.e. flex-grow: 1 and flex-shrink: 1*/
}
Output:
.container {_x000D_
display: flex;_x000D_
width: 100%;_x000D_
color: #fff;_x000D_
font-family: Roboto;_x000D_
}_x000D_
.fixed-width {_x000D_
background: #9BCB3C;_x000D_
width: 200px; /* Fixed width */_x000D_
text-align: center;_x000D_
}_x000D_
.flexible-width {_x000D_
background: #88BEF5;_x000D_
flex: 1; /* Stretch to occupy remaining width */_x000D_
text-align: center;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="fixed-width">_x000D_
1_x000D_
</div>_x000D_
<div class="flexible-width">_x000D_
2_x000D_
</div>_x000D_
<div class="fixed-width">_x000D_
3_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
Dynamic height:
HTML
<div class="container">
<div class="fixed-height">
1
</div>
<div class="flexible-height">
2
</div>
<div class="fixed-height">
3
</div>
</div>
CSS
.container {
display: flex;
}
.fixed-height {
height: 200px; /* Fixed height or flex-basis: 200px */
}
.flexible-height {
flex: 1; /* Stretch to occupy remaining height i.e. flex-grow: 1 and flex-shrink: 1*/
}
Output:
.container {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
height: 100vh;_x000D_
color: #fff;_x000D_
font-family: Roboto;_x000D_
}_x000D_
.fixed-height {_x000D_
background: #9BCB3C;_x000D_
height: 50px; /* Fixed height or flex-basis: 100px */_x000D_
text-align: center;_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
justify-content: center;_x000D_
}_x000D_
.flexible-height {_x000D_
background: #88BEF5;_x000D_
flex: 1; /* Stretch to occupy remaining width */_x000D_
text-align: center;_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
justify-content: center;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="fixed-height">_x000D_
1_x000D_
</div>_x000D_
<div class="flexible-height">_x000D_
2_x000D_
</div>_x000D_
<div class="fixed-height">_x000D_
3_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
If you already installed npm globally on your system, and you are still getting the above error message by using VSCode terminal. Just close your VSCode application and reopen again, that should resolve the issue.
I just bumped into the same issue. I had a ViewPager and I wanted to display an ad at the button of it. The solution I found was to get the pager into a RelativeView and set it's layout_above to the view id i want to see below it. that worked for me.
here is my layout XML:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="@+id/AdLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="vertical" >
</LinearLayout>
<android.support.v4.view.ViewPager
android:id="@+id/mainpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/AdLayout" >
</android.support.v4.view.ViewPager>
</RelativeLayout>
Using hardcoded indexes itself can be a mess.
In order to avoid that, Python offers a built-in object slice()
.
string = "my company has 1000$ on profit, but I lost 500$ gambling."
If we want to know how many money I got left.
Normal solution:
final = int(string[15:19]) - int(string[43:46])
print(final)
>>>500
Using slices:
EARNINGS = slice(15, 19)
LOSSES = slice(43, 46)
final = int(string[EARNINGS]) - int(string[LOSSES])
print(final)
>>>500
Using slice you gain readability.
I've decided to give an answer to this question because I think it can be solved using a simpler syntax than the convoluted try-catch block. The Laravel documentation is pretty brief on this subject.
Instead of using try-catch, you can just use the DB::transaction(){...}
wrapper like this:
// MyController.php
public function store(Request $request) {
return DB::transaction(function() use ($request) {
$user = User::create([
'username' => $request->post('username')
]);
// Add some sort of "log" record for the sake of transaction:
$log = Log::create([
'message' => 'User Foobar created'
]);
// Lets add some custom validation that will prohibit the transaction:
if($user->id > 1) {
throw AnyException('Please rollback this transaction');
}
return response()->json(['message' => 'User saved!']);
});
};
You should then see that the User and the Log record cannot exist without eachother.
Some notes on the implementation above:
return
the transaction, so that you can use the response()
you return within its callback.throw
an exception if you want the transaction to be rollbacked (or have a nested function that throws the exception for you automatically, like an SQL exception from within Eloquent).id
, updated_at
, created_at
and any other fields are AVAILABLE AFTER CREATION for the $user
object (for the duration of this transaction). The transaction will run through any of the creation logic you have. HOWEVER, the whole record is discarded when the AnyException
is thrown. This means that for instance an auto-increment column for id
does get incremented on failed transactions.Tested on Laravel 5.8
I have not yet managed to find the best way possible. Since I am using a keyboard with Finnish
layout, some of the answers do not work for me (e.g. user5036413's answer).
However, in the meantime, I have come up with a solution that at least helps me not to comment each and every line one by one. I am using Chrome browser
in MS Windows
and I have not checked other possibilities though.
The solution:
It uses the fact that you can have multiple line cursors in an Ipython Notebook
.
Press the Alt button and keep holding it. The cursor should change its shape into a big plus sign. The next step is, using your mouse, to point to the beginning of the first line you want to comment and while holding the Alt button pull down your mouse until the last line you want to comment. Finally, you can release the Alt button and then use the #
character to comment. Voila! You have now commented multiple lines.
If the default .m2 is unable to find, maybe someone changed the default path. Issue the following command to find out where is the Maven local repository,
mvn help:evaluate -Dexpression=settings.localRepository
The above command will scan for projects and run some tasks. Final outcome will be like below
As you can see in the picture the maven local repository is C:\Users\INOVA\.m2\repository
I think it's better to change your csv file like:
"age","first_name","last_name"
23,Ivan,Poupkine
,Eugene,Pirogov
It's also possible to define your table like
CREATE TABLE people (
age varchar(20),
first_name varchar(20),
last_name varchar(20)
);
and after copy, you can convert empty strings:
select nullif(age, '')::int as age, first_name, last_name
from people
If you are using jQuery, you don't have to do anything special. Handlers added via $(document).ready()
don't overwrite each other, but rather execute in turn:
$(document).ready(func1)
...
$(document).ready(func2)
If you are not using jQuery, you could use addEventListener
, as demonstrated by Karaxuna, plus attachEvent
for IE<9.
Note that onload
is not equivalent to $(document).ready()
- the former waits for CSS, images... as well, while the latter waits for the DOM tree only. Modern browsers (and IE since IE9) support the DOMContentLoaded
event on the document, which corresponds to the jQuery ready
event, but IE<9 does not.
if(window.addEventListener){
window.addEventListener('load', func1)
}else{
window.attachEvent('onload', func1)
}
...
if(window.addEventListener){
window.addEventListener('load', func2)
}else{
window.attachEvent('onload', func2)
}
If neither option is available (for example, you are not dealing with DOM nodes), you can still do this (I am using onload
as an example, but other options are available for onload
):
var oldOnload1=window.onload;
window.onload=function(){
oldOnload1 && oldOnload1();
func1();
}
...
var oldOnload2=window.onload;
window.onload=function(){
oldOnload2 && oldOnload2();
func2();
}
or, to avoid polluting the global namespace (and likely encountering namespace collisions), using the import/export IIFE pattern:
window.onload=(function(oldLoad){
return function(){
oldLoad && oldLoad();
func1();
}
})(window.onload)
...
window.onload=(function(oldLoad){
return function(){
oldLoad && oldLoad();
func2();
}
})(window.onload)
body {_x000D_
margin: 0; /* Reset default margin */_x000D_
}_x000D_
iframe {_x000D_
display: block; /* iframes are inline by default */_x000D_
background: #000;_x000D_
border: none; /* Reset default border */_x000D_
height: 100vh; /* Viewport-relative units */_x000D_
width: 100vw;_x000D_
}
_x000D_
<iframe></iframe>
_x000D_
Elastic Search 7 changed the configurations for cluster initialisation. What is important to note is the ES instances communicate internally using the Transport layer(TCP) and not the HTTP protocol which is normally used to perform ops on the indices. Below is sample config for 2 machines cluster.
cluster.name: cluster-new
node.name: node-1
node.master: true
node.data: true
bootstrap.memory_lock: true
network.host: 0.0.0.0
http.port: 9200
transport.host: 102.123.322.211
transport.tcp.port: 9300
discovery.seed_hosts: [“102.123.322.211:9300”,"102.123.322.212:9300”]
cluster.initial_master_nodes:
- "node-1"
- "node-2”
Machine 2 config:-
cluster.name: cluster-new
node.name: node-2
node.master: true
node.data: true
bootstrap.memory_lock: true
network.host: 0.0.0.0
http.port: 9200
transport.host: 102.123.322.212
transport.tcp.port: 9300
discovery.seed_hosts: [“102.123.322.211:9300”,"102.123.322.212:9300”]
cluster.initial_master_nodes:
- "node-1"
- "node-2”
cluster.name: This has be same across all the machines that are going to be part of a cluster.
node.name : Identifier for the ES instance. Defaults to machine name if not given.
node.master: specifies whether this ES instance is going to be master or not
node.data: specifies whether this ES instance is going to be data node or not(hold data)
bootsrap.memory_lock: disable swapping.You can start the cluster without setting this flag. But its recommended to set the lock.More info: https://www.elastic.co/guide/en/elasticsearch/reference/master/setup-configuration-memory.html
network.host: 0.0.0.0 if you want to expose the ES instance over network. 0.0.0.0 is different from 127.0.0.1( aka localhost or loopback address). It means all IPv4 addresses on the machine. If machine has multiple ip addresses with a server listening on 0.0.0.0, the client can reach the machine from any of the IPv4 addresses.
http.port: port on which this ES instance will listen to for HTTP requests
transport.host: The IPv4 address of the host(this will be used to communicate with other ES instances running on different machines). More info: https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-transport.html
transport.tcp.port: 9300 (the port where the machine will accept the tcp connections)
discovery.seed_hosts: This was changed in recent versions. Initialise all the IPv4 addresses with TCP port(important) of ES instances that are going to be part of this cluster. This is going to be same across all ES instances that are part of this cluster.
cluster.initial_master_nodes: node names(node.name) of the ES machines that are going to participate in master election.(Quorum based decision making :- https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-discovery-quorums.html#modules-discovery-quorums)
Use extern keyword in another .c file.
A simple solution is to install jshon
library :
jshon -l < /tmp/test.json
2
List<String> strings = Arrays.asList(new String[]{"one", "two", "three"});
This is a list view of the array, the list is partly unmodifiable, you can't add or delete elements. But the time complexity is O(1).
If you want a modifiable a List:
List<String> strings =
new ArrayList<String>(Arrays.asList(new String[]{"one", "two", "three"}));
This will copy all elements from the source array into a new list (complexity: O(n))
Everyone said it, but I guess it won't hurt saying it again.
You need to set the width
to some value. Here is something simpler to understand.
NSCharacterSet *charSet = NSCharacterSet.newlineCharacterSet;
NSString *formatted = [[unformatted componentsSeparatedByCharactersInSet:charSet] componentsJoinedByString:@"\n"];
Try something like this:
IWebDriver _driver = new FirefoxDriver();
_driver.Manage().Window.Position = new Point(0, 0);
_driver.Manage().Window.Size = new Size(1024, 768);
Not sure if it'll resize after being launched though, so maybe it's not what you want
You can call max(vector, na.rm = TRUE)
. More generally, you can use the na.omit()
function.
I think that in order to get the request data, bound and validated by the form object, you must use :
$form->getClientData();
As another answer alludes to under newer versions of Windows it seems to be necessary to read the standard output and/or standard error streams otherwise it will stall between commands. A neater way to do that instead of using delays is to use an async callback to consume output from the stream:
static void RunCommands(List<string> cmds, string workingDirectory = "")
{
var process = new Process();
var psi = new ProcessStartInfo();
psi.FileName = "cmd.exe";
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.UseShellExecute = false;
psi.WorkingDirectory = workingDirectory;
process.StartInfo = psi;
process.Start();
process.OutputDataReceived += (sender, e) => { Console.WriteLine(e.Data); };
process.ErrorDataReceived += (sender, e) => { Console.WriteLine(e.Data); };
process.BeginOutputReadLine();
process.BeginErrorReadLine();
using (StreamWriter sw = process.StandardInput)
{
foreach (var cmd in cmds)
{
sw.WriteLine (cmd);
}
}
process.WaitForExit();
}
Here is a technique which seems to work around the edge cases: the end of the year and leap Februaries.
The problem with datediff(year,…,…)
is that it only finds the difference between the years, and not the actual dates, which is a bit naïve in my opinion. This is only reliable if the date of birth is 1st Jan.
The solution is to time warp the date of birth to the first of January, and the asking date by the same amount.
Because of the leap year problem using the day of year is also unreliable, so I use the month and day to do the time warp:
CREATE FUNCTION age(@then AS date,@now AS date) RETURNS int AS
BEGIN
DECLARE @month INT = month(@then)-1;
DECLARE @day INT = day(@then)-1;
SET @then=dateadd(month,-@month,@then);
SET @then=dateadd(day,-@day,@then);
SET @now=dateadd(month,-@month,@now;)
SET @now=dateadd(day,-@day,@now);
RETURN datediff(year,@then,@now);
END;
You can write this more compactly, of course. You can even write it in one line, if that’s your idea of having a good time:
CREATE FUNCTION age(@then AS date,@now AS date) RETURNS int AS
BEGIN
RETURN datediff(
year,
dateadd(day,-day(@then)+1,dateadd(month,-month(@then)+1,@then)),
dateadd(day,-day(@then)+1,dateadd(month,-month(@then)+1,@now))
);
END;
but that’s only showing off, and it’s less efficient as it needs to recalculate the offsets.
this should work (not tested!)
var url = window.location.href;
if (url.indexOf('?') > -1){
url += '¶m=1'
}else{
url += '?param=1'
}
window.location.href = url;
As Herman pointed out, you can get the index and element from each iteration.
{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}
Working example:
package main
import (
"html/template"
"os"
)
type EntetiesClass struct {
Name string
Value int32
}
// In the template, we use rangeStruct to turn our struct values
// into a slice we can iterate over
var htmlTemplate = `{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}`
func main() {
data := map[string][]EntetiesClass{
"Yoga": {{"Yoga", 15}, {"Yoga", 51}},
"Pilates": {{"Pilates", 3}, {"Pilates", 6}, {"Pilates", 9}},
}
t := template.New("t")
t, err := t.Parse(htmlTemplate)
if err != nil {
panic(err)
}
err = t.Execute(os.Stdout, data)
if err != nil {
panic(err)
}
}
Output:
Pilates
3
6
9
Yoga
15
51
Playground: http://play.golang.org/p/4ISxcFKG7v
In Chrome, on the right-hand side of the URL bar when you are at a password protected URL, you should see a small key symbol. Click the symbol and it will take you directly to the Password Management area where you can remove the entry. That will ensure you receive future prompts or have an opportunity to enter a new password and save it.
If you do not see the key symbol, that same Password Management area can be accessed by going to Chrome -> Settings -> Passwords and forms -> Manage Passwords. Or more simply, this URL – chrome://settings/passwords.
For intellij console the 0x08
character worked for me!
System.out.print((char) 8);
this is the code for set method
public void setAge(int age){
this.age = age;
}
The direct replacement is if
/elif
/else
.
However, in many cases there are better ways to do it in Python. See "Replacements for switch statement in Python?".
I just found the .submodule (forgot exact name) hidden file, it has a list... you can erase them individually that way. I just had one, so I deleted it. Simple, but it might mess up Git, since I don't know if anything's attached to the submodule. Seems ok so far, aside from libetpan's usual upgrade issue, but that's (hopefully) unrelated.
Noticed nobody posted manual erasing, so added
Parse the Id as it would be string and then add.
e.g.
$('.load_more').live("click",function() { //When user clicks
var newcurrentpageTemp = parseInt($(this).attr("id")) + 1;//Get the id from the hyperlink
alert(newcurrentpageTemp);
dosomething();
});
It says right there in the output of git status
:
# (use "git add/rm <file>..." to update what will be committed)
so just do:
git rm <filename>
Maybe you can use WebView, but as you can see in the doc WebView doesn't support javascript and other stuff like widgets by default.
http://developer.android.com/reference/android/webkit/WebView.html
I think that you can enable javascript if you need it.
At first, you need to convert time span to DateTime structure:
var dt = new DateTime(2000, 12, 1, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds)
Then you need to convert the value to string with Short Time format
var result = dt.ToString("t"); // Convert to string using Short Time format
You can't serialize a collection of objects without specifying the expected types. You must pass the list of expected types to the constructor of XmlSerializer
(the extraTypes
parameter) :
List<object> list = new List<object>();
list.Add(new Foo());
list.Add(new Bar());
XmlSerializer xs = new XmlSerializer(typeof(object), new Type[] {typeof(Foo), typeof(Bar)});
using (StreamWriter streamWriter = System.IO.File.CreateText(fileName))
{
xs.Serialize(streamWriter, list);
}
If all the objects of your list inherit from the same class, you can also use the XmlInclude
attribute to specify the expected types :
[XmlInclude(typeof(Foo)), XmlInclude(typeof(Bar))]
public class MyBaseClass
{
}
Try it:
foreach ($json_a as $key => $value)
{
echo $key, ' : ';
foreach($value as $v)
{
echo $v." ";
}
}
Directly from the Windows.h header file:
#ifndef WIN32_LEAN_AND_MEAN
#include <cderr.h>
#include <dde.h>
#include <ddeml.h>
#include <dlgs.h>
#ifndef _MAC
#include <lzexpand.h>
#include <mmsystem.h>
#include <nb30.h>
#include <rpc.h>
#endif
#include <shellapi.h>
#ifndef _MAC
#include <winperf.h>
#include <winsock.h>
#endif
#ifndef NOCRYPT
#include <wincrypt.h>
#include <winefs.h>
#include <winscard.h>
#endif
#ifndef NOGDI
#ifndef _MAC
#include <winspool.h>
#ifdef INC_OLE1
#include <ole.h>
#else
#include <ole2.h>
#endif /* !INC_OLE1 */
#endif /* !MAC */
#include <commdlg.h>
#endif /* !NOGDI */
#endif /* WIN32_LEAN_AND_MEAN */
if you want to know what each of the headers actually do, typeing the header names into the search in the MSDN library will usually produce a list of the functions in that header file.
Also, from Microsoft's support page:
To speed the build process, Visual C++ and the Windows Headers provide the following new defines:
VC_EXTRALEAN
WIN32_LEAN_AND_MEANYou can use them to reduce the size of the Win32 header files.
Finally, if you choose to use either of these preprocessor defines, and something you need is missing, you can just include that specific header file yourself. Typing the name of the function you're after into MSDN will usually produce an entry which will tell you which header to include if you want to use it, at the bottom of the page.
Try converting the entry to a string first. As long as the database column type is a date it will be formated as a date.
self.date || self.exif_date_time_original.to_s
Building on Roland's answer, using tidyr
to reshape the data from wide to long:
library(tidyr)
library(ggplot2)
df <- read.table(text="Rank F1 F2 F3
1 500 250 50
2 400 100 30
3 300 155 100
4 200 90 10", header=TRUE)
df %>%
gather(variable, value, F1:F3) %>%
ggplot(aes(x = Rank, y = value, fill = variable)) +
geom_bar(stat = "identity")
As you can see, there are several ways to achieve this.
I personally use:
Expand all: CTRL + M + L
Collapse all: CTRL + M + O
Bonus:
Expand/Collapse on cursor location: CTRL + M + M
In my case, the issue was with a new class
not being recognized. I solved the issue by deleting the class and re-adding it but this time checking the Watch App Extension
option when creating the new class.
Please note that I do have a Watch App Extension in my Application.
You can track by $index
if your data source has duplicate identifiers
e.g.: $scope.dataSource: [{id:1,name:'one'}, {id:1,name:'one too'}, {id:2,name:'two'}]
You can't iterate this collection while using 'id' as identifier (duplicate id:1).
WON'T WORK:
<element ng-repeat="item.id as item.name for item in dataSource">
// something with item ...
</element>
but you can, if using track by $index
:
<element ng-repeat="item in dataSource track by $index">
// something with item ...
</element>
In events handler you can get id as follows
function show(btn) {_x000D_
console.log('Button id:',btn.id);_x000D_
}
_x000D_
<button id="myButtonId" onclick="show(this)">Click me</button>
_x000D_
This will get you the most expensive car for the user:
SELECT users.userName, MAX(cars.carPrice)
FROM users
LEFT JOIN cars ON cars.belongsToUser=users.id
WHERE users.id=4
GROUP BY users.userName
However, this statement makes me think that you want all of the cars prices sorted, descending:
So question: How do I set the LEFT JOIN table to be ordered by carPrice, DESC ?
So you could try this:
SELECT users.userName, cars.carPrice
FROM users
LEFT JOIN cars ON cars.belongsToUser=users.id
WHERE users.id=4
GROUP BY users.userName
ORDER BY users.userName ASC, cars.carPrice DESC
Check to make sure that the file is complete. This error message can occur if you only partially downloaded a file or if it has major issues. Check the MD5sum.
Check this post, helped me a lot. In short, the best option for me was:
import random
import string
# defining function for random
# string id with parameter
def ran_gen(size, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for x in range(size))
# function call for random string
# generation with size 8 and string
print (ran_gen(8, "AEIOSUMA23"))
Because I needed just 4-6 random characters instead of bulky GUID.
You just need to write the first query as a subquery (derived table), inside parentheses, pick an alias for it (t
below) and alias the columns as well.
The DISTINCT
can also be safely removed as the internal GROUP BY
makes it redundant:
SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
FROM (
SELECT MIN(`date`) AS `date`, `player_name`
FROM `player_playtime`
GROUP BY `player_name`
) AS t
GROUP BY DATE( `date`) DESC LIMIT 60 ;
Since the COUNT
is now obvious that is only counting rows of the derived table, you can replace it with COUNT(*)
and further simplify the query:
SELECT t.date , COUNT(*) AS player_count
FROM (
SELECT DATE(MIN(`date`)) AS date
FROM player_playtime
GROUP BY player_name
) AS t
GROUP BY t.date DESC LIMIT 60 ;
In my case it was an old version of the DLL in C:\WINDOWS\Microsoft.NET\Framework\~\Temporary ASP.NET Files\ directory. You can either delete or replace the old version, or you can remove and add back the reference to the DLL in your project. Basically, either way will create a new pointer to the temporary ASP.NET Files.
This works perfectly for me in Bootstrap 4.
<div class="form-row align-items-center">
<div class="col-md-2">
<label for="FirstName" style="margin-bottom:0rem !important;">First Name</label>
</div>
<div class="col-md-10">
<input type="text" id="FirstName" name="FirstName" class="form-control" val=""/>
/div>
</div>
The question is already answered but I think I've found the solution that is simpler and more relevant to the question title, here it is:
var cli = new WebClient();
cli.Headers[HttpRequestHeader.ContentType] = "application/json";
string response = cli.UploadString("http://some/address", "{some:\"json data\"}");
PS: In the most of .net implementations, but not in all WebClient is IDisposable, so of cource it is better to do 'using' or 'Dispose' on it. However in this particular case it is not really necessary.
Ah, that would be because RegExp is not jQuery. :)
Try this page. jQuery.attr
doesn't return a String so that would certainly cause in this regard. Fortunately I believe you can just use .text()
to return the String representation.
Something like:
$("li").val("title").search(/sometext/i));
Try this command for Version <= Marshmallow,
adb devices
List of devices attached 38ccdc87 device
adb tcpip 5555
restarting in TCP mode port: 5555
adb shell ip addr show wlan0
24: wlan0: mtu 1500 qdisc mq state UP qlen 1000 link/ether ac:c1:ee:6b:22:f1 brd ff:ff:ff:ff:ff:ff inet 192.168.0.18/24 brd 192.168.0.255 scope global wlan0 valid_lft forever preferred_lft forever inet6 fd01::1d45:6b7a:a3b:5f4d/64 scope global temporary dynamic valid_lft 287sec preferred_lft 287sec inet6 fd01::aec1:eeff:fe6b:22f1/64 scope global dynamic valid_lft 287sec preferred_lft 287sec inet6 fe80::aec1:eeff:fe6b:22f1/64 scope link valid_lft forever preferred_lft forever
To connect to your device run this
adb connect 192.168.0.18
connected to 192.168.0.18:5555
Make sure you have adb inside this location android-sdk\platform-tools
If you want the date, given a month and a year, this seems about right:
public static DateTime GetLastDayOfMonth(this DateTime dateTime)
{
return new DateTime(dateTime.Year, dateTime.Month, DateTime.DaysInMonth(dateTime.Year, dateTime.Month));
}
If you installed Anaconda with Visual Studio 2017 for Windows, conda executable is in this path or similar.
In my case path is this:
C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\Scripts
Steps to add it to your PATH:
You will be able to execute conda
Happy coding!
Take the number 123.456789
Floating point lets you represent most every number with a great deal of precision. Fixed is less precise, but simpler for the computer..
For SQL Server 2016 and later, here is a really simple and relatively efficient expression to generate cryptographically random strings of a given byte length:
--Generates 36 bytes (48 characters) of base64 encoded random data
select r from OpenJson((select Crypt_Gen_Random(36) r for json path))
with (r varchar(max))
Note that the byte length is not the same as the encoded size; use the following from this article to convert:
Bytes = 3 * (LengthInCharacters / 4) - Padding
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 30, 300, 50)];
label.backgroundColor = [UIColor clearColor];
label.textAlignment = NSTextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.numberOfLines = 0;
label.lineBreakMode = UILineBreakModeWordWrap;
label.text = @"Your Text";
[self.view addSubview:label];
You could do something like this:
i={'foo':'bar', 'baz':'huh?'}
keys=i.keys() #in python 3, you'll need `list(i.keys())`
values=i.values()
print keys[values.index("bar")] #'foo'
However, any time you change your dictionary, you'll need to update your keys,values because dictionaries are not ordered in versions of Python prior to 3.7. In these versions, any time you insert a new key/value pair, the order you thought you had goes away and is replaced by a new (more or less random) order. Therefore, asking for the index in a dictionary doesn't make sense.
As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. As of Python 3.7+ dictionaries are ordered by order of insertion.
Also note that what you're asking is probably not what you actually want. There is no guarantee that the inverse mapping in a dictionary is unique. In other words, you could have the following dictionary:
d={'i':1, 'j':1}
In that case, it is impossible to know whether you want i
or j
and in fact no answer here will be able to tell you which ('i'
or 'j'
) will be picked (again, because dictionaries are unordered). What do you want to happen in that situation? You could get a list of acceptable keys ... but I'm guessing your fundamental understanding of dictionaries isn't quite right.
In my case, I needed to use RedirectToAction to solve the problem.
[HttpGet]
[ControleDeAcessoAuthorize("Report/ExportToPDF")]
public ActionResult ExportToPDF(int id, string month, string output)
{
try
{
// Validate
if (output != "PDF")
{
throw new Exception("Invalid output.");
}
else
{
...// code to generate report in PDF format
}
}
catch (Exception ex)
{
return RedirectToAction("Error");
}
}
[ControleDeAcessoAuthorize("Report/Error")]
public ActionResult Error()
{
return View();
}
As android doesn't support such a thing, you can do it manually with FontCreator. It has good options for font modifying. I used this tool to build a custom font, even if it takes some times but you can always use it in your projects.
here is the solution for your query returning only one row for each date in that table here in the solution 'tony' will occur twice as two different start dates are there for it
SELECT * FROM
(
SELECT T1.*, ROW_NUMBER() OVER(PARTITION BY TRUNC(START_DATE),OWNER_NAME ORDER BY 1,2 DESC ) RNM
FROM TABLE T1
)
WHERE RNM=1
You can always wrap your promise returning functions in a way that they catches failure and returning instead an agreed value (e.g. error.message), so the exception won't roll all the way up to the Promise.all function and disable it.
async function resetCache(ip) {
try {
const response = await axios.get(`http://${ip}/resetcache`);
return response;
}catch (e) {
return {status: 'failure', reason: 'e.message'};
}
}
This script is about creating tables with foreign key and I added referential integrity constraint sql-server.
create table exams
(
exam_id int primary key,
exam_name varchar(50),
);
create table question_bank
(
question_id int primary key,
question_exam_id int not null,
question_text varchar(1024) not null,
question_point_value decimal,
constraint question_exam_id_fk
foreign key references exams(exam_id)
ON DELETE CASCADE
);
And for the plain js answer if anyone might be interested;
var count = document.getElementsByClassName("item");
Cheers.
Reference: https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
Just remove the obsolete gems from your Gemfile. If you're talking about Heroku (you didn't mention that) then the slug is compiled each new release, just using the current contents of that file.
VARCHAR(255)
and VARCHAR(2)
take exactly the same amount of space on disk! So the only reason to limit it is if you have a specific need for it to be smaller. Otherwise make them all 255.
Specifically, when doing sorting, larger column do take up more space, so if that hurts performance, then you need to worry about it and make them smaller. But if you only ever select 1 row from that table, then you can just make them all 255 and it won't matter.
How about make clicking the a tag, to click on the file button?
There is more browser support for this, but I use ES6, so if you really want to make it work in older and any browser, try to transpile it using babel, or just simply use ES5:
const aTag = document.getElementById("open-file-uploader");_x000D_
const fileInput = document.getElementById("input-button");_x000D_
aTag.addEventListener("click", () => fileInput.click());
_x000D_
#input-button {_x000D_
position: abosulte;_x000D_
width: 1px;_x000D_
height: 1px;_x000D_
clip: rect(1px 1px 1px 1px);_x000D_
clip: rect(1px, 1px, 1px, 1px);_x000D_
}
_x000D_
<a href="#" id="open-file-uploader">Open file uploader</a>_x000D_
<input type="file" id="input-button" />
_x000D_
<div id="content" >
<h1>Update Information</h1>
<div id="support-box">
<div id="wrapper">
<iframe name="frame" id="frame" src="http://website.org/update.php" allowtransparency="true" frameborder="0"></iframe>
</div>
</div>
</div>
#support-box {
width: 50%;
float: left;
display: block;
height: 20rem; /* is support box height you can change as per your requirement*/
background-color:#000;
}
#wrapper {
width: 90%;
display: block;
position: relative;
top: 50%;
transform: translateY(-50%);
background:#ddd;
margin:auto;
height:100px; /* here the height values are automatic you can leave this if you can*/
}
#wrapper iframe {
width: 100%;
display: block;
padding:10px;
margin:auto;
}
Just had to deal with this scenario myself - found a really easy way to do this, simply annotate your property in the model like this:
[DataType(DataType.Date)]
public DateTime? SomeDateProperty { get; set; }
It will hide the time button from the date picker too.
Sorry if this answer is a little late ;)
Add step="0.01"
to the <input type="number" />
parameters:
<input type="number" min="0.01" step="0.01" max="2500" value="25.67" />
Demo: http://jsfiddle.net/uzbjve2u/
But the Dollar sign must stay outside the textbox... every non-numeric or separator charachter will be cropped automatically.
Otherwise you could use a classic textbox, like described here.
The dplyr
select
function selects specific columns from a data frame. To return unique values in a particular column of data, you can use the group_by
function. For example:
library(dplyr)
# Fake data
set.seed(5)
dat = data.frame(x=sample(1:10,100, replace=TRUE))
# Return the distinct values of x
dat %>%
group_by(x) %>%
summarise()
x
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
If you want to change the column name you can add the following:
dat %>%
group_by(x) %>%
summarise() %>%
select(unique.x=x)
This both selects column x
from among all the columns in the data frame that dplyr
returns (and of course there's only one column in this case) and changes its name to unique.x
.
You can also get the unique values directly in base R
with unique(dat$x)
.
If you have multiple variables and want all unique combinations that appear in the data, you can generalize the above code as follows:
set.seed(5)
dat = data.frame(x=sample(1:10,100, replace=TRUE),
y=sample(letters[1:5], 100, replace=TRUE))
dat %>%
group_by(x,y) %>%
summarise() %>%
select(unique.x=x, unique.y=y)
Github's libgit2 binding, pygit2 provides a one-liner cloning a remote directory:
clone_repository(url, path,
bare=False, repository=None, remote=None, checkout_branch=None, callbacks=None)
Years later and this is still a common problem, but its not always facebook's cache: It is very often human error (allow me to elaborate)
OG:TYPE effects your image scrape:
Be aware that og:type=website will cause any /sub-pages/ of that url to become "canonical". This means you will have trouble getting your images to update using the scraper no matter what you do.
Consider this "assumption and common mistake"
-<meta property="og:type" content="website" />
=> https://www.example.org (parent)
-<meta property="og:type" content="website" />
=> https://www.example.org/sub-page/
-<meta property="og:type" content="website" />
=> https://www.example.org/sub-page/child-2/
- Ergo: /sub-page/
and /child-2/
will inherit the og:image
of the parent
Those are not "all websites", 1 is a website, the others are articles.
If you do that Facebook will think all of those are canonical and it will put the FIRST og:image into all of them. (try it, you'll see) - if you set the og:url to be your root or parent domain you've told facebook they are all canonical. (there is good reason for that, but its off topic)
Consider this solution (which is what most people "really want")
-<meta property="og:type" content="article" />
=> https://www.example.org/sub-page/
-<meta property="og:type" content="article" />
=> https://www.example.org/sub-page/child-2/
If you do that now Facebook will give you far far less problems with scraping your NEW images.
In closing, YES the cache busters, random vars, changing urls and suggestions here can work, but they will seem like "intermittent voodoo" if the og:type
is not specified correctly.
PS: remember that a CDN or serverside cache will serve to Facebook's scraper even if you "think" you can see the most recent version. (I wont spend any time on this other than to point out it will waste colossal amounts of your time if not double checked.)
if you want the object on the stack, try this:
MyClass myclass;
myclass.DoSomething();
If you need a pointer to that object:
MyClass* myclassptr = &myclass;
myclassptr->DoSomething();
I have use mkcert to create infinites *.dev.net subdomains & localhost with valid HTTPS/SSL certs (Windows 10 XAMPP & Linux Debian 10 Apache2)
I create the certs on Windows with mkcert v1.4.0 (execute CMD as Administrator):
mkcert -install
mkcert localhost "*.dev.net"
This create in Windows 10 this files (I will install it first in Windows 10 XAMPP)
localhost+1.pem
localhost+1-key.pem
Overwrite the XAMPP default certs:
copy "localhost+1.pem" C:\xampp\apache\conf\ssl.crt\server.crt
copy "localhost+1-key.pem" C:\xampp\apache\conf\ssl.key\server.key
Now, in Apache2 for Debian 10, activate SSL & vhost_alias
a2enmod vhosts_alias
a2enmod ssl
a2ensite default-ssl
systemctl restart apache2
For vhost_alias add this Apache2 config:
nano /etc/apache2/sites-available/999-vhosts_alias.conf
With this content:
<VirtualHost *:80>
UseCanonicalName Off
ServerAlias *.dev.net
VirtualDocumentRoot "/var/www/html/%0/"
</VirtualHost>
Add the site:
a2ensite 999-vhosts_alias
Copy the certs to /root/mkcert by SSH and let overwrite the Debian ones:
systemctl stop apache2
mv /etc/ssl/certs/ssl-cert-snakeoil.pem /etc/ssl/certs/ssl-cert-snakeoil.pem.bak
mv /etc/ssl/private/ssl-cert-snakeoil.key /etc/ssl/private/ssl-cert-snakeoil.key.bak
cp "localhost+1.pem" /etc/ssl/certs/ssl-cert-snakeoil.pem
cp "localhost+1-key.pem" /etc/ssl/private/ssl-cert-snakeoil.key
chown root:ssl-cert /etc/ssl/private/ssl-cert-snakeoil.key
chmod 640 /etc/ssl/private/ssl-cert-snakeoil.key
systemctl start apache2
Edit the SSL config
nano /etc/apache2/sites-enabled/default-ssl.conf
At the start edit the file with this content:
<IfModule mod_ssl.c>
<VirtualHost *:443>
UseCanonicalName Off
ServerAlias *.dev.net
ServerAdmin webmaster@localhost
# DocumentRoot /var/www/html/
VirtualDocumentRoot /var/www/html/%0/
...
Last restart:
systemctl restart apache2
NOTE: don´t forget to create the folders for your subdomains in /var/www/html/
/var/www/html/subdomain1.dev.net
/var/www/html/subdomain2.dev.net
/var/www/html/subdomain3.dev.net
Just drag and drop the DLL file into folder C:\Windows\assembly
using Windows Explorer.
Caveat:
In earlier versions of the .NET Framework, the Shfusion.dll Windows shell extension let you install assemblies by dragging them to File Explorer. Beginning with .NET Framework 4, Shfusion.dll is obsolete.
Source: How to: Install an assembly into the global assembly cache
Yes, you can use jQuery's attribute selector for that.
var linksToGoogle = $('a[href="http://google.com"]');
Alternatively, if your interest is rather links starting with a certain URL, use the attribute-starts-with selector:
var allLinksToGoogle = $('a[href^="http://google.com"]');
Use GNU Parallel:
(echo command1; echo command2) | parallel
parallel ::: command1 command2
To kill:
parallel ::: command1 command2 &
PID=$!
kill -TERM $PID
kill -TERM $PID
I have a function next()
which will maybe inspire you.
function queue(target) {
var array = Array.prototype;
var queueing = [];
target.queue = queue;
target.queued = queued;
return target;
function queued(action) {
return function () {
var self = this;
var args = arguments;
queue(function (next) {
action.apply(self, array.concat.apply(next, args));
});
};
}
function queue(action) {
if (!action) {
return;
}
queueing.push(action);
if (queueing.length === 1) {
next();
}
}
function next() {
queueing[0](function (err) {
if (err) {
throw err;
}
queueing = queueing.slice(1);
if (queueing.length) {
next();
}
});
}
}
Believe or not, keytool does not provide such basic functionality like importing private key to keystore. You can try this workaround with merging PKSC12 file with private key to a keystore:
keytool -importkeystore \
-deststorepass storepassword \
-destkeypass keypassword \
-destkeystore my-keystore.jks \
-srckeystore cert-and-key.p12 \
-srcstoretype PKCS12 \
-srcstorepass p12password \
-alias 1
Or just use more user-friendly KeyMan from IBM for keystore handling instead of keytool.
I closed all the other projects and run my required project in isolation in Pycharm. I created a separate virtualenv from pycharm and added all the required modules in it by using pip. I added this virtual environment in project's interpreter. This solved my problem.
For CUDA7.5 these lines work:
sudo ln -s /usr/bin/gcc-4.9 /usr/local/cuda/bin/gcc
sudo ln -s /usr/bin/g++-4.9 /usr/local/cuda/bin/g++
All of them have there own uses:
If you have an iterable and need to traverse unconditionally to all of them:
for (iterable_type iterable_element : collection)
If you have an iterable but need to conditionally traverse:
for (Iterator iterator = collection.iterator(); iterator.hasNext();)
If data-structure does not implement iterable:
for (int i = 0; i < collection.length; i++)
If you're using Path
:
example_path = Path('/tmp/test.json')
example_dict = {'x': 24, 'y': 25}
json_str = json.dumps(example_dict, indent=4) + '\n'
example_path.write_text(json_str, encoding='utf-8')
To auto-generate the "source.list" file I suggest to use:
https://debgen.simplylinux.ch/
Where you can select the country, the distribution, ..etc After that, all you need to do is to replace (take a backup of the file first) your original source.list file with the generated one and do as mentioned in other answers:
sudo apt-get update
sudo apt-get install build-essential
Laravel 7.X In bootstrap.js, in axios related code, add:
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = $('meta[name="csrf-token"]').attr('content');
Solved lot of unexplained 500 ajax errors. Of course it's for those who use axios
If someone reads the original question to mean that they want to dynamically change the hover css and not just change the base css rule for the element, I've found this to work:
I have a dynamically loaded page that requires me to find out how high the container becomes after data is loaded. Once loaded, I want to change the hover effect of the css so that an element covers the resulting container. I need to change the css .daymark:hover rule to have a new height. This is how...
function changeAttr(attrName,changeThis,toThis){
var mysheet=document.styleSheets[1], targetrule;
var myrules=mysheet.cssRules? mysheet.cssRules: mysheet.rules;
for (i=0; i<myrules.length; i++){
if(myrules[i].selectorText.toLowerCase()==".daymark:hover"){ //find "a:hover" rule
targetrule=myrules[i];
break;
}
}
switch(changeThis)
{
case "height":
targetrule.style.height=toThis+"px";
break;
case "width":
targetrule.style.width=toThis+"px";
break;
}
}
In short slug help get rid of those ugly looking urls with valid-urls for examples in an ecommerec site instead of showing the url as www.myecom.com/product/5432156
i can show it like www.myecom.com/product/iphone11
with the help of slug
nchar(YOURSTRING)
you may need to convert to a character vector first;
nchar(as.character(YOURSTRING))
The JPanel
is actually only a container where you can put different elements in it (even other JPanels
). So in your case I would suggest one big JPanel
as some sort of main container for your window. That main panel you assign a Layout
that suits your needs ( here is an introduction to the layouts).
After you set the layout to your main panel you can add the paint panel and the other JPanels you want (like those with the text in it..).
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
JPanel paintPanel = new JPanel();
JPanel textPanel = new JPanel();
mainPanel.add(paintPanel);
mainPanel.add(textPanel);
This is just an example that sorts all sub panels vertically (Y-Axis). So if you want some other stuff at the bottom of your mainPanel (maybe some icons or buttons) that should be organized with another layout (like a horizontal layout), just create again a new JPanel as a container for all the other stuff and set setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS)
.
As you will find out, the layouts are quite rigid and it may be difficult to find the best layout for your panels. So don't give up, read the introduction (the link above) and look at the pictures – this is how I do it :)
Or you can just use NetBeans to write your program. There you have a pretty easy visual editor (drag and drop) to create all sorts of Windows and Frames. (only understanding the code afterwards is ... tricky sometimes.)
Since there are some many people interested in this question, I wanted to provide a complete example of how to layout a JFrame to make it look like OP wants it to.
The class is called MyFrame and extends swings JFrame
public class MyFrame extends javax.swing.JFrame{
// these are the components we need.
private final JSplitPane splitPane; // split the window in top and bottom
private final JPanel topPanel; // container panel for the top
private final JPanel bottomPanel; // container panel for the bottom
private final JScrollPane scrollPane; // makes the text scrollable
private final JTextArea textArea; // the text
private final JPanel inputPanel; // under the text a container for all the input elements
private final JTextField textField; // a textField for the text the user inputs
private final JButton button; // and a "send" button
public MyFrame(){
// first, lets create the containers:
// the splitPane devides the window in two components (here: top and bottom)
// users can then move the devider and decide how much of the top component
// and how much of the bottom component they want to see.
splitPane = new JSplitPane();
topPanel = new JPanel(); // our top component
bottomPanel = new JPanel(); // our bottom component
// in our bottom panel we want the text area and the input components
scrollPane = new JScrollPane(); // this scrollPane is used to make the text area scrollable
textArea = new JTextArea(); // this text area will be put inside the scrollPane
// the input components will be put in a separate panel
inputPanel = new JPanel();
textField = new JTextField(); // first the input field where the user can type his text
button = new JButton("send"); // and a button at the right, to send the text
// now lets define the default size of our window and its layout:
setPreferredSize(new Dimension(400, 400)); // let's open the window with a default size of 400x400 pixels
// the contentPane is the container that holds all our components
getContentPane().setLayout(new GridLayout()); // the default GridLayout is like a grid with 1 column and 1 row,
// we only add one element to the window itself
getContentPane().add(splitPane); // due to the GridLayout, our splitPane will now fill the whole window
// let's configure our splitPane:
splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); // we want it to split the window verticaly
splitPane.setDividerLocation(200); // the initial position of the divider is 200 (our window is 400 pixels high)
splitPane.setTopComponent(topPanel); // at the top we want our "topPanel"
splitPane.setBottomComponent(bottomPanel); // and at the bottom we want our "bottomPanel"
// our topPanel doesn't need anymore for this example. Whatever you want it to contain, you can add it here
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.Y_AXIS)); // BoxLayout.Y_AXIS will arrange the content vertically
bottomPanel.add(scrollPane); // first we add the scrollPane to the bottomPanel, so it is at the top
scrollPane.setViewportView(textArea); // the scrollPane should make the textArea scrollable, so we define the viewport
bottomPanel.add(inputPanel); // then we add the inputPanel to the bottomPanel, so it under the scrollPane / textArea
// let's set the maximum size of the inputPanel, so it doesn't get too big when the user resizes the window
inputPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, 75)); // we set the max height to 75 and the max width to (almost) unlimited
inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.X_AXIS)); // X_Axis will arrange the content horizontally
inputPanel.add(textField); // left will be the textField
inputPanel.add(button); // and right the "send" button
pack(); // calling pack() at the end, will ensure that every layout and size we just defined gets applied before the stuff becomes visible
}
public static void main(String args[]){
EventQueue.invokeLater(new Runnable(){
@Override
public void run(){
new MyFrame().setVisible(true);
}
});
}
}
Please be aware that this is only an example and there are multiple approaches to layout a window. It all depends on your needs and if you want the content to be resizable / responsive. Another really good approach would be the GridBagLayout which can handle quite complex layouting, but which is also quite complex to learn.
I started with Lua but, then I found that I wanted to see the results instead of just the good old command line flash. So i just added the following line to my file and hey presto, the standard:
please press any key to continue...
os.execute("PAUSE")
My example file is only a print and then a pause statment so I am sure you don't need that posted here.
I am not sure of the CPU implications of a running a process for a full script. However stopping the code mid flow in debugging could be useful.
I dug deeper into this and found the best solutions are here.
http://blog.notdot.net/2010/07/Getting-unicode-right-in-Python
In my case I solved "UnicodeEncodeError: 'charmap' codec can't encode character "
original code:
print("Process lines, file_name command_line %s\n"% command_line))
New code:
print("Process lines, file_name command_line %s\n"% command_line.encode('utf-8'))
Use dropna:
dat.dropna()
You can pass param how
to drop if all labels are nan or any of the labels are nan
dat.dropna(how='any') #to drop if any value in the row has a nan
dat.dropna(how='all') #to drop if all values in the row are nan
Hope that answers your question!
Edit 1:
In case you want to drop rows containing nan
values only from particular column(s), as suggested by J. Doe in his answer below, you can use the following:
dat.dropna(subset=[col_list]) # col_list is a list of column names to consider for nan values.
As the message says, you have to go to Apple, not Sun, for Java on the Mac. As far as I know, Apple JDK 6 is installed by default on Mac OS X 10.6 (Snow Leopard). Maybe you need to install the developer tools from your Mac OS X installation DVD (the dev tools are an optional install from the OS DVD).
See: http://developer.apple.com/java/
NOTE This answer from 16 Oct 2009 is now outdated; you can get the JDK for Mac OS X from the regular JDK download page on Oracle's website now.
Dynamically changing searches based on the given parameters is a complicated subject and doing it one way over another, even with only a very slight difference, can have massive performance implications. The key is to use an index, ignore compact code, ignore worrying about repeating code, you must make a good query execution plan (use an index).
Read this and consider all the methods. Your best method will depend on your parameters, your data, your schema, and your actual usage:
Dynamic Search Conditions in T-SQL by by Erland Sommarskog
The Curse and Blessings of Dynamic SQL by Erland Sommarskog
If you have the proper SQL Server 2008 version (SQL 2008 SP1 CU5 (10.0.2746) and later), you can use this little trick to actually use an index:
Add OPTION (RECOMPILE)
onto your query, see Erland's article, and SQL Server will resolve the OR
from within (@LastName IS NULL OR LastName= @LastName)
before the query plan is created based on the runtime values of the local variables, and an index can be used.
This will work for any SQL Server version (return proper results), but only include the OPTION(RECOMPILE) if you are on SQL 2008 SP1 CU5 (10.0.2746) and later. The OPTION(RECOMPILE) will recompile your query, only the verison listed will recompile it based on the current run time values of the local variables, which will give you the best performance. If not on that version of SQL Server 2008, just leave that line off.
CREATE PROCEDURE spDoSearch
@FirstName varchar(25) = null,
@LastName varchar(25) = null,
@Title varchar(25) = null
AS
BEGIN
SELECT ID, FirstName, LastName, Title
FROM tblUsers
WHERE
(@FirstName IS NULL OR (FirstName = @FirstName))
AND (@LastName IS NULL OR (LastName = @LastName ))
AND (@Title IS NULL OR (Title = @Title ))
OPTION (RECOMPILE) ---<<<<use if on for SQL 2008 SP1 CU5 (10.0.2746) and later
END
A javascript fix to apply the 'active' class to all labels that are parents of checked inputs:
$(':input:checked').parent('.btn').addClass('active');
insert right after
$('.btn').button();
To extend what Rahul Gupta said:
You can use Java function int random = Random.nextInt(n)
.
This returns a random int
in the range [0, n-1]
.
I.e., to get the range [20, 80]
use:
final int random = new Random().nextInt(61) + 20; // [0, 60] + 20 => [20, 80]
To generalize more:
final int min = 20;
final int max = 80;
final int random = new Random().nextInt((max - min) + 1) + min;
The problem is that POST method is forbidden for Nginx server's static files requests. Here is the workaround:
# Pass 405 as 200 for requested address:
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 404 /404.html;
error_page 403 /403.html;
error_page 405 =200 $uri;
}
If using proxy:
# If Nginx is like proxy for Apache:
error_page 405 =200 @405;
location @405 {
root /htdocs;
proxy_pass http://localhost:8080;
}
If using FastCGI:
location ~\.php(.*) {
fastcgi_pass 127.0.0.1:9000;
fastcgi_split_path_info ^(.+\.php)(.*)$;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
include /etc/nginx/fastcgi_params;
}
Browsers usually use GET, so you can use online tools like ApiTester to test your requests.
Have implemented @Micah 's solution to generate a trendline with a few changes and thought I'd share:
order=2
)Rval=True
)Code:
def trendline(xd, yd, order=1, c='r', alpha=1, Rval=False):
"""Make a line of best fit"""
#Calculate trendline
coeffs = np.polyfit(xd, yd, order)
intercept = coeffs[-1]
slope = coeffs[-2]
power = coeffs[0] if order == 2 else 0
minxd = np.min(xd)
maxxd = np.max(xd)
xl = np.array([minxd, maxxd])
yl = power * xl ** 2 + slope * xl + intercept
#Plot trendline
plt.plot(xl, yl, c, alpha=alpha)
#Calculate R Squared
p = np.poly1d(coeffs)
ybar = np.sum(yd) / len(yd)
ssreg = np.sum((p(xd) - ybar) ** 2)
sstot = np.sum((yd - ybar) ** 2)
Rsqr = ssreg / sstot
if not Rval:
#Plot R^2 value
plt.text(0.8 * maxxd + 0.2 * minxd, 0.8 * np.max(yd) + 0.2 * np.min(yd),
'$R^2 = %0.2f$' % Rsqr)
else:
#Return the R^2 value:
return Rsqr
The new version 2.4 of Apache HTTP Server has a module called mod_proxy_wstunnel which is a websocket proxy.
http://httpd.apache.org/docs/2.4/mod/mod_proxy_wstunnel.html
Adding a second drive is probably easiest. That would only take a few minutes, and it wouldn't require any configuration, really.
Alternatively, you could create the second, bigger drive, then run a disk imaging utility to copy all data on disk1 to disk2. That certainly shouldn't take a few hours, but it would take longer than just living with two drives.