Agree no matches in your example.
If you mean both columns on either then need a query like this or need to re-examine the data design.
Select TableA.Col1, TableA.Col2, TableB.Val
FROM TableA
INNER JOIN TableB
ON TableA.Col1 = TableB.Col1 OR TableA.Col2 = TableB.Col2
OR TableA.Col2 = TableB.Col1 OR TableA.Col1 = TableB.Col2
Your NSSet
approach is the best if you're not worried about the order of the objects, but then again, if you're not worried about the order, then why aren't you storing them in an NSSet
to begin with?
I wrote the answer below in 2009; in 2011, Apple added NSOrderedSet
to iOS 5 and Mac OS X 10.7. What had been an algorithm is now two lines of code:
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:yourArray];
NSArray *arrayWithoutDuplicates = [orderedSet array];
If you are worried about the order and you're running on iOS 4 or earlier, loop over a copy of the array:
NSArray *copy = [mutableArray copy];
NSInteger index = [copy count] - 1;
for (id object in [copy reverseObjectEnumerator]) {
if ([mutableArray indexOfObject:object inRange:NSMakeRange(0, index)] != NSNotFound) {
[mutableArray removeObjectAtIndex:index];
}
index--;
}
[copy release];
If you're looking specifically for a way to convert accented characters to non-accented characters, rather than a way to sort accented characters, with a little finagling, the String.localeCompare function can be manipulated to find the basic latin characters that match the extended ones. For example, you might want to produce a human friendly url slug from a page title. If so, you can do something like this:
var baseChars = [];_x000D_
for (var i = 97; i < 97 + 26; i++) {_x000D_
baseChars.push(String.fromCharCode(i));_x000D_
}_x000D_
_x000D_
//if needed, handle fancy compound characters_x000D_
baseChars = baseChars.concat('ss,aa,ae,ao,au,av,ay,dz,hv,lj,nj,oi,ou,oo,tz,vy'.split(','));_x000D_
_x000D_
function isUpperCase(c) { return c !== c.toLocaleLowerCase() }_x000D_
_x000D_
function toBaseChar(c, opts) {_x000D_
opts = opts || {};_x000D_
//if (!('nonAlphaChar' in opts)) opts.nonAlphaChar = '';_x000D_
//if (!('noMatchChar' in opts)) opts.noMatchChar = '';_x000D_
if (!('locale' in opts)) opts.locale = 'en';_x000D_
_x000D_
var cOpts = {sensitivity: 'base'};_x000D_
_x000D_
//exit early for any non-alphabetical character_x000D_
if (c.localeCompare('9', opts.locale, cOpts) <= 0) return opts.nonAlphaChar === undefined ? c : opts.nonAlphaChar;_x000D_
_x000D_
for (var i = 0; i < baseChars.length; i++) {_x000D_
var baseChar = baseChars[i];_x000D_
_x000D_
var comp = c.localeCompare(baseChar, opts.locale, cOpts);_x000D_
if (comp == 0) return (isUpperCase(c)) ? baseChar.toUpperCase() : baseChar;_x000D_
}_x000D_
_x000D_
return opts.noMatchChar === undefined ? c : opts.noMatchChar;_x000D_
}_x000D_
_x000D_
function latinify(str, opts) {_x000D_
return str.replace(/[^\w\s\d]/g, function(c) {_x000D_
return toBaseChar(c, opts);_x000D_
})_x000D_
}_x000D_
_x000D_
// Example:_x000D_
console.log(latinify('Ceština Tsehesenestsestotse Tshiven?a Emigliàn–Rumagnòl Slovenšcina Português Ti?ng Vi?t Straße'))_x000D_
_x000D_
// "Cestina Tsehesenestsestotse Tshivenda Emiglian–Rumagnol Slovenscina Portugues Tieng Viet Strasse"
_x000D_
This should perform quite well, but if further optimization were needed, a binary search could be used with localeCompare
as the comparator to locate the base character. Note that case is preserved, and options allow for either preserving, replacing, or removing characters that aren't alphabetical, or do not have matching latin characters they can be replaced with. This implementation is faster and more flexible, and should work with new characters as they are added. The disadvantage is that compound characters like '?' have to be handled specifically, if they need to be supported.
We can use the PHP cURL library to generate simple HTTP POST request. The following example shows you how to create a simple SOAP request using cURL.
Create the soap-server.php which write the SOAP request into soap-request.xml in web folder.
We can use the PHP cURL library to generate simple HTTP POST request. The following example shows you how to create a simple SOAP request using cURL.
Create the soap-server.php which write the SOAP request into soap-request.xml in web folder.
<?php
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$f = fopen("./soap-request.xml", "w");
fwrite($f, $HTTP_RAW_POST_DATA);
fclose($f);
?>
The next step is creating the soap-client.php which generate the SOAP request using the cURL library and send it to the soap-server.php URL.
<?php
$soap_request = "<?xml version=\"1.0\"?>\n";
$soap_request .= "<soap:Envelope xmlns:soap=\"http://www.w3.org/2001/12/soap-envelope\" soap:encodingStyle=\"http://www.w3.org/2001/12/soap-encoding\">\n";
$soap_request .= " <soap:Body xmlns:m=\"http://www.example.org/stock\">\n";
$soap_request .= " <m:GetStockPrice>\n";
$soap_request .= " <m:StockName>IBM</m:StockName>\n";
$soap_request .= " </m:GetStockPrice>\n";
$soap_request .= " </soap:Body>\n";
$soap_request .= "</soap:Envelope>";
$header = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: \"run\"",
"Content-length: ".strlen($soap_request),
);
$soap_do = curl_init();
curl_setopt($soap_do, CURLOPT_URL, "http://localhost/php-soap-curl/soap-server.php" );
curl_setopt($soap_do, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($soap_do, CURLOPT_TIMEOUT, 10);
curl_setopt($soap_do, CURLOPT_RETURNTRANSFER, true );
curl_setopt($soap_do, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($soap_do, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($soap_do, CURLOPT_POST, true );
curl_setopt($soap_do, CURLOPT_POSTFIELDS, $soap_request);
curl_setopt($soap_do, CURLOPT_HTTPHEADER, $header);
if(curl_exec($soap_do) === false) {
$err = 'Curl error: ' . curl_error($soap_do);
curl_close($soap_do);
print $err;
} else {
curl_close($soap_do);
print 'Operation completed without any errors';
}
?>
Enter the soap-client.php URL in browser to send the SOAP message. If success, Operation completed without any errors will be shown and the soap-request.xml will be created.
<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Body xmlns:m="http://www.example.org/stock">
<m:GetStockPrice>
<m:StockName>IBM</m:StockName>
</m:GetStockPrice>
</soap:Body>
</soap:Envelope>
Original - http://eureka.ykyuen.info/2011/05/05/php-send-a-soap-request-by-curl/
If you need direct access:
WScript.Arguments.Item(0)
WScript.Arguments.Item(1)
...
for me install Microsoft Visual C++ 2015 Redistributable Update 3 from https://www.microsoft.com/en-us/download/details.aspx?id=53587 solved it.
Open Notepad and write this
@echo off
:A
Cls
echo MESSENGER
set /p n=User:
set /p m=Message:
net send %n% %m%
Pause
Goto A
and then save as "Messenger.bat
" and close the Notepad
Step 1:
when you open that saved notepad file it will open as a file Messenger command prompt with this details.
Messenger
User:
after "User
" write the ip of the computer you want to contact and then press enter.
See .offset()
here in the jQuery doc. It gives the position relative to the document, not to the parent. You perhaps have .offset()
and .position()
confused. If you want the position in the window instead of the position in the document, you can subtract off the .scrollTop()
and .scrollLeft()
values to account for the scrolled position.
Here's an excerpt from the doc:
The .offset() method allows us to retrieve the current position of an element relative to the document. Contrast this with .position(), which retrieves the current position relative to the offset parent. When positioning a new element on top of an existing one for global manipulation (in particular, for implementing drag-and-drop), .offset() is the more useful.
To combine these:
var offset = $("selector").offset();
var posY = offset.top - $(window).scrollTop();
var posX = offset.left - $(window).scrollLeft();
You can try it here (scroll to see the numbers change): http://jsfiddle.net/jfriend00/hxRPQ/
Even if the generics problems are fixed in 1.3
the great thing about this method is it works on any class that has an isEmpty()
method! Not just Collections
!
For example it will work on String
as well!
/* Matches any class that has an <code>isEmpty()</code> method
* that returns a <code>boolean</code> */
public class IsEmpty<T> extends TypeSafeMatcher<T>
{
@Factory
public static <T> Matcher<T> empty()
{
return new IsEmpty<T>();
}
@Override
protected boolean matchesSafely(@Nonnull final T item)
{
try { return (boolean) item.getClass().getMethod("isEmpty", (Class<?>[]) null).invoke(item); }
catch (final NoSuchMethodException e) { return false; }
catch (final InvocationTargetException | IllegalAccessException e) { throw new RuntimeException(e); }
}
@Override
public void describeTo(@Nonnull final Description description) { description.appendText("is empty"); }
}
This simple program will list all the cases for version of jar namely
Manifest file not found
Map<String, String> jarsWithVersionFound = new LinkedHashMap<String, String>();
List<String> jarsWithNoManifest = new LinkedList<String>();
List<String> jarsWithNoVersionFound = new LinkedList<String>();
//loop through the files in lib folder
//pick a jar one by one and getVersion()
//print in console..save to file(?)..maybe later
File[] files = new File("path_to_jar_folder").listFiles();
for(File file : files)
{
String fileName = file.getName();
try
{
String jarVersion = new Jar(file).getVersion();
if(jarVersion == null)
jarsWithNoVersionFound.add(fileName);
else
jarsWithVersionFound.put(fileName, jarVersion);
}
catch(Exception ex)
{
jarsWithNoManifest.add(fileName);
}
}
System.out.println("******* JARs with versions found *******");
for(Entry<String, String> jarName : jarsWithVersionFound.entrySet())
System.out.println(jarName.getKey() + " : " + jarName.getValue());
System.out.println("\n \n ******* JARs with no versions found *******");
for(String jarName : jarsWithNoVersionFound)
System.out.println(jarName);
System.out.println("\n \n ******* JARs with no manifest found *******");
for(String jarName : jarsWithNoManifest)
System.out.println(jarName);
It uses the javaxt-core jar which can be downloaded from http://www.javaxt.com/downloads/
Just do:
echo substr($string, 0, -3);
You don't need to use a strlen
call, since, as noted in the substr docs:
If length is given and is negative, then that many characters will be omitted from the end of string
Save yourself a schizophrenic episode and use the Advanced Python scheduler: http://pythonhosted.org/APScheduler
The code is so simple:
from apscheduler.scheduler import Scheduler
sched = Scheduler()
sched.start()
def some_job():
print "Every 10 seconds"
sched.add_interval_job(some_job, seconds = 10)
....
sched.shutdown()
I'm pretty certain it is because the DbContext is not at all thread safe. So sharing the thing is never a good idea.
Attach onchange
event to the checkbox:
<input class="coupon_question" type="checkbox" name="coupon_question" value="1" onchange="valueChanged()"/>
<script type="text/javascript">
function valueChanged()
{
if($('.coupon_question').is(":checked"))
$(".answer").show();
else
$(".answer").hide();
}
</script>
The violation of the contract often means that the comparator is not providing the correct or consistent value when comparing objects. For example, you might want to perform a string compare and force empty strings to sort to the end with:
if ( one.length() == 0 ) {
return 1; // empty string sorts last
}
if ( two.length() == 0 ) {
return -1; // empty string sorts last
}
return one.compareToIgnoreCase( two );
But this overlooks the case where BOTH one and two are empty - and in that case, the wrong value is returned (1 instead of 0 to show a match), and the comparator reports that as a violation. It should have been written as:
if ( one.length() == 0 ) {
if ( two.length() == 0 ) {
return 0; // BOth empty - so indicate
}
return 1; // empty string sorts last
}
if ( two.length() == 0 ) {
return -1; // empty string sorts last
}
return one.compareToIgnoreCase( two );
Seems strange the intricate cable&restart solution steps ... The first time I've plugged the Android device to my Ubuntu (15.10) I've got Connect as: multimedia or camera options and in my Android Studio the device status was unauthorized. It wasn't until I choose between one of the options that I got in the Android device the PC authorization option. When you give the proper permissions in Android then the device status changed to online in Android Studio. Cheers
You should add then
function to instance. Promise
will recognize it as a thenable object with Promise.resolve
automatically
const asyncSymbol = Symbol();
class MyClass {
constructor() {
this.asyncData = null
}
then(resolve, reject) {
return (this[asyncSymbol] = this[asyncSymbol] || new Promise((innerResolve, innerReject) => {
this.asyncData = { a: 1 }
setTimeout(() => innerResolve(this.asyncData), 3000)
})).then(resolve, reject)
}
}
async function wait() {
const asyncData = await new MyClass();
alert('run 3s later')
alert(asyncData.a)
}
Try this:
$Date = $row['valdate']->format('d/m/Y'); // the result will 01/12/2015
NOTE: $row['valdate']
its a value date in the database
A more up to date answer for anyone else who comes across this:
(from https://www.jetbrains.com/help/idea/eclipse.html, §Auto-compilation; click for screenshots)
Compile automatically:
To enable automatic compilation, navigate to Settings/Preferences | Build, Execution, Deployment | Compiler and select the Build project automatically option
Show all errors in one place:
The Problems tool window appears if the Make project automatically option is enabled in the Compiler settings. It shows a list of problems that were detected on project compilation.
Use the Eclipse compiler: This is actually bundled in IntelliJ. It gives much more useful error messages, in my opinion, and, according to this blog, it's much faster since it was designed to run in the background of an IDE and uses incremental compilation.
While Eclipse uses its own compiler, IntelliJ IDEA uses the javac compiler bundled with the project JDK. If you must use the Eclipse compiler, navigate to Settings/Preferences | Build, Execution, Deployment | Compiler | Java Compiler and select it... The biggest difference between the Eclipse and javac compilers is that the Eclipse compiler is more tolerant to errors, and sometimes lets you run code that doesn't compile.
NSDate *todaysDate = [NSDate new];
NSDateFormatter *formatter = [NSDateFormatter new];
[formatter setDateFormat:@"MM-dd-yyyy HH:mm:ss"];
NSString *strDateTime = [formatter stringFromDate:todaysDate];
NSString *strFileName = [NSString stringWithFormat:@"/Users/Shared/Recording_%@.mov",strDateTime];
NSLog(@"filename:%@",strFileName);
Log will be : filename:/Users/Shared/Recording_06-28-2016 12:53:26.mov
According to apple doc:
File-Sharing Support
File-sharing support lets apps make user data files available in iTunes 9.1 and later. An app that declares its support for file sharing makes the contents of its /Documents directory available to the user. The user can then move files in and out of this directory as needed from iTunes. This feature does not allow your app to share files with other apps on the same device; that behavior requires the pasteboard or a document interaction controller object.To enable file sharing for your app, do the following:
Add the UIFileSharingEnabled key to your app’s Info.plist file, and set the value of the key to YES. (The actual key name is "Application supports iTunes file sharing")
Put whatever files you want to share in your app’s Documents directory.
When the device is plugged into the user’s computer, iTunes displays a File Sharing section in the Apps tab of the selected device.
The user can add files to this directory or move files to the desktop.
Apps that support file sharing should be able to recognize when files have been added to the Documents directory and respond appropriately. For example, your app might make the contents of any new files available from its interface. You should never present the user with the list of files in this directory and ask them to decide what to do with those files.
For additional information about the UIFileSharingEnabled key, see Information Property List Key Reference.
You can use java Custom Class for the purpose of sorting.
hi see the following sample code of xml file.
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout
android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:id="@+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dip"
android:text="@+id/TextView01" >
</TextView>
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dip"
android:text="@+id/TextView01" >
</TextView>
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dip"
android:text="@+id/TextView01" >
</TextView>
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dip"
android:text="@+id/TextView01" >
</TextView>
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dip"
android:text="@+id/TextView01" >
</TextView>
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dip"
android:text="@+id/TextView01" >
</TextView>
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dip"
android:text="@+id/TextView01" >
</TextView>
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dip"
android:text="@+id/TextView01" >
</TextView>
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dip"
android:text="@+id/TextView01" >
</TextView>
</LinearLayout>
</RelativeLayout>
</ScrollView>
Yes, with -Xmx
you can configure more memory for your JVM.
To be sure that you don't leak or waste memory. Take a heap dump and use the Eclipse Memory Analyzer to analyze your memory consumption.
If your data is in a Pandas DataFrame, you can use Seaborn's heatmap
function to create your desired plot.
import seaborn as sns
Var_Corr = df.corr()
# plot the heatmap and annotation on it
sns.heatmap(Var_Corr, xticklabels=Var_Corr.columns, yticklabels=Var_Corr.columns, annot=True)
From the question, it looks like the data is in a NumPy array. If that array has the name numpy_data
, before you can use the step above, you would want to put it into a Pandas DataFrame using the following:
import pandas as pd
df = pd.DataFrame(numpy_data)
Nothing compares to extjs in terms of community size and presence on StackOverflow. Despite previous controversy, Ext JS now has a GPLv3 open source license. Its learning curve is long, but it can be quite rewarding once learned. Ext JS lacks a Material Design theme, and the team has repeatedly refused to release the source code on GitHub. For mobile, one must use the separate Sencha Touch library.
Have in mind also that,
large JavaScript libraries, such as YUI, have been receiving less attention from the community. Many developers today look at large JavaScript libraries as walled gardens they don’t want to be locked into.
-- Announcement of YUI development being ceased
That said, below are a number of Ext JS alternatives currently available.
Blueprint is a React-based UI toolkit developed by big data analytics company Palantir in TypeScript, and "optimized for building complex data-dense interfaces for desktop applications". Actively developed on GitHub as of May 2019, with comprehensive documentation. Components range from simple (chips, toast, icons) to complex (tree, data table, tag input with autocomplete, date range picker. No accordion or resizer.
Blueprint targets modern browsers (Chrome, Firefox, Safari, IE 11, and Microsoft Edge) and is licensed under a modified Apache license.
Sandbox / demo • GitHub • Docs
Webix - an advanced, easy to learn, mobile-friendly, responsive and rich free&open source JavaScript UI components library. Webix spun off from DHTMLX Touch (a project with 8 years of development behind it - see below) and went on to become a standalone UI components framework. The GPL3 edition allows commercial use and lets non-GPL applications using Webix keep their license, e.g. MIT, via a license exemption for FLOSS. Webix has 55 UI widgets, including trees, grids, treegrids and charts. Funding comes from a commercial edition with some advanced widgets (Pivot, Scheduler, Kanban, org chart etc.). Webix has an extensive list of free and commercial widgets, and integrates with most popular frameworks (React, Vue, Meteor, etc) and UI components.
Skins look modern, and include a Material Design theme. The Touch theme also looks quite Material Design-ish. See also the Skin Builder.
Minimal GitHub presence, but includes the library code, and the documentation (which still needs major improvements). Webix suffers from a having a small team and a lack of marketing. However, they have been responsive to user feedback, both on GitHub and on their forum.
The library was lean (128Kb gzip+minified for all 55 widgets as of ~2015), faster than ExtJS, dojo and others, and the design is pleasant-looking. The current version of Webix (v6, as of Nov 2018) got heavier (400 - 676kB minified but NOT gzipped).
The demos on Webix.com look and function great. The developer, XB Software, uses Webix in solutions they build for paying customers, so there's likely a good, funded future ahead of it.
Webix aims for backwards compatibility down to IE8, and as a result carries some technical debt.
Wikipedia • GitHub • Playground/sandbox • Admin dashboard demo • Demos • Widget samples
react-md - MIT-licensed Material Design UI components library for React. Responsive, accessible. Implements components from simple (buttons, cards) to complex (sortable tables, autocomplete, tags input, calendars). One lead author, ~1900 GitHub stars.
kendo - jQuery-based UI toolkit with 40+ basic open-source widgets, plus commercial professional widgets (grids, trees, charts etc.). Responsive&mobile support. Works with Bootstrap and AngularJS. Modern, with Material Design themes. The documentation is available on GitHub, which has enabled numerous contributions from users (4500+ commits, 500+ PRs as of Jan 2015).
Well-supported commercially, claiming millions of developers, and part of a large family of developer tools. Telerik has received many accolades, is a multi-national company (Bulgaria, US), was acquired by Progress Software, and is a thought leader.
A Kendo UI Professional developer license costs $700 and posting access to most forums is conditioned upon having a license or being in the trial period.
[Wikipedia] • GitHub/Telerik • Demos • Playground • Tools
OpenUI5 - jQuery-based UI framework with 180 widgets, Apache 2.0-licensed and fully-open sourced and funded by German software giant SAP SE.
The community is much larger than that of Webix, SAP is hiring developers to grow OpenUI5, and they presented OpenUI5 at OSCON 2014.
The desktop themes are rather lackluster, but the Fiori design for web and mobile looks clean and neat.
Wikipedia • GitHub • Mobile-first controls demos • Desktop controls demos • SO
DHTMLX - JavaScript library for building rich Web and Mobile apps. Looks most like ExtJS - check the demos. Has been developed since 2005 but still looks modern. All components except TreeGrid are available under GPLv2 but advanced features for many components are only available in the commercial PRO edition - see for example the tree. Claims to be used by many Fortune 500 companies.
Minimal presence on GitHub (the main library code is missing) and StackOverflow but active forum. The documentation is not available on GitHub, which makes it difficult to improve by the community.
Polymer, a Web Components polyfill, plus Polymer Paper, Google's implementation of the Material design. Aimed at web and mobile apps. Doesn't have advanced widgets like trees or even grids but the controls it provides are mobile-first and responsive. Used by many big players, e.g. IBM or USA Today.
Ant Design claims it is "a design language for background applications", influenced by "nature" and helping designers "create low-entropy atmosphere for developer team". That's probably a poor translation from Chinese for "UI components for enterprise web applications". It's a React UI library written in TypeScript, with many components, from simple (buttons, cards) to advanced (autocomplete, calendar, tag input, table).
The project was born in China, is popular with Chinese companies, and parts of the documentation are available only in Chinese. Quite popular on GitHub, yet it makes the mistake of splitting the community into Chinese and English chat rooms. The design looks Material-ish, but fonts are small and the information looks lost in a see of whitespace.
PrimeUI - collection of 45+ rich widgets based on jQuery UI. Apache 2.0 license. Small GitHub community. 35 premium themes available.
qooxdoo - "a universal JavaScript framework with a coherent set of individual components", developed and funded by German hosting provider 1&1 (see the contributors, one of the world's largest hosting companies. GPL/EPL (a business-friendly license).
Mobile themes look modern but desktop themes look old (gradients).
Wikipedia • GitHub • Web/Mobile/Desktop demos • Widgets Demo browser • Widget browser • SO • Playground • Community
jQuery UI - easy to pick up; looks a bit dated; lacks advanced widgets. Of course, you can combine it with independent widgets for particular needs, e.g. trees or other UI components, but the same can be said for any other framework.
angular + Angular UI. While Angular is backed by Google, it's being radically revamped in the upcoming 2.0 version, and "users will need to get to grips with a new kind of architecture. It's also been confirmed that there will be no migration path from Angular 1.X to 2.0". Moreover, the consensus seems to be that Angular 2 won't really be ready for use until a year or two from now. Angular UI has relatively few widgets (no trees, for example).
DojoToolkit and their powerful Dijit set of widgets. Completely open-sourced and actively developed on GitHub, but development is now (Nov 2018) focused on the new dojo.io framework, which has very few basic widgets. BSD/AFL license. Development started in 2004 and the Dojo Foundation is being sponsored by IBM, Google, and others - see Wikipedia. 7500 questions here on SO.
Themes look desktop-oriented and dated - see the theme tester in dijit. The official theme previewer is broken and only shows "Claro". A Bootstrap theme exists, which looks a lot like Bootstrap, but doesn't use Bootstrap classes. In Jan 2015, I started a thread on building a Material Design theme for Dojo, which got quite popular within the first hours. However, there are questions regarding building that theme for the current Dojo 1.10 vs. the next Dojo 2.0. The response to that thread shows an active and wide community, covering many time zones.
Unfortunately, Dojo has fallen out of popularity and fewer companies appear to use it, despite having (had?) a strong foothold in the enterprise world. In 2009-2012, its learning curve was steep and the documentation needed improvements; while the documentation has substantially improved, it's unclear how easy it is to pick up Dojo nowadays.
With a Material Design theme, Dojo (2.0?) might be the killer UI components framework.
Enyo - front-end library aimed at mobile and TV apps (e.g. large touch-friendly controls). Developed by LG Electronix and Apache-licensed on GitHub.
The radical Cappuccino - Objective-J (a superset of JavaScript) instead of HTML+CSS+DOM
Mochaui, MooTools UI Library User Interface Library. <300 GitHub stars.
CrossUI - cross-browser JS framework to develop and package the exactly same code and UI into Web Apps, Native Desktop Apps (Windows, OS X, Linux) and Mobile Apps (iOS, Android, Windows Phone, BlackBerry). Open sourced LGPL3. Featured RAD tool (form builder etc.). The UI looks desktop-, not web-oriented. Actively developed, small community. No presence on GitHub.
ZinoUI - simple widgets. The DataTable, for instance, doesn't even support sorting.
Wijmo - good-looking commercial widgets, with old (jQuery UI) widgets open-sourced on GitHub (their development stopped in 2013). Developed by ComponentOne, a division of GrapeCity. See Wijmo Complete vs. Open.
CxJS - commercial JS framework based on React, Babel and webpack offering form elements, form validation, advanced grid control, navigational elements, tooltips, overlays, charts, routing, layout support, themes, culture dependent formatting and more.
Widgets - Demo Apps - Examples - GitHub
SproutCore - developed by Apple for web applications with native performance, handling large data sets on the client. Powers iCloud.com. Not intended for widgets.
Wakanda: aimed at business/enterprise web apps - see What is Wakanda?. Architecture:
Wakanda Application Framework (datasource layer + browser-based interface widgets) that helps with browser and device compatibility across desktop and mobile
Wakanda is highly integrated, includes a ton of features out of the box, but has a very small GitHub community and SO presence.
Servoy - "a cross platform frontend development and deployment environment for SQL databases". Boasts a "full WYSIWIG (What You See Is What You Get) UI designer for HTML5 with built-in data-binding to back-end services", responsive design, support for HTML6 Web Components, Websockets and mobile platforms. Written in Java and generates JavaScript code using various JavaBeans.
SmartClient/SmartGWT - mobile and cross-browser HTML5 UI components combined with a Java server. Aimed at building powerful business apps - see demos.
Vaadin - full-stack Java/GWT + JavaScript/HTML3 web app framework
Backbase - portal software
Shiny - front-end library on top R, with visualization, layout and control widgets
ZKOSS: Java+jQuery+Bootstrap framework for building enterprise web and mobile apps.
These libraries don't implement complex widgets such as tables with sorting/filtering, autocompletes, or trees.
Foundation for Apps - responsive front-end framework on top of AngularJS; more of a grid/layout/navigation library
UI Kit - similar to Bootstrap, with fewer widgets, but with official off-canvas.
Using the canvas elements allows for complete control over the UI, and great cross-browser compatibility, but comes at the cost of missing native browser functionality, e.g. page search via Ctrl/Cmd+F.
process.terminate() doesn't work when using shell=True
. This answer will help you.
I use the current working directory ./
when building several apps off the same domain:
<base href="./">
On a side note, I use .htaccess
to assist with my routing on page reload:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* index.html [L]
for me "I" was capital in "Images". which also angular-cli didn't like. so it is also case sensitive.
Some web servers like IIS don't have problem with that, if angular application is hosted in IIS, case sensitive is not a problem.
The problem you run into when setting width to 50% is the rounding of subpixels. If the width of your container is i.e. 99 pixels, a width of 50% can result in 2 containers of 50 pixels each.
Using float is probably easiest, and not such a bad idea. See this question for more details on how to fix the problem then.
If you don't want to use float, try using a width of 49%. This will work cross-browser as far as I know, but is not pixel-perfect..
html:
<div id="a">A</div>
<div id="b">B</div>
css:
#a, #b {
width: 49%;
display: inline-block;
}
#a {background-color: red;}
#b {background-color: blue;}
There are pretty good solutions here but they don't help to understand why the problem actually happens.
But it's very simple, you just need to understand how logic OR ||
works. Whole expression will evaluate to true
when either of its sides evaluates to true
.
Now let's look at your case. Assume whole details.Payment[0].Status
is Status
and it's a number for brevity. Then we have Status != 0 || Status != 1 || ...
.
Imagine Status = 1
:
( 1 != 0 || 1 != 1 || ... ) =
( true || false || ... ) =
( true || ... ) = ... = true
Now imagine Status = 0
:
( 0 != 0 || 0 != 1 || ... ) =
( false || true || ... ) =
( true || ... ) = ... = true
As you it doesn't even matter what you have as ...
as logical OR
of first two expressions gives you true
which will be the result of the full expression.
What you actually need is logical AND
&&
that will be true only if both its sides are true
.
Here is a nice way to display the information that you want:
SELECT B.table_catalog as 'Database_Name',
B.table_name as 'Table_Name',
stuff((select ', ' + A.column_name
from INFORMATION_SCHEMA.COLUMNS A
where A.Table_name = B.Table_Name
FOR XML PATH(''),TYPE).value('(./text())[1]','NVARCHAR(MAX)')
, 1, 2, '') as 'Columns'
FROM INFORMATION_SCHEMA.COLUMNS B
WHERE B.TABLE_NAME like '%%'
AND B.COLUMN_NAME like '%%'
GROUP BY B.Table_Catalog, B.Table_Name
Order by 1 asc
Add anything between either '%%' in the main select to narrow down what tables and/or column names you want.
Look this:
List<Client> result = clients
.stream()
.filter(c ->
(users.stream().map(User::getName).collect(Collectors.toList())).contains(c.getName()))
.collect(Collectors.toList());
I would turn it into a json object, with the added benefit of keeping the keys if you are using an associative array:
$stringRepresentation= json_encode($arr);
There's so many answers to this these days:
foreach-object -parallel
as an alternative for #4Here's workflows with literally a foreach -parallel:
workflow work {
foreach -parallel ($i in 1..3) {
sleep 5
"$i done"
}
}
work
3 done
1 done
2 done
Or a workflow with a parallel block:
function sleepfor($time) { sleep $time; "sleepfor $time done"}
workflow work {
parallel {
sleepfor 3
sleepfor 2
sleepfor 1
}
'hi'
}
work
sleepfor 1 done
sleepfor 2 done
sleepfor 3 done
hi
Here's an api with runspaces example:
$a = [PowerShell]::Create().AddScript{sleep 5;'a done'}
$b = [PowerShell]::Create().AddScript{sleep 5;'b done'}
$c = [PowerShell]::Create().AddScript{sleep 5;'c done'}
$r1,$r2,$r3 = ($a,$b,$c).begininvoke() # run in background
$a.EndInvoke($r1); $b.EndInvoke($r2); $c.EndInvoke($r3) # wait
($a,$b,$c).streams.error # check for errors
($a,$b,$c).dispose() # clean
a done
b done
c done
Just use this constructor of List<T>
. It accepts any IEnumerable<T>
as an argument.
string[] arr = ...
List<string> list = new List<string>(arr);
On Linux (at least) you can set CHROME_LOG_FILE in the environment to have chrome write a log of the Console activity to the named file each time it runs. The log is overwritten every time chrome starts. This way, if you have an automated session that runs chrome, you don't have a to change the way chrome is started, and the log is there after the session ends.
export CHROME_LOG_FILE=chrome.log
This simplest safe & general solution is probably:
find -mindepth 1 -maxdepth 1 -print0 | xargs -0 rm -rf
// Create Customer class as follows:
export default class Customer {}
// Import the class
// no need for .js extension in path cos gets inferred automatically
import Customer from './path/to/Customer';
// or
const Customer = require('./path/to/Customer')
// Use the class
var customer = new Customer();
var name = customer.getName();
Its very simple just write below code:
String s = "http://www.google.com";
Desktop desktop = Desktop.getDesktop();
desktop.browse(URI.create(s));
or if you don't want to load URL then just write your browser name into string values like,
String s = "chrome";
Desktop desktop = Desktop.getDesktop();
desktop.browse(URI.create(s));
it will open browser automatically with empty URL after executing a program
There's no difference, ==
is a synonym for =
(for the C/C++ people, I assume). See here, for example.
You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.
As Requested By User Erickson, I Post My comment As Answer:
I have done some more testing with IE8, IE9, FF14, Opera11, Chrome20 and Tomcat 6.0.32 (fresh installation), Jersey 1.13 on the server side. I used the jQuery function $.getJson and JSONP. Results: All Browsers allowed up to around 5400 chars. FF and IE9 did up to around 6200 chars. Everything above returned "400 Bad request". I did not further investigate what was responsible for the 400. I was fine with the maximum I found, because I needed around 2000 chars in my case.
Working Solution :
For Resize image with size lower then 100Kb
WriteableBitmap bitmap = new WriteableBitmap(140,140);
bitmap.SetSource(dlg.File.OpenRead());
image1.Source = bitmap;
Image img = new Image();
img.Source = bitmap;
WriteableBitmap i;
do
{
ScaleTransform st = new ScaleTransform();
st.ScaleX = 0.3;
st.ScaleY = 0.3;
i = new WriteableBitmap(img, st);
img.Source = i;
} while (i.Pixels.Length / 1024 > 100);
More Reference at http://net4attack.blogspot.com/
Because break can only be used inside a loop. It is used to break out of a loop (stop the loop).
Update: since the time I answered this there has been a lot of work on this look at Apache Arrow for a better read and write of parquet. Also: http://wesmckinney.com/blog/python-parquet-multithreading/
There is a python parquet reader that works relatively well: https://github.com/jcrobak/parquet-python
It will create python objects and then you will have to move them to a Pandas DataFrame so the process will be slower than pd.read_csv
for example.
I had the same issue when my server free disk space available was 0
You can use the command (there must be ample space for the mysql files)
REPAIR TABLE `<table name>`;
for repairing individual tables
There are 2 options to find matching text; string.match
or string.find
.
Both of these perform a regex search on the string to find matches.
string.find()
string.find(subject string, pattern string, optional start position, optional plain flag)
Returns the startIndex
& endIndex
of the substring found.
The plain
flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger)
being interpreted as a regex capture group matching for tiger
, it instead looks for (tiger)
within a string.
Going the other way, if you want to regex match but still want literal special characters (such as .()[]+-
etc.), you can escape them with a percentage; %(tiger%)
.
You will likely use this in combination with string.sub
str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end
string.match()
string.match(s, pattern, optional index)
Returns the capture groups found.
str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end
ASCII was indeed originally conceived as a 7-bit code. This was done well before 8-bit bytes became ubiquitous, and even into the 1990s you could find software that assumed it could use the 8th bit of each byte of text for its own purposes ("not 8-bit clean"). Nowadays people think of it as an 8-bit coding in which bytes 0x80 through 0xFF have no defined meaning, but that's a retcon.
There are dozens of text encodings that make use of the 8th bit; they can be classified as ASCII-compatible or not, and fixed- or variable-width. ASCII-compatible means that regardless of context, single bytes with values from 0x00 through 0x7F encode the same characters that they would in ASCII. You don't want to have anything to do with a non-ASCII-compatible text encoding if you can possibly avoid it; naive programs expecting ASCII tend to misinterpret them in catastrophic, often security-breaking fashion. They are so deprecated nowadays that (for instance) HTML5 forbids their use on the public Web, with the unfortunate exception of UTF-16. I'm not going to talk about them any more.
A fixed-width encoding means what it sounds like: all characters are encoded using the same number of bytes. To be ASCII-compatible, a fixed-with encoding must encode all its characters using only one byte, so it can have no more than 256 characters. The most common such encoding nowadays is Windows-1252, an extension of ISO 8859-1.
There's only one variable-width ASCII-compatible encoding worth knowing about nowadays, but it's very important: UTF-8, which packs all of Unicode into an ASCII-compatible encoding. You really want to be using this if you can manage it.
As a final note, "ASCII" nowadays takes its practical definition from Unicode, not its original standard (ANSI X3.4-1968), because historically there were several dozen variations on the ASCII 127-character repertoire -- for instance, some of the punctuation might be replaced with accented letters to facilitate the transmission of French text. Nowadays all of those variations are obsolescent, and when people say "ASCII" they mean that the bytes with value 0x00 through 0x7F encode Unicode codepoints U+0000 through U+007F. This will probably only matter to you if you ever find yourself writing a technical standard.
If you're interested in the history of ASCII and the encodings that preceded it, start with the paper "The Evolution of Character Codes, 1874-1968" (samizdat copy at http://falsedoor.com/doc/ascii_evolution-of-character-codes.pdf) and then chase its references (many of which are not available online and may be hard to find even with access to a university library, I regret to say).
here is a test script to run on your server to see what is reliabel.
<?php
$host = gethostname();
$ip = gethostbyname($host);
echo "gethostname and gethostbyname: $host at $ip<br>";
$server = $_SERVER['SERVER_ADDR'];
echo "_SERVER[SERVER_ADDR]: $server<br>";
$my_current_ip=exec("ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'");
echo "exec ifconfig ... : $my_current_ip<br>";
$external_ip = file_get_contents("http://ipecho.net/plain");
echo "get contents ipecho.net: $external_ip<br>";
?>
The only different option in there is using fiel_get_contents rather than curl for the extrernal website lookup.
This is the result of hitting the web page on a shared hosting, free account. (actual server name and IP changed)
gethostname and gethostbyname: freesites.servercluster.com at 345.27.413.51
_SERVER[SERVER_ADDR]: 127.0.0.7
exec ifconfig ... :
get contents ipecho.net: 345.27.413.51
Why needed this? Decided to point A record at server to see if it opens the web page. Later ran script to save ip and update on ghost site on same server to lookup IP and alert if changed.
In this case, good results optained by:
gethostname() &
gethostbyname($host)
or
file_get_contents("http://ipecho.net/plain")
This should do the trick.
foo = somevalue
previous = next_ = None
l = len(objects)
for index, obj in enumerate(objects):
if obj == foo:
if index > 0:
previous = objects[index - 1]
if index < (l - 1):
next_ = objects[index + 1]
Here's the docs on the enumerate
function.
Encode each value in the list to a string:
[x.encode('UTF8') for x in EmployeeList]
You need to pick a valid encoding; don't use str()
as that'll use the system default (for Python 2 that's ASCII) which will not encode all possible codepoints in a Unicode value.
UTF-8 is capable of encoding all of the Unicode standard, but any codepoint outside the ASCII range will lead to multiple bytes per character.
However, if all you want to do is test for a specific string, test for a unicode string and Python won't have to auto-encode all values when testing for that:
u'1001' in EmployeeList.values()
Find can be used to print out the file-size in bytes with %s as a printf. %h/%f prints the directory prefix and filename respectively. \n forces a newline.
Example
find . -size +10000k -printf "%h/%f,%s\n"
Output
./DOTT/extract/DOTT/TENTACLE.001,11358470
./DOTT/Day Of The Tentacle.nrg,297308316
./DOTT/foo.iso,297001116
I had a similar problem with the jQuery Thickbox (a lightbox-style dialog widget). The way I fixed my problem is as follows:
function setFocusThickboxIframe() {
var iframe = $("#TB_iframeContent")[0];
iframe.contentWindow.focus();
}
$(document).ready(function(){
$("#id_cmd_open").click(function(){
/*
run thickbox code here to open lightbox,
like tb_show("google this!", "http://www.google.com");
*/
setTimeout(setFocusThickboxIframe, 100);
return false;
});
});
The code doesn't seem to work without the setTimeout(). Based on my testing, it works in Firefox3.5, Safari4, Chrome4, IE7 and IE6.
I ran into a similar issue when building a custom pagination for a site I am working on.
The global variable I created in functions.php was defined and set to 0. I could output this value in my javascript no problem using the method @Karsten outlined above. The issue was with updating the global variable that I initially set to 0 inside the PHP file.
Here is my workaround (hacky? I know!) but after struggling for an hour on a tight deadline the following works:
Inside archive-episodes.php:
<script>
// We define the variable and update it in a php
// function defined in functions.php
var totalPageCount;
</script>
Inside functions.php
<?php
$totalPageCount = WP_Query->max_num_pages; // In my testing scenario this number is 8.
echo '<script>totalPageCount = $totalPageCount;</script>';
?>
To keep it simple, I was outputting the totalPageCount variable in an $ajax.success callback via alert.
$.ajax({
url: ajaxurl,
type: 'POST',
data: {"action": "infinite_scroll", "page_no": pageNumber, "posts_per_page": numResults},
beforeSend: function() {
$(".ajaxLoading").show();
},
success: function(data) {
//alert("DONE LOADING EPISODES");
$(".ajaxLoading").hide();
var $container = $("#episode-container");
if(firstRun) {
$container.prepend(data);
initMasonry($container);
ieMasonryFix();
initSearch();
} else {
var $newItems = $(data);
$container.append( $newItems ).isotope( 'appended', $newItems );
}
firstRun = false;
addHoverState();
smartResize();
alert(totalEpiPageCount); // THIS OUTPUTS THE CORRECT PAGE TOTAL
}
Be it as it may, I hope this helps others! If anyone has a "less-hacky" version or best-practise example I'm all ears.
Here's the link I used as a guide. Hope this helps!
Converting HTML to PDF using ITextSharp
protected void Page_Load(object sender, EventArgs e)
{
try
{
string strHtml = string.Empty;
//HTML File path -http://aspnettutorialonline.blogspot.com/
string htmlFileName = Server.MapPath("~") + "\\files\\" + "ConvertHTMLToPDF.htm";
//pdf file path. -http://aspnettutorialonline.blogspot.com/
string pdfFileName = Request.PhysicalApplicationPath + "\\files\\" + "ConvertHTMLToPDF.pdf";
//reading html code from html file
FileStream fsHTMLDocument = new FileStream(htmlFileName, FileMode.Open, FileAccess.Read);
StreamReader srHTMLDocument = new StreamReader(fsHTMLDocument);
strHtml = srHTMLDocument.ReadToEnd();
srHTMLDocument.Close();
strHtml = strHtml.Replace("\r\n", "");
strHtml = strHtml.Replace("\0", "");
CreatePDFFromHTMLFile(strHtml, pdfFileName);
Response.Write("pdf creation successfully with password -http://aspnettutorialonline.blogspot.com/");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
public void CreatePDFFromHTMLFile(string HtmlStream, string FileName)
{
try
{
object TargetFile = FileName;
string ModifiedFileName = string.Empty;
string FinalFileName = string.Empty;
/* To add a Password to PDF -http://aspnettutorialonline.blogspot.com/ */
TestPDF.HtmlToPdfBuilder builder = new TestPDF.HtmlToPdfBuilder(iTextSharp.text.PageSize.A4);
TestPDF.HtmlPdfPage first = builder.AddPage();
first.AppendHtml(HtmlStream);
byte[] file = builder.RenderPdf();
File.WriteAllBytes(TargetFile.ToString(), file);
iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(TargetFile.ToString());
ModifiedFileName = TargetFile.ToString();
ModifiedFileName = ModifiedFileName.Insert(ModifiedFileName.Length - 4, "1");
string password = "password";
iTextSharp.text.pdf.PdfEncryptor.Encrypt(reader, new FileStream(ModifiedFileName, FileMode.Append), iTextSharp.text.pdf.PdfWriter.STRENGTH128BITS, password, "", iTextSharp.text.pdf.PdfWriter.AllowPrinting);
//http://aspnettutorialonline.blogspot.com/
reader.Close();
if (File.Exists(TargetFile.ToString()))
File.Delete(TargetFile.ToString());
FinalFileName = ModifiedFileName.Remove(ModifiedFileName.Length - 5, 1);
File.Copy(ModifiedFileName, FinalFileName);
if (File.Exists(ModifiedFileName))
File.Delete(ModifiedFileName);
}
catch (Exception ex)
{
throw ex;
}
}
You can download the sample file. Just place the html
you want to convert in the files
folder and run. It will automatically generate the pdf file and place it in the same folder. But in your case, you can specify your html path in the htmlFileName
variable.
response[0]
is not defined, check if it is defined and then check for its property title.
if(typeof response[0] !== 'undefined' && typeof response[0].title !== 'undefined'){
//Do something
}
This should be faster than iterating and will work regardless of shape.
numpy.isnan(myarray).any()
Edit: 30x faster:
import timeit
s = 'import numpy;a = numpy.arange(10000.).reshape((100,100));a[10,10]=numpy.nan'
ms = [
'numpy.isnan(a).any()',
'any(numpy.isnan(x) for x in a.flatten())']
for m in ms:
print " %.2f s" % timeit.Timer(m, s).timeit(1000), m
Results:
0.11 s numpy.isnan(a).any()
3.75 s any(numpy.isnan(x) for x in a.flatten())
Bonus: it works fine for non-array NumPy types:
>>> a = numpy.float64(42.)
>>> numpy.isnan(a).any()
False
>>> a = numpy.float64(numpy.nan)
>>> numpy.isnan(a).any()
True
Although I am commenting late. But I have used this method to do the job. Here when I am running my spring application I am providing the application yaml file via -Dspring.config.location=file:/location-to-file/config-server-vault-application.yml
which contains all of my properties
config-server-vault-application.yml
***********************************
server:
port: 8888
ssl:
trust-store: /trust-store/config-server-trust-store.jks
trust-store-password: config-server
trust-store-type: pkcs12
************************************
Java Code
************************************
@SpringBootApplication
public class ConfigServerApplication {
public static void main(String[] args) throws IOException {
setUpTrustStoreForApplication();
SpringApplication.run(ConfigServerApplication.class, args);
}
private static void setUpTrustStoreForApplication() throws IOException {
YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
List<PropertySource<?>> applicationYamlPropertySource = loader.load(
"config-application-properties", new UrlResource(System.getProperty("spring.config.location")));
Map<String, Object> source = ((MapPropertySource) applicationYamlPropertySource.get(0)).getSource();
System.setProperty("javax.net.ssl.trustStore", source.get("server.ssl.trust-store").toString());
System.setProperty("javax.net.ssl.trustStorePassword", source.get("server.ssl.trust-store-password").toString());
}
}
Updates from 2018 Laravel release(5.7) documentation with some more url() functions and it's usage.
Question: To get the site's URL in Laravel?
This is kind of a general question, so we can split it.
1. Accessing The Base URL
// Get the base URL.
echo url('');
// Get the app URL from configuration which we set in .env file.
echo config('app.url');
2. Accessing The Current URL
// Get the current URL without the query string.
echo url()->current();
// Get the current URL including the query string.
echo url()->full();
// Get the full URL for the previous request.
echo url()->previous();
3. URLs For Named Routes
// http://example.com/home
echo route('home');
4. URLs To Assets(Public)
// Get the URL to the assets, mostly the base url itself.
echo asset('');
5. File URLs
use Illuminate\Support\Facades\Storage;
$url = Storage::url('file.jpg'); // stored in /storage/app/public
echo url($url);
Each of these methods may also be accessed via the URL facade:
use Illuminate\Support\Facades\URL;
echo URL::to(''); // Base URL
echo URL::current(); // Current URL
How to call these Helper functions from blade Template(Views) with usage.
// http://example.com/login
{{ url('/login') }}
// http://example.com/css/app.css
{{ asset('css/app.css') }}
// http://example.com/login
{{ route('login') }}
// usage
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
<!-- Login link -->
<a class="nav-link" href="{{ route('login') }}">Login</a>
<!-- Login Post URL -->
<form method="POST" action="{{ url('/login') }}">
function round(num,dec)
{
num = Math.round(num+'e'+dec)
return Number(num+'e-'+dec)
}
//Round to a decimal of your choosing:
round(1.3453,2)
If you are going to use any DDOS provider like Akamai, they have a maximum limitation of 8k in the response header size. So essentially try to limit your response header size below 8k.
Php will evaluate what you wrote between the [] brackets.
$foo = array('eins', 'zwei', 'apples', 'oranges');
var_dump($foo[3-1]);
Will produce string(6) "apples"
, because it returns $foo[2].
If you want that as a string, put inverted commas around it.
For those interested, this is code for creating SHA-256 hash using sjcl
:
import sjcl from 'sjcl'
const myString = 'Hello'
const myBitArray = sjcl.hash.sha256.hash(myString)
const myHash = sjcl.codec.hex.fromBits(myBitArray)
Use the helper classes VisualTreeHelper
or LogicalTreeHelper
depending on which tree you're interested in. They both provide methods for getting the children of an element (although the syntax differs a little). I often use these classes for finding the first occurrence of a specific type, but you could easily modify it to find all objects of that type:
public static DependencyObject FindInVisualTreeDown(DependencyObject obj, Type type)
{
if (obj != null)
{
if (obj.GetType() == type)
{
return obj;
}
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject childReturn = FindInVisualTreeDown(VisualTreeHelper.GetChild(obj, i), type);
if (childReturn != null)
{
return childReturn;
}
}
}
return null;
}
Also pay attention to the object type of your numpy array, converting it using .astype('uint8')
resolved the issue for me.
I say "star-args" and Python people seem to know what i mean.
**
is trickier - I think just "qargs" since it is usually used as **kw
or **kwargs
I would like to point out over here that Overloading in PHP has a completely different meaning as compared to other programming languages. A lot of people have said that overloading isnt supported in PHP and by the conventional definition of overloading, yes that functionality isnt explicitly available.
However, the correct definition of overloading in PHP is completely different.
In PHP overloading refers to dynamically creating properties and methods using magic methods like __set() and __get(). These overloading methods are invoked when interacting with methods or properties that are not accessible or not declared.
Here is a link from the PHP manual : http://www.php.net/manual/en/language.oop5.overloading.php
The adb tool can be found in sdk/platform-tools/
If you don't see this directory in your SDK, launch the SDK Manager and install "Android SDK Platform-tools"
Also update your PATH environment variable to include the platform-tools/ directory, so you can execute adb from any location.
Give full path as input. Avoid relative paths.
return File.Exists(FinalPath);
strInputString = strInputString.replace(/'/g, "''");
The way to accept license agreements from the command line has changed. You can use the SDK manager which is located at: $ANDROID_SDK_ROOT/tools/bin
e.g on linux:
cd ~/Library/Android/sdk/tools/bin/
Run the sdkmanager as follows:
./sdkmanager --licenses
e.g on Windows:
cd /d "%ANDROID_SDK_ROOT%/tools/bin"
Run the sdkmanager as follows:
sdkmanager --licenses
And accept the licenses you did not accept yet (but need to).
For more details see the Android Studio documentation, although the current documentation is missing any description on the --licenses
option.
You might have two Android SDKs on your machine. Make sure to check both ~/Library/Android/sdk
and /usr/local/share/android-sdk
! If unsure, fully uninstall Android Studio from your machine and start with a clean slate.
Update: ANDROID_HOME is deprecated, ANDROID_SDK_ROOT is now the correct variable
In my case,I was using SubQuery
and had a same problem. I realized that the problem is from memory leakage.
Restarting MSSQL
service cause to flush tempDb
resource and free huge amount of memory.
so this was solve the problem.
<input type="submit" value="Create" name="button"/>_x000D_
<input type="submit" value="Reset" name="button" />
_x000D_
write the following code in Controler.
[HttpPost]
public ActionResult Login(string button)
{
switch (button)
{
case "Create":
return RedirectToAction("Deshboard", "Home");
break;
case "Reset":
return RedirectToAction("Login", "Home");
break;
}
return View();
}
First, the signature of your data() function:
bool data(struct *sampleData)
cannot possibly work, because the argument lacks a name. When you declare a function argument that you intend to actually access, it needs a name. So change it to something like:
bool data(struct sampleData *samples)
But in C++, you don't need to use struct
at all actually. So this can simply become:
bool data(sampleData *samples)
Second, the sampleData
struct is not known to data() at that point. So you should declare it before that:
struct sampleData {
int N;
int M;
string sample_name;
string speaker;
};
bool data(sampleData *samples)
{
samples->N = 10;
samples->M = 20;
// etc.
}
And finally, you need to create a variable of type sampleData
. For example, in your main() function:
int main(int argc, char *argv[]) {
sampleData samples;
data(&samples);
}
Note that you need to pass the address of the variable to the data() function, since it accepts a pointer.
However, note that in C++ you can directly pass arguments by reference and don't need to "emulate" it with pointers. You can do this instead:
// Note that the argument is taken by reference (the "&" in front
// of the argument name.)
bool data(sampleData &samples)
{
samples.N = 10;
samples.M = 20;
// etc.
}
int main(int argc, char *argv[]) {
sampleData samples;
// No need to pass a pointer here, since data() takes the
// passed argument by reference.
data(samples);
}
Many answers have explained how to call a method from the parent which has been overridden in the child.
However
"how do you call a parent class's method from child class?"
could also just mean:
"how do you call inherited methods?"
You can call methods inherited from a parent class just as if they were methods of the child class, as long as they haven't been overwritten.
e.g. in python 3:
class A():
def bar(self, string):
print("Hi, I'm bar, inherited from A"+string)
class B(A):
def baz(self):
self.bar(" - called by baz in B")
B().baz() # prints out "Hi, I'm bar, inherited from A - called by baz in B"
yes, this may be fairly obvious, but I feel that without pointing this out people may leave this thread with the impression you have to jump through ridiculous hoops just to access inherited methods in python. Especially as this question rates highly in searches for "how to access a parent class's method in Python", and the OP is written from the perspective of someone new to python.
I found: https://docs.python.org/3/tutorial/classes.html#inheritance to be useful in understanding how you access inherited methods.
Works in Net Core 2.1
var file = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "email", "EmailRegister.htm");
string SendData = System.IO.File.ReadAllText(file);
Sometimes you, also, need to clean this folder: C:\Windows\Temp\Temporary ASP.NET
I wrote up the answer for another question, though this is a more accurate question for it.
How do constructors and destructors work?
Here is a slightly opinionated answer.
Don't use __del__
. This is not C++ or a language built for destructors. The __del__
method really should be gone in Python 3.x, though I'm sure someone will find a use case that makes sense. If you need to use __del__
, be aware of the basic limitations per http://docs.python.org/reference/datamodel.html:
__del__
is called when the garbage collector happens to be collecting the objects, not when you lose the last reference to an object and not when you execute del object
.__del__
is responsible for calling any __del__
in a superclass, though it is not clear if this is in method resolution order (MRO) or just calling each superclass.__del__
means that the garbage collector gives up on detecting and cleaning any cyclic links, such as losing the last reference to a linked list. You can get a list of the objects ignored from gc.garbage. You can sometimes use weak references to avoid the cycle altogether. This gets debated now and then: see http://mail.python.org/pipermail/python-ideas/2009-October/006194.html.__del__
function can cheat, saving a reference to an object, and stopping the garbage collection.__del__
are ignored.__del__
complements __new__
far more than __init__
. This gets confusing. See http://www.algorithm.co.il/blogs/programming/python-gotchas-1-del-is-not-the-opposite-of-init/ for an explanation and gotchas.__del__
is not a "well-loved" child in Python. You will notice that sys.exit() documentation does not specify if garbage is collected before exiting, and there are lots of odd issues. Calling the __del__
on globals causes odd ordering issues, e.g., http://bugs.python.org/issue5099. Should __del__
called even if the __init__
fails? See http://mail.python.org/pipermail/python-dev/2000-March/thread.html#2423 for a long thread.But, on the other hand:
__del__
means you do not forget to call a close statement. See http://eli.thegreenplace.net/2009/06/12/safely-using-destructors-in-python/ for a pro __del__
viewpoint. This is usually about freeing ctypes or some other special resource.And my pesonal reason for not liking the __del__
function.
__del__
it devolves into thirty messages of confusion.So, find a reason not to use __del__
.
Simply casting the string as an int
won't work reliably. You need to convert it to an int32
. For this you can use the .NET convert
class and its ToInt32
method. The method requires a string
($strNum
) as the main input, and the base number
(10
) for the number system to convert to. This is because you can not only convert to the decimal system (the 10
base number), but also to, for example, the binary system (base 2).
Give this method a try:
[string]$strNum = "1.500"
[int]$intNum = [convert]::ToInt32($strNum, 10)
$intNum
For me, i just cleaned the app and it worked (cmd + shift + k), removing the error. I got the error after updating to swift 2.3.
os.listdir()
- list in the current directory
With listdir in os module you get the files and the folders in the current dir
import os
arr = os.listdir()
print(arr)
>>> ['$RECYCLE.BIN', 'work.txt', '3ebooks.txt', 'documents']
You need the ''
arr = os.listdir('')
arr = os.listdir('c:\\files')
glob
from glob
with glob you can specify a type of file to list like this
import glob
txtfiles = []
for file in glob.glob("*.txt"):
txtfiles.append(file)
glob
im a list comprehensionmylist = [f for f in glob.glob("*.txt")]
Getting the full path name with
os.path.abspath
You get the full path in return
import os
files_path = [os.path.abspath(x) for x in os.listdir()]
print(files_path)
>>> ['F:\\documenti\applications.txt', 'F:\\documenti\collections.txt']
Walk: going through sub directories
os.walk returns the root, the directories list and the files list, that is why I unpacked them in r, d, f in the for loop; it, then, looks for other files and directories in the subfolders of the root and so on until there are no subfolders.
import os
# Getting the current work directory (cwd)
thisdir = os.getcwd()
# r=root, d=directories, f = files
for r, d, f in os.walk(thisdir):
for file in f:
if file.endswith(".docx"):
print(os.path.join(r, file))
os.listdir()
: get files in the current directory (Python 2)
In Python 2, if you want the list of the files in the current directory, you have to give the argument as '.' or os.getcwd() in the os.listdir method.
import os
arr = os.listdir('.')
print(arr)
>>> ['$RECYCLE.BIN', 'work.txt', '3ebooks.txt', 'documents']
To go up in the directory tree
# Method 1
x = os.listdir('..')
# Method 2
x= os.listdir('/')
Get files:
os.listdir()
in a particular directory (Python 2 and 3)
import os
arr = os.listdir('F:\\python')
print(arr)
>>> ['$RECYCLE.BIN', 'work.txt', '3ebooks.txt', 'documents']
Get files of a particular subdirectory with
os.listdir()
import os
x = os.listdir("./content")
os.walk('.')
- current directory
import os
arr = next(os.walk('.'))[2]
print(arr)
>>> ['5bs_Turismo1.pdf', '5bs_Turismo1.pptx', 'esperienza.txt']
next(os.walk('.'))
andos.path.join('dir', 'file')
import os
arr = []
for d,r,f in next(os.walk("F:\\_python")):
for file in f:
arr.append(os.path.join(r,file))
for f in arr:
print(files)
>>> F:\\_python\\dict_class.py
>>> F:\\_python\\programmi.txt
next(os.walk('F:\\')
- get the full path - list comprehension
[os.path.join(r,file) for r,d,f in next(os.walk("F:\\_python")) for file in f]
>>> ['F:\\_python\\dict_class.py', 'F:\\_python\\programmi.txt']
os.walk
- get full path - all files in sub dirs**
x = [os.path.join(r,file) for r,d,f in os.walk("F:\\_python") for file in f]
print(x)
>>> ['F:\\_python\\dict.py', 'F:\\_python\\progr.txt', 'F:\\_python\\readl.py']
os.listdir()
- get only txt files
arr_txt = [x for x in os.listdir() if x.endswith(".txt")]
print(arr_txt)
>>> ['work.txt', '3ebooks.txt']
Using
glob
to get the full path of the files
If I should need the absolute path of the files:
from path import path
from glob import glob
x = [path(f).abspath() for f in glob("F:\\*.txt")]
for f in x:
print(f)
>>> F:\acquistionline.txt
>>> F:\acquisti_2018.txt
>>> F:\bootstrap_jquery_ecc.txt
Using
os.path.isfile
to avoid directories in the list
import os.path
listOfFiles = [f for f in os.listdir() if os.path.isfile(f)]
print(listOfFiles)
>>> ['a simple game.py', 'data.txt', 'decorator.py']
Using
pathlib
from Python 3.4
import pathlib
flist = []
for p in pathlib.Path('.').iterdir():
if p.is_file():
print(p)
flist.append(p)
>>> error.PNG
>>> exemaker.bat
>>> guiprova.mp3
>>> setup.py
>>> speak_gui2.py
>>> thumb.PNG
With list comprehension
:
flist = [p for p in pathlib.Path('.').iterdir() if p.is_file()]
Alternatively, use pathlib.Path()
instead of pathlib.Path(".")
Use glob method in pathlib.Path()
import pathlib
py = pathlib.Path().glob("*.py")
for file in py:
print(file)
>>> stack_overflow_list.py
>>> stack_overflow_list_tkinter.py
Get all and only files with os.walk
import os
x = [i[2] for i in os.walk('.')]
y=[]
for t in x:
for f in t:
y.append(f)
print(y)
>>> ['append_to_list.py', 'data.txt', 'data1.txt', 'data2.txt', 'data_180617', 'os_walk.py', 'READ2.py', 'read_data.py', 'somma_defaltdic.py', 'substitute_words.py', 'sum_data.py', 'data.txt', 'data1.txt', 'data_180617']
Get only files with next and walk in a directory
import os
x = next(os.walk('F://python'))[2]
print(x)
>>> ['calculator.bat','calculator.py']
Get only directories with next and walk in a directory
import os
next(os.walk('F://python'))[1] # for the current dir use ('.')
>>> ['python3','others']
Get all the subdir names with
walk
for r,d,f in os.walk("F:\\_python"):
for dirs in d:
print(dirs)
>>> .vscode
>>> pyexcel
>>> pyschool.py
>>> subtitles
>>> _metaprogramming
>>> .ipynb_checkpoints
os.scandir()
from Python 3.5 and greater
import os
x = [f.name for f in os.scandir() if f.is_file()]
print(x)
>>> ['calculator.bat','calculator.py']
# Another example with scandir (a little variation from docs.python.org)
# This one is more efficient than os.listdir.
# In this case, it shows the files only in the current directory
# where the script is executed.
import os
with os.scandir() as i:
for entry in i:
if entry.is_file():
print(entry.name)
>>> ebookmaker.py
>>> error.PNG
>>> exemaker.bat
>>> guiprova.mp3
>>> setup.py
>>> speakgui4.py
>>> speak_gui2.py
>>> speak_gui3.py
>>> thumb.PNG
Examples:
Ex. 1: How many files are there in the subdirectories?
In this example, we look for the number of files that are included in all the directory and its subdirectories.
import os
def count(dir, counter=0):
"returns number of files in dir and subdirs"
for pack in os.walk(dir):
for f in pack[2]:
counter += 1
return dir + " : " + str(counter) + "files"
print(count("F:\\python"))
>>> 'F:\\\python' : 12057 files'
Ex.2: How to copy all files from a directory to another?
A script to make order in your computer finding all files of a type (default: pptx) and copying them in a new folder.
import os
import shutil
from path import path
destination = "F:\\file_copied"
# os.makedirs(destination)
def copyfile(dir, filetype='pptx', counter=0):
"Searches for pptx (or other - pptx is the default) files and copies them"
for pack in os.walk(dir):
for f in pack[2]:
if f.endswith(filetype):
fullpath = pack[0] + "\\" + f
print(fullpath)
shutil.copy(fullpath, destination)
counter += 1
if counter > 0:
print('-' * 30)
print("\t==> Found in: `" + dir + "` : " + str(counter) + " files\n")
for dir in os.listdir():
"searches for folders that starts with `_`"
if dir[0] == '_':
# copyfile(dir, filetype='pdf')
copyfile(dir, filetype='txt')
>>> _compiti18\Compito Contabilità 1\conti.txt
>>> _compiti18\Compito Contabilità 1\modula4.txt
>>> _compiti18\Compito Contabilità 1\moduloa4.txt
>>> ------------------------
>>> ==> Found in: `_compiti18` : 3 files
Ex. 3: How to get all the files in a txt file
In case you want to create a txt file with all the file names:
import os
mylist = ""
with open("filelist.txt", "w", encoding="utf-8") as file:
for eachfile in os.listdir():
mylist += eachfile + "\n"
file.write(mylist)
Example: txt with all the files of an hard drive
"""
We are going to save a txt file with all the files in your directory.
We will use the function walk()
"""
import os
# see all the methods of os
# print(*dir(os), sep=", ")
listafile = []
percorso = []
with open("lista_file.txt", "w", encoding='utf-8') as testo:
for root, dirs, files in os.walk("D:\\"):
for file in files:
listafile.append(file)
percorso.append(root + "\\" + file)
testo.write(file + "\n")
listafile.sort()
print("N. of files", len(listafile))
with open("lista_file_ordinata.txt", "w", encoding="utf-8") as testo_ordinato:
for file in listafile:
testo_ordinato.write(file + "\n")
with open("percorso.txt", "w", encoding="utf-8") as file_percorso:
for file in percorso:
file_percorso.write(file + "\n")
os.system("lista_file.txt")
os.system("lista_file_ordinata.txt")
os.system("percorso.txt")
All the file of C:\ in one text file
This is a shorter version of the previous code. Change the folder where to start finding the files if you need to start from another position. This code generate a 50 mb on text file on my computer with something less then 500.000 lines with files with the complete path.
import os
with open("file.txt", "w", encoding="utf-8") as filewrite:
for r, d, f in os.walk("C:\\"):
for file in f:
filewrite.write(f"{r + file}\n")
How to write a file with all paths in a folder of a type
With this function you can create a txt file that will have the name of a type of file that you look for (ex. pngfile.txt) with all the full path of all the files of that type. It can be useful sometimes, I think.
import os
def searchfiles(extension='.ttf', folder='H:\\'):
"Create a txt file with all the file of a type"
with open(extension[1:] + "file.txt", "w", encoding="utf-8") as filewrite:
for r, d, f in os.walk(folder):
for file in f:
if file.endswith(extension):
filewrite.write(f"{r + file}\n")
# looking for png file (fonts) in the hard disk H:\
searchfiles('.png', 'H:\\')
>>> H:\4bs_18\Dolphins5.png
>>> H:\4bs_18\Dolphins6.png
>>> H:\4bs_18\Dolphins7.png
>>> H:\5_18\marketing html\assets\imageslogo2.png
>>> H:\7z001.png
>>> H:\7z002.png
(New) Find all files and open them with tkinter GUI
I just wanted to add in this 2019 a little app to search for all files in a dir and be able to open them by doubleclicking on the name of the file in the list.
import tkinter as tk
import os
def searchfiles(extension='.txt', folder='H:\\'):
"insert all files in the listbox"
for r, d, f in os.walk(folder):
for file in f:
if file.endswith(extension):
lb.insert(0, r + "\\" + file)
def open_file():
os.startfile(lb.get(lb.curselection()[0]))
root = tk.Tk()
root.geometry("400x400")
bt = tk.Button(root, text="Search", command=lambda:searchfiles('.png', 'H:\\'))
bt.pack()
lb = tk.Listbox(root)
lb.pack(fill="both", expand=1)
lb.bind("<Double-Button>", lambda x: open_file())
root.mainloop()
Try:
SELECT strftime("%Y-%d-%m", col_name, 'unixepoch') AS col_name
It will format timestamp in milliseconds to yyyy-mm-dd string.
I have a Fascinate as well, and had to change the phone's USB communication mode from MODEM to PDA. Use:
**USBUI
(**87284
) to change both USB and UART to PDA mode. I also had to disconnect and reconnect the USB cable. Once Windows re-recognized the device again, "adb devices" started returning my device.
BTW if you use CDMA workshop or the equivalent, you will need to switch the setting back to MODEM.
Dividing two integers will result in an integer (whole number) result.
You need to cast one number as a float, or add a decimal to one of the numbers, like a/350.0.
public static boolean isDirectory(String path) {
return path !=null && new File(path).isDirectory();
}
To answer the question directly.
You can use the following solution to accomplish your goal:
struct student
{
char name[20];
char country[20];
};
void main()
{
struct student S={"Wolverine","America"};
struct student X;
X=S;
printf("%s%s",X.name,X.country);
}
I found that my problem related to the actual registration of the DLL.
Have you tried to Remove hangouts extension in Google Chrome? because it forces chrome to keep running even you close all the windows.
I was also facing the problem but it resolved now.
To create a group of inputs you can create a custom html element
window.customElements.define('radio-group', RadioGroup);
https://gist.github.com/robdodson/85deb2f821f9beb2ed1ce049f6a6ed47
to keep selected option in each group, you need to add name attribute to inputs in group, if you not add it then all is one group.
Please try this below code in onCreate()
EditText edtView = (EditText) findViewById(R.id.editTextConvertValue);
edtView.setInputType(InputType.TYPE_NULL);
Go to the directory manually and do right click → Select 'Git bash' option.
Git bash terminal automatically opens with the intended directory. For example, go to your project folder. While in the folder, right click and select the option and 'Git bash'. It will open automatically with /c/project
.
Starting from SQL Server 2016
a new way for sharing information in session is introduced via the SESSION_CONTEXT and sp_set_session_context.
You can use them as alternative of CONTEXT_INFO()
which persist only a binary value limited to 128 bytes. Also, the user can rewrite the value anytime and it's not very good to use it for security checks.
The following issues are resolved using the new utils. You can store the data in more user-friendly format:
EXEC sp_set_session_context 'language', 'English';
SELECT SESSION_CONTEXT(N'language');
Also, we can mark it as read-only
:
EXEC sp_set_session_context 'user_id', 4, @read_only = 1;
If you try to modify a read-only
session context you will get something like this:
Msg 15664, Level 16, State 1, Procedure sp_set_session_context, Line 10 Cannot set key 'user_id' in the session context. The key has been set as read_only for this session.
Convert both completed
and total
to double
or at least cast them to double
when doing the devision. I.e. cast the varaibles to double not just the result.
Fair warning, there is a floating point precision problem when working with float
and double
.
All of the previous answers are great. If it is a simple, one line sql command you wish to run, you could also use the -e option.
mysql -h <host> -u<user> -p<password> database -e \
"SELECT * FROM blah WHERE foo='bar';"
have at look at the static methods DateTime.Parse()
and DateTime.TryParse()
. They will allow you to pass in your date string and a format string, and get a DateTime object in return.
You could go two ways with this. Using LINQPad (invaluable if you're new to LINQ) and a dummy database, I built the following queries:
Posts.Join(
Post_metas,
post => post.Post_id,
meta => meta.Post_id,
(post, meta) => new { Post = post, Meta = meta }
)
or
from p in Posts
join pm in Post_metas on p.Post_id equals pm.Post_id
select new { Post = p, Meta = pm }
In this particular case, I think the LINQ syntax is cleaner (I change between the two depending upon which is easiest to read).
The thing I'd like to point out though is that if you have appropriate foreign keys in your database, (between post and post_meta) then you probably don't need an explicit join unless you're trying to load a large number of records. Your example seems to indicate that you are trying to load a single post and its metadata. Assuming that there are many post_meta records for each post, then you could do the following:
var post = Posts.Single(p => p.ID == 1);
var metas = post.Post_metas.ToList();
If you want to avoid the n+1 problem, then you can explicitly tell LINQ to SQL to load all of the related items in one go (although this may be an advanced topic for when you're more familiar with L2S). The example below says "when you load a Post, also load all of its records associated with it via the foreign key represented by the 'Post_metas' property":
var dataLoadOptions = new DataLoadOptions();
dataLoadOptions.LoadWith<Post>(p => p.Post_metas);
var dataContext = new MyDataContext();
dataContext.LoadOptions = dataLoadOptions;
var post = Posts.Single(p => p.ID == 1); // Post_metas loaded automagically
It is possible to make many LoadWith
calls on a single set of DataLoadOptions
for the same type, or many different types. If you do this lots though, you might just want to consider caching.
DECLARE @JCnt int=null
SEt @JCnt=(SELECT COUNT( ISNUll(EmpCode,0)) FROM tbl_Employees WHERE EmpCode=1 )
UPDATE #TempCode
SET janCA= CASE WHEN @JCnt>0 THEN (SELECT SUM (ISNUll(Amount,0)) FROM tbl_Salary WHERE Code=1 )ELSE 0 END
WHERE code=1
Wrap them in {}
:
${"file" . $i} = file($filelist[$i]);
Using ${}
is a way to create dynamic variables, simple example:
${'a' . 'b'} = 'hello there';
echo $ab; // hello there
Others have answered sufficiently. I would just like to add a few examples of frequent extensions:
The main
function returning void
. This is not defined by the standard, meaning it will only work on some compilers (including GCC), but not on others. By the way, int main()
and int main(int, char**)
are the two signatures that the standard does define.
Another popular extension is being able to declare and define functions inside other functions:
void f()
{
void g()
{
// ...
}
// ...
g();
// ...
}
This is nonstandard. If you want this kind of behavior, check out C++11 lambdas
It sounds like you're looking for applicationHost.config
, which is located in C:\Windows\System32\inetsrv\config
.
Yes, it's an XML file, and yes, editing the file by hand will affect the IIS config after a restart. You can think of IIS Manager as a GUI front-end for editing applicationHost.config
and web.config
.
The download attribute is new for the <a>
tag in HTML5
<a href="http://www.odin.com/form.pdf" download>Download Form</a>
or
<a href="http://www.odin.com/form.pdf" download="Form">Download Form</a>
I prefer the first one it is preferable in respect to any extension.
I recently came across Python 3 interpreter at CompileOnline.
$('tbody').find('tr:visible').hightlight(myArray[i]);
This may be useful for who want to use dateformater.dateformat
;
if you want 12.09.18
you use dateformater.dateformat = "dd.MM.yy"
Wednesday, Sep 12, 2018 --> EEEE, MMM d, yyyy
09/12/2018 --> MM/dd/yyyy
09-12-2018 14:11 --> MM-dd-yyyy HH:mm
Sep 12, 2:11 PM --> MMM d, h:mm a
September 2018 --> MMMM yyyy
Sep 12, 2018 --> MMM d, yyyy
Wed, 12 Sep 2018 14:11:54 +0000 --> E, d MMM yyyy HH:mm:ss Z
2018-09-12T14:11:54+0000 --> yyyy-MM-dd'T'HH:mm:ssZ
12.09.18 --> dd.MM.yy
10:41:02.112 --> HH:mm:ss.SSS
Shift+J removes the line change character from the current line, so by pressing "J" at any place in the line you can combine the current line and the next line in the way you want.
From char and varchar (Transact-SQL)
varchar [ ( n | max ) ]
Variable-length, non-Unicode character data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size is the actual length of data entered + 2 bytes. The data entered can be 0 characters in length. The ISO synonyms for varchar are char varying or character varying.
You can resolve the error by providing the column names you are affecting.
> INSERT INTO table_name (column1,column2,column3)
`VALUES(50,'Jon Snow','Eye');`
please note that the semi colon should be added only after the statement providing values
Convert.ToString(object)
converts to string. If the object is null
, Convert.ToString
converts it to an empty string.
Calling .ToString()
on an object with a null value throws a System.NullReferenceException
.
EDIT:
Two exceptions to the rules:
1) ConvertToString(string)
on a null string will always return null.
2) ToString(Nullable<T>)
on a null value will return "" .
Code Sample:
// 1) Objects:
object obj = null;
//string valX1 = obj.ToString(); // throws System.NullReferenceException !!!
string val1 = Convert.ToString(obj);
Console.WriteLine(val1 == ""); // True
Console.WriteLine(val1 == null); // False
// 2) Strings
String str = null;
//string valX2 = str.ToString(); // throws System.NullReferenceException !!!
string val2 = Convert.ToString(str);
Console.WriteLine(val2 == ""); // False
Console.WriteLine(val2 == null); // True
// 3) Nullable types:
long? num = null;
string val3 = num.ToString(); // ok, no error
Console.WriteLine(num == null); // True
Console.WriteLine(val3 == ""); // True
Console.WriteLine(val3 == null); // False
val3 = Convert.ToString(num);
Console.WriteLine(num == null); // True
Console.WriteLine(val3 == ""); // True
Console.WriteLine(val3 == null); // False
Are you using Eclipse? If so I would stick with the default member sort order, because that is likely to be most familiar to whoever reads your code (although it is not my favourite sort order.)
Welcome to C++11 and rvalue references:
#include <cassert>
#include <string>
using std::string;
void myfunc(string*&& val)
{
assert(&val);
assert(val);
assert(val->c_str());
// Do stuff to the string pointer
}
// sometime later
int main () {
// ...
string s;
myfunc(&s);
// ...
}
Now you have access to the value of the pointer (referred to by val
), which is the address of the string.
You can modify the pointer, and no one will care. That is one aspect of what an rvalue is in the first place.
Be careful: The value of the pointer is only valid until myfunc()
returns. At last, its a temporary.
You can also use else if
syntax:
<% if (x === 1) { %>
<p>Hello world!</p>
<% } else if (x === 2) { %>
<p>Hi earth!</p>
<% } else { %>
<p>Hey terra!</p>
<% } %>
pip install easy-tictoc
In the code:
from tictoc import tic, toc
tic()
#Some code
toc()
Disclaimer: I'm the author of this library.
try the following (in RowDataBound method of GridView):
protected void GridViewUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
// this will only change the rows backgound not the column header
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].BackColor = System.Drawing.Color.LightCyan; //first col
e.Row.Cells[1].BackColor = System.Drawing.Color.Black; // second col
}
}
The PrimeFaces ajax events sometimes are very poorly documented, so in most cases you must go to the source code and check yourself.
p:selectOneMenu
supports change event:
<p:selectOneMenu ..>
<p:ajax event="change" update="msgtext"
listener="#{post.subjectSelectionChanged}" />
<!--...-->
</p:selectOneMenu>
which triggers listener with AjaxBehaviorEvent
as argument in signature:
public void subjectSelectionChanged(final AjaxBehaviorEvent event) {...}
** Update**: 11/19/2019
Microsoft has released a new version of the control 150.1400.0
in their Nuget library. My short testing shows that it works again in the forms designer where 150.1357.0
and 150.1358.0
did not. This includes being able to resize and modify the ReportViewer Tasks on the control itself.
** Update**: 8/18/2019
Removing the latest version and rolling back to 150.900.148.0
seems to work on multiple computers I'm using with VS2017 and VS2019.
You can roll back to 150.900.148 in the Nuget solution package manager. It works similarly to the previous versions. Use the drop down box to select the older version.
It may be easier to manually delete references to post 150.900 versions of ReportViewer and readd them than it is to fix them.
Remember to restart Visual Studio after changing the toolbox entry.
Update: 8/7/2019
A newer version of the ReportViewer control has been released, probably coinciding with Visual Studio 2019. I was working with V150.1358.0.
Following the directions in this answer gets the control in the designer's toolbox. But once dropped on the form it doesn't display. The control shows up below the form as a non-visual component.
This is working as designed according to Microsoft SQL BI support. This is the group responsible for the control.
While you still cannot interact with the control directly, these additional steps give a workaround so the control can be sized on the form. While now visible, the designer treats the control as if it didn't exist.
I've created a feedback request at the suggestion of Microsoft SQL BI support. Please consider voting on it to get Microsoft's attention.
Microsoft Azure Feedback page - Restore Designtime features of the WinForms ReportViewer Control
Additional steps:
In the form's form.designer.cs file, add the Reportviewer control to the panel.
//
// panel1
//
this.panel1.Controls.Add(this.reportViewer1);
Return to the form's designer, you should see the reportViewer on the panel
Now you can position the reportViewer by actually interacting with the panel.
Update: Microsoft released a document on April 18, 2017 describing how to configure and use the reporting tool in Visual Studio 2017.
Visual Studio 2017 does not have the ReportViewer
tool installed by default in the ToolBox. Installing the extension Microsoft Rdlc Report Designer for Visual Studio and then adding that to the ToolBox results in a non-visual component that appears below the form.
Microsoft Support had told me this is a bug, but as of April 21, 2017 it is "working as designed".
The following steps need to be followed for each project that requires ReportViewer
.
ReportViewer
in the Toolbox, remove it. Highlight, right-click and delete.
Edited 8/7/2019 - It looks like the current version of the RDLC Report Designer extension no longer interferes. You need this to actually edit the reports.
If you have the Microsoft Rdlc Report Designer for Visual Studio extension installed, uninstall it.
Close your solution and restart Visual Studio. This is a crucial step, errors will occur if VS is not restarted when switching between solutions.
Tools/NuGet Package Manager/Package Manager Console
)At the PM> prompt enter this command, case matters.
Install-Package Microsoft.ReportingServices.ReportViewerControl.WinForms
You should see text describing the installation of the package.
Now we can temporarily add the ReportViewer
tool to the tool box.
Right-click in the toolbox and use Choose Items...
We need to browse to the proper DLL that is located in the solutions Packages
folder, so hit the browse button.
In our example we can paste in the packages folder as shown in the text of Package Manager Console.
C:\Users\jdoe\Documents\Projects\_Test\ReportViewerTest\WindowsFormsApp1\packages
Then double click on the folder named
Microsoft.ReportingServices.ReportViewerControl.Winforms.140.340.80
The version number will probably change in the future.
Then double-click on lib
and again on net40
.
Finally, double click on the file Microsoft.ReportViewer.WinForms.dll
You should see ReportViewer
checked in the dialog. Scroll to the right and you will see the version 14.0.0.0 associated to it.
Click OK.
ReportViewer
is now located in the ToolBox.
Drag the tool to the desired form(s).
Once completed, delete the ReportViewer
tool from the tool box. You can't use it with another project.
You may save the project and are good to go.
Remember to restart Visual Studio any time you need to open a project with ReportViewer
so that the DLL is loaded from the correct location. If you try and open a solution with a form with ReportViewer
without restarting you will see errors indicating that the “The variable 'reportViewer1' is either undeclared or was never assigned.
“.
If you add a new project to the same solution you need to create the project, save the solution, restart Visual Studio and then you should be able to add the ReportViewer
to the form. I have seen it not work the first time and show up as a non-visual component.
When that happens, removing the component from the form, deleting the Microsoft.ReportViewer.*
references from the project, saving and restarting usually works.
If you are planning on doing any kind of inheritance, then I would recommend this.constructor
. This simple example should illustrate why:
class ConstructorSuper {
constructor(n){
this.n = n;
}
static print(n){
console.log(this.name, n);
}
callPrint(){
this.constructor.print(this.n);
}
}
class ConstructorSub extends ConstructorSuper {
constructor(n){
this.n = n;
}
}
let test1 = new ConstructorSuper("Hello ConstructorSuper!");
console.log(test1.callPrint());
let test2 = new ConstructorSub("Hello ConstructorSub!");
console.log(test2.callPrint());
test1.callPrint()
will log ConstructorSuper Hello ConstructorSuper!
to the
consoletest2.callPrint()
will log ConstructorSub Hello ConstructorSub!
to the consoleThe named class will not deal with inheritance nicely unless you explicitly redefine every function that makes a reference to the named Class. Here is an example:
class NamedSuper {
constructor(n){
this.n = n;
}
static print(n){
console.log(NamedSuper.name, n);
}
callPrint(){
NamedSuper.print(this.n);
}
}
class NamedSub extends NamedSuper {
constructor(n){
this.n = n;
}
}
let test3 = new NamedSuper("Hello NamedSuper!");
console.log(test3.callPrint());
let test4 = new NamedSub("Hello NamedSub!");
console.log(test4.callPrint());
test3.callPrint()
will log NamedSuper Hello NamedSuper!
to the
consoletest4.callPrint()
will log NamedSuper Hello NamedSub!
to the consoleSee all the above running in Babel REPL.
You can see from this that test4
still thinks it's in the super class; in this example it might not seem like a huge deal, but if you are trying to reference member functions that have been overridden or new member variables, you'll find yourself in trouble.
I am still not able to make archive from xcode but fastlane did the work for me
There's a jQuery Timer plugin you may want to try
Map<Integer, Point2D> hm = new HashMap<Integer, Point2D>();
1.save your file name as hey.py with the below given hello world script
#! /usr/bin/python
print('Hello, world!')
2.open the terminal in that directory
$ python hey.py
or if you are using python3 then
$ python3 hey.py
Sometimes this issue come because of space in PHP start tag of controller facing same issue just removed whitespace in:
<?php
namespace App\Http\Controllers\Auth;
removing the space resolved my error
Daniel answer is right on the spot. If you want to query more than one field do this:
Employee.objects.values_list('eng_name','rank')
This will return list of tuples. You cannot use named=Ture when querying more than one field.
Moreover if you know that only one field exists with that info and you know the pk id then do this:
Employee.objects.values_list('eng_name','rank').get(pk=1)
add this to your package.json file
scripts {
"dev": "nodemon --watch '**/*.ts' --exec 'ts-node' index.ts"
}
and to make this work you also need to install ts-node as dev-dependency
yarn add ts-node -D
run yarn dev
to start the dev server
Number (1): The IP was incorrect - is the correct answer. The /etc/hosts file (a.k.a. C:\Windows\system32\drivers\etc\hosts ) had an incorrect entry for the local machine name. Corrected the 'hosts' file and Camel runs very well. Thanks for the pointer.
BOOTSTRAP 4
you can use a combination of
fa-chevron-down, fa-chevron-up
fa-sort-down, fa-sort-up
<th class="text-center">
<div class="btn-group" role="group">
<button type="button" class="btn btn-xs btn-link py-0 pl-0 pr-1">
Some Text OR icon
</button>
<div class="btn-group-vertical">
<a href="?sort=asc" class="btn btn-xs btn-link p-0">
<i class="fas fa-sort-up"></i>
</a>
<a href="?sort=desc" class="btn btn-xs btn-link p-0">
<i class="fas fa-sort-down"></i>
</a>
</div>
</div>
</th>
mysql> INSERT INTO tb1 VALUES(1,1),(2,2),(3,3),(6,60),(7,70),(8,80);
mysql> INSERT INTO tb2 VALUES(1,1),(2,2),(3,3),(4,40),(5,50),(9,90);
DELETE records FROM one table :
mysql> DELETE tb1 FROM tb1,tb2 WHERE tb1.id= tb2.id;
DELETE RECORDS FROM both tables:
mysql> DELETE tb2,tb1 FROM tb2 JOIN tb1 USING(id);
The NativeHeap can be increasded by -XX:MaxDirectMemorySize=256M (default is 128)
I've never used it. Maybe you'll find it useful.
In computer programming, particularly in the C, C++, and C# programming languages, a variable or object declared with the volatile
keyword usually has special properties related to optimization and/or threading. Generally speaking, the volatile
keyword is intended to prevent the (pseudo)compiler from applying any optimizations on the code that assume values of variables cannot change "on their own." (c) Wikipedia
Working with large models were very slow before the SP1, (have not tried it after the SP1, but it is said that is a snap now).
I still Design my tables first, then an in-house built tool generates the POCOs for me, so it takes the burden of doing repetitive tasks for each poco object.
when you are using source control systems, you can easily follow the history of your POCOs, it is not that easy with designer generated code.
I have a base for my POCO, which makes a lot of things quite easy.
I have views for all of my tables, each base view brings basic info for my foreign keys and my view POCOs derive from my POCO classes, which is quite usefull again.
And finally I dont like designers.
Yes. For that ensure that you declare the worksheet
For example
Previous Code
Sub Sample()
Dim ws As Worksheet
Set ws = Sheets("Sheet3")
Debug.Print ws.Cells(23, 4).Value
End Sub
New Code
Sub Sample()
Dim ws As Worksheet
Set ws = Sheets("Sheet4")
Debug.Print ws.Cells(23, 4).Value
End Sub
As Zach explained, you can use:
xor = bool(a) ^ bool(b)
Personally, I favor a slightly different dialect:
xor = bool(a) + bool(b) == 1
This dialect is inspired from a logical diagramming language I learned in school where "OR" was denoted by a box containing =1
(greater than or equal to 1) and "XOR" was denoted by a box containing =1
.
This has the advantage of correctly implementing exclusive or on multiple operands.
/Library/Java/JavaVirtualMachines/
is the correct location for the JVM to be installed. This has been the case for several years now. Many years ago, other locations were used, but no longer.
You have a choice of several vendors to obtain an installer app to install a Java implementation on your Mac. Download an installer to run locally and then discard, as you commonly do for many apps.
Your Question mentions JavaFX/OpenJFX. You might find it convenient to use a Java implementation that comes bundled with the OpenJFX libraries, such as LibericaFX from BellSoft or ZuluFX from Azul Systems.
Other answers suggesting the Homebrew package manager seem a bit extreme to me. I am sure Homebrew has some good uses. But to simply run Java, or do Java programming, installing Homebrew is a needless extra step. Installing Homebrew (package manager) for the single goal of obtaining Java is like building a landing strip to park your car instead of using your driveway. If you already have it, fine, use it. But suggesting Homebrew to those who simply need Java is poor advice.
People not already using Home-brew can simply download a Mac installer from a trusted source.
You have multiple sources to obtain an easy-to-use installer app to put Java on your Mac. Run the installer on your Mac just as you do for many other apps.
Here is a flowchart diagram for finding a source of Java 11, some of which also offer Java 8.
Download an installer from a vendor such as Adoptium(AdoptOpenJDK.net).
Run the installer.
JavaVirtualMachines
folder is now correctWhy doesn't Oracle's installer put it where it really goes? And how can I work around this problem?
Not a problem.
The folder /Library/Java/JavaVirtualMachines/
is the new home for JVMs on macOS.
To install a JVM, use an installer, discussed below.
To uninstall, simply use the Finder to delete a JVM from that folder. You will be prompted for system admin password to complete the removal.
Back in 2010, Apple joined the OpenJDK project, along with Oracle, IBM, Red Hat, Azul, and other Java vendors. Each member contributes source code, testing, and feedback to the unified OpenJDK codebase.
Apple contributed most of its Mac-specific code for its JVM. Now Apple no longer releases its own Mac-specific JVM. You now have your choice of JVM supplier, with builds coming from the OpenJDK codebase.
You will find source code at: http://openjdk.java.net
Be aware that in 2017, Oracle, the JCP, and OpenJDK have adopted a new rapid “release train” plan for regularly-scheduled versions of Java to be delivered in a predictable manner.
Read this 2018-07 Azul Systems blog post for many details, Eliminating Java Update Confusion by Simon Ritter.
Also read Java Is Still Free.
For a rather exhaustive list of past and present JVM implementations, see this page at Wikipedia.
Here is a discussion of a few vendors. See the flowchart above for more vendors
Oracle provides JDK and JRE installers for multiple platforms including macOS.
Over the years since acquiring Sun, Oracle has combined the best parts of the two JVM engines, HotSpot and JRocket, and merged them into the OpenJDK project used as the basis for their own branded implementations of Java.
Their new business plan, as of 2018, is to provide a Oracle-branded implementation of Java for a fee in production, and at no cost for use in development/testing/demo. Support for previous releases requires a paid support program. They have declared their intention for their branded release to be at feature-parity with the OpenJDK release. They have even donated their commercial add-ons such as Flight Recorder to the OpenJDK project.
Oracle also releases a build of OpenJDK with no support: http://jdk.java.net/
Oracle has produced a special purpose JDK, GraalVM.
Azul Systems provides a variety of JVM products.
Zulu
line is based directly on OpenJDK, and is available at no cost with optional paid support plans.Zing
line offers commercial JVM products enhanced with alternate technical implementations such as a specialized garbage-collector.Both of their lines offer installers for macOS.
I am currently use Zulu for Java 10.0.1 on macOS High Sierra with IntelliJ 2018.2 and Vaadin 8. I downloaded from this page. By the way, I do not find any Java-related items installed on the Apple System Preferences app.
Adoptium, formerly known as AdoptOpenJDK, is a community-led effort to build binaries of the OpenJDK source. Many of the other vendors of Java implementations support this work at Adoptium.
The OpenJ9 project is an another implementation of the JVM engine, an alternative to HotSpot.
Now sponsored at the Eclipse Foundation, with technology and backing donated by IBM in 2017.
For prebuilt binaries, they refer you to the AdoptOpenJDK project mentioned above.
The installers provided by Oracle or by Azul are both utterly simple to operate. Just run the installer app on your Mac. A window appears to indicate the progress of the installation.
When completed, verify your JVM installation by:
/Library/Java/JavaVirtualMachines/
folder to see an item for the new JVM.java -version
to see the brand and version number of your JVM.After verifying success, dismount the .dmg image in the Finder. Then trash the .dmg file you downloaded.
In Laravel 5.4 the following worked for me:
return back()->withErrors(['field_name' => ['Your custom message here.']]);
Maybe this answer is not quite what you're looking for, but it will fomat any language with the same keyboard shortcut. The solution are language specific keyboard shortcuts.
For every language you want to format, you must find and download a plugin for that, for example a html formatter and a C# formatter. And then you map the command for every plugin to the same key, but with a differnt context (see the link).
Greets
Aggregate used to sum columns in a multi dimensional integer array
int[][] nonMagicSquare =
{
new int[] { 3, 1, 7, 8 },
new int[] { 2, 4, 16, 5 },
new int[] { 11, 6, 12, 15 },
new int[] { 9, 13, 10, 14 }
};
IEnumerable<int> rowSums = nonMagicSquare
.Select(row => row.Sum());
IEnumerable<int> colSums = nonMagicSquare
.Aggregate(
(priorSums, currentRow) =>
priorSums.Select((priorSum, index) => priorSum + currentRow[index]).ToArray()
);
Select with index is used within the Aggregate func to sum the matching columns and return a new Array; { 3 + 2 = 5, 1 + 4 = 5, 7 + 16 = 23, 8 + 5 = 13 }.
Console.WriteLine("rowSums: " + string.Join(", ", rowSums)); // rowSums: 19, 27, 44, 46
Console.WriteLine("colSums: " + string.Join(", ", colSums)); // colSums: 25, 24, 45, 42
But counting the number of trues in a Boolean array is more difficult since the accumulated type (int) differs from the source type (bool); here a seed is necessary in order to use the second overload.
bool[][] booleanTable =
{
new bool[] { true, true, true, false },
new bool[] { false, false, false, true },
new bool[] { true, false, false, true },
new bool[] { true, true, false, false }
};
IEnumerable<int> rowCounts = booleanTable
.Select(row => row.Select(value => value ? 1 : 0).Sum());
IEnumerable<int> seed = new int[booleanTable.First().Length];
IEnumerable<int> colCounts = booleanTable
.Aggregate(seed,
(priorSums, currentRow) =>
priorSums.Select((priorSum, index) => priorSum + (currentRow[index] ? 1 : 0)).ToArray()
);
Console.WriteLine("rowCounts: " + string.Join(", ", rowCounts)); // rowCounts: 3, 1, 2, 2
Console.WriteLine("colCounts: " + string.Join(", ", colCounts)); // colCounts: 3, 2, 1, 2
Angular 2 and Angular 4
In a ngFor loop it must be look like this:
<div class="column" *ngFor="let u of events ">
<div class="thumb">
<img src="assets/uploads/{{u.image}}">
<h4>{{u.name}}</h4>
</div>
<div class="info">
<img src="assets/uploads/{{u.image}}">
<h4>{{u.name}}</h4>
<p>{{u.text}}</p>
</div>
</div>
The operating system is also a program, so we can also create our own program by creating from scratch or changing (limiting or adding) features of one of the small operating systems, and then run it during the boot process (using an ISO image).
For example, this page can be used as a starting point:
How to write a simple operating system
Here, the entire Operating System fit entirely in a 512-byte boot sector (MBR)!
Such or similar simple OS can be used to create a simple framework that will allow us:
make the bootloader load subsequent sectors on the disk into RAM, and jump to that point to continue execution. Or you could read up on FAT12, the filesystem used on floppy drives, and implement that.
There are many possibilities, however. For for example to see a bigger x86 assembly language OS we can explore the MykeOS, x86 operating system which is a learning tool to show the simple 16-bit, real-mode OSes work, with well-commented code and extensive documentation.
Other common type of programs that run without the operating system are also Boot Loaders. We can create a program inspired by such a concept for example using this site:
How to develop your own Boot Loader
The above article presents also the basic architecture of such a programs:
- Correct loading to the memory by 0000:7C00 address.
- Calling the BootMain function that is developed in the high-level language.
- Show “”Hello, world…”, from low-level” message on the display.
As we can see, this architecture is very flexible and allows us to implement any program, not necessarily a boot loader.
In particular, it shows how to use the "mixed code" technique thanks to which it is possible to combine high-level constructions (from C or C++) with low-level commands (from Assembler). This is a very useful method, but we have to remember that:
to build the program and obtain executable file you will need the compiler and linker of Assembler for 16-bit mode. For C/C++ you will need only the compiler that can create object files for 16-bit mode.
The article shows also how to see the created program in action and how to perform its testing and debug.
The above examples used the fact of loading the sector MBR on the data medium. However, we can go deeper into the depths by plaing for example with the UEFI applications:
Beyond loading an OS, UEFI can run UEFI applications, which reside as files on the EFI System Partition. They can be executed from the UEFI command shell, by the firmware's boot manager, or by other UEFI applications. UEFI applications can be developed and installed independently of the system manufacturer.
A type of UEFI application is an OS loader such as GRUB, rEFInd, Gummiboot, and Windows Boot Manager; which loads an OS file into memory and executes it. Also, an OS loader can provide a user interface to allow the selection of another UEFI application to run. Utilities like the UEFI shell are also UEFI applications.
If we would like to start creating such programs, we can, for example, start with these websites:
Programming for EFI: Creating a "Hello, World" Program / UEFI Programming - First Steps
It is well known that there is a whole group of malicious software (which are programs) that are running before the operating system starts.
A huge group of them operate on the MBR sector or UEFI applications, just like the all above solutions, but there are also those that use another entry point such as the Volume Boot Record (VBR) or the BIOS:
There are at least four known BIOS attack viruses, two of which were for demonstration purposes.
or perhaps another one too.
Bootkits have evolved from Proof-of-Concept development to mass distribution and have now effectively become open-source software.
I also think that in this context it is also worth mentioning that there are various forms of booting the operating system (or the executable program intended for this). There are many, but I would like to pay attention to loading the code from the network using Network Boot option (PXE), which allows us to run the program on the computer regardless of its operating system and even regardless of any storage medium that is directly connected to the computer:
First access the children with: this.props.children
, each child will then have its ref
as a property on it.
You can write a PL/SQL function to return that cursor (or you could put that function in a package if you have more code related to this):
CREATE OR REPLACE FUNCTION get_allitems
RETURN SYS_REFCURSOR
AS
my_cursor SYS_REFCURSOR;
BEGIN
OPEN my_cursor FOR SELECT * FROM allitems;
RETURN my_cursor;
END get_allitems;
This will return the cursor.
Make sure not to put your SELECT
-String into quotes in PL/SQL when possible. Putting it in strings means that it can not be checked at compile time, and that it has to be parsed whenever you use it.
If you really need to use dynamic SQL you can put your query in single quotes:
OPEN my_cursor FOR 'SELECT * FROM allitems';
This string has to be parsed whenever the function is called, which will usually be slower and hides errors in your query until runtime.
Make sure to use bind-variables where possible to avoid hard parses:
OPEN my_cursor FOR 'SELECT * FROM allitems WHERE id = :id' USING my_id;
You can use a light weight webserver to serve the file.
For example,
1. install Node
2. install the "http-server" (or similar) package
3. Run the http-server package ( "http-server -c-1") from the folder where the script file is located
4. Load the script from chrome console (run the following script on chrome console
var ele = document.createElement("script");
var scriptPath = "http://localhost:8080/{scriptfilename}.js" //verify the script path
ele.setAttribute("src",scriptPath);
document.head.appendChild(ele)
Create a file called "SetFile.bat" that contains the following line with no carriage return at the end of it...
set FileContents=
Then in your batch file do something like this...
@echo off
copy SetFile.bat + %1 $tmp$.bat > nul
call $tmp$.bat
del $tmp$.bat
%1 is the name of your input file and %FileContents% will contain the contents of the input file after the call. This will only work on a one line file though (i.e. a file containing no carriage returns). You could strip out/replace carriage returns from the file before calling the %tmp%.bat if needed.
my openion is valueof() always called tostring() for representaion and so for rpresentaion of primtive type valueof is generalized.and java by default does not support Data type but it define its work with objaect and class its made all thing in cllas and made object .here Integer.toString(int i) create a limit that conversion for only integer.
We should always go for equals() method for comparison for two integers.Its the recommended practice.
If we compare two integers using == that would work for certain range of integer values (Integer from -128 to 127) due to JVM's internal optimisation.
Please see examples:
Case 1:
Integer a = 100; Integer b = 100;
if (a == b) { System.out.println("a and b are equal"); } else { System.out.println("a and b are not equal"); }
In above case JVM uses value of a and b from cached pool and return the same object instance(therefore memory address) of integer object and we get both are equal.Its an optimisation JVM does for certain range values.
Case 2: In this case, a and b are not equal because it does not come with the range from -128 to 127.
Integer a = 220; Integer b = 220;
if (a == b) { System.out.println("a and b are equal"); } else { System.out.println("a and b are not equal"); }
Proper way:
Integer a = 200;
Integer b = 200;
System.out.println("a == b? " + a.equals(b)); // true
I hope this helps.
If you are using MVC, you put this in the web.config file in the Root directory of the web application, not the web.config in the Views directory. It also needs to be IN the system.web node, not under like George2 stated in his question: "I wrote under system.web section in the web.config"
The timeout parameter value represents minutes.
There are other attributes that can be set in the sessionState element. You can find information here: docs.microsoft.com sessionState
<configuration>
<system.web>
<sessionState timeout="20"></sessionState>
</system.web>
</configuration>
You can then catch the begining of a new session in the Global.asax file by adding the following method:
void Session_Start(object sender, EventArgs e)
{
if (Session.IsNewSession)
{
//do things that need to happen
//when a new session starts.
}
}
Here is the simple solution with StreamEx
EntryStream.of(countByType).sortedBy(e -> e.getValue()).keys().toList();
Beside the well-known (and already mentioned) System.currentTimeMillis()
and System.nanoTime()
there is also a neat library called perf4j which might be useful too, depending on your purpose of course.
In my experience, in an armeabi-v7a mobile, when both armeabi and armeabi-v7a directories are present in the apk, the .so files in armeabi directory won't be linked, although the .so files in armeabi WILL be linked in the same armeabi-v7a mobile, if armeabi-v7a is not present.
I actually wound up just going into index.js in the file-loader module and changing where the contents were emitted to. This is probably not the optimal solution, but until there's some other way, this is fine since I know exactly what's being handled by this loader, which is just fonts.
//index.js
var loaderUtils = require("loader-utils");
module.exports = function(content) {
this.cacheable && this.cacheable();
if(!this.emitFile) throw new Error("emitFile is required from module system");
var query = loaderUtils.parseQuery(this.query);
var url = loaderUtils.interpolateName(this, query.name || "[hash].[ext]", {
context: query.context || this.options.context,
content: content,
regExp: query.regExp
});
this.emitFile("fonts/"+ url, content);//changed path to emit contents to "fonts" folder rather than project root
return "module.exports = __webpack_public_path__ + " + JSON.stringify( url) + ";";
}
module.exports.raw = true;
Map
is an interface in Java. And HashMap
is an implementation of that interface (i.e. provides all of the methods specified in the interface).
I just want to add that there is a master list of IntelliJ suppress parameters at: https://gist.github.com/vegaasen/157fbc6dce8545b7f12c
It looks fairly comprehensive. Partial:
Warning Description - Warning Name
"Magic character" MagicCharacter
"Magic number" MagicNumber
'Comparator.compare()' method does not use parameter ComparatorMethodParameterNotUsed
'Connection.prepare*()' call with non-constant string JDBCPrepareStatementWithNonConstantString
'Iterator.hasNext()' which calls 'next()' IteratorHasNextCallsIteratorNext
'Iterator.next()' which can't throw 'NoSuchElementException' IteratorNextCanNotThrowNoSuchElementException
'Statement.execute()' call with non-constant string JDBCExecuteWithNonConstantString
'String.equals("")' StringEqualsEmptyString
'StringBuffer' may be 'StringBuilder' (JDK 5.0 only) StringBufferMayBeStringBuilder
'StringBuffer.toString()' in concatenation StringBufferToStringInConcatenation
'assert' statement AssertStatement
'assertEquals()' between objects of inconvertible types AssertEqualsBetweenInconvertibleTypes
'await()' not in loop AwaitNotInLoop
'await()' without corresponding 'signal()' AwaitWithoutCorrespondingSignal
'break' statement BreakStatement
'break' statement with label BreakStatementWithLabel
'catch' generic class CatchGenericClass
'clone()' does not call 'super.clone()' CloneDoesntCallSuperClone
Here is the code of ReadDoc/docx.java: This will read a dox/docx file and print its content to the console. you can customize it your way.
import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
public class ReadDocFile
{
public static void main(String[] args)
{
File file = null;
WordExtractor extractor = null;
try
{
file = new File("c:\\New.doc");
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
HWPFDocument document = new HWPFDocument(fis);
extractor = new WordExtractor(document);
String[] fileData = extractor.getParagraphText();
for (int i = 0; i < fileData.length; i++)
{
if (fileData[i] != null)
System.out.println(fileData[i]);
}
}
catch (Exception exep)
{
exep.printStackTrace();
}
}
}
Go to "Run" and execute this:
%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ir
NOTE: run as administrator.
The pid of a backgrounded child process is stored in $!. You can store all child processes' pids into an array, e.g. PIDS[].
wait [-n] [jobspec or pid …]
Wait until the child process specified by each process ID pid or job specification jobspec exits and return the exit status of the last command waited for. If a job spec is given, all processes in the job are waited for. If no arguments are given, all currently active child processes are waited for, and the return status is zero. If the -n option is supplied, wait waits for any job to terminate and returns its exit status. If neither jobspec nor pid specifies an active child process of the shell, the return status is 127.
Use wait command you can wait for all child processes finish, meanwhile you can get exit status of each child processes via $? and store status into STATUS[]. Then you can do something depending by status.
I have tried the following 2 solutions and they run well. solution01 is more concise, while solution02 is a little complicated.
#!/bin/bash
# start 3 child processes concurrently, and store each pid into array PIDS[].
process=(a.sh b.sh c.sh)
for app in ${process[@]}; do
./${app} &
PIDS+=($!)
done
# wait for all processes to finish, and store each process's exit code into array STATUS[].
for pid in ${PIDS[@]}; do
echo "pid=${pid}"
wait ${pid}
STATUS+=($?)
done
# after all processed finish, check their exit codes in STATUS[].
i=0
for st in ${STATUS[@]}; do
if [[ ${st} -ne 0 ]]; then
echo "$i failed"
else
echo "$i finish"
fi
((i+=1))
done
#!/bin/bash
# start 3 child processes concurrently, and store each pid into array PIDS[].
i=0
process=(a.sh b.sh c.sh)
for app in ${process[@]}; do
./${app} &
pid=$!
PIDS[$i]=${pid}
((i+=1))
done
# wait for all processes to finish, and store each process's exit code into array STATUS[].
i=0
for pid in ${PIDS[@]}; do
echo "pid=${pid}"
wait ${pid}
STATUS[$i]=$?
((i+=1))
done
# after all processed finish, check their exit codes in STATUS[].
i=0
for st in ${STATUS[@]}; do
if [[ ${st} -ne 0 ]]; then
echo "$i failed"
else
echo "$i finish"
fi
((i+=1))
done
To activate a Python virtual environment:
$cd ~/python-venv/
$./bin/activate
To deactivate:
$deactivate
This is basically the same answer provided by Evert, but extended to show-off
some cool options of fill_between
from matplotlib import pyplot as pl
import numpy as np
pl.clf()
pl.hold(1)
x = np.linspace(0, 30, 100)
y = np.sin(x) * 0.5
pl.plot(x, y, '-k')
x = np.linspace(0, 30, 30)
y = np.sin(x/6*np.pi)
error = np.random.normal(0.1, 0.02, size=y.shape) +.1
y += np.random.normal(0, 0.1, size=y.shape)
pl.plot(x, y, 'k', color='#CC4F1B')
pl.fill_between(x, y-error, y+error,
alpha=0.5, edgecolor='#CC4F1B', facecolor='#FF9848')
y = np.cos(x/6*np.pi)
error = np.random.rand(len(y)) * 0.5
y += np.random.normal(0, 0.1, size=y.shape)
pl.plot(x, y, 'k', color='#1B2ACC')
pl.fill_between(x, y-error, y+error,
alpha=0.2, edgecolor='#1B2ACC', facecolor='#089FFF',
linewidth=4, linestyle='dashdot', antialiased=True)
y = np.cos(x/6*np.pi) + np.sin(x/3*np.pi)
error = np.random.rand(len(y)) * 0.5
y += np.random.normal(0, 0.1, size=y.shape)
pl.plot(x, y, 'k', color='#3F7F4C')
pl.fill_between(x, y-error, y+error,
alpha=1, edgecolor='#3F7F4C', facecolor='#7EFF99',
linewidth=0)
pl.show()
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.
If you want to pre-subscribe to the same Observable which will be returned, just use
.do():
function getValueFromObservable() {
return this.store.do(
(data:any) => {
console.log("Line 1: " +data);
}
);
}
getValueFromObservable().subscribe(
(data:any) => {
console.log("Line 2: " +data)
}
);
This can be done with java reflection,This method returns false if any one attribute value is present for the object ,hope it helps some one
public boolean isEmpty() {
for (Field field : this.getClass().getDeclaredFields()) {
try {
field.setAccessible(true);
if (field.get(this)!=null) {
return false;
}
} catch (Exception e) {
System.out.println("Exception occured in processing");
}
}
return true;
}
Import namespace :
using System.Configuration;
Create ConfigurationElement Company :
public class Company : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get
{
return this["name"] as string;
}
}
[ConfigurationProperty("code", IsRequired = true)]
public string Code
{
get
{
return this["code"] as string;
}
}
}
ConfigurationElementCollection:
public class Companies
: ConfigurationElementCollection
{
public Company this[int index]
{
get
{
return base.BaseGet(index) as Company ;
}
set
{
if (base.BaseGet(index) != null)
{
base.BaseRemoveAt(index);
}
this.BaseAdd(index, value);
}
}
public new Company this[string responseString]
{
get { return (Company) BaseGet(responseString); }
set
{
if(BaseGet(responseString) != null)
{
BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
}
BaseAdd(value);
}
}
protected override System.Configuration.ConfigurationElement CreateNewElement()
{
return new Company();
}
protected override object GetElementKey(System.Configuration.ConfigurationElement element)
{
return ((Company)element).Name;
}
}
and ConfigurationSection:
public class RegisterCompaniesConfig
: ConfigurationSection
{
public static RegisterCompaniesConfig GetConfig()
{
return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
}
[System.Configuration.ConfigurationProperty("Companies")]
[ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
public Companies Companies
{
get
{
object o = this["Companies"];
return o as Companies ;
}
}
}
and you must also register your new configuration section in web.config (app.config):
<configuration>
<configSections>
<section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>
then you load your config with
var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
do something ..
}
I think @Evert has the right answer:
plt.scatter(dates,values)
plt.plot(dates, values)
plt.show()
Which is pretty much the same as
plt.plot(dates, values, '-o')
plt.show()
or whatever linestyle you prefer.
just use a reference:
Vec3b & color = image.at<Vec3b>(y,x);
color[2] = 13;
This is an improvement to Eric's answer:
UIViewController *_topMostController(UIViewController *cont) {
UIViewController *topController = cont;
while (topController.presentedViewController) {
topController = topController.presentedViewController;
}
if ([topController isKindOfClass:[UINavigationController class]]) {
UIViewController *visible = ((UINavigationController *)topController).visibleViewController;
if (visible) {
topController = visible;
}
}
return (topController != cont ? topController : nil);
}
UIViewController *topMostController() {
UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;
UIViewController *next = nil;
while ((next = _topMostController(topController)) != nil) {
topController = next;
}
return topController;
}
_topMostController(UIViewController *cont)
is a helper function.
Now all you need to do is call topMostController()
and the top most UIViewController should be returned!
Technical differences are a consequence of the goal of each one (OpenJDK is meant to be the reference implementation, open to the community, while Oracle is meant to be a commercial one)
They both have "almost" the same code of the classes in the Java API; but the code for the virtual machine itself is actually different, and when it comes to libraries, OpenJDK tends to use open libraries while Oracle tends to use closed ones; for instance, the font library.
@alvas's answer does the job but it can be done way faster. Assuming that you have documents
: a list of strings.
from nltk.corpus import stopwords
from nltk.tokenize import wordpunct_tokenize
stop_words = set(stopwords.words('english'))
stop_words.update(['.', ',', '"', "'", '?', '!', ':', ';', '(', ')', '[', ']', '{', '}']) # remove it if you need punctuation
for doc in documents:
list_of_words = [i.lower() for i in wordpunct_tokenize(doc) if i.lower() not in stop_words]
Notice that due to the fact that here you are searching in a set (not in a list) the speed would be theoretically len(stop_words)/2
times faster, which is significant if you need to operate through many documents.
For 5000 documents of approximately 300 words each the difference is between 1.8 seconds for my example and 20 seconds for @alvas's.
P.S. in most of the cases you need to divide the text into words to perform some other classification tasks for which tf-idf is used. So most probably it would be better to use stemmer as well:
from nltk.stem.porter import PorterStemmer
porter = PorterStemmer()
and to use [porter.stem(i.lower()) for i in wordpunct_tokenize(doc) if i.lower() not in stop_words]
inside of a loop.
The array form of new-expression accepts only one form of initializer: an empty ()
. This, BTW, has the same effect as the empty {}
in your non-dynamic initialization.
The above applies to pre-C++11 language. Starting from C++11 one can use uniform initialization syntax with array new-expressions
char* c = new char[length]{};
char* d = new char[length]{ 'a', 'b', 'c' };
If you can use LINQ you can use:
var e = enumerable.First();
This will throw an exception though if enumerable is empty: in which case you can use:
var e = enumerable.FirstOrDefault();
FirstOrDefault()
will return default(T)
if the enumerable is empty, which will be null
for reference types or the default 'zero-value' for value types.
If you can't use LINQ, then your approach is technically correct and no different than creating an enumerator using the GetEnumerator
and MoveNext
methods to retrieve the first result (this example assumes enumerable is an IEnumerable<Elem>
):
Elem e = myDefault;
using (IEnumerator<Elem> enumer = enumerable.GetEnumerator()) {
if (enumer.MoveNext()) e = enumer.Current;
}
Joel Coehoorn mentioned .Single()
in the comments; this will also work, if you are expecting your enumerable to contain exactly one element - however it will throw an exception if it is either empty or larger than one element. There is a corresponding SingleOrDefault()
method that covers this scenario in a similar fashion to FirstOrDefault()
. However, David B explains that SingleOrDefault()
may still throw an exception in the case where the enumerable contains more than one item.
Edit: Thanks Marc Gravell for pointing out that I need to dispose of my IEnumerator
object after using it - I've edited the non-LINQ example to display the using
keyword to implement this pattern.
First quote your javascript:
onclick="hello();"
Also you can't call a php function from javascript; you need:
<script type="text/javascript">
function hello()
{
alert ("hello");
}
</script>
In PHP you simply can convert a value to a boolean by using double not operator (!!
):
var_dump(!! true); // true
var_dump(!! "Hello"); // true
var_dump(!! 1); // true
var_dump(!! [1, 2]); // true
var_dump(!! false); // false
var_dump(!! null); // false
var_dump(!! []); // false
var_dump(!! 0); // false
var_dump(!! ''); // false
function telephoneCheck(str) {_x000D_
var a = /^(1\s|1|)?((\(\d{3}\))|\d{3})(\-|\s)?(\d{3})(\-|\s)?(\d{4})$/.test(str);_x000D_
alert(a);_x000D_
}_x000D_
telephoneCheck("(555) 555-5555");
_x000D_
Where str could be any of these formats: 555-555-5555 (555)555-5555 (555) 555-5555 555 555 5555 5555555555 1 555 555 5555
If you are defining a constant to be shared among all the instances of the class, use static const. If the constant is specific to each instance, just use const (but note that all constructors of the class must initialize this const member variable in the initialization list).
It is now possible since 25.3.0 version to call setSelectedItemId()
\o/
For those of you who are here because you are trying to serve a react app from an IIS Virtual Directory (not the root of a website) then this may be for you.
When setting up your redirects '/' wont work on its own, for me it needed the virtual directory name in there too. Here is what my web config looked like:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<defaultDocument>
<files>
<remove value="default.aspx" />
<remove value="iisstart.htm" />
<remove value="index.htm" />
<remove value="Default.asp" />
<remove value="Default.htm" />
</files>
</defaultDocument>
<rewrite>
<rules>
<rule name="React Routes" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
<add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
</conditions>
<action type="Rewrite" url="/YOURVIRTUALDIRECTORYNAME/" />
</rule>
</rules>
</rewrite>
<directoryBrowse enabled="false" />
<httpErrors errorMode="Custom" defaultResponseMode="ExecuteURL">
<remove statusCode="500" subStatusCode="100" />
<remove statusCode="500" subStatusCode="-1" />
<remove statusCode="404" subStatusCode="-1" />
<remove statusCode="403" subStatusCode="18" />
<error statusCode="403" subStatusCode="18" path="/YOURVIRTUALDIRECTORYNAME/" responseMode="ExecuteURL" />
<error statusCode="404" path="/YOURVIRTUALDIRECTORYNAME/" responseMode="ExecuteURL" />
<error statusCode="500" prefixLanguageFilePath="" path="/YOURVIRTUALDIRECTORYNAME/" responseMode="ExecuteURL" />
<error statusCode="500" subStatusCode="100" path="/YOURVIRTUALDIRECTORYNAME/" responseMode="ExecuteURL" />
</httpErrors>
</system.webServer>
</configuration>
In addition to the web.config file the react app isself needed some changes:
in package.json you need to add a 'homepage' entry:
{
"name": "sicon.react.crm",
"version": "0.1.0",
"private": true,
"homepage": "/YOURVIRTUALDIRECTORYNAME/",
"dependencies": {
...
I added the basename to my browser history object that I pass into the router to get access to history:
import {createBrowserHistory } from 'history';
export default createBrowserHistory({
//Pass the public URL as the base name for the router basename: process.env.PUBLIC_URL
});
I also added this property on my React router in App.js:
<Router history={history} basename={process.env.PUBLIC_URL}>
Finally, in index.html I added the following tab above the 'title' tag
<base href="%PUBLIC_URL%/">
it may be that some steps where note required but this seems to have done the job for me. I don't know how to set it up to run either in the root of a site or a virtual directory without a recompile though as the homepage in the package.json
can't be swapped after a build as far as I'm aware.
You're just missing one critical step. You have to explicitly pass the return value in to the second function.
def main():
l = defineAList()
useTheList(l)
Alternatively:
def main():
useTheList(defineAList())
Or (though you shouldn't do this! It might seem nice at first, but globals just cause you grief in the long run.):
l = []
def defineAList():
global l
l.extend(['1','2','3'])
def main():
global l
defineAList()
useTheList(l)
The function returns a value, but it doesn't create the symbol in any sort of global namespace as your code assumes. You have to actually capture the return value in the calling scope and then use it for subsequent operations.
This is spruced up from the answers just above and uses the length/number of options to conform to how many options there actually are.
Hope this helps somebody get the results they need!
function openDropdown(elementId) {
function down() {
var pos = $(this).offset(); // remember position
var len = $(this).find("option").length;
if(len > 20) {
len = 20;
}
$(this).css("position", "absolute");
$(this).css("zIndex", 9999);
$(this).offset(pos); // reset position
$(this).attr("size", len); // open dropdown
$(this).unbind("focus", down);
$(this).focus();
}
function up() {
$(this).css("position", "static");
$(this).attr("size", "1"); // close dropdown
$(this).unbind("change", up);
$(this).focus();
}
$("#" + elementId).focus(down).blur(up).focus();
}
use "\p{Pd}" without quotes to match any type of hyphen. The '-' character is just one type of hyphen which also happens to be a special character in Regex.
Python installation folder > Lib > idlelib > idle.pyw
send a shortcut to desktop.
From the desktop shortcut you can add it to taskbar too for quickaccess.
Hope this helps.
Add store name to template like {% url 'app_name:url_name' %}
App_name = store
In urls.py,
path('search', views.searched, name="searched"),
<form action="{% url 'store:searched' %}" method="POST">
The problem here is the performance, if you have a lot of rows it will be a problem.
If it is your case, please try with this:
import pandas as pd
source = pd.DataFrame({'Country' : ['USA', 'USA', 'Russia','USA'],
'City' : ['New-York', 'New-York', 'Sankt-Petersburg', 'New-York'],
'Short_name' : ['NY','New','Spb','NY']})
source.groupby(['Country','City']).agg(lambda x:x.value_counts().index[0])
source.groupby(['Country','City']).Short_name.value_counts().groupby['Country','City']).first()
The warning is due to you attempting to add an integer (int shift = 3
) to a character value. You can change the data type to char
if you want to avoid that.
A char
is 16 bits, an int
is 32.
char shift = 3;
// ...
eMessage[i] = (message[i] + shift) % (char)letters.length;
As an aside, you can simplify the following:
char[] message = {'o', 'n', 'c', 'e', 'u', 'p', 'o', 'n', 'a', 't', 'i', 'm', 'e'};
To:
char[] message = "onceuponatime".toCharArray();
You can break up long lines with the caret ^
as long as you remember that the caret and the newline following it are completely removed. So, if there should be a space where you're breaking the line, include a space. (More on that below.)
Example:
copy file1.txt file2.txt
would be written as:
copy file1.txt^
file2.txt
You could do that:
KeyValuePair<TKey, TValue>
's in the dictionary (which will be a sizable performance hit if you have a number of entries in the dictionary) Use Method 1 if performance is not a consideration, use Method 2 if memory is not a consideration.
Also, all keys must be unique, but the values are not required to be unique. You may have more than one key with the specified value.
Is there any reason you can't reverse the key-value relationship?
Compute Sum of Column in Datatable , Works 100%
lbl_TotaAmt.Text = MyDataTable.Compute("Sum(BalAmt)", "").ToString();
if you want to have any conditions, use it like this
lbl_TotaAmt.Text = MyDataTable.Compute("Sum(BalAmt)", "srno=1 or srno in(1,2)").ToString();
This took me a while to figure out so this is how I got it working - Angular WebAPI ASP Routing without the # for SEO
Add $locationProvider.html5Mode(true); to app.config
I needed a certain controller (which was in the home controller) to be ignored for uploading images so I added that rule to RouteConfig
routes.MapRoute(
name: "Default2",
url: "Home/{*.}",
defaults: new { controller = "Home", action = "SaveImage" }
);
In Global.asax add the following - making sure to ignore api and image upload paths let them function as normal otherwise reroute everything else.
private const string ROOT_DOCUMENT = "/Index.html";
protected void Application_BeginRequest(Object sender, EventArgs e)
{
var path = Request.Url.AbsolutePath;
var isApi = path.StartsWith("/api", StringComparison.InvariantCultureIgnoreCase);
var isImageUpload = path.StartsWith("/home", StringComparison.InvariantCultureIgnoreCase);
if (isApi || isImageUpload)
return;
string url = Request.Url.LocalPath;
if (!System.IO.File.Exists(Context.Server.MapPath(url)))
Context.RewritePath(ROOT_DOCUMENT);
}
Make sure to use $location.url('/XXX') and not window.location ... to redirect
Reference the CSS files with absolute path
and not
<link href="app/content/bootstrapwc.css" rel="stylesheet" />
Final note - doing it this way gave me full control and I did not need to do anything to the web config.
Hope this helps as this took me a while to figure out.
Try using this:
$(".move_to").on("click", function(e){
e.preventDefault();
$('#contactsForm').attr('action', "/test1").submit();
});
Moving the order in which you use .preventDefault()
might fix your issue. You also didn't use function(e)
so e.preventDefault();
wasn't working.
Here it is working: http://jsfiddle.net/TfTwe/1/ - first of all, click the 'Check action attribute.' link. You'll get an alert saying undefined
. Then click 'Set action attribute.' and click 'Check action attribute.' again. You'll see that the form's action attribute has been correctly set to /test1
.
If you wanted to accomplish this with pure HTML alone, this solution will work across all major browsers:
Description Lists
Simply using the following HTML:
<dl>
<dt>List Item 1</dt>
<dd>Sub-Item 1.1</dd>
<dt>List Item 2</dt>
<dd>Sub-Item 2.1</dd>
<dd>Sub-Item 2.2</dd>
<dd>Sub-Item 2.3</dd>
<dt>List Item 3</dt>
<dd>Sub-Item 3.1</dd>
</dl>
_x000D_
Example here: https://jsfiddle.net/zumcmvma/2/
Reference here: https://www.w3schools.com/tags/tag_dl.asp
I would recommend neXtep for version controlling the database it has got a good set of documentation and forums that explains how to install and the errors encountered. I have tested it for postgreSQL 9.1 and 9.3, i was able to get it working for 9.1 but for 9.3 it doesn't seems to work.
If you're already using Lodash, you can do this simple approach which includes both key and value:
<ul>
<li *ngFor='let key of _.keys(demo)'>{{key}}: {{demo[key]}}</li>
</ul>
In the typescript file, include:
import * as _ from 'lodash';
and in the exported component, include:
_: any = _;
You need to enclose that in <%! %> as follows:
<%!
public String getQuarter(int i){
String quarter;
switch(i){
case 1: quarter = "Winter";
break;
case 2: quarter = "Spring";
break;
case 3: quarter = "Summer I";
break;
case 4: quarter = "Summer II";
break;
case 5: quarter = "Fall";
break;
default: quarter = "ERROR";
}
return quarter;
}
%>
You can then invoke the function within scriptlets or expressions:
<%
out.print(getQuarter(4));
%>
or
<%= getQuarter(17) %>
I couldn't draw a circle inside my ConstraintLayout for some reason, I just couldn't use any of the answers above.
What did work perfectly is a simple TextView with the text that comes out, when you press "Alt+7":
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#0075bc"
android:textSize="40dp"
android:text="•"></TextView>
Try Foo.instance_methods.include? :bar
private void CleanForm(Control ctrl)
{
foreach (var c in ctrl.Controls)
{
if (c is TextBox)
{
((TextBox)c).Text = String.Empty;
}
if( c.Controls.Count > 0)
{
CleanForm(c);
}
}
}
When you initially call ClearForm, pass in this, or Page (I assume that is what 'this' is).
You can do this using Input.setSelectionRange
, part of the Range API for interacting with text selections and the text cursor:
var searchInput = $('#Search');
// Multiply by 2 to ensure the cursor always ends up at the end;
// Opera sometimes sees a carriage return as 2 characters.
var strLength = searchInput.val().length * 2;
searchInput.focus();
searchInput[0].setSelectionRange(strLength, strLength);
Demo: Fiddle
You are looking for JavaScript's String
method substring
e.g.
'Hiya how are you'.substring(0,8);
Which returns the string starting at the first character and finishing before the 9th character - i.e. 'Hiya how'.
I run pre-startup stuff like migrations in a separate ephemeral container, like so (note, compose file has to be of version '2' type):
db:
image: postgres
web:
image: app
command: python manage.py runserver 0.0.0.0:8000
volumes:
- .:/code
ports:
- "8000:8000"
links:
- db
depends_on:
- migration
migration:
build: .
image: app
command: python manage.py migrate
volumes:
- .:/code
links:
- db
depends_on:
- db
This helps things keeping clean and separate. Two things to consider:
You have to ensure the correct startup sequence (using depends_on).
You want to avoid multiple builds which is achieved by tagging it the first time round using build and image; you can refer to image in other containers then.
You could use the setTimeout()
function:
// Your delay in milliseconds
var delay = 1000;
setTimeout(function(){ window.location = URL; }, delay);
You can directly change text or string to proper using this simple method, after checking for null or empty string values in order to eliminate errors:
public string textToProper(string text)
{
string ProperText = string.Empty;
if (!string.IsNullOrEmpty(text))
{
ProperText = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(text);
}
else
{
ProperText = string.Empty;
}
return ProperText;
}
It's just as simple as adding this:
legend: {
display: false,
}
// Or if you want you could use this other option which should also work:
Chart.defaults.global.legend.display = false;
<form method="post" name="myForm" id="myForm">
replace with above form tag remove action from form tag. and set url : "check.php" in ajax in your case first it goes to jQuery ajax then submit again the form. that's why it's creating issue.
i know i'm too late for this reply but i think it would help.