you can start the one when selecting one item from the left tree "virtual device" in AVD manager dialog on the platform of eclipse, the start UI has the option "Wipe User Data"
Complete step-by-step instructions for running the accelerated emulator can be found on the official Android developers website:
Caution: As of SDK Tools Revision 17, the virtual machine acceleration feature for the emulator is experimental; be alert for incompatibilities and errors when using this feature.
Another solution, for those of us without an internet connection to our development machine is:
Create a folder called system-images
in the top level of your SDK directory (next to platforms
and tools
). Create subdirs android-14
and android-15
(as applicable).
Extract the complete armeabi-v7a
folder to these directory; sysimg_armv7a-15_r01.zip (from, e.g. google's repository) goes to android-15
, sysimg_armv7a-14_r02.zip to android-14
.
I've not tried this procedure offline, I finally relented and used my broadband allowance at home, but these are the target locations for these large sysimg's, for future reference.
I've tried creating the image
subdirs where they were absent in 14 and 15 but while this allowed the AVD to create an image (for 15 but not 14) it hadn't shown the Android logo after 15 minutes.
See the Android documentation on controlling the emulator; it's Ctrl + F11 / Ctrl + F12.
On ThinkPad running Ubuntu, you may try CTRL + Left Arrow Key or Right Arrow Key
Like this:
public String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e(LOG_TAG, ex.toString());
}
return null;
}
Check the docs for more info: NetworkInterface.
I have used the following procedure.
Procedure to install the apk files in Android Emulator(AVD):
Check your installed directory(ex: C:\Program Files (x86)\Android\android-sdk\platform-tools), whether it has the adb.exe or not). If not present in this folder, then download the attachment here, extract the zip files. You will get adb files, copy and paste those three files inside tools folder
Run AVD manager from C:\Program Files (x86)\Android\android-sdk and start the Android Emulator.
Copy and paste the apk file inside the C:\Program Files (x86)\Android\android-sdk\platform-tools
Go to Start -> Run -> cmd
Type cd “C:\Program Files (x86)\Android\android-sdk\platform-tools”
Type adb install example.apk
After getting success command
Go to Application icon in Android emulator, we can see the your application
Starting from Android Studio 2.3.2 now you can create an AVD that has Play Store pre-installed on it. Currently, it is supported on the AVD's running
For other emulators, you can try the solution mentioned in this answer.
Go To AVD Manager, Click On The "Down Arrow" Next to The AVD Device that is showing this error, Click on "Show on Disk". Now Delete These Two Files "Cache.img" & "cache.img.qcow2" ..
Works Perfectly Fine For me.
In my case
android studio suddenly stop seeing my device
I fix it by change USB option to Media device (MTP)
how to get USB option from storage USB Computer Connection
check Debugging from developer options
try re-run on device , it should work
issue
USB option was charge only
UPDATE ANSWER 26/7/2016
there many reasons like not enabling developer mode --> USB debugging(if you dont see developer option click 7 times at build number )
but I face another issue every thing was works just fine suddenly android studio cant see my device
to fix this issue you need to restart adb , from terminal
adb kill-server
adb start-server
or from ddms
in devices section --> click at small arrow down --> restart adb
See my answer for the Android Studio environment, Mac and “PANIC: Missing emulator engine program for 'arm' CPU.”.
To solve this problem, you need to specify the -kernel
path manually. i.e.
$ ~/Library/Android/sdk/emulator/emulator @Galaxy_Nexus_Jelly_Bean_API_16 -kernel ~/Library/Android/sdk/system-images/android-16/default/armeabi-v7a/kernel-qemu
Remember to change the emulator name Galaxy_Nexus_Jelly_Bean_API_16
to your own emulator name.
Below command is to check the emulators available for command line.
$ ~/Library/Android/sdk/emulator/emulator -list-avds
And also, ensure that your emulator path is correct, i.e. the one located at ~/Library/Android/sdk/emulator/
.
Here’s what you need to do:
1.Download and extract the SDK.
2.Open a terminal and navigate to the “tools” directory.
3.Launch the “android” tool (./android if you are currently in the tools directory).
4.Tick off the “SDK Platform” for each version of Android that you’d like to use in your emulator.
5.Click the “Install N Packages” button.
6.Click each package and tick off “Accept License” (legally, I’m probably required to tell you that this step may take several hours as you read each license ;).
7.Done with those licenses? Great. Click “Install”. Wait for the SDK manager to finish installing your packages, then you can close it.
8.Back in your terminal, still in the tools directory, enter ./android avd which will launch the Android Virtual Device Manager.
9.Click “New” and fill out the form to build the device you’d like to emulate. In the “Target” dropdown, you’ll see the SDK Platforms that you installed earlier. If the version you need is missing, you need to go back and install it. Click OK when you’re done.
10.Click on the device that you just created and click the “Start” button, tweak any options that you need on the Launch Options window, and click “Launch”.
Check this question's answer also.
I think the easiest way is to move the avd folder from C:\Users[USER].android folder to your desired location then create a symbolic link to it in C:\Users[USER].android with the same name.
If you wonder how to do this, first install Link Shell Extension. After folder movement right click on it and select Pick Link Source then right click in .android folder and in Drop As... sub menu select Symbolic Link.
Unfortunately I ended up having to re-install eclipse. but first (In Linux)(not sure of folder in Windows) do:
sudo rm -R /usr/share/eclipse/
Go to Control Panel>>System and Security>>System>>Advance system settings>>Environment Variables then set variable value of ANDROID_HOME set it like this "C:\Users\username\AppData\Local\Android\sdk" set username as your pc name, then restart your android studio. after that you can create your AVD again than the error will gone than it will start the virtual device.
I am using Kaspersky. I just turned it off and the issue was solved!
You need to try on an emulator with the Google API's version. Each platform has two versions, Android and Android+Google APIs. Ensure that when you create the AVD, you select the Google APIs version on target field.
And the page Ensure Devices Have the Google Play services APK can be also helpful.
Use x86 images and download "Intel Hardware Accelerated Execution Manager" from the sdk manager.
See here how to enable it: http://developer.android.com/tools/devices/emulator.html#accel-vm
Your emulator will be super fast!
just for additional info, If your apps is automatically run on emulator, right click on the project, Run As -> Run Configuration, then on the Run Configuration choose on the Manual. after that, if you run your apps you will be prompted to chose where you want to run your apps, there will be listed all the available device and emulator.
For AMD processors:
You don't need Genymotion, just create a new Virtual Device and while selecting the system Image select the ABI as armeabi instead of the default x86 one.
Try to do all the steps specified in the link below and before that upgrade VirtualBox to 4.2 by following the instructions in VirtualBox 4.2.0 Released With Support For Drag'n'drop From Host To Linux Guests, More. Then upgrade Genymotion to the latest version.
Go to the desktop and run Genymotion. Select a virtual device with Android version 4.2 and then drag and drop the two files Genymotion-ARM-Translation_v1.1.zip first. Then Genymotion will show progress and after this it will promt a dialog. Then click OK and it will ask to reboot the device. Restart ADB. Do the same steps for the second file, gapps-jb-20130812-signed.zip and restart ADB.
I hope this will resolve the issue. Check this link - it explains it clearer.
Usually this implies some Android setup issue with the project. Go to the "Resource Manager" tab where you will be able to click on "Add Android Module" and click on import gradle files. If the import fails, you will get error messages that you can work with
Use the built-in functions for length and max on the description column:
SELECT MAX(LEN(DESC)) FROM table_name;
Note that if your table is very large, there can be performance issues.
you can enable "Instant Run" on Android Studio to get multidex support.
You create buttons dynamically because of that you need to call them with .live()
method if you use jquery 1.7
but this method is deprecated (you can see the list of all deprecated method here) in newer version. if you want to use jquery 1.10 or above you need to call your buttons in this way:
$(document).on('click', 'selector', function(){
// Your Code
});
For Example
If your html is something like this
<div id="btn-list">
<div class="btn12">MyButton</div>
</div>
You can write your jquery like this
$(document).on('click', '#btn-list .btn12', function(){
// Your Code
});
Dim timeFormat As String = "yyyy-MM-dd HH:mm:ss"
objBL.date = Convert.ToDateTime(txtDate.Value).ToString(timeFormat)
In your activity_main.xml
, you can adjust from there
in the line:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
.......
android:theme="@style/Theme.Design.Light.NoActionBar"
.......
">
Sometimes when you can see things like this Click here, You can select from here the "noActionBar" theme.
Hope me helped you.
Probably the path you supplied was not correct. Check that.
I would recomment the article Howto: (Almost) Everything In Active Directory via C# which really helped me in the past in dealing with AD.
I solved this with Access options.
Go to the Office Button --> Access Options --> Trust Center --> Trust Center Settings Button --> Message Bar
In the right hand pane I selected the radio button "Show the message bar in all applications when content has been blocked."
Closed Access, reopened the database and got the warning for blocked content again.
My 'random' library provide a high convenient wrapper around C++11 random classes. You can do almost all things with a simple 'get' method.
Examples:
Random number in a range
auto val = Random::get(-10, 10); // Integer
auto val = Random::get(10.f, -10.f); // Float point
Random boolean
auto val = Random::get<bool>( ) // 50% to generate true
auto val = Random::get<bool>( 0.7 ) // 70% to generate true
Random value from a std::initilizer_list
auto val = Random::get( { 1, 3, 5, 7, 9 } ); // val = 1 or 3 or...
Random iterator from iterator range or all container
auto it = Random::get( vec.begin(), vec.end() ); // it = random iterator
auto it = Random::get( vec ); // return random iterator
And even more things ! Check out the github page:
<?php
// Custom PHP MySQL Pagination Tutorial and Script
// You have to put your mysql connection data and alter the SQL queries(both queries)
mysql_connect("DATABASE_Host_Here","DATABASE_Username_Here","DATABASE_Password_Here") or die (mysql_error());
mysql_select_db("DATABASE_Name_Here") or die (mysql_error());
////////////// QUERY THE MEMBER DATA INITIALLY LIKE YOU NORMALLY WOULD
$sql = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC");
//////////////////////////////////// Pagination Logic ////////////////////////////////////////////////////////////////////////
$nr = mysql_num_rows($sql); // Get total of Num rows from the database query
if (isset($_GET['pn'])) { // Get pn from URL vars if it is present
$pn = preg_replace('#[^0-9]#i', '', $_GET['pn']); // filter everything but numbers for security(new)
//$pn = ereg_replace("[^0-9]", "", $_GET['pn']); // filter everything but numbers for security(deprecated)
} else { // If the pn URL variable is not present force it to be value of page number 1
$pn = 1;
}
//This is where we set how many database items to show on each page
$itemsPerPage = 10;
// Get the value of the last page in the pagination result set
$lastPage = ceil($nr / $itemsPerPage);
// Be sure URL variable $pn(page number) is no lower than page 1 and no higher than $lastpage
if ($pn < 1) { // If it is less than 1
$pn = 1; // force if to be 1
} else if ($pn > $lastPage) { // if it is greater than $lastpage
$pn = $lastPage; // force it to be $lastpage's value
}
// This creates the numbers to click in between the next and back buttons
// This section is explained well in the video that accompanies this script
$centerPages = "";
$sub1 = $pn - 1;
$sub2 = $pn - 2;
$add1 = $pn + 1;
$add2 = $pn + 2;
if ($pn == 1) {
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> ';
} else if ($pn == $lastPage) {
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
} else if ($pn > 2 && $pn < ($lastPage - 1)) {
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub2 . '">' . $sub2 . '</a> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add2 . '">' . $add2 . '</a> ';
} else if ($pn > 1 && $pn < $lastPage) {
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> ';
}
// This line sets the "LIMIT" range... the 2 values we place to choose a range of rows from database in our query
$limit = 'LIMIT ' .($pn - 1) * $itemsPerPage .',' .$itemsPerPage;
// Now we are going to run the same query as above but this time add $limit onto the end of the SQL syntax
// $sql2 is what we will use to fuel our while loop statement below
$sql2 = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC $limit");
//////////////////////////////// END Pagination Logic ////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// Pagination Display Setup /////////////////////////////////////////////////////////////////////
$paginationDisplay = ""; // Initialize the pagination output variable
// This code runs only if the last page variable is ot equal to 1, if it is only 1 page we require no paginated links to display
if ($lastPage != "1"){
// This shows the user what page they are on, and the total number of pages
$paginationDisplay .= 'Page <strong>' . $pn . '</strong> of ' . $lastPage. ' ';
// If we are not on page 1 we can place the Back button
if ($pn != 1) {
$previous = $pn - 1;
$paginationDisplay .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $previous . '"> Back</a> ';
}
// Lay in the clickable numbers display here between the Back and Next links
$paginationDisplay .= '<span class="paginationNumbers">' . $centerPages . '</span>';
// If we are not on the very last page we can place the Next button
if ($pn != $lastPage) {
$nextPage = $pn + 1;
$paginationDisplay .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $nextPage . '"> Next</a> ';
}
}
///////////////////////////////////// END Pagination Display Setup ///////////////////////////////////////////////////////////////////////////
// Build the Output Section Here
$outputList = '';
while($row = mysql_fetch_array($sql2)){
$id = $row["id"];
$firstname = $row["firstname"];
$country = $row["country"];
$outputList .= '<h1>' . $firstname . '</h1><h2>' . $country . ' </h2><hr />';
} // close while loop
?>
<html>
<head>
<title>Simple Pagination</title>
</head>
<body>
<div style="margin-left:64px; margin-right:64px;">
<h2>Total Items: <?php echo $nr; ?></h2>
</div>
<div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
<div style="margin-left:64px; margin-right:64px;"><?php print "$outputList"; ?></div>
<div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
</body>
</html>
You can use a simple if
statement instead of continue. So instead of the way you have your code, you can try:
try(Stream<String> lines = Files.lines(path, StandardCharsets.ISO_8859_1)){
filteredLines = lines.filter(...).foreach(line -> {
...
if(!...) {
// Code you want to run
}
// Once the code runs, it will continue anyway
});
}
The predicate in the if statement will just be the opposite of the predicate in your if(pred) continue;
statement, so just use !
(logical not).
Alternative solution:
>>> from datetime import date
>>> (date(2012, 3, 1) - date(2012, 2, 1)).days
29
I know it is always preferred not to hardcode the sudo password in the script. However, for some reason, if you have no permission to modify /etc/sudoers
or change file owner, Pexpect is a feasible alternative.
Here is a Python function sudo_exec
for your reference:
import platform, os, logging
import subprocess, pexpect
log = logging.getLogger(__name__)
def sudo_exec(cmdline, passwd):
osname = platform.system()
if osname == 'Linux':
prompt = r'\[sudo\] password for %s: ' % os.environ['USER']
elif osname == 'Darwin':
prompt = 'Password:'
else:
assert False, osname
child = pexpect.spawn(cmdline)
idx = child.expect([prompt, pexpect.EOF], 3)
if idx == 0: # if prompted for the sudo password
log.debug('sudo password was asked.')
child.sendline(passwd)
child.expect(pexpect.EOF)
return child.before
The best approach from the response of Khemraj:
App class
class App : Application() {
companion object {
lateinit var instance: Application
lateinit var resourses: Resources
}
// MARK: - Lifecycle
override fun onCreate() {
super.onCreate()
instance = this
resourses = resources
}
}
Declaration in the manifest
<application
android:name=".App"
...>
</application>
Constants class
class Localizations {
companion object {
val info = App.resourses.getString(R.string.info)
}
}
Using
textView.text = Localizations.info
You need something along the lines of this:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(<uri_as_string>);
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile(<xpath_expression>);
Then you call expr.evaluate()
passing in the document defined in that code and the return type you are expecting, and cast the result to the object type of the result.
If you need help with a specific XPath expressions, you should probably ask it as separate questions (unless that was your question in the first place here - I understood your question to be how to use the API in Java).
Edit: (Response to comment): This XPath expression will get you the text of the first URL element under PowerBuilder:
/howto/topic[@name='PowerBuilder']/url/text()
This will get you the second:
/howto/topic[@name='PowerBuilder']/url[2]/text()
You get that with this code:
expr.evaluate(doc, XPathConstants.STRING);
If you don't know how many URLs are in a given node, then you should rather do something like this:
XPathExpression expr = xpath.compile("/howto/topic[@name='PowerBuilder']/url");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
And then loop over the NodeList.
For completeness, the answer is: you can't do that from within RStudio. @agstudy has it right - you need to install the newer version of R, then restart RStudio and it will automagically use the new version, as @Brandon noted.
It would be great if there was an update.R() function, analogous to the install.packages() function or the update.packages(function).
ok, I use a Mac, so I can only provide accurate details for the Mac - perhaps someone else can provide the accurate paths for windows/linux; I believe the process will be the same.
To ensure that your packages work with your shiny new version of R, you need to:
move the packages from the old R installation into the new version; on Mac OSX, this means moving all folders from here:
/Library/Frameworks/R.framework/Versions/2.15/Resources/library
to here:
/Library/Frameworks/R.framework/Versions/3.0/Resources/library
[where you'll replace "2.15" and "3.0" with whatever versions you're upgrading from and to. And only copy whatever packages aren't already in the destination directory. i.e. don't overwrite your new 'base' package with your old one - if you did, don't worry, we'll fix it in the next step anyway. If those paths don't work for you, try using installed.packages()
to find the proper pathnames.]
now you can update your packages by typing update.packages()
in your RStudio console, and answering 'y' to all of the prompts.
> update.packages(checkBuilt=TRUE)
class :
Version 7.3-7 installed in /Library/Frameworks/R.framework/Versions/3.0/Resources/library
Version 7.3-8 available at http://cran.rstudio.com
Update (y/N/c)? y
---etc---
finally, to reassure yourself that you have done everything, type these two commands in the RStudio console to see what you have got:
> version
> packageStatus()
Change your code to:
System.out.println("AM or PM?");
Scanner TimeOfDayQ = new Scanner(System.in);
TimeOfDayStringQ = TimeOfDayQ.next();
if(!TimeOfDayStringQ.equals("AM") && !TimeOfDayStringQ.equals("PM")) { // <--
System.out.println("Sorry, incorrect input.");
System.exit(1);
}
...
if(Hours == 13){
if (TimeOfDayStringQ.equals("AM")) {
TimeOfDayStringQ = "PM"; // <--
} else {
TimeOfDayStringQ = "AM"; // <--
}
Hours = 1;
}
}
You should check whether the distance from the center of the circle to the point is smaller than the radius
using Python
if (x-center_x)**2 + (y-center_y)**2 <= radius**2:
# inside circle
Similar to above, but I used (this was in CSHTML):
JavaScript:
var value = "Hello World!"<br>
$('.output').html(value);
CSHTML:
<div class="output"></div>
I use few methods for chaging flutter app lancher icon but only the manuall method is a bit easy and good. Because you will know how it work.
So to change flutter ios icon. First get copy of your icon 1024×1024 pixel and generate set of icons for android and ios using appicon.co generator. When you get zip file it work contact two folder ios and android open ios folder and copy folder and replace the one in your ios/runner directory.
For android copy all folder present in android folder and replace the ones present in the android/app/src/main/res/drawable here.
After replacing folder on both ios and android stop the app and re run and your icons will be changed.
I have solved a similar problem by first importing the text into an excel spreadsheet, then using the Substitute function to replace both the single and double quotes as required by SQL Server, eg. SUBSTITUTE(SUBSTITUTE(A1, "'", "''"), """", "\""")
In my case, I had many rows (each a line of data to be cleaned then inserted) and had the spreadsheet automatically generate insert queries for the text once the substitution had been done eg. ="INSERT INTO [dbo].[tablename] ([textcolumn]) VALUES ('" & SUBSTITUTE(SUBSTITUTE(A1, "'", "''"), """", "\""") & "')"
I hope that helps.
Use TO_TIMESTAMP function
TO_TIMESTAMP(date_string,'YYYY-MM-DD HH24:MI:SS')
Use the FIND_IN_SET function:
SELECT t.*
FROM YOUR_TABLE t
WHERE FIND_IN_SET(3, t.ids) > 0
Why not just have the parent wait for the child to close. This is more than you need.
// Execute child process
System.Diagnostics.Process proc =
System.Diagnostics.Process.Start("notepad.exe");
proc.WaitForExit();
You can setup _JAVA_OPTIONS
instead of JAVA_OPTS
. This should work without $_JAVA_OPTIONS
.
Not /gi but /g
var fname = "My Family File.jpg"
fname = fname.replace(/ /g,"_");
console.log(fname);
gives
"My_Family_File.jpg"
this.setState({
name:'value'
},() => {
console.log(this.state.name);
});
In My case, I've written below code in build.gradle
android {
// ...
aaptOptions.cruncherEnabled = false
aaptOptions.useNewCruncher = false
// ...
}
It's work for me!...
In my case the route in my router was:
Route::post('/new-order', 'Api\OrderController@initiateOrder')->name('newOrder');
and from the client app I was posting the request to:
https://my-domain/api/new-order/
So, because of the trailing slash I got a 405. Hope it helps someone
double d = 14.4;
if((d-(int)d)!=0)
System.out.println("decimal value is there");
else
System.out.println("decimal value is not there");
I have some general thoughts about the implementation of Task
:
using
.ConfigureAwait
was introduced in 4.5. Task
was introduced in 4.0. Task.ContinueWith
they do not b/c it was realised context switch is expensive and it is turned off by default.I have got a few posts on the subject but my take - in addition to Tugberk's nice answer - is that you should turn all APIs asynchronous and ideally flow the context . Since you are doing async, you can simply use continuations instead of waiting so no deadlock will be cause since no wait is done in the library and you keep the flowing so the context is preserved (such as HttpContext).
Problem is when a library exposes a synchronous API but uses another asynchronous API - hence you need to use Wait()
/Result
in your code.
In my case, the files were already copied, I found the easiest way to follow the steps in this guide: https://www.ryadel.com/en/exporting-importing-app-pools-and-websites-configuration-between-multiple-iis-instances/
I exported AppPools/Websites, copied the xml files to the destination server and Imported AppPools then Websites. Worked very well. This is also another excellent option for this question.
It means that the callback function you passed to this.dataStore.data.find
should return a boolean and have 3 parameters, two of which can be optional:
However, your callback function does not return anything (returns void). You should pass a callback function with the correct return value:
this.dataStore.data.find((element, index, obj) => {
// ...
return true; // or false
});
or:
this.dataStore.data.find(element => {
// ...
return true; // or false
});
Reason why it's this way: the function you pass to the find
method is called a predicate. The predicate here defines a boolean outcome based on conditions defined in the function itself, so that the find
method can determine which value to find.
In practice, this means that the predicate is called for each item in data
, and the first item in data
for which your predicate returns true
is the value returned by find
.
Sadly git is so unrelable :( I just lost 2 days of work :(
It's best to manual backup anything before doing commit. I just did "git commit" and git just destroy all my changes without saying anything.
I learned my lesson - next time backup first and only then commit. Never trust git for anything.
Use chars:
Dim firstChar As char;
firstChar = s.Chars(0);
http://vb.net-informations.com/string/vb.net_String_Chars.htm
You can install from nuget as the the below image:
Or, run the below command line on Package Manager Console:
Install-Package Microsoft.AspNet.WebApi
It will come in the url so you can get it by two ways. Fist one
<td><?php echo anchor('textarea/delete_row', 'DELETE', 'id="$row->id"'); ?></td>
$id = $this->input->get('id');
2nd one.
$id = $this->uri->segment(3);
But in the second method you have to count the no. of segments in the url that on which no. your id come. 2,3,4 etc. then you have to pass. then in the ();
select @EmpID = ID from dbo.Employee
Or
set @EmpID =(select id from dbo.Employee)
Note that the select query might return more than one value or rows. so you can write a select query that must return one row.
If you would like to add more columns to one variable(MS SQL), there is an option to use table defined variable
DECLARE @sampleTable TABLE(column1 type1)
INSERT INTO @sampleTable
SELECT columnsNumberEqualInsampleTable FROM .. WHERE ..
As table type variable do not exist in Oracle and others, you would have to define it:
DECLARE TYPE type_name IS TABLE OF (column_type | variable%TYPE | table.column%TYPE [NOT NULL] INDEX BY BINARY INTEGER;
-- Then to declare a TABLE variable of this type: variable_name type_name;
-- Assigning values to a TABLE variable: variable_name(n).field_name := 'some text'
;
-- Where 'n' is the index value
I just tested this and it works fine
var d = new Date(1441121836000);
The data object has a constructor which takes milliseconds as an argument.
Use the appropriate methods in Scripting.FileSystemObject. Then your code will be more portable to VBScript and VB.net. To get you started, you'll need to include:
Dim fso As Object
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
Then you could use
Call fso.CopyFile(source, destination[, overwrite] )
where source and destination are the full names (including paths) of the file.
See https://docs.microsoft.com/en-us/office/vba/Language/Reference/user-interface-help/copyfile-method
Very edge case, but I had to use a program that worked correctly only when I specified
StartInfo = {..., RedirectStandardOutput = true}
Not specifying it would result in an error. There was not even the need to read the output afterward.
PHP has a built in function called bool chmod(string $filename, int $mode )
private function writeFileContent($file, $content){
$fp = fopen($file, 'w');
fwrite($fp, $content);
fclose($fp);
chmod($file, 0777); //changed to add the zero
return true;
}
This explains the whole thing:
The HTTP Content-Security-Policy (CSP) upgrade-insecure-requests directive instructs user agents to treat all of a site's insecure URLs (those served over HTTP) as though they have been replaced with secure URLs (those served over HTTPS). This directive is intended for web sites with large numbers of insecure legacy URLs that need to be rewritten.
The upgrade-insecure-requests directive is evaluated before block-all-mixed-content and if it is set, the latter is effectively a no-op. It is recommended to set one directive or the other, but not both.
The upgrade-insecure-requests directive will not ensure that users visiting your site via links on third-party sites will be upgraded to HTTPS for the top-level navigation and thus does not replace the Strict-Transport-Security (HSTS) header, which should still be set with an appropriate max-age to ensure that users are not subject to SSL stripping attacks.
What's wrong with self.left = None
?
I think, the differences between ArrayList
and List<T>
are:
List<T>
, where T is value-type is faster than ArrayList
. This is
because List<T>
avoids boxing/unboxing (where T is value-type).ArrayList
used just for backward
compatibility. (is not a real difference, but i think it is
important note).ArrayList
then List<T>
ArrayList
has IsSynchronized
property. So, It is easy
to create and use syncronised ArrayList
. I didin't found IsSynchronized
property for List<T>
. Also Keep in mind this type of synchronization is relatively inefficient, msdn):
var arraylist = new ArrayList();
var arrayListSyncronized = ArrayList.Synchronized(arraylist
Console.WriteLine($"syncronized {arraylist.IsSynchronized}");
Console.WriteLine($"syncronized {arrayListSyncronized.IsSynchronized}");
var list = new List<object>();
var listSyncronized = ArrayList.Synchronized(list);
Console.WriteLine($"syncronized {list.IsSynchronized}");//error, no such prop
Console.WriteLine($"syncronized {list.IsSynchronized}");//error, no such prop
ArrayList
has ArrayList.SyncRoot
property which can be used for syncronisation (msdn). List<T>
hasn't SyncRoot
property, so in
the following construction you need to use some object if you use List<T>
:
ArrayList myCollection = new ArrayList();
lock(myCollection.SyncRoot) // ofcourse you can use another object for this goal
{
foreach (object item in myCollection)
{
// ...
}
}
To complete Zachary's answer, here is a workaround for the "extend in overrides" limitation of eslint config :
overrides: [
Object.assign(
{
files: [ '**/*.test.js' ],
env: { jest: true },
plugins: [ 'jest' ],
},
require('eslint-plugin-jest').configs.recommended
)
]
From https://github.com/eslint/eslint/issues/8813#issuecomment-320448724
The usual way to use assertRaises
is to call a function:
self.assertRaises(TypeError, test_function, args)
to test that the function call test_function(args) raises a TypeError.
The problem with self.testListNone[:1]
is that Python evaluates the expression immediately, before the assertRaises
method is called. The whole reason why test_function
and args
is passed as separate arguments to self.assertRaises
is to allow assertRaises
to call test_function(args)
from within a try...except
block, allowing assertRaises
to catch the exception.
Since you've defined self.testListNone = None
, and you need a function to call, you might use operator.itemgetter like this:
import operator
self.assertRaises(TypeError, operator.itemgetter, (self.testListNone,slice(None,1)))
since
operator.itemgetter(self.testListNone,slice(None,1))
is a long-winded way of saying self.testListNone[:1]
, but which separates the function (operator.itemgetter
) from the arguments.
This error can also happen if the variable you are comparing has hidden characters that are not numbers/digits.
For example, if you are retrieving an integer from a third-party script, you must ensure that the returned string does not contain hidden characters, like "\n"
or "\r"
.
For example:
#!/bin/bash
# Simulate an invalid number string returned
# from a script, which is "1234\n"
a='1234
'
if [ "$a" -gt 1233 ] ; then
echo "number is bigger"
else
echo "number is smaller"
fi
This will result in a script error : integer expression expected
because $a
contains a non-digit newline character "\n"
. You have to remove this character using the instructions here: How to remove carriage return from a string in Bash
So use something like this:
#!/bin/bash
# Simulate an invalid number string returned
# from a script, which is "1234\n"
a='1234
'
# Remove all new line, carriage return, tab characters
# from the string, to allow integer comparison
a="${a//[$'\t\r\n ']}"
if [ "$a" -gt 1233 ] ; then
echo "number is bigger"
else
echo "number is smaller"
fi
You can also use set -xv
to debug your bash script and reveal these hidden characters. See https://www.linuxquestions.org/questions/linux-newbie-8/bash-script-error-integer-expression-expected-934465/
This is the most readily available, handy and useful way to do
freopen("dir","r",stdin);
The web.xml
file is the deployment descriptor for a Servlet-based Java web application (which most Java web apps are). Among other things, it declares which Servlets exist and which URLs they handle.
The part you cite defines a Servlet Filter. Servlet filters can do all kinds of preprocessing on requests. Your specific example is a filter had the Wicket framework uses as its entry point for all requests because filters are in some way more powerful than Servlets.
It all depends on what is your definition of 'clear'. One of the valid ones certainly is:
slice = slice[:0]
But there's a catch. If slice elements are of type T:
var slice []T
then enforcing len(slice)
to be zero, by the above "trick", doesn't make any element of
slice[:cap(slice)]
eligible for garbage collection. This might be the optimal approach in some scenarios. But it might also be a cause of "memory leaks" - memory not used, but potentially reachable (after re-slicing of 'slice') and thus not garbage "collectable".
Actually, to read arrow keys one need to read its scan code. Following are the scan code generated by arrow keys press (not key release)
When num Lock is off
When Num Lock is on these keys get preceded with E0 2A
Byte 50 is 80 DOWN
user_var=getch();
if(user_var == -32)
{
user_var=getch();
switch(user_var)
{
case 72:
cur_sel--;
if (cur_sel==0)
cur_sel=4;
break;
case 80:
cur_sel++;
if(cur_sel==5)
cur_sel=1;
break;
}
}
In the above code I have assumed programmer wants to move 4 lines only.
the answer is already exist above, but I would like to add some thing.. you can specify the following in your @font-face
@font-face {
font-family: 'Name You Font';
src: url('assets/font/xxyourfontxxx.eot');
src: local('Cera Pro Medium'), local('CeraPro-Medium'),
url('assets/font/xxyourfontxxx.eot?#iefix') format('embedded-opentype'),
url('assets/font/xxyourfontxxx.woff') format('woff'),
url('assets/font/xxyourfontxxx.ttf') format('truetype');
font-weight: 500;
font-style: normal;
}
So you can just indicate your fontfamily name that you already choosed
NOTE: the font-weight and font-style depend on your .woff .ttf ... files
give this a try,
insert into tableName (ImageColumn)
SELECT BulkColumn
FROM Openrowset( Bulk 'image..Path..here', Single_Blob) as img
INSERTING
REFRESHING THE TABLE
Here you get JSONObject so change this line:
JSONArray jsonArray = new JSONArray(readlocationFeed);
with following:
JSONObject jsnobject = new JSONObject(readlocationFeed);
and after
JSONArray jsonArray = jsnobject.getJSONArray("locations");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
}
Really, the only use of typedef that carries over to Javaland is aliasing- that is, giving the same class multiple names. That is, you've got a class "A" and you want "B" to refer to the same thing. In C++, you'd be doing "typedef B A;"
Unfortunately, they just don't support it. However, if you control all the types involved you CAN pull a nasty hack at the library level- you either extend B from A or have B implement A.
This is only a warning: your code still works, but probably won't work in the future as the method is deprecated. See the relevant source of Chromium and corresponding patch.
This has already been recognised and fixed in jQuery 1.11 (see here and here).
This can also be done in the GUI. Here's an example adding a multi-column unique constraint to an existing table.
Click OK in each window and you're done.
My env is OSX Yosemite. Had the same issue .... solved by adding the following
1) edit and add the following line to .bash_profile file.
[[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm"
2) Restart terminal and try RVM command again
Also, if you are using LINQ, you can apparently do something like myList.Select(methodGroup)
.
So, for example, I have:
private string DoSomethingToMyString(string input)
{
// blah
}
Instead of explicitly stating the variable to be used like this:
public List<string> GetStringStuff()
{
return something.getStringsFromSomewhere.Select(str => DoSomethingToMyString(str));
}
I can just omit the name of the var:
public List<string> GetStringStuff()
{
return something.getStringsFromSomewhere.Select(DoSomethingToMyString);
}
Try setting a custom CultureInfo for CurrentCulture and CurrentUICulture.
Globalization.CultureInfo customCulture = new Globalization.CultureInfo("en-US", true);
customCulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd h:mm tt";
System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = customCulture;
DateTime newDate = System.Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd h:mm tt"));
I haven't tested your code, just tried to help you understand how it operates in comment;
WITH
cteReports (EmpID, FirstName, LastName, MgrID, EmpLevel)
AS
(
-->>>>>>>>>>Block 1>>>>>>>>>>>>>>>>>
-- In a rCTE, this block is called an [Anchor]
-- The query finds all root nodes as described by WHERE ManagerID IS NULL
SELECT EmployeeID, FirstName, LastName, ManagerID, 1
FROM Employees
WHERE ManagerID IS NULL
-->>>>>>>>>>Block 1>>>>>>>>>>>>>>>>>
UNION ALL
-->>>>>>>>>>Block 2>>>>>>>>>>>>>>>>>
-- This is the recursive expression of the rCTE
-- On the first "execution" it will query data in [Employees],
-- relative to the [Anchor] above.
-- This will produce a resultset, we will call it R{1} and it is JOINed to [Employees]
-- as defined by the hierarchy
-- Subsequent "executions" of this block will reference R{n-1}
SELECT e.EmployeeID, e.FirstName, e.LastName, e.ManagerID,
r.EmpLevel + 1
FROM Employees e
INNER JOIN cteReports r
ON e.ManagerID = r.EmpID
-->>>>>>>>>>Block 2>>>>>>>>>>>>>>>>>
)
SELECT
FirstName + ' ' + LastName AS FullName,
EmpLevel,
(SELECT FirstName + ' ' + LastName FROM Employees
WHERE EmployeeID = cteReports.MgrID) AS Manager
FROM cteReports
ORDER BY EmpLevel, MgrID
The simplest example of a recursive CTE
I can think of to illustrate its operation is;
;WITH Numbers AS
(
SELECT n = 1
UNION ALL
SELECT n + 1
FROM Numbers
WHERE n+1 <= 10
)
SELECT n
FROM Numbers
Q 1) how value of N is getting incremented. if value is assign to N every time then N value can be incremented but only first time N value was initialize.
A1:
In this case, N
is not a variable. N
is an alias. It is the equivalent of SELECT 1 AS N
. It is a syntax of personal preference. There are 2 main methods of aliasing columns in a CTE
in T-SQL
. I've included the analog of a simple CTE
in Excel
to try and illustrate in a more familiar way what is happening.
-- Outside
;WITH CTE (MyColName) AS
(
SELECT 1
)
-- Inside
;WITH CTE AS
(
SELECT 1 AS MyColName
-- Or
SELECT MyColName = 1
-- Etc...
)
Q 2) now here about CTE and recursion of employee relation the moment i add two manager and add few more employee under second manager then problem start. i want to display first manager detail and in the next rows only those employee details will come those who are subordinate of that manager
A2:
Does this code answer your question?
--------------------------------------------
-- Synthesise table with non-recursive CTE
--------------------------------------------
;WITH Employee (ID, Name, MgrID) AS
(
SELECT 1, 'Keith', NULL UNION ALL
SELECT 2, 'Josh', 1 UNION ALL
SELECT 3, 'Robin', 1 UNION ALL
SELECT 4, 'Raja', 2 UNION ALL
SELECT 5, 'Tridip', NULL UNION ALL
SELECT 6, 'Arijit', 5 UNION ALL
SELECT 7, 'Amit', 5 UNION ALL
SELECT 8, 'Dev', 6
)
--------------------------------------------
-- Recursive CTE - Chained to the above CTE
--------------------------------------------
,Hierarchy AS
(
-- Anchor
SELECT ID
,Name
,MgrID
,nLevel = 1
,Family = ROW_NUMBER() OVER (ORDER BY Name)
FROM Employee
WHERE MgrID IS NULL
UNION ALL
-- Recursive query
SELECT E.ID
,E.Name
,E.MgrID
,H.nLevel+1
,Family
FROM Employee E
JOIN Hierarchy H ON E.MgrID = H.ID
)
SELECT *
FROM Hierarchy
ORDER BY Family, nLevel
SELECT ID,space(nLevel+
(CASE WHEN nLevel > 1 THEN nLevel ELSE 0 END)
)+Name
FROM Hierarchy
ORDER BY Family, nLevel
One way to do it is to set the image you want to display as a background in a container (td, div, span etc) and then adjust background-position to get the sprite you want.
It will store value of number of characters printed so far in that printf()
function.
Example:
int a;
printf("Hello World %n \n", &a);
printf("Characters printed so far = %d",a);
The output of this program will be
Hello World
Characters printed so far = 12
I vote for Karthik T's answer. you don't need to open a terminal to run commands.
For example,
// file: RunShellCommandFromJava.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class RunShellCommandFromJava {
public static void main(String[] args) {
String command = "ping -c 3 www.google.com";
Process proc = Runtime.getRuntime().exec(command);
// Read the output
BufferedReader reader =
new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
while((line = reader.readLine()) != null) {
System.out.print(line + "\n");
}
proc.waitFor();
}
}
The output:
$ javac RunShellCommandFromJava.java
$ java RunShellCommandFromJava
PING http://google.com (123.125.81.12): 56 data bytes
64 bytes from 123.125.81.12: icmp_seq=0 ttl=59 time=108.771 ms
64 bytes from 123.125.81.12: icmp_seq=1 ttl=59 time=119.601 ms
64 bytes from 123.125.81.12: icmp_seq=2 ttl=59 time=11.004 ms
--- http://google.com ping statistics ---
3 packets transmitted, 3 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 11.004/79.792/119.601/48.841 ms
You can change the color with tinting the background
<EditText
android:backgroundTint="@color/red"/>
The server might require some kind of encryption and secure authentication.
see http://swiftmailer.org/docs/sending.html#encrypted-smtp
A better pyramid can be printed this way:
The Pattern is $ $$$ $$$$$ $$$$$$$ $$$$$$$$$ $$$$$$$$$$$
public static void main(String agrs[]) {
System.out.println("The Pattern is");
int size = 11; //use only odd numbers here
for (int i = 1; i <= size; i=i+2) {
int spaceCount = (size - i)/2;
for(int j = 0; j< size; j++) {
if(j < spaceCount || j >= (size - spaceCount)) {
System.out.print(" ");
} else {
System.out.print("$");
}
}
System.out.println();
}
}
By default, *.sh
files are opened in a text editor (Xcode or TextEdit). To create a shell script that will execute in Terminal when you open it, name it with the “command” extension, e.g., file.command
. By default, these are sent to Terminal, which will execute the file as a shell script.
You will also need to ensure the file is executable, e.g.:
chmod +x file.command
Without this, Terminal will refuse to execute it.
Note that the script does not have to begin with a #!
prefix in this specific scenario, because Terminal specifically arranges to execute it with your default shell. (Of course, you can add a #!
line if you want to customize which shell is used or if you want to ensure that you can execute it from the command line while using a different shell.)
Also note that Terminal executes the shell script without changing the working directory. You’ll need to begin your script with a cd
command if you actually need it to run with a particular working directory.
built-in types in Python have built in names:
>>> s = "hallo"
>>> type(s) is str
True
>>> s = {}
>>> type(s) is dict
True
btw note the is operator. However, type checking (if you want to call it that) is usually done by wrapping a type-specific test in a try-except clause, as it's not so much the type of the variable that's important, but whether you can do a certain something with it or not.
If you start tinkering with VirtualBox network settings, watch out for this: you might make new network adapters (eth1, eth2), yet have your /etc/network/interfaces
still configured for eth0.
Diagnose:
ethtool -i eth0
Cannot get driver information: no such device
Find your interfaces:
ls /sys/class/net
eth1 eth2 lo
Fix it:
Edit /etc/networking/interfaces
and replace eth0 with the appropriate interface name (e.g eth1, eth2, etc.)
:%s/eth0/eth2/g
Strangely, so many answers, and all of them are using surrogates like JS and keyboard shortcuts instead of just using a selenium feature:
def newTab(driver, url="about:blank"):
wnd = driver.execute(selenium.webdriver.common.action_chains.Command.NEW_WINDOW)
handle = wnd["value"]["handle"]
driver.switch_to.window(handle)
driver.get(url) # changes the handle
return driver.current_window_handle
Another excellent plugin: http://documentcloud.github.com/visualsearch/
Here's the method that I've always used:
$fqdn= $(ping localhost -n 1)[1].split(" ")[1]
From the DOCS
Formats a number as text. Group sizing and separator and other locale-specific configurations are based on the active locale.
SYNTAX:
number_expression | number[:digitInfo[:locale]]
where expression
is a number:
digitInfo
is a string which has a following format:
{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
If you want to show just numbers without characters, put this line of code inside your XML file android:inputType="number"
. The output:
If you want to show a number keyboard that also shows characters, put android:inputType="phone"
on your XML. The output (with characters):
And if you want to show a number keyboard that masks your input just like a password, put android:inputType="numberpassword"
. The output:
I'm really sorry if I only post the links of the screenshot, I want to do research on how to do really post images here but it might consume my time so here it is. I hope my post can help other people. Yes, my answer is duplicate with other answers posted here but to save other people's time that they might need to run their code before seeing the output, my post might save you some time.
For Xcode Version 8.2 (8C38), you can remove the projects completely (project name in Xcode, programs, data, etc.) one by one by doing the following: [Note: the instructions are not for just remove the project names from the Welcome Window]
Launch the Xocde and wait until the Welcome window is displayed. The projects will be shown on the right hand side (see below) Xcode Welcome Window
Right click the project you want to remove completely and a pop window [Show in Folder] jumps out; selec it to find out where is the project in the [Finder] (see below) Find the project folder
Right click the project folder in the Finder to find it’s path through [Get Info]; use path in the Info window to go to the parent folder, and go to there[Locate the project folder path] (see below)
Right click the Project Folder (e.g. DemoProject01) and Porject file (DemoProject01.xcodeproj) and select [Move to Trash] ; you will see that (a) the folder in finder is removed AND (b) the Project in the Xcode Welcome Window’s Project List is removed.
Based on the @AndrewCox 's answer with some minor improvements:
from http.client import HTTPSConnection
from base64 import b64encode
client = HTTPSConnection("www.google.com")
user = "user_name"
password = "password"
headers = {
"Authorization": "Basic {}".format(
b64encode(bytes(f"{user}:{password}", "utf-8")).decode("ascii")
)
}
client.request('GET', '/', headers=headers)
res = client.getresponse()
data = res.read()
Note, you should set encoding if you use bytes
function instead of b""
.
updating web.config with the following assembly binding resolved the issue
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed"
culture="neutral" />
<bindingRedirect oldVersion="4.5.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
The first time I read this it was very helpful to me. Thank you.
Since then I gained some insight about the downside of creating indexes:
if you write into a table (UPDATE
or INSERT
) with one index, you have actually two writing operations in the file system. One for the table data and another one for the index data (and the resorting of it (and - if clustered - the resorting of the table data)). If table and index are located on the same hard disk this costs more time. Thus a table without an index (a heap) , would allow for quicker write operations. (if you had two indexes you would end up with three write operations, and so on)
However, defining two different locations on two different hard disks for index data and table data can decrease/eliminate the problem of increased cost of time. This requires definition of additional file groups with according files on the desired hard disks and definition of table/index location as desired.
Another problem with indexes is their fragmentation over time as data is inserted. REORGANIZE
helps, you must write routines to have it done.
In certain scenarios a heap is more helpful than a table with indexes,
e.g:- If you have lots of rivalling writes but only one nightly read outside business hours for reporting.
Also, a differentiation between clustered and non-clustered indexes is rather important.
Helped me:- What do Clustered and Non clustered index actually mean?
I think what you want to do is this:
$(this).children('img').eq(0);
this will give you a jquery object containing the first img element, whereas
$(this).children('img')[0];
will give you the img element itself.
wp_register_script('custom-js',WP_PLUGIN_URL.'/PLUGIN_NAME/js/custom.js',array(),NULL,true);
wp_enqueue_script('custom-js');
$wnm_custom = array( 'template_url' => get_bloginfo('template_url') );
wp_localize_script( 'custom-js', 'wnm_custom', $wnm_custom );
and in custom.js
alert(wnm_custom.template_url);
width
and height
are used when going the css route.
<!DOCTYPE html>
<html>
<head>
<title>Setting Width and Height on Textareas</title>
<style>
.comments { width: 300px; height: 75px }
</style>
</head>
<body>
<textarea class="comments"></textarea>
</body>
</html>
Since Java 8, there are lambda and method references:
For example, if you want a functional interface A -> B
such as:
import java.util.function.Function;
public MyClass {
public static String applyFunction(String name, Function<String,String> function){
return function.apply(name);
}
}
then you can call it like so
MyClass.applyFunction("42", str -> "the answer is: " + str);
// returns "the answer is: 42"
Also you can pass class method. Say you have:
@Value // lombok
public class PrefixAppender {
private String prefix;
public String addPrefix(String suffix){
return prefix +":"+suffix;
}
}
Then you can do:
PrefixAppender prefixAppender= new PrefixAppender("prefix");
MyClass.applyFunction("some text", prefixAppender::addPrefix);
// returns "prefix:some text"
Note:
Here I used the functional interface Function<A,B>
, but there are many others in the package java.util.function
. Most notable ones are
Supplier
: void -> A
Consumer
: A -> void
BiConsumer
: (A,B) -> void
Function
: A -> B
BiFunction
: (A,B) -> C
and many others that specialize on some of the input/output type. Then, if it doesn't provide the one you need, you can create your own functional interface like so:
@FunctionalInterface
interface Function3<In1, In2, In3, Out> { // (In1,In2,In3) -> Out
public Out apply(In1 in1, In2 in2, In3 in3);
}
Example of use:
String computeAnswer(Function3<String, Integer, Integer, String> f){
return f.apply("6x9=", 6, 9);
}
computeAnswer((question, a, b) -> question + "42");
// "6*9=42"
And you can also do that with thrown exception:
@FunctionalInterface
interface FallibleFunction<In, Out, Ex extends Exception> {
Out get(In input) throws Ex;
}
public <Ex extends IOException> String yo(FallibleFunction<Integer, String, Ex> f) throws Ex {
return f.get(42);
}
(I was going to leave this as a comment on @jldupont's answer, but I don't have enough reputation.)
I've seen answers like @jldupont's answer in other places as well. FWIW, I think it's important to note that this:
except Exception as e:
print(e)
will print the error output to sys.stdout
by default. A more appropriate approach to error handling in general would be:
except Exception as e:
print(e, file=sys.stderr)
(Note that you have to import sys
for this to work.) This way, the error is printed to STDERR
instead of STDOUT
, which allows for the proper output parsing/redirection/etc. I understand that the question was strictly about 'printing an error', but it seems important to point out the best practice here rather than leave out this detail that could lead to non-standard code for anyone who doesn't eventually learn better.
I haven't used the traceback
module as in Cat Plus Plus's answer, and maybe that's the best way, but I thought I'd throw this out there.
here is the full program to make a POST rest call using spring's RestTemplate.
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import com.ituple.common.dto.ServiceResponse;
public class PostRequestMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
Map map = new HashMap<String, String>();
map.put("Content-Type", "application/json");
headers.setAll(map);
Map req_payload = new HashMap();
req_payload.put("name", "piyush");
HttpEntity<?> request = new HttpEntity<>(req_payload, headers);
String url = "http://localhost:8080/xxx/xxx/";
ResponseEntity<?> response = new RestTemplate().postForEntity(url, request, String.class);
ServiceResponse entityResponse = (ServiceResponse) response.getBody();
System.out.println(entityResponse.getData());
}
}
Log4net is saving into your project folder. Something like: \SolutionFolder\ProjectFolder\bin\SolutionConfiguration\logs\log-file.txt
.
Where:
Hope this helps!
Here is the example for Swift 3:
var stringToReplace = "This my string"
if let range = stringToReplace.range(of: "my") {
stringToReplace?.replaceSubrange(range, with: "your")
}
The same trouble with same device has been here.
So, it's Xiaomi trouble, and here is a solution for this problem:
Go to the "Security" application and tap "Options" at top right corner
Scroll down to "Feature Settings" group, and look for "Permissions"
At there switch off "Install via USB" option, which manages installation of the apps via USB and doesn't allow it.
On Latest Redmi Device
Settings > Additional Settings > Developer Options > Developer options: Check the Install via USB option.
Good luck!
The formatter option '%x' % seems to work in assignment statements as well for me. (Assuming Python 3.0 and later)
Example
a = int('0x100', 16)
print(a) #256
print('%x' % a) #100
b = a
print(b) #256
c = '%x' % a
print(c) #100
Despite some success with the /dev/null approach in bash. When I pushed the solution to cron it failed. Checking the size of a returned command worked perfectly though. The ampersrand allows bash to exit.
#!/bin/bash
SERVICE=/path/to/my/service
result=$(ps ax|grep -v grep|grep $SERVICE)
echo ${#result}
if ${#result}> 0
then
echo " Working!"
else
echo "Not Working.....Restarting"
/usr/bin/xvfb-run -a /opt/python27/bin/python2.7 SERVICE &
fi
Although this question is raised over 8 years ago with various solutions and answers, the easiest solution that can be easily updated to increase the scale by just inserting a name in the array without code modification; and also using very short code is the function below.
This solution is for the English reading of numbers (not the South-Asian System) and uses the standard US English (American way) of writing large numbers. i.e. it does not use the UK System (the UK system uses the word "and" like: "three hundred and twenty-two thousand").
Test cases are provided and also an input field.
Remember, it is "Unsigned Integers" that we are converting to words.
You can increase the scale[] array
beyond Sextillion.
As the function is short, you can use it as an internal function in, say, currency conversion where decimal numbers are used and call it twice for the whole part and the fractional part.
Hope it is useful.
/********************************************************
* @function : integerToWords()
* @purpose : Converts Unsigned Integers to Words
* Using String Triplet Array.
* @version : 1.05
* @author : Mohsen Alyafei
* @date : 15 January 2021
* @param : {number} [integer numeric or string]
* @returns : {string} The wordified number string
********************************************************/
const Ones = ["","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten",
"Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"],
Tens = ["","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety","Hundred"],
Scale = ["","Thousand","Million","Billion","Trillion","Quadrillion","Quintillion","Sextillion"];
//==================================
const integerToWords = (n = 0) => {
if (n == 0) return "Zero"; // check for zero
n = ("0".repeat(2*(n+="").length % 3) + n).match(/.{3}/g); // create triplets array
if (n.length > Scale.length) return "Too Large"; // check if larger than scale array
let out= ""; return n.forEach((Triplet,pos) => { // loop into array for each triplet
if (+Triplet) { out+=' ' +(+Triplet[0] ? Ones[+Triplet[0]]+' '+ Tens[10] : "") +
' ' + (+Triplet.substr(1)< 20 ? Ones[+Triplet.substr(1)] :
Tens[+Triplet[1]] + (+Triplet[2] ? "-" : "") + Ones[+Triplet[2]]) +
' ' + Scale[n.length-pos-1]; }
}),out.replace(/\s+/g,' ').trim();}; // lazy job using trim()
//==================================
//=========================================
// Test Cases
//=========================================
var r=0; // test tracker
r |= test(0,"Zero");
r |= test(5,"Five");
r |= test(10,"Ten");
r |= test(19,"Nineteen");
r |= test(33,"Thirty-Three");
r |= test(100,"One Hundred");
r |= test(111,"One Hundred Eleven");
r |= test(890,"Eight Hundred Ninety");
r |= test(1234,"One Thousand Two Hundred Thirty-Four");
r |= test(12345,"Twelve Thousand Three Hundred Forty-Five");
r |= test(123456,"One Hundred Twenty-Three Thousand Four Hundred Fifty-Six");
r |= test(1234567,"One Million Two Hundred Thirty-Four Thousand Five Hundred Sixty-Seven");
r |= test(12345678,"Twelve Million Three Hundred Forty-Five Thousand Six Hundred Seventy-Eight");
r |= test(123456789,"One Hundred Twenty-Three Million Four Hundred Fifty-Six Thousand Seven Hundred Eighty-Nine");
r |= test(1234567890,"One Billion Two Hundred Thirty-Four Million Five Hundred Sixty-Seven Thousand Eight Hundred Ninety");
r |= test(1001,"One Thousand One");
r |= test(10001,"Ten Thousand One");
r |= test(100001,"One Hundred Thousand One");
r |= test(1000001,"One Million One");
r |= test(10000001,"Ten Million One");
r |= test(100000001,"One Hundred Million One");
r |= test(12012,"Twelve Thousand Twelve");
r |= test(120012,"One Hundred Twenty Thousand Twelve");
r |= test(1200012,"One Million Two Hundred Thousand Twelve");
r |= test(12000012,"Twelve Million Twelve");
r |= test(120000012,"One Hundred Twenty Million Twelve");
r |= test(75075,"Seventy-Five Thousand Seventy-Five");
r |= test(750075,"Seven Hundred Fifty Thousand Seventy-Five");
r |= test(7500075,"Seven Million Five Hundred Thousand Seventy-Five");
r |= test(75000075,"Seventy-Five Million Seventy-Five");
r |= test(750000075,"Seven Hundred Fifty Million Seventy-Five");
r |= test(1000,"One Thousand");
r |= test(1000000,"One Million");
r |= test(1000000000,"One Billion");
r |= test(1000000000000,"One Trillion");
r |= test("1000000000000000","One Quadrillion");
r |= test("1000000000000000000","One Quintillion");
r |= test("1000000100100100100","One Quintillion One Hundred Billion One Hundred Million One Hundred Thousand One Hundred");
if (r==0) console.log("All Tests Passed.");
//=====================================
// Tester Function
//=====================================
function test(n,should) {
let result = integerToWords(n);
if (result !== should) {console.log(`${n} Output : ${result}\n${n} Should be: ${should}`);return 1;}
}
_x000D_
<input type="text" name="number" placeholder="Please enter an Integer Number" onkeyup="word.innerHTML=integerToWords(this.value)" />
<div id="word"></div>
_x000D_
function getStringReminder(str, substr, occ) {
let index = str.indexOf(substr);
let preindex = '';
let i = 1;
while (index !== -1) {
preIndex = index;
if (occ == i) {
break;
}
index = str.indexOf(substr, index + 1)
i++;
}
return preIndex;
}
console.log(getStringReminder('bcdefgbcdbcd', 'bcd', 3));
I used this function htmlspecialchars for alt attributes in images
Try this:
df = spark.createDataFrame([('2018-07-27 10:30:00',)], ['Date_col'])
df.select(from_unixtime(unix_timestamp(df.Date_col, 'yyyy-MM-dd HH:mm:ss')).alias('dt_col'))
df.show()
+-------------------+
| Date_col|
+-------------------+
|2018-07-27 10:30:00|
+-------------------+
Personally, I'd append the element to the form instead of hacking the serialized data, e.g.
moredata = 'your custom data here';
// do what you like with the input
$input = $('<input type="text" name="moredata"/>').val(morevalue);
// append to the form
$('#myForm').append($input);
// then..
data: $('#myForm').serialize()
That way, you don't have to worry about ?
or &
You can do it like so:
var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId('4edd40c86762e0fb12000003');
There are two cases:
const reference --good idea, sometimes, especially for heavy objects or proxy classes, compiler optimization
non-const reference --bad idea, sometimes, breaks encapsulations
Both share same issue -- can potentially point to destroyed object...
I would recommend using smart pointers for many situations where you require to return a reference/pointer.
Also, note the following:
There is a formal rule - the C++ Standard (section 13.3.3.1.4 if you are interested) states that a temporary can only be bound to a const reference - if you try to use a non-const reference the compiler must flag this as an error.
If you are sending anything other than simple strings I would recommend using a POST with an appropriate request body, or passing the entire list as an appropriately encoded JSON string. However, with simple strings you just need to append each value to the request URL appropriately and Jersey will deserialize it for you. So given the following example endpoint:
@Path("/service/echo") public class MyServiceImpl {
public MyServiceImpl() {
super();
}
@GET
@Path("/withlist")
@Produces(MediaType.TEXT_PLAIN)
public Response echoInputList(@QueryParam("list") final List<String> inputList) {
return Response.ok(inputList).build();
}
}
Your client would send a request corresponding to:
GET http://example.com/services/echo?list=Hello&list=Stay&list=Goodbye
Which would result in inputList
being deserialized to contain the values 'Hello', 'Stay' and 'Goodbye'
You can change the port of Apache:
NameVirtualHost *:80 here
VirtualHost *:80 and here (two times)
To enter your web page, type: http://localhost:81/index.html
Open your page in Firefox and get the HTTPFox addon. It will tell you all that you need.
Found this on archivist.incuito:
http://archivist.incutio.com/viewlist/css-discuss/76444
When you first request a page, your browser sends a GET request to the server, which returns the HTML to the browser. The browser then starts parsing the page (possibly before all of it has been returned).
When it finds a reference to an external entity such as a CSS file, an image file, a script file, a Flash file, or anything else external to the page (either on the same server/domain or not), it prepares to make a further GET request for that resource.
However the HTTP standard specifies that the browser should not make more than two concurrent requests to the same domain. So it puts each request to a particular domain in a queue, and as each entity is returned it starts the next one in the queue for that domain.
The time it takes for an entity to be returned depends on its size, the load the server is currently experiencing, and the activity of every single machine between the machine running the browser and the server. The list of these machines can in principle be different for every request, to the extent that one image might travel from the USA to me in the UK over the Atlantic, while another from the same server comes out via the Pacific, Asia and Europe, which takes longer. So you might get a sequence like the following, where a page has (in this order) references to three script files, and five image files, all of differing sizes:
- GET script1 and script2; queue request for script3 and images1-5.
- script2 arrives (it's smaller than script1): GET script3, queue images1-5.
- script1 arrives; GET image1, queue images2-5.
- image1 arrives, GET image2, queue images3-5.
- script3 fails to arrive due to a network problem - GET script3 again (automatic retry).
- image2 arrives, script3 still not here; GET image3, queue images4-5.
- image 3 arrives; GET image4, queue image5, script3 still on the way.
- image4 arrives, GET image5;
- image5 arrives.
- script3 arrives.
In short: any old order, depending on what the server is doing, what the rest of the Internet is doing, and whether or not anything has errors and has to be re-fetched. This may seem like a weird way of doing things, but it would quite literally be impossible for the Internet (not just the WWW) to work with any degree of reliability if it wasn't done this way.
Also, the browser's internal queue might not fetch entities in the order they appear in the page - it's not required to by any standard.
(Oh, and don't forget caching, both in the browser and in caching proxies used by ISPs to ease the load on the network.)
I like to use find which is first assigned to variable and IFS switched to new line as follow:
FilesFound=$(find . -name "*.txt")
IFSbkp="$IFS"
IFS=$'\n'
counter=1;
for file in $FilesFound; do
echo "${counter}: ${file}"
let counter++;
done
IFS="$IFSbkp"
As commented by @Konrad Rudolph this will not work with "new lines" in file name. I still think it is handy as it covers most of the cases when you need to loop over command output.
It is recommended that you create a file named setenv.bat and place it in the Tomcat bin directory. With this file (which is run by the catalina.bat and catalina.sh scripts), you can change the following Tomcat environment settings with the JAVA_OPTS variable:
You can set the minimum and maximum memory heap size with the
JVM -Xms and -Xmx parameters.
The best limits depend on many conditions, such as transformations that Integrator ETL should execute. For Information Discovery transformations, a maximum of 1 GB is recommended. For example, to set the minimum heap size to 128 MB and the maximum heap size to 1024 MB, use
JAVA_OPTS=-Xms128m -Xmx1024m
You should set the maximum limit of the PermGen (Permanent Generation) memory space to a size larger than the default. The default of 64 MB is not enough for enterprise applications. A suitable memory limit depends on various criteria, but 256 MB would make a good choice in most cases. If the PermGen space maximum is too low, OutOfMemoryError: PermGen space errors may occur. You can set the PermGen maximum limit with the following JVM parameter
-XX:MaxPermSize=256m
For performance reasons, it is recommended that the application is run in Server mode. Apache Tomcat does not run in Server mode by default. You can set the Server mode by using the JVM -server parameter. You can set the JVM parameter in the JAVA_OPTS variable in the environment variable in the setenv file.
The following is an example of a setenv.bat file:
set "JAVA_OPTS=%JAVA_OPTS% -Xms128m -Xmx1024m -XX:MaxPermSize=256m -server"
A clean approach I find is by giving an ID
for each radio button and then setting it by using the following statement:
document.getElementById('publicedit').checked = true;
An alternative to the usual methods is to hook into the drawing of the view.
OnPreDrawListener
is called many times when displaying a view, so there is no specific iteration where your view has valid measured width or height. This requires that you continually verify (view.getMeasuredWidth() <= 0
) or set a limit to the number of times you check for a measuredWidth
greater than zero.
There is also a chance that the view will never be drawn, which may indicate other problems with your code.
final View view = [ACQUIRE REFERENCE]; // Must be declared final for inner class
ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
if (view.getMeasuredWidth() > 0) {
view.getViewTreeObserver().removeOnPreDrawListener(this);
int width = view.getMeasuredWidth();
int height = view.getMeasuredHeight();
//Do something with width and height here!
}
return true; // Continue with the draw pass, as not to stop it
}
});
Unlike languages that employ 'true' lexical scoping, Python opts to have specific 'namespaces' for variables, whether it be global
, nonlocal
, or local. It could be argued that making developers consciously code with such namespaces in mind is more explicit, thus more understandable. I would argue that such complexities make the language more unwieldy, but I guess it's all down to personal preference.
Here are some examples regarding global
:-
>>> global_var = 5
>>> def fn():
... print(global_var)
...
>>> fn()
5
>>> def fn_2():
... global_var += 2
... print(global_var)
...
>>> fn_2()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in fn_2
UnboundLocalError: local variable 'global_var' referenced before assignment
>>> def fn_3():
... global global_var
... global_var += 2
... print(global_var)
...
>>> fn_3()
7
The same patterns can be applied to nonlocal
variables too, but this keyword is only available to the latter Python versions.
In case you're wondering, nonlocal
is used where a variable isn't global, but isn't within the function definition it's being used. For example, a def
within a def
, which is a common occurrence partially due to a lack of multi-statement lambdas. There's a hack to bypass the lack of this feature in the earlier Pythons though, I vaguely remember it involving the use of a single-element list...
Note that writing to variables is where these keywords are needed. Just reading from them isn't ambiguous, thus not needed. Unless you have inner def
s using the same variable names as the outer ones, which just should just be avoided to be honest.
There is a simple rule of thumb to tell you when to use ==
or is
.
==
is for value equality. Use it when you would like to know if two objects have the same value.is
is for reference equality. Use it when you would like to know if two references refer to the same object.In general, when you are comparing something to a simple type, you are usually checking for value equality, so you should use ==
. For example, the intention of your example is probably to check whether x has a value equal to 2 (==
), not whether x
is literally referring to the same object as 2.
Something else to note: because of the way the CPython reference implementation works, you'll get unexpected and inconsistent results if you mistakenly use is
to compare for reference equality on integers:
>>> a = 500
>>> b = 500
>>> a == b
True
>>> a is b
False
That's pretty much what we expected: a
and b
have the same value, but are distinct entities. But what about this?
>>> c = 200
>>> d = 200
>>> c == d
True
>>> c is d
True
This is inconsistent with the earlier result. What's going on here? It turns out the reference implementation of Python caches integer objects in the range -5..256 as singleton instances for performance reasons. Here's an example demonstrating this:
>>> for i in range(250, 260): a = i; print "%i: %s" % (i, a is int(str(i)));
...
250: True
251: True
252: True
253: True
254: True
255: True
256: True
257: False
258: False
259: False
This is another obvious reason not to use is
: the behavior is left up to implementations when you're erroneously using it for value equality.
I got the same error in this code:
var articulos_en_almacen = xx.IV00102.Where(iv => alm_x_suc.Exists(axs => axs.almacen == iv.LOCNCODE.Trim())).Select(iv => iv.ITEMNMBR.Trim()).ToList();
this was the exactly error:
System.NotSupportedException: 'LINQ to Entities does not recognize the method 'Boolean Exists(System.Predicate`1[conector_gp.Models.almacenes_por_sucursal])' method, and this method cannot be translated into a store expression.'
I solved this way:
var articulos_en_almacen = xx.IV00102.ToList().Where(iv => alm_x_suc.Exists(axs => axs.almacen == iv.LOCNCODE.Trim())).Select(iv => iv.ITEMNMBR.Trim()).ToList();
I added a .ToList() before my table, this decouple the Entity and linq code, and avoid my next linq expression be translated
NOTE: this solution isn't optimal, because avoid entity filtering, and simply loads all table into memory
This answer seems pretty basic but wasn't completely obvious to me at first. If you (re)build the solution it only builds the projects that are configured to build in the Build -> Configuration Manager
This was my issue, I must have inadvertently changed a build configuration settings or something that caused my test projects not to build (when they previously were). So the Test Explorer
window was looking at dlls that were out of date. It became clear to me this was the case after doing a Clean
and seeing most of my tests disappear and not come back after a rebuild
...further inspection of bin
folder showed that these projects weren't being built at all.
$name -replace ";*",""
You were close, but you used the syntax of a wildcard expresson rather than a regular expression, which is what the -replace
operator expects.
Therefore (hash sequence shortened):
PS> 'test.txt ; 131 136 80 89 119 17 60 123 210 121 188' -replace '\s*;.*'
test.txt
Note:
Omitting the substitution-text operand (the 2nd RHS operand) implicitly uses ""
(the empty string), i.e. it effectively removes what the regex matched.
.*
is what represents a potentially empty run (*
) of characters (.
) in a regex - it is the regex equivalent of *
by itself in a wildcard expression.
Adding \s*
before the ;
in the regex also removes trailing whitespace (\s
) after the filename.
I've used '...'
rather than "..."
to enclose the regex, so as to prevent confusion between what PowerShell expands up front (see expandable strings in PowerShell and what the .NET regex engine sees.
Would something like work?
See In eclipse, ctrl-click goes to the declaration of the method I clicked. For interfaces with one implementation, how can I just directly to that implementation? for some alternative solutions.
Just an addition to the previous answers. Let's not forget that when dealing with real data there might be null values, so it's useful to also include those in the counting by using the option dropna=False
(default is True
)
An example:
>>> df['Embarked'].value_counts(dropna=False)
S 644
C 168
Q 77
NaN 2
To work with the base Date class you can look at MDN for its methods (instead of W3Schools due to this reason). There you can find a good description about every method useful to access each single date/time component and informations relative to whether a method is deprecated or not.
Otherwise you can look at Moment.js that is a good library to use for date and time processing. You can use it to manipulate date and time (such as parsing, formatting, i18n, etc.).
Instead of adding any tag which is never a good solution. You can always use margin
property with the required element.
You can add the margin on row class itself. So it will affect globally.
.row{
margin-top: 30px;
margin-bottom: 30px
}
Update: Better solution in all cases would be to introduce a new class and then use it along with .row
class.
.row-m-t{
margin-top : 20px
}
Then use it wherever you want
<div class="row row-m-t"></div>
<RatingBar
android:id="@+id/ratingBar1"
android:numStars="5"
android:stepSize=".5"
android:rating="3.5"
style="@android:style/Widget.DeviceDefault.RatingBar.Small"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
This is what has worked for me. I use this to "add" files over to the other drive, with no overwrites.
Batch file: robocopy-missingfiles.bat
@echo off
echo Copying
echo "%1"
echo to "%2"
echo.
echo Press Cntr+C to abort
Pause
echo.
@echo on
robocopy %1 %2 /Xo /XN /XC /J /SL /S /MT:8 /R:1 /W:1 /V /DCOPY:DAT /ETA /COPY:DATO /FFT /A-:SH /XD $RECYCLE.BIN "System Volume Information"
Example:
robocopy-missingfiles.bat f:\Working-folder\ E:\Backup-folder\
Do test before implementation.
Include this JavaScript in your footer (after loading jQuery):
$('.item').css('min-height',$('.item').height());
I prefer field access, because that way I'm not forced to provide getter/setter for each property.
A quick survey via Google suggests that field access is the majority (e.g., http://java.dzone.com/tips/12-feb-jpa-20-why-accesstype).
I believe field access is the idiom recommended by Spring, but I can't find a reference to back that up.
There's a related SO question that tried to measure performance and came to the conclusion that there's "no difference".
Adam is only partially right. Many, if not most, mathematicians will never touch it. If there is a computer tool used at all, it's going to be something like Mathematica or Maple. Engineering departments, on the other hand, often rely on it and there are definitely useful things for some applied mathematicians. It's also used heavily in industry in some areas.
Something you have to realize about MATLAB is that it started off as a wrapper on Fortran libraries for linear algebra. For a long time, it had an attitude that "all the world is an array of doubles (floats)". As a language, it has grown very organically, and there are some flaws that are very much baked in, if you look at it just as a programming language.
However, if you look at it as an environment for doing certain types of research in, it has some real strengths. It's about as good as it gets for doing floating point linear algebra. The notation is simple and powerful, the implementation fast and trusted. It is very good at generating plots and other interactive tasks. There are a large number of `toolboxes' with good code for particular tasks, that are affordable. There is a large community of users that share numerical codes (Python + NumPy has nothing in the same league, at least yet)
Python, warts and all, is a much better programming language (as are many others). However, it's a decade or so behind in terms of the tools.
The key point is that the majority of people who use MATLAB are not programmers really, and don't want to be.
It's a lousy choice for a general programming language; it's quirky, slow for many tasks (you need to vectorize things to get efficient codes), and not easy to integrate with the outside world. On the other hand, for the things it is good at, it is very very good. Very few things compare. There's a company with reasonable support and who knows how many man-years put into it. This can matter in industry.
Strictly looking at your Python vs. MATLAB comparison, they are mostly different tools for different jobs. In the areas where they do overlap a bit, it's hard to say what the better route to go is (depends a lot on what you're trying to do). But mostly Python isn't all that good at MATLAB's core strengths, and vice versa.
Just include this line
android:selectAllOnFocus="false"
in the XML segment corresponding to the EditText layout.
Some versions of tar, for example, the default versions on HP-UX (I tested 11.11 and 11.31), do not include a command line option to specify a file list, so a decent work-around is to do this:
tar cvf allfiles.tar $(cat mylist.txt)
If you can add another wrapping div "block3" you could do something like this.
<html>
<head>
<style type="text/css">
.block1 {color:red;width:120px;border:1px solid green; height: 100px;}
.block3 {float:left; width:10px;}
.block2 {color:blue;width:70px;border:2px solid black;position:relative;float:right;}
</style>
</head>
<body>
<div class='block1'>
<div class='block3'>
<p>text1</p>
<p>text2</p>
</div>
<div class='block2'>block2</DIV>
</div>
</body>
</html>
You can also initialise it like this:
struct name sara = { "Sara", "Black" };
Since (as a special case) you're allowed to initialise char arrays from string constants.
Now, as for what a struct actually is - it's a compound type composed of other values. What sara
actually looks like in memory is a block of 20 consecutive char values (which can be referred to using sara.first
, followed by 0 or more padding bytes, followed by another block of 20 consecutive char values (which can be referred to using sara.last
). All other instances of the struct name
type are laid out in the same way.
In this case, it is very unlikely that there is any padding, so a struct name
is just a block of 40 characters, for which you have a name for the first 20 and the last 20.
You can find out how big a block of memory a struct name
takes using sizeof(struct name)
, and you can find out where within that block of memory each member of the structure is placed at using offsetof(struct name, first)
and offsetof(struct name, last)
.
Java includes a scripting language extension package starting with version 6.
See the Rhino project documentation for embedding a JavaScript interpreter in Java.
[Edit]
Here is a small example of how you can expose Java objects to your interpreted script:
public class JS {
public static void main(String args[]) throws Exception {
ScriptEngine js = new ScriptEngineManager().getEngineByName("javascript");
Bindings bindings = js.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put("stdout", System.out);
js.eval("stdout.println(Math.cos(Math.PI));");
// Prints "-1.0" to the standard output stream.
}
}
In my case, I was getting this error because I had an input named x
and I was creating (without realizing it) a local variable called x
. I thought I was trying to access an element of the input x
(which was an array), while I was actually trying to access an element of the local variable x
(which was a scalar).
An index is used for several different reasons. The main reason is to speed up querying so that you can get rows or sort rows faster. Another reason is to define a primary-key or unique index which will guarantee that no other columns have the same values.
ok, here is what i understood from your question. You are writing a csv file from python but when you are opening that file into some other application like excel or open office they are showing the complete row in one cell rather than each word in individual cell. I am right??
if i am then please try this,
import csv
with open(r"C:\\test.csv", "wb") as csv_file:
writer = csv.writer(csv_file, delimiter =",",quoting=csv.QUOTE_MINIMAL)
writer.writerow(["a","b"])
you have to set the delimiter = ","
The gcc compiler is not in your $PATH
.
It means either you dont have gcc installed or it's not in your $PATH variable.
To install gcc use this: (run as root)
Redhat base:
yum groupinstall "Development Tools"
Debian base:
apt-get install build-essential
sourceString.Replace(removeString, "");
C++11 added alias declarations, which are generalization of typedef
, allowing templates:
template <size_t N>
using Vector = Matrix<N, 1>;
The type Vector<3>
is equivalent to Matrix<3, 1>
.
In C++03, the closest approximation was:
template <size_t N>
struct Vector
{
typedef Matrix<N, 1> type;
};
Here, the type Vector<3>::type
is equivalent to Matrix<3, 1>
.
T
and TRUE
are True, F
and FALSE
are False. T
and F
can be redefined, however, so you should only rely upon TRUE
and FALSE
. If you compare 0 to FALSE and 1 to TRUE, you will find that they are equal as well, so you might consider them to be True and False as well.
Two tricks. Basically inverting the HTML order of your desired elements in HTML and using
~
Next siblings operator:
float-right
+ inverse the order of HTML elementsdiv{ /* Do with the parent whatever you know just to make the_x000D_
inner float-right elements appear where desired */_x000D_
display:inline-block;_x000D_
}_x000D_
span{_x000D_
float:right; /* float-right the elements! */_x000D_
}_x000D_
span:hover ~ span{ /* On hover target it's "previous";) elements */_x000D_
background:red;_x000D_
}
_x000D_
<div>_x000D_
<!-- Reverse the order of inner elements -->_x000D_
<span>5</span>_x000D_
<span>4</span>_x000D_
<span>3</span>_x000D_
<span>2</span>_x000D_
<span>1</span>_x000D_
</div>
_x000D_
direction: rtl;
+ inverse the order of inner elements.inverse{_x000D_
direction: rtl;_x000D_
display: inline-block; /* inline-block to keep parent at the left of window */_x000D_
}_x000D_
span:hover ~ span{ /* On hover target it's "previous";) elements */_x000D_
background:gold;_x000D_
}
_x000D_
Hover one span and see the previous elements being targeted!<br>_x000D_
_x000D_
<div class="inverse">_x000D_
<!-- Reverse the order of inner elements -->_x000D_
<span>5</span>_x000D_
<span>4</span>_x000D_
<span>3</span>_x000D_
<span>2</span>_x000D_
<span>1</span>_x000D_
</div>
_x000D_
This is improved @Vicky solution - it has clearInterval() added so it prevents a loop of reloading if the redirect takes too long:
$(document).ready(function () {
var myTimer = window.setInterval(function () {
var timeLeft = $("#countdown").html();
if (eval(timeLeft) == 0) {
console.log('Now redirecting');
clearInterval(myTimer);
window.location = ("@Html.Raw(HttpUtility.HtmlDecode(redirectUrl))");
} else {
$("#countdown").html(eval(timeLeft) - eval(1));
}
}, 1000);
});
I would try
Sheets("Sheet1").Activate
Set Ticker = Range(Cells(2, 1), Cells(65, 1))
Ticker.Copy
Worksheets("Sheet2").Range("A1").Offset(0,0).Cells.Select
Worksheets("Sheet2").paste
Try below code to get currently loaded product id:
$product_id = $this->getProduct()->getId();
When you don’t have access to $this, you can use Magento registry:
$product_id = Mage::registry('current_product')->getId();
Also for product type i think
$product = Mage::getModel('catalog/product')->load($product_id);
$productType = $product->getTypeId();
#if defined(CONDITION1) || defined(CONDITION2)
should work. :)
#ifdef
is a bit less typing, but doesn't work well with more complex conditions
Try this:
"maingame": {
"day1": {
"text1": "Tag 1",
"text2": "Heute startet unsere Rundreise \" Example text\". Jeden Tag wird ein neues Reiseziel angesteuert bis wir.</strong> "
}
}
(just one backslash (\
) in front of quotes).
You can do this by setting a style in your paragraph tag. For example if you wanted to change the font size to 28px.
<p style="font-size: 28px;"> Hello, World! </p>
You can also set the color by setting:
<p style="color: blue;"> Hello, World! </p>
However, if you want to preview font sizes and colors (which I recommend doing) before you add them to your website and use them. I recommend testing them out beforehand so you pick a good font size and color that contrasts well with the background. I recommend using this site if you wish to do so, couldn't find anything else: http://fontpreview.herokuapp.com/
WebSockets:
Ratified IETF standard (6455) with support across all modern browsers and even legacy browsers using web-socket-js polyfill.
Uses HTTP compatible handshake and default ports making it much easier to use with existing firewall, proxy and web server infrastructure.
Much simpler browser API. Basically one constructor with a couple of callbacks.
Client/browser to server only.
Only supports reliable, in-order transport because it is built On TCP. This means packet drops can delay all subsequent packets.
WebRTC:
Just beginning to be supported by Chrome and Firefox. MS has proposed an incompatible variant. The DataChannel component is not yet compatible between Firefox and Chrome.
WebRTC is browser to browser in ideal circumstances but even then almost always requires a signaling server to setup the connections. The most common signaling server solutions right now use WebSockets.
Transport layer is configurable with application able to choose if connection is in-order and/or reliable.
Complex and multilayered browser API. There are JS libs to provide a simpler API but these are young and rapidly changing (just like WebRTC itself).
Either use an Allias in the table like T and use T.ID, or use just the column name.
declare @TEMP table (ID int, Name varchar(max))
insert into @temp SELECT ID, Name FROM Table
SELECT * FROM @TEMP
WHERE ID = 1
If you want not to use dimensions you should use this line
android {
compileSdkVersion 24
...
flavorDimensions "default"
...
}
but if you want ti use dimensions you should declare your dimension name first and then use this name after THIS example is from the documentations:
android {
...
buildTypes {
debug {...}
release {...}
}
// Specifies the flavor dimensions you want to use. The order in which you
// list each dimension determines its priority, from highest to lowest,
// when Gradle merges variant sources and configurations. You must assign
// each product flavor you configure to one of the flavor dimensions.
flavorDimensions "api", "mode"
productFlavors {
demo {
// Assigns this product flavor to the "mode" flavor dimension.
dimension "mode"
...
}
full {
dimension "mode"
...
}
// Configurations in the "api" product flavors override those in "mode"
// flavors and the defaultConfig block. Gradle determines the priority
// between flavor dimensions based on the order in which they appear next
// to the flavorDimensions property above--the first dimension has a higher
// priority than the second, and so on.
minApi24 {
dimension "api"
minSdkVersion 24
// To ensure the target device receives the version of the app with
// the highest compatible API level, assign version codes in increasing
// value with API level. To learn more about assigning version codes to
// support app updates and uploading to Google Play, read Multiple APK Support
versionCode 30000 + android.defaultConfig.versionCode
versionNameSuffix "-minApi24"
...
}
minApi23 {
dimension "api"
minSdkVersion 23
versionCode 20000 + android.defaultConfig.versionCode
versionNameSuffix "-minApi23"
...
}
minApi21 {
dimension "api"
minSdkVersion 21
versionCode 10000 + android.defaultConfig.versionCode
versionNameSuffix "-minApi21"
...
}
}
}
...
Graphviz - from the web page:
The Graphviz layout programs take descriptions of graphs in a simple text language, and make diagrams in several useful formats such as images and SVG for web pages, Postscript for inclusion in PDF or other documents; or display in an interactive graph browser. (Graphviz also supports GXL, an XML dialect.)
It's the simplest and most productive tool I've found to create a variety of boxes-and-lines diagrams. I have and use Visio and OmniGraffle, but there's always the temptation to make "just one more adjustment".
It's also quite easy to write code to produce the "dot file" format that Graphiz consumes, so automated diagram production is also nicely within reach.
This cryptic error means that you don't have a C compiler installed. There was a discussion to propose a more explanative error (which is continued here, register and comment if you care about it!) but currently it is still not implemented.
To fix this issue you can either install the Visual Studio 2008 SDK which will take about a GB, or you can install the very small VCForPython27.msi but which is not well supported by distutils currently, here's the procedure:
1) install Microsoft Visual C++ Compiler for Python 2.7 from
http://www.microsoft.com/en-us/download/details.aspx?id=44266
2) Enter MSVC for Python command prompt
3) SET DISTUTILS_USE_SDK=1
4) SET MSSdk=1
5) you can then build your C extensions: python.exe setup.py ...
Steps 2 to 4 must be reproduced everytime before building your C extensions. This is because of an issue with the VCForPython27.msi which install the header files and vcvarsall.bat in folders of a different layout than the VS2008 SDK and thus confuse the compiler detection of distutils. This will get fixed in setuptools in Python 2.7.10.
Bug report and workaround by Gregory Szorc: http://bugs.python.org/issue23246
More info and a workaround for using %%cython magic inside IPython: https://github.com/cython/cython/wiki/CythonExtensionsOnWindows
/EDIT: Also, if you have another version of Python, you cannot use Microsoft Visual C++ for Python 2.7, which is a kind of mini-compiler specifically made by Microsoft for Python 2.7. In this case, you need to install the Visual Studio SDK that match your Python version, or a Windows SDK with the correct NET framework version. See here for more infos: https://github.com/cython/cython/wiki/CythonExtensionsOnWindows#using-windows-sdk-cc-compiler-works-for-all-python-versions
I would take a look at the BinaryReader and BinaryWriter classes. I recently had to serialize data to a byte array (and back) and only found these classes after I'd basically rewritten them myself.
http://msdn.microsoft.com/en-us/library/system.io.binarywriter.aspx
There is a good example on that page too.
If you're looking to do an "upsert" one of the most efficient ways currently in SQL Server for single rows is this:
UPDATE myTable ...
IF @@ROWCOUNT=0
INSERT INTO myTable ....
You can also use the MERGE
syntax if you're doing this with sets of data rather than single rows.
If you want to INSERT
and not UPDATE
then you can just write your single INSERT
statement and use WHERE NOT EXISTS (SELECT ...)
You have to fetch that one record, it will contain the result of Count()
$result = $db->query("SELECT COUNT(*) FROM `table`");
$row = $result->fetch_row();
echo '#: ', $row[0];
This worked for me
Spinner's initialization in Android is problematic sometimes the above problem was solved by this pattern.
Spinner.setAdapter();
Spinner.setSelected(false); // must
Spinner.setSelection(0,true); //must
Spinner.setonItemSelectedListener(this);
Setting adapter should be first part and onItemSelectedListener(this) will be last when initializing a spinner. By the pattern above my OnItemSelected() is not called during initialization of spinner
I've found a solution worked for me:
const handleDownload = async () => {
const req = await axios({
method: "get",
url: `/companies/${company.id}/data`,
responseType: "blob",
});
var blob = new Blob([req.data], {
type: req.headers["content-type"],
});
const link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
link.download = `report_${new Date().getTime()}.xlsx`;
link.click();
};
I just point a responseType: "blob"
Your diameter variable won't work because you're trying to store a String into a variable that will only accept a double. In order for it to work you will need to parse it
Ex:
diameter = Double.parseDouble(JOptionPane.showInputDialog("enter the diameter of a sphere.");
Im sure this problem is related to the files and folders permissions.
table_ages <- subset(infert, select=c("age"))
summary(table_ages)
# age
# Min. :21.00
# 1st Qu.:28.00
# Median :31.00
# Mean :31.50
# 3rd Qu.:35.25
# Max. :44.00
This is probably what they're looking for. summary(...)
applied to a numeric returns the min, max, mean, median, and 25th and 75th percentile of the data.
Note that
summary(infert$age)
# Min. 1st Qu. Median Mean 3rd Qu. Max.
# 21.00 28.00 31.00 31.50 35.25 44.00
The numbers are the same but the format is different. This is because table_ages
is a data frame with one column (ages), whereas infert$age
is a numeric vector. Try typing summary(infert)
.
For the love of all that is holy...
In my case, I had to set the openssl.cafile
PHP config variable to the PEM file path.
I trust it is very true that there are many systems where setting curl.cainfo
in PHP's config is exactly what is needed, but in the environment I'm working with, which is the eboraas/laravel docker container, which uses Debian 8 (jessie) and PHP 5.6, setting that variable did not do the trick.
I noticed that the output of php -i
did not mention anything about that particular config setting, but it did have a few lines about openssl
. There is both an openssl.capath
and openssl.cafile
option, but just setting the second one allowed curl via PHP to finally be okay with HTTPS URLs.
Just copy the parent view's frame to the child-view then add it. After that autoresizing will work. Actually you should only copy the size CGRectMake(0, 0, parentView.frame.size.width, parentView.frame.size.height)
childView.frame = CGRectMake(0, 0, parentView.frame.size.width, parentView.frame.size.height);
[parentView addSubview:childView];
The only suspect entry in your config looks to me to be core.ignorecase
. You could try unsetting that with:
git config --unset core.ignorecase
... and see if the output from git status
or git diff
is different.
Here's how to print the complete list of files in the working tree which match patterns located anywhere in Git's multiple gitignore sources (if you're using GNU find
):
$ cd {your project directory}
$ find . -path ./.git -prune -o -print \
| git check-ignore --no-index --stdin --verbose
It will check all the files in the current branch of the repository (unless you've deleted them locally).
And it identifies the particular gitignore source lines, as well.
Git continues to track changes in some files which match gitignore patterns, simply because those files were added already. Usefully, the above command displays those files, too.
Negative gitignore patterns are also matched. However, these are easily distinguishable in the listing, because they begin with !
.
If you're using Windows, Git Bash includes GNU find
(as revealed by find --version
).
If the list is long (and you have rev
), you can display them by extension (somewhat), too:
$ cd {your project directory}
$ find . -path ./.git -prune -o -print \
| git check-ignore --no-index --stdin --verbose \
| rev | sort | rev
For more details, see man find
, man git-check-ignore
, man rev
, and man sort
.
The point of this whole approach is that Git (the software) is changing rapidly and is highly complex. By contrast, GNU's find
is extremely stable (at least, in its features used here). So, anyone who desires to be competitive by displaying their in-depth knowledge of Git will answer the question in a different way.
What's the best answer? This answer deliberately minimizes its reliance on Git knowledge, toward achieving the goal of stability and simplicity through modularity (information isolation), and is designed to last a long time.
MOVE /-Y Source Destination
Note:/-y will make the announcement of yes/no for overwrite
Nice to see that it have been solved in the 2016 version, but for all of those that is not on that, here are two generalized and simplified versions of the methods above.
The XML-method is shorter, but of course requires the string to allow for the xml-trick (no 'bad' chars.)
XML-Method:
create function dbo.splitString(@input Varchar(max), @Splitter VarChar(99)) returns table as
Return
SELECT Split.a.value('.', 'VARCHAR(max)') AS Data FROM
( SELECT CAST ('<M>' + REPLACE(@input, @Splitter, '</M><M>') + '</M>' AS XML) AS Data
) AS A CROSS APPLY Data.nodes ('/M') AS Split(a);
Recursive method:
create function dbo.splitString(@input Varchar(max), @Splitter Varchar(99)) returns table as
Return
with tmp (DataItem, ix) as
( select @input , CHARINDEX('',@Input) --Recu. start, ignored val to get the types right
union all
select Substring(@input, ix+1,ix2-ix-1), ix2
from (Select *, CHARINDEX(@Splitter,@Input+@Splitter,ix+1) ix2 from tmp) x where ix2<>0
) select DataItem from tmp where ix<>0
Function in action
Create table TEST_X (A int, CSV Varchar(100));
Insert into test_x select 1, 'A,B';
Insert into test_x select 2, 'C,D';
Select A,data from TEST_X x cross apply dbo.splitString(x.CSV,',') Y;
Drop table TEST_X
XML-METHOD 2: Unicode Friendly (Addition courtesy of Max Hodges)
create function dbo.splitString(@input nVarchar(max), @Splitter nVarchar(99)) returns table as
Return
SELECT Split.a.value('.', 'NVARCHAR(max)') AS Data FROM
( SELECT CAST ('<M>' + REPLACE(@input, @Splitter, '</M><M>') + '</M>' AS XML) AS Data
) AS A CROSS APPLY Data.nodes ('/M') AS Split(a);
open the sql file on Notepad++ and ctrl + H.
Then you put "utf8mb4
" on search and "utf8
" on replace.
The issue will be fixed then.
Try returning the dataset from your stored procedure to your datatable in C# or VB.Net. Then the large amount of data in your datatable can be copied to your destination table using a Bulk Copy. I have used BulkCopy for loading large datatables with thousands of rows, into Sql tables with great success in terms of performance.
You may want to experiment with BulkCopy in your C# or VB.Net code.
TL;DR
headroom_by_jQuery = $('#id').offset().top - $(window).scrollTop();
headroom_by_DOM = $('#id')[0].getBoundingClientRect().top; // if no iframe
.getBoundingClientRect() appears to be universal. .offset() and .scrollTop() have been supported since jQuery 1.2. Thanks @user372551 and @prograhammer. To use DOM in an iframe see @ImranAnsari's solution.
Check, you might have written this statement wrong.
public static void main(String Args[])
I have also just started java and was facing the same error and it was occuring as i didn't put []
after args.
so check ur statment.
You can add a custom function to the $http
service using a "decorator" that would add the abort()
function to your promises.
Here's some working code:
app.config(function($provide) {
$provide.decorator('$http', function $logDecorator($delegate, $q) {
$delegate.with_abort = function(options) {
let abort_defer = $q.defer();
let new_options = angular.copy(options);
new_options.timeout = abort_defer.promise;
let do_throw_error = false;
let http_promise = $delegate(new_options).then(
response => response,
error => {
if(do_throw_error) return $q.reject(error);
return $q(() => null); // prevent promise chain propagation
});
let real_then = http_promise.then;
let then_function = function () {
return mod_promise(real_then.apply(this, arguments));
};
function mod_promise(promise) {
promise.then = then_function;
promise.abort = (do_throw_error_param = false) => {
do_throw_error = do_throw_error_param;
abort_defer.resolve();
};
return promise;
}
return mod_promise(http_promise);
}
return $delegate;
});
});
This code uses angularjs's decorator functionality to add a with_abort()
function to the $http
service.
with_abort()
uses $http
timeout option that allows you to abort an http request.
The returned promise is modified to include an abort()
function. It also has code to make sure that the abort()
works even if you chain promises.
Here is an example of how you would use it:
// your original code
$http({ method: 'GET', url: '/names' }).then(names => {
do_something(names));
});
// new code with ability to abort
var promise = $http.with_abort({ method: 'GET', url: '/names' }).then(
function(names) {
do_something(names));
});
promise.abort(); // if you want to abort
By default when you call abort()
the request gets canceled and none of the promise handlers run.
If you want your error handlers to be called pass true to abort(true)
.
In your error handler you can check if the "error" was due to an "abort" by checking the xhrStatus
property. Here's an example:
var promise = $http.with_abort({ method: 'GET', url: '/names' }).then(
function(names) {
do_something(names));
},
function(error) {
if (er.xhrStatus === "abort") return;
});
The hostname regex of smink does not observe the limitation on the length of individual labels within a hostname. Each label within a valid hostname may be no more than 63 octets long.
ValidHostnameRegex="^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])\ (\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$"
Note that the backslash at the end of the first line (above) is Unix shell syntax for splitting the long line. It's not a part of the regular expression itself.
Here's just the regular expression alone on a single line:
^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$
You should also check separately that the total length of the hostname must not exceed 255 characters. For more information, please consult RFC-952 and RFC-1123.
To remove anything that is not a number:
$output = preg_replace('/[^0-9]/', '', $input);
Explanation:
[0-9]
matches any number between 0 and 9 inclusively.^
negates a []
pattern.[^0-9]
matches anything that is not a number, and since we're using preg_replace
, they will be replaced by nothing ''
(second argument of preg_replace
).Initialize all your array elements to null first, then look for the null to find the empty slot
My 2 pennies:-
collection.Count(v => (v.PropertyToUpdate = newValue) == null);
If you want "tag_name" with associated "blogTags_id" use: (PHP > 5.5)
$blogDatas = array_column($your_multi_dim_array, 'tag_name', 'blogTags_id');
echo implode(', ', array_map(function ($k, $v) { return "$k: $v"; }, array_keys($blogDatas), array_values($blogDatas)));
You could also use the .add()
function:
df.loc[:,'variance'] = df.loc[:,'budget'].add(df.loc[:,'actual'])
You can for example create an instance of List<object>
, which implements IEnumerable<object>
. Example:
List<object> list = new List<object>();
list.Add(1);
list.Add(4);
list.Add(5);
IEnumerable<object> en = list;
CallFunction(en);
I had similar problems as people here with Nexus 5 on Windows 7. No .inf file edits were needed, my computer was stuck on an old version of the Google USB drivers (7.0.0.1). Windows 7 refused to install the newer version even if I tried to manually select the directory or .inf file. Had to manually delete specific cached .inf files in WINDOWS\inf folder, follow directions here: http://code.google.com/p/android/issues/detail?id=62365#c7
Also be sure USB debugging is turned on in developer options. There's a trick to expose the developer options, click 7 times on the build number at the bottom of the "About Phone" information!
I have the same issue, I'm not able to open a CSV file in Excel. I've found a solution that worked for me in this question Opening a file in excel via Workbooks.OpenText
That question helped me to figure out a code that works for me. The code looks more or less like this:
Private Sub OpenCSVFile(filename as String)
Dim datasourceFilename As String
Dim currentPath As String
datasourceFilename = "\" & filename & ".csv"
currentPath = ActiveWorkbook.Path
Workbooks.OpenText Filename:=currentPath & datasourceFilename, _
Origin:=xlWindows, _
StartRow:=1, _
DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, _
Semicolon:=False, _
Comma:=True, _
Space:=False, _
Other:=False, _
FieldInfo:=Array(Array(1, 1), Array(2, 1)), _
DecimalSeparator:=".", _
ThousandsSeparator:=",", _
TrailingMinusNumbers:=True
End Sub
At least, it helped me to know about lots of parameters I can use with Workbooks.OpenText
method.
If you use PyCharm, please change you 'Project Interpreter' to '2.7.x'
To make a responsive table, you can make the width of each td
100% and insert a related heading in the td
on mobile browsers (that are less 768px
width.)
Here is a website that demonstrates this technique: http://www.quizexpo.com/list-of-banks-in-india/
Here's a terrible idea for you.
Use an alias, create a new linked server from your server to its own alias.
Now you can do:
select a.SomeColumns, b.OtherColumns
from LocalDb.dbo.LocalTable a
inner join (select * from openquery([AliasToThisServer],'
exec LocalDb.dbo.LocalStoredProcedure
') ) b
on a.Id = b.Id
Default argument values are evaluated at function define-time, but self
is an argument only available at function call time. Thus arguments in the argument list cannot refer each other.
It's a common pattern to default an argument to None
and add a test for that in code:
def p(self, b=None):
if b is None:
b = self.a
print b
The following will do it if, as I assume by your use of ./a.out
, you're on a UNIX-type platform.
for number in 1 2 3 4 ; do \
./a.out $$number ; \
done
Test as follows:
target:
for number in 1 2 3 4 ; do \
echo $$number ; \
done
produces:
1
2
3
4
For bigger ranges, use:
target:
number=1 ; while [[ $$number -le 10 ]] ; do \
echo $$number ; \
((number = number + 1)) ; \
done
This outputs 1 through 10 inclusive, just change the while
terminating condition from 10 to 1000 for a much larger range as indicated in your comment.
Nested loops can be done thus:
target:
num1=1 ; while [[ $$num1 -le 4 ]] ; do \
num2=1 ; while [[ $$num2 -le 3 ]] ; do \
echo $$num1 $$num2 ; \
((num2 = num2 + 1)) ; \
done ; \
((num1 = num1 + 1)) ; \
done
producing:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
4 1
4 2
4 3
If you want force stop your thread:
thread._Thread_stop()
For me works very good.
Have you seen the SqlDateTime object? use SqlDateTime.MinValue
to get your minimum date (Jan 1 1753).
I know how this can be done using
fgets
andstrtol
, I would like to know how this can be done usingscanf()
(if possible).
As the other answers say, scanf
isn't really suitable for this, fgets
and strtol
is an alternative (though fgets
has the drawback that it's hard to detect a 0-byte in the input and impossible to tell what has been input after a 0-byte, if any).
For sake of completeness (and assuming valid input is an integer followed by a newline):
while(scanf("%d%1[\n]", &n, (char [2]){ 0 }) < 2)
Alternatively, use %n
before and after %*1[\n]
with assignment-suppression. Note, however (from the Debian manpage):
This is not a conversion, although it can be suppressed with the
*
assignment-suppression character. The C standard says: "Execution of a%n
directive does not increment the assignment count returned at the completion of execution" but the Corrigendum seems to contradict this. Probably it is wise not to make any assumptions on the effect of%n
conversions on the return value.
Usually, only the endpoint that issues an 'active close' should go into TIME_WAIT state. So, if possible, have your clients issue the active close which will leave the TIME_WAIT on the client and NOT on the server.
See here: http://www.serverframework.com/asynchronousevents/2011/01/time-wait-and-its-design-implications-for-protocols-and-scalable-servers.html and http://www.isi.edu/touch/pubs/infocomm99/infocomm99-web/ for details (the later also explains why it's not always possible due to protocol design that doesn't take TIME_WAIT into consideration).
Maybe something like this:
if "%~s0"=="%~s1" ( cd %~sp1 & shift ) else (
echo CreateObject^("Shell.Application"^).ShellExecute "%~s0","%~0 %*","","runas",1 >"%tmp%%~n0.vbs" & "%tmp%%~n0.vbs" & del /q "%tmp%%~n0.vbs" & goto :eof
)
FrustratedWithFormsDesigner is correct, PL/pgSQL can do this. Here's the script:
CREATE OR REPLACE FUNCTION truncate_tables(username IN VARCHAR) RETURNS void AS $$
DECLARE
statements CURSOR FOR
SELECT tablename FROM pg_tables
WHERE tableowner = username AND schemaname = 'public';
BEGIN
FOR stmt IN statements LOOP
EXECUTE 'TRUNCATE TABLE ' || quote_ident(stmt.tablename) || ' CASCADE;';
END LOOP;
END;
$$ LANGUAGE plpgsql;
This creates a stored function (you need to do this just once) which you can afterwards use like this:
SELECT truncate_tables('MYUSER');
In C++ (without error checking):
std::string blob = ...; // assume blob is in the string
std::string query = "INSERT INTO foo (blob_column) VALUES (?);";
sqlite3_stmt *stmt;
sqlite3_prepare_v2(db, query, query.size(), &stmt, nullptr);
sqlite3_bind_blob(stmt, 1, blob.data(), blob.size(),
SQLITE_TRANSIENT);
That can be SQLITE_STATIC
if the query will be executed before blob
gets destructed.
In addition to the above great answers using Threads, in case you have to use your main thread or prefer an async approach - I wrapped a short class around aio_timers Timer class (to enable repeating)
import asyncio
from aio_timers import Timer
class RepeatingAsyncTimer():
def __init__(self, interval, cb, *args, **kwargs):
self.interval = interval
self.cb = cb
self.args = args
self.kwargs = kwargs
self.aio_timer = None
self.start_timer()
def start_timer(self):
self.aio_timer = Timer(delay=self.interval,
callback=self.cb_wrapper,
callback_args=self.args,
callback_kwargs=self.kwargs
)
def cb_wrapper(self, *args, **kwargs):
self.cb(*args, **kwargs)
self.start_timer()
from time import time
def cb(timer_name):
print(timer_name, time())
print(f'clock starts at: {time()}')
timer_1 = RepeatingAsyncTimer(interval=5, cb=cb, timer_name='timer_1')
timer_2 = RepeatingAsyncTimer(interval=10, cb=cb, timer_name='timer_2')
clock starts at: 1602438840.9690785
timer_1 1602438845.980087
timer_2 1602438850.9806316
timer_1 1602438850.9808934
timer_1 1602438855.9863033
timer_2 1602438860.9868324
timer_1 1602438860.9876585
From further research, I've found:
http://dev.mysql.com/doc/refman/5.1/en/news-5-1-11.html
An SQL-injection security hole has been found in multi-byte encoding processing. The bug was in the server, incorrectly parsing the string escaped with the mysql_real_escape_string() C API function.
This vulnerability was discovered and reported by Josh Berkus and Tom Lane as part of the inter-project security collaboration of the OSDB consortium. For more information about SQL injection, please see the following text.
Discussion. An SQL injection security hole has been found in multi-byte encoding processing. An SQL injection security hole can include a situation whereby when a user supplied data to be inserted into a database, the user might inject SQL statements into the data that the server will execute. With regards to this vulnerability, when character set-unaware escaping is used (for example, addslashes() in PHP), it is possible to bypass the escaping in some multi-byte character sets (for example, SJIS, BIG5 and GBK). As a result, a function such as addslashes() is not able to prevent SQL-injection attacks. It is impossible to fix this on the server side. The best solution is for applications to use character set-aware escaping offered by a function such mysql_real_escape_string().
However, a bug was detected in how the MySQL server parses the output of mysql_real_escape_string(). As a result, even when the character set-aware function mysql_real_escape_string() was used, SQL injection was possible. This bug has been fixed.
Workarounds. If you are unable to upgrade MySQL to a version that includes the fix for the bug in mysql_real_escape_string() parsing, but run MySQL 5.0.1 or higher, you can use the NO_BACKSLASH_ESCAPES SQL mode as a workaround. (This mode was introduced in MySQL 5.0.1.) NO_BACKSLASH_ESCAPES enables an SQL standard compatibility mode, where backslash is not considered a special character. The result will be that queries will fail.
To set this mode for the current connection, enter the following SQL statement:
SET sql_mode='NO_BACKSLASH_ESCAPES';
You can also set the mode globally for all clients:
SET GLOBAL sql_mode='NO_BACKSLASH_ESCAPES';
This SQL mode also can be enabled automatically when the server starts by using the command-line option --sql-mode=NO_BACKSLASH_ESCAPES or by setting sql-mode=NO_BACKSLASH_ESCAPES in the server option file (for example, my.cnf or my.ini, depending on your system). (Bug#8378, CVE-2006-2753)
See also Bug#8303.
Browser caching strategies can be controlled by HTTP headers. Remember that they are just a hint, really. Since browsers are terribly inconsistent in this (and any other) field, you'll need several headers to get the desired effect on a range of browsers.
header ("Pragma-directive: no-cache");
header ("Cache-directive: no-cache");
header ("Cache-control: no-cache");
header ("Pragma: no-cache");
header ("Expires: 0");
js version, catches iPad too:
var is_mobile = /mobile|android/i.test (navigator.userAgent);
In SQL Server 2008 or above I use the following query to find all the dependant stored procedures, user defined functions, triggers, etc. for a given table:
SELECT
coalesce(Referenced_server_name+'.','')+ --possible server name if cross-server
coalesce(referenced_database_name+'.','')+ --possible database name if cross-database
coalesce(referenced_schema_name+'.','')+ --likely schema name
coalesce(referenced_entity_name,'') + --very likely entity name
coalesce('.'+col_name(referenced_ID,referenced_minor_id),'')AS [referencing],
coalesce(object_schema_name(Referencing_ID)+'.','')+ --likely schema name
object_name(Referencing_ID)+ --definite entity name
coalesce('.'+col_name(referencing_ID,referencing_minor_id),'') AS [referenced]
FROM sys.sql_expression_dependencies
WHERE referenced_id =object_id('Table_name')
ORDER BY [referenced]
think works
Criteria criteria = getSession().createCriteria(clazz);
Criterion rest1= Restrictions.and(Restrictions.eq(A, "X"),
Restrictions.in("B", Arrays.asList("X",Y)));
Criterion rest2= Restrictions.and(Restrictions.eq(A, "Y"),
Restrictions.eq(B, "Z"));
criteria.add(Restrictions.or(rest1, rest2));
could you please try below code
<c:forEach var="hash" items="${map['key']}">
<option><c:out value="${hash}"/></option>
</c:forEach>
If you are sure that your structure is correct, just push an empty commit or update the index.html file with some space, it works!
Set Your Own application Path
Dim myPathsValues As String
TextBox1.Text = Application.StartupPath
TextBox2.Text = Len(Application.StartupPath)
TextBox3.Text = Microsoft.VisualBasic.Right(Application.StartupPath, 10)
myPathsValues = Val(TextBox2.Text) - 9
TextBox4.Text = Microsoft.VisualBasic.Left(Application.StartupPath, myPathsValues) & "Reports"
^-?[0-9]{1,3}(?:\.[0-9]{1,10})?$
Regex breakdown:
^-?[0-9]{1,3}(?:\.[0-9]{1,10})?$
-?
# accept negative values
^
# Start of string
[0-9]{1,3}
# Match 1-3 digits (i. e. 0-999)
(?:
# Try to match...
\.
# a decimal point
[0-9]{1,10}
# followed by one to 10 digits (i. e. 0-9999999999)
)?
# ...optionally
$
# End of string
Use:
docker inspect -f "{{.Name}} {{.Config.Cmd}}" $(docker ps -a -q)
... it does a "docker inspect" for all containers.
You can use GetType - GetProperties - Linq Foreach:
obj.GetType().GetProperties().ToList().ForEach(p =>{
//p is each PropertyInfo
DoSomething(p);
});
String FILE_NAME = "C:\\Ajay\\TEST\\data_996KB.json";
File file = new File(FILE_NAME);
if((file.length()) <= (1048576)) {
System.out.println("file size is less than 1 mb");
}else {
System.out.println("file size is More than 1 mb");
}
Note: 1048576= (1024*1024)=1MB output : file size is less than 1 mb