Resolved like this:
# chown -R <user>: node_modules
Useful link here: Access Tomcat Manager App from different host
From Tomcat version 8 onward's, manager/html url won't be accessible to anyone except localhost.
In order to access /manager/html url, you need to do below change in context.xml of manager app. 1. Go to /apache-tomcat-8.5.23/webapps/manager/META-INF location, then edit context.xml
<Context antiResourceLocking="false" privileged="true" >
<Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow="^.*$" />
......
</Context>
Use this as a method with x being any number initially. The string y being passed in by console and v is the array to search!
public static int getIndex(int x, String y, String[]v){
for(int m = 0; m < v.length; m++){
if (v[m].equalsIgnoreCase(y)){
x = m;
}
}
return x;
}
If you change your function definition to use a variable instead:
var get_page = func(url string) string {
...
}
You can override it in your tests:
func TestDownloader(t *testing.T) {
get_page = func(url string) string {
if url != "expected" {
t.Fatal("good message")
}
return "something"
}
downloader()
}
Careful though, your other tests might fail if they test the functionality of the function you override!
The Go authors use this pattern in the Go standard library to insert test hooks into code to make things easier to test:
execute the script in your tomcat/bin
directory:
sh tomcat/bin/version.sh
Server version: Apache Tomcat/7.0.42
Server built: Jul 2 2013 08:57:41
Server number: 7.0.42.0
OS Name: Linux
OS Version: 2.6.32-042stab084.26
Architecture: amd64
JVM Version: 1.7.0_21-b11
JVM Vendor: Oracle Corporation
Move script tag at the end of BODY instead of HEAD because in current code when the script is computed html element doesn't exist in document.
Since you don't want to you jquery. Use window.onload or document.onload to execute the entire piece of code that you have in current script tag. window.onload vs document.onload
In the Hibernate mapping file for the id
property, if you use any generator class, for that property you should not set the value explicitly by using a setter method.
If you set the value of the Id property explicitly, it will lead the error above. Check this to avoid this error.
Is it possible to do it this way, as opposed to using something like Raphael or jQuery SVG?
Definitely.
If it is possible, what's the technique?
This annotated code snippet works:
<!DOCTYPE html>
<html>
<head>
<title>SVG Illustrator Test</title>
</head>
<body>
<object data="alpha.svg" type="image/svg+xml"
id="alphasvg" width="100%" height="100%"></object>
<script>
var a = document.getElementById("alphasvg");
// It's important to add an load event listener to the object,
// as it will load the svg doc asynchronously
a.addEventListener("load",function(){
// get the inner DOM of alpha.svg
var svgDoc = a.contentDocument;
// get the inner element by id
var delta = svgDoc.getElementById("delta");
// add behaviour
delta.addEventListener("mousedown",function(){
alert('hello world!')
}, false);
}, false);
</script>
</body>
</html>
Note that a limitation of this technique is that it is restricted by the same-origin policy, so alpha.svg
must be hosted on the same domain as the .html
file, otherwise the inner DOM of the object will be inaccessible.
Important thing to run this HTML, you need host HTML file to web server like IIS, Tomcat
Beside the obvious reloadData from UI/Main Thread (whatever Apple calls it), in my case, I had forgotten to also update the SECTIONS info. Therefor it did not detect any new sections!
The problem is here:
answer = newList.sort()
sort
does not return the sorted list; rather, it sorts the list in place.
Use:
answer = sorted(newList)
I'd also suggest moving the event handler outside render.
var OnSubmitTest = React.createClass({
submit: function(e){
e.preventDefault();
alert('it works!');
}
render: function() {
return (
<form onSubmit={this.submit}>
<button>Click me</button>
</form>
);
}
});
Try out the CImg library. The tutorial will help you get familiarized. Once you have a CImg object, the data() function will give you access to the 2D pixel buffer array.
I also experienced the same thing. I found out that my favicon.ico had not been processed as a legitimate shortcut icon. I understand that favicons must be scaled to 16x16 and follow the Microsoft Icon format.
Simple Example to understand how to access elements in the dictionary:-
d = {'dog' : 'bark', 'cat' : 'meow' }
print(d.get('cat'))
print(d.get('lion'))
print(d.get('lion', 'Not in the dictionary'))
print(d.get('lion', 'NA'))
print(d.get('dog', 'NA'))
Explore more about Python Dictionaries and learn interactively here...
The best way to set any feature regarding the colors of any widget is to use QPalette.
And the easiest way to find what you are looking for is to open Qt Designer and set the palette of a QLabel and check the generated code.
My feeling is 409 Conflict
is the most appropriate, however, seldom seen in the wild of course:
The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request. The response body SHOULD include enough information for the user to recognize the source of the conflict. Ideally, the response entity would include enough information for the user or user agent to fix the problem; however, that might not be possible and is not required.
Conflicts are most likely to occur in response to a PUT request. For example, if versioning were being used and the entity being PUT included changes to a resource which conflict with those made by an earlier (third-party) request, the server might use the 409 response to indicate that it can't complete the request. In this case, the response entity would likely contain a list of the differences between the two versions in a format defined by the response Content-Type.
If you want to pull a particular file from another branch just do
git checkout branch1 -- filenamefoo.txt
This will pull a version of the file from one branch into the current tree
Take a look at Blaze-Persistence Entity Views which works on top of JPA and provides first class DTO support. You can project anything to attributes within Entity Views and it will even reuse existing join nodes for associations if possible.
Here is an example mapping
@EntityView(Order.class)
interface OrderSummary {
Integer getId();
@Mapping("SUM(orderPositions.price * orderPositions.amount * orderPositions.tax)")
BigDecimal getOrderAmount();
@Mapping("COUNT(orderPositions)")
Long getItemCount();
}
Fetching this will generate a JPQL/HQL query similar to this
SELECT
o.id,
SUM(p.price * p.amount * p.tax),
COUNT(p.id)
FROM
Order o
LEFT JOIN
o.orderPositions p
GROUP BY
o.id
Here is a blog post about custom subquery providers which might be interesting to you as well: https://blazebit.com/blog/2017/entity-view-mapping-subqueries.html
fs-extra adds file system methods that aren't included in the native fs module. It is a drop in replacement for fs.
Install fs-extra
$ npm install --save fs-extra
const fs = require("fs-extra");
// Make sure the output directory is there.
fs.ensureDirSync(newDest);
There are sync and async options.
https://github.com/jprichardson/node-fs-extra/blob/master/docs/ensureDir.md
contentType
option to false
is used for multipart/form-data
forms that pass files.
When one sets the contentType
option to false
, it forces jQuery not to add a Content-Type header, otherwise, the boundary string will be missing from it. Also, when submitting files via multipart/form-data, one must leave the processData
flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.
Use jQuery's .serialize()
method which creates a text string in standard URL-encoded notation.
You need to pass un-encoded data when using contentType: false
.
Try using new FormData
instead of .serialize():
var formData = new FormData($(this)[0]);
See for yourself the difference of how your formData is passed to your php page by using console.log()
.
var formData = new FormData($(this)[0]);
console.log(formData);
var formDataSerialized = $(this).serialize();
console.log(formDataSerialized);
I whipped this up and saw it might be useful for some. (Yes, CoffeeScript. Sue me.)
app.directive 'times', ->
link: (scope, element, attrs) ->
repeater = element.html()
scope.$watch attrs.times, (value) ->
element.html ''
return unless value?
element.html Array(value + 1).join(repeater)
To use:
<div times="customer.conversations_count">
<i class="icon-picture></i>
</div>
Can this get any simpler?
I'm wary about filters because Angular likes to re-evaluate them for no good reason all the time, and it's a huge bottleneck if you have thousands of them like I do.
This directive will even watch for changes in your model, and update the element accordingly.
From the OData documentation:
The OData Protocol is an application-level protocol for interacting with data via RESTful web services.
...
The OData Protocol is different from other REST-based web service approaches in that it provides a uniform way to describe both the data and the data model.
So because pod update SomePod
touches everything in the latest versions of cocoapods, I found a workaround.
Follow the next steps:
Remove SomePod
from the Podfile
Run pod install
pods will now remove SomePod
from our project and from the Podfile.lock
file.
Put back SomePod
into the Podfile
Run pod install
again
This time the latest version of our pod will be installed and saved in the Podfile.lock
.
Os X Mojave 10.14 has:
Error: The Command Line Tools header package must be installed on Mojave.
Solution. Go to
/Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg
location and install the package manually. And brew will start working and we can run:
brew uninstall --force git
brew cleanup --force -s git
brew prune
brew install git
You can run the packager on another port.
$ react-native start --port=8088
Alternatively, find out what is using which ports on Windows with netstat.
$ netstat -a -b -o
Netstat gives you a PID, which you can use to kill the process.
$ taskkill /pid 1234
availabletobindon() {
port="$1"
nc -w 2 -i 1 localhost "$port" 2>&1 | grep -v -q 'Idle timeout expired'
return "$?"
}
select @EmpID = ID from dbo.Employee
Or
set @EmpID =(select id from dbo.Employee)
Note that the select query might return more than one value or rows. so you can write a select query that must return one row.
If you would like to add more columns to one variable(MS SQL), there is an option to use table defined variable
DECLARE @sampleTable TABLE(column1 type1)
INSERT INTO @sampleTable
SELECT columnsNumberEqualInsampleTable FROM .. WHERE ..
As table type variable do not exist in Oracle and others, you would have to define it:
DECLARE TYPE type_name IS TABLE OF (column_type | variable%TYPE | table.column%TYPE [NOT NULL] INDEX BY BINARY INTEGER;
-- Then to declare a TABLE variable of this type: variable_name type_name;
-- Assigning values to a TABLE variable: variable_name(n).field_name := 'some text'
;
-- Where 'n' is the index value
In order to make the canvas full screen width and height always, meaning even when the browser is resized, you need to run your draw loop within a function that resizes the canvas to the window.innerHeight and window.innerWidth.
Example: http://jsfiddle.net/jaredwilli/qFuDr/
<canvas id="canvas"></canvas>
(function() {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d');
// resize the canvas to fill browser window dynamically
window.addEventListener('resize', resizeCanvas, false);
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
/**
* Your drawings need to be inside this function otherwise they will be reset when
* you resize the browser window and the canvas goes will be cleared.
*/
drawStuff();
}
resizeCanvas();
function drawStuff() {
// do your drawing stuff here
}
})();
* { margin:0; padding:0; } /* to remove the top and left whitespace */
html, body { width:100%; height:100%; } /* just to be sure these are full screen*/
canvas { display:block; } /* To remove the scrollbars */
That is how you properly make the canvas full width and height of the browser. You just have to put all the code for drawing to the canvas in the drawStuff() function.
If you have problems like that, first of all your TC
folder put in to the C:..drive.
after completing installation open turbo c blue screen.
there is a OPTIONS > Directories
..in that you can see for option to set up path..
C:\TC\INCUDE
C:\TC\LIB
C:\TC\BIN
..otherwise you can set another path where you want to store your output..Finally you can give OK and finished processes.. It will now work properly
Alternatively, if you're working in .NET v4.5 or above, try using System.Web.MimeMapping.GetMimeMapping(yourFileName) to get MIME types. It is much better than hard-coding strings.
original (not mine) post here
For special permissions, such as android.Manifest.permission.PACKAGE_USAGE_STATS
used AppOpsManager
:
Kotlin
private fun hasPermission(permission:String, permissionAppOpsManager:String): Boolean {
var granted = false
if (VERSION.SDK_INT >= VERSION_CODES.M) {
// requires kitkat
val appOps = applicationContext!!.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
// requires lollipop
val mode = appOps.checkOpNoThrow(permissionAppOpsManager,
android.os.Process.myUid(), applicationContext!!.packageName)
if (mode == AppOpsManager.MODE_DEFAULT) {
granted = applicationContext!!.checkCallingOrSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
} else {
granted = mode == AppOpsManager.MODE_ALLOWED
}
}
return granted
}
and anywhere in code:
val permissionAppOpsManager = AppOpsManager.OPSTR_GET_USAGE_STATS
val permission = android.Manifest.permission.PACKAGE_USAGE_STATS
val permissionActivity = Settings.ACTION_USAGE_ACCESS_SETTINGS
if (hasPermission(permission, permissionAppOpsManager)) {
Timber.i("has permission: $permission")
// do here what needs permission
} else {
Timber.e("has no permission: $permission")
// start activity to get permission
startActivity(Intent(permissionActivity))
}
Other permissions you can get with TedPermission library
Although solutions that can be found in many answers do work in Chrome, they do not work in Safari for Mac and iOS.
Safari requires an additional statement – background-clip
.
This is the full code for a solution that works across all major browsers on different platforms:
/* Disable autofill highlighting */
input:-webkit-autofill {
-webkit-text-fill-color: var(--text-input-color) !important;
-webkit-box-shadow: 0 0 0 1rem var(--page-background-color) inset !important;
background-clip: content-box !important;
}
(Please change the --text-input-color
and --page-background-color
with your own values.)
Its really helped me to dynamically generate ids of showDetailItem
for the below code.
<af:forEach id="fe1" items="#{viewScope.bean.tranTypeList}" var="ttf" varStatus="ttfVs" >
<af:showDetailItem id ="divIDNo${ttfVs.count}" text="#{ttf.trandef}"......>
if you execute this line <af:outputText value="#{ttfVs}"/>
prints the below:
{index=3, count=4, last=false, first=false, end=8, step=1, begin=0}
Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.
UPD 19.03.2019 Here is a version for browser on GitHub.
Assuming it is OK that the operation is not atomic, you can do:
if (std::ifstream(name))
{
std::cout << "File already exists" << std::endl;
return false;
}
std::ofstream file(name);
if (!file)
{
std::cout << "File could not be created" << std::endl;
return false;
}
...
Note that this doesn't work if you run multiple threads trying to create the same file, and certainly will not prevent a second process from "interfering" with the file creation because you have TOCTUI problems. [We first check if the file exists, and then create it - but someone else could have created it in between the check and the creation - if that's critical, you will need to do something else, which isn't portable].
A further problem is if you have permissions such as the file is not readable (so we can't open it for read) but is writeable, it will overwrite the file.
In MOST cases, neither of these things matter, because all you care about is telling someone that "you already have a file like that" (or something like that) in a "best effort" approach.
For MacOS sierra (maybe from Mac OS X yosemate),
To get epoch time(Seconds from 1970) from a file, and save it to a var:
old_dt=`date -j -r YOUR_FILE "+%s"`
To get epoch time of current time
new_dt=`date -j "+%s"`
To calculate difference of above two epoch time
(( diff = new_dt - old_dt ))
To check if diff is more than 23 days
(( new_dt - old_dt > (23*86400) )) && echo Is more than 23 days
If you are testing single characters, then:
var isDigit = (function() {
var re = /^\d$/;
return function(c) {
return re.test(c);
}
}());
will return true or false depending on whether c is a digit or not.
Your EditText
should be wrapped in a TextInputLayout
<android.support.design.widget.TextInputLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/tilEmail">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="@+id/etEmail"
android:hint="Email"
android:layout_marginTop="10dp"
/>
</android.support.design.widget.TextInputLayout>
To get an error message like you wanted, set error to TextInputLayout
TextInputLayout tilEmail = (TextInputLayout) findViewById(R.id.tilEmail);
if (error){
tilEmail.setError("Invalid email id");
}
You should add design support library dependency. Add this line in your gradle dependencies
compile 'com.android.support:design:22.2.0'
Interestingly enough I tried both of these in LinqPad and the variant using group from Dmitry Gribkov by appears to be quicker. (also the final distinct is not required as the result is already distinct.
My (somewhat simple) code was:
public class Pair
{
public int id {get;set;}
public string Arb {get;set;}
}
void Main()
{
var theList = new List<Pair>();
var randomiser = new Random();
for (int count = 1; count < 10000; count++)
{
theList.Add(new Pair
{
id = randomiser.Next(1, 50),
Arb = "not used"
});
}
var timer = new Stopwatch();
timer.Start();
var distinct = theList.GroupBy(c => c.id).Select(p => p.First().id);
timer.Stop();
Debug.WriteLine(timer.Elapsed);
timer.Start();
var otherDistinct = theList.Select(p => p.id).Distinct();
timer.Stop();
Debug.WriteLine(timer.Elapsed);
}
You should investigate why VBA can't find queryname.
I have a saved query named qryAddLoginfoRow. It inserts a row with the current time into my loginfo table. That query runs successfully when called by name by CurrentDb.Execute
.
CurrentDb.Execute "qryAddLoginfoRow"
My guess is that either queryname is a variable holding the name of a query which doesn't exist in the current database's QueryDefs collection, or queryname is the literal name of an existing query but you didn't enclose it in quotes.
Edit:
You need to find a way to accept that queryname does not exist in the current db's QueryDefs collection. Add these 2 lines to your VBA code just before the CurrentDb.Execute
line.
Debug.Print "queryname = '" & queryname & "'"
Debug.Print CurrentDb.QueryDefs(queryname).Name
The second of those 2 lines will trigger run-time error 3265, "Item not found in this collection." Then go to the Immediate window to verify the name of the query you're asking CurrentDb
to Execute
.
Do this :
<script type="text/javascript"> function showDetails(username) { window.location = '/player_detail?username='+username; } </script> <input type="button" name="theButton" value="Detail" onclick="showDetails('username');">
You cannot (should not?) define anything as undefined, as the variable would no longer be undefined – you just defined it to something.
You cannot (should not?) pass undefined
to a function. If you want to pass an empty value, use null
instead.
The statement if(!testvar)
checks for boolean true/false values, this particular one tests whether testvar
evaluates to false
. By definition, null
and undefined
shouldn't be evaluated neither as true
or false
, but JavaScript evaluates null
as false
, and gives an error if you try to evaluate an undefined variable.
To properly test for undefined
or null
, use these:
if(typeof(testvar) === "undefined") { ... }
if(testvar === null) { ... }
Yes, I would use explode or you could use:
preg_split
Which is the advised method with PHP 6. preg_split Documentation
This is meant to supplement my Objective-C answer for Swift users, to keep the Objective-C answer from getting too big.
First, set up the in-app purchase on appstoreconnect.apple.com. Follow the beginning part of my Objective-C answer (steps 1-13, under the App Store Connect header) for instructions on doing that.
It could take a few hours for your product ID to register in App Store Connect, so be patient.
Now that you've set up your in-app purchase information on App Store Connect, we need to add Apple's framework for in-app-purchases, StoreKit
, to the app.
Go into your Xcode project, and go to the application manager (blue page-like icon at the top of the left bar where your app's files are). Click on your app under targets on the left (it should be the first option), then go to "Capabilities" at the top. On the list, you should see an option "In-App Purchase". Turn this capability ON, and Xcode will add StoreKit
to your project.
Now, we're going to start coding!
First, make a new swift file that will manage all of your in-app-purchases. I'm going to call it IAPManager.swift
.
In this file, we're going to create a new class, called IAPManager
that is a SKProductsRequestDelegate
and SKPaymentTransactionObserver
. At the top, make sure you import Foundation
and StoreKit
import Foundation
import StoreKit
public class IAPManager: NSObject, SKProductsRequestDelegate,
SKPaymentTransactionObserver {
}
Next, we're going to add a variable to define the identifier for our in-app purchase (you could also use an enum
, which would be easier to maintain if you have multiple IAPs).
// This should the ID of the in-app-purchase you made on AppStore Connect.
// if you have multiple IAPs, you'll need to store their identifiers in
// other variables, too (or, preferably in an enum).
let removeAdsID = "com.skiplit.removeAds"
Let's add an initializer for our class next:
// This is the initializer for your IAPManager class
//
// A better, and more scaleable way of doing this
// is to also accept a callback in the initializer, and call
// that callback in places like the paymentQueue function, and
// in all functions in this class, in place of calls to functions
// in RemoveAdsManager (you'll see those calls in the code below).
let productID: String
init(productID: String){
self.productID = productID
}
Now, we're going to add the required functions for SKProductsRequestDelegate
and SKPaymentTransactionObserver
to work:
We'll add the RemoveAdsManager
class later
// This is called when a SKProductsRequest receives a response
public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse){
// Let's try to get the first product from the response
// to the request
if let product = response.products.first{
// We were able to get the product! Make a new payment
// using this product
let payment = SKPayment(product: product)
// add the new payment to the queue
SKPaymentQueue.default().add(self)
SKPaymentQueue.default().add(payment)
}
else{
// Something went wrong! It is likely that either
// the user doesn't have internet connection, or
// your product ID is wrong!
//
// Tell the user in requestFailed() by sending an alert,
// or something of the sort
RemoveAdsManager.removeAdsFailure()
}
}
// This is called when the user restores their IAP sucessfully
private func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue){
// For every transaction in the transaction queue...
for transaction in queue.transactions{
// If that transaction was restored
if transaction.transactionState == .restored{
// get the producted ID from the transaction
let productID = transaction.payment.productIdentifier
// In this case, we have only one IAP, so we don't need to check
// what IAP it is. However, this is useful if you have multiple IAPs!
// You'll need to figure out which one was restored
if(productID.lowercased() == IAPManager.removeAdsID.lowercased()){
// Restore the user's purchases
RemoveAdsManager.restoreRemoveAdsSuccess()
}
// finish the payment
SKPaymentQueue.default().finishTransaction(transaction)
}
}
}
// This is called when the state of the IAP changes -- from purchasing to purchased, for example.
// This is where the magic happens :)
public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]){
for transaction in transactions{
// get the producted ID from the transaction
let productID = transaction.payment.productIdentifier
// In this case, we have only one IAP, so we don't need to check
// what IAP it is.
// However, if you have multiple IAPs, you'll need to use productID
// to check what functions you should run here!
switch transaction.transactionState{
case .purchasing:
// if the user is currently purchasing the IAP,
// we don't need to do anything.
//
// You could use this to show the user
// an activity indicator, or something like that
break
case .purchased:
// the user successfully purchased the IAP!
RemoveAdsManager.removeAdsSuccess()
SKPaymentQueue.default().finishTransaction(transaction)
case .restored:
// the user restored their IAP!
IAPTestingHandler.restoreRemoveAdsSuccess()
SKPaymentQueue.default().finishTransaction(transaction)
case .failed:
// The transaction failed!
RemoveAdsManager.removeAdsFailure()
// finish the transaction
SKPaymentQueue.default().finishTransaction(transaction)
case .deferred:
// This happens when the IAP needs an external action
// in order to proceeded, like Ask to Buy
RemoveAdsManager.removeAdsDeferred()
break
}
}
}
Now let's add some functions that can be used to start a purchase or a restore purchases:
// Call this when you want to begin a purchase
// for the productID you gave to the initializer
public func beginPurchase(){
// If the user can make payments
if SKPaymentQueue.canMakePayments(){
// Create a new request
let request = SKProductsRequest(productIdentifiers: [productID])
// Set the request delegate to self, so we receive a response
request.delegate = self
// start the request
request.start()
}
else{
// Otherwise, tell the user that
// they are not authorized to make payments,
// due to parental controls, etc
}
}
// Call this when you want to restore all purchases
// regardless of the productID you gave to the initializer
public func beginRestorePurchases(){
// restore purchases, and give responses to self
SKPaymentQueue.default().add(self)
SKPaymentQueue.default().restoreCompletedTransactions()
}
Next, let's add a new utilities class to manage our IAPs. All of this code could be in one class, but having it multiple makes it a little cleaner. I'm going to make a new class called RemoveAdsManager
, and in it, put a few functions
public class RemoveAdsManager{
class func removeAds()
class func restoreRemoveAds()
class func areAdsRemoved() -> Bool
class func removeAdsSuccess()
class func restoreRemoveAdsSuccess()
class func removeAdsDeferred()
class func removeAdsFailure()
}
The first three functions, removeAds
, restoreRemoveAds
, and areAdsRemoved
, are functions that you'll call to do certain actions. The last four are one that will be called by IAPManager
.
Let's add some code to the first two functions, removeAds
and restoreRemoveAds
:
// Call this when the user wants
// to remove ads, like when they
// press a "remove ads" button
class func removeAds(){
// Before starting the purchase, you could tell the
// user that their purchase is happening, maybe with
// an activity indicator
let iap = IAPManager(productID: IAPManager.removeAdsID)
iap.beginPurchase()
}
// Call this when the user wants
// to restore their IAP purchases,
// like when they press a "restore
// purchases" button.
class func restoreRemoveAds(){
// Before starting the purchase, you could tell the
// user that the restore action is happening, maybe with
// an activity indicator
let iap = IAPManager(productID: IAPManager.removeAdsID)
iap.beginRestorePurchases()
}
And lastly, let's add some code to the last five functions.
// Call this to check whether or not
// ads are removed. You can use the
// result of this to hide or show
// ads
class func areAdsRemoved() -> Bool{
// This is the code that is run to check
// if the user has the IAP.
return UserDefaults.standard.bool(forKey: "RemoveAdsPurchased")
}
// This will be called by IAPManager
// when the user sucessfully purchases
// the IAP
class func removeAdsSuccess(){
// This is the code that is run to actually
// give the IAP to the user!
//
// I'm using UserDefaults in this example,
// but you may want to use Keychain,
// or some other method, as UserDefaults
// can be modified by users using their
// computer, if they know how to, more
// easily than Keychain
UserDefaults.standard.set(true, forKey: "RemoveAdsPurchased")
UserDefaults.standard.synchronize()
}
// This will be called by IAPManager
// when the user sucessfully restores
// their purchases
class func restoreRemoveAdsSuccess(){
// Give the user their IAP back! Likely all you'll need to
// do is call the same function you call when a user
// sucessfully completes their purchase. In this case, removeAdsSuccess()
removeAdsSuccess()
}
// This will be called by IAPManager
// when the IAP failed
class func removeAdsFailure(){
// Send the user a message explaining that the IAP
// failed for some reason, and to try again later
}
// This will be called by IAPManager
// when the IAP gets deferred.
class func removeAdsDeferred(){
// Send the user a message explaining that the IAP
// was deferred, and pending an external action, like
// Ask to Buy.
}
Putting it all together, we get something like this:
import Foundation
import StoreKit
public class RemoveAdsManager{
// Call this when the user wants
// to remove ads, like when they
// press a "remove ads" button
class func removeAds(){
// Before starting the purchase, you could tell the
// user that their purchase is happening, maybe with
// an activity indicator
let iap = IAPManager(productID: IAPManager.removeAdsID)
iap.beginPurchase()
}
// Call this when the user wants
// to restore their IAP purchases,
// like when they press a "restore
// purchases" button.
class func restoreRemoveAds(){
// Before starting the purchase, you could tell the
// user that the restore action is happening, maybe with
// an activity indicator
let iap = IAPManager(productID: IAPManager.removeAdsID)
iap.beginRestorePurchases()
}
// Call this to check whether or not
// ads are removed. You can use the
// result of this to hide or show
// ads
class func areAdsRemoved() -> Bool{
// This is the code that is run to check
// if the user has the IAP.
return UserDefaults.standard.bool(forKey: "RemoveAdsPurchased")
}
// This will be called by IAPManager
// when the user sucessfully purchases
// the IAP
class func removeAdsSuccess(){
// This is the code that is run to actually
// give the IAP to the user!
//
// I'm using UserDefaults in this example,
// but you may want to use Keychain,
// or some other method, as UserDefaults
// can be modified by users using their
// computer, if they know how to, more
// easily than Keychain
UserDefaults.standard.set(true, forKey: "RemoveAdsPurchased")
UserDefaults.standard.synchronize()
}
// This will be called by IAPManager
// when the user sucessfully restores
// their purchases
class func restoreRemoveAdsSuccess(){
// Give the user their IAP back! Likely all you'll need to
// do is call the same function you call when a user
// sucessfully completes their purchase. In this case, removeAdsSuccess()
removeAdsSuccess()
}
// This will be called by IAPManager
// when the IAP failed
class func removeAdsFailure(){
// Send the user a message explaining that the IAP
// failed for some reason, and to try again later
}
// This will be called by IAPManager
// when the IAP gets deferred.
class func removeAdsDeferred(){
// Send the user a message explaining that the IAP
// was deferred, and pending an external action, like
// Ask to Buy.
}
}
public class IAPManager: NSObject, SKProductsRequestDelegate, SKPaymentTransactionObserver{
// This should the ID of the in-app-purchase you made on AppStore Connect.
// if you have multiple IAPs, you'll need to store their identifiers in
// other variables, too (or, preferably in an enum).
static let removeAdsID = "com.skiplit.removeAds"
// This is the initializer for your IAPManager class
//
// An alternative, and more scaleable way of doing this
// is to also accept a callback in the initializer, and call
// that callback in places like the paymentQueue function, and
// in all functions in this class, in place of calls to functions
// in RemoveAdsManager.
let productID: String
init(productID: String){
self.productID = productID
}
// Call this when you want to begin a purchase
// for the productID you gave to the initializer
public func beginPurchase(){
// If the user can make payments
if SKPaymentQueue.canMakePayments(){
// Create a new request
let request = SKProductsRequest(productIdentifiers: [productID])
request.delegate = self
request.start()
}
else{
// Otherwise, tell the user that
// they are not authorized to make payments,
// due to parental controls, etc
}
}
// Call this when you want to restore all purchases
// regardless of the productID you gave to the initializer
public func beginRestorePurchases(){
SKPaymentQueue.default().add(self)
SKPaymentQueue.default().restoreCompletedTransactions()
}
// This is called when a SKProductsRequest receives a response
public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse){
// Let's try to get the first product from the response
// to the request
if let product = response.products.first{
// We were able to get the product! Make a new payment
// using this product
let payment = SKPayment(product: product)
// add the new payment to the queue
SKPaymentQueue.default().add(self)
SKPaymentQueue.default().add(payment)
}
else{
// Something went wrong! It is likely that either
// the user doesn't have internet connection, or
// your product ID is wrong!
//
// Tell the user in requestFailed() by sending an alert,
// or something of the sort
RemoveAdsManager.removeAdsFailure()
}
}
// This is called when the user restores their IAP sucessfully
private func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue){
// For every transaction in the transaction queue...
for transaction in queue.transactions{
// If that transaction was restored
if transaction.transactionState == .restored{
// get the producted ID from the transaction
let productID = transaction.payment.productIdentifier
// In this case, we have only one IAP, so we don't need to check
// what IAP it is. However, this is useful if you have multiple IAPs!
// You'll need to figure out which one was restored
if(productID.lowercased() == IAPManager.removeAdsID.lowercased()){
// Restore the user's purchases
RemoveAdsManager.restoreRemoveAdsSuccess()
}
// finish the payment
SKPaymentQueue.default().finishTransaction(transaction)
}
}
}
// This is called when the state of the IAP changes -- from purchasing to purchased, for example.
// This is where the magic happens :)
public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]){
for transaction in transactions{
// get the producted ID from the transaction
let productID = transaction.payment.productIdentifier
// In this case, we have only one IAP, so we don't need to check
// what IAP it is.
// However, if you have multiple IAPs, you'll need to use productID
// to check what functions you should run here!
switch transaction.transactionState{
case .purchasing:
// if the user is currently purchasing the IAP,
// we don't need to do anything.
//
// You could use this to show the user
// an activity indicator, or something like that
break
case .purchased:
// the user sucessfully purchased the IAP!
RemoveAdsManager.removeAdsSuccess()
SKPaymentQueue.default().finishTransaction(transaction)
case .restored:
// the user restored their IAP!
RemoveAdsManager.restoreRemoveAdsSuccess()
SKPaymentQueue.default().finishTransaction(transaction)
case .failed:
// The transaction failed!
RemoveAdsManager.removeAdsFailure()
// finish the transaction
SKPaymentQueue.default().finishTransaction(transaction)
case .deferred:
// This happens when the IAP needs an external action
// in order to proceeded, like Ask to Buy
RemoveAdsManager.removeAdsDeferred()
break
}
}
}
}
Lastly, you need to add some way for the user to start the purchase and call RemoveAdsManager.removeAds()
and start a restore and call RemoveAdsManager.restoreRemoveAds()
, like a button somewhere! Keep in mind that, per the App Store guidelines, you do need to provide a button to restore purchases somewhere.
The last thing to do is submit your IAP for review on App Store Connect! For detailed instructions on doing that, you can follow the last part of my Objective-C answer, under the Submitting for review header.
Try this way of formation, it is rather fancy ...
Have a look at this jsfiddle
The idea is to choose a the radio as a button instead of the normal circle image.
Warning: Checking for 'IS_AUTHENTICATED_FULLY'
alone will return false if the user has logged in using "Remember me" functionality.
According to Symfony 2 documentation, there are 3 possibilities:
IS_AUTHENTICATED_ANONYMOUSLY - automatically assigned to a user who is in a firewall protected part of the site but who has not actually logged in. This is only possible if anonymous access has been allowed.
IS_AUTHENTICATED_REMEMBERED - automatically assigned to a user who was authenticated via a remember me cookie.
IS_AUTHENTICATED_FULLY - automatically assigned to a user that has provided their login details during the current session.
Those roles represent three levels of authentication:
If you have the
IS_AUTHENTICATED_REMEMBERED
role, then you also have theIS_AUTHENTICATED_ANONYMOUSLY
role. If you have theIS_AUTHENTICATED_FULLY
role, then you also have the other two roles. In other words, these roles represent three levels of increasing "strength" of authentication.
I ran into an issue where users of our system that had used "Remember Me" functionality were being treated as if they had not logged in at all on pages that only checked for 'IS_AUTHENTICATED_FULLY'
.
The answer then is to require them to re-login if they are not authenticated fully, or to check for the remembered role:
$securityContext = $this->container->get('security.authorization_checker');
if ($securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
// authenticated REMEMBERED, FULLY will imply REMEMBERED (NON anonymous)
}
Hopefully, this will save someone out there from making the same mistake I made. I used this very post as a reference when looking up how to check if someone was logged in or not on Symfony 2.
In my case, I fixed it by butting the rules inside a LocationMatch Directive
<LocationMatch "^/.">
#your rewrite rules here
</LocationMatch>
/.
matches any location
I have the rewrite rules inside one of the .conf
files of Apache NOT .htaccess
file.
I don't know why this worked with me, this is my current setup
~/.subversion/config
or
/etc/subversion/config
for Mac/Linux
and
%appdata%\subversion\config
for Windows
I wrestled quite a while with the proper syntax for CREATE TEMPORARY TABLE SELECT. Having figured out a few things, I wanted to share the answers with the rest of the community.
Basic information about the statement is available at the following MySQL links:
CREATE TABLE SELECT and CREATE TABLE.
At times it can be daunting to interpret the spec. Since most people learn best from examples, I will share how I have created a working statement, and how you can modify it to work for you.
Add multiple indexes
This statement shows how to add multiple indexes (note that index names - in lower case - are optional):
CREATE TEMPORARY TABLE core.my_tmp_table
(INDEX my_index_name (tag, time), UNIQUE my_unique_index_name (order_number))
SELECT * FROM core.my_big_table
WHERE my_val = 1
Add a new primary key:
CREATE TEMPORARY TABLE core.my_tmp_table
(PRIMARY KEY my_pkey (order_number),
INDEX cmpd_key (user_id, time))
SELECT * FROM core.my_big_table
Create additional columns
You can create a new table with more columns than are specified in the SELECT statement. Specify the additional column in the table definition. Columns specified in the table definition and not found in select will be first columns in the new table, followed by the columns inserted by the SELECT statement.
CREATE TEMPORARY TABLE core.my_tmp_table
(my_new_id BIGINT NOT NULL AUTO_INCREMENT,
PRIMARY KEY my_pkey (my_new_id), INDEX my_unique_index_name (invoice_number))
SELECT * FROM core.my_big_table
Redefining data types for the columns from SELECT
You can redefine the data type of a column being SELECTed. In the example below, column tag is a MEDIUMINT in core.my_big_table and I am redefining it to a BIGINT in core.my_tmp_table.
CREATE TEMPORARY TABLE core.my_tmp_table
(tag BIGINT,
my_time DATETIME,
INDEX my_unique_index_name (tag) )
SELECT * FROM core.my_big_table
Advanced field definitions during create
All the usual column definitions are available as when you create a normal table. Example:
CREATE TEMPORARY TABLE core.my_tmp_table
(id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
value BIGINT UNSIGNED NOT NULL DEFAULT 0 UNIQUE,
location VARCHAR(20) DEFAULT "NEEDS TO BE SET",
country CHAR(2) DEFAULT "XX" COMMENT "Two-letter country code",
INDEX my_index_name (location))
ENGINE=MyISAM
SELECT * FROM core.my_big_table
What are the problems of static and stack?
The problem with "static" allocation is that the allocation is made at compile-time: you can't use it to allocate some variable number of data, the number of which isn't known until run-time.
The problem with allocating on the "stack" is that the allocation is destroyed as soon as the subroutine which does the allocation returns.
I could write an entire application without allocate variables in the heap?
Perhaps but not a non-trivial, normal, big application (but so-called "embedded" programs might be written without the heap, using a subset of C++).
What garbage collector does ?
It keeps watching your data ("mark and sweep") to detect when your application is no longer referencing it. This is convenient for the application, because the application doesn't need to deallocate the data ... but the garbage collector might be computationally expensive.
Garbage collectors aren't a usual feature of C++ programming.
What could you do manipulating the memory by yourself that you couldn't do using this garbage collector?
Learn the C++ mechanisms for deterministic memory deallocation:
I have tested your example, and while Request.QueryString is not convertible to a string neither implicit nor explicit still the .ToString() method returns the correct result.
Further more when concatenating with a string using the "+" operator as in your example it will also return the correct result (because this behaves as if .ToString() was called).
As such there is nothing wrong with your code, and I would suggest that your issue was because of a typo in your code writing "Querystring" instead of "QueryString".
And this makes more sense with your error message since if the problem is that QueryString is a collection and not a string it would have to give another error message.
If you are still interested, Chris Wolf made a prototype implementation of SQLite with Stored Procedures. You can find the details at his blog post: Adding Stored Procedures to SQLite
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Library
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
string query = "INSERT INTO [Table] (BookName , AuthorName , Category) VALUES('" + textBox1.Text.ToString() + "' , '" + textBox2.Text.ToString() + "' , '" + textBox3.Text.ToString() + "')";
SqlCommand com = new SqlCommand(query, con);
con.Open();
com.ExecuteNonQuery();
con.Close();
MessageBox.Show("Entry Added");
}
private void button3_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
string query = "SELECT * FROM [TABLE] WHERE BookName='" + textBox1.Text.ToString() + "' OR AuthorName='" + textBox2.Text.ToString() + "'";
string query1 = "SELECT BookStatus FROM [Table] where BookName='" + textBox1.Text.ToString() + "'";
string query2 = "SELECT DateOfReturn FROM [Table] where BookName='" + textBox1.Text.ToString() + "'";
SqlCommand com = new SqlCommand(query, con);
SqlDataReader dr, dr1,dr2;
con.Open();
com.ExecuteNonQuery();
dr = com.ExecuteReader();
if (dr.Read())
{
con.Close();
con.Open();
SqlCommand com1 = new SqlCommand(query1, con);
com1.ExecuteNonQuery();
dr1 = com1.ExecuteReader();
dr1.Read();
string i = dr1["BookStatus"].ToString();
if (i =="1" )
{
con.Close();
con.Open();
SqlCommand com2 = new SqlCommand(query2, con);
com2.ExecuteNonQuery();
dr2 = com2.ExecuteReader();
dr2.Read();
MessageBox.Show("This book is already issued\n " + "Book will be available by "+ dr2["DateOfReturn"] );
}
else
{
con.Close();
con.Open();
dr = com.ExecuteReader();
dr.Read();
MessageBox.Show("BookFound\n" + "BookName=" + dr["BookName"] + "\n AuthorName=" + dr["AuthorName"]);
}
con.Close();
}
else
{
MessageBox.Show("This Book is not available in the library");
}
}
private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
string query = "SELECT * FROM [TABLE] WHERE BookName='" + textBox1.Text.ToString() + "'";
string dateofissue1 = DateTime.Today.ToString("dd-MM-yyyy");
string dateofreturn = DateTime.Today.AddDays(15).ToString("dd-MM-yyyy");
string query1 = "update [Table] set BookStatus=1,DateofIssue='"+ dateofissue1 +"',DateOfReturn='"+ dateofreturn +"' where BookName='" + textBox1.Text.ToString() + "'";
con.Open();
SqlCommand com = new SqlCommand(query, con);
SqlDataReader dr;
com.ExecuteNonQuery();
dr = com.ExecuteReader();
if (dr.Read())
{
con.Close();
con.Open();
string dateofissue = DateTime.Today.ToString("dd-MM-yyyy");
textBox4.Text = dateofissue;
textBox5.Text = DateTime.Today.AddDays(15).ToString("dd-MM-yyyy");
SqlCommand com1 = new SqlCommand(query1, con);
com1.ExecuteNonQuery();
MessageBox.Show("Book Isuued");
}
else
{
MessageBox.Show("Book Not Found");
}
con.Close();
}
private void button4_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
string query1 = "update [Table] set BookStatus=0 WHERE BookName='"+textBox1.Text.ToString()+"'";
con.Open();
SqlCommand com = new SqlCommand(query1, con);
com.ExecuteNonQuery();
string today = DateTime.Today.ToString("dd-MM-yyyy");
DateTime today1 = DateTime.Parse(today);
string query = "SELECT dateofReturn from [Table] where BookName='" + textBox1.Text.ToString() + "'";
con.Close();
con.Open();
SqlDataReader dr;
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
dr = cmd.ExecuteReader();
dr.Read();
string DOR = dr["DateOfReturn"].ToString();
DateTime dor = DateTime.Parse(DOR);
TimeSpan ts = today1.Subtract(dor);
string query2 = "update [Table] set DateOfIssue=NULL, DateOfReturn=NULL WHERE BookName='" + textBox1.Text.ToString() + "'";
con.Close();
con.Open();
SqlCommand com2 = new SqlCommand(query2, con);
com2.ExecuteNonQuery();
int x = int.Parse(ts.Days.ToString());
if (x > 0)
{
int fine = x * 5;
textBox6.Text = fine.ToString();
MessageBox.Show("Book Received\nFine=" + fine);
}
else
{
textBox6.Text = "0";
MessageBox.Show("Book Received\nFine=0");
}
con.Close();
}
}
}
Using header file stdio.h
you can easily do it as usual like c. before using %.2lf(set a specific number after % specifier.) using printf().
It simply printf specific digits after decimal point.
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
double total=100;
printf("%.2lf",total);//this prints 100.00 like as C
}
Swift 5 version of the solution
func myCriticalFunction() {
var value1: String?
var value2: String?
let group = DispatchGroup()
group.enter()
//async operation 1
DispatchQueue.global(qos: .default).async {
// Network calls or some other async task
value1 = //out of async task
group.leave()
}
group.enter()
//async operation 2
DispatchQueue.global(qos: .default).async {
// Network calls or some other async task
value2 = //out of async task
group.leave()
}
group.wait()
print("Value1 \(value1) , Value2 \(value2)")
}
If you go to the Flat file connection manager under Advanced and Look at the "OutputColumnWidth" description's ToolTip It will tell you that Composit characters may use more spaces. So the "é" in "Société" most likely occupies more than one character.
EDIT: Here's something about it: http://en.wikipedia.org/wiki/Precomposed_character
According to Apache Tomcat 7 JNDI Datasource HOW-TO page there must be a resource configuration in web.xml:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/TestDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
That works for me
The solution using flexbox without justify-content: space-between
.
<div class="title">
<span>Cumulative performance</span>
<span>20/02/2011</span>
</div>
.title {
display: flex;
}
span:first-of-type {
flex: 1;
}
When we use flex:1
on the first <span>
, it takes up the entire remaining space and moves the second <span>
to the right. The Fiddle with this solution: https://jsfiddle.net/2k1vryn7/
Here https://jsfiddle.net/7wvx2uLp/3/ you can see the difference between two flexbox approaches: flexbox with justify-content: space-between
and flexbox with flex:1
on the first <span>
.
in your PyCharm project:
+
button to install additional python modulesI was in your shoes for a while and finally ended up using node.js, because it can do hybrid solutions like having web and socket server in one. So php backend can submit requests thru http to node web server and then broadcast it with websocket. Very efficiant way to go.
For the complete system you can add the Microsoft.VisualBasic Framework as a reference;
Console.WriteLine("You have {0} bytes of RAM",
new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory);
Console.ReadLine();
-X [your method]
X lets you override the default 'Get'
** corrected lowercase x
to uppercase X
Simple URL :
https://www.google.com/maps/dir/?api=1&destination=lat,lng
This url is specific for routing.
Reference : https://developers.google.com/maps/documentation/urls/guide#directions-action
=VLOOKUP(LEFT(A4,LEN(A4)-9),$D:$F,3,0)
I use this if my Lookup_Value
needs to be truncated because of the format the name is in the Table_Array. E.g. my Lookup_Value
is "Eastbay District", but the Table_Array
list I have only shows this as "Eastbay". "Eastbay District" minus 9 characters will result in "Eastbay".
I hope this helps!
$(function () {
$('<div>').dialog({
modal: true,
open: function ()
{
$(this).load('Sample.htm');
},
height: 400,
width: 400,
title: 'Dynamically Loaded Page'
});
});
http://www.devcurry.com/2010/06/load-page-dynamically-inside-jquery-ui.html
Here are the steps to get the Hardware Accelerated Execution (HAX) which is really quite a lot:
1-check your processor Intel website to see if it supports Intel VT-x or not: http://ark.intel.com/Products/VirtualizationTechnology all Intel Core i processors and some other selected processors support Intel VT-x
2- check your bios to enable Intel VT-x , usually called hardware virtualization or Intel virtualization in bios
3- check if you are using a software conflicting with HAXM, popular software conflicting with haxm include but not limited to:
Hyper-V
Windows phone SDK 8
Avast antivirus 8
4-install Intel management engine interface (MEI), this driver is usually not installed and is not part of retailer Windows DVD, even Windows 8. Check this post about how to install: http://communities.intel.com/community/vproexpert/blog/2011/12/19/mei-driver-now-available-via-microsoft-windows-update This driver is required and is not optional to activate Hardware Acceleration you can also install it from windows update
5-use android SDK manager to download Extras -> Intel x86 Hardware Accelerated Execution Manager.
6-Run installer of HAXM from: [Android SDK Root]\extras\intel\Hardware_Accelerated_Execution_Manager\IntelHaxm.exe
if you passed the previous steps the installer will work just fine ,otherwise it will fail
7-start AVD and see the difference in performance, Animations are faster System UI and launchers crashes in 4.0.3 but are just fine for 4.2.2
see installation guide by intel:
You mean the ASCII ordinal value? Try type casting like this one:
int x = 'a';
Tomcat 7 Ubuntu Server 12.04 LTS:
tail -f /var/log/tomcat7/catalina.out
Interestingly I checked this on an app of mine and I got the same error.
I spent a while checking through headers to see if there was anything undef'ing the _USE_MATH_DEFINES
and found nothing.
So I moved the
#define _USE_MATH_DEFINES
#include <cmath>
to be the first thing in my file (I don't use PCHs so if you are you will have to have it after the #include "stdafx.h"
) and suddenly it compile perfectly.
Try moving it higher up the page. Totally unsure as to why this would cause issues though.
Edit: Figured it out. The #include <math.h>
occurs within cmath's header guards. This means that something higher up the list of #includes is including cmath
without the #define
specified. math.h
is specifically designed so that you can include it again with that define now changed to add M_PI
etc. This is NOT the case with cmath
. So you need to make sure you #define _USE_MATH_DEFINES
before you include anything else. Hope that clears it up for you :)
Failing that just include math.h
you are using non-standard C/C++ as already pointed out :)
Edit 2: Or as David points out in the comments just make yourself a constant that defines the value and you have something more portable anyway :)
You need to plug it into the task scheduler, such that it is launched after login of a user, using a user account that has administrative access on the system, with the highest privileges that are afforded to processes launched by that account.
This is the implementation that is used to autostart processes with administrative privileges when logging in as an ordinary user.
I've used it to launch the 'OpenVPN GUI' helper process which needs elevated privileges to work correctly, and thus would not launch properly from the registry key.
From the command line, you can create the task from an XML description of what you want to accomplish; so for example we have this, exported from my system, which would start notepad with the highest privileges when i log in:
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<RegistrationInfo>
<Date>2015-01-27T18:30:34</Date>
<Author>Pete</Author>
</RegistrationInfo>
<Triggers>
<LogonTrigger>
<StartBoundary>2015-01-27T18:30:00</StartBoundary>
<Enabled>true</Enabled>
</LogonTrigger>
</Triggers>
<Principals>
<Principal id="Author">
<UserId>CHUMBAWUMBA\Pete</UserId>
<LogonType>InteractiveToken</LogonType>
<RunLevel>HighestAvailable</RunLevel>
</Principal>
</Principals>
<Settings>
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
<AllowHardTerminate>true</AllowHardTerminate>
<StartWhenAvailable>false</StartWhenAvailable>
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
<IdleSettings>
<StopOnIdleEnd>true</StopOnIdleEnd>
<RestartOnIdle>false</RestartOnIdle>
</IdleSettings>
<AllowStartOnDemand>true</AllowStartOnDemand>
<Enabled>true</Enabled>
<Hidden>false</Hidden>
<RunOnlyIfIdle>false</RunOnlyIfIdle>
<WakeToRun>false</WakeToRun>
<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
<Priority>7</Priority>
</Settings>
<Actions Context="Author">
<Exec>
<Command>"c:\windows\system32\notepad.exe"</Command>
</Exec>
</Actions>
</Task>
and it's registered by an administrator command prompt using:
schtasks /create /tn "start notepad on login" /xml startnotepad.xml
this answer should really be moved over to one of the other stackexchange sites, as it's not actually a programming question per se.
To avoid problems of side effects after changing env
, especially using multiple nodes, it is better to set a temporary context.
One safe way to alter the environment is:
withEnv(['MYTOOL_HOME=/usr/local/mytool']) {
sh '$MYTOOL_HOME/bin/start'
}
This approach does not poison the env after the command execution.
You should read Supporting multiple screens. You must define dpi on your emulator. 240 is hdpi, 160 is mdpi and below that are usually ldpi.
Extract from Android Developer Guide link above:
320dp: a typical phone screen (240x320 ldpi, 320x480 mdpi, 480x800 hdpi, etc).
480dp: a tweener tablet like the Streak (480x800 mdpi).
600dp: a 7” tablet (600x1024 mdpi).
720dp: a 10” tablet (720x1280 mdpi, 800x1280 mdpi, etc).
Try with this piece of code.
.ui-datepicker{ z-index:1151 !important; }
will solve the problem when you are using bootstrap V3
<div (mouseenter)="changeText=true" (mouseout)="changeText=false">
<span *ngIf="!changeText">Hide</span>
<span *ngIf="changeText">Show</span>
</div>
and if you want to use in *ngFor then assign the object value of hover data and then check its id and show hover info/icon or anything like that:-
<div (mouseenter)="hoverCard(d)" (mouseleave)="hoverCard(null)" *ngFor="let d of data" class="col-lg-3 col-md-4 col-sm-6 mt-4">
<a *ngIf="hoverData && hoverData.id == d.id" class="text-right"><i class="fas fa-edit"></i>Hover Text</a>
Normal Text
</div>
in TS File
hoverData!:Data|null;
hoverCard(d: Data|null){
this.hoverData = sCatg;
}
More readable way of achieving this (not a fan of single line ansible tasks)
- local_action:
module: copy
content: "{{ foo_result }}"
dest: /path/to/destination/file
I've solved it, it can be done executing:
netsh interface portproxy add v4tov4 listenport=4422 listenaddress=192.168.1.111 connectport=80 connectaddress=192.168.0.33
To remove forwarding:
netsh interface portproxy delete v4tov4 listenport=4422 listenaddress=192.168.1.111
To elaborate on Ignacio Vazquez-Abrams's answer:
The Python import mechanism works relative to the __name__
of the current file. When you execute a file directly, it doesn't have its usual name, but has "__main__"
as its name instead. So relative imports don't work.
You can, as Igancio suggested, execute it using the -m
option. If you have a part of your package that is meant to be run as a script, you can also use the __package__
attribute to tell that file what name it's supposed to have in the package hierarchy.
See http://www.python.org/dev/peps/pep-0366/ for details.
I used the below statement to retrieve the values in the XML in the Sql table
with xmlnamespaces(default 'http://test.com/2008/06/23/HL.OnlineContract.ValueObjects')
select * from (
select
OnlineContractID,
DistributorID,
SponsorID,
[RequestXML].value(N'/OnlineContractDS[1]/Properties[1]/Name[1]', 'nvarchar(30)') as [Name]
,[RequestXML].value(N'/OnlineContractDS[1]/Properties[1]/Value[1]', 'nvarchar(30)') as [Value]
,[RequestXML].value(N'/OnlineContractDS[1]/Locale[1]', 'nvarchar(30)') as [Locale]
from [OnlineContract]) as olc
where olc.Name like '%EMAIL%' and olc.Value like '%EMAIL%' and olc.Locale='UK EN'
Simply put:
SELECT *
FROM TABLE_NAME
WHERE
dob > '1/21/2012'
Where 1/21/2012 is the date and you want all data, including that date.
SELECT *
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'
Use a between if you're selecting time between two dates
Update: With PostgreSQL 9.5, there are some jsonb
manipulation functionality within PostgreSQL itself (but none for json
; casts are required to manipulate json
values).
Merging 2 (or more) JSON objects (or concatenating arrays):
SELECT jsonb '{"a":1}' || jsonb '{"b":2}', -- will yield jsonb '{"a":1,"b":2}'
jsonb '["a",1]' || jsonb '["b",2]' -- will yield jsonb '["a",1,"b",2]'
So, setting a simple key can be done using:
SELECT jsonb '{"a":1}' || jsonb_build_object('<key>', '<value>')
Where <key>
should be string, and <value>
can be whatever type to_jsonb()
accepts.
For setting a value deep in a JSON hierarchy, the jsonb_set()
function can be used:
SELECT jsonb_set('{"a":[null,{"b":[]}]}', '{a,1,b,0}', jsonb '{"c":3}')
-- will yield jsonb '{"a":[null,{"b":[{"c":3}]}]}'
Full parameter list of jsonb_set()
:
jsonb_set(target jsonb,
path text[],
new_value jsonb,
create_missing boolean default true)
path
can contain JSON array indexes too & negative integers that appear there count from the end of JSON arrays. However, a non-existing, but positive JSON array index will append the element to the end of the array:
SELECT jsonb_set('{"a":[null,{"b":[1,2]}]}', '{a,1,b,1000}', jsonb '3', true)
-- will yield jsonb '{"a":[null,{"b":[1,2,3]}]}'
For inserting into JSON array (while preserving all of the original values), the jsonb_insert()
function can be used (in 9.6+; this function only, in this section):
SELECT jsonb_insert('{"a":[null,{"b":[1]}]}', '{a,1,b,0}', jsonb '2')
-- will yield jsonb '{"a":[null,{"b":[2,1]}]}', and
SELECT jsonb_insert('{"a":[null,{"b":[1]}]}', '{a,1,b,0}', jsonb '2', true)
-- will yield jsonb '{"a":[null,{"b":[1,2]}]}'
Full parameter list of jsonb_insert()
:
jsonb_insert(target jsonb,
path text[],
new_value jsonb,
insert_after boolean default false)
Again, negative integers that appear in path
count from the end of JSON arrays.
So, f.ex. appending to an end of a JSON array can be done with:
SELECT jsonb_insert('{"a":[null,{"b":[1,2]}]}', '{a,1,b,-1}', jsonb '3', true)
-- will yield jsonb '{"a":[null,{"b":[1,2,3]}]}', and
However, this function is working slightly differently (than jsonb_set()
) when the path
in target
is a JSON object's key. In that case, it will only add a new key-value pair for the JSON object when the key is not used. If it's used, it will raise an error:
SELECT jsonb_insert('{"a":[null,{"b":[1]}]}', '{a,1,c}', jsonb '[2]')
-- will yield jsonb '{"a":[null,{"b":[1],"c":[2]}]}', but
SELECT jsonb_insert('{"a":[null,{"b":[1]}]}', '{a,1,b}', jsonb '[2]')
-- will raise SQLSTATE 22023 (invalid_parameter_value): cannot replace existing key
Deleting a key (or an index) from a JSON object (or, from an array) can be done with the -
operator:
SELECT jsonb '{"a":1,"b":2}' - 'a', -- will yield jsonb '{"b":2}'
jsonb '["a",1,"b",2]' - 1 -- will yield jsonb '["a","b",2]'
Deleting, from deep in a JSON hierarchy can be done with the #-
operator:
SELECT '{"a":[null,{"b":[3.14]}]}' #- '{a,1,b,0}'
-- will yield jsonb '{"a":[null,{"b":[]}]}'
For 9.4, you can use a modified version of the original answer (below), but instead of aggregating a JSON string, you can aggregate into a json object directly with json_object_agg()
.
Original answer: It is possible (without plpython or plv8) in pure SQL too (but needs 9.3+, will not work with 9.2)
CREATE OR REPLACE FUNCTION "json_object_set_key"(
"json" json,
"key_to_set" TEXT,
"value_to_set" anyelement
)
RETURNS json
LANGUAGE sql
IMMUTABLE
STRICT
AS $function$
SELECT concat('{', string_agg(to_json("key") || ':' || "value", ','), '}')::json
FROM (SELECT *
FROM json_each("json")
WHERE "key" <> "key_to_set"
UNION ALL
SELECT "key_to_set", to_json("value_to_set")) AS "fields"
$function$;
Edit:
A version, which sets multiple keys & values:
CREATE OR REPLACE FUNCTION "json_object_set_keys"(
"json" json,
"keys_to_set" TEXT[],
"values_to_set" anyarray
)
RETURNS json
LANGUAGE sql
IMMUTABLE
STRICT
AS $function$
SELECT concat('{', string_agg(to_json("key") || ':' || "value", ','), '}')::json
FROM (SELECT *
FROM json_each("json")
WHERE "key" <> ALL ("keys_to_set")
UNION ALL
SELECT DISTINCT ON ("keys_to_set"["index"])
"keys_to_set"["index"],
CASE
WHEN "values_to_set"["index"] IS NULL THEN 'null'::json
ELSE to_json("values_to_set"["index"])
END
FROM generate_subscripts("keys_to_set", 1) AS "keys"("index")
JOIN generate_subscripts("values_to_set", 1) AS "values"("index")
USING ("index")) AS "fields"
$function$;
Edit 2: as @ErwinBrandstetter noted these functions above works like a so-called UPSERT
(updates a field if it exists, inserts if it does not exist). Here is a variant, which only UPDATE
:
CREATE OR REPLACE FUNCTION "json_object_update_key"(
"json" json,
"key_to_set" TEXT,
"value_to_set" anyelement
)
RETURNS json
LANGUAGE sql
IMMUTABLE
STRICT
AS $function$
SELECT CASE
WHEN ("json" -> "key_to_set") IS NULL THEN "json"
ELSE (SELECT concat('{', string_agg(to_json("key") || ':' || "value", ','), '}')
FROM (SELECT *
FROM json_each("json")
WHERE "key" <> "key_to_set"
UNION ALL
SELECT "key_to_set", to_json("value_to_set")) AS "fields")::json
END
$function$;
Edit 3: Here is recursive variant, which can set (UPSERT
) a leaf value (and uses the first function from this answer), located at a key-path (where keys can only refer to inner objects, inner arrays not supported):
CREATE OR REPLACE FUNCTION "json_object_set_path"(
"json" json,
"key_path" TEXT[],
"value_to_set" anyelement
)
RETURNS json
LANGUAGE sql
IMMUTABLE
STRICT
AS $function$
SELECT CASE COALESCE(array_length("key_path", 1), 0)
WHEN 0 THEN to_json("value_to_set")
WHEN 1 THEN "json_object_set_key"("json", "key_path"[l], "value_to_set")
ELSE "json_object_set_key"(
"json",
"key_path"[l],
"json_object_set_path"(
COALESCE(NULLIF(("json" -> "key_path"[l])::text, 'null'), '{}')::json,
"key_path"[l+1:u],
"value_to_set"
)
)
END
FROM array_lower("key_path", 1) l,
array_upper("key_path", 1) u
$function$;
Updated: Added function for replacing an existing json field's key by another given key. Can be in handy for updating data types in migrations or other scenarios like data structure amending.
CREATE OR REPLACE FUNCTION json_object_replace_key(
json_value json,
existing_key text,
desired_key text)
RETURNS json AS
$BODY$
SELECT COALESCE(
(
SELECT ('{' || string_agg(to_json(key) || ':' || value, ',') || '}')
FROM (
SELECT *
FROM json_each(json_value)
WHERE key <> existing_key
UNION ALL
SELECT desired_key, json_value -> existing_key
) AS "fields"
-- WHERE value IS NOT NULL (Actually not required as the string_agg with value's being null will "discard" that entry)
),
'{}'
)::json
$BODY$
LANGUAGE sql IMMUTABLE STRICT
COST 100;
Update: functions are compacted now.
If you are using Ubuntu
with Apache+php5
, then on current versions there are 2 places where you need to change to short_open_tag = On
/etc/php5/apache2/php.ini
- this is for the pages loaded through your web server (Apache)/etc/php5/cli/php.ini
- this configuration is used when you launch your php files from command line, like: php yourscript.php
- that goes for manually or cronjob executed php files directly on the server.A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.
Consider the following code:
void Foo(int i, float f)
{
// Do things
}
void Bar()
{
int anInt = 1;
Foo(anInt, 2.0);
}
Here i
and f
are the parameters, and anInt
and 2.0
are the arguments.
ES—Shorter
[...element.parentNode.children].indexOf(element);
The spread Operator is a shortcut for that
Global variables that are defined outside of any method or closure can be scope restricted by using the private keyword.
import UIKit
// MARK: Local Constants
private let changeSegueId = "MasterToChange"
private let bookSegueId = "MasterToBook"
Just keep in mind there are 2 spaces between Aug and 26. Other wise your find command will not work.
find . -type f -exec ls -l {} \; | egrep "Aug 26";
I solved this by writing a debounce decorator. The problem described could be solved by applying the @debounceAccessor to the property's set accessor.
I've also supplied an additional debounce decorator for methods, which can be useful for other occasions.
This makes it very easy to debounce a property or a method. The parameter is the number of milliseconds the debounce should last, 100 ms in the example below.
@debounceAccessor(100)
set myProperty(value) {
this._myProperty = value;
}
@debounceMethod(100)
myMethod (a, b, c) {
let d = a + b + c;
return d;
}
And here's the code for the decorators:
function debounceMethod(ms: number, applyAfterDebounceDelay = false) {
let timeoutId;
return function (target: Object, propName: string, descriptor: TypedPropertyDescriptor<any>) {
let originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
if (timeoutId) return;
timeoutId = window.setTimeout(() => {
if (applyAfterDebounceDelay) {
originalMethod.apply(this, args);
}
timeoutId = null;
}, ms);
if (!applyAfterDebounceDelay) {
return originalMethod.apply(this, args);
}
}
}
}
function debounceAccessor (ms: number) {
let timeoutId;
return function (target: Object, propName: string, descriptor: TypedPropertyDescriptor<any>) {
let originalSetter = descriptor.set;
descriptor.set = function (...args: any[]) {
if (timeoutId) return;
timeoutId = window.setTimeout(() => {
timeoutId = null;
}, ms);
return originalSetter.apply(this, args);
}
}
}
I added an additional parameter for the method decorator which let's you trigger the method AFTER the debounce delay. I did that so I could for instance use it when coupled with mouseover or resize events, where I wanted the capturing to occur at the end of the event stream. In this case however, the method won't return a value.
Try using reduce
or inject
.
[1, 2, 3].reduce([]) { |memo, i|
if i % 2 == 0
memo << i
end
memo
}
I agree with the accepted answer that we shouldn't map
and compact
, but not for the same reasons.
I feel deep inside that map
then compact
is equivalent to select
then map
. Consider: map
is a one-to-one function. If you are mapping from some set of values, and you map
, then you want one value in the output set for each value in the input set. If you are having to select
before-hand, then you probably don't want a map
on the set. If you are having to select
afterwards (or compact
) then you probably don't want a map
on the set. In either case you are iterating twice over the entire set, when a reduce
only needs to go once.
Also, in English, you are trying to "reduce a set of integers into a set of even integers".
I Following this thought to guide the development object-oriented Perl.
Bless associate any data structure reference with a class. Given how Perl creates the inheritance structure (in a kind of tree) it is easy to take advantage of the object model to create Objects for composition.
For this association we called object, to develop always have in mind that the internal state of the object and class behaviours are separated. And you can bless/allow any data reference to use any package/class behaviours. Since the package can understand "the emotional" state of the object.
You can remove the existing options by using the empty
method, and then add your new options:
var option = $('<option></option>').attr("value", "option value").text("Text");
$("#selectId").empty().append(option);
If you have your new options in an object you can:
var newOptions = {"Option 1": "value1",
"Option 2": "value2",
"Option 3": "value3"
};
var $el = $("#selectId");
$el.empty(); // remove old options
$.each(newOptions, function(key,value) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
Edit: For removing the all the options but the first, you can use the :gt
selector, to get all the option
elements with index greater than zero and remove
them:
$('#selectId option:gt(0)').remove(); // remove all options, but not the first
I second that.
Dex2jar will generate a WORKING jar, which you can add as your project source, with the xmls you got from apktool.
However, JDGUI generates .java files which have ,more often than not, errors.
It has got something to do with code obfuscation I guess.
Here is what worked for me:
Context:
Building a project on a server
git status
returns a HEAD detached at <commit-SHA>
What ever operation I did locally, I had this error. More specifically:
Solution
<work-dir>/.git/index
. git status
would indicate that all files in the projet are not tracked (no surprise here).git reset HEAD --hard
HEAD detached at <commit-SHA>
when doing a git status
, but then you should be able togit checkout <some-branch>
and you're back on track!
!! IMPORTANT !!
This works only because I am "merly" building. No precious modification has been performed on the code. If you are actually in "dev-time", then I would recommand to save your work first or go for another method.
Hope it will help :).
In Python 3,
def filter_nonprintable(text):
import itertools
# Use characters of control category
nonprintable = itertools.chain(range(0x00,0x20),range(0x7f,0xa0))
# Use translate to remove all non-printable characters
return text.translate({character:None for character in nonprintable})
See this StackOverflow post on removing punctuation for how .translate() compares to regex & .replace()
The ranges can be generated via nonprintable = (ord(c) for c in (chr(i) for i in range(sys.maxunicode)) if unicodedata.category(c)=='Cc')
using the Unicode character database categories as shown by @Ants Aasma.
We can specify how we have to join the string. Instead of '-', we can use ' '
sentence = ['this','is','a','sentence']
s=(" ".join(sentence))
print(s)
i have same issue this work fine for me
<style>
td{
word-break: break-word;
}
</style>
<table style="width: 100%;">
<tr>
<td>Loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong word</td>
<td><span style="display: inline;">Short word</span></td>
</tr>
</table>
Since you're using asp.net code-behind, add an id to the element and runat=server.
You can then reference the objects in the code behind.
Check out this article and this simple example. Quick translation of same to your classes ...
var d1 = typeof(Task<>);
Type[] typeArgs = { typeof(Item) };
var makeme = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(makeme);
Per your edit: For that case, you can do this ...
var d1 = Type.GetType("GenericTest.TaskA`1"); // GenericTest was my namespace, add yours
Type[] typeArgs = { typeof(Item) };
var makeme = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(makeme);
To see where I came up with backtick1 for the name of the generic class, see this article.
Note: if your generic class accepts multiple types, you must include the commas when you omit the type names, for example:
Type type = typeof(IReadOnlyDictionary<,>);
You can probably use:
os.environ.get('USERNAME')
or
os.environ.get('USER')
But it's not going to be safe because environment variables can be changed.
A polyfill is a shim which replaces the original call with the call to a shim.
For example, say you want to use the navigator.mediaDevices object, but not all browsers support this. You could imagine a library that provided a shim which you might use like this:
<script src="js/MediaShim.js"></script>
<script>
MediaShim.mediaDevices.getUserMedia(...);
</script>
In this case, you are explicitly calling a shim instead of using the original object or method. The polyfill, on the other hand, replaces the objects and methods on the original objects.
For example:
<script src="js/adapter.js"></script>
<script>
navigator.mediaDevices.getUserMedia(...);
</script>
In your code, it looks as though you are using the standard navigator.mediaDevices object. But really, the polyfill (adapter.js in the example) has replaced this object with its own one.
The one it has replaced it with is a shim. This will detect if the feature is natively supported and use it if it is, or it will work around it using other APIs if it is not.
So a polyfill is a sort of "transparent" shim. And this is what Remy Sharp (who coined the term) meant when saying "if you removed the polyfill script, your code would continue to work, without any changes required in spite of the polyfill being removed".
Using flexbox:
HTML:
<div class="wrapper">
<img src="pikachu.gif"/>
</div>
CSS:
.wrapper {
height: 300px;
width: 300px;
display: flex;
align-items: flex-end;
}
As requested in some comments on another answer, the image can also be horizontally centred with justify-content: center;
how to change background color in html & css with class
example:
on html you write
<div class="pad_menu">
</div>
on css
.pad_menu {
padding: 100px;
background-color: #A9FFCB;
}
so your background will be change to Magic Mint, if you want to know the code of the color, i suggest you visit https://coolors.co. Hope this useful :)
json_decode()
will return an object or array if second value it's true:
$json = '{"countryId":"84","productId":"1","status":"0","opId":"134"}';
$json = json_decode($json, true);
echo $json['countryId'];
echo $json['productId'];
echo $json['status'];
echo $json['opId'];
git reset --hard origin/master
will remove all commits not in origin/master
where origin
is the repo name and master
is the name of the branch.
Use the power of Python and lean on one of the best libraries around: requests
import requests
r = requests.get('https://my.website.com/rest/path', auth=('myusername', 'mybasicpass'))
print(r.text)
Variable r (requests response) has a lot more parameters that you can use. Best thing is to pop into the interactive interpreter and play around with it, and/or read requests docs.
ubuntu@hostname:/home/ubuntu$ python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> r = requests.get('https://my.website.com/rest/path', auth=('myusername', 'mybasicpass'))
>>> dir(r)
['__attrs__', '__bool__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_content', '_content_consumed', 'apparent_encoding', 'close', 'connection', 'content', 'cookies', 'elapsed', 'encoding', 'headers', 'history', 'iter_content', 'iter_lines', 'json', 'links', 'ok', 'raise_for_status', 'raw', 'reason', 'request', 'status_code', 'text', 'url']
>>> r.content
b'{"battery_status":0,"margin_status":0,"timestamp_status":null,"req_status":0}'
>>> r.text
'{"battery_status":0,"margin_status":0,"timestamp_status":null,"req_status":0}'
>>> r.status_code
200
>>> r.headers
CaseInsensitiveDict({'x-powered-by': 'Express', 'content-length': '77', 'date': 'Fri, 20 May 2016 02:06:18 GMT', 'server': 'nginx/1.6.3', 'connection': 'keep-alive', 'content-type': 'application/json; charset=utf-8'})
If you don't have avahi installed then it's probably cups.
https://github.com/abdmob/x2js - my own library (updated URL from http://code.google.com/p/x2js/):
This library provides XML to JSON (JavaScript Objects) and vice versa javascript conversion functions. The library is very small and doesn't require any other additional libraries.
API functions
- new X2JS() - to create your instance to access all library functionality. Also you could specify optional configuration options here
- X2JS.xml2json - Convert XML specified as DOM Object to JSON
- X2JS.json2xml - Convert JSON to XML DOM Object
- X2JS.xml_str2json - Convert XML specified as string to JSON
- X2JS.json2xml_str - Convert JSON to XML string
Online Demo on http://jsfiddle.net/abdmob/gkxucxrj/1/
var x2js = new X2JS();
function convertXml2JSon() {
$("#jsonArea").val(JSON.stringify(x2js.xml_str2json($("#xmlArea").val())));
}
function convertJSon2XML() {
$("#xmlArea").val(x2js.json2xml_str($.parseJSON($("#jsonArea").val())));
}
convertXml2JSon();
convertJSon2XML();
$("#convertToJsonBtn").click(convertXml2JSon);
$("#convertToXmlBtn").click(convertJSon2XML);
to indent a ul
dropdown menu, use
/* Main Level */
ul{
margin-left:10px;
}
/* Second Level */
ul ul{
margin-left:15px;
}
/* Third Level */
ul ul ul{
margin-left:20px;
}
/* and so on... */
You can indent the li
s and (if applicable) the a
s (or whatever content elements you have) as well , each with differing effects.
You could also use padding-left
instead of margin-left
, again depending on the effect you want.
Update
By default, many browsers use padding-left
to set the initial indentation. If you want to get rid of that, set padding-left: 0px;
Still, both margin-left
and padding-left
settings impact the indentation of lists in different ways. Specifically: margin-left
impacts the indentation on the outside of the element's border, whereas padding-left
affects the spacing on the inside of the element's border. (Learn more about the CSS box model here)
Setting padding-left: 0;
leaves the li's bullet icons hanging over the edge of the element's border (at least in Chrome), which may or may not be what you want.
Examples of padding-left vs margin-left and how they can work together on ul: https://jsfiddle.net/daCrosby/bb7kj8cr/1/
With so many great answers, I thought I would toss one more into the mix. This one, unlike the others, would permit you to cycle through any number of messages with ease:
var index = 0,
messg = [
"PUSH ME",
"DON'T PUSH ME",
"I'M SO CONFUSED!"
];
$(".pushme").on("click", function() {
$(this).text(function(index, text){
index = $.inArray(text, messg);
return messg[++index % messg.length];
});
}??????????????????????????????????????????????);?
\0
is zero character. In C
it is mostly used to indicate the termination of a character string. Of course it is a regular character and may be used as such but this is rarely the case.
The simpler versions of the built-in string manipulation functions in C
require that your string is null-terminated(or ends with \0
).
Here are examples for Delete and Put for React & redux & ReduxThunk with Firebase:
Update (PUT):
export const updateProduct = (id, title, description, imageUrl) => {
await fetch(`https://FirebaseProjectName.firebaseio.com/products/${id}.json`, {
method: "PATCH",
header: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title,
description,
imageUrl,
}),
});
dispatch({
type: "UPDATE_PRODUCT",
pid: id,
productData: {
title,
description,
imageUrl,
},
});
};
};
Delete:
export const deleteProduct = (ProductId) => {
return async (dispatch) => {
await fetch(
`https://FirebaseProjectName.firebaseio.com/products/${ProductId}.json`,
{
method: "DELETE",
}
);
dispatch({
type: "DELETE_PRODUCT",
pid: ProductId,
});
};
};
window.onload = function ()
{
var select = document.getElementById('selectBox');
var delButton = document.getElementById('delete');
function remove()
{
value = select.selectedIndex;
select.removeChild(select[value]);
}
delButton.onclick = remove;
}
To add the item I would create second select box and:
var select2 = document.getElementById('selectBox2');
var addSelect = document.getElementById('addSelect');
function add()
{
value1 = select2.selectedIndex;
select.appendChild(select2[value1]);
}
addSelect.onclick = add;
Not jQuery though.
Yes you need javascript. The simplest way is to just put this at the bottom of your HTML page:
<script type="text/javascript">
alert("Hello world");
</script>
There are more preferred methods, like using jQuery's ready function, but this method will work.
If you use a website and you fill out a form to submit information (your social security number for example) you want to be sure that the information is being sent to the site you think it's being sent to. So browsers were built to say, by default, 'Do not send information to a domain other than the domain being visited).
Eventually that became too limiting but the default idea still remains in browsers. Don't let the web page send information to a different domain. But this is all browser checking. Chrome and firefox, etc have built in code that says 'before send this request, we're going to check that the destination matches the page being visited'.
Postman (or CURL on the cmd line) doesn't have those built in checks. You're manually interacting with a site so you have full control over what you're sending.
The modern approach uses the java.time classes.
YearMonth.from(
ZonedDateTime.parse(
"Mon Mar 14 16:02:37 GMT 2011" ,
DateTimeFormatter.ofPattern( "E MMM d HH:mm:ss z uuuu" )
)
).toString()
2011-03
The modern way is with java.time classes. The old date-time classes such as Calendar
have proven to be poorly-designed, confusing, and troublesome.
Define a custom formatter to match your string input.
String input = "Mon Mar 14 16:02:37 GMT 2011";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "E MMM d HH:mm:ss z uuuu" );
Parse as a ZonedDateTime
.
ZonedDateTime zdt = ZonedDateTime.parse( input , f );
You are interested in the year and month. The java.time classes include YearMonth
class for that purpose.
YearMonth ym = YearMonth.from( zdt );
You can interrogate for the year and month numbers if needed.
int year = ym.getYear();
int month = ym.getMonthValue();
But the toString
method generates a string in standard ISO 8601 format.
String output = ym.toString();
Put this all together.
String input = "Mon Mar 14 16:02:37 GMT 2011";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "E MMM d HH:mm:ss z uuuu" );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );
YearMonth ym = YearMonth.from( zdt );
int year = ym.getYear();
int month = ym.getMonthValue();
Dump to console.
System.out.println( "input: " + input );
System.out.println( "zdt: " + zdt );
System.out.println( "ym: " + ym );
input: Mon Mar 14 16:02:37 GMT 2011
zdt: 2011-03-14T16:02:37Z[GMT]
ym: 2011-03
See this code running in IdeOne.com.
If you must have a Calendar
object, you can convert to a GregorianCalendar
using new methods added to the old classes.
GregorianCalendar gc = GregorianCalendar.from( zdt );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Error in file(file, "rt") :
I just faced the same error and resolved by removing spacing in address using paste0 instead of paste
filepath=paste0(directory,"/",filename[1],sep="")
Try this
{% if var in ['foo', 'bar', 'beer'] %}
...
{% endif %}
If both the list are too big and when we use lamda expression then it will take a long time to fetch . Better to use linq in this case to fetch parameters list:
var items = (from x in parameters
join y in myStrings on x.Source equals y
select x)
.ToList();
Although everyone answer "No" and I know that "No" is the right answer but if you really need to get local variables of a function there is a restricted way.
Consider this function:
var f = function() {
var x = 0;
console.log(x);
};
You can convert your function to a string:
var s = f + '';
You will get source of function as a string
'function () {\nvar x = 0;\nconsole.log(x);\n}'
Now you can use a parser like esprima to parse function code and find local variable declarations.
var s = 'function () {\nvar x = 0;\nconsole.log(x);\n}';
s = s.slice(12); // to remove "function () "
var esprima = require('esprima');
var result = esprima.parse(s);
and find objects with:
obj.type == "VariableDeclaration"
in the result (I have removed console.log(x)
below):
{
"type": "Program",
"body": [
{
"type": "VariableDeclaration",
"declarations": [
{
"type": "VariableDeclarator",
"id": {
"type": "Identifier",
"name": "x"
},
"init": {
"type": "Literal",
"value": 0,
"raw": "0"
}
}
],
"kind": "var"
}
]
}
I have tested this in Chrome, Firefox and Node.
But the problem with this method is that you just have the variables defined in the function itself. For example for this one:
var g = function() {
var y = 0;
var f = function() {
var x = 0;
console.log(x);
};
}
you just have access to the x and not y. But still you can use chains of caller (arguments.callee.caller.caller.caller) in a loop to find local variables of caller functions. If you have all local variable names so you have scope variables. With the variable names you have access to values with a simple eval.
You can also get it by
string(//bookstore/book[1]/title/@lang)
string(//bookstore/book[2]/title/@lang)
although if you are using XMLDOM with JavaScript you can code something like
var n1 = uXmlDoc.selectSingleNode("//bookstore/book[1]/title/@lang");
and n1.text
will give you the value "eng"
If you create your database in direct admin or cpanel, you must edit your sql with notepad or notepad++ and change CREATE DATABASE
command to CREATE DATABASE IF NOT EXISTS
in line22
var countries = new Array();
countries[0] = 'ga';
countries[1] = 'cd';
after that you can do like:
var new_countries = countries.join(',')
after:
$.ajax({
type: "POST",
url: "Concessions.aspx/GetConcessions",
data: new_countries,
...
This thing work as JSON string format.
here is the solution:
#wrapper {
width: 500px;
border: 1px solid black;
overflow: auto; /* so the size of the wrapper is alway the size of the longest content */
}
#first {
float: left;
width: 300px;
border: 1px solid red;
}
#second {
border: 1px solid green;
margin: 0 0 0 302px; /* considering the border you need to use a margin so the content does not float under the first div*/
}
your demo updated;
Using System.Environment.NewLine is the only solution that worked for me. When I tried \r\n, it just repeated the actual \r\n in the text box.
Just use the following command if you wanna set configuration in system level:
$ sudo git config --system user.name "my_name"
Expanding on what others have said I will give a short example.
If you have a 1D array ...
>>> import numpy as np
>>> x = np.arange(4) # array([0, 1, 2, 3])
>>> x[::-1] # returns a view
Out[1]:
array([3, 2, 1, 0])
But if you are working with a 2D array ...
>>> x = np.arange(10).reshape(2, 5)
>>> x
Out[2]:
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
>>> x[::-1] # returns a view:
Out[3]: array([[5, 6, 7, 8, 9],
[0, 1, 2, 3, 4]])
This does not actually reverse the Matrix.
Should use np.flip to actually reverse the elements
>>> np.flip(x)
Out[4]: array([[9, 8, 7, 6, 5],
[4, 3, 2, 1, 0]])
If you want to print the elements of a matrix one-by-one use flat along with flip
>>> for el in np.flip(x).flat:
>>> print(el, end = ' ')
9 8 7 6 5 4 3 2 1 0
My guess is:
SELECT LastName + ', ' + FirstName AS 'FullName'
FROM customers
GROUP BY LastName + ', ' + FirstName
Oracle has a similar limitation, which is annoying. I'm curious if there exists a better solution.
To answer the second half of the question, this limitation applies to more complex expressions such as your case statement as well. The best suggestion I've seen it to use a sub-select to name the complex expression.
Select cell B2 and click "Freeze Panes" this will freeze Row 1 and Column A.
For future reference, selecting Freeze Panes in Excel will freeze the rows above your selected cell and the columns to the left of your selected cell. For example, to freeze rows 1 and 2 and column A, you could select cell B3 and click Freeze Panes. You could also freeze columns A and B and row 1, by selecting cell C2 and clicking "Freeze Panes".
Visual Aid on Freeze Panes in Excel 2010 - http://www.dummies.com/how-to/content/how-to-freeze-panes-in-an-excel-2010-worksheet.html
Microsoft Reference Guide (More Complicated, but resourceful none the less) - http://office.microsoft.com/en-us/excel-help/freeze-or-lock-rows-and-columns-HP010342542.aspx
I would suggest the following:
String[] parsedInput = str.split("\n"); String firstName = parsedInput[0].split(": ")[1]; String lastName = parsedInput[1].split(": ")[1]; myMap.put(firstName,lastName);
Edit: atp's answer below is better. Please use that one!
You might have an easier time, if you're looking for a specific list of files, putting them directly on the command line instead:
# rsync -avP -e ssh `cat deploy/rsync_include.txt` [email protected]:/var/www/
This is assuming, however, that your list isn't so long that the command line length will be a problem and that the rsync_include.txt
file contains just real paths (i.e. no comments, and no regexps).
Are you using Forms authentication?
Forms authentication uses it own value for timeout (30 min. by default). A forms authentication timeout will send the user to the login page with the session still active. This may look like the behavior your app gives when session times out making it easy to confuse one with the other.
<system.web>
<authentication mode="Forms">
<forms timeout="50"/>
</authentication>
<sessionState timeout="60" />
</system.web>
Setting the forms timeout to something less than the session timeout can give the user a window in which to log back in without losing any session data.
If you don't want to go ModelBinding way, you can use DTOs to do this for you. For example, create a POST action in DataLayer which accepts a complex type and send data from the BusinessLayer. You can do it in case of UI->API call.
Here are sample DTO. Assign a Teacher to a Student and Assign multiple papers/subject to the Student.
public class StudentCurriculumDTO
{
public StudentTeacherMapping StudentTeacherMapping { get; set; }
public List<Paper> Paper { get; set; }
}
public class StudentTeacherMapping
{
public Guid StudentID { get; set; }
public Guid TeacherId { get; set; }
}
public class Paper
{
public Guid PaperID { get; set; }
public string Status { get; set; }
}
Then the action in the DataLayer can be created as:
[HttpPost]
[ActionName("MyActionName")]
public async Task<IHttpActionResult> InternalName(StudentCurriculumDTO studentData)
{
//Do whatever.... insert the data if nothing else!
}
To call it from the BusinessLayer:
using (HttpResponseMessage response = await client.PostAsJsonAsync("myendpoint_MyActionName", dataof_StudentCurriculumDTO)
{
//Do whatever.... get response if nothing else!
}
Now this will still work if I wan to send data of multiple Student at once. Modify the MyAction
like below. No need to write [FromBody], WebAPI2 takes the complex type [FromBody] by default.
public async Task<IHttpActionResult> InternalName(List<StudentCurriculumDTO> studentData)
and then while calling it, pass a List<StudentCurriculumDTO>
of data.
using (HttpResponseMessage response = await client.PostAsJsonAsync("myendpoint_MyActionName", List<dataof_StudentCurriculumDTO>)
I had a similar issue so I found a workaround (remove hyperlink tags thanks to regular expressions so that only a paragraph tag remains). I posted this solution on https://github.com/python-openxml/python-docx/issues/85 BP
Your should really use the INFORMATION_SCHEMA
views in your database:
USE <your_database_name>
GO
SELECT * FROM INFORMATION_SCHEMA.TABLES
You can then filter that by table schema and/or table type, e.g.
SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'
The following is what this would look like inside of .draggable({});
$("#yourDraggable").draggable({
revert: "invalid" ,
start: function(){
$(this).css("opacity",0.3);
},
stop: function(){
$(this).draggable( 'disable' )
},
opacity: 0.7,
helper: function () {
$copy = $(this).clone();
$copy.css({
"list-style":"none",
"width":$(this).outerWidth()
});
return $copy;
},
appendTo: 'body',
scroll: false
});
The apache commons lang package provides such a class which can be used to build up a default toString() method using reflection to get the values of fields. Just have a look at this.
Solution I have json object which has data
[{"name":"Ata","email":"[email protected]"}]
You can use following approach to iterate through ng-repeat and use table format instead of list.
<div class="container" ng-controller="fetchdataCtrl">
<ul ng-repeat="item in numbers">
<li>
{{item.name}}: {{item.email}}
</li>
</ul>
</div>
This is what worked for me on Windows. The cause being multiple python installations
python -m pip uninstall pip setuptools
I faced the same issue recently. I found a solution that apparently works for all devices. You can't do async focus programmatically but you can switch focus to your target input when some other input is already focused. So what you need to do is create, hide, append to DOM & focus a fake input on trigger event and, when the async action completes, just call focus again on the target input. Here's an example snippet - run it on your mobile.
edit:
Here's a fiddle with the same code. Apparently you can't run attached snippets on mobiles (or I'm doing something wrong).
var $triggerCheckbox = $("#trigger-checkbox");_x000D_
var $targetInput = $("#target-input");_x000D_
_x000D_
// Create fake & invisible input_x000D_
var $fakeInput = $("<input type='text' />")_x000D_
.css({_x000D_
position: "absolute",_x000D_
width: $targetInput.outerWidth(), // zoom properly (iOS)_x000D_
height: 0, // hide cursor (font-size: 0 will zoom to quarks level) (iOS)_x000D_
opacity: 0, // make input transparent :]_x000D_
});_x000D_
_x000D_
var delay = 2000; // That's crazy long, but good as an example_x000D_
_x000D_
$triggerCheckbox.on("change", function(event) {_x000D_
// Disable input when unchecking trigger checkbox (presentational purpose)_x000D_
if (!event.target.checked) {_x000D_
return $targetInput_x000D_
.attr("disabled", true)_x000D_
.attr("placeholder", "I'm disabled");_x000D_
}_x000D_
_x000D_
// Prepend to target input container and focus fake input_x000D_
$fakeInput.prependTo("#container").focus();_x000D_
_x000D_
// Update placeholder (presentational purpose)_x000D_
$targetInput.attr("placeholder", "Wait for it...");_x000D_
_x000D_
// setTimeout, fetch or any async action will work_x000D_
setTimeout(function() {_x000D_
_x000D_
// Shift focus to target input_x000D_
$targetInput_x000D_
.attr("disabled", false)_x000D_
.attr("placeholder", "I'm alive!")_x000D_
.focus();_x000D_
_x000D_
// Remove fake input - no need to keep it in DOM_x000D_
$fakeInput.remove();_x000D_
}, delay);_x000D_
});
_x000D_
label {_x000D_
display: block;_x000D_
margin-top: 20px;_x000D_
}_x000D_
_x000D_
input {_x000D_
box-sizing: border-box;_x000D_
font-size: inherit;_x000D_
}_x000D_
_x000D_
#container {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
#target-input {_x000D_
width: 250px;_x000D_
padding: 10px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<div id="container">_x000D_
<input type="text" id="target-input" placeholder="I'm disabled" />_x000D_
_x000D_
<label>_x000D_
<input type="checkbox" id="trigger-checkbox" />_x000D_
focus with setTimetout_x000D_
</label>_x000D_
</div>
_x000D_
Plain JavaScript:
var e = document.getElementById("elementId");
var value = e.options[e.selectedIndex].value;
var text = e.options[e.selectedIndex].text;
jQuery:
$("#elementId :selected").text(); // The text content of the selected option
$("#elementId :selected").val(); // The value of the selected option
AngularJS: (http://jsfiddle.net/qk5wwyct):
// HTML
<select ng-model="selectItem" ng-options="item as item.text for item in items">
</select>
<p>Text: {{selectItem.text}}</p>
<p>Value: {{selectItem.value}}</p>
// JavaScript
$scope.items = [{
value: 'item_1_id',
text: 'Item 1'
}, {
value: 'item_2_id',
text: 'Item 2'
}];
in controller just convert json data to object using json_decode php function like this
$member = json_decode($json_string);
and pass to view in view
return view('page',compact('$member'))
in view blade
Member ID: {{$member->member[0]->id}}
Firstname: {{$member->member[0]->firstname}}
Lastname: {{$member->member[0]->lastname}}
Phone: {{$member->member[0]->phone}}
Owner ID: {{$member->owner[0]->id}}
Firstname: {{$member->owner[0]->firstname}}
Lastname: {{$member->owner[0]->lastname}}
If resharper is completely missing from the options menu, it could be because the extension itself has been disabled.
In Visual Studio 2017 ReSharper 2018.X.X can be enabled and disabled by going to Help
> Manage Visual Studio Performance
. Then select JetBrains ReSharper ...
under Extensions
.
In Visual Studio 2019, you would go under Extensions->Manage Extensions->Installed
Copy your XML schema here & get the JSON schema code to the online tools which are available to generate JSON schema from XML schema.
Look at the r.status_code
attribute:
if r.status_code == 404:
# A 404 was issued.
Demo:
>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404
If you want requests
to raise an exception for error codes (4xx or 5xx), call r.raise_for_status()
:
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "requests/models.py", line 664, in raise_for_status
raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.
You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:
if r:
# successful response
If you want to be more explicit, use if r.ok:
.
Set it with a px value. Changing the code like below should work
el.css('marginLeft', mrg + 'px');
String paddedString = org.apache.commons.lang.StringUtils.leftPad("129018", 10, "0")
the second parameter is the desired output length
"0" is the padding char
You haven't actually asked a question, but assuming you have one, this could be your answer...
Assuming all characters, except the "Special Characters" are allowed you can write
String regex = "^[^<>'\"/;`%]*$";
When the DLL was created an import lib is usually automatically created and you should use that linked in to your program along with header files to call it but if not then you can manually call windows functions like LoadLibrary and GetProcAddress to get it working.
I'm using Compact Framework 3.5, and not has a "char.Parse" method. I think is not bad to use the Convert class. (See CLR via C#, Jeffrey Richter)
char letterA = Convert.ToChar(65);
Console.WriteLine(letterA);
letterA = '?';
ushort valueA = Convert.ToUInt16(letterA);
Console.WriteLine(valueA);
char japaneseA = Convert.ToChar(valueA);
Console.WriteLine(japaneseA);
Works with ASCII char or Unicode char
I assume you're talking about on the command-line - if it's in a script, then a new-line acts as a command delimiter.
On the command line, use a semi-colon ';'
The base64 encoding of Content-Type: multipart/form-data
adds an extra 33% overhead. If the server supports it, it is more efficient to send the files directly:
$http.post
Requests Directly from a FileList$scope.upload = function(url, fileList) {
var config = {
headers: { 'Content-Type': undefined },
transformResponse: angular.identity
};
var promises = fileList.map(function(file) {
return $http.post(url, file, config);
});
return $q.all(promises);
};
When sending a POST with a File object, it is important to set 'Content-Type': undefined
. The XHR send method will then detect the File object and automatically set the content type.
ng-model
1The <input type=file>
element does not by default work with the ng-model directive. It needs a custom directive:
angular.module("app",[]);
angular.module("app").directive("selectNgFiles", function() {
return {
require: "ngModel",
link: function postLink(scope,elem,attrs,ngModel) {
elem.on("change", function(e) {
var files = elem[0].files;
ngModel.$setViewValue(files);
})
}
}
});
_x000D_
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
<h1>AngularJS Input `type=file` Demo</h1>
<input type="file" select-ng-files ng-model="fileList" multiple>
<h2>Files</h2>
<div ng-repeat="file in fileList">
{{file.name}}
</div>
</body>
_x000D_
I would highly recommend Open rico. It is difficult to implement in the the beginning, but once you grab it you will never look back.
If you're working with SQL Developer, you have to put the dbms_view in lowercase. The rest compiled fine for me although I haven't called the procedure from code yet.
CREATE OR REPLACE PROCEDURE "MAT_VIEW_FOO_TBL" AS
BEGIN
dbms_mview.refresh('v_materialized_foo_tbl');
END;
What does the letter 'N' on a relationship line in an Entity Relationship diagram mean? Any number
M:N
M - ordinality - describes the minimum (ordinal vs mandatory)
N - cardinality - describes the miximum
1:N (n=0,1,2,3...) one to zero or more
M:N (m and n=0,1,2,3...) zero or more to zero or more (many to many)
1:1 one to one
Find more here: https://www.smartdraw.com/entity-relationship-diagram/
I had same issue using different dependancy what helped me is to set scope to compile.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>compile</scope>
</dependency>
You could do:
df['C'] = df.sum(axis=1)
If you only want to do numerical values:
df['C'] = df.sum(axis=1, numeric_only=True)
SQL Server Express does not come with profiler, but you can use SQL Server 2005/2008 Express Profiler instead.
In your DbContext, create a default constructor for your DbContext and inherit the base like this:
public myDbContext()
: base("MyConnectionString") // connectionstring name define in your web.config
{
}
for those looking for a DESC ... this seems to work --sort=-
ty for the formatting, new to this ...my eyes are loosing some of it's bloodshot
git for-each-ref --format='%(color:cyan)%(authordate:format:%m/%d/%Y %I:%M %p) %(align:25,left)%(color:yellow)%(authorname)%(end) %(color:reset)%(refname:strip=3)' --sort=-authordate refs/remotes
further ref: https://stackoverflow.com/a/5188364/10643471
$(function() {
$("#demo").val('hello');
});
Separate with commas:
http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505
or:
http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505
or:
http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505
Either way, your method signature needs to be:
@RequestMapping(value = "/GetJson", method = RequestMethod.GET)
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
//code to get results from db for those params.
}
Here is a crude way to do it: Transform JSON into bash
variables to eval
them.
This only works for:
Well, yes, it uses PERL to do this job, thanks to CPAN, but is small enough for inclusion directly into a script and hence is quick and easy to debug:
json2bash() {
perl -MJSON -0777 -n -E 'sub J {
my ($p,$v) = @_; my $r = ref $v;
if ($r eq "HASH") { J("${p}_$_", $v->{$_}) for keys %$v; }
elsif ($r eq "ARRAY") { $n = 0; J("$p"."[".$n++."]", $_) foreach @$v; }
else { $v =~ '"s/'/'\\\\''/g"'; $p =~ s/^([^[]*)\[([0-9]*)\](.+)$/$1$3\[$2\]/;
$p =~ tr/-/_/; $p =~ tr/A-Za-z0-9_[]//cd; say "$p='\''$v'\'';"; }
}; J("json", decode_json($_));'
}
use it like eval "$(json2bash <<<'{"a":["b","c"]}')"
Not heavily tested, though. Updates, warnings and more examples see my GIST.
(Unfortunately, following is a link-only-solution, as the C code is far too long to duplicate here.)
For all those, who do not like the above solution,
there now is a C program json2sh
which (hopefully safely) converts JSON into shell variables.
In contrast to the perl
snippet, it is able to process any JSON,
as long as it is well formed.
Caveats:
json2sh
was not tested much.json2sh
may create variables, which start with the shellshock pattern () {
I wrote json2sh
to be able to post-process .bson
with Shell:
bson2json()
{
printf '[';
{ bsondump "$1"; echo "\"END$?\""; } | sed '/^{/s/$/,/';
echo ']';
};
bsons2json()
{
printf '{';
c='';
for a;
do
printf '%s"%q":' "$c" "$a";
c=',';
bson2json "$a";
done;
echo '}';
};
bsons2json */*.bson | json2sh | ..
Explained:
bson2json
dumps a .bson
file such, that the records become a JSON array
END0
-Marker is applied, else you will see something like END1
.END
-Marker is needed, else empty .bson
files would not show up.bsons2json
dumps a bunch of .bson
files as an object, where the output of bson2json
is indexed by the filename.This then is postprocessed by json2sh
, such that you can use grep
/source
/eval
/etc. what you need, to bring the values into the shell.
This way you can quickly process the contents of a MongoDB dump on shell level, without need to import it into MongoDB first.
Using Angular latest version (1.2.1) and track by $index
. This issue is fixed
<div ng-repeat="(i, name) in names track by $index">
Value: {{name}}
<input ng-model="names[i]">
</div>
Try this:
function welcomeMessage() { var shape1 = new Shape(); //alert(shape1.draw()); alert(shape1.hasOwnProperty("name")); }
When working with reflection in JavaScript, member objects are always refered to as the name as a string. For example:
for(i in obj) { ... }
The loop iterator i will be hold a string value with the name of the property. To use that in code you have to address the property using the array operator like this:
for(i in obj) { alert("The value of obj." + i + " = " + obj[i]); }
In fact, depends what you want to get: - Just the min value:
SELECT MIN(price) FROM pieces
A table (multiples rows) whith the min value: Is as John Woo said above.
But, if can be different rows with same min value, the best is ORDER them from another column, because after or later you will need to do it (starting from John Woo answere):
SELECT * FROM pieces WHERE price = ( SELECT MIN(price) FROM pieces) ORDER BY stock ASC
In addition to Jim's answer (sorry not enough rep points to make a comment), just wanted to point out that the arguments specified in PyCharm do not have special characters escaped, unlike what you would do on the command line. So, whereas on the command line you'd do:
python mediadb.py /media/paul/New\ Volume/Users/paul/Documents/spinmaster/\*.png
the PyCharm parameter would be:
"/media/paul/New Volume/Users/paul/Documents/spinmaster/*.png"
Request.QueryString["pID"];
Here Request is a object that retrieves the values that the client browser passed to the server during an HTTP request and QueryString is a collection is used to retrieve the variable values in the HTTP query string.
READ MORE@ http://msdn.microsoft.com/en-us/library/ms524784(v=vs.90).aspx
There is no good way to do that, but you should use portable solution, so avoid system()
calls, in your case you could use cin.get()
or getch()
as you mentioned in your question, also there is one advice. Make all pauses controlled by one (or very few) preprocessor definitions.
For example:
Somewhere in global file:
#define USE_PAUSES
#ifndef _DEBUG //I asume you have _DEBUG definition for debug and don't have it for release build
#undef USE_PAUSES
#endif
Somewhere in code
#ifdef USE_PAUSES
cin.get();
#endif
This is not universal advice, but you should protect yourself from putting pauses in release builds and these should have easy control, my mentioned global file may not be so global, because changes in that may cause really long compilation.
Your constructor is expecting one parameter (data). You're not passing it in the call. I guess you wanted to initialise a field in the object. That would look like this:
class DHT:
def __init__(self):
self.data = {}
self.data['one'] = '1'
self.data['two'] = '2'
self.data['three'] = '3'
def showData(self):
print(self.data)
if __name__ == '__main__':
DHT().showData()
Or even just:
class DHT:
def __init__(self):
self.data = {'one': '1', 'two': '2', 'three': '3'}
def showData(self):
print(self.data)
Try this code
public class WiFiDemo extends Activity implements OnClickListener
{
WifiManager wifi;
ListView lv;
TextView textStatus;
Button buttonScan;
int size = 0;
List<ScanResult> results;
String ITEM_KEY = "key";
ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
SimpleAdapter adapter;
/* Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textStatus = (TextView) findViewById(R.id.textStatus);
buttonScan = (Button) findViewById(R.id.buttonScan);
buttonScan.setOnClickListener(this);
lv = (ListView)findViewById(R.id.list);
wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled() == false)
{
Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
wifi.setWifiEnabled(true);
}
this.adapter = new SimpleAdapter(WiFiDemo.this, arraylist, R.layout.row, new String[] { ITEM_KEY }, new int[] { R.id.list_value });
lv.setAdapter(this.adapter);
registerReceiver(new BroadcastReceiver()
{
@Override
public void onReceive(Context c, Intent intent)
{
results = wifi.getScanResults();
size = results.size();
}
}, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
}
public void onClick(View view)
{
arraylist.clear();
wifi.startScan();
Toast.makeText(this, "Scanning...." + size, Toast.LENGTH_SHORT).show();
try
{
size = size - 1;
while (size >= 0)
{
HashMap<String, String> item = new HashMap<String, String>();
item.put(ITEM_KEY, results.get(size).SSID + " " + results.get(size).capabilities);
arraylist.add(item);
size--;
adapter.notifyDataSetChanged();
}
}
catch (Exception e)
{ }
}
}
WiFiDemo.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal">
<TextView
android:id="@+id/textStatus"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Status" />
<Button
android:id="@+id/buttonScan"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:text="Scan" />
</LinearLayout>
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="20dp"></ListView>
</LinearLayout>
For ListView- row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp">
<TextView
android:id="@+id/list_value"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14dp" />
</LinearLayout>
Add these permission in AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
If you want all the bars to get the same color (fill
), you can easily add it inside geom_bar
.
ggplot(data=df, aes(x=c1+c2/2, y=c3)) +
geom_bar(stat="identity", width=c2, fill = "#FF6666")
Add fill = the_name_of_your_var
inside aes
to change the colors depending of the variable :
c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2)
Use scale_fill_manual()
if you want to manually the change of colors.
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2) +
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))
Query to achieve your requirment
SELECT id,GROUP_CONCAT(text SEPARATOR ' ') AS text FROM table_name group by id;
Short answer
Why? Because there is still whitespace (carriage returns, tabs, spaces, newline) left in the input stream.
When? When you are using some function which does not on their own ignores the leading whitespaces. Cin by default ignores and removes the leading whitespace but getline does not ignore the leading whitespace on its own.
Now a detailed answer.
Everything you input in the console is read from the standard stream stdin. When you enter something, let's say 256 in your case and press enter, the contents of the stream become 256\n
. Now cin picks up 256 and removes it from the stream and \n
still remaining in the stream.
Now next when you enter your name, let's say Raddicus
, the new contents of the stream is \nRaddicus
.
Now here comes the catch.
When you try to read a line using getline, if not provided any delimiter as the third argument, getline by default reads till the newline character and removes the newline character from the stream.
So on calling new line, getline reads and discards \n
from the stream and resulting in an empty string read in mystr which appears like getline is skipped (but it's not) because there was already an newline in the stream, getline will not prompt for input as it has already read what it was supposed to read.
Now, how does cin.ignore help here?
According to the ignore documentation extract from cplusplus.com-
istream& ignore (streamsize n = 1, int delim = EOF);
Extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim.
The function also stops extracting characters if the end-of-file is reached. If this is reached prematurely (before either extracting n characters or finding delim), the function sets the eofbit flag.
So, cin.ignore(256, '\n');
, ignores first 256 characters or all the character untill it encounters delimeter (here \n in your case), whichever comes first (here \n is the first character, so it ignores until \n is encountered).
Just for your reference, If you don't exactly know how many characters to skip and your sole purpose is to clear the stream to prepare for reading a string using getline or cin you should use cin.ignore(numeric_limits<streamsize>::max(),'\n')
.
Quick explanation: It ignores the characters equal to maximum size of stream or until a '\n' is encountered, whichever case happens first.
This is how you can add a textField text change listener
using Swift 3:
Declare your class as UITextFieldDelegate
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self
textField.addTarget(self, action: #selector(UITextFieldDelegate.textFieldShouldEndEditing(_:)), for: UIControlEvents.editingChanged)
}
Then just traditionally add a textFieldShouldEndEditing function:
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { // do stuff
return true
}
SELECT SUBSTRING(COLUMN_TYPE, 6, LENGTH(COLUMN_TYPE) - 6) AS val FROM information_schema.COLUMNS WHERE TABLE_NAME = 'articles' AND COLUMN_NAME = 'status'
Wouldn't work for enum('','X''XX')
What I've done is go to this location in regedit
:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services
From here, you will see a folder for every service on your machine. Simply delete the folder for the service you wish, and you're done.
N.B: Stop the service before you try this.
Try passing width=200
as additional paramater when creating the Label.
This should work in creating label with specified width.
If you want to change it later, you can use:
label.config(width=200)
As you want to change the size of font itself you can try:
label.config(font=("Courier", 44))
I know that you did not ask for this, but if you have more processing units, you should always consider Boruvka's algorithm, because it might be easily parallelized - hence it has a performance advantage over Kruskal and Jarník-Prim algorithm.
Regardless of how do you index the pushbacks your vector contains 10 elements indexed from 0
(0
, 1
, ..., 9
). So in your second loop v[j]
is invalid, when j
is 10
.
This will fix the error:
for(int j = 9;j >= 0;--j)
{
cout << v[j];
}
In general it's better to think about indexes as 0
based, so I suggest you change also your first loop to this:
for(int i = 0;i < 10;++i)
{
v.push_back(i);
}
Also, to access the elements of a container, the idiomatic approach is to use iterators (in this case: a reverse iterator):
for (vector<int>::reverse_iterator i = v.rbegin(); i != v.rend(); ++i)
{
std::cout << *i << std::endl;
}
Use one way flow syntax property binding:
<div [innerHTML]="comment"></div>
From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script>
tag but keeps safe content such as the <b>
element."
right-click the view in the object-explorer, select "script view as...", then "create to" and then "new query editor window"
This one works on Bootstrap 4.3.1.
Jsfiddle: https://jsfiddle.net/ko6L31w4/1/
The HTML code might be a little bit messy because I create a slightly complex dropdown menu for comprehensive test, otherwise everything is pretty straight forward.
Js includes fewer ways to collapse opened dropdowns and CSS only includes minimal styles for full functionalities.
$(function() {_x000D_
$("ul.dropdown-menu [data-toggle='dropdown']").on("click", function(event) {_x000D_
event.preventDefault();_x000D_
event.stopPropagation();_x000D_
_x000D_
//method 1: remove show from sibilings and their children under your first parent_x000D_
_x000D_
/* if (!$(this).next().hasClass('show')) {_x000D_
_x000D_
$(this).parents('.dropdown-menu').first().find('.show').removeClass('show');_x000D_
} */ _x000D_
_x000D_
_x000D_
//method 2: remove show from all siblings of all your parents_x000D_
$(this).parents('.dropdown-submenu').siblings().find('.show').removeClass("show");_x000D_
_x000D_
$(this).siblings().toggleClass("show");_x000D_
_x000D_
_x000D_
//collapse all after nav is closed_x000D_
$(this).parents('li.nav-item.dropdown.show').on('hidden.bs.dropdown', function(e) {_x000D_
$('.dropdown-submenu .show').removeClass("show");_x000D_
});_x000D_
_x000D_
});_x000D_
});
_x000D_
.dropdown-submenu {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.dropdown-submenu>.dropdown-menu {_x000D_
top: 0;_x000D_
left: 100%;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>_x000D_
_x000D_
_x000D_
<nav class="navbar navbar-expand-md navbar-light bg-white py-3 shadow-sm">_x000D_
<div class="container-fluid">_x000D_
<a href="#" class="navbar-brand font-weight-bold">Multilevel Dropdown</a>_x000D_
_x000D_
<button type="button" data-toggle="collapse" data-target="#navbarContent" aria-controls="navbars" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler">_x000D_
<span class="navbar-toggler-icon"></span>_x000D_
</button>_x000D_
_x000D_
_x000D_
<div id="navbarContent" class="collapse navbar-collapse">_x000D_
<ul class="navbar-nav mr-auto">_x000D_
_x000D_
<!-- nav dropdown -->_x000D_
<li class="nav-item dropdown">_x000D_
_x000D_
<a href="#" data-toggle="dropdown" class="nav-link dropdown-toggle">Dropdown</a>_x000D_
<ul class="dropdown-menu">_x000D_
_x000D_
<li><a href="#" class="dropdown-item">Some action</a></li>_x000D_
_x000D_
<!-- lvl 1 dropdown -->_x000D_
<li class="dropdown-submenu">_x000D_
<a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 1</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="#" class="dropdown-item">level 2</a></li>_x000D_
_x000D_
<!-- lvl 2 dropdown -->_x000D_
<li class="dropdown-submenu">_x000D_
<a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 2</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
_x000D_
<!-- lvl 3 dropdown --> _x000D_
<li class="dropdown-submenu">_x000D_
<a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 3</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="#" class="dropdown-item">level 4</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
_x000D_
</ul>_x000D_
</li>_x000D_
_x000D_
<li><a href="#" class="dropdown-item">level 2</a></li>_x000D_
<li><a href="#" class="dropdown-item">level 2</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
_x000D_
<li><a href="#" class="dropdown-item">Some other action</a></li>_x000D_
_x000D_
<li class="dropdown-submenu">_x000D_
<a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 1</a>_x000D_
<ul class="dropdown-menu">_x000D_
_x000D_
<li class="dropdown-submenu">_x000D_
<a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 2</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
<li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
_x000D_
<li class="dropdown-submenu">_x000D_
<a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 2</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
<li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
_x000D_
<li><a href="#" class="dropdown-item">level 2</a></li>_x000D_
_x000D_
<li class="dropdown-submenu">_x000D_
<a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 2</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
<li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
_x000D_
<li><a href="#" class="dropdown-item">level 2</a></li>_x000D_
</ul>_x000D_
</li> _x000D_
</ul>_x000D_
</li>_x000D_
_x000D_
<li class="nav-item"><a href="#" class="nav-link">About</a></li>_x000D_
<li class="nav-item"><a href="#" class="nav-link">Services</a></li>_x000D_
<li class="nav-item"><a href="#" class="nav-link">Contact</a></li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
</nav>
_x000D_
@OP it doesn't matter, you can just split on a space with explode. Until you want to use those values, iterate over the exploded values and discard blanks.
$str = "A B C D";
$s = explode(" ",$str);
foreach ($s as $a=>$b){
if ( trim($b) ) {
print "using $b\n";
}
}
Select Custom Structure in permalinks and add /%category%/%postname%/ after your domain. Adding "/" to the category base doesn't work, you have to add a period/dot. I wrote a tutorial for this here: remove category from URL tutorial
Here's a simple example using $cookies. After clicking on button, the cookie is saved, and then restored after page is reloaded.
app.html:
<html ng-app="app">
<head>
<meta charset="utf-8" />
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular-cookies.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="appController as vm">
<input type="text" ng-model="vm.food" placeholder="Enter food" />
<p>My favorite food is {{vm.food}}.</p>
<p>Open new window, then press Back button.</p>
<button ng-click="vm.openUrl()">Open</button>
</body>
</html>
app.js:
(function () {
"use strict";
angular.module('app', ['ngCookies'])
.controller('appController', ['$cookies', '$window', function ($cookies, $window) {
var vm = this;
//get cookie
vm.food = $cookies.get('myFavorite');
vm.openUrl = function () {
//save cookie
$cookies.put('myFavorite', vm.food);
$window.open("http://www.google.com", "_self");
};
}]);
})();
Why not use commands.getoutput() instead?
import commands
text = "Mario Balotelli"
output = 'espeak "%s"' % text
print text
a = commands.getoutput(output)
Answers so far helped me come up with mine. I'm wary of UTC vs local time; ticks should always be UTC IMO.
public class Time
{
public static void Timestamps()
{
OutputTimestamp();
Thread.Sleep(1000);
OutputTimestamp();
}
private static void OutputTimestamp()
{
var timestamp = DateTime.UtcNow.Ticks;
var localTicks = DateTime.Now.Ticks;
var localTime = new DateTime(timestamp, DateTimeKind.Utc).ToLocalTime();
Console.Out.WriteLine("Timestamp = {0}. Local ticks = {1}. Local time = {2}.", timestamp, localTicks, localTime);
}
}
Output:
Timestamp = 636988286338754530. Local ticks = 636988034338754530. Local time = 2019-07-15 4:03:53 PM.
Timestamp = 636988286348878736. Local ticks = 636988034348878736. Local time = 2019-07-15 4:03:54 PM.
I think I have a better answer.
new Timestamp(longEpochTime).toLocalDateTime();
Something else you could do using raytrace's answer. You could use the stdout of another shell call using backticks to then do some calculations. For instance I wanted to know the file size of the top 100 lines from a couple of files. The original size from wc -c
is in bytes, I want to know kilobytes. Here's what I did:
echo `cat * | head -n 100 | wc -c` / 1024 | bc -l
The answers mentioning canvas.width
return the internal dimensions of the canvas, i.e. those specified when creating the element:
<canvas width="500" height="200">
If you size the canvas with CSS, its DOM dimensions are accessible via .scrollWidth
and .scrollHeight
:
var canvasElem = document.querySelector('canvas');_x000D_
document.querySelector('#dom-dims').innerHTML = 'Canvas DOM element width x height: ' +_x000D_
canvasElem.scrollWidth +_x000D_
' x ' +_x000D_
canvasElem.scrollHeight_x000D_
_x000D_
var canvasContext = canvasElem.getContext('2d');_x000D_
document.querySelector('#internal-dims').innerHTML = 'Canvas internal width x height: ' +_x000D_
canvasContext.canvas.width +_x000D_
' x ' +_x000D_
canvasContext.canvas.height;_x000D_
_x000D_
canvasContext.fillStyle = "#00A";_x000D_
canvasContext.fillText("Distorted", 0, 10);
_x000D_
<p id="dom-dims"></p>_x000D_
<p id="internal-dims"></p>_x000D_
<canvas style="width: 100%; height: 123px; border: 1px dashed black">
_x000D_
I'd just like to add to Jon's example. To get a reference to your own assembly, you can use:
Assembly myAssembly = Assembly.GetExecutingAssembly();
System.Reflection
namespace.
If you want to examine an assembly that you have no reference to, you can use either of these:
Assembly assembly = Assembly.ReflectionOnlyLoad(fullAssemblyName);
Assembly assembly = Assembly.ReflectionOnlyLoadFrom(fileName);
If you intend to instantiate your type once you've found it:
Assembly assembly = Assembly.Load(fullAssemblyName);
Assembly assembly = Assembly.LoadFrom(fileName);
See the Assembly class documentation for more information.
Once you have the reference to the Assembly
object, you can use assembly.GetTypes()
like Jon already demonstrated.
You could use CSS to do that, but it wouldn't be supported in IE8-. You can use some site like http://borderradius.com to come up with actual CSS you'd use, which would look something like this (again, depending on how many browsers you're trying to support):
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
private static void test()
{
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
string [] dirs = System.IO.Directory.GetDirectories("C:\\Test\\");
string[] files = System.IO.Directory.GetFiles("C:\\Test\\");
if (dirs.Length == 0 && files.Length == 0)
Console.WriteLine("Empty");
else
Console.WriteLine("Not Empty");
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
}
This quick test came back in 2 milliseconds for the folder when empty and when containing subfolders & files (5 folders with 5 files in each)
I was getting the same error because of jquery CDN (<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
) was added two times in the HTML head.
I would like to argue one point - that you cannot augment the original assembly - using Mono.Cecil you can inject [InternalsVisibleTo(...)]
to the 3pty assembly. Note there might be legal implications - you're messing with 3pty assembly and technical implications - if the assembly has strong name you either need to strip it or re-sign it with different key.
Install-Package Mono.Cecil
And the code like:
static readonly string[] s_toInject = {
// alternatively "MyAssembly, PublicKey=0024000004800000... etc."
"MyAssembly"
};
static void Main(string[] args) {
const string THIRD_PARTY_ASSEMBLY_PATH = @"c:\folder\ThirdPartyAssembly.dll";
var parameters = new ReaderParameters();
var asm = ModuleDefinition.ReadModule(INPUT_PATH, parameters);
foreach (var toInject in s_toInject) {
var ca = new CustomAttribute(
asm.Import(typeof(InternalsVisibleToAttribute).GetConstructor(new[] {
typeof(string)})));
ca.ConstructorArguments.Add(new CustomAttributeArgument(asm.TypeSystem.String, toInject));
asm.Assembly.CustomAttributes.Add(ca);
}
asm.Write(@"c:\folder-modified\ThirdPartyAssembly.dll");
// note if the assembly is strongly-signed you need to resign it like
// asm.Write(@"c:\folder-modified\ThirdPartyAssembly.dll", new WriterParameters {
// StrongNameKeyPair = new StrongNameKeyPair(File.ReadAllBytes(@"c:\MyKey.snk"))
// });
}
+" "
after each item in the array(except the last one, maybe)do it using jQuery put inside code on the <head></head>
tag
<script type="text/javascript">
$(document).ready(function() {
var docHeight = $(window).height();
var footerHeight = $('#footer').height();
var footerTop = $('#footer').position().top + footerHeight;
if (footerTop < docHeight) {
$('#footer').css('margin-top', 10 + (docHeight - footerTop) + 'px');
}
});
</script>
You can create a constructor using parameter Context of class A then you can use this context.
Context c;
A(Context context){ this.c=context }
From B activity you create a object of class A using this constructor and passing getApplicationContext().
On macOS, use subprocess.run
to pipe your text to pbcopy
:
import subprocess
data = "hello world"
subprocess.run("pbcopy", universal_newlines=True, input=data)
It will copy "hello world" to the clipboard.
no your ans is Wrong
Selection of Al and Ah is from AX not from EAX
e.g
EAX=0000 0000 0000 0000 0000 0000 0000 0111
So if we call AX it should return
0000 0000 0000 0111
if we call AH it should return
0000 0000
and when we call AL it should return
0000 0111
Example number 2
EAX: 22 33 55 77
AX: 55 77
AH: 55
AL: 77
example 3
EAX: 1111 0000 0000 0000 0000 0000 0000 0111
AX= 0000 0000 0000 0111
AH= 0000 0000
AL= 0000 0111
If you're using GCC, you might want to have a look at Optimizing the next_pow2() function by Lockless Inc.. This page describes a way to use built-in function builtin_clz()
(count leading zero) and later use directly x86 (ia32) assembler instruction bsr
(bit scan reverse), just like it's described in another answer's link to gamedev site. This code might be faster than those described in previous answer.
By the way, if you're not going to use assembler instruction and 64bit data type, you can use this
/**
* return the smallest power of two value
* greater than x
*
* Input range: [2..2147483648]
* Output range: [2..2147483648]
*
*/
__attribute__ ((const))
static inline uint32_t p2(uint32_t x)
{
#if 0
assert(x > 1);
assert(x <= ((UINT32_MAX/2) + 1));
#endif
return 1 << (32 - __builtin_clz (x - 1));
}
I think style no. 111 (Japan) should work:
SELECT CONVERT(DATETIME, '2012-08-17', 111)
And if that doesn't work for some reason - you could always just strip out the dashes and then you have the totally reliable ISO-8601 format (YYYYMMDD
) which works for any language and date format setting in SQL Server:
SELECT CAST(REPLACE('2012-08-17', '-', '') AS DATETIME)
you can set maxlength with jquery which is very fast
jQuery(document).ready(function($){ //fire on DOM ready
setformfieldsize(jQuery('#comment'), 50, 'charsremain')
})
I used this code, it is working fine
var arr = MyDiv.getElementsByTagName('script')
for (var n = 0; n < arr.length; n++)
eval(arr[n].innerHTML)//run script inside div
If you want to download gradle with source and docs, the default distribution url configured in gradle-wrapper.properites will not satisfy your need.It is https://services.gradle.org/distributions/gradle-2.10-bin.zip, not https://services.gradle.org/distributions/gradle-2.10-all.zip.This full url is suggested by IDE such as Android Studio.If you want to download the full gradle,You can configure the wrapper task like this:
task wrapper(type: Wrapper) {
gradleVersion = '2.13'
distributionUrl = distributionUrl.replace("bin", "all")
}
public ActionResult ViewNextItem(int? id)
makes the id
integer a nullable type, no need for string<->int conversions.
To create the datepicker and set the date.
$('.next_date').datepicker({ dateFormat: 'dd-mm-yy'}).datepicker("setDate", new Date());