I would save that session cookie as a preference and forcefully repopulate the cookie manager with it. It sounds that session cookie in not surviving Activity restart
myWebView.loadData(myHtmlString, "text/html; charset=UTF-8", null);
This works flawlessly, especially on Android 4.0, which apparently ignores character encoding inside HTML.
Tested on 2.3 and 4.0.3.
In fact, I have no idea about what other values besides "base64" does the last parameter take. Some Google examples put null in there.
To solve Google security, do this:
Lines to the top:
import android.webkit.SslErrorHandler;
import android.net.http.SslError;
Code:
class SSLTolerentWebViewClient extends WebViewClient {
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
if (error.toString() == "piglet")
handler.cancel();
else
handler.proceed(); // Ignore SSL certificate errors
}
}
To Solve this Error in Webview Android,
First Check the Permissions in Manifest.xml,
if not define there,then define as like this.
<uses-permission android:name="android.permission.INTERNET"/>
Swift 5
if let url = URL(string: "https://www.google.com") {
UIApplication.shared.open(url)
}
webview.getSettings().setUseWideViewPort(true);
You need to set an own WebViewClient for your WebView by extending the WebViewClient class.
You need to implement the two methods onPageStarted (show here) and onPageFinished (dismiss here).
More guidance for this topic can be found in Google's WebView tutorial
I created a nice wrapper to call JavaScript methods; it also shows JavaScript errors in log:
private void callJavaScript(String methodName, Object...params){
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("javascript:try{");
stringBuilder.append(methodName);
stringBuilder.append("(");
for (int i = 0; i < params.length; i++) {
Object param = params[i];
if(param instanceof String){
stringBuilder.append("'");
stringBuilder.append(param.toString().replace("'", "\\'"));
stringBuilder.append("'");
}
if(i < params.length - 1){
stringBuilder.append(",");
}
}
stringBuilder.append(")}catch(error){Android.onError(error.message);}");
webView.loadUrl(stringBuilder.toString());
}
You need to add this too:
private class WebViewInterface{
@JavascriptInterface
public void onError(String error){
throw new Error(error);
}
}
And add this interface to your webview:
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new WebViewInterface(), "AndroidErrorReporter");
int PIC_WIDTH= webView.getRight()-webView.getLeft();
I found it necessary to define public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)
, in Android 4.1. Then I followed Michel Olivier's solution.
This question is years old, but maybe my answer will help people like me who have to support old Android version. I tried a lot of different approaches which worked on some Android versions, however not on all. The best solution I found is to use the Crosswalk Webview which is optimized for HTML5 feature support and works on Android 4.1 and higher. It is as simple to use as the default Android WebView. You just have to include the library. Here you can find a simple tutorial on how to use it: https://diego.org/2015/01/07/embedding-crosswalk-in-android-studio/
Have you tried?
mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
Example Link: Webview File Download - Thanks @c49
Why not get the html first then pass it to the web view?
private String getHtml(String url){
HttpGet pageGet = new HttpGet(url);
ResponseHandler<String> handler = new ResponseHandler<String>() {
public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
HttpEntity entity = response.getEntity();
String html;
if (entity != null) {
html = EntityUtils.toString(entity);
return html;
} else {
return null;
}
}
};
pageHTML = null;
try {
while (pageHTML==null){
pageHTML = client.execute(pageGet, handler);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return pageHTML;
}
@Override
public void customizeWebView(final ServiceCommunicableActivity activity, final WebView webview, final SearchResult mRom) {
mRom.setFileSize(getFileSize(mRom.getURLSuffix()));
webview.getSettings().setJavaScriptEnabled(true);
WebViewClient anchorWebViewClient = new WebViewClient()
{
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
//Do what you want to with the html
String html = getHTML(url);
if( html!=null && !url.equals(lastLoadedURL)){
lastLoadedURL = url;
webview.loadDataWithBaseURL(url, html, null, "utf-8", url);
}
}
This should roughly do what you want to do. It is adapted from Is it possible to get the HTML code from WebView and shout out to https://stackoverflow.com/users/325081/aymon-fournier for his answer.
read from assets html file
ViewGroup webGroup;
String content = readContent("content/ganji.html");
final WebView webView = new WebView(this);
webView.loadDataWithBaseURL(null, content, "text/html", "UTF-8", null);
webGroup.addView(webView);
To load your data in WebView. Call loadData() method of WebView
webView.loadData(yourData, "text/html; charset=utf-8", "UTF-8");
You can check this example
http://developer.android.com/reference/android/webkit/WebView.html
set the bg after loading the html(from quick tests it seems loading the html resets the bg color.. this is for 2.3).
if you're loading the html from data you already got, just doing a .postDelayed in which you just set the bg(to for example transparent) is enough..
You could call an mWebView.reload();
That's what it does
inputmode
according to WHATWG spec is the the default method.
For iOS devices adding pattern
could also help.
For backward compatibility use type
as well since Chrome use these as of version 66.
<input
inputmode="numeric"
pattern="[0-9]*"
type="number"
/>
I've also had problem with data being lost after application is restarted. Adding this helped:
webView.getSettings().setDatabasePath("/data/data/" + webView.getContext().getPackageName() + "/databases/");
Here load with progressDialog. Need to give WebClient otherwise it force to open in browser:
final ProgressDialog pDialog = new ProgressDialog(context);
pDialog.setTitle(context.getString(R.string.app_name));
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
WebView webView = (WebView) rootView.findViewById(R.id.web_view);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
pDialog.show();
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
pDialog.dismiss();
}
});
String pdf = "http://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf";
webView.loadUrl("https://drive.google.com/viewerng/viewer?embedded=true&url=" + pdf);
To clear cookie and cache from Webview,
// Clear all the Application Cache, Web SQL Database and the HTML5 Web Storage
WebStorage.getInstance().deleteAllData();
// Clear all the cookies
CookieManager.getInstance().removeAllCookies(null);
CookieManager.getInstance().flush();
webView.clearCache(true);
webView.clearFormData();
webView.clearHistory();
webView.clearSslPreferences();
You can Use Online Css link To set Style over existing content.
For That you have to load data in webview and enable JavaScript Support.
See Below Code:
WebSettings webSettings=web_desc.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDefaultTextEncodingName("utf-8");
webSettings.setTextZoom(55);
StringBuilder sb = new StringBuilder();
sb.append("<HTML><HEAD><LINK href=\" http://yourStyleshitDomain.com/css/mbl-view-content.css\" type=\"text/css\" rel=\"stylesheet\"/></HEAD><body>");
sb.append(currentHomeContent.getDescription());
sb.append("</body></HTML>");
currentWebView.loadDataWithBaseURL("file:///android_asset/", sb.toString(), "text/html", "utf-8", null);
Here Use StringBuilder to append String for Style.
sb.append("<HTML><HEAD><LINK href=\" http://yourStyleshitDomain.com/css/mbl-view-content.css\" type=\"text/css\" rel=\"stylesheet\"/></HEAD><body>");
sb.append(currentHomeContent.getDescription());
Swift 2.0
This is how to check if the file exists using Swift
func isFileExistsInDirectory() -> Bool {
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let documentsDirectory: AnyObject = paths[0]
let dataPath = documentsDirectory.stringByAppendingPathComponent("/YourFileName")
return NSFileManager.defaultManager().fileExistsAtPath(dataPath)
}
TL;DR
headroom_by_jQuery = $('#id').offset().top - $(window).scrollTop();
headroom_by_DOM = $('#id')[0].getBoundingClientRect().top; // if no iframe
.getBoundingClientRect() appears to be universal. .offset() and .scrollTop() have been supported since jQuery 1.2. Thanks @user372551 and @prograhammer. To use DOM in an iframe see @ImranAnsari's solution.
Implement both deprecated and non-deprecated methods like below. First one is to handle API level 21 and higher, second one is handle lower than API level 21
webViewClient = object : WebViewClient() {
.
.
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
parseUri(request?.url)
return true
}
@SuppressWarnings("deprecation")
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
parseUri(Uri.parse(url))
return true
}
}
For a horizontal progress bar, you first need to define your progress bar and link it with your XML file like this, in the onCreate
:
final TextView txtview = (TextView)findViewById(R.id.tV1);
final ProgressBar pbar = (ProgressBar) findViewById(R.id.pB1);
Then, you may use onProgressChanged Method in your WebChromeClient:
MyView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
if(progress < 100 && pbar.getVisibility() == ProgressBar.GONE){
pbar.setVisibility(ProgressBar.VISIBLE);
txtview.setVisibility(View.VISIBLE);
}
pbar.setProgress(progress);
if(progress == 100) {
pbar.setVisibility(ProgressBar.GONE);
txtview.setVisibility(View.GONE);
}
}
});
After that, in your layout you have something like this
<TextView android:text="Loading, . . ."
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="@+id/tV1" android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textColor="#000000"></TextView>
<ProgressBar android:id="@+id/pB1"
style="?android:attr/progressBarStyleHorizontal" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_centerVertical="true"
android:padding="2dip">
</ProgressBar>
This is how I did it in my app.
None of those answers was not helpful for me.
Finally I have found reason and solution. The reason was a lot of CSS3 filters (filter, -webkit-filter).
Solution
I have added detection of WebView in web page script in order to add class "lowquality" to HTML body. BTW. You can easily track WebView by setting user-agent in WebView settings. Then I created new CSS rule
body.lowquality * { filter: none !important; }
Strange. Inside OnCreate method, I'm using
webView.getSettings().setBuiltInZoomControls(true);
And it's working fine here. Anything particular in your webview ?
You could use the String.charAt(int index)
method result as the parameter for String.valueOf(char c).
String.valueOf(myString.charAt(3)) // This will return a string of the character on the 3rd position.
Try setting the style to display=none:
<img src="a.gif" style="display:none">
Being relatively new to Python I'm not sure what the most common idiom is, but the simplest thing I can think of is just using a module instead of a class. What would have been instance methods on your class become just functions in the module and any data just becomes variables in the module instead of members of the class. I suspect this is the pythonic approach to solving the type of problem that people use singletons for.
If you really want a singleton class, there's a reasonable implementation described on the first hit on Google for "Python singleton", specifically:
class Singleton:
__single = None
def __init__( self ):
if Singleton.__single:
raise Singleton.__single
Singleton.__single = self
That seems to do the trick.
Like the other answers, it's impossible. Here is the comment about breaker in underscore underscore issue #21
As mentioned in other answers, all of the following will work for the standard string-based syntax.
WAITFOR DELAY '02:00' --Two hours
WAITFOR DELAY '00:02' --Two minutes
WAITFOR DELAY '00:00:02' --Two seconds
WAITFOR DELAY '00:00:00.200' --Two tenths of a seconds
There is also an alternative method of passing it a DATETIME
value. You might think I'm confusing this with WAITFOR TIME
, but it also works for WAITFOR DELAY
.
Considerations for passing DATETIME
:
'1900-01-01'
).DATETIME
than to properly format a VARCHAR
.How to wait for 2 seconds:
--Example 1
DECLARE @Delay1 DATETIME
SELECT @Delay1 = '1900-01-01 00:00:02.000'
WAITFOR DELAY @Delay1
--Example 2
DECLARE @Delay2 DATETIME
SELECT @Delay2 = dateadd(SECOND, 2, convert(DATETIME, 0))
WAITFOR DELAY @Delay2
A note on waiting for TIME
vs DELAY
:
Have you ever noticed that if you accidentally pass WAITFOR TIME
a date that already passed, even by just a second, it will never return? Check it out:
--Example 3
DECLARE @Time1 DATETIME
SELECT @Time1 = getdate()
WAITFOR DELAY '00:00:01'
WAITFOR TIME @Time1 --WILL HANG FOREVER
Unfortunately, WAITFOR DELAY
will do the same thing if you pass it a negative DATETIME
value (yes, that's a thing).
--Example 4
DECLARE @Delay3 DATETIME
SELECT @Delay3 = dateadd(SECOND, -1, convert(DATETIME, 0))
WAITFOR DELAY @Delay3 --WILL HANG FOREVER
However, I would still recommend using WAITFOR DELAY
over a static time because you can always confirm your delay is positive and it will stay that way for however long it takes your code to reach the WAITFOR
statement.
Here you can find the direct download link for Curl.exe
I was looking for the download process of Curl and every where they said copy curl.exe file in System32 but they haven't provided the direct link but after digging little more I Got it. so here it is enjoy, find curl.exe easily in bin folder just
unzip it and then go to bin folder there you get exe file
I have an utility method to switch to the required window as shown below
public class Utility
{
public static WebDriver getHandleToWindow(String title){
//parentWindowHandle = WebDriverInitialize.getDriver().getWindowHandle(); // save the current window handle.
WebDriver popup = null;
Set<String> windowIterator = WebDriverInitialize.getDriver().getWindowHandles();
System.err.println("No of windows : " + windowIterator.size());
for (String s : windowIterator) {
String windowHandle = s;
popup = WebDriverInitialize.getDriver().switchTo().window(windowHandle);
System.out.println("Window Title : " + popup.getTitle());
System.out.println("Window Url : " + popup.getCurrentUrl());
if (popup.getTitle().equals(title) ){
System.out.println("Selected Window Title : " + popup.getTitle());
return popup;
}
}
System.out.println("Window Title :" + popup.getTitle());
System.out.println();
return popup;
}
}
It will take you to desired window once title of the window is passed as parameter. In your case you can do.
Webdriver childDriver = Utility.getHandleToWindow("titleOfChildWindow");
and then again switch to parent window using the same method
Webdriver parentDriver = Utility.getHandleToWindow("titleOfParentWindow");
This method works effectively when dealing with multiple windows.
For substracting in moment.js:
moment().subtract(1, 'months').format('MMM YYYY');
Documentation:
http://momentjs.com/docs/#/manipulating/subtract/
Before version 2.8.0, the moment#subtract(String, Number) syntax was also supported. It has been deprecated in favor of moment#subtract(Number, String).
moment().subtract('seconds', 1); // Deprecated in 2.8.0
moment().subtract(1, 'seconds');
As of 2.12.0 when decimal values are passed for days and months, they are rounded to the nearest integer. Weeks, quarters, and years are converted to days or months, and then rounded to the nearest integer.
moment().subtract(1.5, 'months') == moment().subtract(2, 'months')
moment().subtract(.7, 'years') == moment().subtract(8, 'months') //.7*12 = 8.4, rounded to 8
As of now (Jan 2017 / Angular > 2.0) you can use the following:
changeBackground(): any {
return { 'background-color': this.color };
}
and
<div class="circle" [ngStyle]="changeBackground()">
<!-- <content></content> --> <!-- content is now deprecated -->
<ng-content><ng-content> <!-- Use ng-content instead -->
</div>
The shortest way is probably like this:
<div class="circle" [ngStyle]="{ 'background-color': color }">
<!-- <content></content> --> <!-- content is now deprecated -->
<ng-content><ng-content> <!-- Use ng-content instead -->
</div>
It's actually working quite good with:
import sys
mods = [m.__name__ for m in sys.modules.values() if m]
This will create a list with importable module names.
Just adding this. In your package.json, if your "main": "index.js" is correctly set. Just use node .
{
"name": "app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
...
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
...
},
"devDependencies": {
...
}
}
I think the issue is with binding:
constructor(props){
super(props);
this.goBack = this.goBack.bind(this); // i think you are missing this
}
goBack(){
this.props.history.goBack();
}
.....
<button onClick={this.goBack}>Go Back</button>
As I have assumed before you posted the code:
constructor(props) {
super(props);
this.handleNext = this.handleNext.bind(this);
this.handleBack = this.handleBack.bind(this); // you are missing this line
}
Try:
Closing all instances of VS and then deleting the account for the TFS server in Control Panel -> User Accounts-> Credentail manager
In Certificates Panel, right click some certificate -> All tasks -> Manage private key -> Add IIS_IUSRS User with full control
In my case, I didnt't need to install my certificate with "Allow private key to be exported" option checked, like said in other answers.
I came across this thread and solve the issue by below steps, My problem may be different. Hope this can help some one .
In Turn windows feature on and off navigate to server roles and select the least below mentioned items .
Cheers !
"Stdafx.h" is a precompiled header.It include file for standard system include files and for project-specific include files that are used frequently but are changed infrequently.which reduces compile time and Unnecessary Processing.
Precompiled Header stdafx.h is basically used in Microsoft Visual Studio to let the compiler know the files that are once compiled and no need to compile it from scratch. You can read more about it
http://www.cplusplus.com/articles/1TUq5Di1/
https://docs.microsoft.com/en-us/cpp/ide/precompiled-header-files?view=vs-2017
var leg= $scope.name.length;
$log.info(leg);
Are you sure you don't want to actually merge the branches? If the working branch has some recent commits you don't want, you can just create a new branch with a HEAD at the point you want.
Now, if you really do want to cherry-pick a range of commits, for whatever reason, an elegant way to do this is to just pull of a patchset and apply it to your new integration branch:
git format-patch A..B
git checkout integration
git am *.patch
This is essentially what git-rebase is doing anyway, but without the need to play games. You can add --3way
to git-am
if you need to merge. Make sure there are no other *.patch files already in the directory where you do this, if you follow the instructions verbatim...
Dont forget the "BUTTON" element wich can handle some more HTML inside...
In the simple setup you are likely using, getchar
works with buffered input, so you have to press enter before getchar gets anything to read. Strings are not terminated by EOF
; in fact, EOF
is not really a character, but a magic value that indicates the end of the file. But EOF
is not part of the string read. It's what getchar
returns when there is nothing left to read.
Executing following sql (It will only work when you don't have multiple mdf/ldf files for same database)
SELECT
db.name AS DBName,
(select mf.Physical_Name FROM sys.master_files mf where mf.type_desc = 'ROWS' and db.database_id = mf.database_id ) as DataFile,
(select mf.Physical_Name FROM sys.master_files mf where mf.type_desc = 'LOG' and db.database_id = mf.database_id ) as LogFile
FROM sys.databases db
will return this output
DBName DataFile LogFile
--------------------------------------------------------------------------------
master C:\....\master.mdf C:\....\mastlog.ldf
tempdb C:\....\tempdb.mdf C:\....\templog.ldf
model C:\....\model.mdf C:\....\modellog.ldf
and rest of the databases
If your TempDB's have multiple MDF's (like mine have), this script will fail. However, you can use
WHERE db.database_id > 4
at the end and it will return all databases except system databases.
It will kill not only all plot windows, but all processes that are called python3, except the current script you run. It works for python3. So, if you are running any other python3 script it will be terminated. As I only run one script at once, it does the job for me.
import os
import subprocess
subprocess.call(["bash","-c",'pyIDs=($(pgrep python3));for x in "${pyIDs[@]}"; do if [ "$x" -ne '+str(os.getpid())+' ];then kill -9 "$x"; fi done'])
VB is full of things like that trying to make it both "like English" and comfortable for people who are used to languages that use () and {} a lot. And on the other side, as you already probably know, most of the time you can use () with function calls if you want to, but don't have to.
I prefer IsNothing()... but I use C and C#, so that's just what is comfortable. And I think it's more readable. But go with whatever feels more comfortable to you.
You can do as yAnTar advised
ALTER TABLE TABLE_NAME ADD Id INT AUTO_INCREMENT PRIMARY KEY
OR
You can add a constraint
ALTER TABLE TABLE_NAME ADD CONSTRAINT constr_ID UNIQUE (user_id, game_id, date, time)
But I think to not lose your existing data, you can add an indentity column and then make a composite key.
const response = await fetch('http://localhost/foo.txt');
const data = await response.text();
console.log(data);
Note that await
can only be used in an async
function. A longer example might be
async function loadFileAndPrintToConsole(url) {_x000D_
try {_x000D_
const response = await fetch(url);_x000D_
const data = await response.text();_x000D_
console.log(data);_x000D_
} catch (err) {_x000D_
console.error(err);_x000D_
}_x000D_
}_x000D_
_x000D_
loadFileAndPrintToConsole('https://threejsfundamentals.org/LICENSE');
_x000D_
@media screen and (max-width : 760px)
(for tablets and phones) and use with this: <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
Both are shorthands for longer expressions.
?:
is short for $a ? $a : $b
. This expression will evaluate to $a if $a evaluates to TRUE.
??
is short for isset($a) ? $a : $b
. This expression will evaluate to $a if $a is set and not null.
Their use cases overlaps when $a is undefined or null. When $a is undefined ??
will not produce an E_NOTICE, but the results are the same. When $a is null the result is the same.
I wrote a very simple class for exporting to "Excel XML" aka SpreadsheetML. It's not quite as convenient for the end user as XSLX (depending on file extension and Excel version, they may get a warning message), but it's a lot easier to work with than XLS or XLSX.
Easiest and Safest Method If you know that you really want to change/update your data structure so that the database can sync with your DBContext, The safest way is to:
This tells EF to make changes to your database so that it matches your DBContext data structure
You can also do this:
var x = new object[] {
new { firstName = "john", lastName = "walter" },
new { brand = "BMW" }
};
And if they are the same anonymous type (firstName and lastName), you won't need to cast as object
.
var y = new [] {
new { firstName = "john", lastName = "walter" },
new { firstName = "jill", lastName = "white" }
};
After I removed
\usepackage{fontspec}% font selecting commands
\usepackage{xunicode}% unicode character macros
\usepackage{xltxtra} % some fixes/extras
it seems to have worked "correctly".
It may be worth noting that the headers and footers only appear from page 2 onwards. Although I've tried the fix for this given in the fancyhdr documentation, I can't get it to work either.
FYI: MikTeX 2.7 under Vista
Here ya go:
viewNoteDateMonth.text = [[displayDate objectAtIndex:2] uppercaseString];
Btw:
"april"
is lowercase
? [NSString lowercaseString]
"APRIL"
is UPPERCASE
? [NSString uppercaseString]
"April May"
is Capitalized/Word Caps
? [NSString capitalizedString]
"April may"
is Sentence caps
? (method missing; see workaround below)
Hence what you want is called "uppercase", not "capitalized". ;)
As for "Sentence Caps" one has to keep in mind that usually "Sentence" means "entire string". If you wish for real sentences use the second method, below, otherwise the first:
@interface NSString ()
- (NSString *)sentenceCapitalizedString; // sentence == entire string
- (NSString *)realSentenceCapitalizedString; // sentence == real sentences
@end
@implementation NSString
- (NSString *)sentenceCapitalizedString {
if (![self length]) {
return [NSString string];
}
NSString *uppercase = [[self substringToIndex:1] uppercaseString];
NSString *lowercase = [[self substringFromIndex:1] lowercaseString];
return [uppercase stringByAppendingString:lowercase];
}
- (NSString *)realSentenceCapitalizedString {
__block NSMutableString *mutableSelf = [NSMutableString stringWithString:self];
[self enumerateSubstringsInRange:NSMakeRange(0, [self length])
options:NSStringEnumerationBySentences
usingBlock:^(NSString *sentence, NSRange sentenceRange, NSRange enclosingRange, BOOL *stop) {
[mutableSelf replaceCharactersInRange:sentenceRange withString:[sentence sentenceCapitalizedString]];
}];
return [NSString stringWithString:mutableSelf]; // or just return mutableSelf.
}
@end
I know this is an old post, but I wanted to add something I learned for the next folks who land here while googling.
In Powershell 5.1, you want to use continue
to move onto the next item in your loop. I tested with 6 items in an array, had a foreach
loop through, but put an if statement with:
foreach($i in $array){
write-host -fore green "hello $i"
if($i -like "something"){
write-host -fore red "$i is bad"
continue
write-host -fore red "should not see this"
}
}
Of the 6 items, the 3rd one was something. As expected, it looped through the first 2, then the matching something gave me the red line where $i
matched, I saw something is bad
and then it went on to the next item in the array without saying should not see this
. I tested with return
and it exited the loop altogether.
I'm not sure why the accepted answer was accepted if the suggested solution did not and does not solve the issue. There can actually be two related issues related to this topic.
Issue #1
The master page (e.g. _Layout.cshtml
) has a section defined and it is required but the inheriting views did not implement it. For example,
The Layout Template
<body>
@* Visible only to admin users *@
<div id="option_box">
@* this section is required due to the absence of the second parameter *@
@RenderSection("OptionBox")
</div>
</body>
The Inheriting View
No need to show any code, just consider that there is no implementation of @section OptionBox {}
on the view.
The Error for Issue #1
Section not defined: "OptionBox ".
Issue #2
The master page (e.g. _Layout.cshtml
) has a section defined and it is required AND the inheriting view did implement it. However, the implementing view have additional script
sections that are not defined on (any of) its master page(s).
The Layout Template
same as above
The Inheriting View
<div>
<p>Looks like the Lakers can still make it to the playoffs</p>
</div>
@section OptionBox {
<a href"">Go and reserve playoff tickets now</a>
}
@section StatsBox {
<ul>
<li>1. San Antonio</li>
<li>8. L. A. Lakers</li>
</ul>
}
The Error for Issue #2
The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "StatsBox"
The OP's issue is similar to Issue #2 and the accepted answer is for Issue #1.
I am just providing another case where you can get this error message. The solution will be the same as Adam has mentioned above. This is from a real code and I renamed the class name.
class FooReader {
public:
/** Constructor */
FooReader() : d(new FooReaderPrivate(this)) { } // will not compile here
.......
private:
FooReaderPrivate* d;
};
====== In a separate file =====
class FooReaderPrivate {
public:
FooReaderPrivate(FooReader*) : parent(p) { }
private:
FooReader* parent;
};
The above will no pass the compiler and get error: invalid use of incomplete type FooReaderPrivate. You basically have to put the inline portion into the *.cpp implementation file. This is OK. What I am trying to say here is that you may have a design issue. Cross reference of two classes may be necessary some cases, but I would say it is better to avoid them at the start of the design. I would be wrong, but please comment then I will update my posting.
If you run into issues with grabbing the source .dot directly you can also use Source.from_file
like this:
from graphviz import Source
from sklearn import tree
tree.export_graphviz(dtreg, out_file='tree.dot', feature_names=X.columns)
Source.from_file('tree.dot')
Generate a number in the range from 100000
to 999999
.
// pseudo code
int n = 100000 + random_float() * 900000;
For more details see the documentation for Random
I got resolved my self after spending couple of hours.
I installed Apache/2.4.7 (Ubuntu) through coookbook in vagrant vm.
/etc/apache2/apache2.conf file does not have <VirtualHost *:80>
element by default.
I did two changes to get it done
<VirtualHost *:80>
then finally I just booted vm..
update: added safer method
check out the previous (unchanged) state of your file; notice the double dash
git checkout HEAD^ -- /path/to/file
commit it:
git commit -am "revert changes on this file, not finished with it yet"
push it, no force needed:
git push
get back to your unfinished work, again do (3 times arrow up):
git checkout HEAD^ -- /path/to/file
To modify the last commit of the repository HEAD, obfuscating your accidentally pushed work, while potentially running into a conflict with your colleague who may have pulled it already, and who will grow grey hair and lose lots of time trying to reconcile his local branch head with the central one:
To remove file change from last commit:
to revert the file to the state before the last commit, do:
git checkout HEAD^ /path/to/file
to update the last commit with the reverted file, do:
git commit --amend
to push the updated commit to the repo, do:
git push -f
Really, consider using the preferred method mentioned before.
After hours and hours work, I created a solution like the below. I copy paste for other people that can benefit.
First create a script file and give this file executable permission.
# cd /etc/cron.daily/
# touch /etc/cron.daily/dbbackup-daily.sh
# chmod 755 /etc/cron.daily/dbbackup-daily.sh
# vi /etc/cron.daily/dbbackup-daily.sh
Then copy following lines into file with Shift+Ins
#!/bin/sh
now="$(date +'%d_%m_%Y_%H_%M_%S')"
filename="db_backup_$now".gz
backupfolder="/var/www/vhosts/example.com/httpdocs/backups"
fullpathbackupfile="$backupfolder/$filename"
logfile="$backupfolder/"backup_log_"$(date +'%Y_%m')".txt
echo "mysqldump started at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
mysqldump --user=mydbuser --password=mypass --default-character-set=utf8 mydatabase | gzip > "$fullpathbackupfile"
echo "mysqldump finished at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
chown myuser "$fullpathbackupfile"
chown myuser "$logfile"
echo "file permission changed" >> "$logfile"
find "$backupfolder" -name db_backup_* -mtime +8 -exec rm {} \;
echo "old files deleted" >> "$logfile"
echo "operation finished at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
echo "*****************" >> "$logfile"
exit 0
Edit:
If you use InnoDB and backup takes too much time, you can add "single-transaction" argument to prevent locking. So mysqldump line will be like this:
mysqldump --user=mydbuser --password=mypass --default-character-set=utf8
--single-transaction mydatabase | gzip > "$fullpathbackupfile"
If you want the .DS_Store
files to become invisible (they still exist but can't be seen) then run the following command in the "Terminal" window:
defaults write com.apple.finder AppleShowAllFiles FALSE; killall Finder
This will set the system default to stop showing these files on your Desktop and elsewhere. It will also restart the Finder in order to make this change visible (especially on your Desktop).
It isn't valid to have the same ID twice, that's why #name
only finds the first one.
You can try:
$("#form2 input").val('Hello World!');
Or,
$("#form2 input[name=name]").val('Hello World!');
If you're stuck with an invalid page and want to select all #name
s, you can use the attribute selector on the id:
$("input[id=name]").val('Hello World!');
I have found a way if you know startIndex and endIndex of the elements one need to remove from ArrayList
Let al
be the original ArrayList and startIndex
,endIndex
be start and end index to be removed from the array respectively:
al.subList(startIndex, endIndex + 1).clear();
Like @Alexis Dufrenoy proposed, the query could be:
SELECT * FROM `table` WHERE find_in_set('sports', interests)>0 OR find_in_set('pub', interests)>0
More information in the manual.
Here is the way I created ssn directive which checks for the the pattern and I have used RobinHerbots jquery.inputmask
angular.module('SocialSecurityNumberDirective', [])
.directive('socialSecurityNumber', socialSecurityNumber);
function socialSecurityNumber() {
var jquery = require('jquery');
var inputmask = require("jquery.inputmask");
return {
require: 'ngModel',
restrict: 'A',
priority: 1000,
link: function(scope,element, attr, ctrl) {
var jquery_element = jquery(element);
jquery_element.inputmask({mask:"***-**-****",autoUnmask:true});
jquery_element.on('keyup paste focus blur', function() {
var val = element.val();
ctrl.$setViewValue(val);
ctrl.$render();
});
var pattern = /^\d{9}$/;
var newValue = null;
ctrl.$validators.ssnDigits = function(value) {
newValue = element.val();
return newValue === '' ? true : pattern.test(newValue);
};
}
};
}
Swift: Ui Button create programmatically
let myButton = UIButton()
myButton.titleLabel!.frame = CGRectMake(15, 54, 300, 500)
myButton.titleLabel!.text = "Button Label"
myButton.titleLabel!.textColor = UIColor.redColor()
myButton.titleLabel!.textAlignment = .Center
If you are reencoding in your ffmpeg command line, that may be the reason why it is CPU intensive. You need to simply copy the streams to the single container. Since I do not have your command line I cannot suggest a specific improvement here. Your acodec and vcodec should be set to copy is all I can say.
EDIT: On seeing your command line and given you have already tried it, this is for the benefit of others who come across the same question. The command:
ffmpeg -i rtsp://@192.168.241.1:62156 -acodec copy -vcodec copy c:/abc.mp4
will not do transcoding and dump the file for you in an mp4. Of course this is assuming the streamed contents are compatible with an mp4 (which in all probability they are).
Select top 2 [id] from table Order by [id] desc
should give you want you the latest two rows added.
However, you will have to pay particular attention to the order by
clause as that will determine the 1st and 2nd row returned.
If the query was to be changed like this:
Select top 2 [id] from table Order by ModifiedDate desc
You could get two different rows. You will have to decide which column to use in your order by statement.
This is the PHP ternary operator (also known as a conditional operator) - if first operand evaluates true, evaluate as second operand, else evaluate as third operand.
Think of it as an "if" statement you can use in expressions. Can be very useful in making concise assignments that depend on some condition, e.g.
$param = isset($_GET['param']) ? $_GET['param'] : 'default';
There's also a shorthand version of this (in PHP 5.3 onwards). You can leave out the middle operand. The operator will evaluate as the first operand if it true, and the third operand otherwise. For example:
$result = $x ?: 'default';
It is worth mentioning that the above code when using i.e. $_GET or $_POST variable will throw undefined index notice and to prevent that we need to use a longer version, with isset
or a null coalescing operator which is introduced in PHP7:
$param = $_GET['param'] ?? 'default';
There are 8 bits in a byte (normally speaking in Windows).
However, if you are dealing with characters, it will depend on the charset/encoding. Unicode character can be 2 or 4 bytes, so that would be 16 or 32 bits, whereas Windows-1252 sometimes incorrectly called ANSI is only 1 bytes so 8 bits.
In Asian version of Windows and some others, the entire system runs in double-byte, so a character is 16 bits.
EDITED
Per Matteo's comment, all contemporary versions of Windows use 16-bits internally per character.
The col
argument in the plot
function assign colors automatically to a vector of integers. If you convert iris$Species
to numeric, notice you have a vector of 1,2 and 3s So you can apply this as:
plot(iris$Sepal.Length, iris$Sepal.Width, col=as.numeric(iris$Species))
Suppose you want red, blue and green instead of the default colors, then you can simply adjust it:
plot(iris$Sepal.Length, iris$Sepal.Width, col=c('red', 'blue', 'green')[as.numeric(iris$Species)])
You can probably see how to further modify the code above to get any unique combination of colors.
I present to you my ConcatenateRange VBA function (thanks Jean for the naming advice!) . It will take a range of cells (any dimension, any direction, etc.) and merge them together into a single string. As an optional third parameter, you can add a seperator (like a space, or commas sererated).
In this case, you'd write this to use it:
=ConcatenateRange(A1:A4)
Function ConcatenateRange(ByVal cell_range As range, _
Optional ByVal separator As String) As String
Dim newString As String
Dim cell As Variant
For Each cell in cell_range
If Len(cell) <> 0 Then
newString = newString & (separator & cell)
End if
Next
If Len(newString) <> 0 Then
newString = Right$(newString, (Len(newString) - Len(separator)))
End If
ConcatenateRange = newString
End Function
I was also facing the same issue until I added the type="module" to the script.
Before it was like this
<script src="../src/main.js"></script>
And after changing it to
<script type="module" src="../src/main.js"></script>
It worked perfectly.
Suppose I have committed changes to master branch.I will get the commit id(xyz) of the commit now i have to go to branch for which i need to push my commits.
Single commit id xyx
git checkout branch-name
git cherry-pick xyz
git push origin branch-name
Multiple commit id's xyz abc qwe
git checkout branch-name
git cherry-pick xyz abc qwe
git push origin branch-name
I'm used "for" operator.
try
{
string s = textBox2.Text;
string[] f = s.Split(',');
for (int i = 0; i < f.Length; i++)
{
MailMessage message = new MailMessage(); // Create instance of message
message.To.Add(f[i]); // Add receiver
message.From = new System.Net.Mail.MailAddress(c);// Set sender .In this case the same as the username
message.Subject = label3.Text; // Set subject
message.Body = richTextBox1.Text; // Set body of message
client.Send(message); // Send the message
message = null; // Clean up
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
since java 8 you can initialize the map in a single line and without static block
private static Map<String, Verbosity> stringMap = Arrays.stream(values())
.collect(Collectors.toMap(Enum::toString, Function.identity()));
The whereNotIn method verifies that the given column's value is not contained in the given array:
$users = DB::table('users')
->whereNotIn('id', [1, 2, 3])
->get();
This is just a wrap up of Sayan Pal answer in a shorter form, ES5 style :
var Foo = function(){
this.bar = undefined;
this.buzz = undefined;
}
var foo = Object.assign(new Foo(),{
bar: "whatever",
buzz: "something else"
});
I like it because it is the closest to the very neat object initialisation in .Net:
var foo = new Foo()
{
bar: "whatever",
...
if the error is
Line 26:
Line 27: @foreach (Customers customer in Model)
Line 28: {
Line 29:
give the full name space
like
@foreach (Start.Models.customer customer in Model)
The accepted answer will return all the parent nodes too. To get only the actual nodes with ABC even if the string is after
:
//*[text()[contains(.,'ABC')]]/text()[contains(.,"ABC")]
My approach to this would be to use async generators.
Assuming you have an array of questions:
const questions = [
"How are you today ?",
"What are you working on ?",
"What do you think of async generators ?",
]
In order to use the await
keyword, you must wrap your program into an async IIFE.
(async () => {
questions[Symbol.asyncIterator] = async function * () {
const stdin = process.openStdin()
for (const q of this) {
// The promise won't be solved until you type something
const res = await new Promise((resolve, reject) => {
console.log(q)
stdin.addListener('data', data => {
resolve(data.toString())
reject('err')
});
})
yield [q, res];
}
};
for await (const res of questions) {
console.log(res)
}
process.exit(0)
})();
Expected results:
How are you today ?
good
[ 'How are you today ?', 'good\n' ]
What are you working on ?
:)
[ 'What are you working on ?', ':)\n' ]
What do you think about async generators ?
awesome
[ 'What do you think about async generators ?', 'awesome\n' ]
If you want to get questions an answers altogether, you can achieve this with a simple modification:
const questionsAndAnswers = [];
for await (const res of questions) {
// console.log(res)
questionsAndAnswers.push(res)
}
console.log(questionsAndAnswers)
/*
[ [ 'How are you today ?', 'good\n' ],
[ 'What are you working on ?', ':)\n' ],
[ 'What do you think about async generators ?', 'awesome\n' ] ]
*/
Try this
typeof(IFoo).IsAssignableFrom(typeof(BarClass));
This will tell you whether BarClass(Derived)
implements IFoo(SomeType)
or not
You can put your file to /etc/cron.d/ in cron format. Add some unique prefix to the filenaname To list script-specific cron jobs simply work with a list of files with a unique prefix. Delete the file when you want to disable the job.
Yes, Slack has the ability to hyperlink words, as long as Format messages with markup is unchecked under Preferences > Advanced to show the formatting toolbar. According to the documentation, start out with one of these:
- Select text, then click the link icon in the formatting toolbar
- Select text, then press ?ShiftU on Mac or CtrlShiftU on Windows/Linux.
Then do this:
Copy the link you'd like to share and paste it in the empty field under Link, then click Save.
What follows is how this answer used to read when it first became so famous. It was correct until about February 2020.
No.
As a couple of commenters said, and as the Slack documentation says:
Note: It’s not possible to hyperlink words in a Slack message.
The simplest non recursive way is:
for d in */; do
echo "$d"
done
The /
at the end tells, use directories only.
There is no need for
Use an anonymous function to protect your local symbol table. Something like:
(function() {
function copyArray(pa) {
// Details
}
Function.prototype.bind = function ( po ) {
__args = copyArray( arguments );
}
})();
This will create a closure that includes your function in the local symbol table, and you won't have to depend on it being available in the global namespace when you call the function.
For me, it works (java - android)
void RevokeAcess()
{
try{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://accounts.google.com/o/oauth2/revoke?token="+ACCESS_TOKEN);
org.apache.http.HttpResponse response = client.execute(post);
}
catch(IOException e)
{
}
CookieManager.getInstance().removeAllCookie(); // this is clear the cookies which tends to same user in android web view
}
You have to call this function in AsyncTask in android
Nvm can be used to manage various node version :
Step1: Download nvm for Windows
Step2: Choose nvm-setup.zip
Step3: Unzip & click on installer.
Step4: Check if nvm properly installed, In new command prompt type nvm
Step5: Install node js using nvm :
nvm install <version> : The version can be a node.js version or "latest" for the latest stable version
Step6: check node version - node -v
Step7(Optional)If you want to install another version of node js - Use STEP 5 with different version.
Step8: Check list node js version - nvm list
Step9: If you want to use specific node version do - nvm use <version>
I think you're looking for something like freopen()
Many sites use AJAX/XHR/fetch to add, show, modify content dynamically and window.history API instead of in-site navigation so current URL is changed programmatically. Such sites are called SPA, short for Single Page Application.
MutationObserver (docs) to literally detect DOM changes:
Performance of MutationObserver to detect nodes in entire DOM.
Simple example:
let lastUrl = location.href;
new MutationObserver(() => {
const url = location.href;
if (url !== lastUrl) {
lastUrl = url;
onUrlChange();
}
}).observe(document, {subtree: true, childList: true});
function onUrlChange() {
console.log('URL changed!', location.href);
}
Event listener for sites that signal content change by sending a DOM event:
pjax:end
on document
used by many pjax-based sites e.g. GitHub,message
on window
used by e.g. Google search in Chrome browser,yt-navigate-finish
used by Youtube,Periodic checking of DOM via setInterval:
Obviously this will work only in cases when you wait for a specific element identified by its id/selector to appear, and it won't let you universally detect new dynamically added content unless you invent some kind of fingerprinting the existing contents.
Cloaking History API:
let _pushState = History.prototype.pushState;
History.prototype.pushState = function (state, title, url) {
_pushState.call(this, state, title, url);
console.log('URL changed', url)
};
Listening to hashchange, popstate events:
window.addEventListener('hashchange', e => {
console.log('URL hash changed', e);
doSomething();
});
window.addEventListener('popstate', e => {
console.log('State changed', e);
doSomething();
});
All above-mentioned methods can be used in a content script. Note that content scripts aren't automatically executed by the browser in case of programmatic navigation via window.history in the web page because only the URL was changed but the page itself remained the same (the content scripts run automatically only once in page lifetime).
Now let's look at the background script.
There are advanced API to work with navigation: webNavigation, webRequest, but we'll use simple chrome.tabs.onUpdated event listener that sends a message to the content script:
manifest.json:
declare background/event page
declare content script
add "tabs"
permission.
background.js
var rxLookfor = /^https?:\/\/(www\.)?google\.(com|\w\w(\.\w\w)?)\/.*?[?#&]q=/;
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (rxLookfor.test(changeInfo.url)) {
chrome.tabs.sendMessage(tabId, 'url-update');
}
});
content.js
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg === 'url-update') {
// doSomething();
}
});
I use the Publish Subscribe pattern for complicated class-dependencies:
ViewModel:
public class ViewModel : ViewModelBase
{
public ViewModel()
{
CloseComand = new DelegateCommand((obj) =>
{
MessageBus.Instance.Publish(Messages.REQUEST_DEPLOYMENT_SETTINGS_CLOSED, null);
});
}
}
Window:
public partial class SomeWindow : Window
{
Subscription _subscription = new Subscription();
public SomeWindow()
{
InitializeComponent();
_subscription.Subscribe(Messages.REQUEST_DEPLOYMENT_SETTINGS_CLOSED, obj =>
{
this.Close();
});
}
}
You can leverage Bizmonger.Patterns to get the MessageBus.
MessageBus
public class MessageBus
{
#region Singleton
static MessageBus _messageBus = null;
private MessageBus() { }
public static MessageBus Instance
{
get
{
if (_messageBus == null)
{
_messageBus = new MessageBus();
}
return _messageBus;
}
}
#endregion
#region Members
List<Observer> _observers = new List<Observer>();
List<Observer> _oneTimeObservers = new List<Observer>();
List<Observer> _waitingSubscribers = new List<Observer>();
List<Observer> _waitingUnsubscribers = new List<Observer>();
int _publishingCount = 0;
#endregion
public void Subscribe(string message, Action<object> response)
{
Subscribe(message, response, _observers);
}
public void SubscribeFirstPublication(string message, Action<object> response)
{
Subscribe(message, response, _oneTimeObservers);
}
public int Unsubscribe(string message, Action<object> response)
{
var observers = new List<Observer>(_observers.Where(o => o.Respond == response).ToList());
observers.AddRange(_waitingSubscribers.Where(o => o.Respond == response));
observers.AddRange(_oneTimeObservers.Where(o => o.Respond == response));
if (_publishingCount == 0)
{
observers.ForEach(o => _observers.Remove(o));
}
else
{
_waitingUnsubscribers.AddRange(observers);
}
return observers.Count;
}
public int Unsubscribe(string subscription)
{
var observers = new List<Observer>(_observers.Where(o => o.Subscription == subscription).ToList());
observers.AddRange(_waitingSubscribers.Where(o => o.Subscription == subscription));
observers.AddRange(_oneTimeObservers.Where(o => o.Subscription == subscription));
if (_publishingCount == 0)
{
observers.ForEach(o => _observers.Remove(o));
}
else
{
_waitingUnsubscribers.AddRange(observers);
}
return observers.Count;
}
public void Publish(string message, object payload)
{
_publishingCount++;
Publish(_observers, message, payload);
Publish(_oneTimeObservers, message, payload);
Publish(_waitingSubscribers, message, payload);
_oneTimeObservers.RemoveAll(o => o.Subscription == message);
_waitingUnsubscribers.Clear();
_publishingCount--;
}
private void Publish(List<Observer> observers, string message, object payload)
{
Debug.Assert(_publishingCount >= 0);
var subscribers = observers.Where(o => o.Subscription.ToLower() == message.ToLower());
foreach (var subscriber in subscribers)
{
subscriber.Respond(payload);
}
}
public IEnumerable<Observer> GetObservers(string subscription)
{
var observers = new List<Observer>(_observers.Where(o => o.Subscription == subscription));
return observers;
}
public void Clear()
{
_observers.Clear();
_oneTimeObservers.Clear();
}
#region Helpers
private void Subscribe(string message, Action<object> response, List<Observer> observers)
{
Debug.Assert(_publishingCount >= 0);
var observer = new Observer() { Subscription = message, Respond = response };
if (_publishingCount == 0)
{
observers.Add(observer);
}
else
{
_waitingSubscribers.Add(observer);
}
}
#endregion
}
}
Subscription
public class Subscription
{
#region Members
List<Observer> _observerList = new List<Observer>();
#endregion
public void Unsubscribe(string subscription)
{
var observers = _observerList.Where(o => o.Subscription == subscription);
foreach (var observer in observers)
{
MessageBus.Instance.Unsubscribe(observer.Subscription, observer.Respond);
}
_observerList.Where(o => o.Subscription == subscription).ToList().ForEach(o => _observerList.Remove(o));
}
public void Subscribe(string subscription, Action<object> response)
{
MessageBus.Instance.Subscribe(subscription, response);
_observerList.Add(new Observer() { Subscription = subscription, Respond = response });
}
public void SubscribeFirstPublication(string subscription, Action<object> response)
{
MessageBus.Instance.SubscribeFirstPublication(subscription, response);
}
}
This one will only remove empty values and not falsey ones, which I think is more desirable.
There is an option to also remove null values.
This method should be much faster than using splice.
function cleanArray(a, removeNull) {
var i, l, temp = [];
l = a.length;
if (removeNull) {
for (i = 0; i < l; i++) {
if (a[i] !== undefined && a[i] !== null) {
temp.push(a[i]);
}
}
} else {
for (i = 0; i < l; i++) {
if (a[i] !== undefined) {
temp.push(a[i]);
}
}
}
a.length = 0;
l = temp.length;
for (i = 0; i < l; i++) {
a[i] = temp[i];
}
temp.length = 0;
return a;
}
var myArray = [1, 2, , 3, , 3, , , 0, , null, false, , NaN, '', 4, , 4, , 5, , 6, , , , ];
cleanArray(myArray);
myArray;
try this:
$(window).unbind('scroll');
it works in my project
A fleshed out version of Michael Foukarakis post (since I don't have the "reputation" to add a comment to that post yet):
#include <stdio.h>
#include <string.h>
void print(unsigned char *byte_array, int byte_array_size)
{
int i = 0;
printf("0x");
for(; i < byte_array_size; i++)
{
printf("%02x", byte_array[i]);
}
printf("\n");
}
int convert(const char *hex_str, unsigned char *byte_array, int byte_array_max)
{
int hex_str_len = strlen(hex_str);
int i = 0, j = 0;
// The output array size is half the hex_str length (rounded up)
int byte_array_size = (hex_str_len+1)/2;
if (byte_array_size > byte_array_max)
{
// Too big for the output array
return -1;
}
if (hex_str_len % 2 == 1)
{
// hex_str is an odd length, so assume an implicit "0" prefix
if (sscanf(&(hex_str[0]), "%1hhx", &(byte_array[0])) != 1)
{
return -1;
}
i = j = 1;
}
for (; i < hex_str_len; i+=2, j++)
{
if (sscanf(&(hex_str[i]), "%2hhx", &(byte_array[j])) != 1)
{
return -1;
}
}
return byte_array_size;
}
void main()
{
char *examples[] = { "", "5", "D", "5D", "5Df", "deadbeef10203040b00b1e50", "02invalid55" };
unsigned char byte_array[128];
int i = 0;
for (; i < sizeof(examples)/sizeof(char *); i++)
{
int size = convert(examples[i], byte_array, 128);
if (size < 0)
{
printf("Failed to convert '%s'\n", examples[i]);
}
else if (size == 0)
{
printf("Nothing to convert for '%s'\n", examples[i]);
}
else
{
print(byte_array, size);
}
}
}
anyItem has never been declared as a variable, so it makes sense that it causes an error. But more importantly, you have code after a return statement and this will cause an unreachable code error.
Solution below to process all elements of the array in parallel, asynchronously AND preserve the order:
const arr = [1, 2, 3, 4, 5, 6, 7, 8];
const randomDelay = () => new Promise(resolve => setTimeout(resolve, Math.random() * 1000));
const calc = async n => {
await randomDelay();
return n * 2;
};
const asyncFunc = async () => {
const unresolvedPromises = arr.map(n => calc(n));
const results = await Promise.all(unresolvedPromises);
};
asyncFunc();
Also codepen.
Notice we only "await" for Promise.all. We call calc without "await" multiple times, and we collect an array of unresolved promises right away. Then Promise.all waits for resolution of all of them and returns an array with the resolved values in order.
For me, fny answers really got it all. since fetch is not throwing error, we need to throw/handle the error ourselves. Posting my solution with async/await. I think it's more strait forward and readable
Solution 1: Not throwing an error, handle the error ourselves
async _fetch(request) {
const fetchResult = await fetch(request); //Making the req
const result = await fetchResult.json(); // parsing the response
if (fetchResult.ok) {
return result; // return success object
}
const responseError = {
type: 'Error',
message: result.message || 'Something went wrong',
data: result.data || '',
code: result.code || '',
};
const error = new Error();
error.info = responseError;
return (error);
}
Here if we getting an error, we are building an error object, plain JS object and returning it, the con is that we need to handle it outside. How to use:
const userSaved = await apiCall(data); // calling fetch
if (userSaved instanceof Error) {
debug.log('Failed saving user', userSaved); // handle error
return;
}
debug.log('Success saving user', userSaved); // handle success
Solution 2: Throwing an error, using try/catch
async _fetch(request) {
const fetchResult = await fetch(request);
const result = await fetchResult.json();
if (fetchResult.ok) {
return result;
}
const responseError = {
type: 'Error',
message: result.message || 'Something went wrong',
data: result.data || '',
code: result.code || '',
};
let error = new Error();
error = { ...error, ...responseError };
throw (error);
}
Here we are throwing and error that we created, since Error ctor approve only string, Im creating the plain Error js object, and the use will be:
try {
const userSaved = await apiCall(data); // calling fetch
debug.log('Success saving user', userSaved); // handle success
} catch (e) {
debug.log('Failed saving user', userSaved); // handle error
}
Solution 3: Using customer error
async _fetch(request) {
const fetchResult = await fetch(request);
const result = await fetchResult.json();
if (fetchResult.ok) {
return result;
}
throw new ClassError(result.message, result.data, result.code);
}
And:
class ClassError extends Error {
constructor(message = 'Something went wrong', data = '', code = '') {
super();
this.message = message;
this.data = data;
this.code = code;
}
}
Hope it helped.
it is not possible to do using only html
Assert by exception message:
try {
MyAgent.getNameByNode("d");
} catch (Exception e) {
Assert.assertEquals("Failed to fetch data.", e.getMessage());
}
Also the same error may occur when you put a new class into the source code of a designer created form's class.
This new class may be removed, and placed in a different cs file.
(At least in my case this was the problem...)
<location path="ControllerName/ActionName">
<system.web>
<httpRuntime executionTimeout="1000"/>
</system.web>
</location>
Probably it is better to set such values in web.config instead of controller. Hardcoding of configurable options is considered harmful.
Take below reference to convert a JSON into POJO and vice-versa
Let's suppose your JSON schema looks like:
{
"type":"object",
"properties": {
"dataOne": {
"type": "string"
},
"dataTwo": {
"type": "integer"
},
"dataThree": {
"type": "boolean"
}
}
}
Then to covert into POJO, your need to decleare some classes as explained in below style:
==================================
package ;
public class DataOne
{
private String type;
public void setType(String type){
this.type = type;
}
public String getType(){
return this.type;
}
}
==================================
package ;
public class DataTwo
{
private String type;
public void setType(String type){
this.type = type;
}
public String getType(){
return this.type;
}
}
==================================
package ;
public class DataThree
{
private String type;
public void setType(String type){
this.type = type;
}
public String getType(){
return this.type;
}
}
==================================
package ;
public class Properties
{
private DataOne dataOne;
private DataTwo dataTwo;
private DataThree dataThree;
public void setDataOne(DataOne dataOne){
this.dataOne = dataOne;
}
public DataOne getDataOne(){
return this.dataOne;
}
public void setDataTwo(DataTwo dataTwo){
this.dataTwo = dataTwo;
}
public DataTwo getDataTwo(){
return this.dataTwo;
}
public void setDataThree(DataThree dataThree){
this.dataThree = dataThree;
}
public DataThree getDataThree(){
return this.dataThree;
}
}
==================================
package ;
public class Root
{
private String type;
private Properties properties;
public void setType(String type){
this.type = type;
}
public String getType(){
return this.type;
}
public void setProperties(Properties properties){
this.properties = properties;
}
public Properties getProperties(){
return this.properties;
}
}
Update 2020: C# 8.0 finally makes this easy:
> "C# 8.0 finally makes this easy"[^4..]
"easy"
You can also slice arrays in the same way, see Indices and ranges.
The defaultdict solution is better. But for completeness you could also check and create empty list before the append. Add the + lines:
+ if not u in self.adj.keys():
+ self.adj[u] = []
self.adj[u].append(edge)
.
.
Inspired by Simon Mattes' answer, I needed to satisfy IHttpActionResult required return type of ResponseMessageResult. Also using nashawn's JsonContent, I ended up with...
return new System.Web.Http.Results.ResponseMessageResult(
new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK)
{
Content = new JsonContent(JsonConvert.SerializeObject(contact, Formatting.Indented))
});
See nashawn's answer for JsonContent.
I was facing same issue, for me adding certificate to trust store solved this issue.
Just one extra option, if you want to revert the default behaviour for all textareas in the application, you could add the following to your CSS:
textarea:not([resize="true"]) {
resize: none !important;
}
And do the following to enable where you want resizing:
<textarea resize="true"></textarea>
Have in mind this solution might not work in all browsers you may want to support. You can check the list of support for resize
here: http://caniuse.com/#feat=css-resize
I was able to accomplish this with VBA in Excel 2013. No special editors needed. All you need is the Visual Basic code editor which can be accessed on the Developer tab. The Developer tab is not visible by default so it needs to be enabled in File>Options>Customize Ribbon. On the Developer tab, click the Visual Basic button. The code editor will launch. Right click in the Project Explorer pane on the left. Click the insert menu and choose module. Add both subs below to the new module.
Sub LoadCustRibbon()
Dim hFile As Long
Dim path As String, fileName As String, ribbonXML As String, user As String
hFile = FreeFile
user = Environ("Username")
path = "C:\Users\" & user & "\AppData\Local\Microsoft\Office\"
fileName = "Excel.officeUI"
ribbonXML = "<mso:customUI xmlns:mso='http://schemas.microsoft.com/office/2009/07/customui'>" & vbNewLine
ribbonXML = ribbonXML + " <mso:ribbon>" & vbNewLine
ribbonXML = ribbonXML + " <mso:qat/>" & vbNewLine
ribbonXML = ribbonXML + " <mso:tabs>" & vbNewLine
ribbonXML = ribbonXML + " <mso:tab id='reportTab' label='Reports' insertBeforeQ='mso:TabFormat'>" & vbNewLine
ribbonXML = ribbonXML + " <mso:group id='reportGroup' label='Reports' autoScale='true'>" & vbNewLine
ribbonXML = ribbonXML + " <mso:button id='runReport' label='PTO' " & vbNewLine
ribbonXML = ribbonXML + "imageMso='AppointmentColor3' onAction='GenReport'/>" & vbNewLine
ribbonXML = ribbonXML + " </mso:group>" & vbNewLine
ribbonXML = ribbonXML + " </mso:tab>" & vbNewLine
ribbonXML = ribbonXML + " </mso:tabs>" & vbNewLine
ribbonXML = ribbonXML + " </mso:ribbon>" & vbNewLine
ribbonXML = ribbonXML + "</mso:customUI>"
ribbonXML = Replace(ribbonXML, """", "")
Open path & fileName For Output Access Write As hFile
Print #hFile, ribbonXML
Close hFile
End Sub
Sub ClearCustRibbon()
Dim hFile As Long
Dim path As String, fileName As String, ribbonXML As String, user As String
hFile = FreeFile
user = Environ("Username")
path = "C:\Users\" & user & "\AppData\Local\Microsoft\Office\"
fileName = "Excel.officeUI"
ribbonXML = "<mso:customUI xmlns:mso=""http://schemas.microsoft.com/office/2009/07/customui"">" & _
"<mso:ribbon></mso:ribbon></mso:customUI>"
Open path & fileName For Output Access Write As hFile
Print #hFile, ribbonXML
Close hFile
End Sub
Call LoadCustRibbon sub in the Wookbook open even and call the ClearCustRibbon sub in the Before_Close Event of the ThisWorkbook code file.
Just answering this old thread can be installed without pip On windows or Linux:
1) Download Requests from https://github.com/kennethreitz/requests click on clone or download button
2) Unzip the files in your python directory .Exp your python is installed in C:Python\Python.exe then unzip there
3) Depending on the Os run the following command:
Thats it :)
My goal was to make a CUDA enabled docker image without using nvidia/cuda as base image. Because I have some custom jupyter image, and I want to base from that.
The host machine had nvidia driver, CUDA toolkit, and nvidia-container-toolkit already installed. Please refer to the official docs, and to Rohit's answer.
Test that nvidia driver and CUDA toolkit is installed correctly with: nvidia-smi
on the host machine, which should display correct "Driver Version" and "CUDA Version" and shows GPUs info.
Test that nvidia-container-toolkit is installed correctly with: docker run --rm --gpus all nvidia/cuda:latest nvidia-smi
I found what I assume to be the official Dockerfile for nvidia/cuda here I "flattened" it, appended the contents to my Dockerfile and tested it to be working nicely:
FROM sidazhou/scipy-notebook:latest
# FROM ubuntu:18.04
###########################################################################
# See https://gitlab.com/nvidia/container-images/cuda/-/blob/master/dist/10.1/ubuntu18.04-x86_64/base/Dockerfile
# See https://sarus.readthedocs.io/en/stable/user/custom-cuda-images.html
###########################################################################
USER root
###########################################################################
# base
RUN apt-get update && apt-get install -y --no-install-recommends \
gnupg2 curl ca-certificates && \
curl -fsSL https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/7fa2af80.pub | apt-key add - && \
echo "deb https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64 /" > /etc/apt/sources.list.d/cuda.list && \
echo "deb https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64 /" > /etc/apt/sources.list.d/nvidia-ml.list && \
apt-get purge --autoremove -y curl \
&& rm -rf /var/lib/apt/lists/*
ENV CUDA_VERSION 10.1.243
ENV CUDA_PKG_VERSION 10-1=$CUDA_VERSION-1
# For libraries in the cuda-compat-* package: https://docs.nvidia.com/cuda/eula/index.html#attachment-a
RUN apt-get update && apt-get install -y --no-install-recommends \
cuda-cudart-$CUDA_PKG_VERSION \
cuda-compat-10-1 \
&& ln -s cuda-10.1 /usr/local/cuda && \
rm -rf /var/lib/apt/lists/*
# Required for nvidia-docker v1
RUN echo "/usr/local/nvidia/lib" >> /etc/ld.so.conf.d/nvidia.conf && \
echo "/usr/local/nvidia/lib64" >> /etc/ld.so.conf.d/nvidia.conf
ENV PATH /usr/local/nvidia/bin:/usr/local/cuda/bin:${PATH}
ENV LD_LIBRARY_PATH /usr/local/nvidia/lib:/usr/local/nvidia/lib64
###########################################################################
#runtime next
ENV NCCL_VERSION 2.7.8
RUN apt-get update && apt-get install -y --no-install-recommends \
cuda-libraries-$CUDA_PKG_VERSION \
cuda-npp-$CUDA_PKG_VERSION \
cuda-nvtx-$CUDA_PKG_VERSION \
libcublas10=10.2.1.243-1 \
libnccl2=$NCCL_VERSION-1+cuda10.1 \
&& apt-mark hold libnccl2 \
&& rm -rf /var/lib/apt/lists/*
# apt from auto upgrading the cublas package. See https://gitlab.com/nvidia/container-images/cuda/-/issues/88
RUN apt-mark hold libcublas10
###########################################################################
#cudnn7 (not cudnn8) next
ENV CUDNN_VERSION 7.6.5.32
RUN apt-get update && apt-get install -y --no-install-recommends \
libcudnn7=$CUDNN_VERSION-1+cuda10.1 \
&& apt-mark hold libcudnn7 && \
rm -rf /var/lib/apt/lists/*
ENV NVIDIA_VISIBLE_DEVICES all
ENV NVIDIA_DRIVER_CAPABILITIES all
ENV NVIDIA_REQUIRE_CUDA "cuda>=10.1"
###########################################################################
#docker build -t sidazhou/scipy-notebook-gpu:latest .
#docker run -itd -gpus all\
# -p 8888:8888 \
# -p 6006:6006 \
# --user root \
# -e NB_UID=$(id -u) \
# -e NB_GID=$(id -g) \
# -e GRANT_SUDO=yes \
# -v ~/workspace:/home/jovyan/work \
# --name sidazhou-jupyter-gpu \
# sidazhou/scipy-notebook-gpu:latest
#docker exec sidazhou-jupyter-gpu python -c "import tensorflow as tf; print(tf.config.experimental.list_physical_devices('GPU'))"
A nonblocking call returns immediately with whatever data are available: the full number of bytes requested, fewer, or none at all.
An asynchronous call requests a transfer that will be performed in its whole(entirety) but will complete at some future time.
I was trying to solve the problem of being able to iterate over several different text arrays all of which are stored within a memory resident database that is a large struct
.
The following was worked out using Visual Studio 2017 Community Edition on an MFC test application. I am including this as an example as this posting was one of several that I ran across that provided some help yet were still insufficient for my needs.
The struct
containing the memory resident data looked something like the following. I have removed most of the elements for the sake of brevity and have also not included the Preprocessor defines used (the SDK in use is for C as well as C++ and is old).
What I was interested in doing is having iterators for the various WCHAR
two dimensional arrays which contained text strings for mnemonics.
typedef struct tagUNINTRAM {
// stuff deleted ...
WCHAR ParaTransMnemo[MAX_TRANSM_NO][PARA_TRANSMNEMO_LEN]; /* prog #20 */
WCHAR ParaLeadThru[MAX_LEAD_NO][PARA_LEADTHRU_LEN]; /* prog #21 */
WCHAR ParaReportName[MAX_REPO_NO][PARA_REPORTNAME_LEN]; /* prog #22 */
WCHAR ParaSpeMnemo[MAX_SPEM_NO][PARA_SPEMNEMO_LEN]; /* prog #23 */
WCHAR ParaPCIF[MAX_PCIF_SIZE]; /* prog #39 */
WCHAR ParaAdjMnemo[MAX_ADJM_NO][PARA_ADJMNEMO_LEN]; /* prog #46 */
WCHAR ParaPrtModi[MAX_PRTMODI_NO][PARA_PRTMODI_LEN]; /* prog #47 */
WCHAR ParaMajorDEPT[MAX_MDEPT_NO][PARA_MAJORDEPT_LEN]; /* prog #48 */
// ... stuff deleted
} UNINIRAM;
The current approach is to use a template to define a proxy class for each of the arrays and then to have a single iterator class that can be used to iterate over a particular array by using a proxy object representing the array.
A copy of the memory resident data is stored in an object that handles reading and writing the memory resident data from/to disk. This class, CFilePara
contains the templated proxy class (MnemonicIteratorDimSize
and the sub class from which is it is derived, MnemonicIteratorDimSizeBase
) and the iterator class, MnemonicIterator
.
The created proxy object is attached to an iterator object which accesses the necessary information through an interface described by a base class from which all of the proxy classes are derived. The result is to have a single type of iterator class which can be used with several different proxy classes because the different proxy classes all expose the same interface, the interface of the proxy base class.
The first thing was to create a set of identifiers which would be provided to a class factory to generate the specific proxy object for that type of mnemonic. These identifiers are used as part of the user interface to identify the particular provisioning data the user is interested in seeing and possibly modifying.
const static DWORD_PTR dwId_TransactionMnemonic = 1;
const static DWORD_PTR dwId_ReportMnemonic = 2;
const static DWORD_PTR dwId_SpecialMnemonic = 3;
const static DWORD_PTR dwId_LeadThroughMnemonic = 4;
The Proxy Class
The templated proxy class and its base class are as follows. I needed to accommodate several different kinds of wchar_t
text string arrays. The two dimensional arrays had different numbers of mnemonics, depending on the type (purpose) of the mnemonic and the different types of mnemonics were of different maximum lengths, varying between five text characters and twenty text characters. Templates for the derived proxy class was a natural fit with the template requiring the maximum number of characters in each mnemonic. After the proxy object is created, we then use the SetRange()
method to specify the actual mnemonic array and its range.
// proxy object which represents a particular subsection of the
// memory resident database each of which is an array of wchar_t
// text arrays though the number of array elements may vary.
class MnemonicIteratorDimSizeBase
{
DWORD_PTR m_Type;
public:
MnemonicIteratorDimSizeBase(DWORD_PTR x) { }
virtual ~MnemonicIteratorDimSizeBase() { }
virtual wchar_t *begin() = 0;
virtual wchar_t *end() = 0;
virtual wchar_t *get(int i) = 0;
virtual int ItemSize() = 0;
virtual int ItemCount() = 0;
virtual DWORD_PTR ItemType() { return m_Type; }
};
template <size_t sDimSize>
class MnemonicIteratorDimSize : public MnemonicIteratorDimSizeBase
{
wchar_t (*m_begin)[sDimSize];
wchar_t (*m_end)[sDimSize];
public:
MnemonicIteratorDimSize(DWORD_PTR x) : MnemonicIteratorDimSizeBase(x), m_begin(0), m_end(0) { }
virtual ~MnemonicIteratorDimSize() { }
virtual wchar_t *begin() { return m_begin[0]; }
virtual wchar_t *end() { return m_end[0]; }
virtual wchar_t *get(int i) { return m_begin[i]; }
virtual int ItemSize() { return sDimSize; }
virtual int ItemCount() { return m_end - m_begin; }
void SetRange(wchar_t (*begin)[sDimSize], wchar_t (*end)[sDimSize]) {
m_begin = begin; m_end = end;
}
};
The Iterator Class
The iterator class itself is as follows. This class provides just basic forward iterator functionality which is all that is needed at this time. However I expect that this will change or be extended when I need something additional from it.
class MnemonicIterator
{
private:
MnemonicIteratorDimSizeBase *m_p; // we do not own this pointer. we just use it to access current item.
int m_index; // zero based index of item.
wchar_t *m_item; // value to be returned.
public:
MnemonicIterator(MnemonicIteratorDimSizeBase *p) : m_p(p) { }
~MnemonicIterator() { }
// a ranged for needs begin() and end() to determine the range.
// the range is up to but not including what end() returns.
MnemonicIterator & begin() { m_item = m_p->get(m_index = 0); return *this; } // begining of range of values for ranged for. first item
MnemonicIterator & end() { m_item = m_p->get(m_index = m_p->ItemCount()); return *this; } // end of range of values for ranged for. item after last item.
MnemonicIterator & operator ++ () { m_item = m_p->get(++m_index); return *this; } // prefix increment, ++p
MnemonicIterator & operator ++ (int i) { m_item = m_p->get(m_index++); return *this; } // postfix increment, p++
bool operator != (MnemonicIterator &p) { return **this != *p; } // minimum logical operator is not equal to
wchar_t * operator *() const { return m_item; } // dereference iterator to get what is pointed to
};
The proxy object factory determines which object to created based on the mnemonic identifier. The proxy object is created and the pointer returned is the standard base class type so as to have a uniform interface regardless of which of the different mnemonic sections are being accessed. The SetRange()
method is used to specify to the proxy object the specific array elements the proxy represents and the range of the array elements.
CFilePara::MnemonicIteratorDimSizeBase * CFilePara::MakeIterator(DWORD_PTR x)
{
CFilePara::MnemonicIteratorDimSizeBase *mi = nullptr;
switch (x) {
case dwId_TransactionMnemonic:
{
CFilePara::MnemonicIteratorDimSize<PARA_TRANSMNEMO_LEN> *mk = new CFilePara::MnemonicIteratorDimSize<PARA_TRANSMNEMO_LEN>(x);
mk->SetRange(&m_Para.ParaTransMnemo[0], &m_Para.ParaTransMnemo[MAX_TRANSM_NO]);
mi = mk;
}
break;
case dwId_ReportMnemonic:
{
CFilePara::MnemonicIteratorDimSize<PARA_REPORTNAME_LEN> *mk = new CFilePara::MnemonicIteratorDimSize<PARA_REPORTNAME_LEN>(x);
mk->SetRange(&m_Para.ParaReportName[0], &m_Para.ParaReportName[MAX_REPO_NO]);
mi = mk;
}
break;
case dwId_SpecialMnemonic:
{
CFilePara::MnemonicIteratorDimSize<PARA_SPEMNEMO_LEN> *mk = new CFilePara::MnemonicIteratorDimSize<PARA_SPEMNEMO_LEN>(x);
mk->SetRange(&m_Para.ParaSpeMnemo[0], &m_Para.ParaSpeMnemo[MAX_SPEM_NO]);
mi = mk;
}
break;
case dwId_LeadThroughMnemonic:
{
CFilePara::MnemonicIteratorDimSize<PARA_LEADTHRU_LEN> *mk = new CFilePara::MnemonicIteratorDimSize<PARA_LEADTHRU_LEN>(x);
mk->SetRange(&m_Para.ParaLeadThru[0], &m_Para.ParaLeadThru[MAX_LEAD_NO]);
mi = mk;
}
break;
}
return mi;
}
Using the Proxy Class and Iterator
The proxy class and its iterator are used as shown in the following loop to fill in a CListCtrl
object with a list of mnemonics. I am using std::unique_ptr
so that when the proxy class i not longer needed and the std::unique_ptr
goes out of scope, the memory will be cleaned up.
What this source code does is to create a proxy object for the array within the struct
which corresponds to the specified mnemonic identifier. It then creates an iterator for that object, uses a ranged for
to fill in the CListCtrl
control and then cleans up. These are all raw wchar_t
text strings which may be exactly the number of array elements so we copy the string into a temporary buffer in order to ensure that the text is zero terminated.
std::unique_ptr<CFilePara::MnemonicIteratorDimSizeBase> pObj(pFile->MakeIterator(m_IteratorType));
CFilePara::MnemonicIterator pIter(pObj.get()); // provide the raw pointer to the iterator who doesn't own it.
int i = 0; // CListCtrl index for zero based position to insert mnemonic.
for (auto x : pIter)
{
WCHAR szText[32] = { 0 }; // Temporary buffer.
wcsncpy_s(szText, 32, x, pObj->ItemSize());
m_mnemonicList.InsertItem(i, szText); i++;
}
Method 1:
If you're already logged in to the db server, just copy and paste this.
SHOW SERVER_ENCODING;
Result:
server_encoding
-----------------
UTF8
For Client encoding :
SHOW CLIENT_ENCODING;
Method 2:
Again if you are already logged in, use this to get the list based result
\l
Press Ctrl-a then : and then type
scrollback 10000
to get a 10000 line buffer, for example.
You can also set the default number of scrollback lines by adding
defscrollback 10000
to your ~/.screenrc
file.
To scroll (if your terminal doesn't allow you to by default), press Ctrl-a ESC and then scroll (with the usual Ctrl-f for next page or Ctrl-a for previous page, or just with your mouse wheel / two-fingers). To exit the scrolling mode, just press ESC.
Another tip: Ctrl-a i shows your current buffer setting.
Month.FEBRUARY.getValue() // February ? 2.
2
The Answer by Jon Skeet is correct.
Now we have a modern replacement for those troublesome old legacy date-time classes: the java.time classes.
java.time.Month
Among those classes is the Month
enum. An enum carries one or more predefined objects, objects that are automatically instantiated when the class loads. On Month
we have a dozen such objects, each given a name: JANUARY
, FEBRUARY
, MARCH
, and so on. Each of those is a static final public
class constant. You can use and pass these objects anywhere in your code. Example: someMethod( Month.AUGUST )
Fortunately, they have sane numbering, 1-12 where 1 is January and 12 is December.
Get a Month
object for a particular month number (1-12).
Month month = Month.of( 2 ); // 2 ? February.
Going the other direction, ask a Month
object for its month number.
int monthNumber = Month.FEBRUARY.getValue(); // February ? 2.
Many other handy methods on this class, such as knowing the number of days in each month. The class can even generate a localized name of the month.
You can get the localized name of the month, in various lengths or abbreviations.
String output =
Month.FEBRUARY.getDisplayName(
TextStyle.FULL ,
Locale.CANADA_FRENCH
);
février
Also, you should pass objects of this enum around your code base rather than mere integer numbers. Doing so provides type-safety, ensures a valid range of values, and makes your code more self-documenting. See Oracle Tutorial if unfamiliar with the surprisingly powerful enum facility in Java.
You also may find useful the Year
and YearMonth
classes.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, .Calendar
, & java.text.SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Now it's possible and supported by all major browsers: https://developer.mozilla.org/en-US/docs/Web/API/File/File
var file = new File(["foo"], "foo.txt", {
type: "text/plain",
});
Late to the game maybe but I stumbled upon this semantics issue while trying to make a REST API.
To expand a little on Wrikken's answer, I think you could use either 409 Conflict
or 403 Forbidden
depending on the situation - in short, use a 403 error when the user can do absolutely nothing to resolve the conflict and complete the request (e.g. they can't send a DELETE
request to explicitly remove the resource), or use 409 if something could possibly be done.
10.4.4 403 Forbidden
The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.
Nowadays, someone says "403" and a permissions or authentication issue comes to mind, but the spec says that it's basically the server telling the client that it's not going to do it, don't ask it again, and here's why the client shouldn't.
As for PUT
vs. POST
... POST
should be used to create a new instance of a resource when the user has no means to or shouldn't create an identifier for the resource. PUT
is used when the resource's identity is known.
9.6 PUT
...
The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request -- the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource. If the server desires that the request be applied to a different URI,
it MUST send a 301 (Moved Permanently) response; the user agent MAY then make its own decision regarding whether or not to redirect the request.
In addition to Nels Beckman's solution, I have the following tips:
Under Configure Build Path, I had to rearrange the order of my entries under Order and Export.
Additionally, as an Eclipse PDE developer, I needed to rearrange the order of my dependencies in my MANIFEST.MF
, adding the problematic package as first on the list.
Playing with these dials, along with running Project > Clean in between, I was able to resolve these warnings.
You can't (and shouldn't) block processing with a sleep function. However, you can use setTimeout
to kick off a function after a delay:
setTimeout(function(){alert("hi")}, 1000);
Depending on your needs, setInterval
might be useful, too.
Just figured this out on my own for showing a countdown but it would also work for a percentage.
import time
#Number of seconds to wait
i=15
#Until seconds has reached zero
while i > -1:
#Ensure string overwrites the previous line by adding spaces at end
print("\r{} seconds left. ".format(i),end='')
time.sleep(1)
i-=1
print("") #Adds newline after it's done
As long as whatever comes after '/r' is the same length or longer (including spaces) than the previous string, it will overwrite it on the same line. Just make sure you include the end='' otherwise it will print to a newline. Hope that helps!
The answer by @nneonneo suggested using NSTimer
but didn't show how to do it. This is the basic syntax:
let delay = 0.5 // time in seconds
NSTimer.scheduledTimerWithTimeInterval(delay, target: self, selector: #selector(myFunctionName), userInfo: nil, repeats: false)
Here is a very simple project to show how it might be used. When a button is pressed it starts a timer that will call a function after a delay of half a second.
import UIKit
class ViewController: UIViewController {
var timer = NSTimer()
let delay = 0.5
// start timer when button is tapped
@IBAction func startTimerButtonTapped(sender: UIButton) {
// cancel the timer in case the button is tapped multiple times
timer.invalidate()
// start the timer
timer = NSTimer.scheduledTimerWithTimeInterval(delay, target: self, selector: #selector(delayedAction), userInfo: nil, repeats: false)
}
// function to be called after the delay
func delayedAction() {
print("action has started")
}
}
Using dispatch_time
(as in Palle's answer) is another valid option. However, it is hard to cancel. With NSTimer
, to cancel a delayed event before it happens, all you need to do is call
timer.invalidate()
Using sleep
is not recommended, especially on the main thread, since it stops all the work being done on the thread.
See here for my fuller answer.
Out-File
defaults to unicode encoding which is why you are seeing the behavior you are. Use -Encoding Ascii
to change this behavior. In your case
Out-File -Encoding Ascii -append textfile.txt.
Add-Content
uses Ascii and also appends by default.
"This is a test" | Add-Content textfile.txt.
As for the lack of newline: You did not send a newline so it will not write one to file.
I didn't see a good and complete answer to your question, so I will show a more complete example. There are some methods posted showing how to get integer input from the user, but whenever you do this you usually also need to
This example shows how to get an integer value from the user that is equal to or greater than 1. If invalid input is given, it will catch the error, display an error message, and request the user to try again for a correct input.
static void Main(string[] args)
{
int intUserInput = 0;
bool validUserInput = false;
while (validUserInput == false)
{
try
{ Console.Write("Please enter an integer value greater than or equal to 1: ");
intUserInput = int.Parse(Console.ReadLine()); //try to parse the user input to an int variable
}
catch (Exception) { } //catch exception for invalid input.
if (intUserInput >= 1) //check to see that the user entered int >= 1
{ validUserInput = true; }
else { Console.WriteLine("Invalid input. "); }
}//end while
Console.WriteLine("You entered " + intUserInput);
Console.WriteLine("Press any key to exit ");
Console.ReadKey();
}//end main
In your question it looks like you wanted to use this for menu options. So if you wanted to get int input for choosing a menu option you could change the if statement to
if ( (intUserInput >= 1) && (intUserInput <= 4) )
This would work if you needed the user to pick an option of 1, 2, 3, or 4.
You can simply assign the B
to the new column , Like -
df['D'] = df['B']
Example/Demo -
In [1]: import pandas as pd
In [2]: df = pd.DataFrame([['a.1','b.1','c.1'],['a.2','b.2','c.2'],['a.3','b.3','c.3']],columns=['A','B','C'])
In [3]: df
Out[3]:
A B C
0 a.1 b.1 c.1
1 a.2 b.2 c.2
2 a.3 b.3 c.3
In [4]: df['D'] = df['B'] #<---What you want.
In [5]: df
Out[5]:
A B C D
0 a.1 b.1 c.1 b.1
1 a.2 b.2 c.2 b.2
2 a.3 b.3 c.3 b.3
In [6]: df.loc[0,'D'] = 'd.1'
In [7]: df
Out[7]:
A B C D
0 a.1 b.1 c.1 d.1
1 a.2 b.2 c.2 b.2
2 a.3 b.3 c.3 b.3
As another answer already said, call select myfunc(:y) from dual;
, but you might find declaring and setting a variable in sqlplus a little tricky:
sql> var y number
sql> begin
2 select 7 into :y from dual;
3 end;
4 /
PL/SQL procedure successfully completed.
sql> print :y
Y
----------
7
sql> select myfunc(:y) from dual;
you could inherit your controller then use it inside your action filter
inside your ActionFilterAttribute class:
if( filterContext.Controller is MyController )
if(filterContext.HttpContext.Session["login"] == null)
(filterContext.Controller as MyController).RedirectToAction("Login");
inside your base controller:
public class MyController : Controller
{
public void RedirectToAction(string actionName) {
base.RedirectToAction(actionName);
}
}
Cons. of this is to change all controllers to inherit from "MyController" class
The only way to do this (except for BalusC's ingenious form idea!) is by adding a JavaScript onclick
event to the button, which is not good for accessibility.
Have you considered styling a normal link like a button? You can't achieve OS specific buttons that way, but it's still the best way IMO.
Executing seq(1, 10, 1)
does what 1:10
does. You can change the last parameter of seq
, i.e. by
, to be the step of whatever size you like.
> #a vector of even numbers
> seq(0, 10, by=2) # Explicitly specifying "by" only to increase readability
> [1] 0 2 4 6 8 10
The general explanation is provided in the link from Dan.
For specific questions your ask :
They can reside on the same machine, even in the same process (JVM for Java). It is a logical distinction (what they do?), not a physical one (where they are?).
form month name to number
d=['JAN','FEB','MAR','April','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC']
N=input()
for i in range(len(d)):
if d[i] == N:
month=(i+1)
print(month)
This might be helpful
from bs4 import UnicodeDammit
with open('automate_data/billboard.csv', 'rb') as file:
content = file.read()
suggestion = UnicodeDammit(content)
suggestion.original_encoding
#'iso-8859-1'
Yet another possibility not yet mentioned here is to use NumPy tile:
a = numpy.tile(numpy.nan, (3, 3))
Also gives
array([[ NaN, NaN, NaN],
[ NaN, NaN, NaN],
[ NaN, NaN, NaN]])
I don't know about speed comparison.
I accomplished this with a custom view. Set layout_width="fill_parent" and layout_height="wrap_content", and point it to the appropriate drawable:
public class Banner extends View {
private final Drawable logo;
public Banner(Context context) {
super(context);
logo = context.getResources().getDrawable(R.drawable.banner);
setBackgroundDrawable(logo);
}
public Banner(Context context, AttributeSet attrs) {
super(context, attrs);
logo = context.getResources().getDrawable(R.drawable.banner);
setBackgroundDrawable(logo);
}
public Banner(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
logo = context.getResources().getDrawable(R.drawable.banner);
setBackgroundDrawable(logo);
}
@Override protected void onMeasure(int widthMeasureSpec,
int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = width * logo.getIntrinsicHeight() / logo.getIntrinsicWidth();
setMeasuredDimension(width, height);
}
}
list.clear()
is going to keep the same ArrayList but the same memory allocation. list = new ArrayList<int>();
is going to allocate new memory for your ArrayList.
The big difference is that ArrayLists will expand dynamically as you need more space. Therefore, if you call list.clear()
you will still, potentially, have a large amount of memory allocated for an ArrayList that might not be needed.
That said list.clear()
will be faster but if memory maters you might want to allocate a new ArrayList.
To answer your question title, "How to use Rank() in SQL Server," this is how it works:
I will use this set of data as an example:
create table #tmp
(
column1 varchar(3),
column2 varchar(5),
column3 datetime,
column4 int
)
insert into #tmp values ('AAA', 'SKA', '2013-02-01 00:00:00', 10)
insert into #tmp values ('AAA', 'SKA', '2013-01-31 00:00:00', 15)
insert into #tmp values ('AAA', 'SKB', '2013-01-31 00:00:00', 20)
insert into #tmp values ('AAA', 'SKB', '2013-01-15 00:00:00', 5)
insert into #tmp values ('AAA', 'SKC', '2013-02-01 00:00:00', 25)
You have a partition which basically specifies grouping.
In this example, if you partition by column2, the rank function will create ranks for groups of column2 values. There will be different ranks for rows where column2 = 'SKA' than rows where column2 = 'SKB' and so on.
The ranks are decided like this: The rank for every record is one plus the number of ranks that come before it in its partition. The rank will only increment when one of the fields you selected (other than the partitioned field(s)) is different than the ones that come before it. If all of the selected fields are the same, then the ranks will tie and both will be assigned the value, one.
Knowing this, if we only wanted to select one value from each group in column two, we could use this query:
with cte as
(
select *,
rank() over (partition by column2
order by column3) rnk
from t
) select * from cte where rnk = 1 order by column3;
COLUMN1 | COLUMN2 | COLUMN3 |COLUMN4 | RNK
------------------------------------------------------------------------------
AAA | SKB | January, 15 2013 00:00:00+0000 |5 | 1
AAA | SKA | January, 31 2013 00:00:00+0000 |15 | 1
AAA | SKC | February, 01 2013 00:00:00+0000 |25 | 1
just convert denominator to decimal before division e.g
select col1 / CONVERT(decimal(4,2), col2) from tbl1
The byte array contains characters in a special encoding (that you should know). The way to convert it to a String is:
String decoded = new String(bytes, "UTF-8"); // example for one encoding type
By The Way - the raw bytes appear may appear as negative decimals just because the java datatype byte
is signed, it covers the range from -128 to 127.
-109 = 0x93: Control Code "Set Transmit State"
The value (-109) is a non-printable control character in UNICODE. So UTF-8 is not the correct encoding for that character stream.
0x93
in "Windows-1252" is the "smart quote" that you're looking for, so the Java name of that encoding is "Cp1252". The next line provides a test code:
System.out.println(new String(new byte[]{-109}, "Cp1252"));
localStorage
is something that is kept on the client side. There is no data transmitted to the server side.
You can only get the data with JavaScript and you can send it to the server side with Ajax.
public static void Fill<T>(this IList<T> col, T value, int fromIndex, int toIndex)
{
if (fromIndex > toIndex)
throw new ArgumentOutOfRangeException("fromIndex");
for (var i = fromIndex; i <= toIndex; i++)
col[i] = value;
}
Something that works for all IList<T>
s.
SELECT DISTINCT a,b,c FROM t
is roughly equivalent to:
SELECT a,b,c FROM t GROUP BY a,b,c
It's a good idea to get used to the GROUP BY syntax, as it's more powerful.
For your query, I'd do it like this:
UPDATE sales
SET status='ACTIVE'
WHERE id IN
(
SELECT id
FROM sales S
INNER JOIN
(
SELECT saleprice, saledate
FROM sales
GROUP BY saleprice, saledate
HAVING COUNT(*) = 1
) T
ON S.saleprice=T.saleprice AND s.saledate=T.saledate
)
<!DOCTYPE html>
Otherwise IE8 is not acting right. Also you should use:
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
Note that this isn't perfect, since if you had something like, say, <a title=">">
it would break. However, it's about the closest you'd get in non-library Python without a really complex function:
import re
TAG_RE = re.compile(r'<[^>]+>')
def remove_tags(text):
return TAG_RE.sub('', text)
However, as lvc mentions xml.etree
is available in the Python Standard Library, so you could probably just adapt it to serve like your existing lxml
version:
def remove_tags(text):
return ''.join(xml.etree.ElementTree.fromstring(text).itertext())
If you want to declare a new substance with no parameter (knowing that the object have default parameters) don't write
type substance1();
but
type substance;
What worked for me ( target: debug an windows server app running on localhost:99999 from an client app running on android phone )
then the service app url (my_dev_machine_ip:99999/path_to_service) was accessible from the phone.
I think the best approach is to use a combination, Your second approach seems to be an elegant solution where browsers are involved.
So depending on the how the call is made. (whether its a browser or a web service call) you can use a combination of the two, with sending a URL to the browser and sending raw data to any other web service client.
My main idea is creating a tempDiv above the view which we want to scroll to. It work well without lagging in my project.
scrollToView = (element, offset) => {
var rect = element.getBoundingClientRect();
var targetY = rect.y + window.scrollY - offset;
var tempDiv;
tempDiv = document.getElementById("tempDiv");
if (tempDiv) {
tempDiv.style.top = targetY + "px";
} else {
tempDiv = document.createElement('div');
tempDiv.id = "tempDiv";
tempDiv.style.background = "#F00";
tempDiv.style.width = "10px";
tempDiv.style.height = "10px";
tempDiv.style.position = "absolute";
tempDiv.style.top = targetY + "px";
document.body.appendChild(tempDiv);
}
tempDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
Example using
onContactUsClick = () => {
this.scrollToView(document.getElementById("contact-us"), 48);
}
Hope it help
There is no need for jQuery here, regular JavaScript will do:
var str = "Abc: Lorem ipsum sit amet";
str = str.substring(str.indexOf(":") + 1);
Or, the .split()
and .pop()
version:
var str = "Abc: Lorem ipsum sit amet";
str = str.split(":").pop();
Or, the regex version (several variants of this):
var str = "Abc: Lorem ipsum sit amet";
str = /:(.+)/.exec(str)[1];
If you
you can do that starting with git 2.10. 2.10 or later is required, because 2.10 fixed the behavior of text=auto together with eol=lf. Source.
Put a .gitattributes
file in the root of your git repository having following contents:
* text=auto eol=lf
Commit it.
You can also add an .editorconfig
in the root of your repository to ensure that modern tooling creates new files with the desired line endings.
# EditorConfig is awesome: http://EditorConfig.org
# top-most EditorConfig file
root = true
# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true
You can't (usefully) compare strings using !=
or ==
, you need to use strcmp
:
while (strcmp(check,input) != 0)
The reason for this is because !=
and ==
will only compare the base addresses of those strings. Not the contents of the strings themselves.
Simple way to do it for html5 in css:
td img{
display: block;
margin-left: auto;
margin-right: auto;
}
Worked for me perfectly.
(a[n:]+[default])[0]
This is probably better as a
gets larger
(a[n:n+1]+[default])[0]
This works because if a[n:]
is an empty list if n => len(a)
Here is an example of how this works with range(5)
>>> range(5)[3:4]
[3]
>>> range(5)[4:5]
[4]
>>> range(5)[5:6]
[]
>>> range(5)[6:7]
[]
And the full expression
>>> (range(5)[3:4]+[999])[0]
3
>>> (range(5)[4:5]+[999])[0]
4
>>> (range(5)[5:6]+[999])[0]
999
>>> (range(5)[6:7]+[999])[0]
999
The problem is you defined myList
from main.py
, but subfile.py
needs to use it. Here is a clean way to solve this problem: move all globals to a file, I call this file settings.py
. This file is responsible for defining globals and initializing them:
# settings.py
def init():
global myList
myList = []
Next, your subfile
can import globals:
# subfile.py
import settings
def stuff():
settings.myList.append('hey')
Note that subfile
does not call init()
— that task belongs to main.py
:
# main.py
import settings
import subfile
settings.init() # Call only once
subfile.stuff() # Do stuff with global var
print settings.myList[0] # Check the result
This way, you achieve your objective while avoid initializing global variables more than once.
Edited: Fixed mistake in code that stopped it working if there were no
YourModel
entries in the db.
There's a lot of mention of how you should use an AutoField, and of course, where possible you should use that.
However there are legitimate reasons for implementing auto-incrementing fields yourself (such as if you need an id to start from 500 or increment by tens for whatever reason).
In your models.py
from django.db import models
def from_500():
'''
Returns the next default value for the `ones` field,
starts from 500
'''
# Retrieve a list of `YourModel` instances, sort them by
# the `ones` field and get the largest entry
largest = YourModel.objects.all().order_by('ones').last()
if not largest:
# largest is `None` if `YourModel` has no instances
# in which case we return the start value of 500
return 500
# If an instance of `YourModel` is returned, we get it's
# `ones` attribute and increment it by 1
return largest.ones + 1
def add_ten():
''' Returns the next default value for the `tens` field'''
# Retrieve a list of `YourModel` instances, sort them by
# the `tens` field and get the largest entry
largest = YourModel.objects.all().order_by('tens').last()
if not largest:
# largest is `None` if `YourModel` has no instances
# in which case we return the start value of 10
return 10
# If an instance of `YourModel` is returned, we get it's
# `tens` attribute and increment it by 10
return largest.tens + 10
class YourModel(model.Model):
ones = models.IntegerField(primary_key=True,
default=from_500)
tens = models.IntegerField(default=add_ten)
your forget this
in oninvalid
, change your code with this:
oninvalid="this.setCustomValidity('Lütfen isaretli yerleri doldurunuz')"
<form><input type="text" name="company_name" oninvalid="this.setCustomValidity('Lütfen isaretli yerleri doldurunuz')" required /><input type="submit">_x000D_
</form>
_x000D_
A list in a flask can be easily jsonify using jsonify like:
from flask import Flask,jsonify
app = Flask(__name__)
tasks = [
{
'id':1,
'task':'this is first task'
},
{
'id':2,
'task':'this is another task'
}
]
@app.route('/app-name/api/v0.1/tasks',methods=['GET'])
def get_tasks():
return jsonify({'tasks':tasks}) #will return the json
if(__name__ == '__main__'):
app.run(debug = True)
The $_GET
variable is populated from the parameters set in the URL. From the URL http://example.com/test.php?foo=bar&baz=buzz
you can get $_GET['foo']
and $_GET['baz']
. So to set these variables, you only have to make a link to that URL.
The shortest way would be:
$("#" + row_id)
Limiting the search to the body doesn't have any benefit.
Also, you should consider renaming your id
s to something more meaningful (and HTML compliant as per Paolo's answer), especially if you have another set of data that needs to be named as well.
It only seems to because that is what it is printing out. But actually, you shouldn't write the logic this way. This is equivalent:
insert into errortable (dateupdated, table1id)
values (sysdate, 1083);
It seems silly to convert the system date to a string just to convert it back to a date.
If you want to see the full date, then you can do:
select TO_CHAR(dateupdated, 'YYYY-MM-DD HH24:MI:SS'), table1id
from errortable;
I feel like reinventing the wheel...
public static T[] ConvertToArray<T>(this IEnumerable<T> enumerable)
{
if (enumerable == null)
throw new ArgumentNullException("enumerable");
return enumerable as T[] ?? enumerable.ToArray();
}
You should notice that this
depends on how function is invoked
ie: when a function is called as a method of an object, its this
is set to the object the method is called on.
this
is accessible in JSX context as your component object, so you can call your desired method inline as this
method.
If you just pass reference to function/method, it seems that react will invoke it as independent function.
onClick={this.onToggleLoop} // Here you just passing reference, React will invoke it as independent function and this will be undefined
onClick={()=>this.onToggleLoop()} // Here you invoking your desired function as method of this, and this in that function will be set to object from that function is called ie: your component object
You can solve your problem with help of Attribute routing
Controller
[Route("api/category/{categoryId}")]
public IEnumerable<Order> GetCategoryId(int categoryId) { ... }
URI in jquery
api/category/1
Route Configuration
using System.Web.Http;
namespace WebApplication
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
// Other Web API configuration not shown.
}
}
}
and your default routing is working as default convention-based routing
Controller
public string Get(int id)
{
return "object of id id";
}
URI in Jquery
/api/records/1
Route Configuration
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Attribute routing.
config.MapHttpAttributeRoutes();
// Convention-based routing.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Review article for more information Attribute routing and onvention-based routing here & this
In my case, web server prevented "OPTIONS" method
Check your web server for the options method
I'm using "webtier"
/www/webtier/domains/[domainname]/config/fmwconfig/components/OHS/VCWeb1/httpd.conf
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_METHOD} ^OPTIONS
RewriteRule .* . [F]
</IfModule>
change to
<IfModule mod_rewrite.c>
RewriteEngine off
RewriteCond %{REQUEST_METHOD} ^OPTIONS
RewriteRule .* . [F]
</IfModule>
Without any example data, it really is difficult to know exactly what you are wanting. For instance, I can't at all divine what your object set
(or is it sets
) looks like.
That said, does the following help at all?
set1 <- data.frame(x = 4:6, y = 6:4, z = c(1, 3, 5))
plot(1:10, type="n")
XX <- "set1"
with(eval(as.symbol(XX)), symbols(x, y, circles = z, add=TRUE))
EDIT:
Now that I see your real task, here is a one-liner that'll do everything you want without requiring any for()
loops:
with(dat, symbols(sq, cu, circles = num,
bg = c("red", "blue")[(num>5) + 1]))
The one bit of code that may feel odd is the bit specifying the background color. Try out these two lines to see how it works:
c(TRUE, FALSE) + 1
# [1] 2 1
c("red", "blue")[c(F, F, T, T) + 1]
# [1] "red" "red" "blue" "blue"
<?php
// Require https
if ($_SERVER['HTTPS'] != "on") {
$url = "https://". $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
header("Location: $url");
exit;
}
?>
That easy.
@Configuration
@ConfigurationProperties(prefix = "params.datasource")
public class JpaConfig extends HikariConfig {
@Bean
public DataSource dataSource() throws SQLException {
return new HikariDataSource(this);
}
}
application.yml
params:
datasource:
driverClassName: com.mysql.jdbc.Driver
jdbcUrl: jdbc:mysql://localhost:3306/myDb
username: login
password: password
maximumPoolSize: 5
UPDATED! Since version Spring Boot 1.3.0 :
application.yml
spring:
datasource:
type: com.zaxxer.hikari.HikariDataSource
url: jdbc:h2:mem:TEST
driver-class-name: org.h2.Driver
username: username
password: password
hikari:
idle-timeout: 10000
UPDATED! Since version Spring Boot 2.0.0 :
The default connection pool has changed from Tomcat to Hikari :)
I think you can get this error if your database model is not correct and the underlying data contains a null which the model is attempting to map to a non-null object.
For example, some auto-generated models can attempt to map nvarchar(1) columns to char rather than string and hence if this column contains nulls it will throw an error when you attempt to access the data.
Note, LinqPad has a compatibility option if you want it to generate a model like that, but probably doesn't do this by default, which might explain it doesn't give you the error.
I had a case where AV was quarantining Psexec - had to disable On-access scanning
Do this:
label.text = [NSString stringWithFormat:@"%d", count];
As Matt J wrote, there is itoa
, but it's not standard. Your code will be more portable if you use snprintf
.
You can get to the root from within each site using $_SERVER['DOCUMENT_ROOT']
. For testing ONLY you can echo out the path to make sure it's working, if you do it the right way. You NEVER want to show the local server paths for things like includes and requires.
Site 1
echo $_SERVER['DOCUMENT_ROOT']; //should be '/main_web_folder/';
Includes under site one would be at:
echo $_SERVER['DOCUMENT_ROOT'].'/includes/'; // should be '/main_web_folder/includes/';
Site 2
echo $_SERVER['DOCUMENT_ROOT']; //should be '/main_web_folder/blog/';
The actual code to access includes from site1 inside of site2 you would say:
include($_SERVER['DOCUMENT_ROOT'].'/../includes/file_from_site_1.php');
It will only use the relative path of the file executing the query if you try to access it by excluding the document root
and the root
slash:
//(not as fool-proof or non-platform specific)
include('../includes/file_from_site_1.php');
Included paths have no place in code on the front end (live) of the site anywhere, and should be secured and used in production environments only.
Additionally for URLs on the site itself you can make them relative to the domain. Browsers will automatically fill in the rest because they know which page they are looking at. So instead of:
<a href='http://www.__domain__name__here__.com/contact/'>Contact</a>
You should use:
<a href='/contact/'>Contact</a>
For good SEO you'll want to make sure that the URLs for the blog do not exist in the other domain, otherwise it may be marked as a duplicate site. With that being said you might also want to add a line to your robots.txt
file for ONLY site1:
User-agent: *
Disallow: /blog/
Look up your IP address and include this snippet of code:
function is_dev(){
//use the external IP from Google.
//If you're hosting locally it's 127.0.01 unless you've changed it.
$ip_address='xxx.xxx.xxx.xxx';
if ($_SERVER['REMOTE_ADDR']==$ip_address){
return true;
} else {
return false;
}
}
if(is_dev()){
echo $_SERVER['DOCUMENT_ROOT'];
}
Remember if your ISP changes your IP, as in you have a DCHP Dynamic IP, you'll need to change the IP in that file to see the results. I would put that file in an include, then require it on pages for debugging.
If you're okay with modern methods like using the browser console log you could do this instead and view it in the browser's debugging interface:
if(is_dev()){
echo "<script>".PHP_EOL;
echo "console.log('".$_SERVER['DOCUMENT_ROOT']."');".PHP_EOL;
echo "</script>".PHP_EOL;
}
I know that an answer has already been approved, but its hard not to try to share that I've created an embedded framework that adds Gif support to iOS that feels just like if you were using any other UIKit Framework class.
Here's an example:
UIGifImage *gif = [[UIGifImage alloc] initWithData:imageData];
anUiImageView.image = gif;
Download the latest release from https://github.com/ObjSal/UIGifImage/releases
-- Sal
The code above exports data without the heading columns which is weird. Here's how to do it. You have to merge the two files later though using text a editor.
SELECT column_name FROM information_schema.columns WHERE table_schema = 'my_app_db' AND table_name = 'customers' INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 5.6/Uploads/customers_heading_cols.csv' FIELDS TERMINATED BY '' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY ',';
You don't define the vector, url
, before trying to subset it. url
is also a function in the base package, so url[i]
is attempting to subset that function... which doesn't make sense.
You probably defined url
in your prior R session, but forgot to copy that code to your script.
To keep your requests fast, cache the server side results of the ping and update the ping file or database every couple of minutes(or however accurate you want it to be). You can use cron to run a shell command with your 8 pings and write the output into a file, the webserver will include this file into your view.
Concepts
Observables in short tackles asynchronous processing and events. Comparing to promises this could be described as observables = promises + events.
What is great with observables is that they are lazy, they can be canceled and you can apply some operators in them (like map
, ...). This allows to handle asynchronous things in a very flexible way.
A great sample describing the best the power of observables is the way to connect a filter input to a corresponding filtered list. When the user enters characters, the list is refreshed. Observables handle corresponding AJAX requests and cancel previous in-progress requests if another one is triggered by new value in the input. Here is the corresponding code:
this.textValue.valueChanges
.debounceTime(500)
.switchMap(data => this.httpService.getListValues(data))
.subscribe(data => console.log('new list values', data));
(textValue
is the control associated with the filter input).
Here is a wider description of such use case: How to watch for form changes in Angular 2?.
There are two great presentations at AngularConnect 2015 and EggHead:
Christoph Burgdorf also wrote some great blog posts on the subject:
In action
In fact regarding your code, you mixed two approaches ;-) Here are they:
Manage the observable by your own. In this case, you're responsible to call the subscribe
method on the observable and assign the result into an attribute of the component. You can then use this attribute in the view for iterate over the collection:
@Component({
template: `
<h1>My Friends</h1>
<ul>
<li *ngFor="#frnd of result">
{{frnd.name}} is {{frnd.age}} years old.
</li>
</ul>
`,
directive:[CORE_DIRECTIVES]
})
export class FriendsList implement OnInit, OnDestroy {
result:Array<Object>;
constructor(http: Http) {
}
ngOnInit() {
this.friendsObservable = http.get('friends.json')
.map(response => response.json())
.subscribe(result => this.result = result);
}
ngOnDestroy() {
this.friendsObservable.dispose();
}
}
Returns from both get
and map
methods are the observable not the result (in the same way than with promises).
Let manage the observable by the Angular template. You can also leverage the async
pipe to implicitly manage the observable. In this case, there is no need to explicitly call the subscribe
method.
@Component({
template: `
<h1>My Friends</h1>
<ul>
<li *ngFor="#frnd of (result | async)">
{{frnd.name}} is {{frnd.age}} years old.
</li>
</ul>
`,
directive:[CORE_DIRECTIVES]
})
export class FriendsList implement OnInit {
result:Array<Object>;
constructor(http: Http) {
}
ngOnInit() {
this.result = http.get('friends.json')
.map(response => response.json());
}
}
You can notice that observables are lazy. So the corresponding HTTP request will be only called once a listener with attached on it using the subscribe
method.
You can also notice that the map
method is used to extract the JSON content from the response and use it then in the observable processing.
Hope this helps you, Thierry
Bootstrap has a way of using media queries to define the different task for different sites. It uses four breakpoints.
we have extra small screen sizes which are less than 576 pixels that small in which I mean it's size from 576 to 768 pixels.
medium screen sizes take up screen size from 768 pixels up to 992 pixels large screen size from 992 pixels up to 1200 pixels.
E.g Small Text
This means that at the small screen between 576px and 768px, center the text For medium screen, change "sm" to "md" and same goes to large "lg"
How about this version in plain ES6/ES2015?
function get(url) {
return new Promise((resolve, reject) => {
const req = new XMLHttpRequest();
req.open('GET', url);
req.onload = () => req.status === 200 ? resolve(req.response) : reject(Error(req.statusText));
req.onerror = (e) => reject(Error(`Network Error: ${e}`));
req.send();
});
}
The function returns a promise. Here is an example on how to use the function and handle the promise it returns:
get('foo.txt')
.then((data) => {
// Do stuff with data, if foo.txt was successfully loaded.
})
.catch((err) => {
// Do stuff on error...
});
If you need to load a json file you can use JSON.parse()
to convert the loaded data into an JS Object.
You can also integrate req.responseType='json'
into the function but unfortunately there is no IE support for it, so I would stick with JSON.parse()
.
Do this:
$(document).ready(function(){
$(".header").click(function(){
$(this).children(".children").toggle();
});
$(".header a").click(function(e) {
e.stopPropagation();
});
});
If you want to read more on .stopPropagation(), look here.
The SELECT ... INTO
needs to be in the select from the CTE.
;WITH Calendar
AS (SELECT /*... Rest of CTE definition removed for clarity*/)
SELECT EventID,
EventStartDate,
EventEndDate,
PlannedDate AS [EventDates],
Cast(PlannedDate AS DATETIME) AS DT,
Cast(EventStartTime AS TIME) AS ST,
Cast(EventEndTime AS TIME) AS ET,
EventTitle,
EventType
INTO TEMPBLOCKEDDATES /* <---- INTO goes here*/
FROM Calendar
WHERE ( PlannedDate >= Getdate() )
AND ',' + EventEnumDays + ',' LIKE '%,' + Cast(Datepart(dw, PlannedDate) AS CHAR(1)) + ',%'
OR EventEnumDays IS NULL
ORDER BY EventID,
PlannedDate
OPTION (maxrecursion 0)
If this was based on roles you could use the multiview panel but not sure if you could do the same against a property of the record.
However, you could do this via code. In your rowdatabound event you can hide or show the button in it.
You could try this:
$in_str = 'this is a test';
$hex_ary = array();
foreach (str_split($in_str) as $chr) {
$hex_ary[] = sprintf("%02X", ord($chr));
}
echo implode(' ',$hex_ary);
Using System.arraycopy()
, something like the following should work:
// create a destination array that is the size of the two arrays
byte[] destination = new byte[ciphertext.length + mac.length];
// copy ciphertext into start of destination (from pos 0, copy ciphertext.length bytes)
System.arraycopy(ciphertext, 0, destination, 0, ciphertext.length);
// copy mac into end of destination (from pos ciphertext.length, copy mac.length bytes)
System.arraycopy(mac, 0, destination, ciphertext.length, mac.length);
Another code example: Tiny Wings Remake on Android using Cocos2d-X
In Pro Angular-6 book is detailed as below;
invalid: This property returns true if the element’s contents are invalid and false otherwise.
pristine: This property returns true if the element’s contents have not been changed.
This same problem occurs when the owners of the file have been deleted. When this happens, if you go to the file's properties, you will see a SID rather than a user name. Take ownership of the file (giving yourself FULL CONTROL). Once that is done you can do whatever you need to do with the file.
I've had this work when logging in as the administrator didn't do the trick.
My own implementation based off hB0 that also allows you to view the number of files in each folder also with a little performance boost.
#include <string>
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <windows.h>
#include <conio.h>
union seperated {
struct {
unsigned int low;
unsigned int high;
} uint;
unsigned long long ull;
};
unsigned long long num_dirs = 1;
unsigned long long num_files = 0;
seperated size_files;
int DeleteDirectory( char* refRootDirectory ); //predeclare it
int DeleteDirectory( char* refRootDirectory ) {
HANDLE hFile; // Handle to directory
std::string strFilePath; // Filepath
WIN32_FIND_DATA FileInformation; // File information
int dwError; // Folder deleting error
std::string strPattern; // Pattern
strPattern = (std::string)(refRootDirectory) + "\\*.*";
hFile = ::FindFirstFile( strPattern.c_str(), &FileInformation );
if( hFile != INVALID_HANDLE_VALUE )
{
do {
if( FileInformation.cFileName[0] != '.' ) {
strFilePath.erase();
strFilePath = std::string(refRootDirectory) + "\\" + FileInformation.cFileName;
if( FileInformation.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) {
DeleteDirectory( (char*)strFilePath.c_str() );
dwError = ::GetLastError();
if( dwError != ERROR_NO_MORE_FILES ) {
std::cout << "!ERROR!: [[" << strFilePath.c_str() << "]]\n";
return dwError;
} else {
// Set directory attributes
if( ! ::SetFileAttributes(refRootDirectory,FILE_ATTRIBUTE_NORMAL) ) {
std::cout << "!ERROR!: [[" << strFilePath.c_str() << "]]\n";
return ::GetLastError();
}
// Delete directory
if( ! ::RemoveDirectory(refRootDirectory) ) {
std::cout << "!ERROR!: [[" << strFilePath.c_str() << "]]\n";
return ::GetLastError();
}
}
++num_dirs;
} else {
// Set file attributes
if( ! ::SetFileAttributes(strFilePath.c_str(),FILE_ATTRIBUTE_NORMAL) ) {
std::cout << "!ERROR!: [[" << strFilePath.c_str() << "]]\n";
return ::GetLastError();
}
// Delete file
if ( ! ::DeleteFile(strFilePath.c_str()) ) {
std::cout << "!ERROR!: [[" << strFilePath.c_str() << "]]\n";
return ::GetLastError();
}
size_files.ull += FileInformation.nFileSizeLow;
size_files.uint.high += FileInformation.nFileSizeHigh;
++num_files;
}
}
} while( ::FindNextFile(hFile,&FileInformation) );
// Close handle
::FindClose( hFile );
}
return 0;
}
unsigned long long num_files_total=0;
unsigned long long num_dirs_total=0;
unsigned long long total_size_files=0;
void my_del_directory( char* dir_name ) {
int iRC = DeleteDirectory( dir_name );
//int iRC=0;
std::cout << "\"" << dir_name << "\""
"\n Folders: " << num_dirs
<< "\n Files: " << num_files
<< "\n Size: " << size_files.ull << " Bytes";
if(iRC)
{
std::cout << "\n!ERROR!: " << iRC;
}
std::cout << "\n\n";
num_dirs_total += num_dirs;
num_files_total += num_files;
total_size_files += size_files.ull;
num_dirs = 1;
num_files = 0;
size_files.ull = 0ULL;
return;
}
int main( void )
{
size_files.ull = 0ULL;
my_del_directory( (char*)"C:\Windows\temp" );
// This will clear out the System temporary directory on windows systems
std::cout << "\n\nResults" << "\nTotal Folders: " << num_dirs_total
<< "\nTotal Files: " << num_files_total
<< "\nTotal Size: " << total_size_files << " Bytes\n";
return 0;
}
It looks like you are trying to parse each line. You've been shown by another answer how to use getline
in a loop to seperate each line. The other tool you are going to want is istringstream
, to seperate each token.
std::string line;
while(std::getline(file, line))
{
std::istringstream iss(line);
std::string token;
while (iss >> token)
{
// do something with token
}
}
Same as AMIB answer, for soft delete error "Unknown column 'table_alias.deleted_at'",
just add ->withTrashed()
then handle it yourself like ->whereRaw('items_alias.deleted_at IS NULL')
Just make a new folder inside C:\xampp\htdocs like C:\xampp\htdocs\test and place your index.php or whatever file in it. Access it by browsing localhost/test/
Good luck!
You can use a plain old C array:
NSInteger myIntegers[40];
for (NSInteger i = 0; i < 40; i++)
myIntegers[i] = i;
// to get one of them
NSLog (@"The 4th integer is: %d", myIntegers[3]);
Or, you can use an NSArray
or NSMutableArray
, but here you will need to wrap up each integer inside an NSNumber
instance (because NSArray
objects are designed to hold class instances).
NSMutableArray *myIntegers = [NSMutableArray array];
for (NSInteger i = 0; i < 40; i++)
[myIntegers addObject:[NSNumber numberWithInteger:i]];
// to get one of them
NSLog (@"The 4th integer is: %@", [myIntegers objectAtIndex:3]);
// or
NSLog (@"The 4th integer is: %d", [[myIntegers objectAtIndex:3] integerValue]);
Clarification Here:
While this will work:
JsonNode rootNode = objectMapper.readTree(file);
Iterator<Map.Entry<String, JsonNode>> fields = rootNode.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> entry = fields.next();
log.info(entry.getKey() + ":" + entry.getValue())
}
This will not:
JsonNode rootNode = objectMapper.readTree(file);
while (rootNode.fields().hasNext()) {
Map.Entry<String, JsonNode> entry = rootNode.fields().next();
log.info(entry.getKey() + ":" + entry.getValue())
}
So be careful to declare the Iterator
as a variable and use that.
Be sure to use the fasterxml
library rather than codehaus
.
===
and !==
are strict comparison operators:
JavaScript has both strict and type-converting equality comparison. For
strict
equality the objects being compared must have the same type and:
- Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
- Two numbers are strictly equal when they are numerically equal (have the same number value).
NaN
is not equal to anything, includingNaN
. Positive and negative zeros are equal to one another.- Two Boolean operands are strictly equal if both are true or both are false.
- Two objects are strictly equal if they refer to the same
Object
.Null
andUndefined
types are==
(but not===
). [I.e. (Null==Undefined
) istrue
but (Null===Undefined
) isfalse
]
Try this too
$url = 'http://www.domain.com/';
$html = file_get_contents($url);
//Change encoding to UTF-8 from ISO-8859-1
$html = iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $html);
I'm here in general only to find out that through dict it is necessary to work inside setattr XD
Refer https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists
dt = datetime.datetime(*t[:7])
just a moment ago, i came across with the same issue. and i resolve it in the following manner.
Response.Redirect("../index.aspx?Name="+this.textName.Text+"&LastName="+this.textlName.Text);
with reference to the this
How to find time complexity of an algorithm
You add up how many machine instructions it will execute as a function of the size of its input, and then simplify the expression to the largest (when N is very large) term and can include any simplifying constant factor.
For example, lets see how we simplify 2N + 2
machine instructions to describe this as just O(N)
.
Why do we remove the two 2
s ?
We are interested in the performance of the algorithm as N becomes large.
Consider the two terms 2N and 2.
What is the relative influence of these two terms as N becomes large? Suppose N is a million.
Then the first term is 2 million and the second term is only 2.
For this reason, we drop all but the largest terms for large N.
So, now we have gone from 2N + 2
to 2N
.
Traditionally, we are only interested in performance up to constant factors.
This means that we don't really care if there is some constant multiple of difference in performance when N is large. The unit of 2N is not well-defined in the first place anyway. So we can multiply or divide by a constant factor to get to the simplest expression.
So 2N
becomes just N
.
yet another solution which uses the fact that np.nan != np.nan
:
In [149]: df.query("EPS == EPS")
Out[149]:
STK_ID EPS cash
STK_ID RPT_Date
600016 20111231 600016 4.3 NaN
601939 20111231 601939 2.5 NaN
First I would verify that your project's generated information isn't corrupt. Do a clean and rebuild on your solution.
If that doesn't help, one thing I've seen work in the past for designer issues is opening up a windows forms project, then closing it again. This is a little chicken-entrails-ish, though, so don't hold your breath.
In C#, there are at least 4 ways to embed a quote within a string:
Please refer this document for detailed explanation.
A quick workaround for this is to use numpy.core.defchararray
. I also faced the same warning message and was able to resolve it using above module.
import numpy.core.defchararray as npd
resultdataset = npd.equal(dataset1, dataset2)
Remember before you merge you need to update the tag, it's quite different from branches (git pull origin tag_name
won't update your local tags). Thus, you need the following command:
git fetch --tags origin
Then you can perform git merge tag_name
to merge the tag onto a branch.
I tried for almost 4 Hours with this and finally figuring it out with guidance from here, I thought I would share my solution with you.
Ok so my domain is an addon domain. I also got "ERROR for site owner: Invalid domain for site key" I had checked that everything was correct almost a thousand times and it looked right to me, until I thought of it in terms of a desktop shortcut.
Solution:
So for an addon domain make sure that the parent url is also in the list of domains i.e: [ADDON DOMAIN].[PARENT DOMAIN].com . The addon location will be the folder that you set on your host so when using addon domains ensure to name the root with something logical.
Hope this helps someone else and thanks for the suggestions people.
Enqueue
and Dequeue
tend to be operations on a queue, a data structure that does exactly what it sounds like it does.
You enqueue items at one end and dequeue at the other, just like a line of people queuing up for tickets to the latest Taylor Swift concert (I was originally going to say Billy Joel but that would date me severely).
There are variations of queues such as double-ended ones where you can enqueue and dequeue at either end but the vast majority would be the simpler form:
+---+---+---+
enqueue -> | 3 | 2 | 1 | -> dequeue
+---+---+---+
That diagram shows a queue where you've enqueued the numbers 1, 2 and 3 in that order, without yet dequeuing any.
By way of example, here's some Python code that shows a simplistic queue in action, with enqueue
and dequeue
functions. Were it more serious code, it would be implemented as a class but it should be enough to illustrate the workings:
import random
def enqueue(lst, itm):
lst.append(itm) # Just add item to end of list.
return lst # And return list (for consistency with dequeue).
def dequeue(lst):
itm = lst[0] # Grab the first item in list.
lst = lst[1:] # Change list to remove first item.
return (itm, lst) # Then return item and new list.
# Test harness. Start with empty queue.
myList = []
# Enqueue or dequeue a bit, with latter having probability of 10%.
for _ in range(15):
if random.randint(0, 9) == 0 and len(myList) > 0:
(itm, myList) = dequeue(myList)
print(f"Dequeued {itm} to give {myList}")
else:
itm = 10 * random.randint(1, 9)
myList = enqueue(myList, itm)
print(f"Enqueued {itm} to give {myList}")
# Now dequeue remainder of list.
print("========")
while len(myList) > 0:
(itm, myList) = dequeue(myList)
print(f"Dequeued {itm} to give {myList}")
A sample run of that shows it in operation:
Enqueued 70 to give [70]
Enqueued 20 to give [70, 20]
Enqueued 40 to give [70, 20, 40]
Enqueued 50 to give [70, 20, 40, 50]
Dequeued 70 to give [20, 40, 50]
Enqueued 20 to give [20, 40, 50, 20]
Enqueued 30 to give [20, 40, 50, 20, 30]
Enqueued 20 to give [20, 40, 50, 20, 30, 20]
Enqueued 70 to give [20, 40, 50, 20, 30, 20, 70]
Enqueued 20 to give [20, 40, 50, 20, 30, 20, 70, 20]
Enqueued 20 to give [20, 40, 50, 20, 30, 20, 70, 20, 20]
Dequeued 20 to give [40, 50, 20, 30, 20, 70, 20, 20]
Enqueued 80 to give [40, 50, 20, 30, 20, 70, 20, 20, 80]
Dequeued 40 to give [50, 20, 30, 20, 70, 20, 20, 80]
Enqueued 90 to give [50, 20, 30, 20, 70, 20, 20, 80, 90]
========
Dequeued 50 to give [20, 30, 20, 70, 20, 20, 80, 90]
Dequeued 20 to give [30, 20, 70, 20, 20, 80, 90]
Dequeued 30 to give [20, 70, 20, 20, 80, 90]
Dequeued 20 to give [70, 20, 20, 80, 90]
Dequeued 70 to give [20, 20, 80, 90]
Dequeued 20 to give [20, 80, 90]
Dequeued 20 to give [80, 90]
Dequeued 80 to give [90]
Dequeued 90 to give []
I got around this by upgrading both the version of Angular that I was using (from v8 -> v9) and the version of TypeScript (from 3.5.3 -> latest).
Static methods can not be overridden because there is nothing to override, as they would be two different methods. For example
static class Class1 {
public static int Method1(){
return 0;
}
}
static class Class2 extends Class1 {
public static int Method1(){
return 1;
}
}
public static class Main {
public static void main(String[] args){
//Must explicitly chose Method1 from Class1 or Class2
Class1.Method1();
Class2.Method1();
}
}
And yes static methods can be overloaded just like any other method.
You need to check out a previous version from before you deleted the files. Try git checkout HEAD^
to checkout the last revision.
This code works even faster (two 1.5 faster than my previous version):
public List<String> GetUserGroups(WindowsIdentity identity)
{
List<String> groups = new List<String>();
String userName = identity.Name;
int pos = userName.IndexOf(@"\");
if (pos > 0) userName = userName.Substring(pos + 1);
PrincipalContext domain = new PrincipalContext(ContextType.Domain, "riomc.com");
UserPrincipal user = UserPrincipal.FindByIdentity(domain, IdentityType.SamAccountName, userName); // NGeodakov
DirectoryEntry de = new DirectoryEntry("LDAP://RIOMC.com");
DirectorySearcher search = new DirectorySearcher(de);
search.Filter = "(&(objectClass=group)(member=" + user.DistinguishedName + "))";
search.PropertiesToLoad.Add("cn");
search.PropertiesToLoad.Add("samaccountname");
search.PropertiesToLoad.Add("memberOf");
SearchResultCollection results = search.FindAll();
foreach (SearchResult sr in results)
{
GetUserGroupsRecursive(groups, sr, de);
}
return groups;
}
public void GetUserGroupsRecursive(List<String> groups, SearchResult sr, DirectoryEntry de)
{
if (sr == null) return;
String group = (String)sr.Properties["cn"][0];
if (String.IsNullOrEmpty(group))
{
group = (String)sr.Properties["samaccountname"][0];
}
if (!groups.Contains(group))
{
groups.Add(group);
}
DirectorySearcher search;
SearchResult sr1;
String name;
int equalsIndex, commaIndex;
foreach (String dn in sr.Properties["memberof"])
{
equalsIndex = dn.IndexOf("=", 1);
if (equalsIndex > 0)
{
commaIndex = dn.IndexOf(",", equalsIndex + 1);
name = dn.Substring(equalsIndex + 1, commaIndex - equalsIndex - 1);
search = new DirectorySearcher(de);
search.Filter = "(&(objectClass=group)(|(cn=" + name + ")(samaccountname=" + name + ")))";
search.PropertiesToLoad.Add("cn");
search.PropertiesToLoad.Add("samaccountname");
search.PropertiesToLoad.Add("memberOf");
sr1 = search.FindOne();
GetUserGroupsRecursive(groups, sr1, de);
}
}
}
You may need to call frame.repaint()
as well to force the frame to actually redraw itself. I've had issues before where I tried to repaint a component and it wasn't updating what was displayed until the parent's repaint() method was called.
Here is one that works better for me (LINQPad version):
DateTime d;
DateTime.TryParseExact(
"2010-08-20T15:00:00Z",
@"yyyy-MM-dd\THH:mm:ss\Z",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal,
out d);
d.ToString()
produces
true
8/20/2010 8:00:00 AM
For disabling all the database related autoconfiguration and exit from:
Cannot determine embedded database driver class for database type NONE
1. Using annotation:
@SpringBootApplication
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class Application {
public static void main(String[] args) {
SpringApplication.run(PayPalApplication.class, args);
}
}
2. Using Application.properties:
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration
in javascript :
document.getElementById("message").value
The problem may be with jquery selector you've chosen
$("video")
is not a selector
The right selector may be putting an id element for video tag i.e.
Let's say your video element looks like this:
<video id="vid1" width="480" height="267" oster="example.jpg" durationHint="33">
<source src="video1.ogv" />
<source src="video2.ogv" />
</video>
Then you can select it via $("#vid1")
with hash mark (#), id selector in jquery.
If a video element is exposed in function,then you have access to HtmlVideoElement (HtmlMediaElement).This elements has control over video element,in your case you can use pause()
method for your video element.
Check reference for VideoElement here.
Also check that there is a fallback reference here.
Python 2
The error is caused because ElementTree did not expect to find non-ASCII strings set the XML when trying to write it out. You should use Unicode strings for non-ASCII instead. Unicode strings can be made either by using the u
prefix on strings, i.e. u'€'
or by decoding a string with mystr.decode('utf-8')
using the appropriate encoding.
The best practice is to decode all text data as it's read, rather than decoding mid-program. The io
module provides an open()
method which decodes text data to Unicode strings as it's read.
ElementTree will be much happier with Unicodes and will properly encode it correctly when using the ET.write()
method.
Also, for best compatibility and readability, ensure that ET encodes to UTF-8 during write()
and adds the relevant header.
Presuming your input file is UTF-8 encoded (0xC2
is common UTF-8 lead byte), putting everything together, and using the with
statement, your code should look like:
with io.open('myText.txt', "r", encoding='utf-8') as f:
data = f.read()
root = ET.Element("add")
doc = ET.SubElement(root, "doc")
field = ET.SubElement(doc, "field")
field.set("name", "text")
field.text = data
tree = ET.ElementTree(root)
tree.write("output.xml", encoding='utf-8', xml_declaration=True)
Output:
<?xml version='1.0' encoding='utf-8'?>
<add><doc><field name="text">data€</field></doc></add>
Use the retainAll()
method of Set
:
Set<String> s1;
Set<String> s2;
s1.retainAll(s2); // s1 now contains only elements in both sets
If you want to preserve the sets, create a new set to hold the intersection:
Set<String> intersection = new HashSet<String>(s1); // use the copy constructor
intersection.retainAll(s2);
The javadoc of retainAll()
says it's exactly what you want:
Retains only the elements in this set that are contained in the specified collection (optional operation). In other words, removes from this set all of its elements that are not contained in the specified collection. If the specified collection is also a set, this operation effectively modifies this set so that its value is the intersection of the two sets.
Try this:
REGEXP '^[a-z0-9]+$'
As regexp is not case sensitive except for binary fields.
I dont do it like this. I find it easier to overload the constructor of the asychtask class ..
public class calc_stanica extends AsyncTask>
String String mWhateveryouwantToPass;
public calc_stanica( String whateveryouwantToPass)
{
this.String mWhateveryouwantToPass = String whateveryouwantToPass;
}
/*Now you can use whateveryouwantToPass in the entire asynchTask ... you could pass in a context to your activity and try that too.*/ ... ...
MATLAB WAS a wrapper around commonly available libraries. And in many cases it still is. When you get to larger datasets, it has many additional optimizations, including examining and special casing common problems (reducing to sparse matrices where useful, for example), and handling edge cases. Often, you can submit a problem in a standard form to a general function, and it will determine the best underlying algorithm to use based on your data. For small N, all algorithms are fast, but MATLAB makes determining the optimal algorithm a non-issue.
This is written by someone who hates MATLAB, and has tried to replace it due to integration issues. From your question, you mention getting MATLAB 5 and using it for a course. At that level, you might want to look at Octave, an open source implementation with the same syntax. I'm guessing it is up to MATLAB 5 levels by now (I only play around with it). That should allow you to "pass your exam". For bare MATLAB functionality it seems to be close. It is lacking in the toolbox support (which, again, mostly serves to reformulate the function calls to forms familiar to engineers in the field and selects the right underlying algorithm to use).