th
elements in the table header or footer differs from number of columns in the table body or defined using columns
option.th
element in the table header.columnDefs.targets
option.th
elements in the table header or footer matches number of columns defined in the columns
option.colspan
attribute in the table header, make sure you have at least two header rows and one unique th
element for each column. See Complex header for more information.columnDefs.targets
option, make sure that zero-based column index refers to existing columns.See jQuery DataTables: Common JavaScript console errors - TypeError: Cannot read property ‘style’ of undefined for more information.
Inherit the tableview delegate and datasource. Implement delegates what you need.
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
And Finally implement this delegate
func tableView(_ tableView: UITableView, didSelectRowAt
indexPath: IndexPath) {
print("row selected : \(indexPath.row)")
}
1. Create class Name RecyclerTouchListener.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
public class RecyclerTouchListener implements RecyclerView.OnItemTouchListener
{
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child));
}
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildAdapterPosition(child));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
}
2. Call RecyclerTouchListener
recycleView.addOnItemTouchListener(new RecyclerTouchListener(this, recycleView,
new RecyclerTouchListener.ClickListener() {
@Override
public void onClick(View view, int position) {
Toast.makeText(MainActivity.this,Integer.toString(position),Toast.LENGTH_SHORT).show();
}
@Override
public void onLongClick(View view, int position) {
}
}));
Sooo simple to get row count:
cursor = dbObj.rawQuery("select count(*) from TABLE where COLUMN_NAME = '1' ", null);
cursor.moveToFirst();
String count = cursor.getString(cursor.getColumnIndex(cursor.getColumnName(0)));
I have the same problem....
I change my project name and i have this problem...my solution was the checking project refences and use /
in my web.xml (instead of /*
)
This is a one line solution.
It will run taskkill only if the process is really running otherwise it will just info that it is not running.
tasklist | find /i "notepad.exe" && taskkill /im notepad.exe /F || echo process "notepad.exe" not running.
This is the output in case the process was running:
notepad.exe 1960 Console 0 112,260 K
SUCCESS: The process "notepad.exe" with PID 1960 has been terminated.
This is the output in case not running:
process "notepad.exe" not running.
if you are using windows os and believe that skype is not the suspect, then you might want to check the task manager and check the "Show processes from all users" and make sure that there is NO entry for httpd.exe. Otherwise, end its process. That solves my problem.
Don't call methods within the Fragment that require getActivity() until onStart in the parent Activity.
private MyFragment myFragment;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
myFragment = new MyFragment();
ft.add(android.R.id.content, youtubeListFragment).commit();
//Other init calls
//...
}
@Override
public void onStart()
{
super.onStart();
//Call your Fragment functions that uses getActivity()
myFragment.onPageSelected();
}
As others have mentioned you have to consume stderr and stdout.
Compared to the other answers, since Java 1.7 it is even more easy. You do not have to create threads yourself anymore to read stderr and stdout.
Just use the ProcessBuilder
and use the methods redirectOutput
in combination with either redirectError
or redirectErrorStream
.
String directory = "/working/dir";
File out = new File(...); // File to write stdout to
File err = new File(...); // File to write stderr to
ProcessBuilder builder = new ProcessBuilder();
builder.directory(new File(directory));
builder.command(command);
builder.redirectOutput(out); // Redirect stdout to file
if(out == err) {
builder.redirectErrorStream(true); // Combine stderr into stdout
} else {
builder.redirectError(err); // Redirect stderr to file
}
Process process = builder.start();
Time 30 minutes later
$newTime = date("Y-m-d H:i:s",strtotime(date("Y-m-d H:i:s")." +30 minutes"))
I needed to print important warning about skipped tests exactly when PyTest
muted literally everything.
I didn't want to fail a test to send a signal, so I did a hack as follow:
def test_2_YellAboutBrokenAndMutedTests():
import atexit
def report():
print C_patch.tidy_text("""
In silent mode PyTest breaks low level stream structure I work with, so
I cannot test if my functionality work fine. I skipped corresponding tests.
Run `py.test -s` to make sure everything is tested.""")
if sys.stdout != sys.__stdout__:
atexit.register(report)
The atexit
module allows me to print stuff after PyTest
released the output streams. The output looks as follow:
============================= test session starts ==============================
platform linux2 -- Python 2.7.3, pytest-2.9.2, py-1.4.31, pluggy-0.3.1
rootdir: /media/Storage/henaro/smyth/Alchemist2-git/sources/C_patch, inifile:
collected 15 items
test_C_patch.py .....ssss....s.
===================== 10 passed, 5 skipped in 0.15 seconds =====================
In silent mode PyTest breaks low level stream structure I work with, so
I cannot test if my functionality work fine. I skipped corresponding tests.
Run `py.test -s` to make sure everything is tested.
~/.../sources/C_patch$
Message is printed even when PyTest
is in silent mode, and is not printed if you run stuff with py.test -s
, so everything is tested nicely already.
e.relatedTarget.data('load-url');
won't work
use dataset.loadUrl
$('#myModal').on('show.bs.modal', function (e) {
var loadurl = e.relatedTarget.dataset.loadUrl;
$(this).find('.modal-body').load(loadurl);
});
For no errors.
error_reporting(0);
or for just not strict
error_reporting(E_ALL ^ E_STRICT);
and if you ever want to display all errors again, use
error_reporting(-1);
Here are the steps to convert the entire column to date
format values.
Add a column to the right of the date column. Right click the new column and select Format
. Set the format to date
.
Highlight the entire old date column and copy it. Highlight the top cell of the new column and select Paste Special
, and only paste values
.
You can then remove the old column.
I think the fastest way to do this is:
GradientDrawable gradientDrawable = new GradientDrawable(
GradientDrawable.Orientation.TOP_BOTTOM, //set a gradient direction
new int[] {0xFF757775,0xFF151515}); //set the color of gradient
gradientDrawable.setCornerRadius(10f); //set corner radius
//Apply background to your view
View view = (RelativeLayout) findViewById( R.id.my_view );
if(Build.VERSION.SDK_INT>=16)
view.setBackground(gradientDrawable);
else view.setBackgroundDrawable(gradientDrawable);
This snippet is from working code.
You can trigger bat file not only from Windows GUI or Task Scheduler, but directly from PHP script when you need it. But in most cases it will have execution for 30-60 sec. depending from your PHP configuration. If job in BAT file is long and you don't want to freeze your PHP scripts, you need to fork BAT job as another process using php.exe
and not be dependable from Apache.
This runs in background mode in Windows, seen as separate processes cmd.exe
and php.exe
from Task Manager not halting your Apache PHP scripts. The messages produced by your script may be stored and retrieved back via log files.
In my case in file_scanner.php
I do some heavy calculations in loop for big array of files which may last for few hours with php function sleep()
not to overload CPU.
The success poiner result from file $r
which you can query via ajax if you want to know success or fauty start. In my case file_scanner.php
writes log file with messages somefile.jpg - OK
wich you can load to your UI with AJAX every few seconds to show progress.
PHP
/**
* Runs bat file in background mode
*
*/
function run_scanner() {
$c='start /b D:\Web\example.com\tasks\file_scanner.bat';
$r=pclose(popen($c, 'r'));
return json_encode(array('result'=>$r));
}
BAT
@echo Off
D:\PHP\php.exe D:\Web\example.com\tasks\file_scanner.php > D:\Web\example.com\tasks\file_scanner.log
exit
If you want see your buffer size in terminal, you can take a look at:
/proc/sys/net/ipv4/tcp_rmem
(for read) /proc/sys/net/ipv4/tcp_wmem
(for write)They contain three numbers, which are minimum, default and maximum memory size values (in byte), respectively.
In python, it's called slicing. Here is an example of python's slice notation:
>>> list1 = ['a','b','c','d','e','f','g','h', 'i', 'j', 'k', 'l']
>>> print list1[:5]
['a', 'b', 'c', 'd', 'e']
>>> print list1[-7:]
['f', 'g', 'h', 'i', 'j', 'k', 'l']
Note how you can slice either positively or negatively. When you use a negative number, it means we slice from right to left.
This works for me :
CREATE DEFINER=`root`@`%` PROCEDURE `save_package_as_template`( IN package_id int ,
IN bus_fun_temp_id int , OUT o_message VARCHAR (50) ,
OUT o_number INT )
BEGIN
DECLARE v_pkg_name varchar(50) ;
DECLARE v_pkg_temp_id int(10) ;
DECLARE v_workflow_count INT(10);
-- checking if workflow created for package
select count(*) INTO v_workflow_count from workflow w where w.package_id =
package_id ;
this_proc:BEGIN -- this_proc block start here
IF v_workflow_count = 0 THEN
select 'no work flow ' as 'workflow_status' ;
SET o_message ='Work flow is not created for this package.';
SET o_number = -2 ;
LEAVE this_proc;
END IF;
select 'work flow created ' as 'workflow_status' ;
-- To send some message
SET o_message ='SUCCESSFUL';
SET o_number = 1 ;
END ;-- this_proc block end here
END
In case of image stacks, I find it easier to use scikit-image
to read, and matplotlib
to show or save. I have handled 16-bit TIFF image stacks with the following code.
from skimage import io
import matplotlib.pyplot as plt
# read the image stack
img = io.imread('a_image.tif')
# show the image
plt.imshow(mol,cmap='gray')
plt.axis('off')
# save the image
plt.savefig('output.tif', transparent=True, dpi=300, bbox_inches="tight", pad_inches=0.0)
In your class AutoMapper
profile, you need to create a map for your entity and viewmodel.
This is usually in AutoMapper/DomainToViewModelMappingProfile
In Configure()
, add a line like
Mapper.CreateMap<YourEntityViewModel, YourEntity>();
In ViewModelToDomainMappingProfile
, add:
Mapper.CreateMap<YourEntity, YourEntityViewModel>();
Just use if
and env.BRANCH_NAME
, example:
if (env.BRANCH_NAME == "deployment") {
... do some build ...
} else {
... do something else ...
}
Try this
$('#add_here').text('new-dynamic-text');
The GetHashCode
function is specifically designed to create a well distributed range of integers with a low probability of collision, so for this use case is likely to be the best you can do.
But, as I'm sure you're aware, hashing 128 bits of information into 32 bits of information throws away a lot of data, so there will almost certainly be collisions if you have a sufficiently large number of GUIDs.
This is how you can create a beautiful button with a bezel and rounded edges:
loginButton = UIButton(frame: CGRectMake(self.view.bounds.origin.x + (self.view.bounds.width * 0.325), self.view.bounds.origin.y + (self.view.bounds.height * 0.8), self.view.bounds.origin.x + (self.view.bounds.width * 0.35), self.view.bounds.origin.y + (self.view.bounds.height * 0.05)))
loginButton.layer.cornerRadius = 18.0
loginButton.layer.borderWidth = 2.0
loginButton.backgroundColor = UIColor.whiteColor()
loginButton.layer.borderColor = UIColor.whiteColor().CGColor
loginButton.setTitle("Login", forState: UIControlState.Normal)
loginButton.setTitleColor(UIColor(red: 24.0/100, green: 116.0/255, blue: 205.0/205, alpha: 1.0), forState: UIControlState.Normal)
There are probably some commands to resolve it, but I would start by looking in your .git/config
file for references to that branch, and removing them.
Most people are using gson : check this
Gson gson = new Gson();
String json = gson.toJson(myObj);
We have various ways to convert a char
to String
. One way is to make use of static method toString()
in Character
class:
char ch = 'I';
String str1 = Character.toString(ch);
Actually this toString
method internally makes use of valueOf
method from String
class which makes use of char array:
public static String toString(char c) {
return String.valueOf(c);
}
So second way is to use this directly:
String str2 = String.valueOf(ch);
This valueOf
method in String
class makes use of char array:
public static String valueOf(char c) {
char data[] = {c};
return new String(data, true);
}
So the third way is to make use of an anonymous array to wrap a single character and then passing it to String
constructor:
String str4 = new String(new char[]{ch});
The fourth way is to make use of concatenation:
String str3 = "" + ch;
This will actually make use of append
method from StringBuilder
class which is actually preferred when we are doing concatenation in a loop.
For me, what worked was:
BeautifulSoup(html_text,from_encoding="utf-8")
Hope this helps someone.
Here's one possible method.
function isMouseInBox(e) {
var textbox = document.getElementById('textbox');
// Box position & sizes
var boxX = textbox.offsetLeft;
var boxY = textbox.offsetTop;
var boxWidth = textbox.offsetWidth;
var boxHeight = textbox.offsetHeight;
// Mouse position comes from the 'mousemove' event
var mouseX = e.pageX;
var mouseY = e.pageY;
if(mouseX>=boxX && mouseX<=boxX+boxWidth) {
if(mouseY>=boxY && mouseY<=boxY+boxHeight){
// Mouse is in the box
return true;
}
}
}
document.addEventListener('mousemove', function(e){
isMouseInBox(e);
})
Try:
SELECT DATE(`date_time_field`) AS date_part, TIME(`date_time_field`) AS time_part FROM `your_table`
Add a $event
to the ng-click
, for example:
<button type="button" ng-click="saveOffer($event)" accesskey="S"></button>
Then the jQuery.Event
was passed to the callback:
Subclass UILabel and override drawTextInRect:
like this:
- (void)drawTextInRect:(CGRect)rect
{
UIEdgeInsets insets = {0, 10, 0, 0};
return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}
You are sending a array of string
var usersRoles = [];
jQuery("#dualSelectRoles2 option").each(function () {
usersRoles.push(jQuery(this).val());
});
So change model type accordingly
public ActionResult AddUser(List<string> model)
{
}
Fighting whether the code is compiling or not I would say create a array of sixe 5 add 2 values and print them , you will get the two values and others are null. The question is although the size is 5 but there are 2 objects in the array . How to find how many objects are present in the array
Stack frame is the packed information related to a function call. This information generally includes arguments passed to th function, local variables and where to return upon terminating. Activation record is another name for a stack frame. The layout of the stack frame is determined in the ABI by the manufacturer and every compiler supporting the ISA must conform to this standard, however layout scheme can be compiler dependent. Generally stack frame size is not limited but there is a concept called "red/protected zone" to allow system calls...etc to execute without interfering with a stack frame.
There is always a SP but on some ABIs (ARM's and PowerPC's for example) FP is optional. Arguments that needed to be placed onto the stack can be offsetted using the SP only. Whether a stack frame is generated for a function call or not depends on the type and number of arguments, local variables and how local variables are accessed generally. On most ISAs, first, registers are used and if there are more arguments than registers dedicated to pass arguments these are placed onto the stack (For example x86 ABI has 6 registers to pass integer arguments). Hence, sometimes, some functions do not need a stack frame to be placed on the stack, just the return address is pushed onto the stack.
I agree with @haha on this one, for the most part. But there are several cross-browser related issues with using the "float:right" and could ultimately give you more of a headache than you want. If you know what the widths are going to be for each column use a float:left on both and save yourself the trouble. Another thing you can incorporate into your methodology is build column classes into your CSS.
So try something like this:
CSS
.col-wrapper{width:960px; margin:0 auto;}
.col{margin:0 10px; float:left; display:inline;}
.col-670{width:670px;}
.col-250{width:250px;}
HTML
<div class="col-wrapper">
<div class="col col-670">[Page Content]</div>
<div class="col col-250">[Page Sidebar]</div>
</div>
When TypeScript thinks that property "x" does not exist on "y", then you can always cast "y" into "any", which will allow you to call anything (like "x") on "y".
Theory
(<any>y).x;
Real World Example
I was getting the error "TS2339: Property 'name' does not exist on type 'Function'" for this code:
let name: string = this.constructor.name;
So I fixed it with:
let name: string = (<any>this).constructor.name;
Your server tells you exactly what you need : [Hint: SSLProxyEngine]
You need to add that directive to your VirtualHost
before the Proxy
directives :
SSLProxyEngine on
ProxyPass /primary/store https://localhost:9763/store/
ProxyPassReverse /primary/store https://localhost:9763/store/
I think you're supposed to place clearApplicationData()
before the super.OnDestroy().
Your app can't process any methods when it has been shut down.
Change:
profileImage.setImageBitmap(
BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)
To:
Bitmap b = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)
profileImage.setImageBitmap(Bitmap.createScaledBitmap(b, 120, 120, false));
Swift 5: Use following code
extension Double {
func getStringValue(withFloatingPoints points: Int = 0) -> String {
let valDouble = modf(self)
let fractionalVal = (valDouble.1)
if fractionalVal > 0 {
return String(format: "%.*f", points, self)
}
return String(format: "%.0f", self)
}
}
You have to return JSON error object yourself after setting the StatusCode, like so ...
if (BadRequest)
{
Dictionary<string, object> error = new Dictionary<string, object>();
error.Add("ErrorCode", -1);
error.Add("ErrorMessage", "Something really bad happened");
return Json(error);
}
Another way is to have a JsonErrorModel
and populate it
public class JsonErrorModel
{
public int ErrorCode { get; set;}
public string ErrorMessage { get; set; }
}
public ActionResult SomeMethod()
{
if (BadRequest)
{
var error = new JsonErrorModel
{
ErrorCode = -1,
ErrorMessage = "Something really bad happened"
};
return Json(error);
}
//Return valid response
}
Take a look at the answer here as well
Java is not platform independent in that it runs on the JVM. Having said that, you gain platform independence via programming against a single abstract machine that has concrete realizations on most common OS platforms (and some embedded appliances).
A related idea is the hardware abstraction layer present in many operating systems that allows the same OS to run on disparate hardware.
In you original question, Turbo C is analagous to the javac program, and the JVM is the OS/HAL.
We got this error when reusing the ConnectionString from EntityFramework connection. We have Username and Password in the connection string but didn't specify "Persist Security Info=True". Thus, the credentials were removed from the connection string after establishing the connection (so we reused an incomplete connection string). Of course, we always have to think twice when using this setting, but in this particular case, it was ok.
You can instantiate an object from matplotlib.pyplot.axes
and call the set_ylim()
on it. It would be something like this:
import matplotlib.pyplot as plt
axes = plt.axes()
axes.set_ylim([0, 1])
Just pass a callback as argument like this:
function getMeta(url, callback) {_x000D_
var img = new Image();_x000D_
img.src = url;_x000D_
img.onload = function() { callback(this.width, this.height); }_x000D_
}_x000D_
getMeta(_x000D_
"http://snook.ca/files/mootools_83_snookca.png",_x000D_
function(width, height) { alert(width + 'px ' + height + 'px') }_x000D_
);
_x000D_
You actually need 3 meta
tags to support Android, iPhone and Windows Phone
<!-- Chrome, Firefox OS and Opera -->
<meta name="theme-color" content="#4285f4">
<!-- Windows Phone -->
<meta name="msapplication-navbutton-color" content="#4285f4">
<!-- iOS Safari -->
<meta name="apple-mobile-web-app-status-bar-style" content="#4285f4">
As of (dplyr 1.0.0) we can use across()
For all columns:
dat <- dat %>%
mutate(across(everything(), ~ifelse(.=="", NA, as.character(.))))
For individual columns:
dat <- dat %>%
mutate(across(c("Age","Gender"), ~ifelse(.=="", NA, as.character(.))))
As of (dplyr 0.8.0 above) the way this should be written has changed. Before it was, funs()
in .funs (funs(name = f(.))
. Instead of funs
, now we use list (list(name = ~f(.)))
Note that there is also a much simpler way to list the column names ! (both the name of the column and column index work)
dat <- dat %>%
mutate_at(.vars = c("Age","Gender"),
.funs = list(~ifelse(.=="", NA, as.character(.))))
Original Answer:
You can also use mutate_at
in dplyr
dat <- dat %>%
mutate_at(vars(colnames(.)),
.funs = funs(ifelse(.=="", NA, as.character(.))))
Select individual columns to change:
dat <- dat %>%
mutate_at(vars(colnames(.)[names(.) %in% c("Age","Gender")]),
.funs = funs(ifelse(.=="", NA, as.character(.))))
Use deactivate
.
(my_env) user@user:~/my_env$ deactivate
user@user-Lenovo-E40-80:~/my_env$
Note, (my_env)
is gone.
According to the documentation you can simply return false;
to break:
$(xml).find("strengths").each(function() {
if (iWantToBreak)
return false;
});
Try this:
Open PgAdmin -> Files -> Open pgpass.conf
You would get the path of pgpass.conf
at the bottom of the window.
Go to that location and open this file, you can find your password there.
If the above does not work, you may consider trying this:
1. edit pg_hba.conf to allow trust authorization temporarily
2. Reload the config file (pg_ctl reload)
3. Connect and issue ALTER ROLE / PASSWORD to set the new password
4. edit pg_hba.conf again and restore the previous settings
5. Reload the config file again
Sub LoopRange()
Dim rCell As Range
Dim rRng As Range
Set rRng = Sheet1.Range("A1:A6")
For Each rCell In rRng.Cells
Debug.Print rCell.Address, rCell.Value
Next rCell
End Sub
I had a similar issue. The next solution is in *case to can't launch the server Locally * and you will see the same error msg.(Image 1)
To solve that and have the server working you must have the next steps.
I hope that works for you or others with similar issues. Follow me for more tips.
The original accepted answer mentions jquery.cookie plugin. A few months ago though, it was renamed to js-cookie and the jQuery dependency removed. One of the reasons was just to make it easy to integrate with other frameworks, like Angular.
Now, if you want to integrate js-cookie with angular, it is as easy as something like:
module.factory( "cookies", function() {
return Cookies.noConflict();
});
And that's it. No jQuery. No ngCookies.
You can also create custom instances to handle specific server-side cookies that are written differently. Take for example PHP, that convert the spaces in the server-side to a plus sign
+
instead of also percent-encode it:
module.factory( "phpCookies", function() {
return Cookies
.noConflict()
.withConverter(function( value, name ) {
return value
// Decode all characters according to the "encodeURIComponent" spec
.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent)
// Decode the plus sign to spaces
.replace(/\+/g, ' ')
});
});
The usage for a custom Provider would be something like this:
module.service( "customDataStore", [ "phpCookies", function( phpCookies ) {
this.storeData = function( data ) {
phpCookies.set( "data", data );
};
this.containsStoredData = function() {
return phpCookies.get( "data" );
}
}]);
I hope this helps anyone.
See detailed info in this issue: https://github.com/js-cookie/js-cookie/issues/103
For detailed docs on how to integrate with server-side, see here: https://github.com/js-cookie/js-cookie/blob/master/SERVER_SIDE.md
Update for Python 3.4+ pathlib
that actually answers the question:
from pathlib import Path
relative = Path("mydir/myfile.txt")
absolute = relative.absolute() # absolute is a Path object
If you only need a temporary string, keep in mind that you can use Path
objects with all the relevant functions in os.path
, including of course abspath
:
from os.path import abspath
absolute = abspath(relative) # absolute is a str object
Use Timer for every second...
new Timer().scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
//your method
}
}, 0, 1000);//put here time 1000 milliseconds=1 second
This is how you can do it-
HTML-
<div style="overflow:hidden; height:100%">
<div style="float:left">a<br>b</div>
<table cellpadding="0" cellspacing="0" style="height:100%;">
<tr><td>This is the content of a table that takes 100% height</td></tr>
</table>
</div>
CSS-
html,body
{
height:100%;
background-color:grey;
}
table
{
background-color:yellow;
}
See the DEMO
Update: Well, if you are not looking for applying 100% height to your parent containers, then here is a jQuery solution that should help you-
Script-
$(document).ready(function(){
var b= $(window).height(); //gets the window's height, change the selector if you are looking for height relative to some other element
$("#tab").css("height",b);
});
For example, my module names are like jan_module
/feb_module
/mar_module
.
month = 'feb'
exec 'from %s_module import *'%(month)
A lot of these solutions work. However, if all you want is to be able to set the margin between items the simplest method I have come up with is to wrap your item - in your case the CheckedTextView - in a LinearLayout and put your margin formatting for the item in that, not the root-layout. Be sure to give this wrapping layout an id and create it along with your CheckedTextView in your adapter.
That's it. In effect, you are instantiating the margin at the item level for the ListView. Because the ListView does not know about any item layout - only your adapter does. This basically inflates the part of the item layout that was being ignored before.
For Google Chrome Version 84.0.4147.105 and higher,
just right click and click 'Save as' and 'Save'
then, txt file will be saved
You're looking for case
:
case when action = 2 and state = 0 then 1 else 0 end as state
MySQL has an if
syntax (if(action=2 and state=0, 1, 0)
), but case
is more universal.
Note that the as state
there is just aliasing the column. I'm assuming this is in the column list of your SQL query.
You can try one of the following:
Method 1:
MyProject
go build
./MyProject
You can do both steps at once by typing go build && ./MyProject
. Go files of the package main
are compiled to an executable.
Method 2:
go run *.go
. It won't create any executable but it runs.To expand on Marian Udrea's answer:
In my scenario, I was trying to align the text with a material icon. There's something weird about material icons that prevented it from being aligned. None of the answers were working, until I added the vertical-align
to the icon element, instead of the parent element.
So, if the icon is 24px
in height:
.parent {
line-height: 24px; // Same as icon height
i.material-icons { // Only if you're using material icons
display: inline-flex;
vertical-align: top;
}
}
This is a one-line shorthand for an if-else statement. It's called the conditional operator.1
Here is an example of code that could be shortened with the conditional operator:
var userType;
if (userIsYoungerThan18) {
userType = "Minor";
} else {
userType = "Adult";
}
if (userIsYoungerThan21) {
serveDrink("Grape Juice");
} else {
serveDrink("Wine");
}
This can be shortened with the ?:
like so:
var userType = userIsYoungerThan18 ? "Minor" : "Adult";
serveDrink(userIsYoungerThan21 ? "Grape Juice" : "Wine");
Like all expressions, the conditional operator can also be used as a standalone statement with side-effects, though this is unusual outside of minification:
userIsYoungerThan21 ? serveGrapeJuice() : serveWine();
They can even be chained:
serveDrink(userIsYoungerThan4 ? 'Milk' : userIsYoungerThan21 ? 'Grape Juice' : 'Wine');
Be careful, though, or you will end up with convoluted code like this:
var k = a ? (b ? (c ? d : e) : (d ? e : f)) : f ? (g ? h : i) : j;
1 Often called "the ternary operator," but in fact it's just a ternary operator [an operator accepting three operands]. It's the only one JavaScript currently has, though.
The problem is in your main.ts
file.
const platform = platformBrowserDynamic();
platform.bootstrapModule(App);
You are trying to bootstrap App
, which is not a real module.
Delete these two lines and replace with the following line:
platformBrowserDynamic().bootstrapModule(AppModule);
and it will fix your error.
It depends..
SELECT x.col
FROM big_table x
WHERE x.key IN( SELECT key FROM really_big_table );
would not be relatively slow the isn't much to limit size of what the query check to see if they key is in. EXISTS would be preferable in this case.
But, depending on the DBMS's optimizer, this could be no different.
As an example of when EXISTS is better
SELECT x.col
FROM big_table x
WHERE EXISTS( SELECT key FROM really_big_table WHERE key = x.key);
AND id = very_limiting_criteria
It means the jar files are missing from the path that you have given while configuring Build Path/adding jars to the project.
Just once again configure the jars.
following for different plateform
WINDOWS: Ctrl + F12
LINUX: Ctrl + F12
MAC OS X: control + F12 (or fn + control + F12, depending on your keyboard configuration)
sdas is being read as a variable. To input a string you need " "
The type initializer for 'CSMessageUtility.CSDetails' threw an exception.
means that the static constructor on that class threw an Exception - so you need to look either in the static constructor of the CSDetails class, or in the initialisation of any static members of that class.
Convert PPK to OpenSSh
OS X: Install Homebrew, then run
brew install putty
Place your keys in some directory, e.g. your home folder. Now convert the PPK keys to SSH keypairs:cache search
To generate the private key:
cd ~
puttygen id_dsa.ppk -O private-openssh -o id_dsa
and to generate the public key:
puttygen id_dsa.ppk -O public-openssh -o id_dsa.pub
Move these keys to ~/.ssh and make sure the permissions are set to private for your private key:
mkdir -p ~/.ssh
mv -i ~/id_dsa* ~/.ssh
chmod 600 ~/.ssh/id_dsa
chmod 666 ~/.ssh/id_dsa.pub
connect with ssh server
ssh -i ~/.ssh/id_dsa username@servername
Port Forwarding to connect mysql remote server
ssh -i ~/.ssh/id_dsa -L 9001:127.0.0.1:3306 username@serverName
The solution was as simple as adding plt.show()
at the end of the code snippet:
import numpy as np
np.random.seed(123)
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras.datasets import mnist
(X_train,y_train),(X_test,y_test) = mnist.load_data()
print X_train.shape
from matplotlib import pyplot as plt
plt.imshow(X_train[0])
plt.show()
First of all, you have got the concept of hashing a little wrong and it had been rectified by Mr. Sanjay.
And yes, Java indeed implement a collision resolution technique. When two keys get hashed to a same value (as the internal array used is finite in size and at some point the hashcode() method will return same hash value for two different keys) at this time, a linked list is formed at the bucket location where all the informations are entered as an Map.Entry object that contains a key-value pair. Accessing an object via a key will at worst require O(n) if the entry in present in such a lists. Comparison between the key you passed with each key in such list will be done by the equals() method.
Although, from Java 8 , the linked lists are replaced with trees (O(log n))
Change display:inline to display:inline-block
.test {
width:200px;
display:inline-block;
overflow: auto;
white-space: nowrap;
margin:0px auto;
border:1px red solid;
}
If you use oh-my-zsh (which every trendy geek should use), after activating the "osx" plugin in .zshrc
, simply enter the tab
command; it will open a new tab and cd
in the directory your were on.
Apple simply recommends declaring an isX
getter for stylistic purposes. It doesn't matter whether you customize the getter name or not, as long as you use the dot notation or message notation with the correct name. If you're going to use the dot notation it makes no difference, you still access it by the property name:
@property (nonatomic, assign) BOOL working;
[self setWorking:YES]; // Or self.working = YES;
BOOL working = [self working]; // Or = self.working;
Or
@property (nonatomic, assign, getter=isWorking) BOOL working;
[self setWorking:YES]; // Or self.working = YES;, same as above
BOOL working = [self isWorking]; // Or = self.working;, also same as above
Here's a solution that (1) doesn't require any code changes or breakpoints, and (2) pauses after program termination so that you can see everything that was printed. It will pause after either F5 or Ctrl+F5. The major downside is that on VS2013 Express (as tested), it doesn't load symbols, so debugging is very restricted.
Create a batch file. I called mine runthenpause.bat
, with the following contents:
%1 %2 %3 %4 %5 %6 %7 %8 %9
pause
The first line will run whatever command you provide and up to eight arguments. The second line will... pause.
Open the project properties | Configuration properties | Debugging.
$(TargetPath)
(or whatever is in "Command").runthenpause.bat
.Now, when you run, runthenpause.bat
will launch your application, and after your application has terminated, will pause for you to see the console output.
I will post an update if I figure out how to get the symbols loaded. I tried /Z7
per this but without success.
If you can ping the FQDN, look at how DNS devolution is set up the PC.
Winsock API which MS ping will automatically use the FQDN of the client PC if append primary and connection specific DNS suffix is checked in TCP/IP advanced DNS settings. If the host is in another domain, the client must perform DNS devolution.
Under XP TCP/IP advanced properties DNS, make sure append parent suffixes is checked so that the ping request traverses the domain back to the parent.
Using AOP/AspectJ and @Loggable
annotation from jcabi-aspects you can do it easy and compact:
@Loggable(Loggable.DEBUG)
public String getSomeResult() {
// return some value
}
Every call to this method will be sent to SLF4J logging facility with DEBUG
logging level. And every log message will include execution time.
You cannot session_start(); when your buffer has already been partly sent.
This mean, if your script already sent informations (something you want, or an error report) to the client, session_start() will fail.
In Laravel 7.x and above, you can just do:
$data = Images::all()->random(4);
you need to use the htmlAttributes anonymous object, like this:
<%= Html.ActionLink("linky", "action", "controller", new { onclick = "someFunction();"}) %>
you could also give it an id an attach to it with jquery/whatever, like this:
<%= Html.ActionLink("linky", "action", "controller", new { id = "myLink" }) %>
$('#myLink').click(function() { /* bla */ });
I just add this because it worked for me, i install composer with the developer option activate (just check the box in the installer)
https://getcomposer.org/Composer-Setup.exe
I think this problem may occurs when you add a new version of php to your wamp server. If you do this, you have to check if the extension_dir variable is configure to "env".
Then check if the php_openssl.dll exist in your phpx.x/ext folder. If there is not php_openssl.dll, you have to download it here : http://www.telecharger-dll.fr/dll-php_openssl.dll.html
If it still not working, check if your apache server use the good php.ini file by running the following cmd command :
php --ini
Configuration File (php.ini) Path: C:\Windows
Loaded Configuration File: C:\wamp64\bin\php\php7.4.7x64\php.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed: (none)
If the loaded configuration file return (none), you have to check your appache/apache2.4.41/conf/httpd.conf file is configure with the proper phpIniDir and the correct module.
It must be something like this :
PHPIniDir "${APACHE_DIR}/bin"
LoadModule php7_module "${INSTALL_DIR}/bin/php/php7.4.7x64/php7apache2_4.dll"
Then restart apache and check the "apache/apache2.4.41/bin/php.ini" (wich is the one configure above by PHPIniDir) it must me like
If wont work in case you have something like : novalidate="novalidate" attached to your form.
For big array, is better to concatenate without array_merge, for avoid a memory copy.
$array1 = array_fill(0,50000,'aa');
$array2 = array_fill(0,100,'bb');
// Test 1 (array_merge)
$start = microtime(true);
$r1 = array_merge($array1, $array2);
echo sprintf("Test 1: %.06f\n", microtime(true) - $start);
// Test2 (avoid copy)
$start = microtime(true);
foreach ($array2 as $v) {
$array1[] = $v;
}
echo sprintf("Test 2: %.06f\n", microtime(true) - $start);
// Test 1: 0.004963
// Test 2: 0.000038
OS_ACTIVITY_MODE didn't work for me (it may have been because I typo'd disable
as disabled
, but isn't that more natural?!?), or at least didn't prevent a great deal of messages. So here's the real deal with the environment variables.
https://llvm.org/svn/llvm-project/lldb/trunk/source/Plugins/Platform/MacOSX/PlatformDarwin.cpp
lldb_private::Error
PlatformDarwin::LaunchProcess(lldb_private::ProcessLaunchInfo &launch_info) {
// Starting in Fall 2016 OSes, NSLog messages only get mirrored to stderr
// if the OS_ACTIVITY_DT_MODE environment variable is set. (It doesn't
// require any specific value; rather, it just needs to exist).
// We will set it here as long as the IDE_DISABLED_OS_ACTIVITY_DT_MODE flag
// is not set. Xcode makes use of IDE_DISABLED_OS_ACTIVITY_DT_MODE to tell
// LLDB *not* to muck with the OS_ACTIVITY_DT_MODE flag when they
// specifically want it unset.
const char *disable_env_var = "IDE_DISABLED_OS_ACTIVITY_DT_MODE";
auto &env_vars = launch_info.GetEnvironmentEntries();
if (!env_vars.ContainsEnvironmentVariable(disable_env_var)) {
// We want to make sure that OS_ACTIVITY_DT_MODE is set so that
// we get os_log and NSLog messages mirrored to the target process
// stderr.
if (!env_vars.ContainsEnvironmentVariable("OS_ACTIVITY_DT_MODE"))
env_vars.AppendArgument(llvm::StringRef("OS_ACTIVITY_DT_MODE=enable"));
}
// Let our parent class do the real launching.
return PlatformPOSIX::LaunchProcess(launch_info);
}
So setting OS_ACTIVITY_DT_MODE
to "NO" in the environment variables (GUI method explained in Schemes screenshot in main answer) makes it work for me.
As far as NSLog
being the dumping ground for system messages, errors, and your own debugging: a real logging approach is probably called for anyway, e.g. https://github.com/fpillet/NSLogger .
OR
Drink the new Kool-Aid: http://asciiwwdc.com/2016/sessions/721 https://developer.apple.com/videos/play/wwdc2016/721/ It's not surprising that there are some hitches after overhauling the entire logging API.
ADDENDUM
Anyway, NSLog
is just a shim:
https://developer.apple.com/library/content/releasenotes/Miscellaneous/RN-Foundation-OSX10.12/
NSLog / CFLog
NSLog is now just a shim to os_log in most circumstances.
Only makes sense now to quote the source for the other env variable. Quite a disparate place, this time from Apple internals. Not sure why they are overlapping. [Incorrect comment about NSLog
removed]
[Edited 22 Sep]: I wonder what "release" and "stream" do differently than "debug". Not enough source.
e = getenv("OS_ACTIVITY_MODE");
if (e) {
if (strcmp(e, "release") == 0) {
mode = voucher_activity_mode_release;
} else if (strcmp(e, "debug") == 0) {
mode = voucher_activity_mode_debug;
} else if (strcmp(e, "stream") == 0) {
mode = voucher_activity_mode_stream;
} else if (strcmp(e, "disable") == 0) {
mode = voucher_activity_mode_disable;
}
}
I found this method to be quite useful. However it will convert your date/time format to just date but never the less it does the job for what I need it for. (I just needed to display the date on a report, the time was irrelevant).
CAST(start_date AS DATE)
UPDATE
(Bear in mind I'm a trainee ;))
I figured an easier way to do this IF YOU'RE USING SSRS.
It's easier to actually change the textbox properties where the field is located in the report. Right click field>Number>Date and select the appropriate format!
Give the command SHOW CREATE TABLE whatever
Then look at the table definition.
It probably has a line like this
logtime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
in it. DEFAULT CURRENT_TIMESTAMP
means that any INSERT
without an explicit time stamp setting uses the current time. Likewise, ON UPDATE CURRENT_TIMESTAMP
means that any update without an explicit timestamp results in an update to the current timestamp value.
You can control this default behavior when creating your table.
Or, if the timestamp column wasn't created correctly in the first place, you can change it.
ALTER TABLE whatevertable
CHANGE whatevercolumn
whatevercolumn TIMESTAMP NOT NULL
DEFAULT CURRENT_TIMESTAMP
ON UPDATE CURRENT_TIMESTAMP;
This will cause both INSERT and UPDATE operations on the table automatically to update your timestamp column. If you want to update whatevertable
without changing the timestamp, that is,
To prevent the column from updating when other columns change
then you need to issue this kind of update.
UPDATE whatevertable
SET something = 'newvalue',
whatevercolumn = whatevercolumn
WHERE someindex = 'indexvalue'
This works with TIMESTAMP
and DATETIME
columns. (Prior to MySQL version 5.6.5 it only worked with TIMESTAMP
s) When you use TIMESTAMP
s, time zones are accounted for: on a correctly configured server machine, those values are always stored in UTC and translated to local time upon retrieval.
points
is not within the function's scope. You can grab a reference to the variable by using nonlocal:
points = 0
def test():
nonlocal points
points += 1
If points
inside test()
should refer to the outermost (module) scope, use global:
points = 0
def test():
global points
points += 1
You can do this using jQuery.offset()
and jQuery.animate()
.
Check out the jsFiddle Demonstration.
function scrollToAnchor(aid){
var aTag = $("a[name='"+ aid +"']");
$('html,body').animate({scrollTop: aTag.offset().top},'slow');
}
scrollToAnchor('id3');
If you don't want to install TortoiseSVN, you can simply install 'Subversion for Windows' from here:
http://sourceforge.net/projects/win32svn/
After installing, just open up a command prompt, go the folder you want to download into, then past in the checkout command as indicated on the project's 'source' page. E.g.
svn checkout http://projectname.googlecode.com/svn/trunk/ projectname-read-only
Note the space between the URL and the last string is intentional, the last string is the folder name into which the source will be downloaded.
If you have a collection of objects that you load using stored procedure you can also use LoadFromCollection
.
using (ExcelPackage package = new ExcelPackage(file))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("test");
worksheet.Cells["A1"].LoadFromCollection(myColl, true, OfficeOpenXml.Table.TableStyles.Medium1);
package.Save();
}
Its supported in notepad++ 5.0+ but not enabled by default. You can enable it from settings -> preferences
laravel have own function skip
for offset
and take
for limit
. just like below example of laravel query :-
Article::where([['user_id','=',auth()->user()->id]])
->where([['title','LIKE',"%".$text_val."%"]])
->orderBy('id','DESC')
->skip(0)
->take(2)
->get();
I think you are looking for this?
var correctAnswer = Answers.First(a => a.Correct);
You can use single by typing :
var correctAnswer = Answers.Single(a => a.Correct);
The SignTool is available as part of the Windows SDK (which comes with Visual Studio Community 2015). Make sure to select the "ClickOnce Publishing Tools" from the feature list during the installation of Visual Studio 2015 to get the SignTool.
Once Visual Studio is installed you can run the signtool
command from the Visual Studio Command Prompt. By default (on Windows 10) the SignTool will be installed at C:\Program Files (x86)\Windows Kits\10\bin\x86\signtool.exe
.
ClickOnce Publishing Tools Installation:
SignTool Location:
$('#submit1, #submit2').click(function () {
if (this.id == 'submit1') {
alert('Submit 1 clicked');
}
else if (this.id == 'submit2') {
alert('Submit 2 clicked');
}
});
I have same problem after update android studio to 1.5, and i fix it by update the gradle location,
Hope this method works for you,
With me, this problem in base Address in app.config of WCF service: When I've used:
<baseAddresses><add baseAddress="http://127.0.0.1:9022/Service/GatewayService"/> </baseAddresses>
it's ok if use .net to connect with public ip or domain.
But when use PHP's SoapClient to connect to "http://[online ip]:9022/Service/GatewayService
", it's throw exception "Coulod not connect to host"
I've changed baseAddress to [online ip]:9022 and everything's ok.
These are configurable variables in php.ini:
; with sane limits
xdebug.var_display_max_depth = 10
xdebug.var_display_max_children = 256
xdebug.var_display_max_data = 1024
; with no limits
; (maximum nesting is 1023)
xdebug.var_display_max_depth = -1
xdebug.var_display_max_children = -1
xdebug.var_display_max_data = -1
Of course, these may also be set at runtime via ini_set()
, useful if you don't want to modify php.ini and restart your web server but need to quickly inspect something more deeply.
ini_set('xdebug.var_display_max_depth', '10');
ini_set('xdebug.var_display_max_children', '256');
ini_set('xdebug.var_display_max_data', '1024');
Xdebug settings are explained in the official documentation.
When the Main class is inside a package then you need to run it as follows :
java <packageName>.<MainClassName>
In your case you should run the program as follows :
java org.tij.exercises.HelloWorld
There are several ways to achieve this.
Probably the easiest would be to use JavaScript to change the form's action.
<input type="submit" value="SecondServlet" onclick="form.action='SecondServlet';">
But this of course won't work when the enduser has JS disabled (mobile browsers, screenreaders, etc).
Another way is to put the second button in a different form, which may or may not be what you need, depending on the concrete functional requirement, which is not clear from the question at all.
<form action="FirstServlet" method="Post">
Last Name: <input type="text" name="lastName" size="20">
<br><br>
<input type="submit" value="FirstServlet">
</form>
<form action="SecondServlet" method="Post">
<input type="submit"value="SecondServlet">
</form>
Note that a form would on submit only send the input data contained in the very same form, not in the other form.
Again another way is to just create another single entry point servlet which delegates further to the right servlets (or preferably, the right business actions) depending on the button pressed (which is by itself available as a request parameter by its name
):
<form action="MainServlet" method="Post">
Last Name: <input type="text" name="lastName" size="20">
<br><br>
<input type="submit" name="action" value="FirstServlet">
<input type="submit" name="action" value="SecondServlet">
</form>
with the following in MainServlet
String action = request.getParameter("action");
if ("FirstServlet".equals(action)) {
// Invoke FirstServlet's job here.
} else if ("SecondServlet".equals(action)) {
// Invoke SecondServlet's job here.
}
This is only not very i18n/maintenance friendly. What if you need to show buttons in a different language or change the button values while forgetting to take the servlet code into account?
A slight change is to give the buttons its own fixed and unique name, so that its presence as request parameter could be checked instead of its value which would be sensitive to i18n/maintenance:
<form action="MainServlet" method="Post">
Last Name: <input type="text" name="lastName" size="20">
<br><br>
<input type="submit" name="first" value="FirstServlet">
<input type="submit" name="second" value="SecondServlet">
</form>
with the following in MainServlet
if (request.getParameter("first") != null) {
// Invoke FirstServlet's job here.
} else if (request.getParameter("second") != null) {
// Invoke SecondServlet's job here.
}
Last way would be to just use a MVC framework like JSF so that you can directly bind javabean methods to buttons, but that would require drastic changes to your existing code.
<h:form>
Last Name: <h:inputText value="#{bean.lastName}" size="20" />
<br/><br/>
<h:commandButton value="First" action="#{bean.first}" />
<h:commandButton value="Second" action="#{bean.Second}" />
</h:form>
with just the following javabean instead of a servlet
@ManagedBean
@RequestScoped
public class Bean {
private String lastName; // +getter+setter
public void first() {
// Invoke original FirstServlet's job here.
}
public void second() {
// Invoke original SecondServlet's job here.
}
}
In my case I was trying to test SSL in my Visual Studio environment using IIS 7.
This is what I ended up doing to get it to work:
Under my site in the 'Bindings...' section on the right in IIS, I had to add the 'https' binding to port 443 and select "IIS Express Developement Certificate".
Under my site in the 'Advanced Settings...' section on the right I had to change the 'Enabled Protocols' from "http" to "https".
Under the 'SSL Settings' icon I selected 'Accept' for client certificates.
Then I had to recycle the app pool.
I also had to import the local host certificate into my personal store using mmc.exe.
My web.config
file was already configured correctly, so after I got all the above sorted out, I was able to continue my testing.
Since you also have PHP in the tag, I'm going to suggest some server side options.
The easiest solution is the one most people suggest here. The problem I generally have with this, is that it can causes your CSS files or <style> tags to be up to 20 times bigger than your html documents and can cause browser slowdowns for parsing and processing tags that it can't understand -moz-border-radius
vs -webkit-border-radius
The second best solution(i've found) is to have php output your actual css file i.e.
<link rel="stylesheet" type="text/css" href="mycss.php">
where
<?php header("Content-Type: text/css"); if( preg_match("/chrome/", $_SERVER['HTTP_USER_AGENT']) ) { // output chrome specific css style } else { // output default css style } ?>
This allows you to create smaller easier to process files for the browser.
The best method I've found, is specific to Apache though. The method is to use mod_rewrite or mod_perl's PerlMapToStorageHandler to remap the URL to a file on the system based on the rendering engine.
say your website is http://www.myexample.com/
and it points to /srv/www/html
. For chrome, if you ask for main.css, instead of loading /srv/www/html/main.css
it checks to see if there is a /srv/www/html/main.webkit.css
and if it exists, it dump that, else it'll output the main.css. For IE, it tries main.trident.css
, for firefox it tries main.gecko.css
. Like above, it allows me to create smaller, more targeted, css files, but it also allows me to use caching better, as the browser will attempt to redownload the file, and the web server will present the browser with proper 304's to tell it, you don't need to redownload it. It also allows my web developers a bit more freedom without for them having to write backend code to target platforms. I also have .js files being redirected to javascript engines as well, for main.js
, in chrome it tries main.v8.js
, in safari, main.nitro.js
, in firefox, main.gecko.js
. This allows for outputting of specific javascript that will be faster(less browser testing code/feature testing). Granted the developers don't have to target specific and can write a main.js
and not make main.<js engine>.js
and it'll load that normally. i.e. having a main.js
and a main.jscript.js
file means that IE gets the jscript one, and everyone else gets the default js, same with the css files.
I solved this problem using the split npm module. Pipe your stream into split, and it will "Break up a stream and reassemble it so that each line is a chunk".
Sample code:
var fs = require('fs')
, split = require('split')
;
var stream = fs.createReadStream(filePath, {flags: 'r', encoding: 'utf-8'});
var lineStream = stream.pipe(split());
linestream.on('data', function(chunk) {
var json = JSON.parse(chunk);
// ...
});
New average = old average * (n-1)/n + new value /n
This is assuming the count only changed by one value. In case it is changed by M values then:
new average = old average * (n-len(M))/n + (sum of values in M)/n).
This is the mathematical formula (I believe the most efficient one), believe you can do further code by yourselves
Try adding the header file to your project's files. (right click on project -> add existing file).
Assuming you don't want the user to be in control, you can't. The web doesn't work like that, the best you can hope for is some heuristics.
If it is an option to force your visitor to install some software and use TCPA you may be able to pull something off.
Displaying a flash message after redirect in Codeigniter
In Your Controller set this
<?php
public function change_password(){
if($this->input->post('submit')){
$change = $this->common_register->change_password();
if($change == true){
$messge = array('message' => 'Password chnage successfully','class' => 'alert alert-success fade in');
$this->session->set_flashdata('item', $messge);
}else{
$messge = array('message' => 'Wrong password enter','class' => 'alert alert-danger fade in');
$this->session->set_flashdata('item',$messge );
}
$this->session->keep_flashdata('item',$messge);
redirect('controllername/methodname','refresh');
}
?>
In Your View File Set this
<script type="application/javascript">
/** After windod Load */
$(window).bind("load", function() {
window.setTimeout(function() {
$(".alert").fadeTo(500, 0).slideUp(500, function(){
$(this).remove();
});
}, 4000);
});
</script>
<?php
if($this->session->flashdata('item')) {
$message = $this->session->flashdata('item');
?>
<div class="<?php echo $message['class'] ?>"><?php echo $message['message']; ?>
</div>
<?php
}
?>
Please check below link for Displaying a flash message after redirect in Codeigniter
You'd need to use return values.
DECLARE @SelectedValue int
CREATE PROCEDURE GetMyInt (@MyIntField int OUTPUT)
AS
SELECT @MyIntField = MyIntField FROM MyTable WHERE MyPrimaryKeyField = 1
Then you call it like this:
EXEC GetMyInt OUTPUT @SelectedValue
If for any reason, you want to avoid using sed, the following will print the line matching TERMINATE
till the end of the file:
tail -n "+$(grep -n 'TERMINATE' file | head -n 1 | cut -d ":" -f 1)" file
and the following will print from the following line matching TERMINATE
till the end of the file:
tail -n "+$(($(grep -n 'TERMINATE' file | head -n 1 | cut -d ":" -f 1)+1))" file
It takes 2 processes to do what sed can do in one process, and if the file changes between the execution of grep and tail, the result can be incoherent, so I recommend using sed. Moreover, if the file dones not contain TERMINATE
, the 1st command fails.
The easiest way to set the version in Android Studio:
1. Press SHIFT+CTRL+ALT+S (or File -> Project Structure -> app)
Android Studio < 3.4:
Android Studio >= 3.4:
I used interop to open Excel and to modify the column widths once the data was done. If you use interop to spit the data into a new Excel workbook (if this is what you want), it will be terribly slow. Instead, I generated a .CSV
, then opened the .CSV
in Excel. This has its own problems, but I've found this the quickest method.
First, convert the .CSV
:
// Convert array data into CSV format.
// Modified from http://csharphelper.com/blog/2018/04/write-a-csv-file-from-an-array-in-c/.
private string GetCSV(List<string> Headers, List<List<double>> Data)
{
// Get the bounds.
var rows = Data[0].Count;
var cols = Data.Count;
var row = 0;
// Convert the array into a CSV string.
StringBuilder sb = new StringBuilder();
// Add the first field in this row.
sb.Append(Headers[0]);
// Add the other fields in this row separated by commas.
for (int col = 1; col < cols; col++)
sb.Append("," + Headers[col]);
// Move to the next line.
sb.AppendLine();
for (row = 0; row < rows; row++)
{
// Add the first field in this row.
sb.Append(Data[0][row]);
// Add the other fields in this row separated by commas.
for (int col = 1; col < cols; col++)
sb.Append("," + Data[col][row]);
// Move to the next line.
sb.AppendLine();
}
// Return the CSV format string.
return sb.ToString();
}
Then, export it to Excel:
public void ExportToExcel()
{
// Initialize app and pop Excel on the screen.
var excelApp = new Excel.Application { Visible = true };
// I use unix time to give the files a unique name that's almost somewhat useful.
DateTime dateTime = DateTime.UtcNow;
long unixTime = ((DateTimeOffset)dateTime).ToUnixTimeSeconds();
var path = @"C:\Users\my\path\here + unixTime + ".csv";
var csv = GetCSV();
File.WriteAllText(path, csv);
// Create a new workbook and get its active sheet.
excelApp.Workbooks.Open(path);
var workSheet = (Excel.Worksheet)excelApp.ActiveSheet;
// iterate over each value and throw it in the chart
for (var column = 0; column < Data.Count; column++)
{
((Excel.Range)workSheet.Columns[column + 1]).AutoFit();
}
currentSheet = workSheet;
}
You'll have to install some stuff, too...
Right click on the solution from solution explorer and select "Manage NuGet Packages." - add Microsoft.Office.Interop.Excel
It might actually work right now if you created the project the way interop wants you to. If it still doesn't work, I had to create a new project in a different category. Under New > Project, select Visual C# > Windows Desktop > Console App. Otherwise, the interop tools won't work.
In case I forgot anything, here's my 'using' statements:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
You can inject .properties
as a map in your class using @Resource
annotation.
If you are working with XML based configuration
, then add below bean in your spring configuration file:
<bean id="myProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="classpath:your.properties"/>
</bean>
For, Annotation based:
@Bean(name = "myProperties")
public static PropertiesFactoryBean mapper() {
PropertiesFactoryBean bean = new PropertiesFactoryBean();
bean.setLocation(new ClassPathResource(
"your.properties"));
return bean;
}
Then you can pick them up in your application as a Map:
@Resource(name = "myProperties")
private Map<String, String> myProperties;
As kovpas has shown you can use the bounding box in most cases, although it is not always guaranteed that the bounding box will fit neatly around the text. A box with a height of 50 and font size of 12 may not give the results you want depending on the UILabel configuration.
Query the UIString within the UILabel to determine its exact metrics and use these to better place your underline regardless of the enclosing bounding box or frame using the drawing code already provided by kovpas.
You should also look at UIFont's "leading" property that gives the distance between baselines based on a particular font. The baseline is where you would want your underline to be drawn.
Look up the UIKit additions to NSString:
(CGSize)sizeWithFont:(UIFont *)font
//Returns the size of the string if it were to be rendered with the specified font on a single line.
(CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size
// Returns the size of the string if it were rendered and constrained to the specified size.
(CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode
//Returns the size of the string if it were rendered with the specified constraints.
Since in css3 one might set multiple background images setting "none" will only create a new layer and hide nothing.
http://www.css3.info/preview/multiple-backgrounds/ http://www.w3.org/TR/css3-background/#backgrounds
I have not found a solution yet...
string html = File.ReadAllText(path);
Package name is the reversed domain name, it is a unique name for each application on Playstore. You can't upload two apps with the same package name. You can check package name of the app from playstore url
https://play.google.com/store/apps/details?id=package_name
so you can easily check on playstore that this package name is in used by some other app or not before uploading it.
I'd just drop the database and then re-create it. On a UNIX or Linux system, that should do it:
$ dropdb development_db_name
$ createdb developmnent_db_name
That's how I do it, actually.
May be below is better.
JSONObject jsonObject=null;
try {
jsonObject=new JSONObject();
jsonObject.put("phonetype","N95");
jsonObject.put("cat","wp");
String jsonStr=jsonObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}
Another way to do it simpler using jquery.
sample:
function add(product_id){
// the code to add the product
//updating the div, here I just change the text inside the div.
//You can do anything with jquery, like change style, border etc.
$("#added_"+product_id).html('the product was added to list');
}
Where product_id is the javascript var and$("#added_"+product_id) is a div id concatenated with product_id, the var from function add.
Best Regards!
Using the syntax that you used,
int array[100] = {-1};
says "set the first element to -1
and the rest to 0
" since all omitted elements are set to 0
.
In C++, to set them all to -1
, you can use something like std::fill_n
(from <algorithm>
):
std::fill_n(array, 100, -1);
In portable C, you have to roll your own loop. There are compiler-extensions or you can depend on implementation-defined behavior as a shortcut if that's acceptable.
Here is another answer. I hope it will help.
<a class="btn" ng-click="delete(item)">Delete</a>
$scope.delete(item){
var index = this.list.indexOf(item);
this.list.splice(index, 1);
}
array.splice(start)
array.splice(start, deleteCount)
array.splice(start, deleteCount, item1, item2, ...)
Full source is here
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
DECLARE @t1 TABLE (
TableID int IDENTITY,
FieldValue varchar(20)
)
--<< No empty string
IF EXISTS (
SELECT *
FROM @t1
WHERE FieldValue = ''
) BEGIN
SELECT TableID
FROM @t1
WHERE FieldValue=''
END
ELSE BEGIN
INSERT INTO @t1 (FieldValue) VALUES ('')
SELECT SCOPE_IDENTITY() AS TableID
END
--<< A record with an empty string already exists
IF EXISTS (
SELECT *
FROM @t1
WHERE FieldValue = ''
) BEGIN
SELECT TableID
FROM @t1
WHERE FieldValue=''
END
ELSE BEGIN
INSERT INTO @t1 (FieldValue) VALUES ('')
SELECT SCOPE_IDENTITY() AS TableID
END
Solution 1: Sometimes the build fails because, the target folder cannot be deleted. (It might be open in the backend due to the previous builds.)
-> Open Task Manager
-> In the Process tab
-> Do "End Process" for the running "java.exe" processess
Solution 2:
-> Restart eclipse
-> Perform Maven Build with command : clean install -DSkipTests
items[node.ind] = items[node.ind]._replace(v=node.v)
(Note: Don't be discouraged to use this solution because of the leading underscore in the function _replace. Specifically for namedtuple some functions have leading underscore which is not for indicating they are meant to be "private")
Python has lexical scoping by default, which means that although an enclosed scope can access values in its enclosing scope, it cannot modify them (unless they're declared global with the global
keyword).
A closure binds values in the enclosing environment to names in the local environment. The local environment can then use the bound value, and even reassign that name to something else, but it can't modify the binding in the enclosing environment.
In your case you are trying to treat counter
as a local variable rather than a bound value. Note that this code, which binds the value of x
assigned in the enclosing environment, works fine:
>>> x = 1
>>> def f():
>>> return x
>>> f()
1
In IE9, it is possible with purely a hack as advised by @Spudley. Since you've customized height and width of the div and select, you need to change div:before
css to match yours.
In case if it is IE10 then using below css3 it is possible
select::-ms-expand {
display: none;
}
However if you're interested in jQuery plugin, try Chosen.js
or you can create your own in js.
The Java Language Specification does not guarantee that the JVM will start a GC when you call System.gc()
. This is the reason of this "may or may not decide to do a GC at that point".
Now, if you look at OpenJDK source code, which is the backbone of Oracle JVM, you will see that a call to System.gc()
does start a GC cycle. If you use another JVM, such as J9, you have to check their documentation to find out the answer. For instance, Azul's JVM has a garbage collector that runs continuously, so a call to System.gc()
won't do anything
Some other answer mention starting a GC in JConsole or VisualVM. Basically, these tools make a remote call to System.gc()
.
Usually, you don't want to start a garbage collection cycle from your code, as it messes up with the semantics of your application. Your application does some business stuff, the JVM takes care of memory management. You should keep those concerns separated (don't make your application do some memory management, focus on business).
However, there are few cases where a call to System.gc()
might be understandable. Consider, for example, microbenchmarks. No-one wants to have a GC cycle to happen in the middle of a microbenchmark. So you may trigger a GC cycle between each measurement to make sure every measurement starts with an empty heap.
string = string.replace(/[\W_]/g, "_");
Note: The question is about arrays of strings. The mentioned routines are not to be mixed with the .Contains method of single strings.
I would like to add an extending answer referring to different C# versions and because of two reasons:
The accepted answer requires Linq which is perfectly idiomatic C# while it does not come without costs, and is not available in C# 2.0 or below. When an array is involved, performance may matter, so there are situations where you want to stay with Array methods.
No answer directly attends to the question where it was asked also to put this in a function (As some answers are also mixing strings with arrays of strings, this is not completely unimportant).
Array.Exists() is a C#/.NET 2.0 method and needs no Linq. Searching in arrays is O(n). For even faster access use HashSet or similar collections.
Since .NET 3.5 there also exists a generic method Array<T>.Exists()
:
public void PrinterSetup(string[] printer)
{
if (Array.Exists(printer, x => x == "jupiter"))
{
Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC");
}
}
You could write an own extension method (C# 3.0 and above) to add the syntactic sugar to get the same/similar ".Contains" as for strings for all arrays without including Linq:
// Using the generic extension method below as requested.
public void PrinterSetup(string[] printer)
{
if (printer.ArrayContains("jupiter"))
{
Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC");
}
}
public static bool ArrayContains<T>(this T[] thisArray, T searchElement)
{
// If you want this to find "null" values, you could change the code here
return Array.Exists<T>(thisArray, x => x.Equals(searchElement));
}
In this case this ArrayContains()
method is used and not the Contains method of Linq.
The elsewhere mentioned .Contains methods refer to List<T>.Contains
(since C# 2.0) or ArrayList.Contains
(since C# 1.1), but not to arrays itself directly.
The multi-framework safe shorthand for ready is:
jQuery(function($, undefined) {
// $ is guaranteed to be short for jQuery in this scope
// undefined is provided because it could have been overwritten elsewhere
});
This is because jQuery isn't the only framework that uses the $
and undefined
variables
Also had this problem - in my case it was caused by having the "Specific Version" property on a number of references set to true. Changing this to false on those references resolved the issue.
.md is markdown
. README.md
is used to generate the html
summary you see at the bottom of projects. Github has their own flavor of Markdown.
Order of Preference: If you have two files named README
and README.md
, the file named README.md
is preferred, and it will be used to generate github's html
summary.
FWIW, Stack Overflow uses local Markdown modifications as well (also see Stack Overflow's C# Markdown Processor)
My workaround had been using gnu sed
. Worked fine for my purposes.
Loius answer is correct, I just want to add an example:
listOne.add("A");
listOne.add("B");
listOne.add("C");
listTwo.add("D");
listTwo.add("E");
listTwo.add("F");
boolean noElementsInCommon = Collections.disjoint(listOne, listTwo); // true
Your CA file must have been in a binary X.509 format instead of Base64 encoding; it needs to be a regular DER or PEM in order for it to be added successfully to the list of trusted CAs on your server.
To proceed, do place your CA file inside your /usr/share/pki/ca-trust-source/anchors/
directory, then run the command line below (you might need sudo privileges based on your settings);
# CentOS 7, Red Hat 7, Oracle Linux 7
update-ca-trust
Please note that all trust settings available in the /usr/share/pki/ca-trust-source/anchors/
directory are interpreted with a lower priority compared to the ones placed under the /etc/pki/ca-trust/source/anchors/
directory which may be in the extended BEGIN TRUSTED file format.
For Ubuntu and Debian systems, /usr/local/share/ca-certificates/
is the preferred directory for that purpose.
As such, you need to place your CA file within the /usr/local/share/ca-certificates/
directory, then update the of trusted CAs by running, with sudo privileges where required, the command line below;
update-ca-certificates
The line starting ALREADYEXISTS
uses ’
as the closing quote, it should be using '
. The open quote on the next line (where the error is reported) is seen as the closing quote, and this mix up is causing the error.
DateTime TaskStart = DateTime.Parse(dr["TaskStart"].ToString());
img.UriSource = new Uri("pack://application:,,,/images/" + fileName, UriKind.Absolute);
In MSBuild or Teamcity use command line
MSBuild yourproject.sln /property:Configuration=Release /property:Platform=x64
or use shorter form:
MSBuild yourproject.sln /p:Configuration=Release /p:Platform=x64
However you need to set up platform in your project anyway, see the answer by Julien Hoarau.
StringUtils is a utility class from Apache commons-lang (many libraries have it but this is the most common library). You need to download the jar and add it to your applications classpath.
What eventually worked for me, after lot's of confusing manuals and confusing tutorials, since Docker is obviously at time of my writing at peek of inflated expectations, is:
docker save image_name > image_name.tar
cat image_name.tar | docker load
Export and import, as proposed in another answers does not export ports and variables, which might be required for your container to run. And you might end up with stuff like "No command specified" etc... When you try to load it on another machine.
So, difference between save and export is that save command saves whole image with history and metadata, while export command exports only files structure (without history or metadata).
Needless to say is that, if you already have those ports taken on the docker hyper-visor you are doing import, by some other docker container, you will end-up in conflict, and you will have to reconfigure exposed ports.
Note: In order to move data with docker, you might be having persistent storage somewhere, which should also be moved alongside with containers.
check out the implode function, since the values are in an array, you want to put the values of the array into a mysql query that inserts the values into a table.
$query = "INSERT INto hardware (specifications) VALUES (".implode(",",$specifications).")";
If the values in the array are text values, you will need to add quotes
$query = "INSERT INto hardware (specifications) VALUES ("'.implode("','",$specifications)."')";
mysql_query($query);
Also, if you don't want duplicate values, switch the "INto" to "IGNORE" and only unique values will be inserted into the table.
Dynamic Variable Names in Java
There is no such thing.
In your case you can use array:
int[] n = new int[3];
for() {
n[i] = 5;
}
For more general (name, value)
pairs, use Map<>
extension UIView {
func getSnapshotImage() -> UIImage {
UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
drawHierarchy(in: bounds, afterScreenUpdates: false)
let snapshotImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return snapshotImage
}
}
Your datatype for @location nchar(20)
should be @location nvarchar(20)
, since nChar has a fixed length (filled with Spaces).
If Location is nchar too you will have to convert it:
... Cast(Location as nVarchar(200)) like '%'+@location+'%' ...
To enable nullable parameters with and AND
condition just use IsNull or Coalesce for comparison, which is not needed in your example using OR
.
e.g. if you would like to compare for Location AND Date and Time.
@location nchar(20),
@time time,
@date date
as
select DonationsTruck.VechileId, Phone, Location, [Date], [Time]
from Vechile, DonationsTruck
where Vechile.VechileId = DonationsTruck.VechileId
and (((Location like '%'+IsNull(@location,Location)+'%')) and [Date]=IsNUll(@date,date) and [Time] = IsNull(@time,Time))
For me, it was a much different solution since it was running on a virtualbox, so I had to edit the hosts file and add the virtualbox as a localhost
127.0.0.1 VirtualBox-blahblah
start wgnplot.exe "c:\path to file to open\foo.dat"
If you start tinkering with VirtualBox network settings, watch out for this: you might make new network adapters (eth1, eth2), yet have your /etc/network/interfaces
still configured for eth0.
Diagnose:
ethtool -i eth0
Cannot get driver information: no such device
Find your interfaces:
ls /sys/class/net
eth1 eth2 lo
Fix it:
Edit /etc/networking/interfaces
and replace eth0 with the appropriate interface name (e.g eth1, eth2, etc.)
:%s/eth0/eth2/g
In modern browsers you can do:
.reMode_hover:not(.reMode_selected):hover{}
Consult http://caniuse.com/css-sel3 for compatibility information.
If you use
$( document ).ready({ })
or
$(function() { });
more than once, the click function will trigger as many times as it is used.
Your FMAT.h requires a definition of std::string in order to complete the definition of class FMAT. In FMAT.cpp, you've done this by #include <string>
before #include "FMAT.h"
. You haven't done that in your main file.
Your attempt to forward declare string
was incorrect on two levels. First you need a fully qualified name, std::string
. Second this works only for pointers and references, not for variables of the declared type; a forward declaration doesn't give the compiler enough information about what to embed in the class you're defining.
you use this code,
var firstValue = "2012-05-12".split('-');
var secondValue = "2014-07-12".split('-');
var firstDate=new Date();
firstDate.setFullYear(firstValue[0],(firstValue[1] - 1 ),firstValue[2]);
var secondDate=new Date();
secondDate.setFullYear(secondValue[0],(secondValue[1] - 1 ),secondValue[2]);
if (firstDate > secondDate)
{
alert("First Date is greater than Second Date");
}
else
{
alert("Second Date is greater than First Date");
}
And also check this link http://www.w3schools.com/js/js_obj_date.asp
Because thats coding convention. See here for more.
As far as I know, display: inline-block
is what you probably need. That will make it seem like it's sort of inline but still allow you to use things like margins and such.
The function I use currently:
/**
* Serializes form or any other element with jQuery.serialize
* @param el
*/
serialize: function(el) {
var serialized = $(el).serialize();
if (!serialized) // not a form
serialized = $(el).
find('input[name],select[name],textarea[name]').serialize();
return serialized;
}
You need to set the classpath to find your compiled class:
java -cp C:\Users\Matt\workspace\HelloWorld2\bin HelloWorld2
' Assume that the code name the worksheet is Sheet1
' Copy the sheet using code name and put in the end.
' Note: Using the code name lets the user rename the worksheet without breaking the VBA code
Sheet1.Copy After:=Sheets(Sheets.Count)
' Rename the copied sheet keeping the same name and appending a string " copied"
ActiveSheet.Name = Sheet1.Name & " copied"
Based on SFEley's answer, here is an updated/fixed one for newer Rails versions:
class SetDefault < ActiveRecord::Migration
def change
change_column :table_name, :column_name, :type, default: "Your value"
end
end
Instead of catching the error, wouldn't it be possible to test in or before the myplotfunction()
function first if the error will occur (i.e. if the breaks are unique) and only plot it for those cases where it won't appear?!
Below is the code to enter date in the format of DD-MM-YYYY you can change the input format by changing the order of '%d-%m-%Y' and also by changing the delimiter.
import datetime
try:
date = input()
date_time_obj = datetime.datetime.strptime(date, '%d-%m-%Y')
print(date_time_obj.strftime('%A'))
except ValueError:
print("Invalid date.")
Here's a quick tip to center align the action:
android:label=" YourTitle"
Assuming that you have Actionbar Enable, You can add this in your activity with some space (Can be adjusted) to place the title at the center.
However, This is just diddly and unreliable method. You probably shouldn't do that. So, The best thing to do is to create a custom ActionBar. So, What you wanna do is remove the default Actionbar and use this to replace it as an ActionBar.
<androidx.constraintlayout.widget.ConstraintLayout
android:elevation="30dp"
android:id="@+id/customAction"
android:layout_width="match_parent"
android:layout_height="56dp"
android:background="@color/colorOnMain"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name"
android:textAllCaps="true"
android:textColor="#FFF"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
I have used Constraint Layout to center the textView and used 10dp elevation with 56dp height so that it looks as same as the default ActionBar.
I prefer the way Golang does quote escaping for XML (and a few extras like newline escaping, and escaping some other characters), so I have ported its XML escape function to PHP below
function isInCharacterRange(int $r): bool {
return $r == 0x09 ||
$r == 0x0A ||
$r == 0x0D ||
$r >= 0x20 && $r <= 0xDF77 ||
$r >= 0xE000 && $r <= 0xFFFD ||
$r >= 0x10000 && $r <= 0x10FFFF;
}
function xml(string $s, bool $escapeNewline = true): string {
$w = '';
$Last = 0;
$l = strlen($s);
$i = 0;
while ($i < $l) {
$r = mb_substr(substr($s, $i), 0, 1);
$Width = strlen($r);
$i += $Width;
switch ($r) {
case '"':
$esc = '"';
break;
case "'":
$esc = ''';
break;
case '&':
$esc = '&';
break;
case '<':
$esc = '<';
break;
case '>':
$esc = '>';
break;
case "\t":
$esc = '	';
break;
case "\n":
if (!$escapeNewline) {
continue 2;
}
$esc = '
';
break;
case "\r":
$esc = '
';
break;
default:
if (!isInCharacterRange(mb_ord($r)) || (mb_ord($r) === 0xFFFD && $Width === 1)) {
$esc = "\u{FFFD}";
break;
}
continue 2;
}
$w .= substr($s, $Last, $i - $Last - $Width) . $esc;
$Last = $i;
}
$w .= substr($s, $Last);
return $w;
}
Note you'll need at least PHP7.2 because of the mb_ord
usage, or you'll have to swap it out for another polyfill, but these functions are working great for us!
For anyone curious, here is the relevant Go source https://golang.org/src/encoding/xml/xml.go?s=44219:44263#L1887
Here is a one-liner solution that works for as low as minSdkVersion 14
which you should insert in you res/styles.xml
:
<item name="android:windowAnimationStyle">@null</item>
like so:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
...
<item name="android:windowAnimationStyle">@null</item>
</style>
...
</resources>
Cheers!
I may have a solution for this, although it will only work in SQL Server 2008 as far as I know. I discovered that you can use the row-constructor described in https://stackoverflow.com/a/7285095/894974 to join a 'fictional' table using a like clause. It sounds more complex then it is, look:
SELECT [name]
,[userID]
,[name]
,[town]
,[email]
FROM usr
join (values ('hotmail'),('gmail'),('live')) as myTable(myColumn) on email like '%'+myTable.myColumn+'%'
This will result in all users with an e-mail adres like the ones provided in the list. Hope it's of use to anyone. The problem had been bothering me a while.
Altering a view could be accomplished by dropping the view and recreating it. Use the following to drop and recreate your view.
IF EXISTS
(SELECT NAME FROM SYS.VIEWS WHERE NAME = 'dbo.test_abc_def')
DROP VIEW dbo.test_abc_def) go
CREATE VIEW dbo.test_abc_def AS
SELECT
VCV.xxxx,
VCV.yyyy AS yyyy
,VCV.zzzz AS zzzz
FROM TABLE_A
Pure css way to make a table fully responsive, no JavaScript is needed. Checke demo here Responsive Tables
<!DOCTYPE>
<html>
<head>
<title>Responsive Table</title>
<style>
/* only for demo purpose. you can remove it */
.container{border: 1px solid #ccc; background-color: #ff0000;
margin: 10px auto;width: 98%; height:auto;padding:5px; text-align: center;}
/* required */
.tablewrapper{width: 95%; overflow-y: hidden; overflow-x: auto;
background-color:green; height: auto; padding: 5px;}
/* only for demo purpose just for stlying. you can remove it */
table { font-family: arial; font-size: 13px; padding: 2px 3px}
table.responsive{ background-color:#1a99e6; border-collapse: collapse;
border-color: #fff}
tr:nth-child(1) td:nth-of-type(1){
background:#333; color: #fff}
tr:nth-child(1) td{
background:#333; color: #fff; font-weight: bold;}
table tr td:nth-child(2) {
background:yellow;
}
tr:nth-child(1) td:nth-of-type(2){color: #333}
tr:nth-child(odd){ background:#ccc;}
tr:nth-child(even){background:#fff;}
</style>
</head>
<body>
<div class="container">
<div class="tablewrapper">
<table class="responsive" width="98%" cellpadding="4" cellspacing="1" border="1">
<tr>
<td>Name</td>
<td>Email</td>
<td>Phone</td>
<td>Address</td>
<td>Contact</td>
<td>Mobile</td>
<td>Office</td>
<td>Home</td>
<td>Residency</td>
<td>Height</td>
<td>Weight</td>
<td>Color</td>
<td>Desease</td>
<td>Extra</td>
<td>DOB</td>
<td>Nick Name</td>
</tr>
<tr>
<td>RN Kushwaha</td>
<td>[email protected]</td>
<td>--</td>
<td>Varanasi</td>
<td>-</td>
<td>999999999</td>
<td>022-111111</td>
<td>-</td>
<td>India</td>
<td>165cm</td>
<td>58kg</td>
<td>bright</td>
<td>--</td>
<td>--</td>
<td>03/07/1986</td>
<td>Aryan</td>
</tr>
</table>
</div>
</div>
</body>
</html>
We can provide background color from the css file. Try this one,
<!DOCTYPE html>
<html>
<head>
<style>
input[type="checkbox"] {
width: 25px;
height: 25px;
background: gray;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
border: none;
outline: none;
position: relative;
left: -5px;
top: -5px;
cursor: pointer;
}
input[type="checkbox"]:checked {
background: blue;
}
.checkbox-container {
position: absolute;
display: inline-block;
margin: 20px;
width: 25px;
height: 25px;
overflow: hidden;
}
</style>
</head>
<body>
<div class="checkbox-container">
<input type="checkbox" />
</div>
</body>
</html>
df[['a', 'b']] # Select all rows of 'a' and 'b'column
df.loc[0:10, ['a', 'b']] # Index 0 to 10 select column 'a' and 'b'
df.loc[0:10, 'a':'b'] # Index 0 to 10 select column 'a' to 'b'
df.iloc[0:10, 3:5] # Index 0 to 10 and column 3 to 5
df.iloc[3, 3:5] # Index 3 of column 3 to 5
//decode base64 string to image
imageBytes = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
image.setImageBitmap(decodedImage);
//setImageBitmap is imp
Could you not have simply added:
align-items:center;
to a new class in your row div. Essentially:
<div class="row align_center">
.align_center { align-items:center; }
In AVD Manager,
Go to Edit Icon on AVD Manager for selected Device.
Click on show advanced settings and increase ram size from 1500 mb to 2 GB.
Then it works.
NOTE: Some virtual devices do not allow you to update RAM, but if so, try installing Nexus 4. because it does.
NOTE2: If still doesnt work, dont give up. just uninstall and reinstall the device with changing RAM again. in some cases this is how it works
NOTE3: If still doesnt work, this means your pc doesnt have enough ram space. so increase the ram to 3gb. it might work but it will suffer
NOTE4: If still doesnt work, try it with multicore 2 instead of 4.
NOTE5: Still doesnt work. Close the Android Studio and NEVER open it back :)
You need some JS to do scroll events. The best way to do this is to set a new CSS class for the fixed position that will get assigned to the relevant div when scrolling goes past a certain point.
HTML
<div class="sticky"></div>
CSS
.fixed {
position: fixed;
top:0; left:0;
width: 100%; }
jQuery
$(window).scroll(function(){
var sticky = $('.sticky'),
scroll = $(window).scrollTop();
if (scroll >= 100) sticky.addClass('fixed');
else sticky.removeClass('fixed');
});
Example fiddle: http://jsfiddle.net/gxRC9/501/
EDIT: Extended example
If the trigger point is unknown but should be whenever the sticky element reaches the top of the screen, offset().top
can be used.
var stickyOffset = $('.sticky').offset().top;
$(window).scroll(function(){
var sticky = $('.sticky'),
scroll = $(window).scrollTop();
if (scroll >= stickyOffset) sticky.addClass('fixed');
else sticky.removeClass('fixed');
});
Extended example fiddle: http://jsfiddle.net/gxRC9/502/
Try format
function:
> xx = 100000000000
> xx
[1] 1e+11
> format(xx, scientific=F)
[1] "100000000000"
If you just want the list, then you should ask here: http://unix.stackexchange.com
The answer is: cd / && find -name *.js
If you want to implement this, you have to specify the language.
mv /usr/local/hadoop_store/hdfs/datanode /usr/local/hadoop_store/hdfs/datanode.backup
mkdir /usr/local/hadoop_store/hdfs/datanode
hadoop datanode OR start-all.sh
jps
i think it should be
select convert(varchar(10),StandardCost) +'S' from DimProduct where ProductKey = 212
or
select cast(StandardCost as varchar(10)) + 'S' from DimProduct where ProductKey = 212
$ch = curl_init();
$data = array(
'client_id' => 'xx',
'client_secret' => 'xx',
'redirect_uri' => $x,
'grant_type' => 'xxx',
'code' => $xx,
);
$data = http_build_query($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_URL, "https://example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$output = curl_exec($ch);
If you're going to be using this often (and on multiple arrays), extend the Array object to create an unset function.
Array.prototype.unset = function(value) {
if(this.indexOf(value) != -1) { // Make sure the value exists
this.splice(this.indexOf(value), 1);
}
}
tag_story.unset(56)
AssertJ 1.4+ has specific assertions to compare XML content:
String expectedXml = "<foo />";
String actualXml = "<bar />";
assertThat(actualXml).isXmlEqualTo(expectedXml);
Here is the Documentation
If you're looking for "in-place" editing of a ListView
's contents (specifically the subitems of a ListView in details view mode), you'll need to implement this yourself, or use a third-party control.
By default, the best you can achieve with a "standard" ListView
is to set it's LabelEdit
property to true to allow the user to edit the text of the first column of the ListView
(assuming you want to allow a free-format text edit).
Some examples (including full source-code) of customized ListView
's that allow "in-place" editing of sub-items are:
There is a bug with Lee's extension code above, you need to add the newly filled row to the table t when iterating throught the items in the list.
public static DataSet ToDataSet<T>(this IList<T> list) {
Type elementType = typeof(T);
DataSet ds = new DataSet();
DataTable t = new DataTable();
ds.Tables.Add(t);
//add a column to table for each public property on T
foreach(var propInfo in elementType.GetProperties())
{
t.Columns.Add(propInfo.Name, propInfo.PropertyType);
}
//go through each property on T and add each value to the table
foreach(T item in list)
{
DataRow row = t.NewRow();
foreach(var propInfo in elementType.GetProperties())
{
row[propInfo.Name] = propInfo.GetValue(item, null);
}
//This line was missing:
t.Rows.Add(row);
}
return ds;
}
This 'just works' for me using jQuery, provided you don't try to append a subset the XHR-returned HTML to the document. (See this bug report showing the problem with jQuery.)
Here is an example showing it working:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>test_1.4</title>
<script type="text/javascript" charset="utf-8" src="jquery.1.4.2.js"></script>
<script type="text/javascript" charset="utf-8">
var snippet = "<div><span id='a'>JS did not run<\/span><script type='text/javascript'>" +
"$('#a').html('Hooray! JS ran!');" +
"<\/script><\/div>";
$(function(){
$('#replaceable').replaceWith($(snippet));
});
</script>
</head>
<body>
<div id="replaceable">I'm going away.</div>
</body>
</html>
Here is the equivalent of the above: http://jsfiddle.net/2CTLH/
npm config set proxy http://proxy.company.com:8080
npm config set https-proxy http://proxy.company.com:8080
credit goes to http://jjasonclark.com/how-to-setup-node-behind-web-proxy.
Perhaps a function along these lines is what you're after:
def add_unique_to_dict_list(dict_list, key, value):
for d in dict_list:
if key in d:
return d[key]
dict_list.append({ key: value })
return value
In case you want to ADD SOME TEXT IN SPECIFIC LINES you can first read the whole file, append the text wherever you want and then overwrite everything like in the code below:
public static void addDatatoFile(String data1, String data2){
String fullPath = "/home/user/dir/file.csv";
File dir = new File(fullPath);
List<String> l = new LinkedList<String>();
try (BufferedReader br = new BufferedReader(new FileReader(dir))) {
String line;
int count = 0;
while ((line = br.readLine()) != null) {
if(count == 1){
//add data at the end of second line
line += data1;
}else if(count == 2){
//add other data at the end of third line
line += data2;
}
l.add(line);
count++;
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
createFileFromList(l, dir);
}
public static void createFileFromList(List<String> list, File f){
PrintWriter writer;
try {
writer = new PrintWriter(f, "UTF-8");
for (String d : list) {
writer.println(d.toString());
}
writer.close();
} catch (FileNotFoundException | UnsupportedEncodingException e) {
e.printStackTrace();
}
}
Select A.ARIDNR,A.LIEFNR
from Table A
join Table B
on A.ARIDNR = B.ARIDNR
and A.LIEFNR<> B.LIEFNR
group by A.ARIDNR,A.LIEFNR
This might give the increased relevance to the head part that you want. It won't double it, but it might possibly good enough for your sake:
SELECT pages.*,
MATCH (head, body) AGAINST ('some words') AS relevance,
MATCH (head) AGAINST ('some words') AS title_relevance
FROM pages
WHERE MATCH (head, body) AGAINST ('some words')
ORDER BY title_relevance DESC, relevance DESC
-- alternatively:
ORDER BY title_relevance + relevance DESC
An alternative that you also want to investigate, if you've the flexibility to switch DB engine, is Postgres. It allows to set the weight of operators and to play around with the ranking.
var mydate = "2017-06-28T00:00:00";
var weekDayName = moment(mydate).format('ddd');
console.log(weekDayName);
Result: Wed
var mydate = "2017-06-28T00:00:00";
var weekDayName = moment(mydate).format('dddd');
console.log(weekDayName);
Result: Wednesday
Here are several options for getting the "tail" items of an iterable:
Given
n = 9
iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Desired Output
[2, 3, 4, 5, 6, 7, 8, 9, 10]
Code
We get the latter output using any of the following options:
from collections import deque
import itertools
import more_itertools
# A: Slicing
iterable[-n:]
# B: Implement an itertools recipe
def tail(n, iterable):
"""Return an iterator over the last *n* items of *iterable*.
>>> t = tail(3, 'ABCDEFG')
>>> list(t)
['E', 'F', 'G']
"""
return iter(deque(iterable, maxlen=n))
list(tail(n, iterable))
# C: Use an implemented recipe, via more_itertools
list(more_itertools.tail(n, iterable))
# D: islice, via itertools
list(itertools.islice(iterable, len(iterable)-n, None))
# E: Negative islice, via more_itertools
list(more_itertools.islice_extended(iterable, -n, None))
Details
iter(iterable)
. itertools
recipe. It is generalized to work on any iterable and resolves the iterator issue in the last solution. This recipe must be implemented manually as it is not officially included in the itertools
module.more_itertools
(install via > pip install more-itertools
); see more_itertools.tail
.itertools
library. Note, itertools.islice
does not support negative slicing. more_itertools
that generalizes itertools.islice
to support negative slicing; see more_itertools.islice_extended
.Which one do I use?
It depends. In most cases, slicing (option A, as mentioned in other answers) is most simple option as it built into the language and supports most iterable types. For more general iterators, use any of the remaining options. Note, options C and E require installing a third-party library, which some users may find useful.
<
stands for the less-than sign: <
>
stands for the greater-than sign: >
≤
stands for the less-than or equals sign: =
≥
stands for the greater-than or equals sign: =
We had the Broken Pipe error after a new network was put into place. After ensuring that port 9100 was open and could connect to the printer over telnet port 9100, we changed the printer driver from "HP" to "Generic PDF", the broken pipe error went away and were able to print successfully.
(RHEL 7, Printers were Ricoh brand, the HP configuration was pre-existing and functional on the previous network)
from tkinter import *
import os
root = Tk()
file = filedialog.askdirectory()
changed_dir = os.listdir(file)
print(changed_dir)
root.mainloop()
Try this one. It may be helpful:
mysql> UPDATE mysql.user SET Password = PASSWORD('pwd') WHERE User='root';
I hope it helps.
Include following line in your method there you want to trigger click event
angular.element('#btn_you_want_to_click_progmaticallt').triggerHandler('click');
});
Just return true
instead?
The return value from the onClick
code is what determines whether the link's inherent clicked action is processed or not - returning false
means that it isn't processed, but if you return true
then the browser will proceed to process it after your function returns and go to the proper anchor.
Exception code 0xc0000005
is an Access Violation. An AV at fault offset 0x00000000
means that something in your service's code is accessing a nil
pointer. You will just have to debug the service while it is running to find out what it is accessing. If you cannot run it inside a debugger, then at least install a third-party exception logger framework, such as EurekaLog or MadExcept, to find out what your service was doing at the time of the AV.
"The
==
operator checks to see if twoObjects
are exactly the sameObject
."
http://leepoint.net/notes-java/data/strings/12stringcomparison.html
String
is an Object
in java, so it falls into that category of comparison rules.
There is also the approach of organizing the folders not by the structure of the framework, but by the structure of the application's function. There is a github starter Angular/Express application that illustrates this called angular-app.
zero(myarray);
is all you need in C++.
Just add this to a header:
template<typename T, size_t SIZE> inline void zero(T(&arr)[SIZE]){
memset(arr, 0, SIZE*sizeof(T));
}
x='buffalo'
exec("%s = %d" % (x,2))
After that you can check it by:
print buffalo
As an output you will see:
2
GCC compiles a C/C++ program into executable in 4 steps.
For example, gcc -o hello hello.c
is carried out as follows:
Preprocessing via the GNU C Preprocessor (cpp.exe
), which includes
the headers (#include
) and expands the macros (#define
).
cpp hello.c > hello.i
The resultant intermediate file "hello.i" contains the expanded source code.
The compiler compiles the pre-processed source code into assembly code for a specific processor.
gcc -S hello.i
The -S option specifies to produce assembly code, instead of object code. The resultant assembly file is "hello.s".
The assembler (as.exe
) converts the assembly code into machine code in the object file "hello.o".
as -o hello.o hello.s
Finally, the linker (ld.exe
) links the object code with the library code to produce an executable file "hello".
ld -o hello hello.o ...libraries...
{% if variable is defined %}
is true if the variable is None
.
Since not is None
is not allowed, that means that
{% if variable != None %}
is really your only option.
In Windows 10 if in the prompt command the path where you start sqlite is
C:\users\USER_NAME
You can find it in the user home folder.
The .db
file is stored where you start the sqlite command.
I hope this solve the issue
With PHP 7, you can use generators and generator delegation (yield from
) to flatten an array:
function array_flatten_iterator (array $array) {
foreach ($array as $value) {
if (is_array($value)) {
yield from array_flatten_iterator($value);
} else {
yield $value;
}
}
}
function array_flatten (array $array) {
return iterator_to_array(array_flatten_iterator($array), false);
}
Example:
$array = [
1,
2,
[
3,
4,
5,
[
6,
7
],
8,
9,
],
10,
11,
];
var_dump(array_flatten($array));