NSString * pathv = [[NSBundle mainBundle] pathForResource:@"vfile" ofType:@"mov"];
playerv = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:pathv]];
[self presentMoviePlayerViewControllerAnimated:playerv];
private void f(Button b, final int a[]) {
b.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
a[0] = a[0] * 5;
}
});
}
You can follow this pattern also
<form action="/action_page.php">
E-mail: <input type="email" name="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$">
<input type="submit">
</form>
Ref : In W3Schools
There are a few ways depending on some data rules that you have not included, but here is one way using what you gave.
SELECT
t1.Field1,
t2.Field2
FROM Table1 t1
LEFT JOIN Table1 t2 ON t1.FK = t2.FK AND t2.Field1 IS NULL
Another way:
SELECT
t1.Field1,
(SELECT Field2 FROM Table2 t2 WHERE t2.FK = t1.FK AND Field1 IS NULL) AS Field2
FROM Table1 t1
For me, it was the web app connection string pointing to the wrong database server.
Interfaces are implemented through classes. They are purely abstract classes, if you will.
In PHP when a class implements from an interface, the methods defined in that interface are to be strictly followed. When a class inherits from a parent class, method parameters may be altered. That is not the case for interfaces:
interface ImplementMeStrictly {
public function foo($a, $b);
}
class Obedient implements ImplementMeStrictly {
public function foo($a, $b, $c)
{
}
}
will cause an error, because the interface wasn't implemented as defined. Whereas:
class InheritMeLoosely {
public function foo($a)
{
}
}
class IDoWhateverWithFoo extends InheritMeLoosely {
public function foo()
{
}
}
Is allowed.
Just do that: getTabAt(index of your tab)
ActionBar actionBar = getSupportActionBar();
actionBar.selectTab(actionBar.getTabAt(0));
Scanner scanner = new Scanner(System.in);
String part = scanner.nextLine();
String line = scanner.nextLine();
String temp = "\\b" + part +"|"+ part + "\\b";
Pattern pattern = Pattern.compile(temp.toLowerCase());
Matcher matcher = pattern.matcher(line.toLowerCase());
System.out.println(matcher.find() ? "YES":"NO");
If you need to determine if any of the words of this text start or end with the sequence. you can use this regex \bsubstring|substring\b anythingsubstring substringanything anythingsubstringanything
Well, I figured out the way and thought to share with the people out there who might run into the same problem.
Let me start with the problem I had been facing,
I had been trying to execute a Dynamic Sql Statement that used two temporary tables I declared at the top of my stored procedure, but because that dynamic sql statment created a new scope, I couldn't use the temporary tables.
Solution:
I simply changed them to Global Temporary Variables and they worked.
Find my stored procedure underneath.
CREATE PROCEDURE RAFCustom_Room_GetRelatedProducts
-- Add the parameters for the stored procedure here
@PRODUCT_SKU nvarchar(15) = Null
AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON;
IF OBJECT_ID('tempdb..##RelPro', 'U') IS NOT NULL
BEGIN
DROP TABLE ##RelPro
END
Create Table ##RelPro
(
RowID int identity(1,1),
ID int,
Item_Name nvarchar(max),
SKU nvarchar(max),
Vendor nvarchar(max),
Product_Img_180 nvarchar(max),
rpGroup int,
Assoc_Item_1 nvarchar(max),
Assoc_Item_2 nvarchar(max),
Assoc_Item_3 nvarchar(max),
Assoc_Item_4 nvarchar(max),
Assoc_Item_5 nvarchar(max),
Assoc_Item_6 nvarchar(max),
Assoc_Item_7 nvarchar(max),
Assoc_Item_8 nvarchar(max),
Assoc_Item_9 nvarchar(max),
Assoc_Item_10 nvarchar(max)
);
Begin
Insert ##RelPro(ID, Item_Name, SKU, Vendor, Product_Img_180, rpGroup)
Select distinct zp.ProductID, zp.Name, zp.SKU,
(Select m.Name From ZNodeManufacturer m(nolock) Where m.ManufacturerID = zp.ManufacturerID),
'http://s0001.server.com/is/sw11/DG/' +
(Select m.Custom1 From ZNodeManufacturer m(nolock) Where m.ManufacturerID = zp.ManufacturerID) +
'_' + zp.SKU + '_3?$SC_3243$', ep.RoomID
From Product zp(nolock) Inner Join RF_ExtendedProduct ep(nolock) On ep.ProductID = zp.ProductID
Where zp.ActiveInd = 1 And SUBSTRING(zp.SKU, 1, 2) <> 'GC' AND zp.Name <> 'PLATINUM' AND zp.SKU = (Case When @PRODUCT_SKU Is Not Null Then @PRODUCT_SKU Else zp.SKU End)
End
declare @curr_row int = 0,
@tot_rows int= 0,
@sku nvarchar(15) = null;
IF OBJECT_ID('tempdb..##TSku', 'U') IS NOT NULL
BEGIN
DROP TABLE ##TSku
END
Create Table ##TSku (tid int identity(1,1), relsku nvarchar(15));
Select @curr_row = (Select MIN(RowId) From ##RelPro);
Select @tot_rows = (Select MAX(RowId) From ##RelPro);
while @curr_row <= @tot_rows
Begin
select @sku = SKU from ##RelPro where RowID = @curr_row;
truncate table ##TSku;
Insert ##TSku(relsku)
Select distinct top(10) tzp.SKU From Product tzp(nolock) INNER JOIN
[INTRANET].raf_FocusAssociatedItem assoc(nolock) ON assoc.associatedItemID = tzp.SKU
Where (assoc.isActive=1) And (tzp.ActiveInd = 1) AND (assoc.productID = @sku)
declare @curr_row1 int = (Select Min(tid) From ##TSku),
@tot_rows1 int = (Select Max(tid) From ##TSku);
If(@tot_rows1 <> 0)
Begin
While @curr_row1 <= @tot_rows1
Begin
declare @col_name nvarchar(15) = null,
@sqlstat nvarchar(500) = null;
set @col_name = 'Assoc_Item_' + Convert(nvarchar(2), @curr_row1);
set @sqlstat = 'update ##RelPro set ' + @col_name + ' = (Select relsku From ##TSku Where tid = ' + Convert(nvarchar(2), @curr_row1) + ') Where RowID = ' + Convert(nvarchar(2), @curr_row);
Exec(@sqlstat);
set @curr_row1 = @curr_row1 + 1;
End
End
set @curr_row = @curr_row + 1;
End
Select * From ##RelPro;
END GO
You could create a class that extends Application
class and then declare your variable as a field of that class and providing getter method for it.
public class MyApplication extends Application {
private String str = "My String";
synchronized public String getMyString {
return str;
}
}
And then to access that variable in your Activity, use this:
MyApplication application = (MyApplication) getApplication();
String myVar = application.getMyString();
Remove below code
s.send("Hello server!")
because your sending s.send("Hello server!")
to server, so your output file is somewhat more in size.
For percent increase and decrease, using 2 different methods:
const a = 541
const b = 394
// Percent increase
console.log(
`Increase (from ${b} to ${a}) => `,
(((a/b)-1) * 100).toFixed(2) + "%",
)
// Percent decrease
console.log(
`Decrease (from ${a} to ${b}) => `,
(((b/a)-1) * 100).toFixed(2) + "%",
)
// Alternatives, using .toLocaleString()
console.log(
`Increase (from ${b} to ${a}) => `,
((a/b)-1).toLocaleString('fullwide', {maximumFractionDigits:2, style:'percent'}),
)
console.log(
`Decrease (from ${a} to ${b}) => `,
((b/a)-1).toLocaleString('fullwide', {maximumFractionDigits:2, style:'percent'}),
)
_x000D_
Firebug seems to allow you to do that.
Prefix the call with Module2 (ex. Module2.IDLE
). I'm assuming since you asked this that you have IDLE defined multiple times in the project, otherwise this shouldn't be necessary.
I like the solution using the -eq
test, because it's basically a one-liner.
My own solution was to use parameter expansion to throw away all the numerals and see if there was anything left. (I'm still using 3.0, haven't used [[
or expr
before, but glad to meet them.)
if [ "${INPUT_STRING//[0-9]}" = "" ]; then
# yes, natural number
else
# no, has non-numeral chars
fi
I have solve this problem by just deleting .gradle folder within my application project..
Delete folder .gradle from your project no need to delete main .gradle folder which is located at C:\Users\<username>
public static int hex2decimal(String s) {
String digits = "0123456789ABCDEF";
s = s.toUpperCase();
int val = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
int d = digits.indexOf(c);
val = 16*val + d;
}
return val;
}
That's the most efficient and elegant solution I have found over the internet. Some of the others solutions provided here didn't always work for me.
I can see that the Debugger is retrieving 4 og:image
tags from your URL.
The first image is the largest and therefore takes longest to load. Try shrink that first image down or change the order to show a smaller image first.
I had the same problem:
curl -v -H "Content-Type: application/json" -X PUT -d '{"name":"json","surname":"gson","married":true,"age":32,"salary":123,"hasCar":true,"childs":["serkan","volkan","aybars"]}' XXXXXX/ponyo/UserModel/json
* About to connect() to localhost port 8081 (#0)
* Trying ::1...
* Connection refused
* Trying 127.0.0.1...
* connected
* Connected to localhost (127.0.0.1) port 8081 (#0)
> PUT /ponyo/UserModel/json HTTP/1.1
> User-Agent: curl/7.28.1
> Host: localhost:8081
> Accept: */*
> Content-Type: application/json
> Content-Length: 121
>
* upload completely sent off: 121 out of 121 bytes
< HTTP/1.1 415 Unsupported Media Type
< Content-Type: text/html; charset=iso-8859-1
< Date: Wed, 09 Apr 2014 13:55:43 GMT
< Content-Length: 0
<
* Connection #0 to host localhost left intact
* Closing connection #0
I resolved it by adding the dependency to pom.xml as follows. Please try it.
<dependency>
<groupId>com.owlike</groupId>
<artifactId>genson</artifactId>
<version>0.98</version>
</dependency>
nanoScrollerJS is simply to use. I always use them...
Browser compatibility:
Mobile browsers support:
Code example from the Documentation,
<div id="about" class="nano">
<div class="nano-content"> ... content here ... </div>
</div>
if (!json[0]) alert("JSON empty");
Google's libs-for-android has a nice libraries for managing image and file cache.
Give the Exec Maven plugin a try
Same here. I had this error when running an import command from terminal without activating python3 shell through manage.py in a django project (yes, I am a newbie yet). As one must expect, activating shell allowed the command to be interpreted correctly.
./manage.py shell
and only then
>>> from django.contrib.sites.models import Site
What would be handy would be to apply the Camera position to a new plot. So I plot, then move the plot around with the mouse changing the distance. Then try to replicate the view including the distance on another plot. I find that axx.ax.get_axes() gets me an object with the old .azim and .elev.
IN PYTHON...
axx=ax1.get_axes()
azm=axx.azim
ele=axx.elev
dst=axx.dist # ALWAYS GIVES 10
#dst=ax1.axes.dist # ALWAYS GIVES 10
#dst=ax1.dist # ALWAYS GIVES 10
Later 3d graph...
ax2.view_init(elev=ele, azim=azm) #Works!
ax2.dist=dst # works but always 10 from axx
EDIT 1... OK, Camera position is the wrong way of thinking concerning the .dist value. It rides on top of everything as a kind of hackey scalar multiplier for the whole graph.
This works for the magnification/zoom of the view:
xlm=ax1.get_xlim3d() #These are two tupples
ylm=ax1.get_ylim3d() #we use them in the next
zlm=ax1.get_zlim3d() #graph to reproduce the magnification from mousing
axx=ax1.get_axes()
azm=axx.azim
ele=axx.elev
Later Graph...
ax2.view_init(elev=ele, azim=azm) #Reproduce view
ax2.set_xlim3d(xlm[0],xlm[1]) #Reproduce magnification
ax2.set_ylim3d(ylm[0],ylm[1]) #...
ax2.set_zlim3d(zlm[0],zlm[1]) #...
As an update...with ECMAScript 6 you can FINALLY set default values in function parameter declarations like so:
function f (x, y = 7, z = 42) {
return x + y + z
}
f(1) === 50
As referenced by - http://es6-features.org/#DefaultParameterValues
JAR Files
A JAR (short for Java Archive) file permits the combination of several files into a single one. Files with the '.jar'; extension are utilized by software developers to distribute Java classes and various metadata. These also hold libraries and resource files, as well as accessory files (such as property files).
Users can extract and create JAR files with Java Development Kit's (JDK) '.jar' command. ZIP tools may also be used.
JAR files have optional manifest files. Entries within the manifest file prescribe the JAR file's use. A 'main' class specification for a file class denotes the file as a detached or ‘stand-alone' program.
WAR Files
A WAR (or Web Application archive) files can comprise XML (extensible Markup Language) files, Java classes, as well as Java Server pages for purposes of Internet application. It is also employed to mark libraries and Web pages which make up a Web application. Files with the ‘.war' extension contain the Web app for use with server or JSP (Java Server Page) containers. It has JSP, HTML (Hypertext Markup Language), JavaScript, and various files for creating the aforementioned Web apps.
A WAR file is structured as such to allow for special directories and files. It may also have a digital signature (much like that of a JAR file) to show the veracity of the code.
EAR Files
An EAR (Enterprise Archive) file merges JAR and WAR files into a single archive. These files with the ‘.ear' extension have a directory for metadata. The modules are packaged into on archive for smooth and simultaneous operation of the different modules within an app server.
The EAR file also has deployment descriptors (which are XML files) which effectively dictate the deployment of the different modules.
Xcode 10 Swift 4.2
To show Push Notification when your app is in the foreground -
Step 1 : add delegate UNUserNotificationCenterDelegate in AppDelegate class.
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
Step 2 : Set the UNUserNotificationCenter delegate
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.delegate = self
Step 3 : This step will allow your app to show Push Notification even when your app is in foreground
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound])
}
Step 4 : This step is optional. Check if your app is in the foreground and if it is in foreground then show Local PushNotification.
func application(_ application: UIApplication,didReceiveRemoteNotification userInfo: [AnyHashable: Any],fetchCompletionHandler completionHandler:@escaping (UIBackgroundFetchResult) -> Void) {
let state : UIApplicationState = application.applicationState
if (state == .inactive || state == .background) {
// go to screen relevant to Notification content
print("background")
} else {
// App is in UIApplicationStateActive (running in foreground)
print("foreground")
showLocalNotification()
}
}
Local Notification function -
fileprivate func showLocalNotification() {
//creating the notification content
let content = UNMutableNotificationContent()
//adding title, subtitle, body and badge
content.title = "App Update"
//content.subtitle = "local notification"
content.body = "New version of app update is available."
//content.badge = 1
content.sound = UNNotificationSound.default()
//getting the notification trigger
//it will be called after 5 seconds
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
//getting the notification request
let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content, trigger: trigger)
//adding the notification to notification center
notificationCenter.add(request, withCompletionHandler: nil)
}
UPDATE:
onActivityCreated()
is deprecated from API Level 28.
onCreate():
The onCreate()
method in a Fragment
is called after the Activity
's onAttachFragment()
but before that Fragment
's onCreateView()
.
In this method, you can assign variables, get Intent
extras, and anything else that doesn't involve the View hierarchy (i.e. non-graphical initialisations). This is because this method can be called when the Activity
's onCreate()
is not finished, and so trying to access the View hierarchy here may result in a crash.
onCreateView():
After the onCreate()
is called (in the Fragment
), the Fragment
's onCreateView()
is called. You can assign your View
variables and do any graphical initialisations. You are expected to return a View
from this method, and this is the main UI view, but if your Fragment
does not use any layouts or graphics, you can return null
(happens by default if you don't override).
onActivityCreated():
As the name states, this is called after the Activity
's onCreate()
has completed. It is called after onCreateView()
, and is mainly used for final initialisations (for example, modifying UI elements). This is deprecated from API level 28.
To sum up...
... they are all called in the Fragment
but are called at different times.
The onCreate()
is called first, for doing any non-graphical initialisations. Next, you can assign and declare any View
variables you want to use in onCreateView()
. Afterwards, use onActivityCreated()
to do any final initialisations you want to do once everything has completed.
If you want to view the official Android documentation, it can be found here:
There are also some slightly different, but less developed questions/answers here on Stack Overflow:
// ToFloat32 converts a int num to a float32 num
func ToFloat32(in int) float32 {
return float32(in)
}
// ToFloat64 converts a int num to a float64 num
func ToFloat64(in int) float64 {
return float64(in)
}
<script>
function check(){
return false;
}
</script>
<form name="form1" method="post" onsubmit="return check();" action="target">
<input type="text" />
<input type="submit" value="enviar" />
</form>
A much simpler alternative is to get the information from the connection object itself. For example:
IDbConnection connection = new SqlConnection(connectionString);
var dbName = connection.Database;
Similarly you can get the server name as well from the connection object.
DbConnection connection = new SqlConnection(connectionString);
var server = connection.DataSource;
Note to under
connetionString =@"server=XXX;Trusted_Connection=yes;database=yourDB;";
Note: XXX = . OR .\SQLEXPRESS OR .\MSSQLSERVER OR (local)\SQLEXPRESS OR (localdb)\v11.0 &...
you can replace 'server' with 'Data Source'
too you can replace 'database' with 'Initial Catalog'
Sample:
connetionString =@"server=.\SQLEXPRESS;Trusted_Connection=yes;Initial Catalog=books;";
@Html.Partial("NameOfPartialView")
You can use jquery's load function here.
$("#your_element_id").load("file_name.html");
If you need more info, here is the link.
Both node.js and MongoChef force me to convert to ObjectId. This is what I use to grab a list of users from the DB and fetch a few properties. Mind the type conversion on line 8.
// this will complement the list with userName and userPhotoUrl based on userId field in each item
augmentUserInfo = function(list, callback){
var userIds = [];
var users = []; // shortcut to find them faster afterwards
for (l in list) { // first build the search array
var o = list[l];
if (o.userId) {
userIds.push( new mongoose.Types.ObjectId( o.userId ) ); // for the Mongo query
users[o.userId] = o; // to find the user quickly afterwards
}
}
db.collection("users").find( {_id: {$in: userIds}} ).each(function(err, user) {
if (err) callback( err, list);
else {
if (user && user._id) {
users[user._id].userName = user.fName;
users[user._id].userPhotoUrl = user.userPhotoUrl;
} else { // end of list
callback( null, list );
}
}
});
}
Look for GSpread.NET. It's also an OpenSource project and it doesn't require Office installed. You can work with Google Spreadsheets by using API from Microsoft Excel. If you want to re-use the old code to get access to Google Spreadsheets, GSpread.NET is the best way. You need to add a few row:
Set objExcel = CreateObject("GSpreadCOM.Application")
// Name - User name, any you like
// ClientIdAndSecret - `client_id|client_secret` format
// ScriptId - Google Apps script ID
app.MailLogon(Name, ClientIdAndSecret, ScriptId);
Further code remain unchanged.
Solution as dictionary comprehension with enumerate:
dict = {item : values[index] for index, item in enumerate(keys)}
Solution as for loop with enumerate:
dict = {}
for index, item in enumerate(keys):
dict[item] = values[index]
Angular Concepts
imports
makes the exported declarations of other modules available in the current moduledeclarations
are to make directives (including components and pipes) from the current module available to other directives in the current module. Selectors of directives, components or pipes are only matched against the HTML if they are declared or imported.providers
are to make services and values known to DI (dependency injection). They are added to the root scope and they are injected to other services or directives that have them as dependency.A special case for providers
are lazy loaded modules that get their own child injector. providers
of a lazy loaded module are only provided to this lazy loaded module by default (not the whole application as it is with other modules).
For more details about modules see also https://angular.io/docs/ts/latest/guide/ngmodule.html
exports
makes the components, directives, and pipes available in modules that add this module to imports
. exports
can also be used to re-export modules such as CommonModule and FormsModule, which is often done in shared modules.
entryComponents
registers components for offline compilation so that they can be used with ViewContainerRef.createComponent()
. Components used in router configurations are added implicitly.
TypeScript (ES2015) imports
import ... from 'foo/bar'
(which may resolve to an index.ts
) are for TypeScript imports. You need these whenever you use an identifier in a typescript file that is declared in another typescript file.
Angular's @NgModule()
imports
and TypeScript import
are entirely different concepts.
See also jDriven - TypeScript and ES6 import syntax
Most of them are actually plain ECMAScript 2015 (ES6) module syntax that TypeScript uses as well.
well I think the problem solved this below code works:
function sum() {
var result=0;
var txtFirstNumberValue = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
if (txtFirstNumberValue !="" && txtSecondNumberValue ==""){
result = parseInt(txtFirstNumberValue);
}else if(txtFirstNumberValue == "" && txtSecondNumberValue != ""){
result= parseInt(txtSecondNumberValue);
}else if (txtSecondNumberValue != "" && txtFirstNumberValue != ""){
result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
}
if (!isNaN(result)) {
document.getElementById('txt3').value = result;
}
}
You need to use get_serving_url
from the Images API. As that page explains, you need to call create_gs_key()
first to get the key to pass to the Images API.
In Java I used encoding "IBM850" to write the file. That solved the problem.
Here you have a way to do it in one line for two arrays:
const startArray = [1,2,3,4]
const newArray = [4,5,6]
const result = [...startArray, ...newArray.filter(a => !startArray.includes(a))]
console.log(result);
//Result: [1,2,3,4,5,6]
If you mean File.separator
and File.pathSeparator
then:
File.pathSeparator
is used to separate individual file paths in a list of file paths. Consider on windows, the PATH environment variable. You use a ;
to separate the file paths so on Windows File.pathSeparator
would be ;
.
File.separator
is either /
or \
that is used to split up the path to a specific file. For example on Windows it is \
or C:\Documents\Test
in your xml file you should set layout_width and layout_height from wrap_content to match_parent. it's fixed for me.
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
This only inserts if the item to be inserted is not already present.
Works the same as:
if not exists (...) insert ...
in T-SQL
insert into destination (DESTINATIONABBREV)
select 'xyz' from dual
left outer join destination d on d.destinationabbrev = 'xyz'
where d.destinationid is null;
may not be pretty, but it's handy :)
and in jquery:
$('element').attr('some attribute','some attributes value')
i.e
$('a').attr('href','http://www.stackoverflow.com/')
For anyone who wants to sort the variable in third layer:
<select ng-option="friend.pet.name for friend in friends"></select>
you can do it like this
<select ng-option="friend.pet.name for friend in friends | orderBy: 'pet.name'"></select>
lodash will work, tested even for angular 5, http://jsfiddle.net/L5qrfx3x/
var remoteJSON = {"allowExternalMembers": "false", "whoCanJoin":
"CAN_REQUEST_TO_JOIN"};
var localJSON = {"whoCanJoin": "CAN_REQUEST_TO_JOIN",
"allowExternalMembers": "false"};
if(_.isEqual(remoteJSON, localJSON)){
//TODO
}
it works, for installation in angular, follow this
You open the file in text mode.
More specifically:
ifile = open('sample.csv', "rt", encoding=<theencodingofthefile>)
Good guesses for encoding is "ascii" and "utf8". You can also leave the encoding off, and it will use the system default encoding, which tends to be UTF8, but may be something else.
I'll share a straight-forward way that worked for me.
[" ".join([str(elem) for elem in tup]) for tup in df.columns.tolist()]
#df = df.reset_index() if needed
Well, if you gonna present alternate optimization, we can also go for an iterator:
static IEnumerable<DateTime> RandomDay()
{
DateTime start = new DateTime(1995, 1, 1);
Random gen = new Random();
int range = ((TimeSpan)(DateTime.Today - start)).Days;
while (true)
yield return start.AddDays(gen.Next(range));
}
you could use it like this:
int i=0;
foreach(DateTime dt in RandomDay())
{
Console.WriteLine(dt);
if (++i == 10)
break;
}
a = [32, 37, 28, 30, 37, 25, 27, 24, 35,
55, 23, 31, 55, 21, 40, 18, 50,
35, 41, 49, 37, 19, 40, 41, 31]
import pandas as pd
pd.Series(a).idxmax()
9
That is how I usually do it.
To turn on full error reporting, add this to your script:
error_reporting(E_ALL);
This causes even minimal warnings to show up. And, just in case:
ini_set('display_errors', '1');
Will force the display of errors. This should be turned off in production servers, but not when you're developing.
You can use
CharSequence[] cs = String[] {"String to CharSequence"};
For deployment better to set up classpath exactly and keep environment clear. Or at *.bat (the same for linux, but with correct variables symbols):
CLASSPATH="c:\lib;d:\temp\test.jar;<long classpath>"
CLASSPATH=%CLASSPATH%;"<another_logical_droup_of_classpath"
java -cp %CLASSPATH% com.test.MainCLass
Or at command line or *.bat (for *.sh too) if classpath id not very long:
java -cp "c:\lib;d:\temp\test.jar;<short classpath>"
Use the stringi package:
require(stringi)
group<-data.frame(c("12357e", "12575e", "197e18", "e18947"))
stri_replace_all(group[,1], "", fixed="e")
[1] "12357" "12575" "19718" "18947"
def chunk(lst):
out = []
for x in xrange(2, len(lst) + 1):
if not len(lst) % x:
factor = len(lst) / x
break
while lst:
out.append([lst.pop(0) for x in xrange(factor)])
return out
I found the Chrome option to be OK but there are quite a few steps to go through to get to the font files. Once you're there, the downloading is super easy. I usually use the dev tools in Safari as there are fewer steps. Just go to the page you want, click on "Show page source" or "show page resources" in the Developer menu (both work for this) and the page resources are listed in folders on the left hand side. Click the font folder and the fonts are listed. Right click and save file. If you are downloading a lot of font files from one site it may be quicker to work your way through Chrome's pathway as the "open in tab" does download the fonts quicker. If you're taking one or two fonts from a lot of different sites, Safari will be quicker overall.
As dd copies data with the conv=noerror,sync option, any errors it encounters will result in the remainder of the block being replaced with zero-bytes. Larger block sizes will copy more quickly, but each time an error is encountered the remainder of the block is ignored.
You can use a Dictionary to keep track of the keys and values.
For instance...
dictOfStuff = {} ##Make a Dictionary
x = "Buffalo" ##OR it can equal the input of something, up to you.
dictOfStuff[x] = 4 ##Get the dict spot that has the same key ("name") as what X is equal to. In this case "Buffalo". and set it to 4. Or you can set it to what ever you like
print(dictOfStuff[x]) ##print out the value of the spot in the dict that same key ("name") as the dictionary.
A dictionary is very similar to a real life dictionary. You have a word and you have a definition. You can look up the word and get the definition. So in this case, you have the word "Buffalo" and it's definition is 4. It can work with any other word and definition. Just make sure you put them into the dictionary first.
Most simple way,
use json.dumps
but if its datetime will require to parse datetime into json serializer.
here is mine,
import MySQLdb, re, json
from datetime import date, datetime
def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, (datetime, date)):
return obj.isoformat()
raise TypeError ("Type %s not serializable" % type(obj))
conn = MySQLdb.connect(instance)
curr = conn.cursor()
curr.execute("SELECT * FROM `assets`")
data = curr.fetchall()
print json.dumps(data, default=json_serial)
it will return json dump
one more simple method without json dumps, here get header and use zip to map with each finally made it as json but this is not change datetime into json serializer...
data_json = []
header = [i[0] for i in curr.description]
data = curr.fetchall()
for i in data:
data_json.append(dict(zip(header, i)))
print data_json
here is my soln to define the remote and local port and then write out to a file the received data, put this all in a class of your choice with the correct imports
static UdpClient sendClient = new UdpClient();
static int localPort = 49999;
static int remotePort = 49000;
static IPEndPoint localEP = new IPEndPoint(IPAddress.Any, localPort);
static IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), remotePort);
static string logPath = System.AppDomain.CurrentDomain.BaseDirectory + "/recvd.txt";
static System.IO.StreamWriter fw = new System.IO.StreamWriter(logPath, true);
private static void initStuff()
{
fw.AutoFlush = true;
sendClient.ExclusiveAddressUse = false;
sendClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
sendClient.Client.Bind(localEP);
sendClient.BeginReceive(DataReceived, sendClient);
}
private static void DataReceived(IAsyncResult ar)
{
UdpClient c = (UdpClient)ar.AsyncState;
IPEndPoint receivedIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
Byte[] receivedBytes = c.EndReceive(ar, ref receivedIpEndPoint);
fw.WriteLine(DateTime.Now.ToString("HH:mm:ss.ff tt") + " (" + receivedBytes.Length + " bytes)");
c.BeginReceive(DataReceived, ar.AsyncState);
}
static void Main(string[] args)
{
initStuff();
byte[] emptyByte = {};
sendClient.Send(emptyByte, emptyByte.Length, remoteEP);
}
If you're not wanting to save changes set savechanges to false
Sub CloseBook2()
ActiveWorkbook.Close savechanges:=False
End Sub
for more examples, http://support.microsoft.com/kb/213428 and i believe in the past I've just used
ActiveWorkbook.Close False
PhpStorm supports all the features of WebStorm but some are not bundled so you might need to install the corresponding plugin for some framework via Settings > Plugins > Install JetBrains Plugin.
The shortest way is: @RequestMapping({"", "/", "welcome"})
Although you can also do:
@RequestMapping(value={"", "/", "welcome"})
@RequestMapping(path={"", "/", "welcome"})
The number in parentheses in a type declaration is display width, which is unrelated to the range of values that can be stored in a data type. Just because you can declare Int(20)
does not mean you can store values up to 10^20 in it:
[...] This optional display width may be used by applications to display integer values having a width less than the width specified for the column by left-padding them with spaces. ...
The display width does not constrain the range of values that can be stored in the column, nor the number of digits that are displayed for values having a width exceeding that specified for the column. For example, a column specified as SMALLINT(3) has the usual SMALLINT range of -32768 to 32767, and values outside the range allowed by three characters are displayed using more than three characters.
For a list of the maximum and minimum values that can be stored in each MySQL datatype, see here.
You can convert yourInt
to bytes by using a ByteBuffer
like this:
return ByteBuffer.allocate(4).putInt(yourInt).array();
Beware that you might have to think about the byte order when doing so.
Here's a function that will dynamically create a CSS rule in all major browsers. createCssRule
takes a selector (e.g. "p.purpleText"), a rule (e.g. "color: purple;") and optionally a Document
(the current document is used by default):
var addRule;
if (typeof document.styleSheets != "undefined" && document.styleSheets) {
addRule = function(selector, rule) {
var styleSheets = document.styleSheets, styleSheet;
if (styleSheets && styleSheets.length) {
styleSheet = styleSheets[styleSheets.length - 1];
if (styleSheet.addRule) {
styleSheet.addRule(selector, rule)
} else if (typeof styleSheet.cssText == "string") {
styleSheet.cssText = selector + " {" + rule + "}";
} else if (styleSheet.insertRule && styleSheet.cssRules) {
styleSheet.insertRule(selector + " {" + rule + "}", styleSheet.cssRules.length);
}
}
}
} else {
addRule = function(selector, rule, el, doc) {
el.appendChild(doc.createTextNode(selector + " {" + rule + "}"));
};
}
function createCssRule(selector, rule, doc) {
doc = doc || document;
var head = doc.getElementsByTagName("head")[0];
if (head && addRule) {
var styleEl = doc.createElement("style");
styleEl.type = "text/css";
styleEl.media = "screen";
head.appendChild(styleEl);
addRule(selector, rule, styleEl, doc);
styleEl = null;
}
};
createCssRule("body", "background-color: purple;");
Ok, I've been working on this for a few hours, and I've developed what I believe to be the most pythonic solution yet. The following code snippets are python3 but shouldn't be too horribly painful to backport if you need.
The first thing we're gonna do is start with a mixin that makes your db models act kinda like dict
s:
from sqlalchemy.inspection import inspect
class ModelMixin:
"""Provide dict-like interface to db.Model subclasses."""
def __getitem__(self, key):
"""Expose object attributes like dict values."""
return getattr(self, key)
def keys(self):
"""Identify what db columns we have."""
return inspect(self).attrs.keys()
Now we're going to define our model, inheriting the mixin:
class MyModel(db.Model, ModelMixin):
id = db.Column(db.Integer, primary_key=True)
foo = db.Column(...)
bar = db.Column(...)
# etc ...
That's all it takes to be able to pass an instance of MyModel()
to dict()
and get a real live dict
instance out of it, which gets us quite a long way towards making jsonify()
understand it. Next, we need to extend JSONEncoder
to get us the rest of the way:
from flask.json import JSONEncoder
from contextlib import suppress
class MyJSONEncoder(JSONEncoder):
def default(self, obj):
# Optional: convert datetime objects to ISO format
with suppress(AttributeError):
return obj.isoformat()
return dict(obj)
app.json_encoder = MyJSONEncoder
Bonus points: if your model contains computed fields (that is, you want your JSON output to contain fields that aren't actually stored in the database), that's easy too. Just define your computed fields as @property
s, and extend the keys()
method like so:
class MyModel(db.Model, ModelMixin):
id = db.Column(db.Integer, primary_key=True)
foo = db.Column(...)
bar = db.Column(...)
@property
def computed_field(self):
return 'this value did not come from the db'
def keys(self):
return super().keys() + ['computed_field']
Now it's trivial to jsonify:
@app.route('/whatever', methods=['GET'])
def whatever():
return jsonify(dict(results=MyModel.query.all()))
One of the libraries that I use for Font Awesome is this:
https://github.com/Bearded-Hen/Android-Bootstrap
Specifically,
https://github.com/Bearded-Hen/Android-Bootstrap/wiki/Font-Awesome-Text
The documentation is easy to understand.
First, add the needed dependencies in the build.gradle:
dependencies {
compile 'com.beardedhen:androidbootstrap:1.2.3'
}
Secondly, you can add this in your XML:
<com.beardedhen.androidbootstrap.FontAwesomeText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
fontawesometext:fa_icon="fa-github"
android:layout_margin="10dp"
android:textSize="32sp"
/>
but make sure you add this in your root layout if you want to use above code example:
xmlns:fontawesometext="http://schemas.android.com/apk/res-auto"
You need to use the TO_DATE
function.
SELECT TO_DATE('01/01/2004', 'MM/DD/YYYY') FROM DUAL;
There's also a package called bit
that is specifically designed for fast boolean operations. It's especially useful if you have large vectors or need to do many boolean operations.
z <- sample(c(TRUE, FALSE), 1e8, rep = TRUE)
system.time({
sum(z) # 0.170s
})
system.time({
bit::sum.bit(z) # 0.021s, ~10x improvement in speed
})
The default ip of Mysql in instance EC2
Ubuntu is 127.0.0.1
if you want to change it is just to follow the answers that have already been given here.
If you use Wordpress you can just use the wordpress build in function with the video id provided wp_get_attachment_metadata($videoID):
wp_get_attachment_metadata($videoID);
helped me a lot. thats why i'm posting it, although its just for wordpress users.
You can't use IF like that. You can do what you want with AND and OR:
SELECT t.first_name,
t.last_name,
t.employid,
t.status
FROM employeetable t
WHERE ((status_flag = STATUS_ACTIVE AND t.status = 'A')
OR (status_flag = STATUS_INACTIVE AND t.status = 'T')
OR (source_flag = SOURCE_FUNCTION AND t.business_unit = 'production')
OR (source_flag = SOURCE_USER AND t.business_unit = 'users'))
AND t.first_name LIKE firstname
AND t.last_name LIKE lastname
AND t.employid LIKE employeeid;
No, it sets all members/elements that haven't been explicitly set to their default-initialisation value, which is zero for numeric types.
The solution that worked for me is here in PHP
:
$android = stripos($_SERVER['HTTP_USER_AGENT'], "android");
$iphone = stripos($_SERVER['HTTP_USER_AGENT'], "iphone");
$ipad = stripos($_SERVER['HTTP_USER_AGENT'], "ipad");
$whatsappNumber = '1234597891';
$whatsappLink = '';
if($android !== false || $ipad !== false || $iphone !== false) {//For mobile
$whatsappLink = '<a href="https://api.whatsapp.com/send?phone='.$whatsappNumber.'">'.$whatsappNumber.'</a>';
} else {//For desktop
$whatsappLink = '<a href="https://web.whatsapp.com/send?phone='.$whatsappNumber.'">'.$whatsappNumber.'</a>';
}
As of jQuery 1.4.1, the hover event works with live()
. It basically just binds to the mouseenter and mouseleave events, which you can do with versions prior to 1.4.1 just as well:
$("table tr")
.mouseenter(function() {
// Hover starts
})
.mouseleave(function() {
// Hover ends
});
This requires two binds but works just as well.
We are doing the same thing. To support only TLS 1.2 and no SSL protocols, you can do this:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
SecurityProtocolType.Tls is only TLS 1.0, not all TLS versions.
As a side: If you want to check that your site does not allow SSL connections, you can do so here (I don't think this will be affected by the above setting, we had to edit the registry to force IIS to use TLS for incoming connections): https://www.ssllabs.com/ssltest/index.html
To disable SSL 2.0 and 3.0 in IIS, see this page: https://www.sslshopper.com/article-how-to-disable-ssl-2.0-in-iis-7.html
i believe the reason it is not working in your example is that you have imported datetime
like so :
from datetime import datetime
this leads to the error you see
In [30]: isinstance(x, datetime.date)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/<ipython-input-30-9a298ea6fce5> in <module>()
----> 1 isinstance(x, datetime.date)
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types
if you simply import like so :
import datetime
the code will run as shown in all of the other answers
In [31]: import datetime
In [32]: isinstance(x, datetime.date)
Out[32]: True
In [33]:
I've encountered string, which had mixings of English, Russian and some other alphabets, which caused exception. I need only Russian and English, and this currently works for me:
ec1 = Encoding::Converter.new "UTF-8","Windows-1251",:invalid=>:replace,:undef=>:replace,:replace=>""
ec2 = Encoding::Converter.new "Windows-1251","UTF-8",:invalid=>:replace,:undef=>:replace,:replace=>""
t = ec2.convert ec1.convert t
I also get the same error in an ASP.NET application when I saved some unicode data (Hindi) in the Web.config file and saved it with "Unicode" encoding.
It fixed the error for me when I saved the Web.config file with "UTF-8" encoding.
The basic principle of centering a page is to have a body CSS and main_container CSS. It should look something like this:
body {
margin: 0;
padding: 0;
text-align: center;
}
#main_container {
margin: 0 auto;
text-align: left;
}
The formula above didn't work for me, but I used this without any issue. Pass your current location to the function, and loop through an array of markers to find the closest:
function find_closest_marker( lat1, lon1 ) {
var pi = Math.PI;
var R = 6371; //equatorial radius
var distances = [];
var closest = -1;
for( i=0;i<markers.length; i++ ) {
var lat2 = markers[i].position.lat();
var lon2 = markers[i].position.lng();
var chLat = lat2-lat1;
var chLon = lon2-lon1;
var dLat = chLat*(pi/180);
var dLon = chLon*(pi/180);
var rLat1 = lat1*(pi/180);
var rLat2 = lat2*(pi/180);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(rLat1) * Math.cos(rLat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
distances[i] = d;
if ( closest == -1 || d < distances[closest] ) {
closest = i;
}
}
// (debug) The closest marker is:
console.log(markers[closest]);
}
Another way (worked for 2015) is open "Install/remove programs" (Apps & features), find Visual Studio, select Modify. In opened window, press Modify, check
Languages -> Visual C++ -> Common tools for Visual C++
Windows and web development -> Tools for universal windows apps -> Tools (1.4.1)
and Windows 10 SDK ([version])
Windows and web development -> Tools for universal windows apps -> Windows 10 SDK ([version])
and install. Then right click on solution -> Re-target and it will compile
The first approach to take is to modify your web.config using the <location>
configuration tag, and <allow users="?"/>
to allow anonymous or <allow users="*"/>
for all:
<configuration>
<location path="Path/To/Public/Folder">
<system.web>
<authorization>
<allow users="?"/>
</authorization>
</system.web>
</location>
</configuration>
If that approach doesn't work then you can take the following approach which requires making a small modification to the IIS applicationHost.config.
First, change the anonymousAuthentication section's overrideModeDefault from "Deny" to "Allow" in C:\Windows\System32\inetsrv\config\applicationHost.config:
<section name="anonymousAuthentication" overrideModeDefault="Allow" />
overrideMode
is a security feature of IIS. If override is disallowed at the system level in applicationHost.config then there is nothing you can do in web.config to enable it. If you don't have this level of access on your target system you have to take up that discussion with your hosting provider or system administrator.
Second, after setting overrideModeDefault="Allow"
then you can put the following in your web.config:
<location path="Path/To/Public/Folder">
<system.webServer>
<security>
<authentication>
<anonymousAuthentication enabled="true" />
</authentication>
</security>
</system.webServer>
</location>
class String
def black
return "\e[30m#{self}\e[0m"
end
def red
return "\e[31m#{self}\e[0m"
end
def light_green
return "\e[32m#{self}\e[0m"
end
def purple
return "\e[35m#{self}\e[0m"
end
def blue_dark
return "\e[34m#{self}\e[0m"
end
def blue_light
return "\e[36m#{self}\e[0m"
end
def white
return "\e[37m#{self}\e[0m"
end
def randColor
array_color = [
"\e[30m#{self}\e[0m",
"\e[31m#{self}\e[0m",
"\e[32m#{self}\e[0m",
"\e[35m#{self}\e[0m",
"\e[34m#{self}\e[0m",
"\e[36m#{self}\e[0m",
"\e[37m#{self}\e[0m" ]
return array_color[rand(0..array_color.size)]
end
end
puts "black".black
puts "red".red
puts "light_green".light_green
puts "purple".purple
puts "dark blue".blue_dark
puts "light blue".blue_light
puts "white".white
puts "random color".randColor
Here is the full HTML that I use to center by button in Bootsrap form after closing form-group:
<div class="form-row text-center">
<div class="col-12">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
int rgb = ((r&0x0ff)<<16)|((g&0x0ff)<<8)|(b&0x0ff);
If you know that your r, g, and b values are never > 255 or < 0 you don't need the &0x0ff
Additionaly
int red = (rgb>>16)&0x0ff;
int green=(rgb>>8) &0x0ff;
int blue= (rgb) &0x0ff;
No need for multipling.
Simply use the third parameter for selected value in mvc4
@Html.DropDownList("CountryList", new SelectList(ViewBag.Countries, "Value", "Text","974"))
Here "974" is selected Value Specified
In my result selected country is now qatar.in C# as below`
foreach (CountryModel item in CountryModel.GetCountryList())
{
if (item.CountryPhoneCode.Trim() != "974")
{
countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode });
}
else {
countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode,Selected=true });
}
}
Import package modules at runtime (Python recipe)
http://code.activestate.com/recipes/223972/
###################
## #
## classloader.py #
## #
###################
import sys, types
def _get_mod(modulePath):
try:
aMod = sys.modules[modulePath]
if not isinstance(aMod, types.ModuleType):
raise KeyError
except KeyError:
# The last [''] is very important!
aMod = __import__(modulePath, globals(), locals(), [''])
sys.modules[modulePath] = aMod
return aMod
def _get_func(fullFuncName):
"""Retrieve a function object from a full dotted-package name."""
# Parse out the path, module, and function
lastDot = fullFuncName.rfind(u".")
funcName = fullFuncName[lastDot + 1:]
modPath = fullFuncName[:lastDot]
aMod = _get_mod(modPath)
aFunc = getattr(aMod, funcName)
# Assert that the function is a *callable* attribute.
assert callable(aFunc), u"%s is not callable." % fullFuncName
# Return a reference to the function itself,
# not the results of the function.
return aFunc
def _get_class(fullClassName, parentClass=None):
"""Load a module and retrieve a class (NOT an instance).
If the parentClass is supplied, className must be of parentClass
or a subclass of parentClass (or None is returned).
"""
aClass = _get_func(fullClassName)
# Assert that the class is a subclass of parentClass.
if parentClass is not None:
if not issubclass(aClass, parentClass):
raise TypeError(u"%s is not a subclass of %s" %
(fullClassName, parentClass))
# Return a reference to the class itself, not an instantiated object.
return aClass
######################
## Usage ##
######################
class StorageManager: pass
class StorageManagerMySQL(StorageManager): pass
def storage_object(aFullClassName, allOptions={}):
aStoreClass = _get_class(aFullClassName, StorageManager)
return aStoreClass(allOptions)
Java 8 introduces the Instant.ofEpochSecond
utility method for creating an Instant
from a Unix timestamp, this can then be converted into a ZonedDateTime
and finally formatted, e.g.:
final DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
final long unixTime = 1372339860;
final String formattedDtm = Instant.ofEpochSecond(unixTime)
.atZone(ZoneId.of("GMT-4"))
.format(formatter);
System.out.println(formattedDtm); // => '2013-06-27 09:31:00'
I thought this might be useful for people who are using Java 8.
This is not the way to do it. You should use delegates.
I'll assume we have two view controllers, ViewController1 and ViewController2, and this check thing is in the first one and when its state changes, you want to do something in ViewController2. To achieve that in the proper way, you should do the below:
Add a new file to your project (Objective-C Protocol) menu File ? New. Now name it ViewController1Delegate or whatever you want and write these between the @interface and @end directives:
@optional
- (void)checkStateDidChange:(BOOL)checked;
Now go to ViewController2.h and add:
#import "ViewController1Delegate.h"
Then change its definition to:
@interface ViewController2: UIViewController<ViewController1Delegate>
Now go to ViewController2.m and inside the implementation add:
- (void)checkStateDidChange:(BOOL)checked {
if (checked) {
// Do whatever you want here
NSLog(@"Checked");
}
else {
// Also do whatever you want here
NSLog(@"Not checked");
}
}
Now go to ViewController1.h and add the following property:
@property (weak, nonatomic) id<ViewController1Delegate> delegate;
Now if you are creating ViewController1 inside ViewController2 after some event, then you should do it this way using NIB files:
ViewController1* controller = [[NSBundle mainBundle] loadNibNamed:@"ViewController1" owner:self options:nil][0];
controller.delegate = self;
[self presentViewController:controller animated:YES completion:nil];
Now you are all set. Whenever you detect the event of check changed in ViewController1, all you have to do is the below:
[delegate checkStateDidChange:checked]; // You pass here YES or NO based on the check state of your control
You only need to do
pg_ctl register
then execute servcies.msc
enable the "PostgresSQL" and set to auto
then, your postgresql will run like the "server".
May be with:
SELECT count(*) FROM `table`
where
created_at>='2011-03-17 06:42:10' and created_at<='2011-03-17 07:42:50';
or use between
:
SELECT count(*) FROM `table`
where
created_at between '2011-03-17 06:42:10' and '2011-03-17 07:42:50';
You can change the datetime as per your need. May be use curdate()
or now()
to get the desired dates.
ActiveRecord#where will return an ActiveRecord::Relation object (which will never be nil). Try using .empty? on the relation to test if it will return any records.
xampp\phpMyAdmin/config.inc
Find-
$cfg['Servers'][$i]['auth_type'] = 'config'
and change the 'config' to 'http' and that will allow you to type the user name and password when you go to your phpMyAdmin page using your browser.
The FragmentManger's function add and replace can be described as these 1. add means it will add the fragment in the fragment back stack and it will show at given frame you are providing like
getFragmentManager.beginTransaction.add(R.id.contentframe,Fragment1.newInstance(),null)
2.replace means that you are replacing the fragment with another fragment at the given frame
getFragmentManager.beginTransaction.replace(R.id.contentframe,Fragment1.newInstance(),null)
The Main utility between the two is that when you are back stacking the replace will refresh the fragment but add will not refresh previous fragment.
It's simple and follow the small Steps to proceed:
$cd project and execute $git init --bare
Let's say this project.git folder is present at your ip with address inside home_folder/workspace/project.git
, forex- ec2 - /home/ubuntu/workspace/project.git
Now in your local machine, $cd
into the project folder which you want to push to git execute the below commands:
git init .
git remote add origin [email protected]:/home/ubuntu/workspace/project.git
git add .
git commit -m "Initial commit"
Below is an optional command but found it has been suggested as i was working to setup the same thing
git config --global remote.origin.receivepack "git receive-pack"
git pull origin master
git push origin master
This should work fine and will push the local code to the remote git repository.
To check the remote fetch url, cd project_folder/.git
and cat config
, this will give the remote url being used for pull and push operations.
You can also use an alternative way, after creating the project.git
folder on git, clone the project and copy the entire content into that folder. Commit the changes and it should be the same way. While cloning make sure you have access or the key being is the secret key for the remote server being used for deployment.
I was having the same "Class [class name] not found" error message, but it wasn't a namespace issue. All my namespaces were set up correctly. I even tried composer dump-autoload
and it didn't help me.
Surprisingly (to me) I then did composer dump-autoload -o
which according to Composer's help, "optimizes PSR0 and PSR4 packages to be loaded with classmaps too, good for production." Somehow doing it that way got composer to behave and include the class correctly in the autoload_classmap.php file.
One Line Answer:
Monitor: controls only ONE thread at a time can execute in the monitor. (need to acquire lock to execute the single thread)
Semaphore: a lock that protects a shared resource. (need to acquire the lock to access resource)
If, like me, you want to make a function pack or something that people can download then it's very simple. Just write your function in a python file and save it as the name you want IN YOUR PYTHON DIRECTORY. Now, in your script where you want to use this, you type:
from FILE NAME import FUNCTION NAME
Note - the parts in capital letters are where you type the file name and function name.
Now you just use your function however it was meant to be.
Example:
FUNCTION SCRIPT - saved at C:\Python27 as function_choose.py
def choose(a):
from random import randint
b = randint(0, len(a) - 1)
c = a[b]
return(c)
SCRIPT USING FUNCTION - saved wherever
from function_choose import choose
list_a = ["dog", "cat", "chicken"]
print(choose(list_a))
OUTPUT WILL BE DOG, CAT, OR CHICKEN
Hoped this helped, now you can create function packs for download!
--------------------------------This is for Python 2.7-------------------------------------
The dollar sign is treated just like a normal letter or underscore (_
). It has no special significance to the interpreter.
Unlike many similar languages, identifiers (such as functional and variable names) in Javascript can contain not only letters, numbers and underscores, but can also contain dollar signs. They are even allowed to start with a dollar sign, or consist only of a dollar sign and nothing else.
Thus, $
is a valid function or variable name in Javascript.
Why would you want a dollar sign in an identifier?
The syntax doesn't really enforce any particular usage of the dollar sign in an identifier, so it's up to you how you wish to use it. In the past, it has often been recommended to start an identifier with a dollar sign only in generated code - that is, code created not by hand but by a code generator.
In your example, however, this doesn't appear to be the case. It looks like someone just put a dollar sign at the start for fun - perhaps they were a PHP programmer who did it out of habit, or something. In PHP, all variable names must have a dollar sign in front of them.
There is another common meaning for a dollar sign in an interpreter nowadays: the jQuery object, whose name only consists of a single dollar sign ($
). This is a convention borrowed from earlier Javascript frameworks like Prototype, and if jQuery is used with other such frameworks, there will be a name clash because they will both use the name $
(jQuery can be configured to use a different name for its global object). There is nothing special in Javascript that allows jQuery to use the single dollar sign as its object name; as mentioned above, it's simply just another valid identifier name.
useHistory
hook:If you have React >= 16.8
and functional components you can use the useHistory
hook from react-router.
import React from 'react';
import { useHistory } from 'react-router-dom';
const YourComponent = () => {
const history = useHistory();
const handleClick = () => {
history.push("/path/to/push");
}
return (
<div>
<button onClick={handleClick} type="button" />
</div>
);
}
export default YourComponent;
withRouter
HOC:As @ambar mentioned in the comments, React-router has changed their code base since their V4. Here are the documentations - official, withRouter
import React, { Component } from 'react';
import { withRouter } from "react-router-dom";
class YourComponent extends Component {
handleClick = () => {
this.props.history.push("path/to/push");
}
render() {
return (
<div>
<button onClick={this.handleClick} type="button">
</div>
);
};
}
export default withRouter(YourComponent);
browserHistory
You can achieve this functionality using react-router BrowserHistory
. Code below:
import React, { Component } from 'react';
import { browserHistory } from 'react-router';
export default class YourComponent extends Component {
handleClick = () => {
browserHistory.push('/login');
};
render() {
return (
<div>
<button onClick={this.handleClick} type="button">
</div>
);
};
}
connected-react-router
If you have connected your component with redux, and have configured connected-react-router all you have to do is
this.props.history.push("/new/url");
ie, you don't need withRouter
HOC to inject history
to the component props.
// reducers.js
import { combineReducers } from 'redux';
import { connectRouter } from 'connected-react-router';
export default (history) => combineReducers({
router: connectRouter(history),
... // rest of your reducers
});
// configureStore.js
import { createBrowserHistory } from 'history';
import { applyMiddleware, compose, createStore } from 'redux';
import { routerMiddleware } from 'connected-react-router';
import createRootReducer from './reducers';
...
export const history = createBrowserHistory();
export default function configureStore(preloadedState) {
const store = createStore(
createRootReducer(history), // root reducer with router state
preloadedState,
compose(
applyMiddleware(
routerMiddleware(history), // for dispatching history actions
// ... other middlewares ...
),
),
);
return store;
}
// set up other redux requirements like for eg. in index.js
import { Provider } from 'react-redux';
import { Route, Switch } from 'react-router';
import { ConnectedRouter } from 'connected-react-router';
import configureStore, { history } from './configureStore';
...
const store = configureStore(/* provide initial state if any */)
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<> { /* your usual react-router v4/v5 routing */ }
<Switch>
<Route exact path="/yourPath" component={YourComponent} />
</Switch>
</>
</ConnectedRouter>
</Provider>,
document.getElementById('root')
);
// YourComponent.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
...
class YourComponent extends Component {
handleClick = () => {
this.props.history.push("path/to/push");
}
render() {
return (
<div>
<button onClick={this.handleClick} type="button">
</div>
);
}
};
}
export default connect(mapStateToProps = {}, mapDispatchToProps = {})(YourComponent);
This should be equivalent to your current code, only a lot faster:
output <- matrix(unlist(z), ncol = 10, byrow = TRUE)
I had same problem. In my case MongoDB server wasn't running.
Try to open this in your web browser:
http://localhost:28017
If you can't, this means that you have to start MongoDB server.
Run mongod
in another terminal tab.
Then in your main tab run mongo
which is is the shell that connects to your MongoDB server.
If you need exact your example, you should add format to ToString()
string test = DateTime.ParseExact(DateTime.Now.ToString("dd.MM.yyyy"), "dd.MM.yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
But it's better to use straight formatting:
string test = DateTime.Now.ToString("yyyy-MM-dd")
Without VBA...
If you can use a helper column, you can use the MATCH
function to test if a value in one column exists in another column (or in another column on another worksheet). It will return an Error if there is no match
To simply identify duplicates, use a helper column
Assume data in Sheet1, Column A, and another list in Sheet2, Column A. In your helper column, row 1, place the following formula:
=If(IsError(Match(A1, 'Sheet2'!A:A,False)),"","Duplicate")
Drag/copy this forumla down, and it should identify the duplicates.
To highlight cells, use conditional formatting:
With some tinkering, you can use this MATCH
function in a Conditional Formatting rule which would highlight duplicate values. I would probably do this instead of using a helper column, although the helper column is a great way to "see" results before you make the conditional formatting rule.
Something like:
=NOT(ISERROR(MATCH(A1, 'Sheet2'!A:A,FALSE)))
For Excel 2007 and prior, you cannot use conditional formatting rules that reference other worksheets. In this case, use the helper column and set your formatting rule in column A like:
=B1="Duplicate"
This screenshot is from the 2010 UI, but the same rule should work in 2007/2003 Excel.
Okay, so this question is old... but I wanted to do something similar and I found a solution that works for me. Maybe it might help someone else.
I have a List<QuestionType>
that I fill a drop down with. I want to put that selection into the QuestionType
property on the Question
object that I'm creating in the form. I'm using Knockout.js
for the select binding. This sets the self.QuestionType
knockout observable property to a QuestionType
object when the user selects one.
<select class="form-control form-control-sm"
data-bind="options: QuestionTypes, optionsText: 'QuestionTypeText', value: QuestionType, optionsCaption: 'Choose...'">
</select>
I have a hidden field that will hold this object:
@Html.Hidden("NewQuestion.QuestionTypeJson", Model.NewQuestion.QuestionTypeJson)
In the subscription for the observable, I set the hidden field to a JSON.stringify
-ed version of the object.
self.QuestionType.subscribe(function(newValue) {
if (newValue !== null && newValue !== undefined) {
document.getElementById('NewQuestion_QuestionTypeJson').value = JSON.stringify(newValue);
}
});
In the Question
object, I have a field called QuestionTypeJson
that is filled when the user selects a question type. I use this field to get the QuestionType
in the Question
object like this:
public string QuestionTypeJson { get; set; }
private QuestionType _questionType = new QuestionType();
public QuestionType QuestionType
{
get => string.IsNullOrEmpty(QuestionTypeJson) ? _questionType : JsonConvert.DeserializeObject<QuestionType>(QuestionTypeJson);
set => _questionType = value;
}
So if the QuestionTypeJson
field contains something, it will deserialize that and use it for QuestionType
, otherwise it'll just use what is in the backing field.
I have essentially 'passed' a JavaScript object to my model without using Razor
or an Ajax
call. You can probably do something similar to this without using Knockout.js
, but that's what I'm using so...
This answer should be helpful if you don't want to use any other modules besides datetime
.
datetime.utcfromtimestamp(timestamp)
returns a naive datetime
object (not an aware one). Aware ones are timezone aware, and naive are not. You want an aware one if you want to convert between timezones (e.g. between UTC and local time).
If you aren't the one instantiating the date to start with, but you can still create a naive datetime
object in UTC time, you might want to try this Python 3.x code to convert it:
import datetime
d=datetime.datetime.strptime("2011-01-21 02:37:21", "%Y-%m-%d %H:%M:%S") #Get your naive datetime object
d=d.replace(tzinfo=datetime.timezone.utc) #Convert it to an aware datetime object in UTC time.
d=d.astimezone() #Convert it to your local timezone (still aware)
print(d.strftime("%d %b %Y (%I:%M:%S:%f %p) %Z")) #Print it with a directive of choice
Be careful not to mistakenly assume that if your timezone is currently MDT that daylight savings doesn't work with the above code since it prints MST. You'll note that if you change the month to August, it'll print MDT.
Another easy way to get an aware datetime
object (also in Python 3.x) is to create it with a timezone specified to start with. Here's an example, using UTC:
import datetime, sys
aware_utc_dt_obj=datetime.datetime.now(datetime.timezone.utc) #create an aware datetime object
dt_obj_local=aware_utc_dt_obj.astimezone() #convert it to local time
#The following section is just code for a directive I made that I liked.
if sys.platform=="win32":
directive="%#d %b %Y (%#I:%M:%S:%f %p) %Z"
else:
directive="%-d %b %Y (%-I:%M:%S:%f %p) %Z"
print(dt_obj_local.strftime(directive))
If you use Python 2.x, you'll probably have to subclass datetime.tzinfo
and use that to help you create an aware datetime
object, since datetime.timezone
doesn't exist in Python 2.x.
This is where the documentation is:
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
The numeric ("N") format specifier converts a number to a string of the form "-d,ddd,ddd.ddd…", where "-" indicates a negative number symbol if required, "d" indicates a digit (0-9) ...
And this is where they talk about the default (2):
// Displays a negative value with the default number of decimal digits (2).
Int64 myInt = -1234;
Console.WriteLine( myInt.ToString( "N", nfi ) );
This query will give you the exact output for current running jobs. This will also shows the duration of running job in minutes.
WITH
CTE_Sysession (AgentStartDate)
AS
(
SELECT MAX(AGENT_START_DATE) AS AgentStartDate FROM MSDB.DBO.SYSSESSIONS
)
SELECT sjob.name AS JobName
,CASE
WHEN SJOB.enabled = 1 THEN 'Enabled'
WHEN sjob.enabled = 0 THEN 'Disabled'
END AS JobEnabled
,sjob.description AS JobDescription
,CASE
WHEN ACT.start_execution_date IS NOT NULL AND ACT.stop_execution_date IS NULL THEN 'Running'
WHEN ACT.start_execution_date IS NOT NULL AND ACT.stop_execution_date IS NOT NULL AND HIST.run_status = 1 THEN 'Stopped'
WHEN HIST.run_status = 0 THEN 'Failed'
WHEN HIST.run_status = 3 THEN 'Canceled'
END AS JobActivity
,DATEDIFF(MINUTE,act.start_execution_date, GETDATE()) DurationMin
,hist.run_date AS JobRunDate
,run_DURATION/10000 AS Hours
,(run_DURATION%10000)/100 AS Minutes
,(run_DURATION%10000)%100 AS Seconds
,hist.run_time AS JobRunTime
,hist.run_duration AS JobRunDuration
,'tulsql11\dba' AS JobServer
,act.start_execution_date AS JobStartDate
,act.last_executed_step_id AS JobLastExecutedStep
,act.last_executed_step_date AS JobExecutedStepDate
,act.stop_execution_date AS JobStopDate
,act.next_scheduled_run_date AS JobNextRunDate
,sjob.date_created AS JobCreated
,sjob.date_modified AS JobModified
FROM MSDB.DBO.syssessions AS SYS1
INNER JOIN CTE_Sysession AS SYS2 ON SYS2.AgentStartDate = SYS1.agent_start_date
JOIN msdb.dbo.sysjobactivity act ON act.session_id = SYS1.session_id
JOIN msdb.dbo.sysjobs sjob ON sjob.job_id = act.job_id
LEFT JOIN msdb.dbo.sysjobhistory hist ON hist.job_id = act.job_id AND hist.instance_id = act.job_history_id
WHERE ACT.start_execution_date IS NOT NULL AND ACT.stop_execution_date IS NULL
ORDER BY ACT.start_execution_date DESC
try this: (you missed the single quotes)
var floorplanSettings = '@Html.Raw(Json.Encode(Model.FloorPlanSettings))';
In my case the window was also missing and "View -> ToolWindows -> Logcat (Alt + 6)" did not even exist. Pressing ALT+6 also had absolutely no effect whatsoever.
I fixed it this way:
After closing the terminal the Logcat window appeared in the tab list and the menu entry appeared in the "View -> ToolWindows" category.
just need putting the datatype of the column in the datasource
dataSource: {
data: empModel.Value,
pageSize: 10,
schema: {
model: {
fields: {
DOJ: { type: "date" }
}
}
}
}
and then your statement column:
columns: [
{
field: "Name",
width: 90,
title: "Name"
},
{
field: "DOJ",
width: 90,
title: "DOJ",
type: "date",
format:"{0:MM-dd-yyyy}"
}
]
new[,2]
is a factor, not a numeric vector. Transform it first
new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5
set myPATH="C:\Users\DEB\Downloads\10.1.1.0.4"
cd %myPATH%
The single quotes do not indicate a string, they make it starts: 'C:\
instead of C:\
so
%name%
is the usual syntax for expanding a variable, the !name!
syntax needs to be enabled using the command setlocal ENABLEDELAYEDEXPANSION
first, or by running the command prompt with CMD /V:ON
.
Don't use PATH as your name, it is a system name that contains all the locations of executable programs. If you overwrite it, random bits of your script will stop working. If you intend to change it, you need to do set PATH=%PATH%;C:\Users\DEB\Downloads\10.1.1.0.4
to keep the current PATH content, and add something to the end.
Expanding on the previous answers even further, you can add an id
attribute to your footnote's link:
Bla bla <sup id="a1">[1](#f1)</sup>
Then from within the footnote, link back to it.
<b id="f1">1</b> Footnote content here. [?](#a1)
This will add a little ?
at the end of your footnote's content, which takes your readers back to the line containing the footnote's link.
The below code useful to display in the map insertion order.
<ul>
<li *ngFor="let recipient of map | keyvalue: asIsOrder">
{{recipient.key}} --> {{recipient.value}}
</li>
</ul>
.ts file add the below code.
asIsOrder(a, b) {
return 1;
}
grid.newpage() ## If you're using ggplot
grid() ## If you just want to activate the device.
See: Python Sound ("Bell")
This helped me when i wanted to do the same.
All credits go to gbc
Have you tried :
import sys
sys.stdout.write('\a')
sys.stdout.flush()
That works for me here on Mac OS 10.5
Actually, I think your original attempt works also with a little modification:
print('\a')
(You just need the single quotes around the character sequence).
This is straight from Bjarne Stroustrup's page:
If you so choose, you can still shoot yourself in the foot by inheriting constructors in a derived class in which you define new member variables needing initialization:
struct B1 {
B1(int) { }
};
struct D1 : B1 {
using B1::B1; // implicitly declares D1(int)
int x;
};
void test()
{
D1 d(6); // Oops: d.x is not initialized
D1 e; // error: D1 has no default constructor
}
Opens a new window with the url you supplied :)
<button class="button" onClick="window.open('http://www.example.com');">
<span class="icon">Open</span>
</button>
hope that helps :)
In VB.NET
Dim directory as String = My.Application.Info.DirectoryPath
In C#
string directory = AppDomain.CurrentDomain.BaseDirectory;
Bootstrap v3.3.6 isn't compatible with the jQuery 3.0. This will be fixed in the upcoming Bootstrap version 3.3.7. Here's the issue currently open on GitHub. https://github.com/twbs/bootstrap/issues/16834
For MS SQL CEILING(your number) will round it up. FLOOR(your number) will round it down
How about:
df <- data.frame(matrix(ncol = 3, nrow = 0))
x <- c("name", "age", "gender")
colnames(df) <- x
To do all these operations in one-liner:
setNames(data.frame(matrix(ncol = 3, nrow = 0)), c("name", "age", "gender"))
#[1] name age gender
#<0 rows> (or 0-length row.names)
Or
data.frame(matrix(ncol=3,nrow=0, dimnames=list(NULL, c("name", "age", "gender"))))
I don't think desc
takes an na.rm
argument... I'm actually surprised it doesn't throw an error when you give it one. If you just want to remove NA
s, use na.omit
(base) or tidyr::drop_na
:
outcome.df %>%
na.omit() %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
library(tidyr)
outcome.df %>%
drop_na() %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
If you only want to remove NA
s from the HeartAttackDeath column, filter with is.na
, or use tidyr::drop_na
:
outcome.df %>%
filter(!is.na(HeartAttackDeath)) %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
outcome.df %>%
drop_na(HeartAttackDeath) %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
As pointed out at the dupe, complete.cases
can also be used, but it's a bit trickier to put in a chain because it takes a data frame as an argument but returns an index vector. So you could use it like this:
outcome.df %>%
filter(complete.cases(.)) %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
You can try also using below script
<html>
<head>
<script>
function load()
{
document.frm1.submit()
}
</script>
</head>
<body onload="load()">
<form action="http://www.google.com" id="frm1" name="frm1">
<input type="text" value="" />
</form>
</body>
</html>
FOO=bar
export FOO
$date = date('h:i:s A', strtotime($today . " +10 hours"));
You can use white-space: pre;
to make elements act like <pre>
, which preserves newlines. Example:
p {_x000D_
white-space: pre;_x000D_
}
_x000D_
<p>hello _x000D_
How are you</p>
_x000D_
Note for IE that this only works in IE8+.
The short answer is that setting grid-auto-rows: 1fr;
on the grid container solves what was asked.
I still believe this is a fundamental / functional flaw brought about by a technicality. If you have an optional field by which you can identify a customer you now have to hack a dummy value into it, just because NULL != NULL, not particularly elegant yet it is an "industry standard"
If you already have the databinding in place John Myczek answer is complete. If not you have at least 2 options I know of if you want to specify the source of your data. (However I am not sure whether or not this is in line with most guidelines, like MVVM)
Then you just bind to Users collections and columns are autogenerated as you speficy them. Strings passed to property descriptors are names for column headers. At runtime you can add more PropertyDescriptors to 'Users' add another column to the grid.
Tieme put a lot of effort into his excellent answer, but I think the core of the OP's question is how these technologies relate to PHP rather than how each technology works.
PHP is the most used language in web development besides the obvious client side HTML, CSS, and Javascript. Yet PHP has 2 major issues when it comes to real-time applications:
libphp5.so
on Linux, php5ts.dll
on Windows, etc) as if it still a CGI processing a GET/POST request. It still executes code as if it just has to build a "page" and then end its life cycle. As a result, it has very little support for multi-thread or event-driven programming (within PHP userspace), making it currently unpractical for real-time, multi-user applications.Note that PHP does have extensions to provide event loops (such as libevent
) and threads (such as pthreads
) in PHP userspace, but very, very, few of the applications use these.
PHP 7 will be a great step to fix these issues as well, and seems very promising as a platform for real-time applications.
I just wrote a simple script to collect the dependencies in ./node_modules. It fulfills my requirement at the moment. This may help some others, I post it here.
var fs = require("fs");
function main() {
fs.readdir("./node_modules", function (err, dirs) {
if (err) {
console.log(err);
return;
}
dirs.forEach(function(dir){
if (dir.indexOf(".") !== 0) {
var packageJsonFile = "./node_modules/" + dir + "/package.json";
if (fs.existsSync(packageJsonFile)) {
fs.readFile(packageJsonFile, function (err, data) {
if (err) {
console.log(err);
}
else {
var json = JSON.parse(data);
console.log('"'+json.name+'": "' + json.version + '",');
}
});
}
}
});
});
}
main();
In my case, the above script outputs:
"colors": "0.6.0-1",
"commander": "1.0.5",
"htmlparser": "1.7.6",
"optimist": "0.3.5",
"progress": "0.1.0",
"request": "2.11.4",
"soupselect": "0.2.0", // Remember: remove the comma character in the last line.
Now, you can copy&paste them. Have fun!
Or you can simply use OleDbDataAdapter to get data from Excel
There is no error when I use your code,
but I am calling the hasLetter
method like this:
hasLetter("a",words);
A 24 hour clock:
setInterval(function(){
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
// Add leading zeros
minutes = (minutes < 10 ? "0" : "") + minutes;
seconds = (seconds < 10 ? "0" : "") + seconds;
hours = (hours < 10 ? "0" : "") + hours;
// Compose the string for display
var currentTimeString = hours + ":" + minutes + ":" + seconds;
$(".clock").html(currentTimeString);
},1000);
// 24 hour clock _x000D_
setInterval(function() {_x000D_
_x000D_
var currentTime = new Date();_x000D_
var hours = currentTime.getHours();_x000D_
var minutes = currentTime.getMinutes();_x000D_
var seconds = currentTime.getSeconds();_x000D_
_x000D_
// Add leading zeros_x000D_
hours = (hours < 10 ? "0" : "") + hours;_x000D_
minutes = (minutes < 10 ? "0" : "") + minutes;_x000D_
seconds = (seconds < 10 ? "0" : "") + seconds;_x000D_
_x000D_
// Compose the string for display_x000D_
var currentTimeString = hours + ":" + minutes + ":" + seconds;_x000D_
$(".clock").html(currentTimeString);_x000D_
_x000D_
}, 1000);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="clock"></div>
_x000D_
One more option is to add the path of the privatekey file like this in terminal:
ssh-add "path to the privatekeyfile"
and then execute the pull command
Simple python code for separating the digits in string
s="rollnumber99mixedin447"
list(filter(lambda c: c >= '0' and c <= '9', [x for x in s]))
You can't do without transaction logs in SQL Server, under any circumstances. The engine simply won't function.
You CAN set your recovery model to SIMPLE on your dev machines - that will prevent transaction log bloating when tran log backups aren't done.
ALTER DATABASE MyDB SET RECOVERY SIMPLE;
$pdf->SetY($Y_Fields_Name_position);
$pdf->SetX(#);
$pdf->MultiCell($height,$width,"Line1 \nLine2 \nLine3",1,'C',1);
In every Column, before you set the X Position indicate first the Y position, so it became like this
Column 1
$pdf->SetY($Y_Fields_Name_position);
$pdf->SetX(#);
$pdf->MultiCell($height,$width,"Line1 \nLine2 \nLine3",1,'C',1);
Column 2
$pdf->SetY($Y_Fields_Name_position);
$pdf->SetX(#);
$pdf->MultiCell($height,$width,"Line1 \nLine2 \nLine3",1,'C',1);
Left shift: It is equal to the product of the value which has to be shifted and 2 raised to the power of number of bits to be shifted.
Example:
1 << 3
0000 0001 ---> 1
Shift by 1 bit
0000 0010 ----> 2 which is equal to 1*2^1
Shift By 2 bits
0000 0100 ----> 4 which is equal to 1*2^2
Shift by 3 bits
0000 1000 ----> 8 which is equal to 1*2^3
Right shift: It is equal to quotient of value which has to be shifted by 2 raised to the power of number of bits to be shifted.
Example:
8 >> 3
0000 1000 ---> 8 which is equal to 8/2^0
Shift by 1 bit
0000 0100 ----> 4 which is equal to 8/2^1
Shift By 2 bits
0000 0010 ----> 2 which is equal to 8/2^2
Shift by 3 bits
0000 0001 ----> 1 which is equal to 8/2^3
you can also use Git bash where head and tail are emulated as well
In my case i did the following and worked for me
1) "Unnecessarily complicated" is IMHO to create first an unmodifiable List before adding its elements to the ArrayList.
2) The solution matches exact the question: "Is there a way to define an ArrayList with the double type?"
double type:
double[] arr = new double[] {1.38, 2.56, 4.3};
ArrayList:
ArrayList<Double> list = DoubleStream.of( arr ).boxed().collect(
Collectors.toCollection( new Supplier<ArrayList<Double>>() {
public ArrayList<Double> get() {
return( new ArrayList<Double>() );
}
} ) );
…and this creates the same compact and fast compilation as its Java 1.8 short-form:
ArrayList<Double> list = DoubleStream.of( arr ).boxed().collect(
Collectors.toCollection( ArrayList::new ) );
This is the correct way:
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
activityIndicator.center = CGPointMake(self.view.frame.size.width / 2.0, self.view.frame.size.height / 2.0);
[self.view addSubview: activityIndicator];
[activityIndicator startAnimating];
[activityIndicator release];
Setup your autoresizing mask if you support rotation. Cheers!!!
Such a thing probably does not exist "as-is". It doesn't really exist on Linux or other UNIX-like operating systems either though.
ncurses is only a library that helps you manage interactions with the underlying terminal environment. But it doesn't provide a terminal emulator itself.
The thing that actually displays stuff on the screen (which in your requirement is listed as "native resizable win32 windows") is usually called a Terminal Emulator. If you don't like the one that comes with Windows (you aren't alone; no person on Earth does) there are a few alternatives. There is Console, which in my experience works sometimes and appears to just wrap an underlying Windows terminal emulator (I don't know for sure, but I'm guessing, since there is a menu option to actually get access to that underlying terminal emulator, and sure enough an old crusty Windows/DOS box appears which mirrors everything in the Console window).
A better option
Another option, which may be more appealing is puttycyg. It hooks in to Putty (which, coming from a Linux background, is pretty close to what I'm used to, and free) but actually accesses an underlying cygwin instead of the Windows command interpreter (CMD.EXE
). So you get all the benefits of Putty's awesome terminal emulator, as well as nice ncurses
(and many other) libraries provided by cygwin. Add a couple command line arguments to the Shortcut that launches Putty (or the Batch file) and your app can be automatically launched without going through Putty's UI.
fromDic.ToList().ForEach(x =>
{
if (toDic.ContainsKey(x.Key))
toDic.Remove(x.Key);
toDic.Add(x);
});
Here is a post which introduces different types of keystore in Java and the differences among different types of keystore. http://www.pixelstech.net/article/1408345768-Different-types-of-keystore-in-Java----Overview
Below are the descriptions of different keystores from the post:
JKS, Java Key Store. You can find this file at sun.security.provider.JavaKeyStore. This keystore is Java specific, it usually has an extension of jks. This type of keystore can contain private keys and certificates, but it cannot be used to store secret keys. Since it's a Java specific keystore, so it cannot be used in other programming languages.
JCEKS, JCE key store. You can find this file at com.sun.crypto.provider.JceKeyStore. This keystore has an extension of jceks. The entries which can be put in the JCEKS keystore are private keys, secret keys and certificates.
PKCS12, this is a standard keystore type which can be used in Java and other languages. You can find this keystore implementation at sun.security.pkcs12.PKCS12KeyStore. It usually has an extension of p12 or pfx. You can store private keys, secret keys and certificates on this type.
PKCS11, this is a hardware keystore type. It servers an interface for the Java library to connect with hardware keystore devices such as Luna, nCipher. You can find this implementation at sun.security.pkcs11.P11KeyStore. When you load the keystore, you no need to create a specific provider with specific configuration. This keystore can store private keys, secret keys and cetrificates. When loading the keystore, the entries will be retrieved from the keystore and then converted into software entries.
The alpha can be set along with the color using the following hex format #ARGB or #AARRGGBB. See http://developer.android.com/guide/topics/resources/color-list-resource.html
This function will return the results of a query as an array of powershell objects so you can use them in filters and access columns easily:
function sql($sqlText, $database = "master", $server = ".")
{
$connection = new-object System.Data.SqlClient.SQLConnection("Data Source=$server;Integrated Security=SSPI;Initial Catalog=$database");
$cmd = new-object System.Data.SqlClient.SqlCommand($sqlText, $connection);
$connection.Open();
$reader = $cmd.ExecuteReader()
$results = @()
while ($reader.Read())
{
$row = @{}
for ($i = 0; $i -lt $reader.FieldCount; $i++)
{
$row[$reader.GetName($i)] = $reader.GetValue($i)
}
$results += new-object psobject -property $row
}
$connection.Close();
$results
}
I'm the author of modular-spring-contexts.
This is a small utility library to allow a more modular organization of spring contexts than is achieved by using Composing XML-based configuration metadata. modular-spring-contexts
works by defining modules, which are basically stand alone application contexts and allowing modules to import beans from other modules, which are exported ín their originating module.
The key points then are
A simple example would look like this:
File moduleDefinitions.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:module="http://www.gitlab.com/SpaceTrucker/modular-spring-contexts"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.gitlab.com/SpaceTrucker/modular-spring-contexts xsd/modular-spring-contexts.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config />
<module:module id="serverModule">
<module:config location="/serverModule.xml" />
</module:module>
<module:module id="clientModule">
<module:config location="/clientModule.xml" />
<module:requires module="serverModule" />
</module:module>
</beans>
File serverModule.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:module="http://www.gitlab.com/SpaceTrucker/modular-spring-contexts"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.gitlab.com/SpaceTrucker/modular-spring-contexts xsd/modular-spring-contexts.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config />
<bean id="serverSingleton" class="java.math.BigDecimal" scope="singleton">
<constructor-arg index="0" value="123.45" />
<meta key="exported" value="true"/>
</bean>
</beans>
File clientModule.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:module="http://www.gitlab.com/SpaceTrucker/modular-spring-contexts"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.gitlab.com/SpaceTrucker/modular-spring-contexts xsd/modular-spring-contexts.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config />
<module:import id="importedSingleton" sourceModule="serverModule" sourceBean="serverSingleton" />
</beans>
I can give a small hack, you can use T-SQL function. Try this:
SELECT ID, PARSENAME(WebsiteName, 2)
FROM dbo.YourTable .....
I know this is kind of late for a response. But I did run into this error and I found a solution here: https://rvm.io/integration/gnome-terminal
You just have to enable 'Run command as login shell' under the terminal preferences.
You can call window.focus();
but moving or losing the focus is bound to interfere with anyone using the tab key to get around the page.
you could listen for keycode 13, and forego the effect if the tab key is pressed.
You want to cast the numbers:
double num3 = (double)num1/(double)num2;
Note: If any of the arguments in C# is a double
, a double
divide is used which results in a double
. So, the following would work too:
double num3 = (double)num1/num2;
For more information see:
You can access the MySQL command line with XAMPP for Windows
click XAMPP icon to launch its cPanel
click on Shell button
mysql -h localhost -u root
and click enterYou should see all the command lines and what they do
Setting environment for using XAMPP for Windows.
Your PC c:\xampp
# mysql -h localhost - root
mysql Ver 15.1 Distrib 10.1.19-MariaDB, for Win32 (AMD64)
Copyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.
Usage: mysql [OPTIONS] [database]
Default options are read from the following files in the given order:
C:\WINDOWS\my.ini C:\WINDOWS\my.cnf C:\my.ini C:\my.cnf C:\xampp\mysql\my.ini C:\xampp\mysql\my.cnf C:\xampp\mysql\bin\my.ini C:\xampp\mysql\bin\my.cnf
The following groups are read: mysql client client-server client-mariadb
The following options may be given as the first argument:
--print-defaults Print the program argument list and exit.
--no-defaults Don't read default options from any option file.
--defaults-file=# Only read default options from the given file #.
--defaults-extra-file=# Read this file after the global files are read.
-?, --help Display this help and exit.
-I, --help Synonym for -?
--abort-source-on-error
Abort 'source filename' operations in case of errors
--auto-rehash Enable automatic rehashing. One doesn't need to use
'rehash' to get table and field completion, but startup
and reconnecting may take a longer time. Disable with
--disable-auto-rehash.
(Defaults to on; use --skip-auto-rehash to disable.)
-A, --no-auto-rehash
No automatic rehashing. One has to use 'rehash' to get
table and field completion. This gives a quicker start of
mysql and disables rehashing on reconnect.
--auto-vertical-output
Automatically switch to vertical output mode if the
result is wider than the terminal width.
-B, --batch Don't use history file. Disable interactive behavior.
(Enables --silent.)
--character-sets-dir=name
Directory for character set files.
--column-type-info Display column type information.
-c, --comments Preserve comments. Send comments to the server. The
default is --skip-comments (discard comments), enable
with --comments.
-C, --compress Use compression in server/client protocol.
-#, --debug[=#] This is a non-debug version. Catch this and exit.
--debug-check Check memory and open file usage at exit.
-T, --debug-info Print some debug info at exit.
-D, --database=name Database to use.
--default-character-set=name
Set the default character set.
--delimiter=name Delimiter to be used.
-e, --execute=name Execute command and quit. (Disables --force and history
file.)
-E, --vertical Print the output of a query (rows) vertically.
-f, --force Continue even if we get an SQL error. Sets
abort-source-on-error to 0
-G, --named-commands
Enable named commands. Named commands mean this program's
internal commands; see mysql> help . When enabled, the
named commands can be used from any line of the query,
otherwise only from the first line, before an enter.
Disable with --disable-named-commands. This option is
disabled by default.
-i, --ignore-spaces Ignore space after function names.
--init-command=name SQL Command to execute when connecting to MySQL server.
Will automatically be re-executed when reconnecting.
--local-infile Enable/disable LOAD DATA LOCAL INFILE.
-b, --no-beep Turn off beep on error.
-h, --host=name Connect to host.
-H, --html Produce HTML output.
-X, --xml Produce XML output.
--line-numbers Write line numbers for errors.
(Defaults to on; use --skip-line-numbers to disable.)
-L, --skip-line-numbers
Don't write line number for errors.
-n, --unbuffered Flush buffer after each query.
--column-names Write column names in results.
(Defaults to on; use --skip-column-names to disable.)
-N, --skip-column-names
Don't write column names in results.
--sigint-ignore Ignore SIGINT (CTRL-C).
-o, --one-database Ignore statements except those that occur while the
default database is the one named at the command line.
-p, --password[=name]
Password to use when connecting to server. If password is
not given it's asked from the tty.
-W, --pipe Use named pipes to connect to server.
-P, --port=# Port number to use for connection or 0 for default to, in
order of preference, my.cnf, $MYSQL_TCP_PORT,
/etc/services, built-in default (3306).
--progress-reports Get progress reports for long running commands (like
ALTER TABLE)
(Defaults to on; use --skip-progress-reports to disable.)
--prompt=name Set the mysql prompt to this value.
--protocol=name The protocol to use for connection (tcp, socket, pipe,
memory).
-q, --quick Don't cache result, print it row by row. This may slow
down the server if the output is suspended. Doesn't use
history file.
-r, --raw Write fields without conversion. Used with --batch.
--reconnect Reconnect if the connection is lost. Disable with
--disable-reconnect. This option is enabled by default.
(Defaults to on; use --skip-reconnect to disable.)
-s, --silent Be more silent. Print results with a tab as separator,
each row on new line.
--shared-memory-base-name=name
Base name of shared memory.
-S, --socket=name The socket file to use for connection.
--ssl Enable SSL for connection (automatically enabled with
other flags).
--ssl-ca=name CA file in PEM format (check OpenSSL docs, implies
--ssl).
--ssl-capath=name CA directory (check OpenSSL docs, implies --ssl).
--ssl-cert=name X509 cert in PEM format (implies --ssl).
--ssl-cipher=name SSL cipher to use (implies --ssl).
--ssl-key=name X509 key in PEM format (implies --ssl).
--ssl-crl=name Certificate revocation list (implies --ssl).
--ssl-crlpath=name Certificate revocation list path (implies --ssl).
--ssl-verify-server-cert
Verify server's "Common Name" in its cert against
hostname used when connecting. This option is disabled by
default.
-t, --table Output in table format.
--tee=name Append everything into outfile. See interactive help (\h)
also. Does not work in batch mode. Disable with
--disable-tee. This option is disabled by default.
-u, --user=name User for login if not current user.
-U, --safe-updates Only allow UPDATE and DELETE that uses keys.
-U, --i-am-a-dummy Synonym for option --safe-updates, -U.
-v, --verbose Write more. (-v -v -v gives the table output format).
-V, --version Output version information and exit.
-w, --wait Wait and retry if connection is down.
--connect-timeout=# Number of seconds before connection timeout.
--max-allowed-packet=#
The maximum packet length to send to or receive from
server.
--net-buffer-length=#
The buffer size for TCP/IP and socket communication.
--select-limit=# Automatic limit for SELECT when using --safe-updates.
--max-join-size=# Automatic limit for rows in a join when using
--safe-updates.
--secure-auth Refuse client connecting to server if it uses old
(pre-4.1.1) protocol.
--server-arg=name Send embedded server this as a parameter.
--show-warnings Show warnings after every statement.
--plugin-dir=name Directory for client-side plugins.
--default-auth=name Default authentication client-side plugin to use.
--binary-mode By default, ASCII '\0' is disallowed and '\r\n' is
translated to '\n'. This switch turns off both features,
and also turns off parsing of all clientcommands except
\C and DELIMITER, in non-interactive mode (for input
piped to mysql or loaded using the 'source' command).
This is necessary when processing output from mysqlbinlog
that may contain blobs.
Variables (--variable-name=value)
and boolean options {FALSE|TRUE} Value (after reading options)
--------------------------------- ----------------------------------------
abort-source-on-error FALSE
auto-rehash FALSE
auto-vertical-output FALSE
character-sets-dir (No default value)
column-type-info FALSE
comments FALSE
compress FALSE
debug-check FALSE
debug-info FALSE
database (No default value)
default-character-set auto
delimiter ;
vertical FALSE
force FALSE
named-commands FALSE
ignore-spaces FALSE
init-command (No default value)
local-infile FALSE
no-beep FALSE
host localhost
html FALSE
xml FALSE
line-numbers TRUE
unbuffered FALSE
column-names TRUE
sigint-ignore FALSE
port 3306
progress-reports TRUE
prompt \N [\d]>
quick FALSE
raw FALSE
reconnect TRUE
shared-memory-base-name (No default value)
socket C:/xampp/mysql/mysql.sock
ssl FALSE
ssl-ca (No default value)
ssl-capath (No default value)
ssl-cert (No default value)
ssl-cipher (No default value)
ssl-key (No default value)
ssl-crl (No default value)
ssl-crlpath (No default value)
ssl-verify-server-cert FALSE
table FALSE
user (No default value)
safe-updates FALSE
i-am-a-dummy FALSE
connect-timeout 0
max-allowed-packet 16777216
net-buffer-length 16384
select-limit 1000
max-join-size 1000000
secure-auth FALSE
show-warnings FALSE
plugin-dir (No default value)
default-auth (No default value)
binary-mode FALSE
In setup.py under setup( :
setup(
name = 'foo library'
...
package_data={
'foolibrary.folderA': ['*'], # All files from folder A
'foolibrary.folderB': ['*.txt'] #All text files from folder B
},
As far as Angular CLI: 7.1.4, there are two common ways to achieve changing the default port.
In the angular.json
, add the --port
option to serve
part and use ng serve
to start the server.
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "demos:build",
"port": 1337
},
"configurations": {
"production": {
"browserTarget": "demos:build:production"
}
}
},
In the package.json
, add the --port
option to ng serve
and use npm start
to start the server.
"scripts": {
"ng": "ng",
"start": "ng serve --port 8000",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
Note that your initial query is probably not returning what you want:
SELECT availables.bookdate AS Date, DATEDIFF(now(),availables.updated_at) as Age
FROM availables INNER JOIN rooms ON availables.room_id=rooms.id
WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094 GROUP BY availables.bookdate
You are grouping by book date, but you are not using any grouping function on the second column of your query.
The query you are probably looking for is:
SELECT availables.bookdate AS Date, count(*) as subtotal, sum(DATEDIFF(now(),availables.updated_at) as Age)
FROM availables INNER JOIN rooms ON availables.room_id=rooms.id
WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094
GROUP BY availables.bookdate
If you are using atomic, it means the thread will be safe and read-only. If you are using nonatomic, it means the multiple threads access the variable and is thread unsafe, but it is executed fast, done a read and write operations; this is a dynamic type.
While you are switching, switch to PDO instead of mysqli, It helps you write database agnositc code and have better features for prepared statements.
Bindparam for PDO: http://se.php.net/manual/en/pdostatement.bindparam.php
$sth = $dbh->prepare("SELECT * FROM tablename WHERE field1 = :value1 && field2 = :value2");
$sth->bindParam(':value1', 'foo');
$sth->bindParam(':value2', 'bar');
$sth->execute();
or:
$sth = $dbh->prepare("SELECT * FROM tablename WHERE field1 = ? && field2 = ?");
$sth->bindParam(1, 'foo');
$sth->bindParam(2, 'bar');
$sth->execute();
or execute with the parameters as an array:
$sth = $dbh->prepare("SELECT * FROM tablename WHERE field1 = :value1 && field2 = :value2");
$sth->execute(array(':value1' => 'foo' , ':value2' => 'bar'));
It will be easier for you if you would like your application to be able to run on different databases in the future.
I also think you should invest some time in using some of the classes from Zend Framwework whilst working with PDO. Check out their Zend_Db and more specifically [Zend_Db_Factory][2]. You do not have to use all of the framework or convert your application to the MVC pattern, but using the framework and reading up on it is time well spent.
Hi I tested below code that worked fine :
long timeInMillis = System.currentTimeMillis();
Calendar cal1 = Calendar.getInstance();
cal1.setTimeInMillis(timeInMillis);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss a");
dateFormat.format(cal1.getTime());
Just put a line break into your text.
You don't add lines as a method. Multiline just supports the use of line breaks.
In my case the error was still there, because my system used upgraded Java. If you are using Java 10, modify the compileOptions:
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_10
targetCompatibility JavaVersion.VERSION_1_10
}
I think you can use the nrows
parameter. From the docs:
nrows : int, default None
Number of rows of file to read. Useful for reading pieces of large files
which seems to work. Using one of the standard large test files (988504479 bytes, 5344499 lines):
In [1]: import pandas as pd
In [2]: time z = pd.read_csv("P00000001-ALL.csv", nrows=20)
CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
Wall time: 0.00 s
In [3]: len(z)
Out[3]: 20
In [4]: time z = pd.read_csv("P00000001-ALL.csv")
CPU times: user 27.63 s, sys: 1.92 s, total: 29.55 s
Wall time: 30.23 s
Another simple example:
public static void listFilesInDirectory(String pathString) {
// A local class (a class defined inside a block, here a method).
class MyFilter implements FileFilter {
@Override
public boolean accept(File file) {
return !file.isHidden() && file.getName().endsWith(".txt");
}
}
File directory = new File(pathString);
File[] files = directory.listFiles(new MyFilter());
for (File fileLoop : files) {
System.out.println(fileLoop.getName());
}
}
// Call it
listFilesInDirectory("C:\\Users\\John\\Documents\\zTemp");
// Output
Cool.txt
RedditKinsey.txt
...
In case someone else ends up here struggling to customize admin form Many2Many saving behaviour, you can't call self.instance.my_m2m.add(obj)
in your ModelForm.save
override, as ModelForm.save
later populates your m2m from self.cleaned_data['my_m2m']
which overwrites your changes. Instead call:
my_m2ms = list(self.cleaned_data['my_m2ms'])
my_m2ms.extend(my_custom_new_m2ms)
self.cleaned_data['my_m2ms'] = my_m2ms
(It is fine to convert the incoming QuerySet to a list - the ManyToManyField
does that anyway.)
While it's true that @RequestBody
must map to a single object, that object can be a Map
, so this gets you a good way to what you are attempting to achieve (no need to write a one off backing object):
@RequestMapping(value = "/Test", method = RequestMethod.POST)
@ResponseBody
public boolean getTest(@RequestBody Map<String, String> json) {
//json.get("str1") == "test one"
}
You can also bind to Jackson's ObjectNode if you want a full JSON tree:
public boolean getTest(@RequestBody ObjectNode json) {
//json.get("str1").asText() == "test one"
I got the Error even though i was catching the exception.
try {
bitmap = BitmapFactory.decodeStream(getAssets().open("kitten.jpg"));
} catch (IOException e) {
Log.e("blabla", "Error", e);
finish();
}
Issue was that the IOException wasn't imported
import java.io.IOException;
It's not called null as in other languages, but None
. There is always only one instance of this object, so you can check for equivalence with x is None
(identity comparison) instead of x == None
, if you want.
The rgba() function can accept a single hex color as well decimal RGB values. For example, this would work just fine:
@mixin background-opacity($color, $opacity: 0.3) {
background: $color; /* The Fallback */
background: rgba($color, $opacity);
}
element {
@include background-opacity(#333, 0.5);
}
If you ever need to break the hex color into RGB components, though, you can use the red(), green(), and blue() functions to do so:
$red: red($color);
$green: green($color);
$blue: blue($color);
background: rgb($red, $green, $blue); /* same as using "background: $color" */
If you didn't commit it to the master branch yet, its easy:
git checkout -b oops/fluke/dang
)git add -u; git commit;
)git checkout master
)Your changes will be saved in branch oops/fluke/dang; master will be as it was.
Try it.
You can just pass the path to the style sheet .
{!! HTML::style('css/style.css') !!}
You can just pass the path to the javascript.
{!! HTML::script('js/script.js') !!}
Add the following lines in the require section of composer.json file and run composer update "illuminate/html": "5.*".
Register the service provider in config/app.php by adding the following value into the providers array:
'Illuminate\Html\HtmlServiceProvider'
Register facades by adding these two lines in the aliases array:
'Form'=> 'Illuminate\Html\FormFacade',
'HTML'=> 'Illuminate\Html\HtmlFacade'
#example1 {_x000D_
background: url(http://www.w3schools.com/css/img_flwr.gif) left top no-repeat, url(http://www.w3schools.com/css/img_flwr.gif) right bottom no-repeat, url(http://www.w3schools.com/css/paper.gif) left top repeat;_x000D_
padding: 15px;_x000D_
background-size: 150px, 130px, auto;_x000D_
background-position: 50px 30px, 430px 30px, 130px 130px;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div id="example1">_x000D_
<h1>Lorem Ipsum Dolor</h1>_x000D_
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>_x000D_
<p>Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p>_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
We can easily add multiple images using CSS3. we can read in detail here http://www.w3schools.com/css/css3_backgrounds.asp
If you don't mind using 3rd Party Libraries cyclops-react has an extended Stream type that will allow you to do just that via the append / prepend operators.
Individual values, arrays, iterables, Streams or reactive-streams Publishers can be appended and prepended as instance methods.
Stream stream = ReactiveSeq.of(1,2)
.filter(x -> x!=0)
.append(ReactiveSeq.of(3,4))
.filter(x -> x!=1)
.append(5)
.filter(x -> x!=2);
[Disclosure I am the lead developer of cyclops-react]
=
can be used when the subquery returns only 1 value.
When subquery returns more than 1 value, you will have to use IN
:
select *
from table
where id IN (multiple row query);
For example:
SELECT *
FROM Students
WHERE Marks = (SELECT MAX(Marks) FROM Students) --Subquery returns only 1 value
SELECT *
FROM Students
WHERE Marks IN
(SELECT Marks
FROM Students
ORDER BY Marks DESC
LIMIT 10) --Subquery returns 10 values
The DPI of the screen of the Nexus 10 is ±300, which is in the unofficial xhdpi
range of 280-400.
Usually, devices use resources designed for their density. But there are exceptions, and exceptions might be added in the future.
The Nexus 10 uses xxhdpi
resources when it comes to launcher icons.
The standard quantised DPI for xxhdpi is 480 (which means screens with a DPI somewhere in the range of 400-560 are probably xxhdpi).
This has been discussed on SO multiple times. Here are a few links to get you started:
SO: Capturing image from webcam in java?
openCVF applet: http://www.colorfulwolf.com/blog/2011/07/05/accessing-the-webcam-from-inside-a-java-applet/
config: http://ganeshtiwaridotcomdotnp.blogspot.in/2011/12/opencv-javacv-eclipse-project.html
Linked list to demonstrate Insert Front, Delete Front, Insert Rear and Delete Rear operations in Java:
import java.io.DataInputStream;
import java.io.IOException;
public class LinkedListTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Node root = null;
DataInputStream reader = new DataInputStream(System.in);
int op = 0;
while(op != 6){
try {
System.out.println("Enter Option:\n1:Insert Front 2:Delete Front 3:Insert Rear 4:Delete Rear 5:Display List 6:Exit");
//op = reader.nextInt();
op = Integer.parseInt(reader.readLine());
switch (op) {
case 1:
System.out.println("Enter Value: ");
int val = Integer.parseInt(reader.readLine());
root = insertNodeFront(val,root);
display(root);
break;
case 2:
root=removeNodeFront(root);
display(root);
break;
case 3:
System.out.println("Enter Value: ");
val = Integer.parseInt(reader.readLine());
root = insertNodeRear(val,root);
display(root);
break;
case 4:
root=removeNodeRear(root);
display(root);
break;
case 5:
display(root);
break;
default:
System.out.println("Invalid Option");
break;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Exited!!!");
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static Node insertNodeFront(int value, Node root){
Node temp = new Node(value);
if(root==null){
return temp; // as root or first
}
else
{
temp.next = root;
return temp;
}
}
static Node removeNodeFront(Node root){
if(root==null){
System.out.println("List is Empty");
return null;
}
if(root.next==null){
return null; // remove root itself
}
else
{
root=root.next;// make next node as root
return root;
}
}
static Node insertNodeRear(int value, Node root){
Node temp = new Node(value);
Node cur = root;
if(root==null){
return temp; // as root or first
}
else
{
while(cur.next!=null)
{
cur = cur.next;
}
cur.next = temp;
return root;
}
}
static Node removeNodeRear(Node root){
if(root==null){
System.out.println("List is Empty");
return null;
}
Node cur = root;
Node prev = null;
if(root.next==null){
return null; // remove root itself
}
else
{
while(cur.next!=null)
{
prev = cur;
cur = cur.next;
}
prev.next=null;// remove last node
return root;
}
}
static void display(Node root){
System.out.println("Current List:");
if(root==null){
System.out.println("List is Empty");
return;
}
while (root!=null){
System.out.print(root.val+"->");
root=root.next;
}
System.out.println();
}
static class Node{
int val;
Node next;
public Node(int value) {
// TODO Auto-generated constructor stub
val = value;
next = null;
}
}
}
.getBoundingClientRect() returns the size of an element and its position relative to the viewport.We can easily get following
Example :
var element = d3.select('.elementClassName').node();
element.getBoundingClientRect().width;
You need to link with the math library, libm:
$ gcc -Wall foo.c -o foo -lm
Instead of saving it to a file, save it to php://output
Docs:
$objWriter->save('php://output');
This will send it AS-IS to the browser.
You want to add some headersDocs first, like it's common with file downloads, so the browser knows which type that file is and how it should be named (the filename):
// We'll be outputting an excel file
header('Content-type: application/vnd.ms-excel');
// It will be called file.xls
header('Content-Disposition: attachment; filename="file.xls"');
// Write file to the browser
$objWriter->save('php://output');
First do the headers, then the save. For the excel headers see as well the following question: Setting mime type for excel document.
You could use a library called requests.
import requests
r = requests.get("http://example.com/foo/bar")
This is quite easy. Then you can do like this:
>>> print(r.status_code)
>>> print(r.headers)
>>> print(r.content)
An alternative is not to replace the .class file in the jar file. Instead put it into a new jar file and ensure that it appears earlier on your classpath than the original jar file.
Not sure I would recommend this for production software but for development it is quick and easy.
After searching around I found a way to create a temp table dynamically for any stored procedure without using OPENROWSET
or OPENQUERY
using a generic schema of Stored Procedure's result definition especially when you are not database Administrator.
Sql server has a buit-in proc sp_describe_first_result_set
that can provide you with schema of any procedures resultset. I created a schema table from results of this procedure and manually set all the field to NULLABLE.
declare @procname varchar(100) = 'PROCEDURENAME' -- your procedure name
declare @param varchar(max) = '''2019-06-06''' -- your parameters
declare @execstr nvarchar(max) = N'exec ' + @procname
declare @qry nvarchar(max)
-- Schema table to store the result from sp_describe_first_result_set.
create table #d
(is_hidden bit NULL, column_ordinal int NULL, name sysname NULL, is_nullable bit NULL, system_type_id int NULL, system_type_name nvarchar(256) NULL,
max_length smallint NULL, precision tinyint NULL, scale tinyint NULL, collation_name sysname NULL, user_type_id int NULL, user_type_database sysname NULL,
user_type_schema sysname NULL,user_type_name sysname NULL,assembly_qualified_type_name nvarchar(4000),xml_collection_id int NULL,xml_collection_database sysname NULL,
xml_collection_schema sysname NULL,xml_collection_name sysname NULL,is_xml_document bit NULL,is_case_sensitive bit NULL,is_fixed_length_clr_type bit NULL,
source_server sysname NULL,source_database sysname NULL,source_schema sysname NULL,source_table sysname NULL,source_column sysname NULL,is_identity_column bit NULL,
is_part_of_unique_key bit NULL,is_updateable bit NULL,is_computed_column bit NULL,is_sparse_column_set bit NULL,ordinal_in_order_by_list smallint NULL,
order_by_list_length smallint NULL,order_by_is_descending smallint NULL,tds_type_id int NULL,tds_length int NULL,tds_collation_id int NULL,
tds_collation_sort_id tinyint NULL)
-- Get result set definition of your procedure
insert into #d
EXEC sp_describe_first_result_set @exestr, NULL, 0
-- Create a query to generate and populate a global temp table from above results
select
@qry = 'Create table ##t(' +
stuff(
(select ',' + name + ' '+ system_type_name + ' NULL'
from #d d For XML Path, TYPE)
.value(N'.[1]', N'nvarchar(max)')
, 1,1,'')
+ ')
insert into ##t
Exec '+@procname+' ' + @param
Exec sp_executesql @qry
-- Use below global temp table to query the data as you may
select * from ##t
-- **WARNING** Don't forget to drop the global temp table ##t.
--drop table ##t
drop table #d
Developed and tested on Sql Server version - Microsoft SQL Server 2016 (RTM) - 13.0.1601.5(Build 17134:)
You can tweak the schema for your SQL server version that you are using (if needed).
Try:
awk -F',' '{print $3}' myfile.txt
Here in -F you are saying to awk that use "," as field separator.
.htaccess
is in DOS format, change it to UNIX format (in Notepad++, click Edit>Convert
).htaccess
is in UTF8 Without-BOM, make it WITH BOM.Just pass the list to np.array
:
a = np.array(a)
You can also take this opportunity to set the dtype
if the default is not what you desire.
a = np.array(a, dtype=...)
You can do it without setlocal
, because of the setlocal
command the variable won't survive an endlocal
because it was created in setlocal
. In this way the variable will be defined the right way.
To do that use this code:
set var1=A
set var2=B
set AB=hi
call set newvar=%%%var1%%var2%%%
echo %newvar%
Note: You MUST use call
before you set the variable or it won't work.
You have your storyboard set up to expect an outlet called tableView
but the actual outlet name is myTableView
.
If you delete the connection in the storyboard and reconnect to the right variable name, it should fix the problem.
I am using the method posted by Brock Adams and it even works in Firefox, if it's user initiated.
open(location, '_self').close();
I am calling it from a button press so it is user initiated, and it is still working fine using Chrome 35-40, Internet Explorer 11, Safari 7-8 and ALSO Firefox 29-35. I tested using version 8.1 of Windows and Mac OS X 10.6, 10.9 & 10.10 if that is different.
Self-Closing Window Code (on the page that closes itself)
The complete code to be used on the user-opened window that can close itself:
window_to_close.htm
JavaScript:
function quitBox(cmd)
{
if (cmd=='quit')
{
open(location, '_self').close();
}
return false;
}
HTML:
<input type="button" name="Quit" id="Quit" value="Quit" onclick="return quitBox('quit');" />
Try this test page: (Now tested in Chrome 40 and Firefox 35)
http://browserstrangeness.bitbucket.io/window_close_tester.htm
Window Opener Code (on a page that opens the above page)
To make this work, security-imposed cross browser compatibility requires that the window that is to be closed must have already been opened by the user clicking a button within the same site domain.
For example, the window that uses the method above to close itself, can be opened from a page using this code (code provided from my example page linked above):
window_close_tester.htm
JavaScript:
function open_a_window()
{
window.open("window_to_close.htm");
return false;
}
HTML:
<input type="button" onclick="return open_a_window();" value="Open New Window/Tab" />
I just had the same problem. I'd say it has nothing to do with the apache.conf.
a2ensite must have changed - line 532 is the line that enforces the .conf suffix:
else {
$dir = 'sites';
$sffx = '.conf';
$reload = 'reload';
}
If you change it to:
else {
$dir = 'sites';
#$sffx = '.conf';
$sffx = '';
$reload = 'reload';
}
...it will work without any suffix.
Of course you wouldn't want to change the a2ensite script, but changing the conf file's suffix is the correct way.
It's probably just a way of enforcing the ".conf"-suffix.
Depending on the system configuration, size of CHAR mesured in BYTES can vary. In your examples: