Kendo UI provides the best and ultimate collection of JavaScript UI components with libraries for jQuery, Angular, React, and Vue. You can quickly build eye-catching, high-performance, responsive web applications regardless of your JavaScript framework choice. Here is a timepicker UI component from them:
Also below is an alternate and a simple solution
<!--Css-->
<link href="css/timepicker.css" type="text/css" rel="stylesheet" />
<!--Html-->
<div class="row">
<div class="col">
<label class="label-in">Time</label>
<input class="timepicker" id="event-time" type="text" value="" required="">
</div>
</div>
<!--Script-->
<script src="Scripts/ClockPicker.js"></script>
<script>
$('.timepicker').timepicker({
});
</script>
Here is yet another popular framework Bootstrap Time Picker from mdbootstrap
You can have a datetime picker when using matInput
with type datetime-local
like so:
<mat-form-field>
<input matInput type="datetime-local" placeholder="start date">
</mat-form-field>
You can click on each part of the placeholder to set the day, month, year, hours,minutes and whether its AM or PM.
You can create a fast refresh materialized view to store the count.
Example:
create table sometable (
id number(10) not null primary key
, name varchar2(100) not null);
create materialized view log on sometable with rowid including new values;
create materialized view sometable_count
refresh on commit
as
select count(*) count
from sometable;
insert into sometable values (1,'Raymond');
insert into sometable values (2,'Hans');
commit;
select count from sometable_count;
It will slow mutations on table sometable a bit but the counting will become a lot faster.
Try these styles:
p.event_desc {_x000D_
font: bold 12px "Helvetica Neue", Helvetica, Arial, sans-serif;_x000D_
line-height: 14px;_x000D_
height:75px;_x000D_
margin: 0px;_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
padding: 10px;_x000D_
border: 1px solid #f00;_x000D_
}
_x000D_
<p class="event_desc">lorem ipsum</p>
_x000D_
when i used FQL I found the problem (but it is still problem) the documentation says that the number shown is the sum of:
but on my website the shown number is sum of these 4 counts + number of shares (again)
For those who are still coming for solution here, the easiest solution would be to use <wsdlLocation>
, without changing any code. Working steps are given below:
src/main/resource
In pom file, add both wsdlDirectory and wsdlLocation(don't miss / at the beginning of wsdlLocation), like below. While wsdlDirectory is used to generate code and wsdlLocation is used at runtime to create dynamic proxy.
<wsdlDirectory>src/main/resources/mydir</wsdlDirectory>
<wsdlLocation>/mydir/my.wsdl</wsdlLocation>
Then in your java code(with no-arg constructor):
MyPort myPort = new MyPortService().getMyPort();
For completeness, I am providing here full code generation part, with fluent api in generated code.
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxws-maven-plugin</artifactId>
<version>2.5</version>
<dependencies>
<dependency>
<groupId>org.jvnet.jaxb2_commons</groupId>
<artifactId>jaxb2-fluent-api</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-tools</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>wsdl-to-java-generator</id>
<goals>
<goal>wsimport</goal>
</goals>
<configuration>
<xjcArgs>
<xjcArg>-Xfluent-api</xjcArg>
</xjcArgs>
<keep>true</keep>
<wsdlDirectory>src/main/resources/package</wsdlDirectory>
<wsdlLocation>/package/my.wsdl</wsdlLocation>
<sourceDestDir>${project.build.directory}/generated-sources/annotations/jaxb</sourceDestDir>
<packageName>full.package.here</packageName>
</configuration>
</execution>
</executions>
new[,2]
is a factor, not a numeric vector. Transform it first
new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5
While a similar answer has already been sort of posted, I think the reason to use the new PrimitiveIterator.OfInt was not clear. A good solution is to use Java 8 PrimitiveIterator since it's specialized for primitive int types (and avoids the extra boxing/unboxing penalty):
int[] arr = {1,2,3};
// If you use Iterator<Integer> here as type then you can't get the actual benefit of being able to use nextInt() later
PrimitiveIterator.OfInt iterator = Arrays.stream(arr).iterator();
while (iterator.hasNext()) {
System.out.println(iterator.nextInt());
// Use nextInt() instead of next() here to avoid extra boxing penalty
}
Ref: https://doc.bccnsoft.com/docs/jdk8u12-docs/api/java/util/PrimitiveIterator.OfInt.html
I found this post while trying to figure out what the exit status was for a script that was aborted due to a set -e
. The answer didn't appear obvious to me; hence this answer. Basically, set -e
aborts the execution of a command (e.g. a shell script) and returns the exit status code of the command that failed (i.e. the inner script, not the outer script).
For example, suppose I have the shell script outer-test.sh
:
#!/bin/sh
set -e
./inner-test.sh
exit 62;
The code for inner-test.sh
is:
#!/bin/sh
exit 26;
When I run outer-script.sh
from the command line, my outer script terminates with the exit code of the inner script:
$ ./outer-test.sh
$ echo $?
26
This worked for me
For folks using MongoClient
try this:
MongoClient.connect(connectionurl,
{useUnifiedTopology: true, useNewUrlParser: true}, callback() {
For mongoose:
mongoose.connect(connectionurl,
{useUnifiedTopology: true, useNewUrlParser: true}).then(()=>{
Remove other connectionOptions
ALTERNATIVES:
Easy copy/paste of latest version (but install instructions may change - see below!)
Karl's library takes much more effort to setup, but much nicer long-term solution (it converts your library into a Framework).
Use this, then tweak it to add support for Archive builds - c.f. @Frederik's comment below on the changes he's using to make this work nicely with Archive mode.
RECENT CHANGES: 1. Added support for iOS 10.x (while maintaining support for older platforms)
Info on how to use this script with a project-embedded-in-another-project (although I highly recommend NOT doing that, ever - Apple has a couple of show-stopper bugs in Xcode if you embed projects inside each other, from Xcode 3.x through to Xcode 4.6.x)
Bonus script to let you auto-include Bundles (i.e. include PNG files, PLIST files etc from your library!) - see below (scroll to bottom)
now supports iPhone5 (using Apple's workaround to the bugs in lipo). NOTE: the install instructions have changed (I can probably simplify this by changing the script in future, but don't want to risk it now)
"copy headers" section now respects the build setting for the location of the public headers (courtesy of Frederik Wallner)
Added explicit setting of SYMROOT (maybe need OBJROOT to be set too?), thanks to Doug Dickinson
SCRIPT (this is what you have to copy/paste)
For usage / install instructions, see below
##########################################
#
# c.f. https://stackoverflow.com/questions/3520977/build-fat-static-library-device-simulator-using-xcode-and-sdk-4
#
# Version 2.82
#
# Latest Change:
# - MORE tweaks to get the iOS 10+ and 9- working
# - Support iOS 10+
# - Corrected typo for iOS 1-10+ (thanks @stuikomma)
#
# Purpose:
# Automatically create a Universal static library for iPhone + iPad + iPhone Simulator from within XCode
#
# Author: Adam Martin - http://twitter.com/redglassesapps
# Based on: original script from Eonil (main changes: Eonil's script WILL NOT WORK in Xcode GUI - it WILL CRASH YOUR COMPUTER)
#
set -e
set -o pipefail
#################[ Tests: helps workaround any future bugs in Xcode ]########
#
DEBUG_THIS_SCRIPT="false"
if [ $DEBUG_THIS_SCRIPT = "true" ]
then
echo "########### TESTS #############"
echo "Use the following variables when debugging this script; note that they may change on recursions"
echo "BUILD_DIR = $BUILD_DIR"
echo "BUILD_ROOT = $BUILD_ROOT"
echo "CONFIGURATION_BUILD_DIR = $CONFIGURATION_BUILD_DIR"
echo "BUILT_PRODUCTS_DIR = $BUILT_PRODUCTS_DIR"
echo "CONFIGURATION_TEMP_DIR = $CONFIGURATION_TEMP_DIR"
echo "TARGET_BUILD_DIR = $TARGET_BUILD_DIR"
fi
#####################[ part 1 ]##################
# First, work out the BASESDK version number (NB: Apple ought to report this, but they hide it)
# (incidental: searching for substrings in sh is a nightmare! Sob)
SDK_VERSION=$(echo ${SDK_NAME} | grep -o '\d\{1,2\}\.\d\{1,2\}$')
# Next, work out if we're in SIM or DEVICE
if [ ${PLATFORM_NAME} = "iphonesimulator" ]
then
OTHER_SDK_TO_BUILD=iphoneos${SDK_VERSION}
else
OTHER_SDK_TO_BUILD=iphonesimulator${SDK_VERSION}
fi
echo "XCode has selected SDK: ${PLATFORM_NAME} with version: ${SDK_VERSION} (although back-targetting: ${IPHONEOS_DEPLOYMENT_TARGET})"
echo "...therefore, OTHER_SDK_TO_BUILD = ${OTHER_SDK_TO_BUILD}"
#
#####################[ end of part 1 ]##################
#####################[ part 2 ]##################
#
# IF this is the original invocation, invoke WHATEVER other builds are required
#
# Xcode is already building ONE target...
#
# ...but this is a LIBRARY, so Apple is wrong to set it to build just one.
# ...we need to build ALL targets
# ...we MUST NOT re-build the target that is ALREADY being built: Xcode WILL CRASH YOUR COMPUTER if you try this (infinite recursion!)
#
#
# So: build ONLY the missing platforms/configurations.
if [ "true" == ${ALREADYINVOKED:-false} ]
then
echo "RECURSION: I am NOT the root invocation, so I'm NOT going to recurse"
else
# CRITICAL:
# Prevent infinite recursion (Xcode sucks)
export ALREADYINVOKED="true"
echo "RECURSION: I am the root ... recursing all missing build targets NOW..."
echo "RECURSION: ...about to invoke: xcodebuild -configuration \"${CONFIGURATION}\" -project \"${PROJECT_NAME}.xcodeproj\" -target \"${TARGET_NAME}\" -sdk \"${OTHER_SDK_TO_BUILD}\" ${ACTION} RUN_CLANG_STATIC_ANALYZER=NO" BUILD_DIR=\"${BUILD_DIR}\" BUILD_ROOT=\"${BUILD_ROOT}\" SYMROOT=\"${SYMROOT}\"
xcodebuild -configuration "${CONFIGURATION}" -project "${PROJECT_NAME}.xcodeproj" -target "${TARGET_NAME}" -sdk "${OTHER_SDK_TO_BUILD}" ${ACTION} RUN_CLANG_STATIC_ANALYZER=NO BUILD_DIR="${BUILD_DIR}" BUILD_ROOT="${BUILD_ROOT}" SYMROOT="${SYMROOT}"
ACTION="build"
#Merge all platform binaries as a fat binary for each configurations.
# Calculate where the (multiple) built files are coming from:
CURRENTCONFIG_DEVICE_DIR=${SYMROOT}/${CONFIGURATION}-iphoneos
CURRENTCONFIG_SIMULATOR_DIR=${SYMROOT}/${CONFIGURATION}-iphonesimulator
echo "Taking device build from: ${CURRENTCONFIG_DEVICE_DIR}"
echo "Taking simulator build from: ${CURRENTCONFIG_SIMULATOR_DIR}"
CREATING_UNIVERSAL_DIR=${SYMROOT}/${CONFIGURATION}-universal
echo "...I will output a universal build to: ${CREATING_UNIVERSAL_DIR}"
# ... remove the products of previous runs of this script
# NB: this directory is ONLY created by this script - it should be safe to delete!
rm -rf "${CREATING_UNIVERSAL_DIR}"
mkdir "${CREATING_UNIVERSAL_DIR}"
#
echo "lipo: for current configuration (${CONFIGURATION}) creating output file: ${CREATING_UNIVERSAL_DIR}/${EXECUTABLE_NAME}"
xcrun -sdk iphoneos lipo -create -output "${CREATING_UNIVERSAL_DIR}/${EXECUTABLE_NAME}" "${CURRENTCONFIG_DEVICE_DIR}/${EXECUTABLE_NAME}" "${CURRENTCONFIG_SIMULATOR_DIR}/${EXECUTABLE_NAME}"
#########
#
# Added: StackOverflow suggestion to also copy "include" files
# (untested, but should work OK)
#
echo "Fetching headers from ${PUBLIC_HEADERS_FOLDER_PATH}"
echo " (if you embed your library project in another project, you will need to add"
echo " a "User Search Headers" build setting of: (NB INCLUDE THE DOUBLE QUOTES BELOW!)"
echo ' "$(TARGET_BUILD_DIR)/usr/local/include/"'
if [ -d "${CURRENTCONFIG_DEVICE_DIR}${PUBLIC_HEADERS_FOLDER_PATH}" ]
then
mkdir -p "${CREATING_UNIVERSAL_DIR}${PUBLIC_HEADERS_FOLDER_PATH}"
# * needs to be outside the double quotes?
cp -r "${CURRENTCONFIG_DEVICE_DIR}${PUBLIC_HEADERS_FOLDER_PATH}"* "${CREATING_UNIVERSAL_DIR}${PUBLIC_HEADERS_FOLDER_PATH}"
fi
fi
INSTALL INSTRUCTIONS
...BONUS OPTIONAL usage:
If you can't find the output file, here's a workaround:
Add the following code to the very end of the script (courtesy of Frederik Wallner): open "${CREATING_UNIVERSAL_DIR}"
Apple deletes all output after 200 lines. Select your Target, and in the Run Script Phase, you MUST untick: "Show environment variables in build log"
if you're using a custom "build output" directory for XCode4, then XCode puts all your "unexpected" files in the wrong place.
...that is the location of your Universal Build.
How to include "non sourcecode" files in your project (PNG, PLIST, XML, etc)
Script to auto-copy the built bundle(s) into same folder as your FAT static library:
echo "RunScript2:"
echo "Autocopying any bundles into the 'universal' output folder created by RunScript1"
CREATING_UNIVERSAL_DIR=${SYMROOT}/${CONFIGURATION}-universal
cp -r "${BUILT_PRODUCTS_DIR}/"*.bundle "${CREATING_UNIVERSAL_DIR}"
yes you can use MapView in v2... for further details you can get help from this
https://gist.github.com/joshdholtz/4522551
SomeFragment.java
public class SomeFragment extends Fragment implements OnMapReadyCallback{
MapView mapView;
GoogleMap map;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.some_layout, container, false);
// Gets the MapView from the XML layout and creates it
mapView = (MapView) v.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
return v;
}
@Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
/*
//in old Api Needs to call MapsInitializer before doing any CameraUpdateFactory call
try {
MapsInitializer.initialize(this.getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
*/
// Updates the location and zoom of the MapView
/*CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
map.animateCamera(cameraUpdate);*/
map.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(43.1, -87.9)));
}
@Override
public void onResume() {
mapView.onResume();
super.onResume();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<permission
android:name="com.example.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.example.permission.MAPS_RECEIVE"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="your_key"/>
<activity
android:name=".HomeActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
some_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<com.google.android.gms.maps.MapView android:id="@+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
Use conditional comments. You're trying to detect users of IE < 9 and conditional comments will work in those browsers; in other browsers (IE >= 10 and non-IE), the comments will be treated as normal HTML comments, which is what they are.
Example HTML:
<!--[if lt IE 9]>
WE DON'T LIKE YOUR BROWSER
<![endif]-->
You can also do this purely with script, if you need:
var div = document.createElement("div");
div.innerHTML = "<!--[if lt IE 9]><i></i><![endif]-->";
var isIeLessThan9 = (div.getElementsByTagName("i").length == 1);
if (isIeLessThan9) {
alert("WE DON'T LIKE YOUR BROWSER");
}
Just specify it in shared.loader
or common.loader
property of /conf/catalina.properties
.
No sophisticated date/time formatting routines exist in JavaScript.
You will have to use an external library for formatted date output, "JavaScript Date Format" from Flagrant Badassery looks very promising.
For the input conversion, several suggestions have been made already. :)
I figured out that in my case, my database was in different subnet than the subnet from where i was trying to access the db.
Passing data from PHP is easy, you can generate JavaScript with it. The other way is a bit harder - you have to invoke the PHP script by a Javascript request.
An example (using traditional event registration model for simplicity):
<!-- headers etc. omitted -->
<script>
function callPHP(params) {
var httpc = new XMLHttpRequest(); // simplified for clarity
var url = "get_data.php";
httpc.open("POST", url, true); // sending as POST
httpc.onreadystatechange = function() { //Call a function when the state changes.
if(httpc.readyState == 4 && httpc.status == 200) { // complete and no errors
alert(httpc.responseText); // some processing here, or whatever you want to do with the response
}
};
httpc.send(params);
}
</script>
<a href="#" onclick="callPHP('lorem=ipsum&foo=bar')">call PHP script</a>
<!-- rest of document omitted -->
Whatever get_data.php
produces, that will appear in httpc.responseText. Error handling, event registration and cross-browser XMLHttpRequest compatibility are left as simple exercises to the reader ;)
See also Mozilla's documentation for further examples
function for sql server:
CREATE function NTSGetCinC(@Cadena nvarchar(4000), @UnChar nvarchar(100))
Returns int
as
begin
declare @t1 int
declare @t2 int
declare @t3 int
set @t1 = len(@Cadena)
set @t2 = len(replace(@Cadena,@UnChar,''))
set @t3 = len(@UnChar)
return (@t1 - @t2) / @t3
end
Code for visual basic and others:
Public Function NTSCuentaChars(Texto As String, CharAContar As String) As Long
NTSCuentaChars = (Len(Texto) - Len(Replace(Texto, CharAContar, ""))) / Len(CharAContar)
End Function
You can control select all customised classes and methods, and right-click, choose "Source", then select "Generate Element Comment". You should get what you want.
If you want to modify the Code Template then you can go to Preferences -- Java -- Code Style -- Code Templates, then do whatever you want.
If you just want a count of the distinct pairs.
The simplest way to do that is as follows
SELECT COUNT(DISTINCT a,b) FROM pairs
The previous solutions would list all the pairs and then you'd have to do a second query to count them.
Messing around with environment variables or hard-coded parent folder offsets is never a good idea when there is a API to get the info you want, call SHGetSpecialFolderPath(...,CSIDL_PROFILE,...)
var date = new Date();
var formattedDate = moment(date).format('YYYYMMDD');
Have a look at:
JPA query language
: The Java Persistence Query Language JPA Criteria API
: Using the Criteria API to Create QueriesThere are some differences between Function overloading & overriding though both contains the same function name.In overloading ,between the same name functions contain different type of argument or return type;Such as: "function add (int a,int b)" & "function add(float a,float b); Here the add() function is overloaded. In the case of overriding both the argument and function name are same.It generally found in inheritance or in traits.We have to follow some tactics to introduce, what function will execute now. So In overriding the programmer follows some tactics to execute the desired function where in the overloading the program can automatically identify the desired function...Thanks!
I just did some research on IANA official list. I believe the answer given here 'font/xxx' is incorrect as there is no 'font' type in the MIME standard.
Based on the RFCs and IANA, this appears to be the current state of the play as at May 2013:
These three are official and assigned by IANA:
These are not not official/assigned, and so must use the 'x-' syntax:
The application/font-woff appears new and maybe only official since Jan 2013. So "application/x-font-woff" might be safer/more compatible in the short term.
C++ solution found here (http://www.cplusplus.com/forum/unices/16430/)
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
void ouch(int sig)
{
printf("OUCH! - I got signal %d\n", sig);
}
int main()
{
struct sigaction act;
act.sa_handler = ouch;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
sigaction(SIGINT, &act, 0);
while(1) {
printf("Hello World!\n");
sleep(1);
}
}
I was also keen on these kind of games. One modern example which I have used is http://www.robotbattle.com/. There are various others - for example the ones listed at http://www.google.com/Top/Games/Video_Games/Simulation/Programming_Games/Robotics/
When including files in PHP, it acts like the code exists within the file they are being included from. Imagine copy and pasting the code from within each of your included files directly into your index.php
. That is how PHP works with includes.
So, in your example, since you've set a variable called $name
in your front.inc
file, and then included both front.inc
and end.inc
in your index.php
, you will be able to echo
the variable $name
anywhere after the include
of front.inc
within your index.php
. Again, PHP processes your index.php
as if the code from the two files you are including are part of the file.
When you place an echo
within an included file, to a variable that is not defined within itself, you're not going to get a result because it is treated separately then any other included file.
In other words, to do the behavior you're expecting, you will need to define it as a global.
Currently, it is evaluating to True
because the variable has a value. There is a good example found here of what happens when you evaluate arbitrary types as a boolean.
In short, what you want to do is isolate the 'True'
or 'False'
string and run eval
on it.
>>> eval('True')
True
>>> eval('False')
False
From the docs:
Another common operation is the use of boolean vectors to filter the data. The operators are: | for or, & for and, and ~ for not. These must be grouped by using parentheses.
http://pandas.pydata.org/pandas-docs/version/0.15.2/indexing.html#boolean-indexing
Try:
alldata_balance = alldata[(alldata[IBRD] !=0) | (alldata[IMF] !=0)]
I had a similar problem, and found that I accidentally defined a class as its own subclass. I got no warning or error for this but the compiling got stuck.
class mainClass : mainClass
{
...
}
tk.mainloop()
blocks. It means that execution of your Python commands halts there. You can see that by writing:
while 1:
ball.draw()
tk.mainloop()
print("hello") #NEW CODE
time.sleep(0.01)
You will never see the output from the print statement. Because there is no loop, the ball doesn't move.
On the other hand, the methods update_idletasks()
and update()
here:
while True:
ball.draw()
tk.update_idletasks()
tk.update()
...do not block; after those methods finish, execution will continue, so the while
loop will execute over and over, which makes the ball move.
An infinite loop containing the method calls update_idletasks()
and update()
can act as a substitute for calling tk.mainloop()
. Note that the whole while loop can be said to block just like tk.mainloop()
because nothing after the while loop will execute.
However, tk.mainloop()
is not a substitute for just the lines:
tk.update_idletasks()
tk.update()
Rather, tk.mainloop()
is a substitute for the whole while loop:
while True:
tk.update_idletasks()
tk.update()
Response to comment:
Here is what the tcl docs say:
Update idletasks
This subcommand of update flushes all currently-scheduled idle events from Tcl's event queue. Idle events are used to postpone processing until “there is nothing else to do”, with the typical use case for them being Tk's redrawing and geometry recalculations. By postponing these until Tk is idle, expensive redraw operations are not done until everything from a cluster of events (e.g., button release, change of current window, etc.) are processed at the script level. This makes Tk seem much faster, but if you're in the middle of doing some long running processing, it can also mean that no idle events are processed for a long time. By calling update idletasks, redraws due to internal changes of state are processed immediately. (Redraws due to system events, e.g., being deiconified by the user, need a full update to be processed.)
APN As described in Update considered harmful, use of update to handle redraws not handled by update idletasks has many issues. Joe English in a comp.lang.tcl posting describes an alternative:
So update_idletasks()
causes some subset of events to be processed that update()
causes to be processed.
From the update docs:
update ?idletasks?
The update command is used to bring the application “up to date” by entering the Tcl event loop repeatedly until all pending events (including idle callbacks) have been processed.
If the idletasks keyword is specified as an argument to the command, then no new events or errors are processed; only idle callbacks are invoked. This causes operations that are normally deferred, such as display updates and window layout calculations, to be performed immediately.
KBK (12 February 2000) -- My personal opinion is that the [update] command is not one of the best practices, and a programmer is well advised to avoid it. I have seldom if ever seen a use of [update] that could not be more effectively programmed by another means, generally appropriate use of event callbacks. By the way, this caution applies to all the Tcl commands (vwait and tkwait are the other common culprits) that enter the event loop recursively, with the exception of using a single [vwait] at global level to launch the event loop inside a shell that doesn't launch it automatically.
The commonest purposes for which I've seen [update] recommended are:
- Keeping the GUI alive while some long-running calculation is executing. See Countdown program for an alternative. 2) Waiting for a window to be configured before doing things like geometry management on it. The alternative is to bind on events such as that notify the process of a window's geometry. See Centering a window for an alternative.
What's wrong with update? There are several answers. First, it tends to complicate the code of the surrounding GUI. If you work the exercises in the Countdown program, you'll get a feel for how much easier it can be when each event is processed on its own callback. Second, it's a source of insidious bugs. The general problem is that executing [update] has nearly unconstrained side effects; on return from [update], a script can easily discover that the rug has been pulled out from under it. There's further discussion of this phenomenon over at Update considered harmful.
.....
Is there any chance I can make my program work without the while loop?
Yes, but things get a little tricky. You might think something like the following would work:
class Ball:
def __init__(self, canvas, color):
self.canvas = canvas
self.id = canvas.create_oval(10, 10, 25, 25, fill=color)
self.canvas.move(self.id, 245, 100)
def draw(self):
while True:
self.canvas.move(self.id, 0, -1)
ball = Ball(canvas, "red")
ball.draw()
tk.mainloop()
The problem is that ball.draw() will cause execution to enter an infinite loop in the draw() method, so tk.mainloop() will never execute, and your widgets will never display. In gui programming, infinite loops have to be avoided at all costs in order to keep the widgets responsive to user input, e.g. mouse clicks.
So, the question is: how do you execute something over and over again without actually creating an infinite loop? Tkinter has an answer for that problem: a widget's after()
method:
from Tkinter import *
import random
import time
tk = Tk()
tk.title = "Game"
tk.resizable(0,0)
tk.wm_attributes("-topmost", 1)
canvas = Canvas(tk, width=500, height=400, bd=0, highlightthickness=0)
canvas.pack()
class Ball:
def __init__(self, canvas, color):
self.canvas = canvas
self.id = canvas.create_oval(10, 10, 25, 25, fill=color)
self.canvas.move(self.id, 245, 100)
def draw(self):
self.canvas.move(self.id, 0, -1)
self.canvas.after(1, self.draw) #(time_delay, method_to_execute)
ball = Ball(canvas, "red")
ball.draw() #Changed per Bryan Oakley's comment
tk.mainloop()
The after() method doesn't block (it actually creates another thread of execution), so execution continues on in your python program after after() is called, which means tk.mainloop() executes next, so your widgets get configured and displayed. The after() method also allows your widgets to remain responsive to other user input. Try running the following program, and then click your mouse on different spots on the canvas:
from Tkinter import *
import random
import time
root = Tk()
root.title = "Game"
root.resizable(0,0)
root.wm_attributes("-topmost", 1)
canvas = Canvas(root, width=500, height=400, bd=0, highlightthickness=0)
canvas.pack()
class Ball:
def __init__(self, canvas, color):
self.canvas = canvas
self.id = canvas.create_oval(10, 10, 25, 25, fill=color)
self.canvas.move(self.id, 245, 100)
self.canvas.bind("<Button-1>", self.canvas_onclick)
self.text_id = self.canvas.create_text(300, 200, anchor='se')
self.canvas.itemconfig(self.text_id, text='hello')
def canvas_onclick(self, event):
self.canvas.itemconfig(
self.text_id,
text="You clicked at ({}, {})".format(event.x, event.y)
)
def draw(self):
self.canvas.move(self.id, 0, -1)
self.canvas.after(50, self.draw)
ball = Ball(canvas, "red")
ball.draw() #Changed per Bryan Oakley's comment.
root.mainloop()
I'm not sure what server side technology you are using but try using a json array. A couple of options for you to try:
{
"address": "colombo",
"username": "hesh",
"password": "123",
"registetedDate": "2015-4-3",
"firstname": "hesh",
"contactNo": "07762",
"accountNo": "16161",
"lastName": "jay"
},
[
1436517454492,
1436517476993
]
If that doesn't work you may also try:
{
freelancer: {
"address": "colombo",
"username": "hesh",
"password": "123",
"registetedDate": "2015-4-3",
"firstname": "hesh",
"contactNo": "07762",
"accountNo": "16161",
"lastName": "jay"
},
skills : [
1436517454492,
1436517476993
]
}
Considering there might be several img
tags I would recommend re.findall
:
import re
with open("sample.txt", 'r') as f_in, open('writetest.txt', 'w') as f_out:
for line in f_in:
for img in re.findall('<img[^>]+>', line):
print >> f_out, "yo it's a {}".format(img)
Was looking for a solution to this problem today. None of the above answers seemed to satisfy. I wanted a solution that could be a one liner, no conditional logic and nothing that had to be wrapped in a function.
Here's what I came up with, seems to work really well:
hostname="http://www.example.com:1234" hostname.split("//").slice(-1)[0].split(":")[0].split('.').slice(-2).join('.') // gives "example.com"
May look complicated at first glance, but it works pretty simply; the key is using 'slice(-n)' in a couple of places where the good part has to be pulled from the end of the split array (and [0] to get from the front of the split array).
Each of these tests return "example.com":
"http://example.com".split("//").slice(-1)[0].split(":")[0].split('.').slice(-2).join('.') "http://example.com:1234".split("//").slice(-1)[0].split(":")[0].split('.').slice(-2).join('.') "http://www.example.com:1234".split("//").slice(-1)[0].split(":")[0].split('.').slice(-2).join('.') "http://foo.www.example.com:1234".split("//").slice(-1)[0].split(":")[0].split('.').slice(-2).join('.')
Use a ValueConverter
[ValueConversion(typeof(string), typeof(String))]
public class MyConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return string.Format("{0}:{1}", (string) value, (string) parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}
and in the markup
<src:MyConverter x:Key="MyConverter"/>
. . .
<TextBlock Text="{Binding Name, Converter={StaticResource MyConverter Parameter=ID}}" />
Although the answers given here can be used to temporarily change window size, they don't seem to affect font size (at least not on my PC). I have an alternative way. I don't know if this what you're looking for but if you want to make changes automatically/permanently to Console font/window size, you can always do a script that edits the registry:
HKEY_CURRENT_USER\Console
HKEY_CURRENT_USER\Console\%%SystemRoot%%_system32_cmd.exe
HKEY_CURRENT_USER\Console\%%SystemRoot%%_system32_WindowsPowerShell_v1.0_powershell.exe
Those keys deal with the consoles that come up when your run a script or press shift and select "open command prompt here". The Command Prompt entry in your start menu does not use the registry to store it's preferences but stores the prefs in the shortcut itself.
I have a monitor that I can run in 720p native or 1440p supersampling. I needed a quick way to change my console's font/window size, so I made these scripts. These scripts do two things: (1) change the font/window sizes in the registry and (2) swap out the shortcuts in the Start menu with ones that have a different window and font size. I basically made two sets of copies of the Command Prompt and Power Shell shortcuts and stored them in Documents. One set of shortcuts was configured with Consolas font size at 16 for my monitor is in 720p (called it "Command Prompt.720pRes.lnk") and another version of the same shortcut was configure with font size at 36 (called it "Command Prompt.HighRes.lnk"). The script will copy from the set I want to use to overwrite the Start menu one.
console-1440p.cmd:
::Assign New Window and Font Size for Windows Command Prompt
set CMDpNewFont=00240000
set CMDpNewWindowSize=000f0078
set commandPromptLinkFlag=highRes
::Make temporary .reg file to resize command console
>%temp%\consoleSIZEchanger.reg ECHO Windows Registry Editor Version 5.00
>>%temp%\consoleSIZEchanger.reg ECHO.
>>%temp%\consoleSIZEchanger.reg ECHO [HKEY_CURRENT_USER\Console]
>>%temp%\consoleSIZEchanger.reg ECHO "WindowSize"=dword:%CMDpNewWindowSize%
>>%temp%\consoleSIZEchanger.reg ECHO "FontSize"=dword:%CMDpNewFont%
>>%temp%\consoleSIZEchanger.reg ECHO.
>>%temp%\consoleSIZEchanger.reg ECHO [HKEY_CURRENT_USER\Console\%%SystemRoot%%_system32_cmd.exe]
>>%temp%\consoleSIZEchanger.reg ECHO "WindowSize"=dword:%CMDpNewWindowSize%
>>%temp%\consoleSIZEchanger.reg ECHO "FontSize"=dword:%CMDpNewFont%
>>%temp%\consoleSIZEchanger.reg ECHO.
>>%temp%\consoleSIZEchanger.reg ECHO [HKEY_CURRENT_USER\Console\%%SystemRoot%%_system32_WindowsPowerShell_v1.0_powershell.exe]
>>%temp%\consoleSIZEchanger.reg ECHO "WindowSize"=dword:%CMDpNewWindowSize%
>>%temp%\consoleSIZEchanger.reg ECHO "FontSize"=dword:%CMDpNewFont%
::Merge and delete consoleSIZEchanger.reg
REGEDIT /S %temp%\consoleSIZEchanger.reg
del %temp%\consoleSIZEchanger.reg
::Copy Preconfigured Command Prompt/PowerShell shortcuts to Pinned Start Menu, Accessories and any other Custom Location you would define
copy "%homedrive%%homepath%\Documents\Command Prompt.%commandPromptLinkFlag%.lnk" "%homedrive%%homepath%\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\StartMenu\Command Prompt.lnk"
copy "%homedrive%%homepath%\Documents\Command Prompt.%commandPromptLinkFlag%.lnk" "%homedrive%%homepath%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Accessories\Command Prompt.lnk"
copy "%homedrive%%homepath%\Documents\Windows PowerShell.%commandPromptLinkFlag%.lnk" "%homedrive%\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\Windows PowerShell\Windows PowerShell.lnk"
copy "%homedrive%%homepath%\Documents\Windows PowerShell.%commandPromptLinkFlag%.lnk" "%homedrive%%homepath%\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\StartMenu\Windows PowerShell.lnk"
copy "%homedrive%%homepath%\Documents\Windows PowerShell (x86).%commandPromptLinkFlag%.lnk" "%homedrive%\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\Windows PowerShell\Windows PowerShell (x86).lnk"
copy "%homedrive%%homepath%\Documents\Windows PowerShell (x86).%commandPromptLinkFlag%.lnk" "%homedrive%%homepath%\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\StartMenu\Windows PowerShell (x86).lnk"
console-720p.cmd:
::Assign New Window and Font Size for Windows Command Prompt
set CMDpNewFont=00100000
set CMDpNewWindowSize=0014007d
set commandPromptLinkFlag=720Res
::Make temporary .reg file to resize command console
>%temp%\consoleSIZEchanger.reg ECHO Windows Registry Editor Version 5.00
>>%temp%\consoleSIZEchanger.reg ECHO.
>>%temp%\consoleSIZEchanger.reg ECHO [HKEY_CURRENT_USER\Console]
>>%temp%\consoleSIZEchanger.reg ECHO "WindowSize"=dword:%CMDpNewWindowSize%
>>%temp%\consoleSIZEchanger.reg ECHO "FontSize"=dword:%CMDpNewFont%
>>%temp%\consoleSIZEchanger.reg ECHO.
>>%temp%\consoleSIZEchanger.reg ECHO [HKEY_CURRENT_USER\Console\%%SystemRoot%%_system32_cmd.exe]
>>%temp%\consoleSIZEchanger.reg ECHO "WindowSize"=dword:%CMDpNewWindowSize%
>>%temp%\consoleSIZEchanger.reg ECHO "FontSize"=dword:%CMDpNewFont%
>>%temp%\consoleSIZEchanger.reg ECHO.
>>%temp%\consoleSIZEchanger.reg ECHO [HKEY_CURRENT_USER\Console\%%SystemRoot%%_system32_WindowsPowerShell_v1.0_powershell.exe]
>>%temp%\consoleSIZEchanger.reg ECHO "WindowSize"=dword:%CMDpNewWindowSize%
>>%temp%\consoleSIZEchanger.reg ECHO "FontSize"=dword:%CMDpNewFont%
::Merge and delete consoleSIZEchanger.reg
REGEDIT /S %temp%\consoleSIZEchanger.reg
del %temp%\consoleSIZEchanger.reg
::Copy Preconfigured Command Prompt/PowerShell shortcuts to Pinned Start Menu, Accessories and any other Custom Location you would define
copy "%homedrive%%homepath%\Documents\Command Prompt.%commandPromptLinkFlag%.lnk" "%homedrive%%homepath%\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\StartMenu\Command Prompt.lnk"
copy "%homedrive%%homepath%\Documents\Command Prompt.%commandPromptLinkFlag%.lnk" "%homedrive%%homepath%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Accessories\Command Prompt.lnk"
copy "%homedrive%%homepath%\Documents\Windows PowerShell.%commandPromptLinkFlag%.lnk" "%homedrive%\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\Windows PowerShell\Windows PowerShell.lnk"
copy "%homedrive%%homepath%\Documents\Windows PowerShell.%commandPromptLinkFlag%.lnk" "%homedrive%%homepath%\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\StartMenu\Windows PowerShell.lnk"
copy "%homedrive%%homepath%\Documents\Windows PowerShell (x86).%commandPromptLinkFlag%.lnk" "%homedrive%\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\Windows PowerShell\Windows PowerShell (x86).lnk"
copy "%homedrive%%homepath%\Documents\Windows PowerShell (x86).%commandPromptLinkFlag%.lnk" "%homedrive%%homepath%\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\StartMenu\Windows PowerShell (x86).lnk"
works perfekt for me:
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
CTEditor ctEdit = Element as CTEditor;
if (ctEdit == null) return;
if (e.PropertyName == "Text")
{
double xHeight = Element.Height;
double aHaight = Control.Height;
double height;
Control.Measure(LayoutParams.MatchParent,LayoutParams.WrapContent);
height = Control.MeasuredHeight;
height = xHeight / aHaight * height;
if (Element.HeightRequest != height)
Element.HeightRequest = height;
}
}
Check the manual for mysql_fetch_object()
. It returns an object, not an array of objects.
I'm guessing you want something like this
$results = mysql_query("SELECT * FROM sidemenu WHERE `menu_id`='".$menu."' ORDER BY `id` ASC LIMIT 1", $con);
$sidemenus = array();
while ($sidemenu = mysql_fetch_object($results)) {
$sidemenus[] = $sidemenu;
}
Might I suggest you have a look at PDO. PDOStatement::fetchAll(PDO::FETCH_OBJ)
does what you assumed mysql_fetch_object()
to do
Anonymous ftp logins are usually the username 'anonymous' with the user's email address as the password. Some servers parse the password to ensure it looks like an email address.
User: anonymous
Password: [email protected]
Use git rebase --abort
. From the official Linux kernel documentation for git rebase
:
git rebase --continue | --skip | --abort | --edit-todo
You can play here with different types and check the output,
export class ParentCmp {
myVar:stirng="micronyks";
myVal:any;
myArray:Array[]=[1,2,3];
myArr:Array[];
constructor() {
if(this.myVar){
console.log('has value') // answer
}
else{
console.log('no value');
}
if(this.myVal){
console.log('has value')
}
else{
console.log('no value'); //answer
}
if(this.myArray){
console.log('has value') //answer
}
else{
console.log('no value');
}
if(this.myArr){
console.log('has value')
}
else{
console.log('no value'); //answer
}
}
}
The currently accepted answer does not actually address the question, which asks how to save lists that contain both strings and float numbers. For completeness I provide a fully working example, which is based, with some modifications, on the link given in @joris comment.
import numpy as np
names = np.array(['NAME_1', 'NAME_2', 'NAME_3'])
floats = np.array([ 0.1234 , 0.5678 , 0.9123 ])
ab = np.zeros(names.size, dtype=[('var1', 'U6'), ('var2', float)])
ab['var1'] = names
ab['var2'] = floats
np.savetxt('test.txt', ab, fmt="%10s %10.3f")
Update: This example also works properly in Python 3 by using the 'U6'
Unicode string dtype, when creating the ab
structured array, instead of the 'S6'
byte string. The latter dtype would work in Python 2.7, but would write strings like b'NAME_1'
in Python 3.
Trying to access an undefined variable will throw you a ReferenceError
.
A solution to this is to use typeof
:
if (typeof window === "undefined") {
console.log("Oops, `window` is not defined")
}
or a try catch:
try { window } catch (err) {
console.log("Oops, `window` is not defined")
}
While typeof window
is probably the cleanest of the two, the try catch can still be useful in some cases.
Access-Engine does not support
SELECT count(DISTINCT....) FROM ...
You have to do it like this:
SELECT count(*)
FROM
(SELECT DISTINCT Name FROM table1)
Its a little workaround... you're counting a DISTINCT selection.
sys.path
might include items that aren't specifically in your PYTHONPATH
environment variable. To query the variable directly, use:
import os
try:
user_paths = os.environ['PYTHONPATH'].split(os.pathsep)
except KeyError:
user_paths = []
You can't do it like that. The join
clause (and the Join()
extension method) supports only equijoins. That's also the reason, why it uses equals
and not ==
. And even if you could do something like that, it wouldn't work, because join
is an inner join, not outer join.
This example will help you:
<form>
<input type="button" value="Open Window" onclick="window.open('http://www.google.com')">
</form>
You can open next page on same page by:
<input type="button" value="Open Window" onclick="window.open('http://www.google.com','_self')">
I think you set it as
var data = [];
but after some time you made it like:
data = 'some thing which is not an array';
then
data.push('')
will not work as it is not an array anymore.
UPDATE your_table
SET your_field = REPLACE(your_field, 'articles/updates/', 'articles/news/')
WHERE your_field LIKE '%articles/updates/%'
Now rows that were like
http://www.example.com/articles/updates/43
will be
http://www.example.com/articles/news/43
You can use the report process status ps
command:
ps ax | grep '[m]ysqld'
Python 2
Using urllib.urlretrieve
import urllib
urllib.urlretrieve("http://www.gunnerkrigg.com//comics/00000001.jpg", "00000001.jpg")
Python 3
Using urllib.request.urlretrieve (part of Python 3's legacy interface, works exactly the same)
import urllib.request
urllib.request.urlretrieve("http://www.gunnerkrigg.com//comics/00000001.jpg", "00000001.jpg")
Solved, use array list of string to get name from Ingredients. Use below code:
JSONObject jsonObj = new JSONObject(jsonStr);
//extracting data array from json string
JSONArray ja_data = jsonObj.getJSONArray("data");
int length = ja_data.length();
//loop to get all json objects from data json array
for(int i=0; i<length; i++){
JSONObject jObj = ja_data.getJSONObject(i);
Toast.makeText(this, jObj.getString("Name"), Toast.LENGTH_LONG).show();
// getting inner array Ingredients
JSONArray ja = jObj.getJSONArray("Ingredients");
int len = ja.length();
ArrayList<String> Ingredients_names = new ArrayList<>();
for(int j=0; j<len; j++){
JSONObject json = ja.getJSONObject(j);
Ingredients_names.add(json.getString("name"));
}
}
It appears that this is a FAQ, and the resolution offered is:
Simple search (Ctrl+H) without regexp
You can turn on View/Show End of Line or view/Show All, and select the now visible newline characters. Then when you start the command some characters matching the newline character will be pasted into the search field. Matches will be replaced by the replace string, unlike in regex mode.
Note 1: If you select them with the mouse, start just before them and drag to the start of the next line. Dragging to the end of the line won't work.
Note 2: You can't copy and paste them into the field yourself.
Advanced search (Ctrl+R) without regexp
Ctrl+M will insert something that matches newlines. They will be replaced by the replace string.
I know this post is old, however, to get the effect you are looking for, you may want to try the following:
#define TAKE_ADVANTAGE
/* Forward declaration of "struct Cell" as type Cell. */
typedef struct Cell Cell;
#ifdef TAKE_ADVANTAGE
/*
Define Cell structure taking advantage of forward declaration.
*/
struct Cell
{
int isParent;
Cell *child;
};
#else
/*
Or...you could define it as other posters have mentioned without taking
advantage of the forward declaration.
*/
struct Cell
{
int isParent;
struct Cell *child;
};
#endif
/*
Some code here...
*/
/* Use the Cell type. */
Cell newCell;
In either of the two cases mentioned in the code fragment above, you MUST declare your child Cell structure as a pointer. If you do not, then you will get the "field 'child' has incomplete type" error. The reason is that "struct Cell" must be defined in order for the compiler to know how much space to allocate when it is used.
If you attempt to use "struct Cell" inside the definition of "struct Cell", then the compiler cannot yet know how much space "struct Cell" is supposed to take. However, the compiler already knows how much space a pointer takes, and (with the forward declaration) it knows that "Cell" is a type of "struct Cell" (although it doesn't yet know how big a "struct Cell" is). So, the compiler can define a "Cell *" within the struct that is being defined.
Just adding to the correct answer you can set the timeout with the arrow function like this:
it('Some test', () => {
}).timeout(5000)
[self.navigationController.navigationBar.layer setZPosition:-0.1];
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(10, 20, 35, 35)];
[view setBackgroundColor:[UIColor redColor]];
[self.navigationController.view addSubview:view];
[self.navigationController.view bringSubviewToFront:view];
self.navigationController.view.clipsToBounds = NO;
[self.navigationController.navigationBar.layer setZPosition:0.0];
Recently D3js is able to handle local json file.
This is the issue https://github.com/mbostock/d3/issues/673
This is the patch inorder for D3 to work with local json files. https://github.com/mbostock/d3/pull/632
Try
string reversed(temp.rbegin(), temp.rend());
EDIT: Elaborating as requested.
string::rbegin()
and string::rend()
, which stand for "reverse begin" and "reverse end" respectively, return reverse iterators into the string. These are objects supporting the standard iterator interface (operator*
to dereference to an element, i.e. a character of the string, and operator++
to advance to the "next" element), such that rbegin()
points to the last character of the string, rend()
points to the first one, and advancing the iterator moves it to the previous character (this is what makes it a reverse iterator).
Finally, the constructor we are passing these iterators into is a string constructor of the form:
template <typename Iterator>
string(Iterator first, Iterator last);
which accepts a pair of iterators of any type denoting a range of characters, and initializes the string to that range of characters.
sudo ./scriptname
sudo bash will basically switch you over to running a shell as root, although it's probably best to stay as su as little as possible.
Since ng-show
is an angular attribute i think, we don't need to put the evaluation flower brackets ({{}}
)..
For attributes like class
we need to encapsulate the variables with evaluation flower brackets ({{}}
).
Your compound PRIMARY KEY
specification already does what you want. Omit the line that's giving you a syntax error, and omit the redundant CONSTRAINT
(already implied), too:
CREATE TABLE tags
(
question_id INTEGER NOT NULL,
tag_id SERIAL NOT NULL,
tag1 VARCHAR(20),
tag2 VARCHAR(20),
tag3 VARCHAR(20),
PRIMARY KEY(question_id, tag_id)
);
NOTICE: CREATE TABLE will create implicit sequence "tags_tag_id_seq" for serial column "tags.tag_id"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "tags_pkey" for table "tags"
CREATE TABLE
pg=> \d tags
Table "public.tags"
Column | Type | Modifiers
-------------+-----------------------+-------------------------------------------------------
question_id | integer | not null
tag_id | integer | not null default nextval('tags_tag_id_seq'::regclass)
tag1 | character varying(20) |
tag2 | character varying(20) |
tag3 | character varying(20) |
Indexes:
"tags_pkey" PRIMARY KEY, btree (question_id, tag_id)
If you run SHOW VARIABLES
from a mysql console you can look for basedir.
When I run the following:
mysql> SHOW VARIABLES WHERE `Variable_name` = 'basedir';
on my system I get /usr/local/mysql
as the Value returned.
(I am not using MAMP - I installed MySQL with homebrew.
mysqld
on my machine is in /usr/local/mysql/bin
so the basedir is where most everything will be installed to.
Also util:
mysql> SHOW VARIABLES WHERE `Variable_name` = 'datadir';
To find where the DBs are stored.
For more: http://dev.mysql.com/doc/refman/5.0/en/show-variables.html
and http://dev.mysql.com/doc/refman/5.0/en/server-options.html#option_mysqld_basedir
The solution that work for me is the following:
$("#spanId").text("text to show");
Using jQuery you can achieve this by doing
var cw = $('.child').width();
$('.child').css({'height':cw+'px'});
In SQL Server, you can do:
select coalesce(format(try_convert(date, col, 112), 'yyyyMMdd'), col)
This attempts the conversion, keeping the previous value if available.
Note: I hope you learned a lesson about storing dates as dates and not strings.
You can use a lambda with an input parameter, like so:
.Returns((string myval) => { return myval; });
Or slightly more readable:
.Returns<string>(x => x);
Refer https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists
dt = datetime.datetime(*t[:7])
Another example:
[
[
{
"@id":1,
"deviceId":1,
"typeOfDevice":"1",
"state":"1",
"assigned":true
},
{
"@id":2,
"deviceId":3,
"typeOfDevice":"3",
"state":"Excelent",
"assigned":true
},
{
"@id":3,
"deviceId":4,
"typeOfDevice":"júuna",
"state":"Excelent",
"assigned":true
},
{
"@id":4,
"deviceId":5,
"typeOfDevice":"nffjnff",
"state":"Regular",
"assigned":true
},
{
"@id":5,
"deviceId":6,
"typeOfDevice":"44",
"state":"Excelent",
"assigned":true
},
{
"@id":6,
"deviceId":7,
"typeOfDevice":"rr",
"state":"Excelent",
"assigned":true
},
{
"@id":7,
"deviceId":8,
"typeOfDevice":"j",
"state":"Excelent",
"assigned":true
},
{
"@id":8,
"deviceId":9,
"typeOfDevice":"55",
"state":"Excelent",
"assigned":true
},
{
"@id":9,
"deviceId":10,
"typeOfDevice":"5",
"state":"Excelent",
"assigned":true
},
{
"@id":10,
"deviceId":11,
"typeOfDevice":"5",
"state":"Excelent",
"assigned":true
}
],
1
]
$.each(data[0], function(i, item) {
data[0][i].deviceId + data[0][i].typeOfDevice + data[0][i].state + data[0][i].assigned
});
Use http://www.jsoneditoronline.org/ to understand the JSON code better
You can use the following:
return Redirect::back()->withInput(Input::all());
If you're using Form Request Validation, this is exactly how Laravel will redirect you back with errors and the given input.
Excerpt from \Illuminate\Foundation\Validation\ValidatesRequests
:
return redirect()->to($this->getRedirectUrl()) ->withInput($request->input()) ->withErrors($errors, $this->errorBag());
Based on my comment to the accepted answer, there are a lot potential pitfalls that you may encounter by declaring font-sizes smaller than 12px
. By declaring styles that lead to computed font-sizes of less than 12px
, like so:
html {
font-size: 8px;
}
p {
font-size: 1.4rem;
}
// Computed p size: 11px.
You'll run into issues with browsers, like Chrome with a Chinese language pack that automatically renders any font sizes computed under 12px
as 12px
. So, the following is true:
h6 {
font-size: 12px;
}
p {
font-size: 8px;
}
// Both render at 12px in Chrome with a Chinese language pack.
// How unpleasant of a surprise.
I would also argue that for accessibility reasons, you generally shouldn't use sizes under 12px. You might be able to make a case for captions and the like, but again--prepare to be surprised under some browser setups, and prepared to make your grandma squint when she's trying to read your content.
I would instead, opt for something like this:
h1 {
font-size: 2.5rem;
}
h2 {
font-size: 2.25rem;
}
h3 {
font-size: 2rem;
}
h4 {
font-size: 1.75rem;
}
h5 {
font-size: 1.5rem;
}
h6 {
font-size: 1.25rem;
}
p {
font-size: 1rem;
}
@media (max-width: 480px) {
html {
font-size: 12px;
}
}
@media (min-width: 480px) {
html {
font-size: 13px;
}
}
@media (min-width: 768px) {
html {
font-size: 14px;
}
}
@media (min-width: 992px) {
html {
font-size: 15px;
}
}
@media (min-width: 1200px) {
html {
font-size: 16px;
}
}
You'll find that tons of sites that have to focus on accessibility use rather large font sizes, even for p
elements.
As a side note, setting margin-bottom
equal to the font-size
usually also tends to be attractive, i.e.:
h1 {
font-size: 2.5rem;
margin-bottom: 2.5rem;
}
Good luck.
You can remove them from the repository manually:
git rm --cached file1 file2 dir/file3
Or, if you have a lot of files:
git rm --cached `git ls-files -i --exclude-from=.gitignore`
But this doesn't seem to work in Git Bash on Windows. It produces an error message. The following works better:
git ls-files -i --exclude-from=.gitignore | xargs git rm --cached
Regarding rewriting the whole history without these files, I highly doubt there's an automatic way to do it.
And we all know that rewriting the history is bad, don't we? :)
An MSI is a Windows Installer database. Windows Installer (a service installed with Windows) uses this to install software on your system (i.e. copy files, set registry values, etc...).
A setup.exe may either be a bootstrapper or a non-msi installer. A non-msi installer will extract the installation resources from itself and manage their installation directly. A bootstrapper will contain an MSI instead of individual files. In this case, the setup.exe will call Windows Installer to install the MSI.
Some reasons you might want to use a setup.exe:
Crude way:
The problem with the method above is that we will be doing the "find" multiple times, i.e. there is a possibility of each node getting traversed multiple times. We can overcome this problem if we can record the information so as to not process it again (think dynamic programming).
So rather than doing find every node, we keep a record of as to whats already been found.
Better Way:
Code:
struct Node *
findCA(struct Node *root, struct Node *n1, struct Node *n2, int *set) {
int left_set, right_set;
left_set = right_set = 0;
struct Node *leftCA, *rightCA;
leftCA = rightCA = NULL;
if (root == NULL) {
return NULL;
}
if (root == n1 || root == n2) {
left_set = 1;
if (n1 == n2) {
right_set = 1;
}
}
if(!left_set) {
leftCA = findCA(root->left, n1, n2, &left_set);
if (leftCA) {
return leftCA;
}
}
if (!right_set) {
rightCA= findCA(root->right, n1, n2, &right_set);
if(rightCA) {
return rightCA;
}
}
if (left_set && right_set) {
return root;
} else {
*set = (left_set || right_set);
return NULL;
}
}
One can make calls by using Bootstrap. The current version does not has any source update issues Trouble updating Bootstrap's typeahead data-source with post response , i.e. the source of bootstrap once updated can be again modified.
Please refer to below for an example:
jQuery('#help').typeahead({
source : function(query, process) {
jQuery.ajax({
url : "urltobefetched",
type : 'GET',
data : {
"query" : query
},
dataType : 'json',
success : function(json) {
process(json);
}
});
},
minLength : 1,
});
Here is how to set it correctly for both iOS 6 and 7.
+ (void)fixNavBarColor:(UINavigationBar*)bar {
if (iosVersion >= 7) {
bar.barTintColor = [UIColor redColor];
bar.translucent = NO;
}else {
bar.tintColor = [UIColor redColor];
bar.opaque = YES;
}
}
Before converting a function as promise In Node.JS
var request = require('request'); //http wrapped module
function requestWrapper(url, callback) {
request.get(url, function (err, response) {
if (err) {
callback(err);
}else{
callback(null, response);
}
})
}
requestWrapper(url, function (err, response) {
console.log(err, response)
})
After Converting It
var request = require('request');
function requestWrapper(url) {
return new Promise(function (resolve, reject) { //returning promise
request.get(url, function (err, response) {
if (err) {
reject(err); //promise reject
}else{
resolve(response); //promise resolve
}
})
})
}
requestWrapper('http://localhost:8080/promise_request/1').then(function(response){
console.log(response) //resolve callback(success)
}).catch(function(error){
console.log(error) //reject callback(failure)
})
Incase you need to handle multiple request
var allRequests = [];
allRequests.push(requestWrapper('http://localhost:8080/promise_request/1'))
allRequests.push(requestWrapper('http://localhost:8080/promise_request/2'))
allRequests.push(requestWrapper('http://localhost:8080/promise_request/5'))
Promise.all(allRequests).then(function (results) {
console.log(results);//result will be array which contains each promise response
}).catch(function (err) {
console.log(err)
});
The Boris Guéry answer's at this post, may help you: Doctrine 2, query inside entities
$idsToFilter = array(1,2,3,4);
$member->getComments()->filter(
function($entry) use ($idsToFilter) {
return in_array($entry->getId(), $idsToFilter);
}
);
You can use routerLink in the following manner,
<input type="button" value="Add Bulk Enquiry" [routerLink]="['../addBulkEnquiry']" class="btn">
or use <button [routerLink]="['./url']">
in your case, for more info you could read the entire stacktrace on github https://github.com/angular/angular/issues/9471
the other methods are also correct but they create a dependency on the component file.
Hope your concern is resolved.
List
is an interface, not a concrete class.
An interface is just a set of functions that a class can implement; it doesn't make any sense to instantiate an interface.
ArrayList
is a concrete class that happens to implement this interface and all of the methods in it.
You don't escape quotes in regular expressions
this.Vals.replace(/["']/g, "")
You can simply just pass the attribute you want without any annotations in your controller:
@RequestMapping(value = "/someUrl")
public String someMethod(String valueOne) {
//do stuff with valueOne variable here
}
Works with GET and POST
Express.js is a framework used for Node and it is most commonly used as a web application for node js.
Here is a link to a video on how to quickly set up a node app with express https://www.youtube.com/watch?v=QEcuSSnqvck
You will simply need to do a type check for each of the basic numeric types.
Here's an extension method that should do the job:
public static bool IsNumber(this object value)
{
return value is sbyte
|| value is byte
|| value is short
|| value is ushort
|| value is int
|| value is uint
|| value is long
|| value is ulong
|| value is float
|| value is double
|| value is decimal;
}
This should cover all numeric types.
It seems you do actually want to parse the number from a string during deserialisation. In this case, it would probably just be best to use double.TryParse
.
string value = "123.3";
double num;
if (!double.TryParse(value, out num))
throw new InvalidOperationException("Value is not a number.");
Of course, this wouldn't handle very large integers/long decimals, but if that is the case you just need to add additional calls to long.TryParse
/ decimal.TryParse
/ whatever else.
Have you seen the SqlDateTime object? use SqlDateTime.MinValue
to get your minimum date (Jan 1 1753).
I created a derived class to have a more self-documented instruction instead of $conn=null;
.
class CMyPDO extends PDO {
public function __construct($dsn, $username = null, $password = null, array $options = null) {
parent::__construct($dsn, $username, $password, $options);
}
static function getNewConnection() {
$conn=null;
try {
$conn = new CMyPDO("mysql:host=$host;dbname=$dbname",$user,$pass);
}
catch (PDOException $exc) {
echo $exc->getMessage();
}
return $conn;
}
static function closeConnection(&$conn) {
$conn=null;
}
}
So I can call my code between:
$conn=CMyPDO::getNewConnection();
// my code
CMyPDO::closeConnection($conn);
Just to extend on the previous answer, if you are linking two requests together and want to send the cookies returned from the first one to the second one (for example, maintaining a session alive across requests) you can do:
import requests
r1 = requests.post('http://www.yourapp.com/login')
r2 = requests.post('http://www.yourapp.com/somepage',cookies=r1.cookies)
If you develop in Visual Studio 2013 and 2015 versions, you can use their GPU Usage tool:
Moreover, it seems you can diagnose any application with it, not only Visual Studio Projects:
In addition to Visual Studio projects you can also collect GPU usage data on any loose .exe applications that you have sitting around. Just open the executable as a solution in Visual Studio and then start up a diagnostics session and you can target it with GPU usage. This way if you are using some type of engine or alternative development environment you can still collect data on it as long as you end up with an executable.
Source: http://blogs.msdn.com/b/ianhu/archive/2014/12/16/gpu-usage-for-directx-in-visual-studio.aspx
NoClassDefFound error is a nebulous error and is often hiding a more serious issue. It is not the same as ClassNotFoundException (which is thrown when the class is just plain not there).
NoClassDefFound may indicate the class is not there, as the javadocs indicate, but it is typically thrown when, after the classloader has loaded the bytes for the class and calls "defineClass" on them. Also carefully check your full stack trace for other clues or possible "cause" Exceptions (though your particular backtrace shows none).
The first place to look when you get a NoClassDefFoundError is in the static bits of your class i.e. any initialization that takes place during the defining of the class. If this fails it will throw a NoClassDefFoundError - it's supposed to throw an ExceptionInInitializerError and indicate the details of the problem but in my experience, these are rare. It will only do the ExceptionInInitializerError the first time it tries to define the class, after that it will just throw NoClassDefFound. So look at earlier logs.
I would thus suggest looking at the code in that HibernateTransactionInterceptor line and seeing what it is requiring. It seems that it is unable to define the class SpringFactory. So maybe check the initialization code in that class, that might help. If you can debug it, stop it at the last line above (17) and debug into so you can try find the exact line that is causing the exception. Also check higher up in the log, if you very lucky there might be an ExceptionInInitializerError.
Here is the simple code snippet to upload a single file with additional parameters using requests:
url = 'https://<file_upload_url>'
fp = '/Users/jainik/Desktop/data.csv'
files = {'file': open(fp, 'rb')}
payload = {'file_id': '1234'}
response = requests.put(url, files=files, data=payload, verify=False)
Please note that you don't need to explicitly specify any content type.
NOTE: Wanted to comment on one of the above answers but could not because of low reputation so drafted a new response here.
If you are using Entity Framework like me, you should define Time out on Startup class as follows:
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), o => o.CommandTimeout(180)));
Cannot comment anymore but voted it up and wanted to let folks know that "
works very well for the xml config files when forming regex expressions for RegexTransformer in Solr like so: regex=".*img src="(.*)".*"
using the escaped version instead of double-quotes.
//an easy way:
str := fmt.Sprint(data)
On wamp in my configuration where I have multiple phpmyadmins, the values in config files were overwritten in wamp/alias/phpmyadmin.conf
. I set up two lines there:
1. php_admin_value max_execution_time 3600
2. php_admin_value max_input_time 3600
... it finally worked!
mime-types starting with x-
are not standardized. In case of javascript it's kind of outdated.
Additional the second code snippet
<?Header('Content-Type: text/javascript');?>
requires short_open_tags
to be enabled. you should avoid it.
<?php Header('Content-Type: text/javascript');?>
However, the completely correct mime-type for javascript is
application/javascript
http://www.iana.org/assignments/media-types/application/index.html
In the accepted answer you get annoying spacing between the visible rows when the expandable row is hidden. You can get rid of that by adding this to css:
.collapse-row.collapsed + tr {
display: none;
}
'+' is adjacent sibling selector, so if you want your expandable row to be the next row, this selects the next tr following tr named collapse-row.
Here is updated fiddle: http://jsfiddle.net/Nb7wy/2372/
Try to this cors npm modules.
var cors = require('cors')
var app = express()
app.use(cors())
This module provides many features to fine tune cors setting such as domain whitelisting, enabling cors for specific apis etc.
And this is an alternative.If you are returning as list then it is simple to get the values.
def select_choice():
...
return [i, card]
values = select_choice()
print values[0]
print values[1]
I am pretty sure all you have to do is run
pip3 install jupyter
I would like to add a solution, that have helpt me to solve this problem in entity framework:
var eventsCustom = eventCustomRepository.FindAllEventsCustomByUniqueStudentReference(userDevice.UniqueStudentReference)
.Where(x => x.DateTimeStart.Year == currentDateTime.Year &&
x.DateTimeStart.Month== currentDateTime.Month &&
x.DateTimeStart.Day == currentDateTime.Day
);
I hope that it helps.
Here is an optimal and robust solution for checking string palindrome using ES6 features.
const str="madam"_x000D_
var result=[...str].reduceRight((c,v)=>((c+v)))==str?"Palindrome":"Not Palindrome";_x000D_
console.log(result);
_x000D_
simple and best way to use date function
example
SELECT * FROM
data
WHERE date(datetime) = '2009-10-20'
OR
SELECT * FROM
data
WHERE date(datetime ) >= '2009-10-20' && date(datetime ) <= '2009-10-20'
Here is an expanded solution based on DrewT's answer above that uses cookies if localStorage is not available. It uses Mozilla's docCookies library:
function localStorageGet( pKey ) {
if( localStorageSupported() ) {
return localStorage[pKey];
} else {
return docCookies.getItem( 'localstorage.'+pKey );
}
}
function localStorageSet( pKey, pValue ) {
if( localStorageSupported() ) {
localStorage[pKey] = pValue;
} else {
docCookies.setItem( 'localstorage.'+pKey, pValue );
}
}
// global to cache value
var gStorageSupported = undefined;
function localStorageSupported() {
var testKey = 'test', storage = window.sessionStorage;
if( gStorageSupported === undefined ) {
try {
storage.setItem(testKey, '1');
storage.removeItem(testKey);
gStorageSupported = true;
} catch (error) {
gStorageSupported = false;
}
}
return gStorageSupported;
}
In your source, just use:
localStorageSet( 'foobar', 'yes' );
...
var foo = localStorageGet( 'foobar' );
...
This error is caused by:
Y = Dataset.iloc[:,18].values
Indexing is out of bounds here most probably because there are less than 19 columns in your Dataset, so column 18 does not exist. The following code you provided doesn't use Y at all, so you can just comment out this line for now.
You need to set the timeout to "None" when you open the serial port:
ser = serial.Serial(**bco_port**, timeout=None, baudrate=115000, xonxoff=False, rtscts=False, dsrdtr=False)
This is a blocking command, so you are waiting until you receive data that has newline (\n or \r\n) at the end: line = ser.readline()
Once you have the data, it will return ASAP.
It's not clear to me exactly where the high-score that you're interested in is stored, but the code below should be what you need to check if the file exists and append to it if desired. I prefer this method to the "try/except".
import os
player = 'bob'
filename = player+'.txt'
if os.path.exists(filename):
append_write = 'a' # append if already exists
else:
append_write = 'w' # make a new file if not
highscore = open(filename,append_write)
highscore.write("Username: " + player + '\n')
highscore.close()
The de-facto unbiased shuffle algorithm is the Fisher-Yates (aka Knuth) Shuffle.
See https://github.com/coolaj86/knuth-shuffle
You can see a great visualization here (and the original post linked to this)
function shuffle(array) {_x000D_
var currentIndex = array.length, temporaryValue, randomIndex;_x000D_
_x000D_
// While there remain elements to shuffle..._x000D_
while (0 !== currentIndex) {_x000D_
_x000D_
// Pick a remaining element..._x000D_
randomIndex = Math.floor(Math.random() * currentIndex);_x000D_
currentIndex -= 1;_x000D_
_x000D_
// And swap it with the current element._x000D_
temporaryValue = array[currentIndex];_x000D_
array[currentIndex] = array[randomIndex];_x000D_
array[randomIndex] = temporaryValue;_x000D_
}_x000D_
_x000D_
return array;_x000D_
}_x000D_
_x000D_
// Used like so_x000D_
var arr = [2, 11, 37, 42];_x000D_
shuffle(arr);_x000D_
console.log(arr);
_x000D_
Some more info about the algorithm used.
var value = fac.GetCachedValue("Auto Print Clinical Warnings")
// 0 = Start at the first character
// 1 = The length of the string to grab
if (value.ToLower().SubString(0, 1) == "y")
{
// Do your stuff.
}
What I do is, I replace
values.
Like this-
df['col'].replace(to_replace=['category_1', 'category_2', 'category_3'], value=[1, 2, 3], inplace=True)
In this way, if the col
column has categorical values, they get replaced by the numerical values.
What you're looking for is a LIMIT clause.
SELECT a.names,
COUNT(b.post_title) AS num
FROM wp_celebnames a
JOIN wp_posts b ON INSTR(b.post_title, a.names) > 0
WHERE b.post_date > DATE_SUB(CURDATE(), INTERVAL 1 DAY)
GROUP BY a.names
ORDER BY num DESC
LIMIT 10
Tried a lot of the solutions without success and then I
JSON explicitly excludes functions because it isn't meant to be a JavaScript-only data structure (despite the JS in the name).
Always get a positive random number.
var nexnumber = Guid.NewGuid().GetHashCode();
if (nexnumber < 0)
{
nexnumber *= -1;
}
If I recall correctly Twig doesn't support ||
and &&
operators, but requires or
and and
to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.
{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}
Expressions
Expressions can be used in {% blocks %} and ${ expressions }.
Operator Description
== Does the left expression equal the right expression?
+ Convert both arguments into a number and add them.
- Convert both arguments into a number and substract them.
* Convert both arguments into a number and multiply them.
/ Convert both arguments into a number and divide them.
% Convert both arguments into a number and calculate the rest of the integer division.
~ Convert both arguments into a string and concatenate them.
or True if the left or the right expression is true.
and True if the left and the right expression is true.
not Negate the expression.
For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:
{% if (foo and bar) or (fizz and (foo + bar == 3)) %}
Maybe you been given sudo access to only some programs/paths? Then there is no way to do what you want. (unless you will hack it somehow)
If it is not the case then maybe you can write bash script:
cat > myscript.sh
#!/bin/sh
ls -hal /root/ > /root/test.out
Press ctrl + d :
chmod a+x myscript.sh
sudo myscript.sh
Hope it help.
You can use git hooks for that. Just create a hook that pushes changed to the other repo after an update.
Of course you might get merge conflicts so you have to figure how to deal with them.
You can remove unwanted menu items in Page_Load, like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Roles.IsUserInRole("Admin"))
{
MenuItemCollection menuItems = mTopMenu.Items;
MenuItem adminItem = new MenuItem();
foreach (MenuItem menuItem in menuItems)
{
if (menuItem.Text == "Roles")
adminItem = menuItem;
}
menuItems.Remove(adminItem);
}
}
I'm sure there's a neater way to find the right item to remove, but this one works. You could also add all the wanted menu items in a Page_Load method, instead of adding them in the markup.
Using display:none is not SEO-friendly. The following way allows the hidden content to be searchable. Adding the transition-delay ensures any links included in the hidden content is clickable.
.collapse > p{
cursor: pointer;
display: block;
}
.collapse:focus{
outline: none;
}
.collapse > div {
height: 0;
width: 0;
overflow: hidden;
transition-delay: 0.3s;
}
.collapse:focus div{
display: block;
height: 100%;
width: 100%;
overflow: auto;
}
<div class="collapse" tabindex="1">
<p>Question 1</p>
<div>
<p>Visit <a href="https://stackoverflow.com/">Stack Overflow</a></p>
</div>
</div>
<div class="collapse" tabindex="2">
<p>Question 2</p>
<div>
<p>Visit <a href="https://stackoverflow.com/">Stack Overflow</a></p>
</div>
</div>
Remember that char
is an integral type, and thus can be given an integer value, as well as a char constant.
char c = 0x2202;//aka 8706 in decimal. \u codepoints are in hex.
String s = String.valueOf(c);
You can float your column divs using float: left; and give them widths.
And to make sure none of your other content gets messed up, you can wrap the floated divs within a parent div and give it some clear float styling.
Hope this helps.
I always considered the .hpp
header to be a sort of portmanteau of .h
and .cpp
files...a header which contains implementation details as well.
Typically when I've seen (and use) .hpp
as an extension, there is no corresponding .cpp
file. As others have said, this isn't a hard and fast rule, just how I tend to use .hpp
files.
Call dplyr
package by installing from cran
in r
library(dplyr)
(file)$(colname)<-sub("-",NA,file$colname)
It will convert all the blank cell in a particular column as NA
If the column contains "-", "", 0 like this change it in code according to the type of blank cell
E.g. if I get a blank cell like "" instead of "-", then use this code:
(file)$(colname)<-sub("", NA, file$colname)
How about adding one extra decimal that is to be rounded and then discarded:
var d = 0.241534545765;
var result1 = d.ToString("0.###%");
var result2 = result1.Remove(result1.Length - 1);
Here is a little utility function that collapses a named or unnamed list of values to a single string for easier printing. It will also print the code line itself. It's from my list examples in R page.
Generate some lists named or unnamed:
# Define Lists
ls_num <- list(1,2,3)
ls_str <- list('1','2','3')
ls_num_str <- list(1,2,'3')
# Named Lists
ar_st_names <- c('e1','e2','e3')
ls_num_str_named <- ls_num_str
names(ls_num_str_named) <- ar_st_names
# Add Element to Named List
ls_num_str_named$e4 <- 'this is added'
Here is the a function that will convert named or unnamed list to string:
ffi_lst2str <- function(ls_list, st_desc, bl_print=TRUE) {
# string desc
if(missing(st_desc)){
st_desc <- deparse(substitute(ls_list))
}
# create string
st_string_from_list = paste0(paste0(st_desc, ':'),
paste(names(ls_list), ls_list, sep="=", collapse=";" ))
if (bl_print){
print(st_string_from_list)
}
}
Testing the function with the lists created prior:
> ffi_lst2str(ls_num)
[1] "ls_num:=1;=2;=3"
> ffi_lst2str(ls_str)
[1] "ls_str:=1;=2;=3"
> ffi_lst2str(ls_num_str)
[1] "ls_num_str:=1;=2;=3"
> ffi_lst2str(ls_num_str_named)
[1] "ls_num_str_named:e1=1;e2=2;e3=3;e4=this is added"
Testing the function with subset of list elements:
> ffi_lst2str(ls_num_str_named[c('e2','e3','e4')])
[1] "ls_num_str_named[c(\"e2\", \"e3\", \"e4\")]:e2=2;e3=3;e4=this is added"
> ffi_lst2str(ls_num[2:3])
[1] "ls_num[2:3]:=2;=3"
> ffi_lst2str(ls_str[2:3])
[1] "ls_str[2:3]:=2;=3"
> ffi_lst2str(ls_num_str[2:4])
[1] "ls_num_str[2:4]:=2;=3;=NULL"
> ffi_lst2str(ls_num_str_named[c('e2','e3','e4')])
[1] "ls_num_str_named[c(\"e2\", \"e3\", \"e4\")]:e2=2;e3=3;e4=this is added"
There could be many reasons for this. A few that come up quickly to my mind:
InitializeComponent()
?This CsvEscape
function is XSLT 1.0 and escapes column values ,
, "
, and newlines like RFC 4180 or Excel. It makes use of the fact that you can recursively call XSLT templates:
EscapeQuotes
replaces all double quotes with 2 double quotes, recursively from the start of the string.CsvEscape
checks if the text contains a comma or double quote, and if so surrounds the whole string with a pair of double quotes and calls EscapeQuotes
for the string.Example usage: xsltproc xmltocsv.xslt file.xml > file.csv
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8"/>
<xsl:template name="EscapeQuotes">
<xsl:param name="value"/>
<xsl:choose>
<xsl:when test="contains($value,'"')">
<xsl:value-of select="substring-before($value,'"')"/>
<xsl:text>""</xsl:text>
<xsl:call-template name="EscapeQuotes">
<xsl:with-param name="value" select="substring-after($value,'"')"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$value"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template name="CsvEscape">
<xsl:param name="value"/>
<xsl:choose>
<xsl:when test="contains($value,',')">
<xsl:text>"</xsl:text>
<xsl:call-template name="EscapeQuotes">
<xsl:with-param name="value" select="$value"/>
</xsl:call-template>
<xsl:text>"</xsl:text>
</xsl:when>
<xsl:when test="contains($value,'
')">
<xsl:text>"</xsl:text>
<xsl:call-template name="EscapeQuotes">
<xsl:with-param name="value" select="$value"/>
</xsl:call-template>
<xsl:text>"</xsl:text>
</xsl:when>
<xsl:when test="contains($value,'"')">
<xsl:text>"</xsl:text>
<xsl:call-template name="EscapeQuotes">
<xsl:with-param name="value" select="$value"/>
</xsl:call-template>
<xsl:text>"</xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$value"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="/">
<xsl:text>project,name,language,owner,state,startDate</xsl:text>
<xsl:text>
</xsl:text>
<xsl:for-each select="projects/project">
<xsl:call-template name="CsvEscape"><xsl:with-param name="value" select="normalize-space(name)"/></xsl:call-template>
<xsl:text>,</xsl:text>
<xsl:call-template name="CsvEscape"><xsl:with-param name="value" select="normalize-space(language)"/></xsl:call-template>
<xsl:text>,</xsl:text>
<xsl:call-template name="CsvEscape"><xsl:with-param name="value" select="normalize-space(owner)"/></xsl:call-template>
<xsl:text>,</xsl:text>
<xsl:call-template name="CsvEscape"><xsl:with-param name="value" select="normalize-space(state)"/></xsl:call-template>
<xsl:text>,</xsl:text>
<xsl:call-template name="CsvEscape"><xsl:with-param name="value" select="normalize-space(startDate)"/></xsl:call-template>
<xsl:text>
</xsl:text>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Shubham's answer explains very well. This answer is addition to it as per to avoid some pitfalls and refactoring to a more readable syntax
Pitfall : There is common misconception in rendering array of objects especially if there is an update or delete action performed on data. Use case would be like deleting an item from table row. Sometimes when row which is expected to be deleted, does not get deleted and instead other row gets deleted.
To avoid this, use key
prop in root element which is looped over in JSX tree of .map()
. Also adding React's Fragment
will avoid adding another element in between of ul
and li
when rendered via calling method.
state = {
userData: [
{ id: '1', name: 'Joe', user_type: 'Developer' },
{ id: '2', name: 'Hill', user_type: 'Designer' }
]
};
deleteUser = id => {
// delete operation to remove item
};
renderItems = () => {
const data = this.state.userData;
const mapRows = data.map((item, index) => (
<Fragment key={item.id}>
<li>
{/* Passing unique value to 'key' prop, eases process for virtual DOM to remove specific element and update HTML tree */}
<span>Name : {item.name}</span>
<span>User Type: {item.user_type}</span>
<button onClick={() => this.deleteUser(item.id)}>
Delete User
</button>
</li>
</Fragment>
));
return mapRows;
};
render() {
return <ul>{this.renderItems()}</ul>;
}
Important : Decision to use which value should we pass to key
prop also matters as common way is to use index
parameter provided by .map()
.
TLDR; But there's a drawback to it and avoid it as much as possible and use any unique id
from data which is being iterated such as item.id
. There's a good article on this - https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318
As @arman-p pointed out MYSQL has no explode(). However, I think the solution presented in much more complicated than it needs to be. To do a quick check when you are given a comma delimited list string (e.g, list of the table keys to look for) you do:
SELECT
table_key, field_1, field_2, field_3
FROM
my_table
WHERE
field_3 = 'my_field_3_value'
AND (comma_list = table_key
OR comma_list LIKE CONCAT(table_key, ',%')
OR comma_list LIKE CONCAT('%,', table_key, ',%')
OR comma_list LIKE CONCAT('%,', table_key))
This assumes that you need to also check field_3 on the table too. If you do not need it, do not add that condition.
You need to use parentheses: myList.insert([1, 2, 3])
. When you leave out the parentheses, python thinks you are trying to access myList.insert
at position 1, 2, 3
, because that's what brackets are used for when they are right next to a variable.
Prevent saving changes that require table re-creation
Five swift clicks
- Tools
- Options
- Designers
- Prevent saving changes that require table re-creation
- OK.
After saving, repeat the proceudure to re-tick the box. This safe-guards against accidental data loss.
Further explanation
By default SQL Server Management Studio prevents the dropping of tables, because when a table is dropped its data contents are lost.*
When altering a column's datatype in the table Design view, when saving the changes the database drops the table internally and then re-creates a new one.
*Your specific circumstances will not pose a consequence since your table is empty. I provide this explanation entirely to improve your understanding of the procedure.
On OS X Synalyze It! lets you display parts of your file in different encodings (all which are supported by the ICU library). Once you know what's the source encoding you can copy the whole file (bytes) via clipboard and insert into a new document where the target encoding (UTF-8 or whatever you like) is selected.
Very helpful when working with UTF-8 or other Unicode representations is UnicodeChecker
EventArgs e
is a parameter called e that contains the event data, see the EventArgs MSDN page for more information.
Object Sender
is a parameter called Sender that contains a reference to the control/object that raised the event.
Event Arg Class: http://msdn.microsoft.com/en-us/library/system.eventargs.aspx
Example:
protected void btn_Click (object sender, EventArgs e){
Button btn = sender as Button;
btn.Text = "clicked!";
}
Edit: When Button is clicked, the btn_Click event handler will be fired. The "object sender" portion will be a reference to the button which was clicked
If you're using ZLib in your project, then you need to find :
#if 1
in zconf.h and replace(uncomment) it with :
#if HAVE_UNISTD_H /* ...the rest of the line
If it isn't ZLib I guess you should find some alternative way to do this. GL.
This allows for a centered content body with min-width for my forms to not collapse funny:
html {
overflow-y: scroll;
height: 100%;
margin: 0px auto;
padding: 0;
}
body {
height: 100%;
margin: 0px auto;
max-width: 960px;
min-width: 750px;
padding: 0;
}
div#footer {
width: 100%;
position: absolute;
bottom: 0;
left: 0;
height: 60px;
}
div#wrapper {
height: auto !important;
min-height: 100%;
height: 100%;
position: relative;
overflow: hidden;
}
div#pageContent {
padding-bottom: 60px;
}
div#header {
width: 100%;
}
And my layout page looks like:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title></title>
</head>
<body>
<div id="wrapper">
<div id="header"></div>
<div id="pageContent"></div>
<div id="footer"></div>
</div>
</body>
</html>
Example here: http://data.nwtresearch.com/
One more note, if you want the full page background like the code you added looks like, remove the height: auto !important;
from the wrapper div: http://jsfiddle.net/mdares/a8VVw/
The following is my preferred way, and will change the cursor everytime a page is about to change i.e. beforeunload
$(window).on('beforeunload', function(){
$('*').css("cursor", "progress");
});
You can ping an address that doesn't exist and specify the desired timeout:
ping 192.0.2.2 -n 1 -w 10000 > nul
And since the address does not exist, it'll wait 10,000 ms (10 seconds) and return.
-w 10000
part specifies the desired timeout in milliseconds.-n 1
part tells ping that it should only try once (normally it'd try 4 times).> nul
part is appended so the ping command doesn't output anything to screen.You can easily make a sleep command yourself by creating a sleep.bat somewhere in your PATH and using the above technique:
rem SLEEP.BAT - sleeps by the supplied number of seconds
@ping 192.0.2.2 -n 1 -w %1000 > nul
NOTE (September 2002): The 192.0.2.x address is reserved as per RFC 3330 so it definitely will not exist in the real world. Quoting from the spec:
192.0.2.0/24 - This block is assigned as "TEST-NET" for use in documentation and example code. It is often used in conjunction with domain names example.com or example.net in vendor and protocol documentation. Addresses within this block should not appear on the public Internet.
In my Case: I have put the correct path for Android and java but still getting the error.
The problem was that I have added the Android platform using sudo command.sudo ionic cordova platform android
.
To solve my problem: First I have removed the platform android by running command
sudo ionic cordova platform rm android
then add the android platform again with out sudoionic cordova platform add android
but i get the error of permissions.
To resolve the error run command
sudo chmod -R 777 {Path-of-your-project}
in my case sudo chmod -R 777 ~/codebase/IonicProject
Then run command
ionic cordova platform add android
or
ionic cordova run android
So, I know this is an old topic, but I'll first say it isn't possible. The closest thing currently is locking the mouse to a single position, and tracking change in its x and y. This concept has been adopted by - it looks like - Chrome and Firefox. It's managed by what's called Mouse Lock, and hitting escape will break it. From my brief read-up, I think the idea is that it locks the mouse to one location, and reports motion events similar to click-and-drag events.
Here's the release documentation:
FireFox: https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API
Chrome: http://www.chromium.org/developers/design-documents/mouse-lock
And here's a pretty neat demonstration: http://media.tojicode.com/q3bsp/
The following worked for me. First I'd make sure the files in the a
directory are source-controlled:
$ cd a
$ git init
$ git add .
$ git commit -m "..."
Then
$ git remote add origin https://URL/TO/REPO
$ git pull origin master --allow-unrelated-histories
$ git push origin master
Tracemalloc module was integrated as a built-in module starting from Python 3.4, and appearently, it's also available for prior versions of Python as a third-party library (haven't tested it though).
This module is able to output the precise files and lines that allocated the most memory. IMHO, this information is infinitly more valuable than the number of allocated instances for each type (which ends up being a lot of tuples 99% of the time, which is a clue, but barely helps in most cases).
I recommend you use tracemalloc in combination with pyrasite. 9 times out of 10, running the top 10 snippet in a pyrasite-shell will give you enough information and hints to to fix the leak within 10 minutes. Yet, if you're still unable to find the leak cause, pyrasite-shell in combination with the other tools mentioned in this thread will probably give you some more hints too. You should also take a look on all the extra helpers provided by pyrasite (such as the memory viewer).
Was facing the same issue, used this one
Console.log(Date.parse("Jun 13, 2018 10:50:39 GMT+1"));
It will return milliseconds to which u can check have +100 timzone intialize British time Hope it helps!!
Update: 19 -11-2019
The below answer is no more relevant to present day.
So for any one looking for answers you should look at the documentation linked below
https://developer.android.com/training/articles/user-data-ids
Old Answer - Not relevant now. You check this blog in the link below
http://android-developers.blogspot.in/2011/03/identifying-app-installations.html
ANDROID_ID
import android.provider.Settings.Secure;
private String android_id = Secure.getString(getContext().getContentResolver(),
Secure.ANDROID_ID);
The above is from the link @ Is there a unique Android device ID?
More specifically, Settings.Secure.ANDROID_ID. This is a 64-bit quantity that is generated and stored when the device first boots. It is reset when the device is wiped.
ANDROID_ID seems a good choice for a unique device identifier. There are downsides: First, it is not 100% reliable on releases of Android prior to 2.2 (“Froyo”). Also, there has been at least one widely-observed bug in a popular handset from a major manufacturer, where every instance has the same ANDROID_ID.
The below solution is not a good one coz the value survives device wipes (“Factory resets”) and thus you could end up making a nasty mistake when one of your customers wipes their device and passes it on to another person.
You get the imei number of the device using the below
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.getDeviceId();
http://developer.android.com/reference/android/telephony/TelephonyManager.html#getDeviceId%28%29
Add this is manifest
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
In my case I removed these two
Android TV Intel x86 Atom System Image
Wear OS Intel x86 Atom System Image
under Android 9 (API 28)
ALTER PROCEDURE LN
(
@Firstname nvarchar(200)
)
AS
BEGIN
UPDATE tbl_Students1
SET Firstname=@Firstname
WHERE Studentid=3
END
exec LN 'Thanvi'
I solve my issue using these commands
git checkout [BRANCH]
git branch master [BRANCH] -f
git checkout master
git push origin master -f
my suggestion: Choose a different version. I had the same problem you have deinstalled v5.6.11, downloaded and installed v5.6.3, works fine for me.
cheers!
As Unwind points out f and g provide different default outputs.
Roughly speaking if you care more about the details of what comes after the decimal point I would do with f and if you want to scale for large numbers go with g. From some dusty memories f is very nice with small values if your printing tables of numbers as everything stays lined up but something like g is needed if you stand a change of your numbers getting large and your layout matters. e is more useful when your numbers tend to be very small or very large but never near ten.
An alternative is to specify the output format so that you get the same number of characters representing your number every time.
Sorry for the woolly answer but it is a subjective out put thing that only gets hard answers if the number of characters generated is important or the precision of the represented value.
Thanks Ravi and other users .... Nevertheless I have got the solution
SELECT @phoneNumber=
CASE
WHEN ISNULL(rdg2.nPhoneNumber ,'0') in ('0','-',NULL)
THEN ISNULL(rdg2.nMobileNumber, '0')
WHEN ISNULL(rdg2.nMobileNumber, '0') in ('0','-',NULL)
THEN '0'
ELSE ISNULL(rdg2.nPhoneNumber ,'0')
END
FROM tblReservation_Details_Guest rdg2
WHERE nReservationID=@nReservationID
Just need to put '0' instead of 0
My solution was to use a short nickname (less than 31 characters) and then write the entire name in cell 0.
No prompt use:
dir /x
Procure o nome reduzido do diretório na linha do "Program Files (x86)"
27/08/2018 15:07 <DIR> PROGRA~2 Program Files (x86)
Coloque a seguinte configuração em php.ini para a opção:
extension_dir="C:\PROGRA~2\path\to\php\ext"
Acredito que isso resolverá seu problema.
Zorro
Did you try cal.getTime()
? This gets the date representation.
You might also want to look at the javadoc.
Using jQuery: $('#gift-close').trigger('click');
Using JavaScript: document.getElementById('gift-close').click();
DataSet myDataset = new DataSet();
DataTable customers = myDataset.Tables.Add("Customers");
customers.Columns.Add("Name");
customers.Columns.Add("Age");
customers.Rows.Add("Chris", "25");
//Get data
DataTable myCustomers = myDataset.Tables["Customers"];
DataRow currentRow = null;
for (int i = 0; i < myCustomers.Rows.Count; i++)
{
currentRow = myCustomers.Rows[i];
listBox1.Items.Add(string.Format("{0} is {1} YEARS OLD", currentRow["Name"], currentRow["Age"]));
}
See with the help of the following example if you can use literals and '$' sign in your case.
function doHomework(subject) {
alert(\`Starting my ${subject} homework.\`);
}
doHomework('maths');
You could go into the designer of the web form and change the "webcontrols" to be "public" instead of "protected" but I'm not sure how safe that is. I prefer to make hidden inputs and have some jQuery set the values into those hidden inputs, then create public properties in the web form's class (code behind), and access the values that way.
Go with right click: Advanced > Get Specific Version. Select "Letest Version" and now, important, mark two checks:
The checks are:
Overwrite writeable files that are not checked
Overwrite all files even if the local version matches the specified version
DateTimeFormatter
has in-built formats that can directly be used to parse a character sequence. It is case Sensitive, Nov will work however nov and
NOV wont work:
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MMM-dd");
try {
LocalDate datetime = LocalDate.parse(oldDate, pattern);
System.out.println(datetime);
} catch (DateTimeParseException e) {
// DateTimeParseException - Text '2019-nov-12' could not be parsed at index 5
// Exception handling message/mechanism/logging as per company standard
}
DateTimeFormatterBuilder
provides custom way to create a formatter. It is Case Insensitive, Nov , nov and NOV will be treated as same.
DateTimeFormatter f = new DateTimeFormatterBuilder().parseCaseInsensitive()
.append(DateTimeFormatter.ofPattern("yyyy-MMM-dd")).toFormatter();
try {
LocalDate datetime = LocalDate.parse(oldDate, f);
System.out.println(datetime); // 2019-11-12
} catch (DateTimeParseException e) {
// Exception handling message/mechanism/logging as per company standard
}
The function example:
func file_is_exists(f string) bool {
_, err := os.Stat(f)
if os.IsNotExist(err) {
return false
}
return err == nil
}
Instead of parsing it manually it's better to use pathinfo function:
$path_parts = pathinfo($value);
$extension = strtolower($path_parts['extension']);
$fileName = $path_parts['filename'];
string[,] myGridData = new string[dataGridView1.Rows.Count,3];
int i = 0;
foreach(DataRow row in dataGridView1.Rows)
{
myGridData[i][0] = row.Cells[0].Value.ToString();
myGridData[i][1] = row.Cells[1].Value.ToString();
myGridData[i][2] = row.Cells[2].Value.ToString();
i++;
}
Hope this helps....
You're calling writer.close();
after you've done writing to it. Once a stream is closed, it can not be written to again. Usually, the way I go about implementing this is by moving the close out of the write to method.
public void writeToFile(){
String file_text= pedStatusText + " " + gatesStatus + " " + DrawBridgeStatusText;
try {
writer.write(file_text);
writer.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And add a method cleanUp
to close the stream.
public void cleanUp() {
writer.close();
}
This means that you have the responsibility to make sure that you're calling cleanUp
when you're done writing to the file. Failure to do this will result in memory leaks and resource locking.
EDIT: You can create a new stream each time you want to write to the file, by moving writer
into the writeToFile()
method..
public void writeToFile() {
FileWriter writer = new FileWriter("status.txt", true);
// ... Write to the file.
writer.close();
}
if you have error in Sqlite built in python you can use Conda to solve this conflict
conda install sqlite
# database Intraction
$SQLServer = "YourServerName" #use Server\Instance for named SQL instances!
$SQLDBName = "YourDBName"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName;
User ID= YourUserID; Password= YourPassword"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = 'StoredProcName'
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
#End :database Intraction
clear
TreeMap
sorts by the key natural ordering. The keys should implement Comparable
or be compatible with a Comparator
(if you passed one instance to constructor). In you case, Float
already implements Comparable
so you don't have to do anything special.
You can call keySet
to retrieve all the keys in ascending order.
" ".repeat(10);
generate(() -> " ").limit(10).collect(joining());
where:
import static java.util.stream.Collectors.joining;
import static java.util.stream.Stream.generate;
In Laravel 5.4, you can use guessClientExtension
I find the solution for listbox items' background to yellow. I tried the following solution to achieve the output.
for (int i = 0; i < lstEquipmentItem.Items.Count; i++)
{
if ((bool)ds.Tables[0].Rows[i]["Valid_Equipment"] == false)
{
lblTKMWarning.Text = "Invalid Equipment & Serial Numbers are highlited.";
lblTKMWarning.ForeColor = System.Drawing.Color.Red;
lstEquipmentItem.Items[i].Attributes.Add("style", "background-color:Yellow");
Count++;
}
}
I changed this:
var htmlText = '<embed width=100% height=100%'
+ ' type="application/pdf"'
+ ' src="data:application/pdf,'
+ escape(pdfText)
+ '"></embed>';
to
var htmlText = '<embed width=100% height=100%'
+ ' type="application/pdf"'
+ ' src="data:application/pdf;base64,'
+ escape(pdfText)
+ '"></embed>';
and it worked for me.
The following cites the C11 standard (final draft).
6.3.1.2: When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.
bool
(mapped by stdbool.h
to the internal name _Bool
for C) itself is an unsigned integer type:
... The type _Bool and the unsigned integer types that correspond to the standard signed integer types are the standard unsigned integer types.
According to 6.2.5p2:
An object declared as type _Bool is large enough to store the values 0 and 1.
AFAIK these definitions are semantically identical to C++ - with the minor difference of the built-in(!) names. bool
for C++ and _Bool
for C.
Note that C does not use the term rvalues as C++ does. However, in C pointers are scalars, so assigning a pointer to a _Bool
behaves as in C++.
In Prepared Statements the user is forced to enter data as parameters . If user enters some vulnerable statements like DROP TABLE or SELECT * FROM USERS then data won't be affected as these would be considered as parameters of the SQL statement
To change the navigation icon you can use:
Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.my_icon);
To change the overflow icon you can use the method:
toolbar.setOverflowIcon(ContextCompat.getDrawable(this, R.drawable.ic_my_menu);
If you would like to change the color of the icons you can use:
with a Material Components Theme (with a MaterialToolbar
for example):
<com.google.android.material.appbar.MaterialToolbar
android:theme="@style/MyThemeOverlay_Toolbar"
...>
<style name="MyThemeOverlay_Toolbar" parent="ThemeOverlay.MaterialComponents.Toolbar.Primary">
<!-- color used by navigation icon and overflow icon -->
<item name="colorOnPrimary">@color/myColor</item>
</style>
With an AppCompat Theme:
<android.support.v7.widget.Toolbar
app:theme="@style/ThemeToolbar" />
<style name="ThemeToolbar" parent="Theme.AppCompat.Light">
<!-- navigation icon color -->
<item name="colorControlNormal">@color/my_color</item>
<!-- color of the menu overflow icon -->
<item name="android:textColorSecondary">@color/my_color</item>
</style>
You can also change the overflow icon overriding in the app theme the actionOverflowButtonStyle
attribute:
With a Material Components Theme:
<style name="AppTheme.Base" parent="Theme.MaterialComponents.DayNight">
<item name="actionOverflowButtonStyle">@style/OverFlow</item>
</style>
<style name="OverFlow" parent="Widget.AppCompat.ActionButton.Overflow">
<item name="srcCompat">@drawable/my_overflow_menu</item>
</style>
With an AppCompat theme:
<style name="AppTheme.Base" parent="Theme.AppCompat.Light">
<item name="actionOverflowButtonStyle">@style/OverFlow</item>
</style>
<style name="OverFlow" parent="Widget.AppCompat.ActionButton.Overflow">
<item name="srcCompat">@drawable/my_overflow_menu</item>
</style>
hr {
border-top:1px dotted #000;
/*Rest of stuff here*/
}
Remove specific index(i removed 16 and 21 from matrix)
import numpy as np
mat = np.arange(12,26)
a = [4,9]
del_map = np.delete(mat, a)
del_map.reshape(3,4)
Output:
array([[12, 13, 14, 15],
[17, 18, 19, 20],
[22, 23, 24, 25]])
I was trying to figure out if it's possible to browse the code of an earlier commit like you can on GitHub and it brought me here. I used the information I found here, and after fiddling around with the urls, I actually found a way to browse code of old commits as well.
When you're browsing your code the URL is something like:
https://bitbucket.org/user/repo/src/
and by adding a commit hash at the end like this:
https://bitbucket.org/user/repo/src/a0328cb
You can browse the code at the point of that commit. I don't understand why there's no dropdown box for choosing a commit directly, the feature is already there. Strange.
rows.RemoveAt(rows.Count - 1);
You can use this methode to check if a view has children or not .
public static boolean hasChildren(ViewGroup viewGroup) {
return viewGroup.getChildCount() > 0;
}
Actually, the entire approach would be cleaner if you only had to use one instance of StringBuffer, instead of creating one in every recursive call... I would go for:
private String getWhoozitYs(){
StringBuffer sb = new StringBuffer();
while (generator.nextBoolean()) {
sb.append("y");
}
return sb.toString();
}
This is the only one right answer on this whole page as people answered about "Visual Studio", not "Visual Studio Code":
To change color theme in "Visual Studio Code", use:
File -> Preferences -> Color Theme -> select any color theme you like
You can also download other custom themes as extensions. To do that, open extensions tab on sidebar and type "theme" into the search field to filter extensions only to themes related ones. Click any you like, click "download" and then "install". After installation and restarting VSC, you can find newly installed themes next to default themes in the same place:
File -> Preferences -> Color Theme -> select newly downloaded color theme
PS - Microsoft made bad naming decision by calling this new editor Visual Studio Code, it's terrible how many wrong links we have in google and stackoverflow. They should rename it to VSCode or something.
You could use the JS confirm function.
<form onSubmit="if(!confirm('Is the form filled out correctly?')){return false;}">
<input type="submit" />
</form>
Add the dots to all values:
[[UIColor colorWithRed:222./255. green:227./255. blue: 229./255. alpha:1] CGColor]) ;
Otherwise, you are dividing float by int.
This is what do you want? DEMO. Try to shrink the browser's window and you'll see that the elements will be ordered.
What I used? Flexible Box Model or Flexbox.
Just add the follow CSS classes to your container element (in this case div#container
):
flex-init-setup
and flex-ppal-setup
.
Where:
Here are the CSS rules:
.flex-init-setup {
display: -webkit-box;
display: -moz-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
}
.flex-ppal-setup {
-webkit-flex-flow: column wrap;
-moz-flex-flow: column wrap;
flex-flow: column wrap;
-webkit-justify-content: center;
-moz-justify-content: center;
justify-content: center;
}
Be good, Leonardo
Your web_window variable must have gone out of scope when you tried to close the window. Add this line into your _openpageview function to test:
setTimeout(function(){web_window.close();},1000);
In html5 you can do using the full expression:
<select required="required">
I don't know why the short expression doesn't work, but try this one. It will solve.
Add this link:
/usr/local/lib/*.so.*
The total is:
g++ -o main.out main.cpp -I /usr/local/include -I /usr/local/include/opencv -I /usr/local/include/opencv2 -L /usr/local/lib /usr/local/lib/*.so /usr/local/lib/*.so.*
While it's true that json
is a built-in module, I also found that on an Ubuntu system with python-minimal
installed, you DO have python
but you can't do import json
. And then I understand that you would try to install the module using pip!
If you have python-minimal
you'll get a version of python with less modules than when you'd typically compile python yourself, and one of the modules you'll be missing is the json
module. The solution is to install an additional package, called libpython2.7-stdlib
, to install all 'default' python libraries.
sudo apt install libpython2.7-stdlib
And then you can do import json
in python and it would work!
Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)
Do it the other way around:
$a = "1,435";
$b = str_replace( ',', '', $a );
if( is_numeric( $b ) ) {
$a = $b;
}
The easiest would be:
$var = intval(preg_replace('/[^\d.]/', '', $var));
or if you need float:
$var = floatval(preg_replace('/[^\d.]/', '', $var));
I'm new, but some of the answers above are insanely complicated, so here's an alternative.
NOTE: As long as 0-9 are contiguous (which they should be according to the standard), this should filter out all other characters but numbers and ' '. Knowing 0-9 should be contiguous and a char is really an int, we can do the below.
EDIT: I didn't notice the poster wanted spaces too, so I altered it...
#include <cstdio>
#include <cstring>
void numfilter(char * buff, const char * string)
{
do
{ // According to standard, 0-9 should be contiguous in system int value.
if ( (*string >= '0' && *string <= '9') || *string == ' ')
*buff++ = *string;
} while ( *++string );
*buff++ = '\0'; // Null terminate
}
int main()
{
const char *string = "(555) 555-5555";
char buff[ strlen(string) + 1 ];
numfilter(buff, string);
printf("%s\n", buff);
return 0;
}
Below is to filter supplied characters.
#include <cstdio>
#include <cstring>
void cfilter(char * buff, const char * string, const char * toks)
{
const char * tmp; // So we can keep toks pointer addr.
do
{
tmp = toks;
*buff++ = *string; // Assume it's correct and place it.
do // I can't think of a faster way.
{
if (*string == *tmp)
{
buff--; // Not correct, pull back and move on.
break;
}
}while (*++tmp);
}while (*++string);
*buff++ = '\0'; // Null terminate
}
int main()
{
char * string = "(555) 555-5555";
char * toks = "()-";
char buff[ strlen(string) + 1 ];
cfilter(buff, string, toks);
printf("%s\n", buff);
return 0;
}
crontab
does not work for me on CentOS x86 6.5. @reboot seems to be not working.
Finally I got this solution:
Edit: /etc/rc.local
sudo vi /etc/rc.local
Add this line to the end of the file. Change USER_NAME
and PATH_TO_PROJECT
to your own. NODE_ENV=production
means the app runs in production mode. You can add more lines if you need to run more than one node.js app.
su - USER_NAME -c "NODE_ENV=production /usr/local/bin/forever start /PATH_TO_PROJECT/app.js"
Don't set NODE_ENV
in a separate line, your app will still run in development mode, because forever does not get NODE_ENV
.
# WRONG!
su - USER_NAME -c "export NODE_ENV=production"
Save and quit vi (press ESC : w q return
). You can try rebooting your server. After your server reboots, your node.js app should run automatically, even if you don't log into any account remotely via ssh.
You'd better set NODE_ENV
environment in your shell. NODE_ENV
will be set automatically when your account USER_NAME
logs in.
echo export NODE_ENV=production >> ~/.bash_profile
So you can run commands like forever stop/start /PATH_TO_PROJECT/app.js
via ssh without setting NODE_ENV
again.
Adding to above answers but offering an alternative quick solution in php and wordpress. For this example I am storing the location field via ACF and looping through the posts to grab that data.
I found that storing the lat / lng in an array and check the value of that array to see if the loop matches, we can then update the value within that array with the amount we want to shift our pips by.
//This is the value to shift the pips by. I found this worked best with markerClusterer
$add_to_latlng = 0.00003;
while ($query->have_posts()) {
$query->the_post();
$meta = get_post_meta(get_the_ID(), "postcode", true); //uses an acf field to store location
$lat = $meta["lat"];
$lng = $meta["lng"];
if(in_array($meta["lat"],$lat_checker)){ //check if this meta matches
//if matches then update the array to a new value (current value + shift value)
// This is using the lng value for a horizontal line of pips, use lat for vertical, or both for a diagonal
if(isset($latlng_storer[$meta["lng"]])){
$latlng_storer[$meta["lng"]] = $latlng_storer[$meta["lng"]] + $add_to_latlng;
$lng = $latlng_storer[$meta["lng"]];
} else {
$latlng_storer[$meta["lng"]] = $meta["lng"];
$lng = $latlng_storer[$meta["lng"]];
}
} else {
$lat_checker[] = $meta["lat"]; //just for simple checking of data
$latlng_storer[$meta["lat"]] = floatval($meta["lat"]);
$latlng_storer[$meta["lng"]] = floatval($meta["lng"]);
}
$entry[] = [
"lat" => $lat,
"lng" => $lng,
//...Add all the other post data here and use this array for the pips
];
} // end query
Once I've grabbed these locations I json encode the $entry variable and use that within my JS.
let locations = <?=json_encode($entry)?>;
I know this is a rather specific situation but I hope this helps someone along the line!
Wrap the sections you want to hide in their own tbody and dynamically show/hide that.
If you want to run your scripts, then
mysql -u root -p < yourscript.sql
Agree with iLoveTux , applying too many things (many colors and backgrounds) nothing worked , but here's what started working, Apply these properties to its css:
-webkit-appearance: none;
-moz-appearance: none;
-o-appearance: none;
appearance:none;
and then css styling started working on checkbox :)
Array push and pop method can be used for sequence of promises. You can also push new promises when you need additional data. This is the code, I will use in React Infinite loader to load sequence of pages.
var promises = [Promise.resolve()];_x000D_
_x000D_
function methodThatReturnsAPromise(page) {_x000D_
return new Promise((resolve, reject) => {_x000D_
setTimeout(() => {_x000D_
console.log(`Resolve-${page}! ${new Date()} `);_x000D_
resolve();_x000D_
}, 1000);_x000D_
});_x000D_
}_x000D_
_x000D_
function pushPromise(page) {_x000D_
promises.push(promises.pop().then(function () {_x000D_
return methodThatReturnsAPromise(page)_x000D_
}));_x000D_
}_x000D_
_x000D_
pushPromise(1);_x000D_
pushPromise(2);_x000D_
pushPromise(3);
_x000D_
I agree with stephenbayer. But since it is a webservice, it is easier for end-user to use just one form of the webmethod, than using multiple versions of the same method. I think in this situation Nullable Types are perfect for optional parameters.
public void Foo(int a, int b, int? c)
{
if(c.HasValue)
{
// do something with a,b and c
}
else
{
// do something with a and b only
}
}
Here is a good example in Python3.
>>> a = input("What is your name?")
What is your name?Peter
>>> b = input("Where are you from?")
Where are you from?DE
>>> print("So you are %s of %s" % (a, b))
So you are Peter of DE
Sometimes type setting:
max_allowed_packet = 16M
in my.ini is not working.
Try to determine the my.ini as follows:
set-variable = max_allowed_packet = 32M
or
set-variable = max_allowed_packet = 1000000000
Then restart the server:
/etc/init.d/mysql restart
The order of items in the PATH matters. If there are multiple entries for various java installations, the first one in your PATH will be used.
I have had similar issues after installing a product, like Oracle, that puts it's JRE at the beginning of the PATH.
Ensure that the JDK you want to be loaded is the first entry in your PATH (or at least that it appears before C:\Program Files\Java\jre6\bin
appears).
Since you're not using JSON as the data type no your AJAX call, I would assume that you can't access the value because the PHP you gave will only ever be true or false. isset
is a function to check if something exists and has a value, not to get access to the value.
Change your PHP to be:
$uid = (isset($_POST['userID'])) ? $_POST['userID'] : 0;
The above line will check to see if the post variable exists. If it does exist it will set $uid
to equal the posted value. If it does not exist then it will set $uid
equal to 0.
Later in your code you can check the value of $uid
and react accordingly
if($uid==0) {
echo 'User ID not found';
}
This will make your code more readable and also follow what I consider to be best practices for handling data in PHP.
imho: Apache HTTP Client
usage example:
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;
import java.io.*;
public class HttpClientTutorial {
private static String url = "http://www.apache.org/";
public static void main(String[] args) {
// Create an instance of HttpClient.
HttpClient client = new HttpClient();
// Create a method instance.
GetMethod method = new GetMethod(url);
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
try {
// Execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
}
// Read the response body.
byte[] responseBody = method.getResponseBody();
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
System.out.println(new String(responseBody));
} catch (HttpException e) {
System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("Fatal transport error: " + e.getMessage());
e.printStackTrace();
} finally {
// Release the connection.
method.releaseConnection();
}
}
}
some highlight features: