I wanted to be able to easily let users create a default profile for PowerShell to override some settings, and ended up with the following one-liner (multiple statements yes, but can be pasted into PowerShell and executed at once, which was the main goal):
cls; [string]$filePath = $profile; [string]$fileContents = '<our standard settings>'; if(!(Test-Path $filePath)){md -Force ([System.IO.Path]::GetDirectoryName($filePath)) | Out-Null; $fileContents | sc $filePath; Write-Host 'File created!'; } else { Write-Warning 'File already exists!' };
For readability, here's how I would do it in a .ps1 file instead:
cls; # Clear console to better notice the results
[string]$filePath = $profile; # Declared as string, to allow the use of texts without plings and still not fail.
[string]$fileContents = '<our standard settings>'; # Statements can now be written on individual lines, instead of semicolon separated.
if(!(Test-Path $filePath)) {
New-Item -Force ([System.IO.Path]::GetDirectoryName($filePath)) | Out-Null; # Ignore output of creating directory
$fileContents | Set-Content $filePath; # Creates a new file with the input
Write-Host 'File created!';
}
else {
Write-Warning "File already exists! To remove the file, run the command: Remove-Item $filePath";
};
Not much documentation on PowerShell loops.
Documentation on loops in PowerShell is plentiful, and you might want to check out the following help topics: about_For
, about_ForEach
, about_Do
, about_While
.
foreach($line in Get-Content .\file.txt) {
if($line -match $regex){
# Work here
}
}
Another idiomatic PowerShell solution to your problem is to pipe the lines of the text file to the ForEach-Object
cmdlet:
Get-Content .\file.txt | ForEach-Object {
if($_ -match $regex){
# Work here
}
}
Instead of regex matching inside the loop, you could pipe the lines through Where-Object
to filter just those you're interested in:
Get-Content .\file.txt | Where-Object {$_ -match $regex} | ForEach-Object {
# Work here
}
Using param to name the parameters allows you to ignore the order of the parameters:
ParamEx.ps1
# Show how to handle command line parameters in Windows PowerShell
param(
[string]$FileName,
[string]$Bogus
)
write-output 'This is param FileName:'+$FileName
write-output 'This is param Bogus:'+$Bogus
ParaEx.bat
rem Notice that named params mean the order of params can be ignored
powershell -File .\ParamEx.ps1 -Bogus FooBar -FileName "c:\windows\notepad.exe"
To close the current cmd windows immediately, just add as the last command/line:
move nul 2>&0
Try move nul
to nowhere and redirect the stderr to stdin
will result in the current window cmd.exe being closed
This is different from closing a bat, or exiting it using goto :EOF
or Exit /b
These solutions Failed in my case with Relative Layout and If KeyBoard is Open
android:scrollbars="none"
&
android:scrollbarStyle="insideOverlay"
also not working.
toolbar is gone, my done button is gone.
This one is Working for me
myScrollView.setVerticalScrollBarEnabled(false);
There are two options. The first (and better) one is using the Fetch as Google option in Webmaster Tools that Mike Flynn commented about. Here are detailed instructions:
With the option above, as long as every page can be reached from some link on the initial page or a page that it links to, Google should recrawl the whole thing. If you want to explicitly tell it a list of pages to crawl on the domain, you can follow the directions to submit a sitemap.
Your second (and generally slower) option is, as seanbreeden pointed out, submitting here: http://www.google.com/addurl/
Update 2019:
I am just having hard time to understand concept behind putting wait() in object class For this questions sake consider as if wait() and notifyAll() are in thread class
In the Java language, you wait()
on a particular instance of an Object
– a monitor assigned to that object to be precise. If you want to send a signal to one thread that is waiting on that specific object instance then you call notify()
on that object. If you want to send a signal to all threads that are waiting on that object instance, you use notifyAll()
on that object.
If wait()
and notify()
were on the Thread
instead then each thread would have to know the status of every other thread. How would thread1 know that thread2 was waiting for access to a particular resource? If thread1 needed to call thread2.notify()
it would have to somehow find out that thread2
was waiting. There would need to be some mechanism for threads to register the resources or actions that they need so others could signal them when stuff was ready or available.
In Java, the object itself is the entity that is shared between threads which allows them to communicate with each other. The threads have no specific knowledge of each other and they can run asynchronously. They run and they lock, wait, and notify on the object that they want to get access to. They have no knowledge of other threads and don't need to know their status. They don't need to know that it is thread2 which is waiting for the resource – they just notify on the resource and whomever it is that is waiting (if anyone) will be notified.
In Java, we then use objects as synchronization, mutex, and communication points between threads. We synchronize on an object to get mutex access to an important code block and to synchronize memory. We wait on an object if we are waiting for some condition to change – some resource to become available. We notify on an object if we want to awaken sleeping threads.
// locks should be final objects so the object instance we are synchronizing on,
// never changes
private final Object lock = new Object();
...
// ensure that the thread has a mutex lock on some key code
synchronized (lock) {
...
// i need to wait for other threads to finish with some resource
// this releases the lock and waits on the associated monitor
lock.wait();
...
// i need to signal another thread that some state has changed and they can
// awake and continue to run
lock.notify();
}
There can be any number of lock objects in your program – each locking a particular resource or code segment. You might have 100 lock objects and only 4 threads. As the threads run the various parts of the program, they get exclusive access to one of the lock objects. Again, they don't have to know the running status of the other threads.
This allows you to scale up or down the number of threads running in your software as much as you want. You find that the 4 threads is blocking too much on outside resources, then you can increase the number. Pushing your battered server too hard then reduce the number of running threads. The lock objects ensure mutex and communication between the threads independent of how many threads are running.
Using Gradle & Lombok, here is the simplest configuration for Log4j2 that worked for me using the latest Spring Boot (2.4.1 at this time) :
configurations {
compileOnly { extendsFrom annotationProcessor }
compile.exclude module: 'spring-boot-starter-logging'
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-web-services'
implementation 'org.springframework.boot:spring-boot-starter-log4j2'
compileOnly 'org.projectlombok:lombok'
// (*** other dependencies ***)
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'
}
I noticed you will get errors if you include spring-bbot-starter-log4j2
as a compileOnly
dependency instead of as an implementation
.
Just annotate your classes with @Log4j2
(or @Slf4j
) and lombok will make available a log
variable you can use for logging.
As usual, provide a log4j2.xml
configuration file in your /src/main/resources
folder.
python has named optional arguments
def func(a, b=2, c=3):
print a, b, c
>>> func(1)
1 2 3
>>> func(1, c=4)
1 2 4
AFAIK Ruby has only positioned arguments because b=2 in the function declaration is an affectation that always append.
See repmat in the documentation.
B = repmat(5,1,10)
This may be useful for someone else looking at this question. I rewrote Justin's code to allow the method to receive the target size object required as well. This works very well when using Canvas. All credit should go to JUSTIN for his great initial code.
private Bitmap getBitmap(int path, Canvas canvas) {
Resources resource = null;
try {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
resource = getResources();
// Decode image size
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(resource, path, options);
int scale = 1;
while ((options.outWidth * options.outHeight) * (1 / Math.pow(scale, 2)) >
IMAGE_MAX_SIZE) {
scale++;
}
Log.d("TAG", "scale = " + scale + ", orig-width: " + options.outWidth + ", orig-height: " + options.outHeight);
Bitmap pic = null;
if (scale > 1) {
scale--;
// scale to max possible inSampleSize that still yields an image
// larger than target
options = new BitmapFactory.Options();
options.inSampleSize = scale;
pic = BitmapFactory.decodeResource(resource, path, options);
// resize to desired dimensions
int height = canvas.getHeight();
int width = canvas.getWidth();
Log.d("TAG", "1th scale operation dimenions - width: " + width + ", height: " + height);
double y = Math.sqrt(IMAGE_MAX_SIZE
/ (((double) width) / height));
double x = (y / height) * width;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(pic, (int) x, (int) y, true);
pic.recycle();
pic = scaledBitmap;
System.gc();
} else {
pic = BitmapFactory.decodeResource(resource, path);
}
Log.d("TAG", "bitmap size - width: " +pic.getWidth() + ", height: " + pic.getHeight());
return pic;
} catch (Exception e) {
Log.e("TAG", e.getMessage(),e);
return null;
}
}
Justin's code is VERY effective at reducing the overhead of working with large Bitmaps.
The initial issue is solved by changing lat
and lon
to double.
I want to add comment to solution with Location location = locationManager.getLastKnownLocation(bestProvider);
It works to find out last known location when other app was lisnerning for that. If, for example, no app did that since device start, the code will return zeros (spent some time myself recently to figure that out).
Also, it's a good practice to stop listening when there is no need for that by locationManager.removeUpdates(this);
Also, even with permissions in manifest
, the code works when location service is enabled in Android settings on a device.
This cannot be done in pure java. But you can run external programs using java and get the result.
Process p=Runtime.getRuntime().exec("systeminfo");
Scanner scan=new Scanner(p.getInputStream());
while(scan.hasNext()){
String temp=scan.nextLine();
if(temp.equals("Available Physical Memmory")){
System.out.println("RAM :"temp.split(":")[1]);
break;
}
}
Eclipse > Help > Eclipse Marketplace...
Search for m2e
Install Maven Integration for Eclipse (Juno and newer)
. [It works for Indigo also]
These lines are your problem (or at least one of your problems, if there are more):
private static string s_bstCommonAppData = Path.Combine(s_commonAppData, "XXXX");
private static string s_bstUserDataDir = Path.Combine(s_bstCommonAppData, "UserData");
private static string s_commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
You reference some static members in the initializers for other static members. This is a bad idea, as the compiler doesn't know in which order to initialize them. The result is that during the initialization of s_bstCommonAppData
, the dependent field s_commonAppData
has not yet been initialized, so you are calling Path.Combine(null, "XXXX")
and this method does not accept null arguments.
You can fix this by making sure that fields used in the initialization of other fields are declared first:
private static string s_commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
private static string s_bstCommonAppData = Path.Combine(s_commonAppData, "XXXX");
private static string s_bstUserDataDir = Path.Combine(s_bstCommonAppData, "UserData");
Or use a static constructor to explicitly order the assignments:
private static string s_bstCommonAppData;
private static string s_bstUserDataDir;
private static string s_commonAppData;
static Logger()
{
s_commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
s_bstCommonAppData = Path.Combine(s_commonAppData, "XXXX");
s_bstUserDataDir = Path.Combine(s_bstCommonAppData, "UserData");
}
How about skipping the particular file while iterating over all the files in the folder! Below code would skip all excel files that start with 'eph'
import glob
import re
for file in glob.glob('*.xlsx'):
if re.match('eph.*\.xlsx',file):
continue
else:
#do your stuff here
print(file)
This way you can use more complex regex patterns to include/exclude a particular set of files in a folder.
It's done by binding to the scroll event of the container (usually window).
Quick example:
// Cache selectors
var topMenu = $("#top-menu"),
topMenuHeight = topMenu.outerHeight()+15,
// All list items
menuItems = topMenu.find("a"),
// Anchors corresponding to menu items
scrollItems = menuItems.map(function(){
var item = $($(this).attr("href"));
if (item.length) { return item; }
});
// Bind to scroll
$(window).scroll(function(){
// Get container scroll position
var fromTop = $(this).scrollTop()+topMenuHeight;
// Get id of current scroll item
var cur = scrollItems.map(function(){
if ($(this).offset().top < fromTop)
return this;
});
// Get the id of the current element
cur = cur[cur.length-1];
var id = cur && cur.length ? cur[0].id : "";
// Set/remove active class
menuItems
.parent().removeClass("active")
.end().filter("[href='#"+id+"']").parent().addClass("active");
});?
See the above in action at jsFiddle including scroll animation.
For Dialog This may helpful for someone. I want a dialog to take full width of screen. searched a lot but nothing found useful. Finally this worked for me:
mDialog.setContentView(R.layout.my_custom_dialog);
mDialog.getWindow().setBackgroundDrawable(null);
after adding this, my dialog appears in full width of screen.
Use this code:
'{:x}'.format(int(line))
it allows you to specify a number of digits too:
'{:06x}'.format(123)
# '00007b'
For Python 2.6 use
'{0:x}'.format(int(line))
or
'{0:06x}'.format(int(line))
I have tried the following config for eclipse.ini:
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
1024M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
1024m
--launcher.defaultAction
openFile
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.6
-Xms128m
-Xmx2048m
Now eclipse performance is about 2 times faster then before.
You can also find a good help ref here: http://help.eclipse.org/indigo/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/misc/runtime-options.html
I've also faced the problem of ordering of loaded scripts, which was solved through sequential loading of scripts. The loading is based on Rob W's answer.
function scriptFromFile(file) {
var script = document.createElement("script");
script.src = chrome.extension.getURL(file);
return script;
}
function scriptFromSource(source) {
var script = document.createElement("script");
script.textContent = source;
return script;
}
function inject(scripts) {
if (scripts.length === 0)
return;
var otherScripts = scripts.slice(1);
var script = scripts[0];
var onload = function() {
script.parentNode.removeChild(script);
inject(otherScripts);
};
if (script.src != "") {
script.onload = onload;
document.head.appendChild(script);
} else {
document.head.appendChild(script);
onload();
}
}
The example of usage would be:
var formulaImageUrl = chrome.extension.getURL("formula.png");
var codeImageUrl = chrome.extension.getURL("code.png");
inject([
scriptFromSource("var formulaImageUrl = '" + formulaImageUrl + "';"),
scriptFromSource("var codeImageUrl = '" + codeImageUrl + "';"),
scriptFromFile("EqEditor/eq_editor-lite-17.js"),
scriptFromFile("EqEditor/eq_config.js"),
scriptFromFile("highlight/highlight.pack.js"),
scriptFromFile("injected.js")
]);
Actually, I'm kinda new to JS, so feel free to ping me to the better ways.
A generic piece of code that will work for multiple columns. This can also be used if there is a need to conditionally implement search functionality in the application.
search_key = "abc"
search_args = [col.ilike('%%%s%%' % search_key) for col in ['col1', 'col2', 'col3']]
query = Query(table).filter(or_(*search_args))
session.execute(query).fetchall()
Note: the %%
are important to skip % formatting the query.
One of the best examples of Hadoop-like MapReduce implementation.
Keep in mind though that they are limited to key-value based implementations of the MapReduce idea (so they are limiting in applicability).
I'd recomment using good old javascript:
document.getElementById("addRunner").reset();
The problem is with the input.nextInt() method - it only reads the int value. So when you continue reading with input.nextLine() you receive the "\n" Enter key. So to skip this you have to add the input.nextLine(). Hope this should be clear now.
Try it like that:
System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // This line you have to add (It consumes the \n character)
System.out.print("Text1: ");
String text1 = input.nextLine();
System.out.print("Text2: ");
String text2 = input.nextLine();
Here's a function I wrote that uses pseudo-transparency to represent overlapping histograms
plotOverlappingHist <- function(a, b, colors=c("white","gray20","gray50"),
breaks=NULL, xlim=NULL, ylim=NULL){
ahist=NULL
bhist=NULL
if(!(is.null(breaks))){
ahist=hist(a,breaks=breaks,plot=F)
bhist=hist(b,breaks=breaks,plot=F)
} else {
ahist=hist(a,plot=F)
bhist=hist(b,plot=F)
dist = ahist$breaks[2]-ahist$breaks[1]
breaks = seq(min(ahist$breaks,bhist$breaks),max(ahist$breaks,bhist$breaks),dist)
ahist=hist(a,breaks=breaks,plot=F)
bhist=hist(b,breaks=breaks,plot=F)
}
if(is.null(xlim)){
xlim = c(min(ahist$breaks,bhist$breaks),max(ahist$breaks,bhist$breaks))
}
if(is.null(ylim)){
ylim = c(0,max(ahist$counts,bhist$counts))
}
overlap = ahist
for(i in 1:length(overlap$counts)){
if(ahist$counts[i] > 0 & bhist$counts[i] > 0){
overlap$counts[i] = min(ahist$counts[i],bhist$counts[i])
} else {
overlap$counts[i] = 0
}
}
plot(ahist, xlim=xlim, ylim=ylim, col=colors[1])
plot(bhist, xlim=xlim, ylim=ylim, col=colors[2], add=T)
plot(overlap, xlim=xlim, ylim=ylim, col=colors[3], add=T)
}
Here's another way to do it using R's support for transparent colors
a=rnorm(1000, 3, 1)
b=rnorm(1000, 6, 1)
hist(a, xlim=c(0,10), col="red")
hist(b, add=T, col=rgb(0, 1, 0, 0.5) )
The results end up looking something like this:
Basically, tree conflicts arise if there is some restructure in the folder structure on the branch.
You need to delete the conflict folder and use svn clean
once.
Hope this solves your conflict.
I made a wider input field by using either span4 or span6 as class.
<input type="text" class="span6 input-large search-query">
This way you don't need the additional custom css, mentioned earlier.
Try this
public static long Hextonumber(String hexval)
{
hexval="0x"+hexval;
// String decimal="0x00000bb9";
Long number = Long.decode(hexval);
//....... System.out.println("String [" + hexval + "] = " + number);
return number;
//3001
}
Query Builder:
DB::table(..)->select(..)->whereNotIn('book_price', [100,200])->get();
Eloquent:
SomeModel::select(..)->whereNotIn('book_price', [100,200])->get();
You can think of Python global variables as "module" variables - and as such they are much more useful than the traditional "global variables" from C.
A global variable is actually defined in a module's __dict__
and can be accessed from outside that module as a module attribute.
So, in your example:
# ../myproject/main.py
# Define global myList
# global myList - there is no "global" declaration at module level. Just inside
# function and methods
myList = []
# Imports
import subfile
# Do something
subfile.stuff()
print(myList[0])
And:
# ../myproject/subfile.py
# Save "hey" into myList
def stuff():
# You have to make the module main available for the
# code here.
# Placing the import inside the function body will
# usually avoid import cycles -
# unless you happen to call this function from
# either main or subfile's body (i.e. not from inside a function or method)
import main
main.mylist.append("hey")
I found it, I was trying to compile my app which is using facebook sdk. I was made that like augst 2016. When I try to open it today i got same error. I had that line in my gradle " compile 'com.facebook.android:facebook-android-sdk:4.+' " and I went https://developers.facebook.com/docs/android/change-log-4x this page and i found the sdk version while i was running this app succesfully and it was 4.14.1 then I changed that line to " compile 'com.facebook.android:facebook-android-sdk:4.14.1' " and it worked.
Find out the process ID (PID) which is occupying the port number (e.g., 5955) you would like to free
sudo lsof -i :5955
Kill the process which is currently using the port using its PID
sudo kill -9 PID
Don't use the ['type']
parameter to validate uploads. That field is user-provided, and can be trivially forged, allowing ANY type of file to be uploaded. The same goes for the ['name']
parameter - that's the name of the file as provided by the user. It is also trivial to forge, so the user's sending nastyvirus.exe
and calling it cutekittens.jpg
.
The proper method for validating uploads is to use server-side mime-type determination, e.g. via fileinfo, plus having proper upload success checking, which you do not:
if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error " . $_FILES['file']['error']);
}
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES['file']['tmp_name']);
$ok = false;
switch ($mime) {
case 'image/jpeg':
case 'application/pdf'
case etc....
$ok = true;
default:
die("Unknown/not permitted file type");
}
move_uploaded_file(...);
You are also using the user-provided filename as part of the final destination of the move_uploaded_files. it is also trivial to embed path data into that filename, which you then blindly use. That means a malicious remote user can scribble on ANY file on your server that they know the path for, plus plant new files.
This error can also occur if you accidentally use commas instead of AND
in the ON
clause of a JOIN
:
JOIN joined_table ON (joined_table.column = table.column, joined_table.column2 = table.column2)
^
should be AND, not a comma
You can use the CSS declaration font-weight: bold;
.
I would advise you to read the CSS beginner guide at http://htmldog.com/guides/cssbeginner/ .
Go via POSIXct
and you want to set a TZ
there -- here you see my (Chicago) default:
R> val <- 1352068320
R> as.POSIXct(val, origin="1970-01-01")
[1] "2012-11-04 22:32:00 CST"
R> as.Date(as.POSIXct(val, origin="1970-01-01"))
[1] "2012-11-05"
R>
Edit: A few years later, we can now use the anytime package:
R> library(anytime)
R> anytime(1352068320)
[1] "2012-11-04 16:32:00 CST"
R> anydate(1352068320)
[1] "2012-11-04"
R>
Note how all this works without any format or origin arguments.
I got the same problem when accessing mysql with root. The problem I found is that some database files does not have permission by the mysql user, which is the user that started the mysql server daemon.
We can check this with ls -l /var/lib/mysql
command, if the mysql user does not have permission of reading or writing on some files or directories, that might cause problem. We can change the owner or mode of those files or directories with chown/chmod
commands.
After these changes, restart the mysqld daemon and login with root with command:
mysql -u root
Then change passwords or create other users for logging into mysql.
HTH
If you just copy&paste the example URL that Google gives in their website http://maps.google.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true_or_false it will fail because of the wrong parameter of the sensor. You should change it to true or false and not the one that they wrote. Maybe is the error that you have had, like it happened to me...
If you just want to pass a class to a function, so that this function can create new instances of that class, just treat the class like any other value you would give as a parameter:
def printinstance(someclass):
print someclass()
Result:
>>> printinstance(list)
[]
>>> printinstance(dict)
{}
For lists, use contains
:
[1,2,3].contains(1) == true
So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]
Python has a %
operator for this.
>>> a = 5
>>> b = "hello"
>>> buf = "A = %d\n , B = %s\n" % (a, b)
>>> print buf
A = 5
, B = hello
>>> c = 10
>>> buf = "C = %d\n" % c
>>> print buf
C = 10
See this reference for all supported format specifiers.
You could as well use format
:
>>> print "This is the {}th tome of {}".format(5, "knowledge")
This is the 5th tome of knowledge
Another pitfall is that connectionString
sometimes refers to the name of the connection string in the app/web-config and sometimes to the actual connection string itself and vice versa.
Very easy to fix but sometimes hard to spot.
After setting the sort expression on the DefaultView (table.DefaultView.Sort = "Town ASC, Cutomer ASC"
) you should loop over the table using the DefaultView not the DataTable instance itself
foreach(DataRowView r in table.DefaultView)
{
//... here you get the rows in sorted order
Console.WriteLine(r["Town"].ToString());
}
Using the Select method of the DataTable instead, produces an array of DataRow. This array is sorted as from your request, not the DataTable
DataRow[] rowList = table.Select("", "Town ASC, Cutomer ASC");
foreach(DataRow r in rowList)
{
Console.WriteLine(r["Town"].ToString());
}
bmleite has the correct answer about including the module.
If that is correct in your situation, you should also ensure that you are not redefining the modules in multiple files.
Remember:
angular.module('ModuleName', []) // creates a module.
angular.module('ModuleName') // gets you a pre-existing module.
So if you are extending a existing module, remember not to overwrite when trying to fetch it.
DateTime dateTime = dateTime.Today.ToString("MM.dd.yyyy");
Console.Write(dateTime);
Try this
var s = {name: "raul", age: "22", gender: "Male"}
var keys = [];
for(var k in s) keys.push(k);
Here keys array will return your keys ["name", "age", "gender"]
import re
mylist = [x for x in re.compile('\s*[,|\s+]\s*').split(string)]
Simply, comma or at least one white spaces with/without preceding/succeeding white spaces.
Please try!
Using replace and assigning a new df:
import pandas as pd
df = pd.DataFrame(['-',3,2,5,1,-5,-1,'-',9])
dfnew = df.replace('-', 0)
print(dfnew)
(venv) D:\assets>py teste2.py
0
0 0
1 3
2 2
3 5
4 1
5 -5
Working from your jsFiddle example:
The jsFiddle was fine, but you were missing semi-colons at the end of the event.preventDefault() statements.
This works: Revised jsFiddle
jQuery(document).ready(function() {
jQuery(".rec1").click(function(event) {
event.preventDefault();
jQuery('#rec-box').html(jQuery(this).next().html());
});
jQuery(".rec2").click(function(event) {
event.preventDefault();
jQuery('#rec-box2').html(jQuery(this).next().html());
});
});
invisible(cat("Dataset: ", dataset, fill = TRUE))
invisible(cat(" Width: " ,width, fill = TRUE))
invisible(cat(" Bin1: " ,bin1interval, fill = TRUE))
invisible(cat(" Bin2: " ,bin2interval, fill = TRUE))
invisible(cat(" Bin3: " ,bin3interval, fill = TRUE))
produces output without NULL at the end of the line or on the next line
Dataset: 17 19 26 29 31 32 34 45 47 51 52 59 60 62 63
Width: 15.33333
Bin1: 17 32.33333
Bin2: 32.33333 47.66667
Bin3: 47.66667 63
Git introduced a --ff-only option when merging.
From: http://git-scm.com/docs/git-merge
--ff-only
Refuse to merge and exit with a non-zero status unless the current HEAD is already up-to-date or the merge can be resolved as a fast-forward.
Doing this will attempt to merge and fast-forward, and if it can't it aborts and prompts you that the fast-forward could not be performed, but leaves your working branch untouched. If it can fast-forward, then it will perform the merge on your working branch. This option is also available on git pull
. Thus, you could do the following:
git pull --ff-only origin branchA #See if you can pull down and merge branchA
git merge --ff-only branchA branchB #See if you can merge branchA into branchB
Have you tried with the custom format "#,##0.##"
?
I decode JSON this way:
eval( 'var from_json_object = ' + my_json_str + ';' );
function call asStartOfDay()
on java.time.LocalDate
object returns a java.time.LocalDateTime
object
Have you tried using the 'static' storage class similar to?:
public static class employee
{
static NameValueCollection appSetting = ConfigurationManager.AppSettings;
}
I am updating a simple solution. First add an id to your segue which presents modal. Than in properties change it's presentation style to "Over Current Context". Than add this code in presenting view controller (The controller which is presenting modal).
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let Device = UIDevice.currentDevice()
let iosVersion = NSString(string: Device.systemVersion).doubleValue
let iOS8 = iosVersion >= 8
let iOS7 = iosVersion >= 7 && iosVersion < 8
if((segue.identifier == "chatTable")){
if (iOS8){
}
else {
self.navigationController?.modalPresentationStyle = UIModalPresentationStyle.CurrentContext
}
}
}
Make sure you change segue.identifier to your own id ;)
The web server is prompting you for a SPNEGO (Simple and Protected GSSAPI Negotiation Mechanism) token.
This is a Microsoft invention for negotiating a type of authentication to use for Web SSO (single-sign-on):
See:
First checkout to the branch which you want to rename:
git branch -m old_branch new_branch
git push -u origin new_branch
To remove an old branch from remote
:
git push origin :old_branch
Disabled elements don't fire mouse events. Most browsers will propagate an event originating from the disabled element up the DOM tree, so event handlers could be placed on container elements. However, Firefox doesn't exhibit this behaviour, it just does nothing at all when you click on a disabled element.
I can't think of a better solution but, for complete cross browser compatibility, you could place an element in front of the disabled input and catch the click on that element. Here's an example of what I mean:
<div style="display:inline-block; position:relative;">
<input type="text" disabled />
<div style="position:absolute; left:0; right:0; top:0; bottom:0;"></div>
</div>?
jq:
$("div > div").click(function (evt) {
$(this).hide().prev("input[disabled]").prop("disabled", false).focus();
});?
Example: http://jsfiddle.net/RXqAm/170/ (updated to use jQuery 1.7 with prop
instead of attr
).
closures are beautiful! they solve a lot of problems that come with anonymous functions, and make really elegant code possible (at least as long as we talk about php).
javascript programmers use closures all the time, sometimes even without knowing it, because bound variables aren't explicitly defined - that's what "use" is for in php.
there are better real-world examples than the above one. lets say you have to sort an multidimensional array by a sub-value, but the key changes.
<?php
function generateComparisonFunctionForKey($key) {
return function ($left, $right) use ($key) {
if ($left[$key] == $right[$key])
return 0;
else
return ($left[$key] < $right[$key]) ? -1 : 1;
};
}
$myArray = array(
array('name' => 'Alex', 'age' => 70),
array('name' => 'Enrico', 'age' => 25)
);
$sortByName = generateComparisonFunctionForKey('name');
$sortByAge = generateComparisonFunctionForKey('age');
usort($myArray, $sortByName);
usort($myArray, $sortByAge);
?>
warning: untested code (i don't have php5.3 installed atm), but it should look like something like that.
there's one downside: a lot of php developers may be a bit helpless if you confront them with closures.
to understand the nice-ty of closures more, i'll give you another example - this time in javascript. one of the problems is the scoping and the browser inherent asynchronity. especially, if it comes to window.setTimeout();
(or -interval). so, you pass a function to setTimeout, but you can't really give any parameters, because providing parameters executes the code!
function getFunctionTextInASecond(value) {
return function () {
document.getElementsByName('body')[0].innerHTML = value; // "value" is the bound variable!
}
}
var textToDisplay = prompt('text to show in a second', 'foo bar');
// this returns a function that sets the bodys innerHTML to the prompted value
var myFunction = getFunctionTextInASecond(textToDisplay);
window.setTimeout(myFunction, 1000);
myFunction returns a function with a kind-of predefined parameter!
to be honest, i like php a lot more since 5.3 and anonymous functions/closures. namespaces may be more important, but they're a lot less sexy.
Make as shown.
$(document).ready(function(){_x000D_
$('#myModal').modal('show');_x000D_
_x000D_
$('#myBtn').on('click', function(){_x000D_
$('#myModal').modal('show');_x000D_
});_x000D_
_x000D_
});_x000D_
<br/>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<title>Bootstrap Example</title>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
<h2>Activate Modal with JavaScript</h2>_x000D_
<!-- Trigger the modal with a button -->_x000D_
<button type="button" class="btn btn-info btn-lg" id="myBtn">Open Modal</button>_x000D_
_x000D_
<!-- Modal -->_x000D_
<div class="modal fade" id="myModal" role="dialog">_x000D_
<div class="modal-dialog">_x000D_
_x000D_
<!-- Modal content-->_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<button type="button" class="close" data-dismiss="modal">×</button>_x000D_
<h4 class="modal-title">Modal Header</h4>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<p>Some text in the modal.</p>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
Running PHP as a CGI means that you basically tell your web server the location of the PHP executable file, and the server runs that executable
whereas
PHP FastCGI Process Manager (PHP-FPM) is an alternative FastCGI daemon for PHP that allows a website to handle strenuous loads. PHP-FPM maintains pools (workers that can respond to PHP requests) to accomplish this. PHP-FPM is faster than traditional CGI-based methods, such as SUPHP, for multi-user PHP environments
However, there are pros and cons to both and one should choose as per their specific use case.
I found info on this link for fastcgi vs fpm quite helpful in choosing which handler to use in my scenario.
Tested and working!
with https, user & password
<?php
//Data, connection, auth
$dataFromTheForm = $_POST['fieldName']; // request data from the form
$soapUrl = "https://connecting.website.com/soap.asmx?op=DoSomething"; // asmx URL of WSDL
$soapUser = "username"; // username
$soapPassword = "password"; // password
// xml post structure
$xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetItemPrice xmlns="http://connecting.website.com/WSDL_Service"> // xmlns value to be set to your WSDL URL
<PRICE>'.$dataFromTheForm.'</PRICE>
</GetItemPrice >
</soap:Body>
</soap:Envelope>'; // data from the form, e.g. some ID number
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice",
"Content-length: ".strlen($xml_post_string),
); //SOAPAction: your op URL
$url = $soapUrl;
// PHP cURL for https connection with auth
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// converting
$response = curl_exec($ch);
curl_close($ch);
// converting
$response1 = str_replace("<soap:Body>","",$response);
$response2 = str_replace("</soap:Body>","",$response1);
// convertingc to XML
$parser = simplexml_load_string($response2);
// user $parser to get your data out of XML response and to display it.
?>
$elements_array = ['first', 'second'];
function to remove some array elements
function remove($arr, $data) {
return array_filter($arr, function ($element) use ($data) {
return $element != $data;
});
}
call and print
print_r(remove($elements_array, 'second'));
the result
Array ( [0] => first )
I you want to put the response of the request in the navItems
. Because http.get()
return an observable you will have to subscribe to it.
Look at this example:
// version without map_x000D_
this.http.get("../data/navItems.json")_x000D_
.subscribe((success) => {_x000D_
this.navItems = success.json(); _x000D_
});_x000D_
_x000D_
// with map_x000D_
import 'rxjs/add/operator/map'_x000D_
this.http.get("../data/navItems.json")_x000D_
.map((data) => {_x000D_
return data.json();_x000D_
})_x000D_
.subscribe((success) => {_x000D_
this.navItems = success; _x000D_
});
_x000D_
I guess your end goal is to show Distinct (unique) values inside your original Pivot table.
For example you could have data set with OrderNumber, OrderDate, OrderItem, orderQty
First pivot table will show you OrderDate and sum of OrderQty and you probably want to see Count of unique orders in the same Pivot. You woudln't be able to do so within standard pivot table
If you want to do it, you would need Office 2016 (or perhaps pover Pivot might work). In office 2016 select your data > Insert > Pivot Table > choose tick "Add this data to the Data Model"
After that, you would be able to select grouping method as Distinct (Count)
I have same problem .I use this codes
addIntent
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Tack Image"), PICK_PHOTO);
add onActivityResult
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_PHOTO && resultCode == Activity.RESULT_OK) {
if (data == null) {
//error
return;
}
try {
Uri uri = data.getData();
File file = FileUtil.from(currentActivity, uri);
} catch (IOException e) {
e.printStackTrace();
}
}
}
FileUtil class
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.OpenableColumns;
import android.util.Log;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class FileUtil {
private static final int EOF = -1;
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
private FileUtil() {
}
public static File from(Context context, Uri uri) throws IOException {
InputStream inputStream = context.getContentResolver().openInputStream(uri);
String fileName = getFileName(context, uri);
String[] splitName = splitFileName(fileName);
File tempFile = File.createTempFile(splitName[0], splitName[1]);
tempFile = rename(tempFile, fileName);
tempFile.deleteOnExit();
FileOutputStream out = null;
try {
out = new FileOutputStream(tempFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (inputStream != null) {
copy(inputStream, out);
inputStream.close();
}
if (out != null) {
out.close();
}
return tempFile;
}
private static String[] splitFileName(String fileName) {
String name = fileName;
String extension = "";
int i = fileName.lastIndexOf(".");
if (i != -1) {
name = fileName.substring(0, i);
extension = fileName.substring(i);
}
return new String[]{name, extension};
}
private static String getFileName(Context context, Uri uri) {
String result = null;
if (uri.getScheme().equals("content")) {
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
}
if (result == null) {
result = uri.getPath();
int cut = result.lastIndexOf(File.separator);
if (cut != -1) {
result = result.substring(cut + 1);
}
}
return result;
}
private static File rename(File file, String newName) {
File newFile = new File(file.getParent(), newName);
if (!newFile.equals(file)) {
if (newFile.exists() && newFile.delete()) {
Log.d("FileUtil", "Delete old " + newName + " file");
}
if (file.renameTo(newFile)) {
Log.d("FileUtil", "Rename file to " + newName);
}
}
return newFile;
}
private static long copy(InputStream input, OutputStream output) throws IOException {
long count = 0;
int n;
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
while (EOF != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
}
and you must add provider_paths.xml to xml folder like image
provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="external_files" path="."/>
</paths>
and finaly add below in AndroidManifest.xml
<application
...>
...
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
...
</application>
I hope I helped
As mentioned by @Vivek Solanki, I also uploaded my file on the colaboratory dashboard under "File" section.
Just take a note of where the file has been uploaded. For me,
train_data = pd.read_csv('/fileName.csv')
worked.
For virtualenv to install all files in the requirements.txt file.
pip install -r requirements.txt
in your shellusing jQuery input mask plugin (6 whole and 2 decimal places):
HTML:
<input class="mask" type="text" />
jQuery:
$(".mask").inputmask('Regex', {regex: "^[0-9]{1,6}(\\.\\d{1,2})?$"});
I hope this helps someone
You can use anonymous class like this:
comboBox.DisplayMember = "Text";
comboBox.ValueMember = "Value";
comboBox.Items.Add(new { Text = "report A", Value = "reportA" });
comboBox.Items.Add(new { Text = "report B", Value = "reportB" });
comboBox.Items.Add(new { Text = "report C", Value = "reportC" });
comboBox.Items.Add(new { Text = "report D", Value = "reportD" });
comboBox.Items.Add(new { Text = "report E", Value = "reportE" });
UPDATE: Although above code will properly display in combo box, you will not be able to use SelectedValue
or SelectedText
properties of ComboBox
. To be able to use those, bind combo box as below:
comboBox.DisplayMember = "Text";
comboBox.ValueMember = "Value";
var items = new[] {
new { Text = "report A", Value = "reportA" },
new { Text = "report B", Value = "reportB" },
new { Text = "report C", Value = "reportC" },
new { Text = "report D", Value = "reportD" },
new { Text = "report E", Value = "reportE" }
};
comboBox.DataSource = items;
With numpy:
In [128]: list_a = np.array([1, 2, 4, 6])
In [129]: filter = np.array([True, False, True, False])
In [130]: list_a[filter]
Out[130]: array([1, 4])
or see Alex Szatmary's answer if list_a can be a numpy array but not filter
Numpy usually gives you a big speed boost as well
In [133]: list_a = [1, 2, 4, 6]*10000
In [134]: fil = [True, False, True, False]*10000
In [135]: list_a_np = np.array(list_a)
In [136]: fil_np = np.array(fil)
In [139]: %timeit list(itertools.compress(list_a, fil))
1000 loops, best of 3: 625 us per loop
In [140]: %timeit list_a_np[fil_np]
10000 loops, best of 3: 173 us per loop
h:commandButton must be enclosed in a h:form and has the two ways of navigation i.e. static by setting the action attribute and dynamic by setting the actionListener attribute hence it is more advanced as follows:
<h:form>
<h:commandButton action="page.xhtml" value="cmdButton"/>
</h:form>
this code generates the follwing html:
<form id="j_idt7" name="j_idt7" method="post" action="/jsf/faces/index.xhtml" enctype="application/x-www-form-urlencoded">
whereas the h:button is simpler and just used for static or rule based navigation as follows
<h:button outcome="page.xhtml" value="button"/>
the generated html is
<title>Facelet Title</title></head><body><input type="button" onclick="window.location.href='/jsf/faces/page.xhtml'; return false;" value="button" />
Have you tried using @JsonProperty?
@Entity
public class City {
@id
Long id;
String name;
@JsonProperty("label")
public String getName() { return name; }
public void setName(String name){ this.name = name; }
@JsonProperty("value")
public Long getId() { return id; }
public void setId(Long id){ this.id = id; }
}
For the line
line.split()
What are you splitting on? Looks like a CSV, so try
line.split(',')
Example:
"one,two,three".split() # returns one element ["one,two,three"]
"one,two,three".split(',') # returns three elements ["one", "two", "three"]
As @TigerhawkT3 mentions, it would be better to use the CSV module. Incredibly quick and easy method available here.
Expanding on eumiro's comment, normally tuple(l)
will convert a list l
into a tuple:
In [1]: l = [4,5,6]
In [2]: tuple
Out[2]: <type 'tuple'>
In [3]: tuple(l)
Out[3]: (4, 5, 6)
However, if you've redefined tuple
to be a tuple rather than the type
tuple
:
In [4]: tuple = tuple(l)
In [5]: tuple
Out[5]: (4, 5, 6)
then you get a TypeError since the tuple itself is not callable:
In [6]: tuple(l)
TypeError: 'tuple' object is not callable
You can recover the original definition for tuple
by quitting and restarting your interpreter, or (thanks to @glglgl):
In [6]: del tuple
In [7]: tuple
Out[7]: <type 'tuple'>
Vertical align doesn't quite work the way you want it to. See: http://phrogz.net/css/vertical-align/index.html
This isn't pretty, but it WILL do what you want: Vertical align behaves as expected only when used in a table cell.
There are other alternatives: You can declare things as tables or table cells within CSS to make them behave as desired, for example. Margins and positioning can sometimes be played with to get the same effect. None of the solutions are terrible pretty, though.
Add in pom.xml:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<version>4.0.0.RC2</version>
</dependency>
and use org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors
for authorization request.
See the sample usage at https://github.com/rwinch/spring-security-test-blog
(https://jira.spring.io/browse/SEC-2592).
Update:
4.0.0.RC2 works for spring-security 3.x. For spring-security 4 spring-security-test become part of spring-security (http://docs.spring.io/spring-security/site/docs/4.0.x/reference/htmlsingle/#test, version is the same).
Setting Up is changed: http://docs.spring.io/spring-security/site/docs/4.0.x/reference/htmlsingle/#test-mockmvc
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
Sample for basic-authentication: http://docs.spring.io/spring-security/site/docs/4.0.x/reference/htmlsingle/#testing-http-basic-authentication.
Suppose consider two string s and t.
Give them some values.
When you compare them using (s==t) it returns a boolean value(true or false , 1 or 0).
But when you compare using s.compare(t) ,the expression returns a value
(i) 0 - if s and t are equal
(ii) <0 - either if the value of the first unmatched character in s is less than that of t or the length of s is less than that of t.
(iii) >0 - either if the value of the first unmatched character in t is less than that of s or the length of t is less than that of s.
This might do the trick:
$(document).ready(function() {
$("input[type=text]").change(function() {
$(this).data("old", $(this).data("new") || "");
$(this).data("new", $(this).val());
console.log($(this).data("old"));
console.log($(this).data("new"));
});
});
Use Application.ActiveWorkbook.Path
for just the path itself (without the workbook name) or Application.ActiveWorkbook.FullName
for the path with the workbook name.
If you want unsigned bytes in Java, just subtract 256 from the number you're interested in. It will produce two's complement with a negative value, which is the desired number in unsigned bytes.
Example:
int speed = 255; //Integer with the desired byte value
byte speed_unsigned = (byte)(speed-256);
//This will be represented in two's complement so its binary value will be 1111 1111
//which is the unsigned byte we desire.
You need to use such dirty hacks when using leJOS to program the NXT brick.
I had some issues that this didn't address in getting this environment set up on OSX. It had to do with the solution that I was maintaining having additional dependencies on some of the Google APIs. It wasn't enough to just download and install the items listed in the first response.
You have to download these.
I think random.choice()
is a better option.
import numpy as np
mylist = [13,23,14,52,6,23]
np.random.choice(mylist, 3, replace=False)
the function returns an array of 3 randomly chosen values from the list
None of the above worked for me but the below did:
sudo chown -R user: /Library/Frameworks/Python.framework/Versions/3.9/share/jupyter/
Where user is your username.
To me, this is the most "natural" way to structure such data in JSON, provided that all of the keys are strings.
{
"keyvaluelist": {
"slide0001.html": "Looking Ahead",
"slide0008.html": "Forecast",
"slide0021.html": "Summary"
},
"otherdata": {
"one": "1",
"two": "2",
"three": "3"
},
"anotherthing": "thing1",
"onelastthing": "thing2"
}
I read this as
a JSON object with four elements
element 1 is a map of key/value pairs named "keyvaluelist",
element 2 is a map of key/value pairs named "otherdata",
element 3 is a string named "anotherthing",
element 4 is a string named "onelastthing"
The first element or second element could alternatively be described as objects themselves, of course, with three elements each.
This is probably not the main reason why the create_all()
method call doesn't work for people, but for me, the cobbled together instructions from various tutorials have it such that I was creating my db in a request context, meaning I have something like:
# lib/db.py
from flask import g, current_app
from flask_sqlalchemy import SQLAlchemy
def get_db():
if 'db' not in g:
g.db = SQLAlchemy(current_app)
return g.db
I also have a separate cli command that also does the create_all:
# tasks/db.py
from lib.db import get_db
@current_app.cli.command('init-db')
def init_db():
db = get_db()
db.create_all()
I also am using a application factory.
When the cli command is run, a new app context is used, which means a new db is used. Furthermore, in this world, an import model in the init_db method does not do anything, because it may be that your model file was already loaded(and associated with a separate db).
The fix that I came around to was to make sure that the db was a single global reference:
# lib/db.py
from flask import g, current_app
from flask_sqlalchemy import SQLAlchemy
db = None
def get_db():
global db
if not db:
db = SQLAlchemy(current_app)
return db
I have not dug deep enough into flask, sqlalchemy, or flask-sqlalchemy to understand if this means that requests to the db from multiple threads are safe, but if you're reading this you're likely stuck in the baby stages of understanding these concepts too.
The best solution I could find for this problem is to specify private key file in ansible.cfg (I usually keep it in the same folder as a playbook):
[defaults]
inventory=ec2.py
vault_password_file = ~/.vault_pass.txt
host_key_checking = False
private_key_file = /Users/eric/.ssh/secret_key_rsa
Though, it still sets private key globally for all hosts in playbook.
Note: You have to specify full path to the key file - ~user/.ssh/some_key_rsa silently ignored.
You need to find the position of the first /
, and then calculate the portion you want:
string url = "www.example.com/aaa/bbb.jpg";
int Idx = url.IndexOf("/");
string yourValue = url.Substring(Idx + 1, url.Length - Idx - 4);
For folks that have programmed in nodeJs before, particularly using expressJS. I think of .ashx
as a middleware that calls the next
function. While .aspx
will be the controller that actually responds to the request either around res.redirect
, res.send
or whatever.
I was in the same place as you, finally I found a neat answer :
<form action="xx/xx" method="POST">
<input type="hidden" name="what you want" value="what you want">
<input type="image" src="xx.xx">
</form>
I'd like to provide an alternate, easier solution that is specific to FontAwesome. If you're using a different iconic font, JOPLOmacedo's answer is still perfectly fine for use.
FontAwesome now handles list styles internally with CSS classes.
Here's the official example:
<ul class="fa-ul">
<li><span class="fa-li"><i class="fas fa-check-square"></i></span>List icons can</li>
<li><span class="fa-li"><i class="fas fa-check-square"></i></span>be used to</li>
<li><span class="fa-li"><i class="fas fa-spinner fa-pulse"></i></span>replace bullets</li>
<li><span class="fa-li"><i class="far fa-square"></i></span>in lists</li>
</ul>
This question has been answered here
a = [1,2,3,4]
sum(a)
sum(a) returns 10
A much simpler way nowadays is to use the jquery filter() as follows:
var options = $('select option');
var query = $('input').val();
options.filter(function() {
$(this).toggle($(this).val().toLowerCase().indexOf(query) > -1);
});
We can use npm view any-promise(your module name) -v
There's a whole page of the Django documentation devoted to this, well indexed from the contents page.
As that page states, you need to do:
my_obj.categories.add(fragmentCategory.objects.get(id=1))
or
my_obj.categories.create(name='val1')
All the above solutions work great if you develop and run the Java application outside any IDE like Eclipse or Netbeans.
If you are on Windows 7 and used Eclipse IDE for Development in Java, you might run into issues if using Command Prompt to run the class files built inside Eclipse.
E.g. Your source code in Eclipse is having the following package hierarchy: edu.sjsu.myapp.Main.java
You have json.jar as an external dependency for the Main.java
When you try running Main.java from within Eclipse, it will run without any issues.
But when you try running this using Command Prompt after compiling Main.java in Eclipse, it will shoot some weird errors saying "ClassNotDef Error blah blah".
I assume you are in the working directory of your source code !!
Use the following syntax to run it from command prompt:
javac -cp ".;json.jar" Main.java
java -cp ".;json.jar" edu.sjsu.myapp.Main
[Don't miss the . above]
This is because you have placed the Main.java inside the package edu.sjsu.myapp and java.exe will look for the exact pattern.
Hope it helps !!
Adding file-loader npm to webpack.config.js per its official usage instruction like so:
config.module.rules.push(
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {}
}
]
}
);
worked for me.
Pretty simple: Just put it inside a static method.
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(linkYouTube)));
C99 has log2
(as well as log2f
and log2l
for float and long double).
Since Bootstrap 3 removed the submenu part and we need to adapt ourselves the style, I think it's better to go with SmartMenu Bootstrap: https://vadikom.github.io/smartmenus/src/demo/bootstrap-navbar.html#
That would save us time on mobile responsive and style.
This plugin also very promising.
"Commercial use" in cases like this is actually just a shorthand to indicate that the product is dual-licensed under both an open source and a traditional paid-for commercial license.
Any "true" open source license will not discriminate against commercial use. (See clause 6 of the Open Source Definition.) However, open source licenses like the GPL contain clauses that are incompatible with most companies' approach to commercial software (since the GPL requires that you make your source code available if you incorporate GPL'ed code into your product).
Duel-licensing is a way to accommodate this and also provides a revenue stream for the company providing the software. For users that don't mind the restrictions of the GPL and don't need support, the product is available under an open source license. For users for whom the GPL's restrictions would be incompatible with their business model, and for users that do need support, a commercial license is available.
You gave the specific example of the Screwturn wiki, which is dual-licensed under the GPL and a commercial license. Under the terms of the GPL (i.e., without getting a "commercial" license), you can do the following:
In other words, there's a lot that you can do without getting a commercial license. This is especially true for web-based software, since people can use web-based software without it being distributed to them. Screwturn's web site even acknowledges this: they state that the commercial license is for "either integrating it in a commercial application, or using it in an enterprise environment where free software is not allowed," not for any use related to commerce.
All of the preceding is merely my understanding and is not intended to be legal advice. Consult your lawyer to be certain.
Though this is a late answer, I found this from NodeJS docs:
The 'exit' event is emitted when the REPL is exited either by receiving the
.exit
command as input, the user pressing<ctrl>-C
twice to signal SIGINT, or by pressing<ctrl>-D
to signal 'end' on the input stream. The listener callback is invoked without any arguments.
So to summarize you can exit by:
.exit
in nodejs REPL.<ctrl>-C
twice. <ctrl>-D
. process.exit(0)
meaning a natural exit from REPL. If you want to return any other status you can return a non zero number. process.kill(process.pid)
is the way to kill using nodejs api from within your code or from REPL.Behind the scenes, the anonymous delegate gets turned into an actual method so you could have some overhead with the second choice if the compiler didn't choose to inline the function. Additionally, any local variables referenced by the body of the anonymous delegate example would change in nature because of compiler tricks to hide the fact that it gets compiled to a new method. More info here on how C# does this magic:
http://blogs.msdn.com/oldnewthing/archive/2006/08/04/688527.aspx
You need to retrieve the checkbox before using it.
Give the checkbox an id
attribute to retrieve it with document.getElementById(..)
and then check its current state.
For example:
function checkAddress()
{
var chkBox = document.getElementById('checkAddress');
if (chkBox.checked)
{
// ..
}
}
And your HTML would then look like this:
<input type="checkbox" id="checkAddress" name="checkAddress" onclick="checkAddress()"/>
(Also changed the onchange
to onclick
. Doesn't work quite well in IE :).
What you are trying to do is add additional information to each item in the list that you already created so
alist[ 'from form', 'stuff 2', 'stuff 3']
for j in range( 0,len[alist]):
temp= []
temp.append(alist[j]) # alist[0] is 'from form'
temp.append('t') # slot for first piece of data 't'
temp.append('-') # slot for second piece of data
blist.append(temp) # will be alist with 2 additional fields for extra stuff assocated with each item in alist
You can go to Design mode and select "Fix" at the bottom of the warning. Then a pop up will appear (seems like it's going to register the new string) and voila, the error is fixed.
I fix my problem with javascript + HTML. First i check selected options and save its in a hidden field of my form:
for(i=0; i < form.select.options.length; i++)
if (form.select.options[i].selected)
form.hidden.value += form.select.options[i].value;
Next, i get by post that field and get all the string ;-) I hope it'll be work for somebody more. Thanks to all.
There's a much, much easier way. Do this:
MyComponent.vue
<template>
stuff here
</template>
<script>
import $ from 'jquery';
import 'selectize';
$(function() {
// use jquery
$('body').css('background-color', 'orange');
// use selectize, s jquery plugin
$('#myselect').selectize( options go here );
});
</script>
Make sure JQuery is installed first with npm install jquery
. Do the same with your plugin.
View(function_name)
- eg. View(mean)
Make sure to use uppercase [V]. The read-only code will open in the editor.
What you have is EXTRATERRESTRIAL ALIEN (U+1F47D)
and BROKEN HEART (U+1F494)
which
are not in the basic multilingual plane. They cannot be even represented in java as one char, "".length() == 4
. They are definitely not null characters and one will see squares if you are not using fonts that support them.
MySQL's utf8
only supports basic multilingual plane, and you need to use utf8mb4
instead:
For a supplementary character, utf8 cannot store the character at all, while utf8mb4 requires four bytes to store it. Since utf8 cannot store the character at all, you do not have any supplementary characters in utf8 columns and you need not worry about converting characters or losing data when upgrading utf8 data from older versions of MySQL.
So to support these characters, your MySQL needs to be 5.5+ and you need to use utf8mb4
everywhere. Connection encoding needs to be utf8mb4
, character set needs to be utf8mb4
and collaction needs to be utf8mb4
. For java it's still just "utf-8"
, but MySQL needs a distinction.
I don't know what driver you are using but a driver agnostic way to set connection charset is to send the query:
SET NAMES 'utf8mb4'
Right after making the connection.
See also this for Connector/J:
14.14: How can I use 4-byte UTF8, utf8mb4 with Connector/J?
To use 4-byte UTF8 with Connector/J configure the MySQL server with character_set_server=utf8mb4. Connector/J will then use that setting as long as characterEncoding has not been set in the connection string. This is equivalent to autodetection of the character set.
Adjust your columns and database as well:
var1 varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL
Again, your MySQL version needs to be relatively up-to-date for utf8mb4 support.
Iterating over dictionaries using 'for' loops
d = {'x': 1, 'y': 2, 'z': 3} for key in d: ...
How does Python recognize that it needs only to read the key from the dictionary? Is key a special word in Python? Or is it simply a variable?
It's not just for
loops. The important word here is "iterating".
A dictionary is a mapping of keys to values:
d = {'x': 1, 'y': 2, 'z': 3}
Any time we iterate over it, we iterate over the keys. The variable name key
is only intended to be descriptive - and it is quite apt for the purpose.
This happens in a list comprehension:
>>> [k for k in d]
['x', 'y', 'z']
It happens when we pass the dictionary to list (or any other collection type object):
>>> list(d)
['x', 'y', 'z']
The way Python iterates is, in a context where it needs to, it calls the __iter__
method of the object (in this case the dictionary) which returns an iterator (in this case, a keyiterator object):
>>> d.__iter__()
<dict_keyiterator object at 0x7fb1747bee08>
We shouldn't use these special methods ourselves, instead, use the respective builtin function to call it, iter
:
>>> key_iterator = iter(d)
>>> key_iterator
<dict_keyiterator object at 0x7fb172fa9188>
Iterators have a __next__
method - but we call it with the builtin function, next
:
>>> next(key_iterator)
'x'
>>> next(key_iterator)
'y'
>>> next(key_iterator)
'z'
>>> next(key_iterator)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
When an iterator is exhausted, it raises StopIteration
. This is how Python knows to exit a for
loop, or a list comprehension, or a generator expression, or any other iterative context. Once an iterator raises StopIteration
it will always raise it - if you want to iterate again, you need a new one.
>>> list(key_iterator)
[]
>>> new_key_iterator = iter(d)
>>> list(new_key_iterator)
['x', 'y', 'z']
We've seen dicts iterating in many contexts. What we've seen is that any time we iterate over a dict, we get the keys. Back to the original example:
d = {'x': 1, 'y': 2, 'z': 3} for key in d:
If we change the variable name, we still get the keys. Let's try it:
>>> for each_key in d:
... print(each_key, '=>', d[each_key])
...
x => 1
y => 2
z => 3
If we want to iterate over the values, we need to use the .values
method of dicts, or for both together, .items
:
>>> list(d.values())
[1, 2, 3]
>>> list(d.items())
[('x', 1), ('y', 2), ('z', 3)]
In the example given, it would be more efficient to iterate over the items like this:
for a_key, corresponding_value in d.items():
print(a_key, corresponding_value)
But for academic purposes, the question's example is just fine.
You can use a temporary deletion list:
List<String> keyList = new ArrayList<String>;
for(Map.Entry<String,String> entry : hashTable){
if(entry.getValue().equals("delete")) // replace with your own check
keyList.add(entry.getKey());
}
for(String key : keyList){
hashTable.remove(key);
}
You can find more information about Hashtable methods in the Java API
it is very simple....
[in make file]
==== 1 ===================
OBJS = ....\
version.o <<== add to your obj lists
==== 2 ===================
DATE = $(shell date +'char szVersionStr[20] = "%Y-%m-%d %H:%M:%S";') <<== add
all:version $(ProgramID) <<== version add at first
version: <<== add
echo '$(DATE)' > version.c <== add ( create version.c file)
[in program]
=====3 =============
extern char szVersionStr[20];
[ using ]
=== 4 ====
printf( "Version: %s\n", szVersionStr );
From the documentation:
__file__
is the pathname of the file from which the module was loaded, if it was loaded from a file. The__file__
attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.
From the mailing list thread linked by @kindall in a comment to the question:
I haven't tried to repro this particular example, but the reason is that we don't want to have to call getpwd() on every import nor do we want to have some kind of in-process variable to cache the current directory. (getpwd() is relatively slow and can sometimes fail outright, and trying to cache it has a certain risk of being wrong.)
What we do instead, is code in site.py that walks over the elements of sys.path and turns them into absolute paths. However this code runs before '' is inserted in the front of sys.path, so that the initial value of sys.path is ''.
For the rest of this, consider sys.path
not to include ''
.
So, if you are outside the part of sys.path
that contains the module, you'll get an absolute path. If you are inside the part of sys.path
that contains the module, you'll get a relative path.
If you load a module in the current directory, and the current directory isn't in sys.path
, you'll get an absolute path.
If you load a module in the current directory, and the current directory is in sys.path
, you'll get a relative path.
webRequest.ContentType = "application/x-www-form-urlencoded";
Where does application/x-www-form-urlencoded's name come from?
If you send HTTP GET request, you can use query parameters as follows:
http://example.com/path/to/page
?name=ferret&color=purple
The content of the fields is encoded as a query string. The application/x-www-form-
urlencoded
's name come from the previous url query parameter but the query parameters is
in where the body of request instead of url.
The whole form data is sent as a long query string.The query string contains name- value pairs separated by & character
e.g. field1=value1&field2=value2
It can be simple request called simple - don't trigger a preflight check
Simple request must have some properties. You can look here for more info. One of them is that there are only three values allowed for Content-Type header for simple requests
3.For mostly flat param trees, application/x-www-form-urlencoded is tried and tested.
request.ContentType = "application/json; charset=utf-8";
axios and superagent, two of the more popular npm HTTP libraries, work with JSON bodies by default.
{ "id": 1, "name": "Foo", "price": 123, "tags": [ "Bar", "Eek" ], "stock": { "warehouse": 300, "retail": 20 } }
Now, if the request isn't simple request, the browser automatically sends a HTTP request before the original one by OPTIONS method to check whether it is safe to send the original request. If itis ok, Then send actual request. You can look here for more info.
No difference here, but it matters when you have a type that has a constructor.
struct S {
constexpr S(int);
};
const S s0(0);
constexpr S s1(1);
s0
is a constant, but it does not promise to be initialized at compile-time. s1
is marked constexpr
, so it is a constant and, because S
's constructor is also marked constexpr
, it will be initialized at compile-time.
Mostly this matters when initialization at runtime would be time-consuming and you want to push that work off onto the compiler, where it's also time-consuming, but doesn't slow down execution time of the compiled program
In MySQL use the '^'
to identify you want to check the first char of the string then define the array [] of letters you want to check for.
Try This
SELECT * FROM artists WHERE name REGEXP '^[abc]'
Well, the "last five rows" are actually the last five rows depending on your clustered index. Your clustered index, by definition, is the way that he rows are ordered. So you really can't get the "last five rows" without some order. You can, however, get the last five rows as it pertains to the clustered index.
SELECT TOP 5 * FROM MyTable
ORDER BY MyCLusteredIndexColumn1, MyCLusteredIndexColumnq, ..., MyCLusteredIndexColumnN DESC
This is to do with the encoding of your terminal not being set to UTF-8. Here is my terminal
$ echo $LANG
en_GB.UTF-8
$ python
Python 2.7.3 (default, Apr 20 2012, 22:39:59)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = '(\xef\xbd\xa1\xef\xbd\xa5\xcf\x89\xef\xbd\xa5\xef\xbd\xa1)\xef\xbe\x89'
>>> s1 = s.decode('utf-8')
>>> print s1
(?????)?
>>>
On my terminal the example works with the above, but if I get rid of the LANG
setting then it won't work
$ unset LANG
$ python
Python 2.7.3 (default, Apr 20 2012, 22:39:59)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = '(\xef\xbd\xa1\xef\xbd\xa5\xcf\x89\xef\xbd\xa5\xef\xbd\xa1)\xef\xbe\x89'
>>> s1 = s.decode('utf-8')
>>> print s1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-5: ordinal not in range(128)
>>>
Consult the docs for your linux variant to discover how to make this change permanent.
Here's my bash command line to list multiple certificates in order of their expiration, most recently expiring first.
for pem in /etc/ssl/certs/*.pem; do
printf '%s: %s\n' \
"$(date --date="$(openssl x509 -enddate -noout -in "$pem"|cut -d= -f 2)" --iso-8601)" \
"$pem"
done | sort
Sample output:
2015-12-16: /etc/ssl/certs/Staat_der_Nederlanden_Root_CA.pem
2016-03-22: /etc/ssl/certs/CA_Disig.pem
2016-08-14: /etc/ssl/certs/EBG_Elektronik_Sertifika_Hizmet_S.pem
In my case, HTTPS protocol was not supported by libcurl at the first place. To find out which protocols are supported and which are not, I checked the curl version using command:
curl --version
It provided information as follows:
curl 7.50.3 (x86_64-apple-darwin15.6.0) libcurl/7.50.3 SecureTransport zlib/1.2.5
Protocols: dict file ftp ftps gopher http imap imaps ldap ldaps pop3 pop3s rtsp smb smbs smtp smtps telnet tftp
Features: IPv6 Largefile NTLM NTLM_WB SSL libz UnixSockets
where https protocol happens to be not supported.
Then I re-installed curl and installed it using the following commands(after unpacked):
./configure --with-darwinssl (enable ssl communication in mac) make make test sudo make install
And after several minutes of work, Problems resolved!
Then I re-run the curl version command, it showed:
curl 7.50.3 (x86_64-apple-darwin15.6.0) libcurl/7.50.3 SecureTransport zlib/1.2.5
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp smb smbs smtp smtps telnet tftp
Features: IPv6 Largefile NTLM NTLM_WB SSL libz UnixSockets
HTTPS protocol showed up!
Finally, a useful site to refer when you run into curl problems.
https://curl.haxx.se/docs/install.html
It's an implicit conversion to bool
. I.e. wherever implicit conversions are allowed, your class can be converted to bool
by calling that method.
if you are getting a message (IOS8 / swift) that viewDidLayoutSubviews
does not exist, use the following instead
override func viewDidAppear(animated: Bool)
This fixed it for me
Another option would be to use Angular's built-in pub-sub architecture in order to notify your directive to focus. Similar to the other approaches, but it's then not directly tied to a property, and is instead listening in on it's scope for a particular key.
Directive:
angular.module("app").directive("focusOn", function($timeout) {
return {
restrict: "A",
link: function(scope, element, attrs) {
scope.$on(attrs.focusOn, function(e) {
$timeout((function() {
element[0].focus();
}), 10);
});
}
};
});
HTML:
<input type="text" name="text_input" ng-model="ctrl.model" focus-on="focusTextInput" />
Controller:
//Assume this is within your controller
//And you've hit the point where you want to focus the input:
$scope.$broadcast("focusTextInput");
With minimal editing to your code (Not sure if they've taught classes or not in your course), change:
def close_window(root):
root.destroy()
to
def close_window():
window.destroy()
and it should work.
Explanation:
Your version of close_window
is defined to expect a single argument, namely root
. Subsequently, any calls to your version of close_window
need to have that argument, or Python will give you a run-time error.
When you created a Button
, you told the button to run close_window
when it is clicked. However, the source code for Button widget is something like:
# class constructor
def __init__(self, some_args, command, more_args):
#...
self.command = command
#...
# this method is called when the user clicks the button
def clicked(self):
#...
self.command() # Button calls your function with no arguments.
#...
As my code states, the Button
class will call your function with no arguments. However your function is expecting an argument. Thus you had an error. So, if we take out that argument, so that the function call will execute inside the Button class, we're left with:
def close_window():
root.destroy()
That's not right, though, either, because root
is never assigned a value. It would be like typing in print(x)
when you haven't defined x
, yet.
Looking at your code, I figured you wanted to call destroy
on window
, so I changed root
to window
.
Greybox cannot handle forms inside it on its own. It requires a forms plugin. No iframes or external html files needed. Don't forget to download the greybox.css file too as the page misses that bit out.
Kiss Jquery UI goodbye and a lightbox hello. You can get it here.
I had issues installing Express on Ubuntu:
If for some reason NPM command is missing, test npm command with npm help
. If not there, follow these steps - http://arnolog.net/post/8424207595/installing-node-js-npm-express-mongoose-on-ubuntu
If just the Express command is not working, try:
sudo npm install -g express
This made everything work as I'm used to with Windows7 and OSX.
Hope this helps!
As was mentioned in an older version (2009) of the "Tree Conflict" design document:
XFAIL conflict from merge of add over versioned file
This test does a merge which brings a file addition without history onto an existing versioned file.
This should be a tree conflict on the file of the 'local obstruction, incoming add upon merge
' variety. Fixed expectations in r35341.
(This is also called "evil twins" in ClearCase by the way):
a file is created twice (here "added" twice) in two different branches, creating two different histories for two different elements, but with the same name.
The theoretical solution is to manually merge those files (with an external diff tool) in the destination branch 'B2
'.
If you still are working on the source branch, the ideal scenario would be to remove that file from the source branch B1
, merge back from B2
to B1
in order to make that file visible on B1
(you will then work on the same element).
If a merge back is not possible because merges only occurs from B1
to B2
, then a manual merge will be necessary for each B1->B2
merges.
Try this:
SELECT to_char(sysdate - (2 / 24), 'MM-DD-YYYY HH24') FROM DUAL
To test it using a new date instance:
SELECT to_char(TO_DATE('11/06/2015 00:00','dd/mm/yyyy HH24:MI') - (2 / 24), 'MM-DD-YYYY HH24:MI') FROM DUAL
Output is: 06-10-2015 22:00, which is the previous day.
To dismiss the Viewcontroller called with the previous answers code by CmdSft
ViewController *viewController = [[ViewController alloc] init];
[self presentViewController:viewController animated:YES completion:nil];
you can use
[self dismissViewControllerAnimated:YES completion: nil];
It can be done in bash itself if you have control of the configuration file format. You just need to source (".") the configuration file rather than subshell it. That ensures the variables are created in the context of the current shell (and continue to exist) rather than the subshell (where the variable disappear when the subshell exits).
$ cat config.data
export parm_jdbc=jdbc:db2://box7.co.uk:5000/INSTA
export parm_user=pax
export parm_pwd=never_you_mind
$ cat go.bash
. config.data
echo "JDBC string is " $parm_jdbc
echo "Username is " $parm_user
echo "Password is " $parm_pwd
$ bash go.bash
JDBC string is jdbc:db2://box7.co.uk:5000/INSTA
Username is pax
Password is never_you_mind
If your config file cannot be a shell script, you can just 'compile' it before executing thus (the compilation depends on your input format).
$ cat config.data
parm_jdbc=jdbc:db2://box7.co.uk:5000/INSTA # JDBC URL
parm_user=pax # user name
parm_pwd=never_you_mind # password
$ cat go.bash
cat config.data
| sed 's/#.*$//'
| sed 's/[ \t]*$//'
| sed 's/^[ \t]*//'
| grep -v '^$'
| sed 's/^/export '
>config.data-compiled
. config.data-compiled
echo "JDBC string is " $parm_jdbc
echo "Username is " $parm_user
echo "Password is " $parm_pwd
$ bash go.bash
JDBC string is jdbc:db2://box7.co.uk:5000/INSTA
Username is pax
Password is never_you_mind
In your specific case, you could use something like:
$ cat config.data
export p_p1=val1
export p_p2=val2
$ cat go.bash
. ./config.data
echo "select * from dbtable where p1 = '$p_p1' and p2 like '$p_p2%' order by p1"
$ bash go.bash
select * from dbtable where p1 = 'val1' and p2 like 'val2%' order by p1
Then pipe the output of go.bash into MySQL and voila, hopefully you won't destroy your database :-).
Note that you can also make your Makefile simpler, at the same time:
DEBUG ?= 1
ifeq (DEBUG, 1)
CFLAGS =-g3 -gdwarf2 -DDEBUG
else
CFLAGS=-DNDEBUG
endif
CXX = g++ $(CFLAGS)
CC = gcc $(CFLAGS)
EXECUTABLE = output
OBJECTS = CommandParser.tab.o CommandParser.yy.o Command.o
LIBRARIES = -lfl
all: $(EXECUTABLE)
$(EXECUTABLE): $(OBJECTS)
$(CXX) -o $@ $^ $(LIBRARIES)
%.yy.o: %.l
flex -o $*.yy.c $<
$(CC) -c $*.yy.c
%.tab.o: %.y
bison -d $<
$(CXX) -c $*.tab.c
%.o: %.cpp
$(CXX) -c $<
clean:
rm -f $(EXECUTABLE) $(OBJECTS) *.yy.c *.tab.c
Now you don't have to repeat filenames all over the place. Any .l files will get passed through flex and gcc, any .y files will get passed through bison and g++, and any .cpp files through just g++.
Just list the .o files you expect to end up with, and Make will do the work of figuring out which rules can satisfy the needs...
for the record:
$@
The name of the target file (the one before the colon)
$<
The name of the first (or only) prerequisite file (the first one after the colon)
$^
The names of all the prerequisite files (space separated)
$*
The stem (the bit which matches the %
wildcard in the rule definition.
Here is a functional ES6 way of iterating over a NodeList
. This method uses the Array
's forEach
like so:
Array.prototype.forEach.call(element.childNodes, f)
Where f
is the iterator function that receives a child nodes as it's first parameter and the index as the second.
If you need to iterate over NodeLists more than once you could create a small functional utility method out of this:
const forEach = f => x => Array.prototype.forEach.call(x, f);
// For example, to log all child nodes
forEach((item) => { console.log(item); })(element.childNodes)
// The functional forEach is handy as you can easily created curried functions
const logChildren = forEach((childNode) => { console.log(childNode); })
logChildren(elementA.childNodes)
logChildren(elementB.childNodes)
(You can do the same trick for map()
and other Array functions.)
Take Matt Solnit example, imagine that you define an association between Car and Wheels as LAZY and you need some Wheels fields. This means that after the first select, hibernate is going to do "Select * from Wheels where car_id = :id" FOR EACH Car.
This makes the first select and more 1 select by each N car, that's why it's called n+1 problem.
To avoid this, make the association fetch as eager, so that hibernate loads data with a join.
But attention, if many times you don't access associated Wheels, it's better to keep it LAZY or change fetch type with Criteria.
You could do it without javascript and simply use anchor tags? Then it would be accessible to those js free.
although as you are using modals, I assume you don't care about being js free. ;)
Try:
SELECT DATE(`date_time_field`) AS date_part, TIME(`date_time_field`) AS time_part FROM `your_table`
http://www.javaspecialists.co.za/archive/Issue113.html
The solution starts out similar to yours with an int value as part of the enum definition. He then goes on to create a generics-based lookup utility:
public class ReverseEnumMap<V extends Enum<V> & EnumConverter> {
private Map<Byte, V> map = new HashMap<Byte, V>();
public ReverseEnumMap(Class<V> valueType) {
for (V v : valueType.getEnumConstants()) {
map.put(v.convert(), v);
}
}
public V get(byte num) {
return map.get(num);
}
}
This solution is nice and doesn't require 'fiddling with reflection' because it's based on the fact that all enum types implicitly inherit the Enum interface.
Another way is to use the DateTime class, this way you can also specify the timezone. Note: PHP 5.3 or higher.
// For the current date
function isTodayWeekend() {
$currentDate = new DateTime("now", new DateTimeZone("Europe/Amsterdam"));
return $currentDate->format('N') >= 6;
}
If you need to be able to check a certain date string, you can use DateTime::createFromFormat
function isWeekend($date) {
$inputDate = DateTime::createFromFormat("d-m-Y", $date, new DateTimeZone("Europe/Amsterdam"));
return $inputDate->format('N') >= 6;
}
The beauty of this way is that you can specify the timezone without changing the timezone globally in PHP, which might cause side-effects in other scripts (for ex. Wordpress).
There is a file called config.inc.php in the phpmyadmin folder.
The file path is C:\wamp\apps\phpmyadmin4.0.4
Edit The auth_type 'cookie' to 'config' or 'http'
$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['auth_type'] = 'config';
or
$cfg['Servers'][$i]['auth_type'] = 'http';
When you go to the phpmyadmin site then you will be asked for the username and password. This also secure external people from accessing your phpmyadmin application if you happen to have your web server exposed to outside connections.
which means that cacerts keystore isn't password protected
That's a false assumption. If you read more carefully, you'll find that the listing was provided without verifying the integrity of the keystore because you didn't provide the password. The listing doesn't require a password, but your keystore definitely has a password, as indicated by:
In order to verify its integrity, you must provide your keystore password.
Java's default cacerts password is "changeit", unless you're on a Mac, where it's "changeme" up to a certain point. Apparently as of Mountain Lion (based on comments and another answer here), the password for Mac is now also "changeit", probably because Oracle is now handling distribution for the Mac JVM as well.
In my case I had to update windows first, after that the problem has gone.
Using functions with the ellipses is not very safe. If performance is not critical for log function consider using operator overloading as in boost::format. You could write something like this:
#include <sstream>
#include <boost/format.hpp>
#include <iostream>
using namespace std;
class formatted_log_t {
public:
formatted_log_t(const char* msg ) : fmt(msg) {}
~formatted_log_t() { cout << fmt << endl; }
template <typename T>
formatted_log_t& operator %(T value) {
fmt % value;
return *this;
}
protected:
boost::format fmt;
};
formatted_log_t log(const char* msg) { return formatted_log_t( msg ); }
// use
int main ()
{
log("hello %s in %d-th time") % "world" % 10000000;
return 0;
}
The following sample demonstrates possible errors with ellipses:
int x = SOME_VALUE;
double y = SOME_MORE_VALUE;
printf( "some var = %f, other one %f", y, x ); // no errors at compile time, but error at runtime. compiler do not know types you wanted
log( "some var = %f, other one %f" ) % y % x; // no errors. %f only for compatibility. you could write %1% instead.
Declare it as a decimal
which uses the int
variable and divide this by 100
int number = 700
decimal correctNumber = (decimal)number / 100;
Edit: Bala was faster with his reaction
dim mydate = from cv in mydata.t1s
select cv.date1 asc
datetime mindata = mydate[0];
You should always avoid using system()
because
You should use CreateProcess().
You can use Createprocess() to just start up an .exe and creating a new process for it. The application will run independent from the calling application.
Here's an example I used in one of my projects:
#include <windows.h>
VOID startup(LPCTSTR lpApplicationName)
{
// additional information
STARTUPINFO si;
PROCESS_INFORMATION pi;
// set the size of the structures
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
// start the program up
CreateProcess( lpApplicationName, // the path
argv[1], // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi // Pointer to PROCESS_INFORMATION structure (removed extra parentheses)
);
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}
EDIT: The error you are getting is because you need to specify the path of the .exe file not just the name. Openfile.exe probably doesn't exist.
I am using Jupiter Notebook 5.6.0. Here, to get autosuggestion I am just hitting Tab key after entering at least one character.
**Example:** Enter character `p` and hit Tab.
To get the methods and properties inside the imported library use same Tab key with Alice
import numpy as np
np. --> Hit Tab key
Just dot is working. The doctype makes a difference however as sometimes the ./ is fine as well.
<a href=".">Link to this folder</a>
Your id will be passed through as #1, #2 etc. However, # is not valid as an ID (CSS selectors prefix IDs with #).
Here is a very simple way:
<asp:ButtonField ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True"
CommandArgument='<%# Container.DataItemIndex %>' />
If the problem is not solved by above answer, check whether the Windows SDK version is 10.0.15063.0.
Project -> Properties -> General -> Windows SDK Version -> select 10.0.15063.0
After this rebuild the solution.
If you're a fan of NumPy
ish syntax, then there's tensor.shape
.
In [3]: ar = torch.rand(3, 3)
In [4]: ar.shape
Out[4]: torch.Size([3, 3])
# method-1
In [7]: list(ar.shape)
Out[7]: [3, 3]
# method-2
In [8]: [*ar.shape]
Out[8]: [3, 3]
# method-3
In [9]: [*ar.size()]
Out[9]: [3, 3]
P.S.: Note that tensor.shape
is an alias to tensor.size()
, though tensor.shape
is an attribute of the tensor in question whereas tensor.size()
is a function.
I use this command.
kubectl -n <namespace> logs -f deployment/<app-name> --all-containers=true --since=10m
^(((([13578]|0[13578]|1[02])[-](0[1-9]|[1-9]|1[0-9]|2[0-9]|3[01]))|(([469]|0[469]|11)[-]([1-9]|1[0-9]|2[0-9]|3[0]))|((2|02)([-](0[1-9]|1[0-9]|2[0-8]))))[-](19([6-9][0-9])|20([0-9][0-9])))|((02)[-](29)[-](19(6[048]|7[26]|8[048]|9[26])|20(0[048]|1[26]|2[048])))
this regex will validate dates in format:
12-30-2016 (mm-dd-yyyy) or 12-3-2016 (mm-d-yyyy) or 1-3-2016 (m-d-yyyy) or 1-30-2016 (m-dd-yyyy)
Just go to your android/app/build.gradle
and then add to the dependencies
section:
dependencies{
compile ("com.facebook.react:react-native:0.50.3") { force = true }
}
/// the react native version can be found in package.json
$(window).on("touchstart", function(ev) {
var e = ev.originalEvent;
console.log(e.touches);
});
I know it been asked a long time ago, but I thought a concrete example might help.
Word of warning: if you put config files in your WEB-INF/classes
folder, and your IDE, say Eclipse, does a clean/rebuild, it will nuke your conf files unless they were in the Java source directory. BalusC's great answer alludes to that in option 1 but I wanted to add emphasis.
I learned the hard way that if you "copy" a web project in Eclipse, it does a clean/rebuild from any source folders. In my case I had added a "linked source dir" from our POJO java library, it would compile to the WEB-INF/classes
folder. Doing a clean/rebuild in that project (not the web app project) caused the same problem.
I thought about putting my confs in the POJO src folder, but these confs are all for 3rd party libs (like Quartz or URLRewrite) that are in the WEB-INF/lib
folder, so that didn't make sense. I plan to test putting it in the web projects "src" folder when i get around to it, but that folder is currently empty and having conf files in it seems inelegant.
So I vote for putting conf files in WEB-INF/commonConfFolder/filename.properties
, next to the classes folder, which is Balus option 2.
<head><script>var xxx = ${params.xxx}</script></head>
Using EL expression ${param.xxx} in <head>
to get params from a post method, and make sure the js file is included after <head>
so that you can handle a param like 'xxx' directly in your js file.
The issue is that you are not able to get a connection to MYSQL database and hence it is throwing an error saying that cannot build a session factory.
Please see the error below:
Caused by: java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO)
which points to username
not getting populated
.
Please recheck system properties
dataSource.setUsername(System.getProperty("root"));
some packages seems to be missing as well pointing to a dependency issue:
package org.gjt.mm.mysql does not exist
Please run a mvn dependency:tree
command to check for dependencies
You should install node.js with nvm, because that way you do not have to provide superuser privileges when installing global packages (you can simply execute "npm install -g packagename" without prepending 'sudo').
Brew is fantastic for other things, however. I tend to be biased towards Bower whenever I have the option to install something with Bower.
As an important issue, when you want to utilize shell to delete .svn folders You need -depth argument to prevent find command entering the directory that was just deleted and showing error messages like e.g.
"find: ./.svn: No such file or directory"
As a result, You can use find command like below:
cd [dir_to_delete_svn_folders]
find . -depth -name .svn -exec rm -fr {} \;
OK, but you don`t want to open the whole realtime database! You need something like this.
{
/* Visit https://firebase.google.com/docs/database/security to learn more about security rules. */
"rules": {
".read": "auth.uid !=null",
".write": "auth.uid !=null"
}
}
or
{
"rules": {
"users": {
"$uid": {
".write": "$uid === auth.uid"
}
}
}
}
Use the System.Web.UI.HtmlTextWriter class.
StringWriter writer = new StringWriter();
HtmlTextWriter html = new HtmlTextWriter(writer);
html.RenderBeginTag(HtmlTextWriterTag.H1);
html.WriteEncodedText("Heading Here");
html.RenderEndTag();
html.WriteEncodedText(String.Format("Dear {0}", userName));
html.WriteBreak();
html.RenderBeginTag(HtmlTextWriterTag.P);
html.WriteEncodedText("First part of the email body goes here");
html.RenderEndTag();
html.Flush();
string htmlString = writer.ToString();
For extensive HTML that includes the creation of style attributes HtmlTextWriter is probably the best way to go. However it can be a bit clunky to use and some developers like the markup itself to be easily read but perversly HtmlTextWriter's choices with regard indentation is a bit wierd.
In this example you can also use XmlTextWriter quite effectively:-
writer = new StringWriter();
XmlTextWriter xml = new XmlTextWriter(writer);
xml.Formatting = Formatting.Indented;
xml.WriteElementString("h1", "Heading Here");
xml.WriteString(String.Format("Dear {0}", userName));
xml.WriteStartElement("br");
xml.WriteEndElement();
xml.WriteElementString("p", "First part of the email body goes here");
xml.Flush();
data = """a,b,c
d,e,f
g,h,i
j,k,l"""
print(data.split()) # ['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']
str.split
, by default, splits by all the whitespace characters. If the actual string has any other whitespace characters, you might want to use
print(data.split("\n")) # ['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']
Or as @Ashwini Chaudhary suggested in the comments, you can use
print(data.splitlines())
Looking at the code always helps too. That is, you can actually take a look at the generated partial class (that calls LoadComponent) by doing the following:
The YourClass.g.cs ... is the code for generated partial class. Again, if you open that up you can see the InitializeComponent method and how it calls LoadComponent ... and much more.
The direct formula produces big integers when n is bigger than 20.
So, yet another response:
from math import factorial
reduce(long.__mul__, range(n-r+1, n+1), 1L) // factorial(r)
short, accurate and efficient because this avoids python big integers by sticking with longs.
It is more accurate and faster when comparing to scipy.special.comb:
>>> from scipy.special import comb
>>> nCr = lambda n,r: reduce(long.__mul__, range(n-r+1, n+1), 1L) // factorial(r)
>>> comb(128,20)
1.1965669823265365e+23
>>> nCr(128,20)
119656698232656998274400L # accurate, no loss
>>> from timeit import timeit
>>> timeit(lambda: comb(n,r))
8.231969118118286
>>> timeit(lambda: nCr(128, 20))
3.885951042175293
Actually, for the configuration of the machine, just open the .vmx file with a text editor (e.g. notepad, gedit, etc.). You will be able to see the OS type, memsize, ethernet.connectionType, and other settings. Then when you make your machine, just look in the text editor for the corresponding settings. When it asks for the disk, select the .vmdk disk as mentioned above.
You can create an ExpandoObject like this:
IDictionary<string,object> expando = new ExpandoObject();
expando["Name"] = value;
And after casting it to dynamic, those values will look like properties:
dynamic d = expando;
Console.WriteLine(d.Name);
However, they are not actual properties and cannot be accessed using Reflection. So the following statement will return a null:
d.GetType().GetProperty("Name")
You can minimize this function in a lot of way, and you can also implement it with a custom regex for negative values or custom charts:
$('.number').on('input',function(){
var n=$(this).val().replace(/ /g,'').replace(/\D/g,'');
if (!$.isNumeric(n))
$(this).val(n.slice(0, -1))
else
$(this).val(n)
});
Here is a function which I use as a part of my Utils
class:
public static boolean isNetworkConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return (cm.getActiveNetworkInfo() != null) && cm.getActiveNetworkInfo().isConnectedOrConnecting();
}
Use it like: Utils.isNetworkConnected(MainActivity.this);
It is possible to get traffic data. Below is my implementation in python. The API has some quota & is not fully free, but good enough for small projects
import requests
import time
import json
while True:
url = "https://maps.googleapis.com/maps/api/distancematrix/json"
querystring = {"units":"metric","departure_time":str(int(time.time())),"traffic_model":"best_guess","origins":"ITPL,Bangalore","destinations":"Tin Factory,Bangalore","key":"GetYourKeyHere"}
headers = {
'cache-control': "no-cache",
'postman-token': "something"
}
response = requests.request("GET", url, headers=headers, params=querystring)
d = json.loads(response.text)
print("On", time.strftime("%I:%M:%S"),"time duration is",d['rows'][0]['elements'][0]['duration']['text'], " & traffic time is ",d['rows'][0]['elements'][0]['duration_in_traffic']['text'])
time.sleep(1800)
print(response.text)
Response is :-
{
"destination_addresses": [
"Tin Factory, Swamy Vivekananda Rd, Krishna Reddy Industrial Estate, Dooravani Nagar, Bengaluru, Karnataka 560016, India"
],
"origin_addresses": [
"Whitefield Main Rd, Pattandur Agrahara, Whitefield, Bengaluru, Karnataka 560066, India"
],
"rows": [
{
"elements": [
{
"distance": {
"text": "10.5 km",
"value": 10505
},
"duration": {
"text": "35 mins",
"value": 2120
},
"duration_in_traffic": {
"text": "45 mins",
"value": 2713
},
"status": "OK"
}
]
}
],
"status": "OK"
}
You need to pass "departure_time":str(int(time.time()))
is a required query string parameter for traffic information.
Your traffic information would be present in duration_in_traffic
.
Refer this documentation for more info.
https://developers.google.com/maps/documentation/distance-matrix/intro#traffic-model
In vi, J
(that's Shift + J) or :join
should do what you want, for the most part. Note that they adjust whitespace. In particular, you'll end up with a space between the two joined lines in many cases, and if the second line is indented that indentation will be removed prior to joining.
In Vim you can also use gJ
(G, then Shift + J) or :join!
. These will join lines without doing any whitespace adjustments.
In Vim, see :help J
for more information.
$.fn.attr(attributeName) returns the attribute value as string, or undefined
when the attribute is not present.
Since ""
, and undefined
are both falsy (evaluates to false when coerced to boolean) values in JavaScript, in this case I would write the check as below:
if (wlocation) { ... }
After spend a lot time, trying follow these answers actually after code below it worked for me. Before do it just but be sure that there is no problem in update :)
gem update --system
Anything that is part of Outer should have access to all of Outer's members, public or private.
Edit: your compiler is correct, var is not a member of Inner. But if you have a reference or pointer to an instance of Outer, it could access that.
While the marked answer is correct there is a way of achieving this without exceptions. The service is returning Optional<T>
of the searched object and this is mapped to HttpStatus.OK
if found and to 404 if empty.
@Controller
public class SomeController {
@RequestMapping.....
public ResponseEntity<Object> handleCall() {
return service.find(param).map(result -> new ResponseEntity<>(result, HttpStatus.OK))
.orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
}
@Service
public class Service{
public Optional<Object> find(String param){
if(!found()){
return Optional.empty();
}
...
return Optional.of(data);
}
}
R defines a ~
(tilde) operator for use in formulas. Formulas have all sorts of uses, but perhaps the most common is for regression:
library(datasets)
lm( myFormula, data=iris)
help("~")
or help("formula")
will teach you more.
@Spacedman has covered the basics. Let's discuss how it works.
First, being an operator, note that it is essentially a shortcut to a function (with two arguments):
> `~`(lhs,rhs)
lhs ~ rhs
> lhs ~ rhs
lhs ~ rhs
That can be helpful to know for use in e.g. apply
family commands.
Second, you can manipulate the formula as text:
oldform <- as.character(myFormula) # Get components
myFormula <- as.formula( paste( oldform[2], "Sepal.Length", sep="~" ) )
Third, you can manipulate it as a list:
myFormula[[2]]
myFormula[[3]]
Finally, there are some helpful tricks with formulae (see help("formula")
for more):
myFormula <- Species ~ .
For example, the version above is the same as the original version, since the dot means "all variables not yet used." This looks at the data.frame you use in your eventual model call, sees which variables exist in the data.frame but aren't explicitly mentioned in your formula, and replaces the dot with those missing variables.
You could do something like this also:
<ol type="A" style="font-weight: bold;">
<li style="padding-bottom: 8px;">****</li>
It is simple code for the beginners.
This code is been tested in "Mozilla, chrome and edge..
Another idea:
If, as in this case, you build the container just place a startup script in it and run this with command. Or mount the startup script as volume.
MemoryStream ms = new MemoryStream();
file.PostedFile.InputStream.CopyTo(ms);
var byts = ms.ToArray();
ms.Dispose();
Maybe you can use this properties:
ActiveCell.Interior.ColorIndex - one of 56 preset colors
and
ActiveCell.Interior.Color - RGB color, used like that:
ActiveCell.Interior.Color = RGB(255,255,255)
If you have a path with spaces you must surround it with quotation marks (").
Not sure if that's exactly what you're asking though?
Programmatically, you could use:
textView.setTextAppearance(android.R.style.TextAppearance_Large);
By default Spring Security redirects user to the URL that he originally requested (/Load.do in your case) after login.
You can set always-use-default-target to true to disable this behavior:
<security:http auto-config="true">
<security:intercept-url pattern="/Admin**" access="hasRole('PROGRAMMER') or hasRole('ADMIN')"/>
<security:form-login login-page="/Load.do"
default-target-url="/Admin.do?m=loadAdminMain"
authentication-failure-url="/Load.do?error=true"
always-use-default-target = "true"
username-parameter="j_username"
password-parameter="j_password"
login-processing-url="/j_spring_security_check"/>
<security:csrf/><!-- enable Cross Site Request Forgery protection -->
</security:http>
To read from the stdin:
char string[512];
fgets(string, sizeof(string), stdin); /* no buffer overflows here, you're safe! */
I think you’re misreading the message — your branch isn’t ahead of master
, it is master
. It’s ahead of origin/master
, which is a remote tracking branch that records the status of the remote repository from your last push
, pull
, or fetch
. It’s telling you exactly what you did; you got ahead of the remote and it’s reminding you to push.
This should do the trick!
// convert object => json
$json = json_encode($myObject);
// convert json => object
$obj = json_decode($json);
Here's an example
$foo = new StdClass();
$foo->hello = "world";
$foo->bar = "baz";
$json = json_encode($foo);
echo $json;
//=> {"hello":"world","bar":"baz"}
print_r(json_decode($json));
// stdClass Object
// (
// [hello] => world
// [bar] => baz
// )
If you want the output as an Array instead of an Object, pass true
to json_decode
print_r(json_decode($json, true));
// Array
// (
// [hello] => world
// [bar] => baz
// )
More about json_encode()
See also: json_decode()
Remove single quotes around @username, and with respect to oracle use :
with parameter name instead of @
, like:
OracleCommand oraCommand = new OracleCommand("SELECT fullname FROM sup_sys.user_profile
WHERE domain_user_name = :userName", db);
oraCommand.Parameters.Add(new OracleParameter("userName", domainUser));
Source: Using Parameters
you can use a regular Button
and the android:drawableTop attribute (or left, right, bottom) instead.
How about adding a new script tag to <head> with the script to (re)load? Something like below:
<script>
function load_js()
{
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.src= 'source_file.js';
head.appendChild(script);
}
load_js();
</script>
The main point is inserting a new script tag -- you can remove the old one without consequence. You may need to add a timestamp to the query string if you have caching issues.
There are two types of coding.
(1) hard-coding (2) soft-coding
Hard-coding. Assign values to program during writing source code and make executable file of program.Now, it is very difficult process to change or modify the program source code values. like in block-chain technology, genesis block is hard-code that cannot changed or modified.
Soft-coding: it is process of inserting values from external source into computer program. like insert values through keyboard, command line interface. Soft-coding considered as good programming practice because developers can easily modify programs.
What's wrong with the printStacktrace()
method provided by Throwable
(and thus every exception)? It shows all the info you requested, including the type, message, and stack trace of the root exception and all (nested) causes. In Java 7, it even shows you the information about "supressed" exceptions that might occur in a try-with-resources statement.
Of course you wouldn't want to write to System.err
, which the no-argument version of the method does, so instead use one of the available overloads.
In particular, if you just want to get a String:
Exception e = ...
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionDetails = sw.toString();
If you happen to use the great Guava library, it provides a utility method doing this: com.google.common.base.Throwables#getStackTraceAsString(Throwable)
.
You can use text that is only accessible to screen readers by placing it in a span which you hide in an accessible way. Place the x in the CSS which can't be read by screen readers, thus won't confuse, but is visible on the page, and also accessible by keyboard users.
<style>
.hidden {opacity:0; position:absolute; width:0;}
.close {padding:4px 8px; border:1px solid #000; background-color:#fff; cursor:pointer;}
.close:before {content:'\00d7'; color:red; font-size:2em;}
</style>
<button class="close"><span class="hidden">close</span></button>
You could put your data into a recordset and use Excel's CopyFromRecordset Method - it's much faster than populating cell-by-cell.
You can create a recordset from a dataset using this code. You will have to do some trials to see if using this method is faster than what you are currently doing.
Yes, it is possible to use @Transactional on private methods, but as others have mentioned this won't work out of the box. You need to use AspectJ. It took me some time to figure out how to get it working. I will share my results.
I chose to use compile-time weaving instead of load-time weaving because I think it's an overall better option. Also, I'm using Java 8 so you may need to adjust some parameters.
First, add the dependency for aspectjrt.
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.8</version>
</dependency>
Then add the AspectJ plugin to do the actual bytecode weaving in Maven (this may not be a minimal example).
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.8</version>
<configuration>
<complianceLevel>1.8</complianceLevel>
<source>1.8</source>
<target>1.8</target>
<aspectLibraries>
<aspectLibrary>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</aspectLibrary>
</aspectLibraries>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>
Finally add this to your config class
@EnableTransactionManagement(mode = AdviceMode.ASPECTJ)
Now you should be able to use @Transactional on private methods.
One caveat to this approach: You will need to configure your IDE to be aware of AspectJ otherwise if you run the app via Eclipse for example it may not work. Make sure you test against a direct Maven build as a sanity check.