For me it was tls12:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
You need to set basicHttpBinding -> MaxReceivedMessageSize in the client configuration.
Try this
<allow users="?" />
Now you are using <deny users="?" />
that means you are not allowing authenticated user to use your site.
in my case, I need to have my wcf running for more than 2 hours. Setting and did not work at all. The wcf did not execute longer than maybe 20~30 minutes. So I changed the idle timeout setting of application pool in IIS manager then it worked! In IIS manager, choose your application pool and right click on it and choose advanced settings then change the idle timeout setting to any minutes you want. So, I think setting the web.config and setting the application pool are both needed.
Try setting the timeout value in your web service proxy class:
WebReference.ProxyClass myProxy = new WebReference.ProxyClass();
myProxy.Timeout = 100000; //in milliseconds, e.g. 100 seconds
I had to add "Current" using .NET 4.5:
HttpContext.Current.Server.ScriptTimeout = 300;
Replace -ggdb with -g and make sure you aren't stripping the binary with the strip command.
Specific to the navigation icon, this is the correct order
// get the actionbar as Toolbar and set it up
Toolbar toolbar = (Toolbar) findViewById(R.id.signIn_toolbar);
setSupportActionBar(toolbar);
Inform the Toolbar to provide back navigation. This will set the icon to the default material icon
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Later override the icon with the custom one, in my case the Holo back icon
toolbar.setNavigationIcon(R.drawable.ic_chevron_left_white_36dp);
Finally i found a way to clone specific commit using git cherry-pick. Assuming you don't have any repository in local and you are pulling specific commit from remote,
1) create empty repository in local and git init
2) git remote add origin "url-of-repository"
3) git fetch origin [this will not move your files to your local workspace unless you merge]
4) git cherry-pick "Enter-long-commit-hash-that-you-need"
Done.This way, you will only have the files from that specific commit in your local.
You can get this using -> git log --pretty=oneline
You need to ensure that C:\Python35\Sripts
is in your system path. Follow the top answer instructions here to do that:
You run the command in windows command prompt, not in the python interpreter that you have open.
Press:
Win + R
Type CMD
in the run window which has opened
Type pip install openpyxl
in windows command prompt.
Use boost::filesystem, that will give you a portable way of doing those kinds of things and abstract away all ugly details for you.
In my case, I had to add using System.Data.Entity;
Call decode()
on a bytes
instance to get the text which it encodes.
str = bytes.decode()
The last parameter to the rgba()
function is the "alpha" or "opacity" parameter. If you set it to 0
it will mean "completely transparent", and the first three parameters (the red
, green
, and blue
channels) won't matter because you won't be able to see the color anyway.
With that in mind, I would choose rgba(0, 0, 0, 0)
because:
You could avoid the rgba
model altogether and use the transparent
keyword instead, which according to w3.org, is equivalent to "transparent black" and should compute to rgba(0, 0, 0, 0)
. For example:
h1 {
background-color: transparent;
}
This saves you yet another couple bytes while your intentions of using transparency are obvious (in case one is unfamiliar with RGBA).
As of CSS3, you can use the transparent
keyword for any CSS property that accepts a color.
ALTER TABLE old_table_name RENAME new_table_name;
or
RENAME TABLE old_table_name TO new_table_name;
This is the normal behavior and the reason is that your sqlCommandHandlerService.persist
method needs a TX when being executed (because it is marked with @Transactional
annotation). But when it is called inside processNextRegistrationMessage
, because there is a TX available, the container doesn't create a new one and uses existing TX. So if any exception occurs in sqlCommandHandlerService.persist
method, it causes TX to be set to rollBackOnly
(even if you catch the exception in the caller and ignore it).
To overcome this you can use propagation levels for transactions. Have a look at this to find out which propagation best suits your requirements.
Well after a colleague came to me with a couple of questions about a similar situation, I feel this needs a bit of clarification.
Although propagations solve such issues, you should be VERY careful about using them and do not use them unless you ABSOLUTELY understand what they mean and how they work. You may end up persisting some data and rolling back some others where you don't expect them to work that way and things can go horribly wrong.
Looking at the code below, I tried it and found:
Instead of writing DBCon = DBConnection.Instance();
you should put DBConnection DBCon - new DBConnection();
(That worked for me)
and instead of MySqlComman cmd = new MySqlComman(query, DBCon.GetConnection());
you should put MySqlCommand cmd = new MySqlCommand(query, DBCon.GetConnection());
(it's missing the d)
I ran the code below, once with foo
taking the shared_ptr
by const&
and again with foo
taking the shared_ptr
by value.
void foo(const std::shared_ptr<int>& p)
{
static int x = 0;
*p = ++x;
}
int main()
{
auto p = std::make_shared<int>();
auto start = clock();
for (int i = 0; i < 10000000; ++i)
{
foo(p);
}
std::cout << "Took " << clock() - start << " ms" << std::endl;
}
Using VS2015, x86 release build, on my intel core 2 quad (2.4GHz) processor
const shared_ptr& - 10ms
shared_ptr - 281ms
The copy by value version was an order of magnitude slower.
If you are calling a function synchronously from the current thread, prefer the const&
version.
There is an additional reason, which no one else has mentioned, why you might choose to create your object dynamically. Dynamic, heap based objects allow you to make use of polymorphism.
If PowerShell is open in a directory other than the target file, e.g.:
If someScript.ps1
is located here: C:\SlowLearner\some_missing_path\someScript.ps1
, then C:\SlowLearner>. ./someScript.ps1
wont work.
In that case, navigate to the path: cd some_missing_path
then this would work:
C:\SlowLearner\some_missing_path>. ./someScript.ps1
To convert any object to string there are several methods in Java
String convertedToString = String.valueOf(Object); //method 1
String convertedToString = "" + Object; //method 2
String convertedToString = Object.toString(); //method 3
I would prefer the first and third
EDIT
If working in kotlin, the official android language
val number: Int = 12345
String convertAndAppendToString = "number = $number" //method 1
String convertObjectMemberToString = "number = ${Object.number}" //method 2
String convertedToString = Object.toString() //method 3
Solution posted by Denys S. in the question post:
I quite messed it up with c to c++ conversion (basically env
variable stuff), but I got it working with the following code for C++:
#include <string.h>
#include <stdio.h>
#include <jni.h>
jstring Java_the_package_MainActivity_getJniString( JNIEnv* env, jobject obj){
jstring jstr = (*env)->NewStringUTF(env, "This comes from jni.");
jclass clazz = (*env)->FindClass(env, "com/inceptix/android/t3d/MainActivity");
jmethodID messageMe = (*env)->GetMethodID(env, clazz, "messageMe", "(Ljava/lang/String;)Ljava/lang/String;");
jobject result = (*env)->CallObjectMethod(env, obj, messageMe, jstr);
const char* str = (*env)->GetStringUTFChars(env,(jstring) result, NULL); // should be released but what a heck, it's a tutorial :)
printf("%s\n", str);
return (*env)->NewStringUTF(env, str);
}
And next code for java methods:
public class MainActivity extends Activity {
private static String LIB_NAME = "thelib";
static {
System.loadLibrary(LIB_NAME);
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.textview);
tv.setText(this.getJniString());
}
// please, let me live even though I used this dark programming technique
public String messageMe(String text) {
System.out.println(text);
return text;
}
public native String getJniString();
}
It might be easiest to try the RCurl package. Install the package and try the following:
# install.packages("RCurl")
library(RCurl)
URL <- "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv"
x <- getURL(URL)
## Or
## x <- getURL(URL, ssl.verifypeer = FALSE)
out <- read.csv(textConnection(x))
head(out[1:6])
# RT SERIALNO DIVISION PUMA REGION ST
# 1 H 186 8 700 4 16
# 2 H 306 8 700 4 16
# 3 H 395 8 100 4 16
# 4 H 506 8 700 4 16
# 5 H 835 8 800 4 16
# 6 H 989 8 700 4 16
dim(out)
# [1] 6496 188
download.file("https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv",destfile="reviews.csv",method="libcurl")
short answer, specific to OAuth2,
This will work although when embedding PHP in HTML it is better practice to use the following form:
<table>
<?php foreach($array as $key=>$value): ?>
<tr>
<td><?= $key; ?></td>
</tr>
<?php endforeach; ?>
</table>
You can find the doc for the alternative syntax on PHP.net
I tried all the solutions above and in addition, those in related answers as well. Solutions including but not limited to passing the blob manually to a HTMLInputElement's file property, calling all the readAs* methods on FileReader, using a File instance as second argument for a FormData.append call, trying to get the blob data as a string by getting the values at URL.createObjectURL(myBlob) which turned out nasty and crashed my machine.
Now, if you happen to attempt those or more and still find you're unable to upload your blob, it could mean the problem is server-side. In my case, my blob exceeded the http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize and post_max_size limit in PHP.INI so the file was leaving the front end form but getting rejected by the server. You could either increase this value directly in PHP.INI or via .htaccess
Sorry for the delay. I was with the same problem and I found a link with good answers, could that will help new guys
All credits for BinaryIntellect web site and the authors
Basically, there are four situations: using differents verbs, using routing, overload marking with [NoAction] attribute and change the action attribute name with [ActionName]
So, depends that's your requiriments and your situation.
Howsoever, follow the link:
Link: http://www.binaryintellect.net/articles/8f9d9a8f-7abf-4df6-be8a-9895882ab562.aspx
JSON_UNESCAPED_UNICODE
was added in PHP 5.4 so it looks like you need upgrade your version of PHP to take advantage of it. 5.4 is not released yet though! :(
There is a 5.4 alpha release candidate on QA though if you want to play on your development machine.
def window(seq, size, step=1):
# initialize iterators
iters = [iter(seq) for i in range(size)]
# stagger iterators (without yielding)
[next(iters[i]) for j in range(size) for i in range(-1, -j-1, -1)]
while(True):
yield [next(i) for i in iters]
# next line does nothing for step = 1 (skips iterations for step > 1)
[next(i) for i in iters for j in range(step-1)]
next(it)
raises StopIteration
when the sequence is finished, and for some cool reason that's beyond me, the yield statement here excepts it and the function returns, ignoring the leftover values that don't form a full window.
Anyway, this is the least-lines solution yet whose only requirement is that seq
implement either __iter__
or __getitem__
and doesn't rely on itertools
or collections
besides @dansalmo's solution :)
I think with np.array()
you can only create C like though you mention the order, when you check using np.isfortran()
it says false. but with np.ndarrray()
when you specify the order it creates based on the order provided.
For those coming here from a later day and age and one a working solution:
(Get-WmiObject -class "cim_physicalmemory" | Measure-Object -Property Capacity -Sum).Sum
this will give the total sum of bytes.
$bytes = (Get-WmiObject -class "cim_physicalmemory" | Measure-Object -Property Capacity -Sum).Sum
$kb = $bytes / 1024
$mb = $bytes / 1024 / 1024
$gb = $bytes / 1024 / 1024 / 1024
I tested this up to windows server 2008 (winver 6.0) even there this command seems to work
For anyone else that comes across this post and might find it useful... There is actually nothing wrong with my code. I made the mistake of requesting client_credentials type access code instead of password access code (#facepalms). FYI I am using urlencoded post hence the use of querystring.. So for those that may be looking for some example code.. here is my full request
Big thanks to @swapnil for trying to help me debug this.
const data = {
grant_type: USER_GRANT_TYPE,
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
scope: SCOPE_INT,
username: DEMO_EMAIL,
password: DEMO_PASSWORD
};
axios.post(TOKEN_URL, Querystring.stringify(data))
.then(response => {
console.log(response.data);
USER_TOKEN = response.data.access_token;
console.log('userresponse ' + response.data.access_token);
})
.catch((error) => {
console.log('error ' + error);
});
const AuthStr = 'Bearer '.concat(USER_TOKEN);
axios.get(URL, { headers: { Authorization: AuthStr } })
.then(response => {
// If request is good...
console.log(response.data);
})
.catch((error) => {
console.log('error ' + error);
});
As we can see from the answers posted, this is surprisingly not a trivial task. When faced with a task like this, it would seem that many programmers choose to throw common sense out the window, in order to produce the most obscure snippet they possibly can come up with.
Things to consider:
' '
.What I would do:
void remove_spaces (char* restrict str_trimmed, const char* restrict str_untrimmed)
{
while (*str_untrimmed != '\0')
{
if(!isspace(*str_untrimmed))
{
*str_trimmed = *str_untrimmed;
str_trimmed++;
}
str_untrimmed++;
}
*str_trimmed = '\0';
}
In this code, the source string "str_untrimmed" is left untouched, which is guaranteed by using proper const correctness. It does not crash if the source string contains nothing but a null termination. It always null terminates the destination string.
Memory allocation is left to the caller. The algorithm should only focus on doing its intended work. It removes all white spaces.
There are no subtle tricks in the code. It does not try to squeeze in as many operators as possible on a single line. It will make a very poor candidate for the IOCCC. Yet it will yield pretty much the same machine code as the more obscure one-liner versions.
When copying something, you can however optimize a bit by declaring both pointers as restrict
, which is a contract between the programmer and the compiler, where the programmer guarantees that the destination and source are not the same address (or rather, that the data they point to are only accessed through that very pointer and not through some other pointer). This allows more efficient optimization, since the compiler can then copy straight from source to destination without temporary memory in between.
If you are loading the XML file from a remote location, I would check to see if the file is actually being downloaded correctly using a sniffer like Fiddler.
I wrote a quick console app to run your code and parse the file and it works fine for me.
You can login to mysql and type
mysql> SHOW INNODB STATUS\G
You will have all the output and you should have a better idea of what the error is.
For better performance you should use:
var numItems = $('div.item').length;
Since it will only look for the div
elements in DOM
and will be quick.
Suggestion: using size()
instead of length
property means one extra step in the processing since SIZE()
uses length
property in the function definition and returns the result.
this should work:
private void cleanlistbox(object sender, EventArgs e)
{
listBox1.Items.Clear( );
}
If you don't have avahi installed then it's probably cups.
HTML and CSS only.
#leftsideMenu ul li {_x000D_
border-bottom: 1px dashed lightgray;_x000D_
background-color: cadetblue;_x000D_
}_x000D_
_x000D_
#leftsideMenu ul li a {_x000D_
padding: 8px 20px 8px 20px;_x000D_
color: white;_x000D_
display: block;_x000D_
}_x000D_
_x000D_
#leftsideMenu ul li a:hover {_x000D_
background-color: lightgreen;_x000D_
transition: 0.5s;_x000D_
padding-left: 30px;_x000D_
padding-right: 10px;_x000D_
}
_x000D_
<div id="leftsideMenu">_x000D_
<ul style="list-style-type:none">_x000D_
<li><a href="#">India</a></li>_x000D_
<li><a href="#">USA</a></li>_x000D_
<li><a href="#">Russia</a></li>_x000D_
<li><a href="#">China</a></li>_x000D_
<li><a href="#">Afganistan</a></li>_x000D_
<li><a href="#">Landon</a></li>_x000D_
<li><a href="#">Scotland</a></li>_x000D_
<li><a href="#">Ireland</a></li>_x000D_
</ul>_x000D_
</div>
_x000D_
Here is working example:
in head
<script type="text/javascript" src="jspdf.debug.js"></script>
script:
<script type="text/javascript">
function demoFromHTML() {
var pdf = new jsPDF('p', 'pt', 'letter');
// source can be HTML-formatted string, or a reference
// to an actual DOM element from which the text will be scraped.
source = $('#customers')[0];
// we support special element handlers. Register them with jQuery-style
// ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
// There is no support for any other type of selectors
// (class, of compound) at this time.
specialElementHandlers = {
// element with id of "bypass" - jQuery style selector
'#bypassme': function(element, renderer) {
// true = "handled elsewhere, bypass text extraction"
return true
}
};
margins = {
top: 80,
bottom: 60,
left: 40,
width: 522
};
// all coords and widths are in jsPDF instance's declared units
// 'inches' in this case
pdf.fromHTML(
source, // HTML string or DOM elem ref.
margins.left, // x coord
margins.top, {// y coord
'width': margins.width, // max width of content on PDF
'elementHandlers': specialElementHandlers
},
function(dispose) {
// dispose: object with X, Y of the last line add to the PDF
// this allow the insertion of new lines after html
pdf.save('Test.pdf');
}
, margins);
}
</script>
and table:
<div id="customers">
<table id="tab_customers" class="table table-striped" >
<colgroup>
<col width="20%">
<col width="20%">
<col width="20%">
<col width="20%">
</colgroup>
<thead>
<tr class='warning'>
<th>Country</th>
<th>Population</th>
<th>Date</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>Chinna</td>
<td>1,363,480,000</td>
<td>March 24, 2014</td>
<td>19.1</td>
</tr>
<tr>
<td>India</td>
<td>1,241,900,000</td>
<td>March 24, 2014</td>
<td>17.4</td>
</tr>
<tr>
<td>United States</td>
<td>317,746,000</td>
<td>March 24, 2014</td>
<td>4.44</td>
</tr>
<tr>
<td>Indonesia</td>
<td>249,866,000</td>
<td>July 1, 2013</td>
<td>3.49</td>
</tr>
<tr>
<td>Brazil</td>
<td>201,032,714</td>
<td>July 1, 2013</td>
<td>2.81</td>
</tr>
</tbody>
</table>
</div>
and button to run:
<button onclick="javascript:demoFromHTML()">PDF</button>
and working example online:
or try this: HTML Table Export
Try this:
window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=\''+elemA+'\'&lon=\''+elemB+'\'&setLatLon=Set";
you can send your DateTime value into SQL as a String with its special format. this format is "yyyy-MM-dd HH:mm:ss"
Example: CurrentTime is a variable as datetime Type in SQL. And dt is a DateTime variable in .Net.
DateTime dt=DateTime.Now;
string sql = "insert into Users (CurrentTime) values (‘{0}’)";
sql = string.Format(sql, dt.ToString("yyyy-MM-dd HH:mm:ss") );
You can use the Feed Dialog via URL to emulate the behavior of Sharer.php, but it's a little more complicated. You need a Facebook App setup with the Base URL of the URL you plan to share configured. Then you can do the following:
1) Create a link like:
http://www.facebook.com/dialog/feed?app_id=[FACEBOOK_APP_ID]' +
'&link=[FULLY_QUALIFIED_LINK_TO_SHARE_CONTENT]' +
'&picture=[LINK_TO_IMAGE]' +
'&name=' + encodeURIComponent('[CONTENT_TITLE]') +
'&caption=' + encodeURIComponent('[CONTENT_CAPTION]) +
'&description=' + encodeURIComponent('[CONTENT_DESCRIPTION]') +
'&redirect_uri=' + FBVars.baseURL + '[URL_TO_REDIRECT_TO_AFTER_SHARE]' +
'&display=popup';
(obviously replace the [CONTENT] with the appropriate content. Documentation here: https://developers.facebook.com/docs/reference/dialogs/feed)
2) Open that link in a popup window with JavaScript on click of the share link
3) I like to create file (i.e. popupclose.html) to redirect users back to when they finish sharing, this file will contain <script>window.close();</script>
to close the popup window
The only downside of using the Feed Dialog (besides setup) is that, if you manage Pages as well, you don't have the ability to choose to share via a Page, only a regular user account can share. And it can give you some really cryptic error messages, most of them are related to the setup of your Facebook app or problems with either the content or URL you are sharing.
After you start the Redis-server using:service redis-server start --port 8000
or redis-server
.
Use redis-cli -p 8000
to connect to the server as a client in a different terminal.
You can use either
Check the documentation for ASYNC option for both.
If you are using Redis through its python interface, use these two functions for the same functionality:
def flushall(self):
"Delete all keys in all databases on the current host"
return self.execute_command('FLUSHALL')
and
def flushdb(self):
"Delete all keys in the current database"
return self.execute_command('FLUSHDB')
If you meant to run foo() inside a python script every 10 seconds, you can do something on these lines.
import time
def foo():
print "Howdy"
while True:
foo()
time.sleep(10)
Use the valgrind option --track-origins=yes
to have it track the origin of uninitialized values. This will make it slower and take more memory, but can be very helpful if you need to track down the origin of an uninitialized value.
Update: Regarding the point at which the uninitialized value is reported, the valgrind manual states:
It is important to understand that your program can copy around junk (uninitialised) data as much as it likes. Memcheck observes this and keeps track of the data, but does not complain. A complaint is issued only when your program attempts to make use of uninitialised data in a way that might affect your program's externally-visible behaviour.
From the Valgrind FAQ:
As for eager reporting of copies of uninitialised memory values, this has been suggested multiple times. Unfortunately, almost all programs legitimately copy uninitialised memory values around (because compilers pad structs to preserve alignment) and eager checking leads to hundreds of false positives. Therefore Memcheck does not support eager checking at this time.
ALTER TABLE Testing ALTER COLUMN TestDec decimal(16,1)
Just put decimal(precision, scale)
, replacing the precision and scale with your desired values.
I haven't done any testing with this with data in the table, but if you alter the precision, you would be subject to losing data if the new precision is lower.
Use this:
((AssemblyFileVersionAttribute)Attribute.GetCustomAttribute(
Assembly.GetExecutingAssembly(),
typeof(AssemblyFileVersionAttribute), false)
).Version;
Or this:
new Version(System.Windows.Forms.Application.ProductVersion);
If the library is included in the VS project, you can check .cproj
file, e.g.:
<ItemGroup>
<Reference Include="Microsoft.Dynamic, Version=1.1.0.20, Culture=neutral, PublicKeyToken=7f709c5b713576e1, processorArchitecture=MSIL">
...
para resolver o meu problema, eu apenas adicionei na minha MainActivity ("Theme = To solve my problem, I just added it in my MainActivity ("Theme =" @ style / MyTheme "") where MyTheme is the name of my theme
[Activity(Label = "Name Label", MainLauncher = true, Icon = "@drawable/icon", LaunchMode = LaunchMode.SingleTop, Theme = "@style/MyTheme")]
$song = DB::table('songs')->find($id);
here you use method find($id)
for Laravel, if you use this method, you should have column named 'id' and set it as primary key, so then you'll be able to use method find()
otherwise use where('SongID', $id)
instead of find($id)
string stringToDecrypt = HttpContext.Current.Request.QueryString.ToString()
//change to string stringToDecrypt = HttpUtility.UrlDecode(HttpContext.Current.Request.QueryString.ToString())
The easy way to get over of this authentication issue is by stealing authentication token using Fiddler.
Steps
Click on SEND button and it shall fetch results.
To further touch on Darin's answer, you can get to your specific claims by using the FindFirst method:
var identity = (ClaimsIdentity)User.Identity;
var role = identity.FindFirst(ClaimTypes.Role).Value;
strcat(destination,source) can be used to concatenate two strings in c++.
To have a deep understanding you can lookup in the following link-
i want to replace last ',' with space
if (fieldName.endsWith(",")) {
fieldName = fieldName.substring(0, fieldName.length() - 1) + " ";
}
If you want to remove the trailing comma, simply get rid of the + " "
.
Wow, No one brings up the fact that if you actually buy SQL server at 5k bucks, you might want to use it for more than your web application. If your using express, maybe you don't care. I see SQL servers run Databases for 20 to 30 applicaitions, so putting it on the webserver would not be smart.
Secondly, depends on whom the server is for. I do work for financial companies and the govt. So we use a crazy pain in the arse approach of using only sprocs and limiting ports from webserver to SQL. So if the web app gets hacked. The only thing the hacker can do is call sprocs as the user account on the webserver is locked down to only see/call sprocs on the DB. So now the hacker has to figure out how to get into the DB. If its on the web server well its kind of easy to get to.
if not exist "%USERPROFILE%\.qgis-custom\" (
mkdir "%USERPROFILE%\.qgis-custom" 2>nul
if not errorlevel 1 (
xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
)
)
You have it almost done. The logic is correct, just some little changes.
This code checks for the existence of the folder (see the ending backslash, just to differentiate a folder from a file with the same name).
If it does not exist then it is created and creation status is checked. If a file with the same name exists or you have no rights to create the folder, it will fail.
If everyting is ok, files are copied.
All paths are quoted to avoid problems with spaces.
It can be simplified (just less code, it does not mean it is better). Another option is to always try to create the folder. If there are no errors, then copy the files
mkdir "%USERPROFILE%\.qgis-custom" 2>nul
if not errorlevel 1 (
xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
)
In both code samples, files are not copied if the folder is not being created during the script execution.
EDITED - As dbenham comments, the same code can be written as a single line
md "%USERPROFILE%\.qgis-custom" 2>nul && xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
The code after the &&
will only be executed if the previous command does not set errorlevel. If mkdir
fails, xcopy
is not executed.
It has nothing to do with a space embedded in the folder structure.
I had the same problem. But when I created an environmental variable (defined both at the system- and user-level) called TNS_HOME and made it to point to the folder where TNSNAMES.ORA existed, the problem was resolved. Voila!
venki
Don't press Esc ever. See this answer to learn why. As mentioned above, Ctrl + C is a better alternative. I strongly suggest mapping your Caps Lock key to escape.
If you're editing a Ctags compatible language, using a tags file and :ta
, Ctrl + ], etc. is a great way to navigate the code, even across multiple files. Also, Ctrl + N and Ctrl + P completion using the tags file is a great way to cut down on keystrokes.
If you're editing a line that is wrapped because it's wider than your buffer, you can move up/down using gk and gj.
Try to focus on effective use of the motion commands before you learn bad habits. Things like using 'dt' or 'd3w' instead of pressing x a bunch of times. Basically, any time that you find yourself pressing the same key repeatedly, there's probably a better/faster/more concise way of accomplishing the same thing.
MySQL recommends using indexes for a variety of reasons including elimination of rows between conditions: http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html
This makes your datetime column an excellent candidate for an index if you are going to be using it in conditions frequently in queries. If your only condition is BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY)
and you have no other index in the condition, MySQL will have to do a full table scan on every query. I'm not sure how many rows are generated in 30 days, but as long as it's less than about 1/3 of the total rows it will be more efficient to use an index on the column.
Your question about creating an efficient database is very broad. I'd say to just make sure that it's normalized and all appropriate columns are indexed (i.e. ones used in joins and where clauses).
I was looking for a nice and complete example of how to bind multiple query parameters dynamically to any SELECT, INSERT, UPDATE and DELETE query. Alec mentions in his answer a way of how to bind result, for me the get_result() after execute() function for SELECT queries works just fine, and am able to retrieve all the selected results into an array of associative arrays.
Anyway, I ended up creating a function where I am able to dynamically bind any amount of parameters to a parametrized query ( using call_user_func_array function) and obtain a result of the query execution. Below is the function with its documentation (please read before it before using - especially the $paremetersTypes - Type specification chars parameter is important to understand)
/**
* Prepares and executes a parametrized QUERY (SELECT, INSERT, UPDATE, DELETE)
*
* @param[in] $dbConnection mysqli database connection to be used for query execution
* @param[in] $dbQuery parametrized query to be bind parameters for and then execute
* @param[in] $isDMQ boolean value, should be set to TRUE for (DELETE, INSERT, UPDATE - Data manipulaiton queries), FALSE for SELECT queries
* @param[in] $paremetersTypes String representation for input parametrs' types as per http://php.net/manual/en/mysqli-stmt.bind-param.php
* @param[in] $errorOut A variable to be passed by reference where a string representation of an error will be present if a FAUILURE occurs
* @param[in] $arrayOfParemetersToBind Parameters to be bind to the parametrized query, parameters need to be specified in an array in the correct order
* @return array of feched records associative arrays for SELECT query on SUCCESS, TRUE for INSERT, UPDATE, DELETE queries on SUCCESS, on FAIL sets the error and returns NULL
*/
function ExecuteMySQLParametrizedQuery($dbConnection, $dbQuery, $isDMQ, $paremetersTypes, &$errorOut, $arrayOfParemetersToBind)
{
$stmt = $dbConnection->prepare($dbQuery);
$outValue = NULL;
if ($stmt === FALSE)
$errorOut = 'Failed to prepare statement for query: ' . $dbQuery;
else if ( call_user_func_array(array($stmt, "bind_param"), array_merge(array($paremetersTypes), $arrayOfParemetersToBind)) === FALSE)
$errorOut = 'Failed to bind required parameters to query: ' . $dbQuery . ' , parameters :' . json_encode($arrayOfParemetersToBind);
else if (!$stmt->execute())
$errorOut = "Failed to execute query [$dbQuery] , erorr:" . $stmt->error;
else
{
if ($isDMQ)
$outValue = TRUE;
else
{
$result = $stmt->get_result();
if ($result === FALSE)
$errorOut = 'Failed to obtain result from statement for query ' . $dbQuery;
else
$outValue = $result->fetch_all(MYSQLI_ASSOC);
}
}
$stmt->close();
return $outValue;
}
usage:
$param1 = "128989";
$param2 = "some passcode";
$insertQuery = "INSERT INTO Cards (Serial, UserPin) VALUES (?, ?)";
$rowsInserted = ExecuteMySQLParametrizedQuery($dbConnection, $insertQuery, TRUE, 'ss', $errorOut, array(&$param1, &$param2) ); // Make sure the parameters in an array are passed by reference
if ($rowsInserted === NULL)
echo 'error ' . $errorOut;
else
echo "successfully inserted row";
$selectQuery = "SELECT CardID FROM Cards WHERE Serial like ? AND UserPin like ?";
$arrayOfCardIDs = ExecuteMySQLParametrizedQuery($dbConnection, $selectQuery, FALSE, 'ss', $errorOut, array(&$param1, &$param2) ); // Make sure the parameters in an array are passed by reference
if ($arrayOfCardIDs === NULL)
echo 'error ' . $errorOut;
else
{
echo 'obtained result array of ' . count($arrayOfCardIDs) . 'selected rows';
if (count($arrayOfCardIDs) > 0)
echo 'obtained card id = ' . $arrayOfCardIDs[0]['CardID'];
}
You can use random.uniform
import random
random.uniform(0, 1)
I have talked to customer support and confirmed that this can not be done on github.com. They have passed the suggestion along to the Github team though, so hopefully it will be possible in the future. If so, I'll be sure to edit this answer.
Meanwhile, Rory O'Kane's answer is a brilliant alternative based on cloc
and a shallow repo clone.
For the lazy guys:
First download cookie: http://plugins.jquery.com/cookie/
Add it to your html:
<script src="{% static 'designer/js/jquery.cookie.js' %}"></script>
Now you can create a working POST request:
var csrftoken = $.cookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$.ajax(save_url, {
type : 'POST',
contentType : 'application/json',
data : JSON.stringify(canvas),
success: function () {
alert("Saved!");
}
})
append strings with add function
str1 = "Hello"
str2 = " World"
str3 = str.__add__(str2)
print(str3)
Output
Hello World
for the maven users, comment the scope provided in the following dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<!--<scope>provided</scope>-->
</dependency>
UPDATE
As feed.me mentioned you have to uncomment the provided part depending on what kind of app you are deploying.
Here is a useful link with the details: http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#build-tool-plugins-maven-packaging
One way is to stack the frames on top of each other, then you can simply raise one above the other in the stacking order. The one on top will be the one that is visible. This works best if all the frames are the same size, but with a little work you can get it to work with any sized frames.
Note: for this to work, all of the widgets for a page must have that page (ie: self
) or a descendant as a parent (or master, depending on the terminology you prefer).
Here's a bit of a contrived example to show you the general concept:
try:
import tkinter as tk # python 3
from tkinter import font as tkfont # python 3
except ImportError:
import Tkinter as tk # python 2
import tkFont as tkfont # python 2
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")
# the container is where we'll stack a bunch of frames
# on top of each other, then the one we want visible
# will be raised above the others
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, PageOne, PageTwo):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
# put all of the pages in the same location;
# the one on the top of the stacking order
# will be the one that is visible.
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("StartPage")
def show_frame(self, page_name):
'''Show a frame for the given page name'''
frame = self.frames[page_name]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is the start page", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button1 = tk.Button(self, text="Go to Page One",
command=lambda: controller.show_frame("PageOne"))
button2 = tk.Button(self, text="Go to Page Two",
command=lambda: controller.show_frame("PageTwo"))
button1.pack()
button2.pack()
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 1", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame("StartPage"))
button.pack()
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 2", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame("StartPage"))
button.pack()
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
If you find the concept of creating instance in a class confusing, or if different pages need different arguments during construction, you can explicitly call each class separately. The loop serves mainly to illustrate the point that each class is identical.
For example, to create the classes individually you can remove the loop (for F in (StartPage, ...)
with this:
self.frames["StartPage"] = StartPage(parent=container, controller=self)
self.frames["PageOne"] = PageOne(parent=container, controller=self)
self.frames["PageTwo"] = PageTwo(parent=container, controller=self)
self.frames["StartPage"].grid(row=0, column=0, sticky="nsew")
self.frames["PageOne"].grid(row=0, column=0, sticky="nsew")
self.frames["PageTwo"].grid(row=0, column=0, sticky="nsew")
Over time people have asked other questions using this code (or an online tutorial that copied this code) as a starting point. You might want to read the answers to these questions:
Here is what the code looks like with @Component:
Main class that schedules the job:
public class NotificationScheduler {
private SchedulerFactory sf;
private Scheduler scheduler;
@PostConstruct
public void initNotificationScheduler() {
try {
sf = new StdSchedulerFactory("spring/quartz.properties");
scheduler = sf.getScheduler();
scheduler.start();
// test out sending a notification at startup, prepare some parameters...
this.scheduleImmediateNotificationJob(messageParameters, recipients);
try {
// wait 20 seconds to show jobs
logger.info("sleeping...");
Thread.sleep(40L * 1000L);
logger.info("finished sleeping");
// executing...
} catch (Exception ignore) {
}
} catch (SchedulerException e) {
e.printStackTrace();
throw new RuntimeException("NotificationScheduler failed to retrieve a Scheduler instance: ", e);
}
}
public void scheduleImmediateNotificationJob(){
try {
JobKey jobKey = new JobKey("key");
Date fireTime = DateBuilder.futureDate(delayInSeconds, IntervalUnit.SECOND);
JobDetail emailJob = JobBuilder.newJob(EMailJob.class)
.withIdentity(jobKey.toString(), "immediateEmailsGroup")
.build();
TriggerKey triggerKey = new TriggerKey("triggerKey");
SimpleTrigger trigger = (SimpleTrigger) TriggerBuilder.newTrigger()
.withIdentity(triggerKey.toString(), "immediateEmailsGroup")
.startAt(fireTime)
.build();
// schedule the job to run
Date scheduleTime1 = scheduler.scheduleJob(emailJob, trigger);
} catch (SchedulerException e) {
logger.error("error scheduling job: " + e.getMessage(), e);
e.printStackTrace();
}
}
@PreDestroy
public void cleanup(){
sf = null;
try {
scheduler.shutdown();
} catch (SchedulerException e) {
e.printStackTrace();
}
}
The EmailJob is the same as in my first posting except for the @Component annotation:
@Component
public class EMailJob implements Job {
@Autowired
private JavaMailSenderImpl mailSenderImpl;
... }
And the Spring's configuration file has:
...
<context:property-placeholder location="classpath:spring/*.properties" />
<context:spring-configured/>
<context:component-scan base-package="com.mybasepackage">
<context:exclude-filter expression="org.springframework.stereotype.Controller"
type="annotation" />
</context:component-scan>
<bean id="mailSenderImpl" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="${mail.host}"/>
<property name="port" value="${mail.port}"/>
...
</bean>
<bean id="notificationScheduler" class="com.mybasepackage.notifications.NotificationScheduler">
</bean>
Thanks for all the help!
Marina
Example: say you have an 'image' you want to scale you will need a bufferedImage probably, and probably will be starting out with just 'Image' object. So this works I think... The AVATAR_SIZE is the target width we want our image to be:
Image imgData = image.getScaledInstance(Constants.AVATAR_SIZE, -1, Image.SCALE_SMOOTH);
BufferedImage bufferedImage = new BufferedImage(imgData.getWidth(null), imgData.getHeight(null), BufferedImage.TYPE_INT_RGB);
bufferedImage.getGraphics().drawImage(imgData, 0, 0, null);
In short, REST emphasizes nouns over verbs. As your API becomes more complex, you add more things, rather than more commands.
First of all, Thanks to code author!
I found the below link while googling and it is very simple and works best. Would never fail unless SVG is deprecated.
https://codepen.io/moistpaint/pen/ywFDe/
There is some js loading error in the code here but its perfectly working on the codepen.io link provided.
var mapOptions = {_x000D_
zoom: 16,_x000D_
center: new google.maps.LatLng(-37.808846, 144.963435)_x000D_
};_x000D_
map = new google.maps.Map(document.getElementById('map-canvas'),_x000D_
mapOptions);_x000D_
_x000D_
_x000D_
var pinz = [_x000D_
{_x000D_
'location':{_x000D_
'lat' : -37.807817,_x000D_
'lon' : 144.958377_x000D_
},_x000D_
'lable' : 2_x000D_
},_x000D_
{_x000D_
'location':{_x000D_
'lat' : -37.807885,_x000D_
'lon' : 144.965415_x000D_
},_x000D_
'lable' : 42_x000D_
},_x000D_
{_x000D_
'location':{_x000D_
'lat' : -37.811377,_x000D_
'lon' : 144.956596_x000D_
},_x000D_
'lable' : 87_x000D_
},_x000D_
{_x000D_
'location':{_x000D_
'lat' : -37.811293,_x000D_
'lon' : 144.962883_x000D_
},_x000D_
'lable' : 145_x000D_
},_x000D_
{_x000D_
'location':{_x000D_
'lat' : -37.808089,_x000D_
'lon' : 144.962089_x000D_
},_x000D_
'lable' : 999_x000D_
},_x000D_
];_x000D_
_x000D_
_x000D_
_x000D_
for(var i = 0; i <= pinz.length; i++){_x000D_
var image = 'data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2238%22%20height%3D%2238%22%20viewBox%3D%220%200%2038%2038%22%3E%3Cpath%20fill%3D%22%23808080%22%20stroke%3D%22%23ccc%22%20stroke-width%3D%22.5%22%20d%3D%22M34.305%2016.234c0%208.83-15.148%2019.158-15.148%2019.158S3.507%2025.065%203.507%2016.1c0-8.505%206.894-14.304%2015.4-14.304%208.504%200%2015.398%205.933%2015.398%2014.438z%22%2F%3E%3Ctext%20transform%3D%22translate%2819%2018.5%29%22%20fill%3D%22%23fff%22%20style%3D%22font-family%3A%20Arial%2C%20sans-serif%3Bfont-weight%3Abold%3Btext-align%3Acenter%3B%22%20font-size%3D%2212%22%20text-anchor%3D%22middle%22%3E' + pinz[i].lable + '%3C%2Ftext%3E%3C%2Fsvg%3E';_x000D_
_x000D_
_x000D_
var myLatLng = new google.maps.LatLng(pinz[i].location.lat, pinz[i].location.lon);_x000D_
var marker = new google.maps.Marker({_x000D_
position: myLatLng,_x000D_
map: map,_x000D_
icon: image_x000D_
});_x000D_
}
_x000D_
html, body, #map-canvas {_x000D_
height: 100%;_x000D_
margin: 0px;_x000D_
padding: 0px_x000D_
}
_x000D_
<div id="map-canvas"></div>_x000D_
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDtc3qowwB96ObzSu2vvjEoM2pVhZRQNSA&signed_in=true&callback=initMap&libraries=drawing,places"></script>
_x000D_
You just need to uri-encode your SVG html and replace the one in the image variable after "data:image/svg+xml" in the for loop.
For uri encoding you can use uri-encoder-decoder
You can decode the existing svg code first to get a better understanding of what is written.
You can't expect ObjectInputStream
to automagically convert text into objects. The hexadecimal 54657374
is "Test"
as text. You must be sending it directly as bytes.
The logic applies to many other objectives. And how to read .sh_history of each user from /home/ filesystem? What if there are thousand of them?
#!/bin/ksh
last |head -10|awk '{print $1}'|
while IFS= read -r line
do
su - "$line" -c 'tail .sh_history'
done
Here is the script https://github.com/imvieira/SysAdmin_DevOps_Scripts/blob/master/get_and_run.sh
<p style="margin-left:5em;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet. Phasellus tempor nisi eget tellus venenatis tempus. Aliquam dapibus porttitor convallis. Praesent pretium luctus orci, quis ullamcorper lacus lacinia a. Integer eget molestie purus. Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>
That'll do it, there's a few improvements obviously, but that's the basics. And I use 'em'
as the measurement, you may want to use other units, like 'px'
.
EDIT: What they're describing above is a way of associating groups of styles, or classes, with elements on a web page. You can implement that in a few ways, here's one which may suit you:
In your HTML page, containing the <p>
tagged content from your DB add in a new 'style' node and wrap the styles you want to declare in a class like so:
<head>
<style type="text/css">
p { margin-left:5em; /* Or another measurement unit, like px */ }
</style>
</head>
<body>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</body>
So above, all <p>
elements in your document will have that style rule applied. Perhaps you are pumping your paragraph content into a container of some sort? Try this:
<head>
<style type="text/css">
.container p { margin-left:5em; /* Or another measurement unit, like px */ }
</style>
</head>
<body>
<div class="container">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</div>
<p>Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra.</p>
</body>
In the example above, only the <p>
element inside the div, whose class name is 'container', will have the styles applied - and not the <p>
element outside the container.
In addition to the above, you can collect your styles together and remove the style element from the <head>
tag, replacing it with a <link>
tag, which points to an external CSS file. This external file is where you'd now put your <p>
tag styles. This concept is known as 'seperating content from style' and is considered good practice, and is also an extendible way to create styles, and can help with low maintenance.
@sdbrain's answer in Swift 3:
let url = URL.init(fileURLWithPath: Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "www")!)
webView.loadRequest(NSURLRequest.init(url: url) as URLRequest)
I was building a nav menu. I have overflow: hidden
in my nav's css which hid everything. I thought it was a z-index problem, but really I was hiding everything outside my nav.
The solution that worked for me, is missing from the list of answers. Hence I am posting this solution here:
File[]dirs = new File("/mypath/mydir/").listFiles((FileFilter)FileFilterUtils.directoryFileFilter());
Here I have used org.apache.commons.io.filefilter.FileFilterUtils
from Apache commons-io-2.2.jar. Its documentation is available here: https://commons.apache.org/proper/commons-io/javadocs/api-2.2/org/apache/commons/io/filefilter/FileFilterUtils.html
request.stream
is the stream of raw data passed to the application by the WSGI server. No parsing is done when reading it, although you usually want request.get_data()
instead.
data = request.stream.read()
The stream will be empty if it was previously read by request.data
or another attribute.
The simplest answer to the meaning of deprecated
when used to describe software APIs is:
- Stop using APIs marked as deprecated!
- They will go away in a future release!!
- Start using the new versions ASAP!!!
ran into this issue while trying to connect mysql in SSH client, found adding the socket path to the command helpful when switching between sockets is necessary.
> mysql -u user -p --socket=/path/to/mysql5143.sock
Unless you are subtracting dates on same browser client and don't care about edge cases like day light saving time changes, you are probably better off using moment.js which offers powerful localized APIs. For example, this is what I have in my utils.js:
subtractDates: function(date1, date2) {
return moment.subtract(date1, date2).milliseconds();
},
millisecondsSince: function(dateSince) {
return moment().subtract(dateSince).milliseconds();
},
None of this worked, what worked for me is scaling image down.
So depending on what size you want the image or what resoultion your image is, you can do something like this:
.ok {
transform: perspective(100px) rotateY(0deg) scale(0.5);
transition: transform 1s;
object-fit:contain;
}
.ok:hover{
transform: perspective(100px) rotateY(-10deg) scale(0.5);
}
/* Demo Preview Stuff */
.bad {
max-width: 320px;
object-fit:contain;
transform: perspective(100px) rotateY(0deg);
transition: transform 1s;
}
.bad:hover{
transform: perspective(100px) rotateY(-10deg);
}
div {
text-align: center;
position: relative;
display: flex;
}
h3{
position: absolute;
bottom: 30px;
left: 0;
right: 0;
}
.b {
display: flex;
}
_x000D_
<center>
<h2>Hover on images</h2>
<div class="b">
<div>
<img class="ok" src='https://www.howtogeek.com/wp-content/uploads/2018/10/preview-11.png'>
<h3>Sharp</h3>
</div>
<div>
<img class="bad" src='https://www.howtogeek.com/wp-content/uploads/2018/10/preview-11.png'>
<h3>Blurry</h3>
</div>
</div>
</center>
_x000D_
The image should be scaled down, make sure you have a big image resoultion
if (!obj) {
// object (not class!) doesn't exist yet
}
else ...
You could use an image submit button:
<input type="image" src="images/login.jpg" alt="Submit Form" />
You can just use localStorage
and remember the date it was first created in session cookie
. When localStorage
"session" is older than the value of cookie then you may clear the localStorage
Cons of this is that someone can still read the data after the browser is closed so it's not a good solution if your data is private and confidental.
You can store your data to localStorage
for a couple of seconds and add event listener for a storage
event. This way you will know when any of the tabs wrote something to the localStorage
and you can copy its content to the sessionStorage
, then just clear the localStorage
What I normally do is e .
(e-space-dot) which gives me a browsable current directory - then I can /
- search for name fragments, just like finding a word in a text file. I find that generally good enough, simple and quick.
$('#some_select_box option:selected').remove();
To split the difference of opinion
I prefer:
xls.DisplayAlerts = False
wb.SaveAs fullFilePath, AccessMode:=xlExclusive, ConflictResolution:=xlLocalSessionChanges
xls.DisplayAlerts = True
You can use "Overrides" in Chrome to persist javascript changes between page loads, even where you aren't hosting the original source.
You can use the ljust
method on strings.
>>> name = 'John'
>>> name.ljust(15)
'John '
Note that if the name is longer than 15 characters, ljust
won't truncate it. If you want to end up with exactly 15 characters, you can slice the resulting string:
>>> name.ljust(15)[:15]
From the python docs on os.walk()
:
# Delete everything reachable from the directory named in 'top',
# assuming there are no symbolic links.
# CAUTION: This is dangerous! For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
The problem is you typed the wrong file extension for excel file. you used .xsl instead of xls.
I know i came in late but it can help future readers of this post.
MySQL has a SQL query "SHOW INDEX FROM" which returns the indexes from a table. For eg. - the following query will show all the indexes for the products table:-
SHOW INDEXES FROM products \G
It returns a table with type, column_name, Key_name, etc. and displays output with all indexes and primary keys as -
*************************** 1. row ***************************
Table: products
Non_unique: 0
Key_name: PRIMARY
Seq_in_index: 1
Column_name: product_id
Collation: A
Cardinality: 0
Sub_part: NULL
Packed: NULL
Null:
Index_type: BTREE
Comment:
Index_comment:
To just display primary key from the table use :-
SHOW INDEXES FROM table_name WHERE Key_name = 'PRIMARY'
An alternative method is to use a Gulp plugin created specifically for this problem. https://www.npmjs.com/package/gulp-ng-module-sort
It allows you to sort your scripts by adding in a .pipe(ngModuleSort())
as such:
var ngModuleSort = require('gulp-ng-module-sort');
var concat = require('gulp-concat');
gulp.task('angular-scripts', function() {
return gulp.src('./src/app/**/*.js')
.pipe(ngModuleSort())
.pipe(concat('angularAppScripts.js))
.pipe(gulp.dest('./dist/));
});
Assuming a directory convention of:
|——— src/
| |——— app/
| |——— module1/
| |——— sub-module1/
| |——— sub-module1.js
| |——— module1.js
| |——— module2/
| |——— sub-module2/
| |——— sub-module2.js
| |——— sub-module3/
| |——— sub-module3.js
| |——— module2.js
| |——— app.js
Hope this helps!
PUT ing
PUT /binders/{id}/docs
Create or update, and relate a single document to a binder
e.g.:
PUT /binders/1/docs HTTP/1.1
{
"docNumber" : 1
}
PATCH ing
PATCH /docs
Create docs if they do not exist and relate them to binders
e.g.:
PATCH /docs HTTP/1.1
[
{ "op" : "add", "path" : "/binder/1/docs", "value" : { "doc_number" : 1 } },
{ "op" : "add", "path" : "/binder/8/docs", "value" : { "doc_number" : 8 } },
{ "op" : "add", "path" : "/binder/3/docs", "value" : { "doc_number" : 6 } }
]
I'll include additional insights later, but in the meantime if you want to, have a look at RFC 5789, RFC 6902 and William Durand's Please. Don't Patch Like an Idiot blog entry.
char arr[50];
gets(arr);
int c=0,i,l;
l=strlen(arr);
for(i=0;i<l;i++){
if(arr[i]==32){
printf("\n");
}
else
printf("%c",arr[i]);
}
Consider an array A of N x 2 dimensions. To add one more row, use the following.
A.loc[A.shape[0]] = [3,4]
You can use the version-select
package:
npm i -D version-select
{
"name": "test",
"version": "1.0.0",
"scripts": {
"version-select": "version-select"
},
"devDependencies": {
"version-select": "^1.0.13"
}
}
A quick addition to @Cem Catikka's comment, when using ExpectedException:
Keep in mind that your expected exception will be wrapped in an InvocationTargetException, so in order to get to your exception you will have to throw the cause of the InvocationTargetException you received. Something like (testing private method validateRequest() on BizService):
@Rule
public ExpectedException thrown = ExpectedException.none();
@Autowired(required = true)
private BizService svc;
@Test
public void testValidateRequest() throws Exception {
thrown.expect(BizException.class);
thrown.expectMessage(expectMessage);
BizRequest request = /* Mock it, read from source - file, etc. */;
validateRequest(request);
}
private void validateRequest(BizRequest request) throws Exception {
Method method = svc.getClass().getDeclaredMethod("validateRequest", BizRequest.class);
method.setAccessible(true);
try {
method.invoke(svc, request);
}
catch (InvocationTargetException e) {
throw ((BizException)e.getCause());
}
}
A generic solution is to introduce a new type. It may be more involved, but it has the advantage of working for any type that doesn't define its own infinity.
If T
is a type for which lteq
is defined, you can define InfiniteOr<T>
with lteq
something like this:
class InfiniteOr with type parameter T:
field the_T of type null-or-an-actual-T
isInfinite()
return this.the_T == null
getFinite():
assert(!isInfinite());
return this.the_T
lteq(that)
if that.isInfinite()
return true
if this.isInfinite()
return false
return this.getFinite().lteq(that.getFinite())
I'll leave it to you to translate this to exact Java syntax. I hope the ideas are clear; but let me spell them out anyways.
The idea is to create a new type which has all the same values as some already existing type, plus one special value which—as far as you can tell through public methods—acts exactly the way you want infinity to act, e.g. it's greater than anything else. I'm using null
to represent infinity here, since that seems the most straightforward in Java.
If you want to add arithmetic operations, decide what they should do, then implement that. It's probably simplest if you handle the infinite cases first, then reuse the existing operations on finite values of the original type.
There might or might not be a general pattern to whether or not it's beneficial to adopt a convention of handling left-hand-side infinities before right-hand-side infinities or vice versa; I can't tell without trying it out, but for less-than-or-equal (lteq
) I think it's simpler to look at right-hand-side infinity first. I note that lteq
is not commutative, but add
and mul
are; maybe that is relevant.
Note: coming up with a good definition of what should happen on infinite values is not always easy. It is for comparison, addition and multiplication, but maybe not subtraction. Also, there is a distinction between infinite cardinal and ordinal numbers which you may want to pay attention to.
If you just need sampling without replacement:
>>> import random
>>> random.sample(range(1, 100), 3)
[77, 52, 45]
random.sample takes a population and a sample size k
and returns k
random members of the population.
If you have to control for the case where k
is larger than len(population)
, you need to be prepared to catch a ValueError
:
>>> try:
... random.sample(range(1, 2), 3)
... except ValueError:
... print('Sample size exceeded population size.')
...
Sample size exceeded population size
You could take a look at date-and-time api for easily date manipulation.
let now = date.format(new Date(), 'YYYY-MM-DD HH:mm:ss', true);_x000D_
console.log(now);
_x000D_
<script src="https://cdn.jsdelivr.net/npm/date-and-time/date-and-time.min.js"></script>
_x000D_
I was getting similar problem for other reason (url pattern test-response
not added in csrf token)
I resolved it by allowing my URL pattern in following property in config/local.properties
:
csrf.allowed.url.patterns = /[^/]+(/[^?])+(sop-response)$,/[^/]+(/[^?])+(merchant_callback)$,/[^/]+(/[^?])+(hop-response)$
modified to
csrf.allowed.url.patterns = /[^/]+(/[^?])+(sop-response)$,/[^/]+(/[^?])+(merchant_callback)$,/[^/]+(/[^?])+(hop-response)$,/[^/]+(/[^?])+(test-response)$
When you use @DataJpaTest you need to load classes using @Import explicitly. It wouldn't load you for auto.
First step: go to /etc/phpmyadmin/config.inc.php then uncomment lines where you find AllowNoPassword . Second step: login to your mysql default account
mysql -u root -p
use mysql;
update user set plugin="" where user='root';
flush privilege;
and that's all!
As an extension to Hiale's solution, you could provide a different or modified version that supports processes that have multiple main windows.
First, amend the structure to allow storing of multiple handles:
struct handle_data {
unsigned long process_id;
std::vector<HWND> handles;
};
Second, amend the callback function:
BOOL CALLBACK enum_windows_callback(HWND handle, LPARAM lParam)
{
handle_data& data = *(handle_data*)lParam;
unsigned long process_id = 0;
GetWindowThreadProcessId(handle, &process_id);
if (data.process_id != process_id || !is_main_window(handle)) {
return TRUE;
}
// change these 2 lines to allow storing of handle and loop again
data.handles.push_back(handle);
return TRUE;
}
Finally, amend the returns on the main function:
std::vector<HWD> find_main_window(unsigned long process_id)
{
handle_data data;
data.process_id = process_id;
EnumWindows(enum_windows_callback, (LPARAM)&data);
return data.handles;
}
You can use date filter to convert in date and display in specific format.
In .ts file (typescript):
let dateString = '1968-11-16T00:00:00'
let newDate = new Date(dateString);
In HTML:
{{dateString | date:'MM/dd/yyyy'}}
Below are some formats which you can implement :
Backend:
public todayDate = new Date();
HTML :
<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option>
</select>
Is Powershell an option?
Start Powershell:
powershell
Create the VPN Connection: Add-VpnConnection
Add-VpnConnection [-Name] <string> [-ServerAddress] <string> [-TunnelType <string> {Pptp | L2tp | Sstp | Ikev2 | Automatic}] [-EncryptionLevel <string> {NoEncryption | Optional | Required | Maximum}] [-AuthenticationMethod <string[]> {Pap | Chap | MSChapv2 | Eap}] [-SplitTunneling] [-AllUserConnection] [-L2tpPsk <string>] [-RememberCredential] [-UseWinlogonCredential] [-EapConfigXmlStream <xml>] [-Force] [-PassThru] [-WhatIf] [-Confirm]
Edit VPN connections: Set-VpnConnection
Set-VpnConnection [-Name] <string> [[-ServerAddress] <string>] [-TunnelType <string> {Pptp | L2tp | Sstp | Ikev2 | Automatic}] [-EncryptionLevel <string> {NoEncryption | Optional | Required | Maximum}] [-AuthenticationMethod <string[]> {Pap | Chap | MSChapv2 | Eap}] [-SplitTunneling <bool>] [-AllUserConnection] [-L2tpPsk <string>] [-RememberCredential <bool>] [-UseWinlogonCredential <bool>] [-EapConfigXmlStream <xml>] [-PassThru] [-Force] [-WhatIf] [-Confirm]
Lookup VPN Connections: Get-VpnConnection
Get-VpnConnection [[-Name] <string[]>] [-AllUserConnection]
Connect: rasdial [connectionName]
rasdial connectionname [username [password | \]] [/domain:domain*] [/phone:phonenumber] [/callback:callbacknumber] [/phonebook:phonebookpath] [/prefixsuffix**]
You can manage your VPN connections with the powershell commands above, and simply use the connection name to connect via rasdial
.
The results of Get-VpnConnection
can be a little verbose. This can be simplified with a simple Select-Object
filter:
Get-VpnConnection | Select-Object -Property Name
More information can be found here:
You should look into XPath. Once you start using it, you'll find its a lot more efficient and easier to code than iterating through lists. It also lets you directly get the things you want.
Then the code would be something similar to
string attrVal = doc.SelectSingleNode("/MyConfiguration/@SuperNumber").Value;
Note that XPath 3.0 became a W3C Recommendation on April 8, 2014.
I like Çagatay's solution, but I the popups were not hiding on mouseout. I added this extra functionality with this:
// hides the popup
$('*[data-poload]').bind('mouseout',function(){
var e=$(this);
e.popover('hide');
});
All you need is a ADODB.Connection
Dim cnn As ADODB.Connection ' Requieres reference to the
Dim rs As ADODB.Recordset ' Microsoft ActiveX Data Objects Library
Set cnn = CreateObject("adodb.Connection")
cnn.Open "DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\Access\webforums\whiteboard2003.mdb;"
Set rs = cnn.Execute(SQLQuery) ' Retrieve the data
>>> dict(zip(keys, values))
{0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}
I am adding my answer, it is just an addon to the above, as for me I tried all the /n options and it didn't work, I saw my text is comming from server with double slash so I used this:
var fixedText = yourString.replace(/(\r\n|\n|\r|\\n)/gm, '');
From PowerShell Core 6.0 you are able to write &
at end of command and it will be equivalent to running you pipeline in background in current working directory.
It's not equivalent to &
in bash, it's just a nicer syntax for current PowerShell jobs feature. It returns a job object so you can use all other command that you would use for jobs. For example Receive-Job
:
C:\utils> ping google.com &
Id Name PSJobTypeName State HasMoreData Location Command
-- ---- ------------- ----- ----------- -------- -------
35 Job35 BackgroundJob Running True localhost Microsoft.PowerShell.M...
C:\utils> Receive-Job 35
Pinging google.com [172.217.16.14] with 32 bytes of data:
Reply from 172.217.16.14: bytes=32 time=11ms TTL=55
Reply from 172.217.16.14: bytes=32 time=11ms TTL=55
Reply from 172.217.16.14: bytes=32 time=10ms TTL=55
Reply from 172.217.16.14: bytes=32 time=10ms TTL=55
Ping statistics for 172.217.16.14:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 10ms, Maximum = 11ms, Average = 10ms
C:\utils>
If you want to execute couple of statements in background you can combine &
call operator, { }
script block and this new &
background operator like here:
& { cd .\SomeDir\; .\SomeLongRunningOperation.bat; cd ..; } &
Here's some more info from documentation pages:
from What's New in PowerShell Core 6.0:
Support backgrounding of pipelines with ampersand (&) (#3360)
Putting
&
at the end of a pipeline causes the pipeline to be run as a PowerShell job. When a pipeline is backgrounded, a job object is returned. Once the pipeline is running as a job, all of the standard*-Job
cmdlets can be used to manage the job. Variables (ignoring process-specific variables) used in the pipeline are automatically copied to the job soCopy-Item $foo $bar &
just works. The job is also run in the current directory instead of the user's home directory. For more information about PowerShell jobs, see about_Jobs.
from about_operators / Ampersand background operator &:
Ampersand background operator &
Runs the pipeline before it in a PowerShell job. The ampersand background operator acts similarly to the UNIX "ampersand operator" which famously runs the command before it as a background process. The ampersand background operator is built on top of PowerShell jobs so it shares a lot of functionality with
Start-Job
. The following command contains basic usage of the ampersand background operator.Get-Process -Name pwsh &
This is functionally equivalent to the following usage of
Start-Job
.
Start-Job -ScriptBlock {Get-Process -Name pwsh}
Since it's functionally equivalent to using
Start-Job
, the ampersand background operator returns aJob
object just likeStart-Job does
. This means that you are able to useReceive-Job
andRemove-Job
just as you would if you had usedStart-Job
to start the job.$job = Get-Process -Name pwsh & Receive-Job $job
Output
NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName ------ ----- ----- ------ -- -- ----------- 0 0.00 221.16 25.90 6988 988 pwsh 0 0.00 140.12 29.87 14845 845 pwsh 0 0.00 85.51 0.91 19639 988 pwsh $job = Get-Process -Name pwsh & Remove-Job $job
For more information on PowerShell jobs, see about_Jobs.
Sorry to revive an old thread but should anyone be looking for an alternative solution where you store your string lists as one field in your database, here's how I solved that. Create a Converter like this:
import java.util.Arrays;
import java.util.List;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import static java.util.Collections.*;
@Converter
public class StringListConverter implements AttributeConverter<List<String>, String> {
private static final String SPLIT_CHAR = ";";
@Override
public String convertToDatabaseColumn(List<String> stringList) {
return stringList != null ? String.join(SPLIT_CHAR, stringList) : "";
}
@Override
public List<String> convertToEntityAttribute(String string) {
return string != null ? Arrays.asList(string.split(SPLIT_CHAR)) : emptyList();
}
}
Now use it on your Entities like this:
@Convert(converter = StringListConverter.class)
private List<String> yourList;
In the database, your list will be stored as foo;bar;foobar
, and in your Java object you will get a list with those strings.
Hope this is helpful to someone.
please try below code.
background: transparent\0/;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#00FFFFFF,endColorstr=#00FFFFFF)progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='image',src='assets/img/bgSmall.png'); /* IE7 */
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#00FFFFFF,endColorstr=#00FFFFFF)progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='image',src='assets/img/bgSmall.png')"; /* IE8 */
I got the same problem. Than I realized I had a default string value for the column I was trying to alter. Removing the default value made the error go away :)
I wrote this JS function dump()
to work like PHP's var_dump()
.
To show the contents of the variable in an alert window: dump(variable)
To show the contents of the variable in the web page: dump(variable, 'body')
To just get a string of the variable: dump(variable, 'none')
/* repeatString() returns a string which has been repeated a set number of times */
function repeatString(str, num) {
out = '';
for (var i = 0; i < num; i++) {
out += str;
}
return out;
}
/*
dump() displays the contents of a variable like var_dump() does in PHP. dump() is
better than typeof, because it can distinguish between array, null and object.
Parameters:
v: The variable
howDisplay: "none", "body", "alert" (default)
recursionLevel: Number of times the function has recursed when entering nested
objects or arrays. Each level of recursion adds extra space to the
output to indicate level. Set to 0 by default.
Return Value:
A string of the variable's contents
Limitations:
Can't pass an undefined variable to dump().
dump() can't distinguish between int and float.
dump() can't tell the original variable type of a member variable of an object.
These limitations can't be fixed because these are *features* of JS. However, dump()
*/
function dump(v, howDisplay, recursionLevel) {
howDisplay = (typeof howDisplay === 'undefined') ? "alert" : howDisplay;
recursionLevel = (typeof recursionLevel !== 'number') ? 0 : recursionLevel;
var vType = typeof v;
var out = vType;
switch (vType) {
case "number":
/* there is absolutely no way in JS to distinguish 2 from 2.0
so 'number' is the best that you can do. The following doesn't work:
var er = /^[0-9]+$/;
if (!isNaN(v) && v % 1 === 0 && er.test(3.0)) {
out = 'int';
}
*/
break;
case "boolean":
out += ": " + v;
break;
case "string":
out += "(" + v.length + '): "' + v + '"';
break;
case "object":
//check if null
if (v === null) {
out = "null";
}
//If using jQuery: if ($.isArray(v))
//If using IE: if (isArray(v))
//this should work for all browsers according to the ECMAScript standard:
else if (Object.prototype.toString.call(v) === '[object Array]') {
out = 'array(' + v.length + '): {\n';
for (var i = 0; i < v.length; i++) {
out += repeatString(' ', recursionLevel) + " [" + i + "]: " +
dump(v[i], "none", recursionLevel + 1) + "\n";
}
out += repeatString(' ', recursionLevel) + "}";
}
else {
//if object
let sContents = "{\n";
let cnt = 0;
for (var member in v) {
//No way to know the original data type of member, since JS
//always converts it to a string and no other way to parse objects.
sContents += repeatString(' ', recursionLevel) + " " + member +
": " + dump(v[member], "none", recursionLevel + 1) + "\n";
cnt++;
}
sContents += repeatString(' ', recursionLevel) + "}";
out += "(" + cnt + "): " + sContents;
}
break;
default:
out = v;
break;
}
if (howDisplay == 'body') {
var pre = document.createElement('pre');
pre.innerHTML = out;
document.body.appendChild(pre);
}
else if (howDisplay == 'alert') {
alert(out);
}
return out;
}
Whenever there are issues of mismatched axis limits, the right tool in base
graphics is to use matplot
. The key is to leverage the from
and to
arguments to density.default
. It's a bit hackish, but fairly straightforward to roll yourself:
set.seed(102349)
x1 = rnorm(1000, mean = 5, sd = 3)
x2 = rnorm(5000, mean = 2, sd = 8)
xrng = range(x1, x2)
#force the x values at which density is
# evaluated to be the same between 'density'
# calls by specifying 'from' and 'to'
# (and possibly 'n', if you'd like)
kde1 = density(x1, from = xrng[1L], to = xrng[2L])
kde2 = density(x2, from = xrng[1L], to = xrng[2L])
matplot(kde1$x, cbind(kde1$y, kde2$y))
Add bells and whistles as desired (matplot
accepts all the standard plot
/par
arguments, e.g. lty
, type
, col
, lwd
, ...).
You can iterate over the row data
$('#button').click(function () {
var ids = $.map(table.rows('.selected').data(), function (item) {
return item[0]
});
console.log(ids)
alert(table.rows('.selected').data().length + ' row(s) selected');
});
Demo: Fiddle
This works fine in all browser...
$(document).attr("title", "New Title");
Works in IE too
a.button:hover{
background: #383; }
works for me but in my case
#buttonClick:hover {
background-color:green; }
Here is the JSONP I wrote to share with everyone:
the page to send req
http://c64.tw/r20/eqDiv/fr64.html
please save the srec below to .html youself
c64.tw/r20/eqDiv/src/fr64.txt
the page to resp, please save the srec below to .jsp youself
c64.tw/r20/eqDiv/src/doFr64.txt
or embedded the code in your page:
function callbackForJsonp(resp) {
var elemDivResp = $("#idForDivResp");
elemDivResp.empty();
try {
elemDivResp.html($("#idForF1").val() + " + " + $("#idForF2").val() + "<br/>");
elemDivResp.append(" = " + resp.ans + "<br/>");
elemDivResp.append(" = " + resp.ans2 + "<br/>");
} catch (e) {
alert("callbackForJsonp=" + e);
}
}
$(document).ready(function() {
var testUrl = "http://c64.tw/r20/eqDiv/doFr64.jsp?callback=?";
$(document.body).prepend("post to " + testUrl + "<br/><br/>");
$("#idForBtnToGo").click(function() {
$.ajax({
url : testUrl,
type : "POST",
data : {
f1 : $("#idForF1").val(),
f2 : $("#idForF2").val(),
op : "add"
},
dataType : "jsonp",
crossDomain : true,
//jsonpCallback : "callbackForJsonp",
success : callbackForJsonp,
//success : function(resp) {
//console.log("Yes, you success");
//callbackForJsonp(resp);
//},
error : function(XMLHttpRequest, status, err) {
console.log(XMLHttpRequest.status + "\n" + err);
//alert(XMLHttpRequest.status + "\n" + err);
}
});
});
});
As Tyler has suggested in one of the comments here, using
max-width: 100%;
on the child may work (worked for me). Using align-self: stretch
only works if you aren't using align-items: center
(which I did). width: 100%
only works if you haven't multiple childs inside your flexbox which you want to show side by side.
In 2020 Page Speed Insights user agents are: "Chrome-Lighthouse" for mobile and "Google Page Speed Insights" for desktop.
<?php if (!isset($_SERVER['HTTP_USER_AGENT']) || stripos($_SERVER['HTTP_USER_AGENT'], 'Chrome-Lighthouse') === false || stripos($_SERVER['HTTP_USER_AGENT'], 'Google Page Speed Insights') === false): ?>
// your google analytics code and other external script you want to hide from PageSpeed Insights here
<?php endif; ?>
How about [^\\d]*([0-9]+[\\s]*[.,]{0,1}[\\s]*[0-9]*).*
I think it would take care of numbers with fractional part.
I included white spaces and included ,
as possible separator.
I'm trying to get the numbers out of a string including floats and taking into account that the user might make a mistake and include white spaces while typing the number.
If you have forgot the MySQL root password, can’t remember or want to break in….. you can reset the mysql database password from the command line in either Linux or OS X as long as you know the root user password of the box you are on:
(1) Stop MySQL
sudo /usr/local/mysql/support-files/mysql.server stop
(2) Start it in safe mode:
sudo mysqld_safe --skip-grant-tables
(3) This will be an ongoing command until the process is finished so open another shell/terminal window, log in without a password:
mysql -u root
UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root';
In the UPDATE command above just replace the 'password' with your own new password, make sure to keep the quotation marks
(4) Save and quite
FLUSH PRIVILEGES;
\q
(5) Start MySQL
sudo /usr/local/mysql/support-files/mysql.server start
I've created a small bash script called kubetail
that makes this possible. For example to tail all logs for pods named "app1" you can do:
kubetail app1
You can find the script here.
The original accepted answer mentions jquery.cookie plugin. A few months ago though, it was renamed to js-cookie and the jQuery dependency removed. One of the reasons was just to make it easy to integrate with other frameworks, like Angular.
Now, if you want to integrate js-cookie with angular, it is as easy as something like:
module.factory( "cookies", function() {
return Cookies.noConflict();
});
And that's it. No jQuery. No ngCookies.
You can also create custom instances to handle specific server-side cookies that are written differently. Take for example PHP, that convert the spaces in the server-side to a plus sign
+
instead of also percent-encode it:
module.factory( "phpCookies", function() {
return Cookies
.noConflict()
.withConverter(function( value, name ) {
return value
// Decode all characters according to the "encodeURIComponent" spec
.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent)
// Decode the plus sign to spaces
.replace(/\+/g, ' ')
});
});
The usage for a custom Provider would be something like this:
module.service( "customDataStore", [ "phpCookies", function( phpCookies ) {
this.storeData = function( data ) {
phpCookies.set( "data", data );
};
this.containsStoredData = function() {
return phpCookies.get( "data" );
}
}]);
I hope this helps anyone.
See detailed info in this issue: https://github.com/js-cookie/js-cookie/issues/103
For detailed docs on how to integrate with server-side, see here: https://github.com/js-cookie/js-cookie/blob/master/SERVER_SIDE.md
public static string NumberToWords(int number)
{
if (number == 0)
return "zero";
if (number < 0)
return "minus " + NumberToWords(Math.Abs(number));
string words = "";
if ((number / 1000000) > 0)
{
words += NumberToWords(number / 1000000) + " million ";
number %= 1000000;
}
if ((number / 1000) > 0)
{
words += NumberToWords(number / 1000) + " thousand ";
number %= 1000;
}
if ((number / 100) > 0)
{
words += NumberToWords(number / 100) + " hundred ";
number %= 100;
}
if (number > 0)
{
if (words != "")
words += "and ";
var unitsMap = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
var tensMap = new[] { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };
if (number < 20)
words += unitsMap[number];
else
{
words += tensMap[number / 10];
if ((number % 10) > 0)
words += "-" + unitsMap[number % 10];
}
}
return words;
}
EDIT: After your comments, I understand that you want to pass variable through your form.
You can do this using hidden field:
<input type='hidden' name='var' value='<?php echo "$var";?>'/>
In PHP action File:
<?php
if(isset($_POST['var'])) $var=$_POST['var'];
?>
Or using sessions: In your first page:
$_SESSION['var']=$var;
start_session();
should be placed at the beginning of your php page.
In PHP action File:
if(isset($_SESSION['var'])) $var=$_SESSION['var'];
First Answer:
You can also use $GLOBALS
:
if (isset($_POST['save_exit']))
{
echo $GLOBALS['var'];
}
Check this documentation for more informations.
That is the mode with which you are opening the file. "wb" means that you are writing to the file (w), and that you are writing in binary mode (b).
Check out the documentation for more: clicky
You can use <i [className]="'fa fa-' + data?.icon"> </i>
I believe this won't work because you are using a console application and there is no Event Loop running. An Event Loop / Message Pump used for event handling is setup automatically when a Winforms application is created, but not for a console app.
Two other ways are strcpy(str, "");
and string[0] = 0
To really delete the Variable contents (in case you have dirty code which is not working properly with the snippets above :P ) use a loop like in the example below.
#include <string.h>
...
int i=0;
for(i=0;i<strlen(string);i++)
{
string[i] = 0;
}
In case you want to clear a dynamic allocated array of chars from the beginning, you may either use a combination of malloc() and memset() or - and this is way faster - calloc() which does the same thing as malloc but initializing the whole array with Null.
At last i want you to have your runtime in mind. All the way more, if you're handling huge arrays (6 digits and above) you should try to set the first value to Null instead of running memset() through the whole String.
It may look dirtier at first, but is way faster. You just need to pay more attention on your code ;)
I hope this was useful for anybody ;)
This is what worked for me.
formaction="@Url.Action("Edit")"
Snippet :
<input type="submit" formaction="@Url.Action("Edit")" formmethod="post" value="Save" class="btn btn-primary" />
<input type="submit" formaction="@Url.Action("PartialEdit")" formmethod="post" value="Select Type" class="btn btn-primary" />
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit( Quote quote)
{
//code
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult PartialEdit(Quote quote)
{
//code
}
Might help some one who wants to have 2 different action methods instead of one method using selectors or using client scripts .
if (UIDevice.current.identifierForVendor?.uuidString) != nil
{
self.lblDeviceIdValue.text = UIDevice.current.identifierForVendor?.uuidString
}
here describes the process well. However, some of the characters that didn't fit in latin space are gone forever. UTF-8 is a SUPERSET of latin1. Not the reverse. Most will fit in single byte space, but any undefined ones will not (check a list of latin1 - not all 256 characters are defined, depending on mysql's latin1 definition)
I found a simple method to add arbitrary time to a Date object
Date d = new Date(new Date().getTime() + 86400000)
Where:
86 400 000ms = 1 Day : 24*60*60*1000
3 600 000ms = 1 Hour : 60*60*1000
You can also selected headers to every axios
request:
// Add a request interceptor
axios.interceptors.request.use(function (config) {
config.headers.Authorization = 'AUTH_TOKEN';
return config;
});
Second method
axios.defaults.headers.common['Authorization'] = 'AUTH_TOKEN';
Some browsers such as Firefox, Chrome, Safari, Opera and IE10+ can handle Base64 natively. Take a look at this Stackoverflow question. It's using btoa()
and atob()
functions.
For server-side JavaScript (Node), you can use Buffer
s to decode.
If you are going for a cross-browser solution, there are existing libraries like CryptoJS or code like:
http://ntt.cc/2008/01/19/base64-encoder-decoder-with-javascript.html
With the latter, you need to thoroughly test the function for cross browser compatibility. And error has already been reported.
I have used Open source Web Design in the past. They have quite a few css themes, don't know about ASP.Net
If your intention was to find a way to represent null in an enumeration of singleton objects, then it's a bad idea to (de)reference null (it C++11, nullptr).
Why not declare static singleton object that represents NULL within the class as follows and add a cast-to-pointer operator that returns nullptr ?
Edit: Corrected several mistypes and added if-statement in main() to test for the cast-to-pointer operator actually working (which I forgot to.. my bad) - March 10 2015 -
// Error.h
class Error {
public:
static Error& NOT_FOUND;
static Error& UNKNOWN;
static Error& NONE; // singleton object that represents null
public:
static vector<shared_ptr<Error>> _instances;
static Error& NewInstance(const string& name, bool isNull = false);
private:
bool _isNull;
Error(const string& name, bool isNull = false) : _name(name), _isNull(isNull) {};
Error() {};
Error(const Error& src) {};
Error& operator=(const Error& src) {};
public:
operator Error*() { return _isNull ? nullptr : this; }
};
// Error.cpp
vector<shared_ptr<Error>> Error::_instances;
Error& Error::NewInstance(const string& name, bool isNull = false)
{
shared_ptr<Error> pNewInst(new Error(name, isNull)).
Error::_instances.push_back(pNewInst);
return *pNewInst.get();
}
Error& Error::NOT_FOUND = Error::NewInstance("NOT_FOUND");
//Error& Error::NOT_FOUND = Error::NewInstance("UNKNOWN"); Edit: fixed
//Error& Error::NOT_FOUND = Error::NewInstance("NONE", true); Edit: fixed
Error& Error::UNKNOWN = Error::NewInstance("UNKNOWN");
Error& Error::NONE = Error::NewInstance("NONE");
// Main.cpp
#include "Error.h"
Error& getError() {
return Error::UNKNOWN;
}
// Edit: To see the overload of "Error*()" in Error.h actually working
Error& getErrorNone() {
return Error::NONE;
}
int main(void) {
if(getError() != Error::NONE) {
return EXIT_FAILURE;
}
// Edit: To see the overload of "Error*()" in Error.h actually working
if(getErrorNone() != nullptr) {
return EXIT_FAILURE;
}
}
This LINQ below will generate the SQL for a left outer join and then take all of the results that don't find a match in your exclusion list.
List<Person> filteredResults =from p in people
join e in exclusions on p.compositeKey equals e.compositeKey into temp
from t in temp.DefaultIfEmpty()
where t.compositeKey == null
select p
let me know if it works!
You can use the function ginv() (Moore-Penrose generalized inverse) in the MASS package
Another cause can be VS 2013 Community Update 5 installing the WRONG SHORTCUTS; it installs VS 2012 shortcuts for VS 2013.
To fix it, edit the shortcuts. Rename them from 2012 to 2013, and change '11' to '12' in the path to vcvarsall.
It is an old question, but I just ran into it.
Type.GetMethod(string name)
will throw an AmbiguousMatchException if there is more than one method with that name, so we better handle that case
public static bool HasMethod(this object objectToCheck, string methodName)
{
try
{
var type = objectToCheck.GetType();
return type.GetMethod(methodName) != null;
}
catch(AmbiguousMatchException)
{
// ambiguous means there is more than one result,
// which means: a method with that name does exist
return true;
}
}
simple query this query select all record from table where email is unique:
select distinct email,* from table_name
I faced this issue too. I was using jquery.poptrox.min.js
for image popping and zooming and I received an error which said:
“Uncaught TypeError: a.indexOf is not a function” error.
This is because indexOf
was not supported in 3.3.1/jquery.min.js
so a simple fix to this is to change it to an old version 2.1.0/jquery.min.js
.
This fixed it for me.
An alternative way is to use MySql Workbench. Go to Administration -> Users and privileges -> and change 'localhost' with '%' in 'Limit to Host Matching' (From host) attribute for users you wont to give remote access Or create new user ( Add account button ) with '%' on this attribute instead localhost.
Totally frustrating, I had the same issue and tried most of the above. The exported certificate correctly had permissions to read the file in C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys
, however as it turns out it didn't have permission on the folder. Added it and it worked
You should be able to just check out the one file you want to restore. Try something like svn co svn://your_repos/path/to/file/you/want/to/restore@rev
where rev
is the last revision at which the file existed.
I had to do exactly this a little while ago and if I remember correctly, using the -r
option to svn
didn't work; I had to use the :rev
syntax. (Although I might have remembered it backwards...)
You could use an image submit button:
<input type="image" id="saveform" src="logg.png " alt="Submit Form" />
I took the idiot route. Added these to the end of /etc/profile
for environment in `find /etc/environments.d -type f`
do
. $environment
done
created a folder /etc/environments create a file in it called "oracle" or "whatever" and added the stuff I needed set globally to it.
/etc$ cat /etc/environments.d/Oracle
export PATH=$PATH:/Library/Oracle/instantclient_11_2
export DYLD_LIBRARY_PATH=/Library/Oracle/instantclient_11_2
export SQLPATH=/Library/Oracle/instantclient_11_2
export PATH=$PATH:/Library/Oracle/instantclient_11_2
export TNS_ADMIN=/Library/Oracle/instantclient_11_2/network/admin
An excerpt from an apple technical note (Thanks to matthias-bauch)
Xcode includes all your command-line tools. If it is installed on your system, remove it to uninstall your tools.
If your tools were downloaded separately from Xcode, then they are located at
/Library/Developer/CommandLineTools
on your system. Delete the CommandLineTools folder to uninstall them.
you could easily delete using terminal:
Here is an article that explains how to remove the command line tools but do it at your own risk.Try this only if any of the above doesn't work.
git config --global --unset http.proxy
git config --unset http.proxy
http_proxy=""
To avoid getting expections at run time , do something like this.
There are chances of having empty string sometimes,
string a = "abc,xyz,wer";
string b=string.Empty;
if(!string.IsNullOrEmpty(a ))
{
b = a.Split(',')[0];
}
docker export -o <nameOfContainer>.tar <nameOfContainer>
Might need to prune the existing container using docker prune ...
Import with required modifications:
cat <nameOfContainer>.tar | docker import -c "ENTRYPOINT service mysql start && /bin/bash" - <nameOfContainer>
Run the container for example with always restart option to make sure it will auto resume after host/daemon recycle:
docker run -d -t -i --restart always --name <nameOfContainer> <nameOfContainer> /bin/bash
Side note: In my opinion reasonable is to start only cron service leaving container as clean as possible then just modify crontab or cron.hourly, .daily etc... with corresponding checkup/monitoring scripts. Reason is You rely only on one daemon and in case of changes it is easier with ansible or puppet to redistribute cron scripts instead of track services that start at boot.
step-1
open -> Visual Studio 2017 Developer Command Prompt
step-2
WSDL.exe /OUT:myFile.cs WSDLURL /Language:CS /serverInterface
step-2
create new "Web service Project"
step-3
add -> web service
step-4
copy all code from myFile.cs (generated above) except "using classes" eg:
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.6.1055.0")]
[System.Web.Services.WebServiceBindingAttribute(Name="calculoterServiceSoap",Namespace="http://tempuri.org/")]
public interface ICalculoterServiceSoap {
/// <remarks/>
[System.Web.Services.WebMethodAttribute()]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/addition", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
string addition(int firtNo, int secNo);
}
step-4
past it into your webService.asmx.cs (inside of namespace) created above in step-2
step-5
inherit the interface class with your web service class eg:
public class WebService2 : ICalculoterServiceSoap
Run your script with .
. myscript.sh
This will run the script in the current shell environment.
export
governs which variables will be available to new processes, so if you say
FOO=1
export BAR=2
./runScript.sh
then $BAR
will be available in the environment of runScript.sh
, but $FOO
will not.
Chris Beeley is rigth, you only need the proportions by column. Using your data is:
your_matrix<-(
rbind(
c(23,234,324),
c(34,534,12),
c(56,324,124),
c(34,234,124),
c(123,534,654)
)
)
barplot(prop.table(your_matrix, 2) )
You need to read and write document.cookie
if (document.cookie.indexOf("visited=") >= 0) {
// They've been here before.
alert("hello again");
}
else {
// set a new cookie
expiry = new Date();
expiry.setTime(expiry.getTime()+(10*60*1000)); // Ten minutes
// Date()'s toGMTSting() method will format the date correctly for a cookie
document.cookie = "visited=yes; expires=" + expiry.toGMTString();
alert("this is your first time");
}
The scope <scope>provided</scope>
gives you an opportunity to tell that the jar would be available at runtime, so do not bundle it. It does not mean that you do not need it at compile time, hence maven would try to download that.
Now I think, the below maven artifact do not exist at all. I tries searching google, but not able to find. Hence you are getting this issue.
Change groupId
to <groupId>net.sourceforge.ant4x</groupId>
to get the latest jar.
<dependency>
<groupId>net.sourceforge.ant4x</groupId>
<artifactId>ant4x</artifactId>
<version>${net.sourceforge.ant4x-version}</version>
<scope>provided</scope>
</dependency>
Another solution for this problem is:
Where http://localhost/repo is your local repo URL:
<repositories>
<repository>
<id>wmc-central</id>
<url>http://localhost/repo</url>
</repository>
<-- Other repository config ... -->
</repositories>
You can use System.load()
to provide an absolute path which is what you want, rather than a file in the standard library folder for the respective OS.
If you want native applications that already exist, use System.loadLibrary(String filename)
. If you want to provide your own you're probably better with load().
You should also be able to use loadLibrary
with the java.library.path
set correctly. See ClassLoader.java
for implementation source showing both paths being checked (OpenJDK)
I added viewlocationformat to RazorViewEngine and worked for me.
ViewLocationFormats = new[] {
"~/Views/{1}/{0}.cshtml",
"~/Views/Shared/{0}.cshtml",
"~/Areas/Admin/Views/{1}/{0}.cshtml",
"~/Areas/Admin/Views/Shared/{0}.cshtml"
};
It depends on what you are trying to do.
file, err := os.Open("file.txt")
fmt.print(file)
The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File
), not file-content. To obtain file-content, you may READ
from a file-descriptor.
To read all file content(in bytes) to memory, ioutil.ReadAll
package main
import (
"fmt"
"io/ioutil"
"os"
"log"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
b, err := ioutil.ReadAll(file)
fmt.Print(b)
}
But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read
from *os.File
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
buf := make([]byte, 32*1024) // define your buffer size here.
for {
n, err := file.Read(buf)
if n > 0 {
fmt.Print(buf[:n]) // your read buffer.
}
if err == io.EOF {
break
}
if err != nil {
log.Printf("read %d bytes: %v", n, err)
break
}
}
}
Otherwise, you could also use the standard util package: bufio
, try Scanner
. A Scanner
reads your file in tokens: separator.
By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).
package main
import (
"fmt"
"os"
"log"
"bufio"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
scanner := bufio.NewScanner(file)
for scanner.Scan() { // internally, it advances token based on sperator
fmt.Println(scanner.Text()) // token in unicode-char
fmt.Println(scanner.Bytes()) // token in bytes
}
}
Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.
After formatting the previous answer to my own code, I have found an efficient way to copy all necessary data if you are attempting to paste the values returned via AutoFilter
to a separate sheet.
With .Range("A1:A" & LastRow)
.Autofilter Field:=1, Criteria1:="=*" & strSearch & "*"
.Offset(1,0).SpecialCells(xlCellTypeVisible).Cells.Copy
Sheets("Sheet2").activate
DestinationRange.PasteSpecial
End With
In this block, the AutoFilter
finds all of the rows that contain the value of strSearch
and filters out all of the other values. It then copies the cells (using offset in case there is a header), opens the destination sheet and pastes the values to the specified range on the destination sheet.
Note that time.gmtime
maps timestamp 0
to 1970-1-1 00:00:00
.
In [61]: import time
In [63]: time.gmtime(0)
Out[63]: time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)
time.mktime(time.gmtime(0))
gives you a timestamp shifted by an amount that depends on your locale, which in general may not be 0.
In [64]: time.mktime(time.gmtime(0))
Out[64]: 18000.0
The inverse of time.gmtime
is calendar.timegm
:
In [62]: import calendar
In [65]: calendar.timegm(time.gmtime(0))
Out[65]: 0
According to the documentation, there are three kinds of lists that can be used with an AlertDialog
:
I will give an example of each below.
The way to make a traditional single-choice list is to use setItems
.
Java version
// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose an animal");
// add a list
String[] animals = {"horse", "cow", "camel", "sheep", "goat"};
builder.setItems(animals, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0: // horse
case 1: // cow
case 2: // camel
case 3: // sheep
case 4: // goat
}
}
});
// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();
There is no need for an OK button because as soon as the user clicks on a list item control is returned to the OnClickListener
.
Kotlin version
// setup the alert builder
val builder = AlertDialog.Builder(context)
builder.setTitle("Choose an animal")
// add a list
val animals = arrayOf("horse", "cow", "camel", "sheep", "goat")
builder.setItems(animals) { dialog, which ->
when (which) {
0 -> { /* horse */ }
1 -> { /* cow */ }
2 -> { /* camel */ }
3 -> { /* sheep */ }
4 -> { /* goat */ }
}
}
// create and show the alert dialog
val dialog = builder.create()
dialog.show()
The advantage of the radio button list over the traditional list is that the user can see what the current setting is. The way to make a radio button list is to use setSingleChoiceItems
.
Java version
// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose an animal");
// add a radio button list
String[] animals = {"horse", "cow", "camel", "sheep", "goat"};
int checkedItem = 1; // cow
builder.setSingleChoiceItems(animals, checkedItem, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// user checked an item
}
});
// add OK and Cancel buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// user clicked OK
}
});
builder.setNegativeButton("Cancel", null);
// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();
I hard coded the chosen item here, but you could keep track of it with a class member variable in a real project.
Kotlin version
// setup the alert builder
val builder = AlertDialog.Builder(context)
builder.setTitle("Choose an animal")
// add a radio button list
val animals = arrayOf("horse", "cow", "camel", "sheep", "goat")
val checkedItem = 1 // cow
builder.setSingleChoiceItems(animals, checkedItem) { dialog, which ->
// user checked an item
}
// add OK and Cancel buttons
builder.setPositiveButton("OK") { dialog, which ->
// user clicked OK
}
builder.setNegativeButton("Cancel", null)
// create and show the alert dialog
val dialog = builder.create()
dialog.show()
The way to make a checkbox list is to use setMultiChoiceItems
.
Java version
// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose some animals");
// add a checkbox list
String[] animals = {"horse", "cow", "camel", "sheep", "goat"};
boolean[] checkedItems = {true, false, false, true, false};
builder.setMultiChoiceItems(animals, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
// user checked or unchecked a box
}
});
// add OK and Cancel buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// user clicked OK
}
});
builder.setNegativeButton("Cancel", null);
// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();
Here I hard coded the the which items in the list were already checked. It is more likely that you would want to keep track of them in an ArrayList<Integer>
. See the documentation example for more details. You can also set the checked items to null
if you always want everything to start unchecked.
Kotlin version
// setup the alert builder
val builder = AlertDialog.Builder(context)
builder.setTitle("Choose some animals")
// add a checkbox list
val animals = arrayOf("horse", "cow", "camel", "sheep", "goat")
val checkedItems = booleanArrayOf(true, false, false, true, false)
builder.setMultiChoiceItems(animals, checkedItems) { dialog, which, isChecked ->
// user checked or unchecked a box
}
// add OK and Cancel buttons
builder.setPositiveButton("OK") { dialog, which ->
// user clicked OK
}
builder.setNegativeButton("Cancel", null)
// create and show the alert dialog
val dialog = builder.create()
dialog.show()
context
in the code above, don't use getApplicationContext()
or you will get an IllegalStateException
(see here for why). Instead, get a reference to the activity context, such as with this
.setAdapter
or setCursor
or passing in a Cursor
or ListAdapter
into the setSingleChoiceItems
or setMultiChoiceItems
.To test all of the examples above I just had a simple project with a single button than showed the dialog when clicked:
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
}
public void showAlertDialogButtonClicked(View view) {
// example code to create alert dialog lists goes here
}
}
When I am developing, I prefer to use this practical class to configure Migrations.
Hope it helps.
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
this.Configuration.LazyLoadingEnabled = false;
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
Database.SetInitializer(new StackOverflowInitializer());
}
public class StackOverflowInitializer : DropCreateDatabaseIfModelChanges<ApplicationDbContext>
{
public StackOverflowInitializer()
{
// TODO NOTHING, COMMENT ALL
// IF CHANGES, RECREATE
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<ApplicationDbContext>());
// CREATE ONLY NOT EXITS
//Database.SetInitializer<Context>(new CreateDatabaseIfNotExists<ApplicationDbContext>());
}
}
public System.Data.Entity.DbSet<stackoverflow.Models.Company> Companies { get; set; }
}
Facelets is a XML based view technology. The &
is a special character in XML representing the start of an entity like &
which ends with the ;
character. You'd need to either escape it, which is ugly:
rendered="#{beanA.prompt == true && beanB.currentBase != null}"
or to use the and
keyword instead, which is preferred as to readability and maintainability:
rendered="#{beanA.prompt == true and beanB.currentBase != null}"
Unrelated to the concrete problem, comparing booleans with booleans makes little sense when the expression expects a boolean outcome already. I'd get rid of == true
:
rendered="#{beanA.prompt and beanB.currentBase != null}"
Use \overleftarrow
to create a long arrow to the left.
\overleftarrow{blahblahblah}
I think that your model #2 is fine, however you can take a look at the more complex model which stores questions and pre-made answers (offered answers) and allows them to be re-used in different surveys.
- One survey can have many questions; one question can be (re)used in many surveys.
- One (pre-made) answer can be offered for many questions. One question can have many answers offered. A question can have different answers offered in different surveys. An answer can be offered to different questions in different surveys. There is a default "Other" answer, if a person chooses other, her answer is recorded into Answer.OtherText.
- One person can participate in many surveys, one person can answer specific question in a survey only once.
Using the word class as a key in a Javascript dictionary can also trigger the dreaded "Expected identifier, string or number" error because class is a reserved keyword in Internet Explorer.
BAD
{ class : 'overlay'} // ERROR: Expected identifier, string or number
GOOD
{'class': 'overlay'}
When using a reserved keyword as a key in a Javascript dictionary, enclose the key in quotes.
Hope this hint saves you a day of debugging hell.
Is it as optional functionality.
If you won't provide it when user will try to purchase non-consumable product AppStore will restore old transaction. But your app will think that this is new transaction.
If you will provide restore mechanism then your purchase manager will see restored transaction.
If app should distinguish this options then you should provide functionality for restoring previously purchased products.
Copy the .rpm file in a separate folder then run the following command $ yourfile.rpm | cpio -idmv
Try renaming the default file. In my case, a recent move to IIS7.5 gave the 405 error. I changed index.aspx to default.aspx and it worked immediately for me.
You want the 'change' event handler, instead of 'click'.
$('#mySelect').change(function(){
var value = $(this).val();
});
The way you can exclude a destination directory while using the /mir is by making sure the destination directory also exists on the source. I went into my source drive and created blank directories with the same name as on the destination, and then added that directory name to the /xd. It successfully mirrored everything while excluding the directory on the source, thereby leaving the directory on the destination intact.
Global exclusions look like they're being worked on, but until then...
From the Sonatype maven reference (bottom of the page):
Dependency management in a top-level POM is different from just defining a dependency on a widely shared parent POM. For starters, all dependencies are inherited. If mysql-connector-java were listed as a dependency of the top-level parent project, every single project in the hierarchy would have a reference to this dependency. Instead of adding in unnecessary dependencies, using dependencyManagement allows you to consolidate and centralize the management of dependency versions without adding dependencies which are inherited by all children. In other words, the dependencyManagement element is equivalent to an environment variable which allows you to declare a dependency anywhere below a project without specifying a version number.
As an example:
<dependencies>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</dependencyManagement>
It doesn't make the code less verbose overall, but it does make it less verbose where it counts. If you still want it less verbose you can follow these tips also from the Sonatype reference.
Use the FROM_UNIXTIME()
function in MySQL
Remember that if you are using a framework that stores it in milliseconds (for example Java's timestamp) you have to divide by 1000 to obtain the right Unix time in seconds.
Try this
// Create a DecimalFormat that fits your requirements
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(',');
symbols.setDecimalSeparator('.');
String pattern = "#,##0.0#";
DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
decimalFormat.setParseBigDecimal(true);
// parse the string
BigDecimal bigDecimal = (BigDecimal) decimalFormat.parse("10,692,467,440,017.120");
System.out.println(bigDecimal);
If you are building an application with I18N support you should use DecimalFormatSymbols(Locale)
Also keep in mind that decimalFormat.parse
can throw a ParseException
so you need to handle it (with try/catch) or throw it and let another part of your program handle it
Look at the methods in the java.io.File class:
File file = new File("yourfileName");
String path = file.getAbsolutePath();
You can also use
$(document).ready(function() {
//some even that will run ajax request - for example click on a button
var uname = $('#username').val();
$.ajax({
type: 'POST',
url: 'func.php', //this should be url to your PHP file
dataType: 'html',
data: {func: 'toptable', user_id: uname},
beforeSend: function() {
$('#right').html('checking');
},
complete: function() {},
success: function(html) {
$('#right').html(html);
}
});
});
And your func.php:
function toptable()
{
echo 'something happens in here';
}
Hope it helps somebody
You have to workaround this via static application context accessor approach:
@Component
public class StaticContextAccessor {
private static StaticContextAccessor instance;
@Autowired
private ApplicationContext applicationContext;
@PostConstruct
public void registerInstance() {
instance = this;
}
public static <T> T getBean(Class<T> clazz) {
return instance.applicationContext.getBean(clazz);
}
}
Then you can access bean instances in a static manner.
public class Boo {
public static void randomMethod() {
StaticContextAccessor.getBean(Foo.class).doStuff();
}
}
I have recently blogged on a solution that worked for me by using a Markdown XSLT file to transform the HTML Source. The HTML source will of course need to be valid XML first
We use blat to do this all the time in our environment. I use it as well to connect to Gmail with Stunnel. Here's the params to send a file
blat -to [email protected] -server smtp.example.com -f [email protected] -subject "subject" -body "body" -attach c:\temp\file.txt
Or you can put that file in as the body
blat c:\temp\file.txt -to [email protected] -server smtp.example.com -f [email protected] -subject "subject"
You may try Navicat. It used to have a free "Lite" version whih is unfortunately not available any more. The pro version supports several important DB engines, not only SQLite. I am currently using the 30-day free eval version.
Note however:
If you issue SET TRANSACTION ISOLATION LEVEL in a stored procedure or trigger, when the object returns control the isolation level is reset to the level in effect when the object was invoked. For example, if you set REPEATABLE READ in a batch, and the batch then calls a stored procedure that sets the isolation level to SERIALIZABLE, the isolation level setting reverts to REPEATABLE READ when the stored procedure returns control to the batch.
list comprehension?
[x.strip() for x in lst]
Here is a simple method: go to Start then Programs then Microsoft SQL Server 2005 then Configuration Tools then SQL Server Configuration Manager then SQL Server 2005 Network Configuration then Here you can locate all the instance installed onto your machine.
After a long reserch and digging too deep i found the solution of certificate pinning in android and yes its different from iOS where we need a certificate itself but in android we just need a hash pin and that's it.
How to get hash pin for certificate?
Initially just use a wrong hash pin and your java class will throw an error with correct hash pins or pin chain, just copy and paste into your code thats it.
This solution fixed my problem : https://stackoverflow.com/a/45853669/3448003
It's a reserved keyword (like return, filter, function, break).
Also, as per Section 7.6.4 of Bruce Payette's Powershell in Action:
But what happens when you want a script to exit from within a function defined in that script? ... To make this easier, Powershell has the exit keyword.
Of course, as other have pointed out, it's not hard to do what you want by wrapping exit in a function:
PS C:\> function ex{exit}
PS C:\> new-alias ^D ex
Though this isn't 'powershell' specific... you can easily list the drives and partitions using diskpart, list volume
PS C:\Dev> diskpart
Microsoft DiskPart version 6.1.7601
Copyright (C) 1999-2008 Microsoft Corporation.
On computer: Box
DISKPART> list volume
Volume ### Ltr Label Fs Type Size Status Info
---------- --- ----------- ----- ---------- ------- --------- --------
Volume 0 D DVD-ROM 0 B No Media
Volume 1 C = System NTFS Partition 100 MB Healthy System
Volume 2 G C = Box NTFS Partition 244 GB Healthy Boot
Volume 3 H D = Data NTFS Partition 687 GB Healthy
Volume 4 E System Rese NTFS Partition 100 MB Healthy
This is not so much an answer to your original question as to one of the queries you had in the body of your question.
A little preamble, so that my naming doesn't seem strange:
import matplotlib
from matplotlib import rc
from matplotlib.figure import Figure
ax = self.figure.add_subplot( 111 )
As has been mentioned you can use ticklabel_format to specify that matplotlib should use scientific notation for large or small values:
ax.ticklabel_format(style='sci',scilimits=(-3,4),axis='both')
You can affect the way that this is displayed using the flags in rcParams (from matplotlib import rcParams) or by setting them directly. I haven't found a more elegant way of changing between '1e' and 'x10^' scientific notation than:
ax.xaxis.major.formatter._useMathText = True
This should give you the more Matlab-esc, and indeed arguably better appearance. I think the following should do the same:
rc('text', usetex=True)
I've found out that GPS does not need Internet, BUT of course if you need to download maps, you will need a data connection or wifi.
http://androidforums.com/samsung-fascinate/288871-gps-independent-3g-wi-fi.html http://www.droidforums.net/forum/droid-applications/63145-does-google-navigation-gps-requires-3g-work.html
use Date.prototype.toLocaleTimeString()
as documented here
please note the locale example en-US in the url.
You need an extra reference for this; the most convenient way to do this is via the NuGet package System.IO.Compression.ZipFile
<!-- Version here correct at time of writing, but please check for latest -->
<PackageReference Include="System.IO.Compression.ZipFile" Version="4.3.0" />
If you are working on .NET Framework without NuGet, you need to add a dll reference to the assembly, "System.IO.Compression.FileSystem.dll" - and ensure you are using at least .NET 4.5 (since it doesn't exist in earlier frameworks).
For info, you can find the assembly and .NET version(s) from MSDN
Java inbuilt libraries support only AIFC, AIFF, AU, SND and WAVE formats. Here I only discussed playing an audio file using Clip only and see the various methods of a clip.
PlayAudio.java
.Audio.java
.PlayAudio.java
import java.io.IOException;
import java.util.Scanner;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
public class PlayAudio {
public static void main(String[] args) throws
UnsupportedAudioFileException, IOException,
LineUnavailableException {
PlayMp3 playMp3;
playMp3=new PlayMp3();
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter Choice :-");
System.out.println("1. Play");
System.out.println("2. pause");
System.out.println("3. resume");
System.out.println("4. restart");
System.out.println("5. stop");
System.out.println(PlayMp3.status);
System.out.println(":::- ");
int c = sc.nextInt();
if (c ==5){
playMp3.stop();
break;
}
switch (c) {
case 1:
playMp3.play();
break;
case 2:
playMp3.pause();
break;
case 3:
playMp3.resume();
break;
case 4:
playMp3.restart();
break;
case 5:
playMp3.stop();
default:
System.out.println("Please Enter Valid Option :-");
}
}
sc.close();
}
}
Audio.java
import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
public class Audio {
private String filePath="mp.snd";
public static String status="paused";
private Long currentFrame=0L;
private Clip clip;
private AudioInputStream audioInputStream;
public Audio() throws UnsupportedAudioFileException, IOException, LineUnavailableException {
audioInputStream = AudioSystem.getAudioInputStream(new File(filePath));
clip = AudioSystem.getClip();
clip.open(audioInputStream);
}
public void play(){
clip.start();
status = "playing";
}
public void pause(){
if (status.equals("paused")) {
System.out.println("audio is already paused");
return;
}
currentFrame = clip.getMicrosecondPosition();
clip.stop();
status = "paused";
}
public void resume() throws UnsupportedAudioFileException, IOException, LineUnavailableException {
if (status.equals("play"))
{
System.out.println("Audio is already being playing");
return;
}
clip.close();
//starts again and goes to currentFrame
resetAudioStream();
clip.setMicrosecondPosition(currentFrame);
play();
status="playing";
}
public void restart() throws UnsupportedAudioFileException, IOException, LineUnavailableException {
clip.stop();
clip.close();
resetAudioStream();
currentFrame = 0L;
clip.setMicrosecondPosition(0);
play();
status="Playing from start";
}
public void stop(){
currentFrame = 0L;
clip.stop();
clip.close();
status="stopped";
}
private void resetAudioStream() throws IOException, UnsupportedAudioFileException, LineUnavailableException {
audioInputStream = AudioSystem.getAudioInputStream(new File(filePath).getAbsoluteFile());
clip.open(audioInputStream);
}
}
To answer a more generic case, this error is noticed when you pick a function name which is already used in some built in library. For e.g., select.
A simple method to know about it is while compiling the file, the compiler will indicate the previous declaration.
Building on @Kristian's answer, I had a desire to display a fixed number of decimal places. That can be accomplished with other arguments in the QString::number(...)
function. For instance, I wanted 3 decimal places:
double value = 34.0495834;
QString strValue = QString::number(value, 'f', 3);
// strValue == "34.050"
The 'f'
specifies decimal format notation (more info here, you can also specify scientific notation) and the 3
specifies the precision (number of decimal places). Probably already linked in other answers, but more info about the QString::number
function can be found here in the QString
documentation
It is used in the new short hand for/loop
final List<String> list = new ArrayList<String>();
for (final String s : list)
{
System.out.println(s);
}
and the ternary operator
list.isEmpty() ? true : false;
You need the following permissions in your manifest file:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
Then you can use the following in your activity class:
WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);
Use the following to check if it's enabled or not
boolean wifiEnabled = wifiManager.isWifiEnabled()
You'll find a nice tutorial on the subject on this site.