In addition to Jon Skeet's answer, I'd like to explain why most of the time when using ==
you actually get the answer true
on different string instances with the same value:
string a = "Hell";
string b = "Hello";
a = a + "o";
Console.WriteLine(a == b);
As you can see, a
and b
must be different string instances, but because strings are immutable, the runtime uses so called string interning to let both a
and b
reference the same string in memory. The ==
operator for objects checks reference, and since both a
and b
reference the same instance, the result is true
. When you change either one of them, a new string instance is created, which is why string interning is possible.
By the way, Jon Skeet's answer is not complete. Indeed, x == y
is false
but that is only because he is comparing objects and objects compare by reference. If you'd write (string)x == (string)y
, it will return true
again. So strings have their ==-operator overloaded, which calls String.Equals
underneath.
For example for Unreal engine Automation tool run from batch file - this worked for me
eg: -cmdline=" -Messaging" -device=device -addcmdline="-SessionId=session -SessionOwner='owner' -SessionName='Build' -dataProviderMode=local -LogCmds='LogCommodity OFF' -execcmds='automation list; runtests tests+separated+by+T1+T2; quit' " -run
Hope this helps someone, worked for me.
You can add your Script Manager tags just below the <Form>
tag of your page. Here is how you can place your Script Manager tag.
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
If you are using Master Pages, its recommended to use your Script Manager in your Master page so that you do not have to write it again and again on every page that contains AJAX controls.
Just use:
<TextBlock Text="{Binding Date, StringFormat=\{0:d\}}" />
You can also use the Cast() operation :
Declare @name varchar(100);
set @name='....';
Select Cast(@name as varchar(10)) as new_name
If the array element is not integer you can use something like below :
$skus = array('LDRES10','LDRES12','LDRES11'); //sample data
if(!empty($skus)){
$sql = "SELECT * FROM `products` WHERE `prodCode` IN ('" . implode("','", $skus) . "') "
}
If you want headless browser support then there is another approach you might adopt.
https://github.com/detro/ghostdriver
It was announced during Selenium Conference and it is still in development. It uses PhantomJS as the browser and is much better than HTMLUnitDriver, there are no screenshots yet, but as it is still in active development.
Google have made this easier in SDK 21. Now we have attributes for specifying the thumb tint colors:
android:thumbTint
android:thumbTintMode
android:progressTint
http://developer.android.com/reference/android/widget/AbsSeekBar.html#attr_android:thumbTint http://developer.android.com/reference/android/widget/AbsSeekBar.html#attr_android:thumbTintMode
Beware! While it's true that "sort -u" and "sort|uniq" are equivalent, any additional options to sort can break the equivalence. Here's an example from the coreutils manual:
For example, 'sort -n -u' inspects only the value of the initial numeric string when checking for uniqueness, whereas 'sort -n | uniq' inspects the entire line.
Similarly, if you sort on key fields, the uniqueness test used by sort won't necessarily look at the entire line anymore. After being bitten by that bug in the past, these days I tend to use "sort|uniq" when writing Bash scripts. I'd rather have higher I/O overhead than run the risk that someone else in the shop won't know about that particular pitfall when they modify my code to add additional sort parameters.
If you are using FormBuilder
, see @dfsq's answer.
If you are not using FormBuilder
, there are two ways to be notified of changes.
Method 1
As discussed in the comments on the question, use an event binding on each input element. Add to your template:
<input type="text" class="form-control" required [ngModel]="model.first_name"
(ngModelChange)="doSomething($event)">
Then in your component:
doSomething(newValue) {
model.first_name = newValue;
console.log(newValue)
}
The Forms page has some additional information about ngModel that is relevant here:
The
ngModelChange
is not an<input>
element event. It is actually an event property of theNgModel
directive. When Angular sees a binding target in the form[(x)]
, it expects thex
directive to have anx
input property and anxChange
output property.The other oddity is the template expression,
model.name = $event
. We're used to seeing an$event
object coming from a DOM event. The ngModelChange property doesn't produce a DOM event; it's an AngularEventEmitter
property that returns the input box value when it fires..We almost always prefer
[(ngModel)]
. We might split the binding if we had to do something special in the event handling such as debounce or throttle the key strokes.
In your case, I suppose you want to do something special.
Method 2
Define a local template variable and set it to ngForm
.
Use ngControl on the input elements.
Get a reference to the form's NgForm directive using @ViewChild, then subscribe to the NgForm's ControlGroup for changes:
<form #myForm="ngForm" (ngSubmit)="onSubmit()">
....
<input type="text" ngControl="firstName" class="form-control"
required [(ngModel)]="model.first_name">
...
<input type="text" ngControl="lastName" class="form-control"
required [(ngModel)]="model.last_name">
class MyForm {
@ViewChild('myForm') form;
...
ngAfterViewInit() {
console.log(this.form)
this.form.control.valueChanges
.subscribe(values => this.doSomething(values));
}
doSomething(values) {
console.log(values);
}
}
For more information on Method 2, see Savkin's video.
See also @Thierry's answer for more information on what you can do with the valueChanges
observable (such as debouncing/waiting a bit before processing changes).
Unfortunately, it appears that we can't post shares for individual topics or articles within a page. It appears Facebook just wants us to share entire pages (based on url only).
There's also their new share dialog, but even though they claim it can do all of what the old sharer.php could do, that doesn't appear to be true.
And here's Facebooks 'best practices' for sharing.
This is ridiculous but I just have rebooted my machine (mac) and the problem was gone like it has never happened. I hate to sound like a support guy...
Very simple:
#content {
max-height: 100%;
}
An AXD file is a file used by ASP.NET applications for handling embedded resource requests. It contains instructions for retrieving embedded resources, such as images, JavaScript (.JS) files, and.CSS files.
AXD files are used for injecting resources into the client-side webpage and access them on the server in a standard way.
You can do an interactive rebase:
git rebase -i <commit>
This will bring up your default editor. Just delete the line containing the commit you want to remove to delete that commit.
You will, of course, need access to the remote repository to apply this change there too.
See this question: Git: removing selected commits from repository
Subclass is to Class as Java is to Programming Language.
Just something important to keep in mind: Spring versions prior to 3.1.2 are compatible with JACKSON 1.x and NOT with JACKSON 2.x. This is because going from JACKSON 1.x to 2.x the classes's package names were changed. In JACKSON 1.x classes are under org.codehaus.jackson while in JACKSON 2.x they are under com.fasterxml.jackson.
To address this issue, starting with Spring 3.1.2 they added a new MappingJackson2HttpMessageConverter to replace MappingJacksonHttpMessageConverter.
You could find more details regarding compatibility issues in this link: Jackson annotations being ignored in Spring
For Docker 1.8, I use:
$ docker inspect -f "{{ .Config.Volumes }}" 957d2dd1d4e8
map[/xmount/dvol.01:{}]
$
In my case , I used the 'is' a jQuery function, I had a HTML element with different css classes added , I was looking for a specific class in the middle of these , so I used the "is" a good alternative to check a class dynamically added to an html element , which already has other css classes, it is another good alternative.
simple example :
<!--element html-->
<nav class="cbp-spmenu cbp-spmenu-horizontal cbp-spmenu-bottom cbp-spmenu-open" id="menu">somethings here... </nav>
<!--jQuery "is"-->
$('#menu').is('.cbp-spmenu-open');
advanced example :
<!--element html-->
<nav class="cbp-spmenu cbp-spmenu-horizontal cbp-spmenu-bottom cbp-spmenu-open" id="menu">somethings here... </nav>
<!--jQuery "is"-->
if($('#menu').is('.cbp-spmenu-bottom.cbp-spmenu-open')){
$("#menu").show();
}
This answer is quite similar to the accepted answer, but doesn't override the Date
prototype, and only uses one function call to check if Daylight Savings Time is in effect, rather than two.
The idea is that, since no country observes DST that lasts for 7 months[1], in an area that observes DST the offset from UTC time in January will be different to the one in July.
While Daylight Savings Time moves clocks forwards, JavaScript always returns a greater value during Standard Time. Therefore, getting the minimum offset between January and July will get the timezone offset during DST.
We then check if the dates timezone is equal to that minimum value. If it is, then we are in DST; otherwise we are not.
The following function uses this algorithm. It takes a date object, d
, and returns true
if daylight savings time is in effect for that date, and false
if it is not:
function isDST(d) {
let jan = new Date(d.getFullYear(), 0, 1).getTimezoneOffset();
let jul = new Date(d.getFullYear(), 6, 1).getTimezoneOffset();
return Math.max(jan, jul) != d.getTimezoneOffset();
}
For future purposes, this may help too:
It's ok to use setState in useEffect
you just need to have attention as described already to not create a loop.
But it's not the only problem that may occur. See below:
Imagine that you have a component Comp
that receives props
from parent and according to a props
change you want to set Comp
's state. For some reason, you need to change for each prop in a different useEffect
:
DO NOT DO THIS
useEffect(() => {
setState({ ...state, a: props.a });
}, [props.a]);
useEffect(() => {
setState({ ...state, b: props.b });
}, [props.b]);
It may never change the state of a as you can see in this example: https://codesandbox.io/s/confident-lederberg-dtx7w
The reason why this happen in this example it's because both useEffects run in the same react cycle when you change both prop.a
and prop.b
so the value of {...state}
when you do setState
are exactly the same in both useEffect
because they are in the same context. When you run the second setState
it will replace the first setState
.
DO THIS INSTEAD
The solution for this problem is basically call setState
like this:
useEffect(() => {
setState(state => ({ ...state, a: props.a }));
}, [props.a]);
useEffect(() => {
setState(state => ({ ...state, b: props.b }));
}, [props.b]);
Check the solution here: https://codesandbox.io/s/mutable-surf-nynlx
Now, you always receive the most updated and correct value of the state when you proceed with the setState
.
I hope this helps someone!
Since the question on how to convert from ISO-8859-1 to UTF-8 is closed because of this one I'm going to post my solution here.
The problem is when you try to GET anything by using XMLHttpRequest, if the XMLHttpRequest.responseType is "text" or empty, the XMLHttpRequest.response is transformed to a DOMString and that's were things break up. After, it's almost impossible to reliably work with that string.
Now, if the content from the server is ISO-8859-1 you'll have to force the response to be of type "Blob" and later convert this to DOMSTring. For example:
var ajax = new XMLHttpRequest();
ajax.open('GET', url, true);
ajax.responseType = 'blob';
ajax.onreadystatechange = function(){
...
if(ajax.responseType === 'blob'){
// Convert the blob to a string
var reader = new window.FileReader();
reader.addEventListener('loadend', function() {
// For ISO-8859-1 there's no further conversion required
Promise.resolve(reader.result);
});
reader.readAsBinaryString(ajax.response);
}
}
Seems like the magic is happening on readAsBinaryString so maybe someone can shed some light on why this works.
For Jackson versions < 2.0 use this annotation on the class being serialized:
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
The error message fatal: Unable to write new index file
means that we could not write the new content to the git index file .git\index
(See here for more information about git index). After reviewing all the answers to this question, I summarize the following root causes:
.git\index
is locked by other users or processes. (Solution: Unlock the file)The link Find out which process is locking a file or folder in Windows specifies the following approach to find out the process which is locking a specific file:
SysInternals Process Explorer - Go to Find > Find Handle or DLL. In the "Handle or DLL substring:" text box, type the path to the file (e.g. "C:\path\to\file.txt") and click "Search". All processes which have an open handle to that file should be listed.
Use the above approach to find which process locked .git\index
and then stop the locking executable. This unlocks .git\index
.
For example, Process Explorer Search shows that .git\index
is locked by vmware-vmx.exe
. Suspending the VMWare Player virtual machine (which accessed the git repo via a shared folder) solved the issue.
In bootstrap 4.3.1 I can change the background color of the toggler icon to white via the css code.
.navbar-toggler{
background-color:white;
}
And in my opinion the so changed icon looks fine as well on light as on dark background.
Unique counts of field values are achieved by using facets. See ES documentation for the full story, but the gist is that you will create a query and then ask ES to prepare facets on the results for counting values found in fields. It's up to you to customize the fields used and even describe how you want the values returned. The most basic of facet types is just to group by terms, which would be like an IP address above. You can get pretty complex with these, even requiring a query within your facet!
{
"query": {
"match_all": {}
},
"facets": {
"terms": {
"field": "ip_address"
}
}
}
In your Component you can add .class to your host element if you would have some general styles that you want to apply.
export class MyComponent{
@HostBinding('class') classes = 'classA classB';
If still you are facing checkout for proxy setting, for me it was the proxy setting which were missing and was not able to make the request as direct http/https are blocked. So i configured the proxy from my organization while making the request.
npm install https-proxy-agent
or
npm install http-proxy-agent
const httpsProxyAgent = require('https-proxy-agent');
const agent = new httpsProxyAgent("http://yourorganzation.proxy.url:8080");
const options = {
hostname: 'encrypted.google.com',
port: 443,
path: '/',
method: 'GET',
agent: agent
};
It sounds like what you want is a User who has many Questions.
The Question has many Answers, one of which is the User's Choice.
Is this what you are after?
I would model something like that along these lines:
class User
has_many :questions
end
class Question
belongs_to :user
has_many :answers
has_one :choice, :class_name => "Answer"
validates_inclusion_of :choice, :in => lambda { answers }
end
class Answer
belongs_to :question
end
Click "view details" to find the inner exception.
Using JACOB call Office Word is a 100% perfect solution. But it only supports on Windows platform because need Office Word installed.
Using JACOB API call Office Word to convert doc/docx to pdf.
public void convertDocx2pdf(String docxFilePath) {
File docxFile = new File(docxFilePath);
String pdfFile = docxFilePath.substring(0, docxFilePath.lastIndexOf(".docx")) + ".pdf";
if (docxFile.exists()) {
if (!docxFile.isDirectory()) {
ActiveXComponent app = null;
long start = System.currentTimeMillis();
try {
ComThread.InitMTA(true);
app = new ActiveXComponent("Word.Application");
Dispatch documents = app.getProperty("Documents").toDispatch();
Dispatch document = Dispatch.call(documents, "Open", docxFilePath, false, true).toDispatch();
File target = new File(pdfFile);
if (target.exists()) {
target.delete();
}
Dispatch.call(document, "SaveAs", pdfFile, 17);
Dispatch.call(document, "Close", false);
long end = System.currentTimeMillis();
logger.info("============Convert Finished:" + (end - start) + "ms");
} catch (Exception e) {
logger.error(e.getLocalizedMessage(), e);
throw new RuntimeException("pdf convert failed.");
} finally {
if (app != null) {
app.invoke("Quit", new Variant[] {});
}
ComThread.Release();
}
}
}
}
If you are using maven, adding below dependency should work
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
You're very close:
while IFS=$'\t' read -r -a myArray
do
echo "${myArray[0]}"
echo "${myArray[1]}"
echo "${myArray[2]}"
done < myfile
(The -r
tells read
that \
isn't special in the input data; the -a myArray
tells it to split the input-line into words and store the results in myArray
; and the IFS=$'\t'
tells it to use only tabs to split words, instead of the regular Bash default of also allowing spaces to split words as well. Note that this approach will treat one or more tabs as the delimiter, so if any field is blank, later fields will be "shifted" into earlier positions in the array. Is that O.K.?)
In my case the error happened because the new line after the return
statement.
Error : Expected an assignment or function call and instead saw an expression
return
(
<ul>
{
props.numbers.map(number => <li key={number.toString()}>number</li>)
}
</ul>
);
Working OK. No Error
return (
<ul>
{
props.numbers.map(number => <li key={number.toString()}>number</li>)
}
</ul>
);
add
.hover_img a:hover span {
display: block;
width: 350px;
}
to show hover image full size in table change 350 to your size.
Function imageMorph
will create a new img element therefore the id is removed.
Changed to
$("#wrapper > img")
You should use live() function for click event if you want you rocket lanch again.
Updated demo: http://jsfiddle.net/ynhat/QQRsW/4/
You can also use Uploadify, which is a great jQuery upload plugin, it let's you upload multiple files, and also style the file fields easily. http://www.uploadify.com
If it helps anyone. You can do what the accepted answer by Infeligo has suggested but just put this extra bit in the code for a forced download.
response.setContentType("application/force-download");
File.Create
returns a FileStream
object that you can call Close()
on.
I was facing the same issue in bitbucket, and this worked for me:
line1
##<2 white spaces><enter>
line2
I finally got this to work on my own hosted xampp windows 10 server web site. I.e. padlocks came up as ssl. I am using xampp version from November 2020.
Went to certbot.eff.org. Selected from their home page software [apache] and system [windows]. Then downloaded and installed certbot software found at the next page into my C drive.
Then from command line [cmd in Windows Start and then before you open cmd right click to run cmd as admin] I enhtered the command from Certbot page above. I.e. navigated to system32-- C:\WINDOWS\system32> certbot certonly --standalone
Then followed the prompts and enteredmy domain name. This created certs as cert1.pem and key1.pem in C:\Certbot yourwebsitedomain folder. the cmd windows tells you where these are.
Then took these and changed their names from cert1.pem to my domainname or shorter+cert.pem and same for domainname or shorter+key.key. Copied these into C:\xampp\apache\ssl.crt and ssl.key folders respectively.
Then for G:\xampp\apache\conf\extra\httpd-vhosts entered the following:
<VirtualHost *:443>
DocumentRoot "G:/xampp/htdocs/yourwebsitedomainname.hopto.org/public/" ###NB My document root is public. Yours may not be. Or could have an index.php page before /public###
ServerName yourwebsitedomainnamee.hopto.org
<Directory G:/xampp/htdocs/yourwebsitedomainname.hopto.org>
Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride All
Require all granted
</Directory>
ErrorLog "G:/xampp/apache/logs/error.log"
CustomLog "G:/xampp/apache/logs/access.log" common
SSLEngine on
SSLCertificateFile "G:\xampp\apache\conf\ssl.crt\abscert.pem"
SSLCertificateKeyFile "G:\xampp\apache\conf\ssl.key\abskey.pem"
</VirtualHost>
<VirtualHost _default_:443>
DocumentRoot "G:/xampp/htdocs/yourwebsitedomainnamee.hopto.org/public/"
###NB My document root is public. Yours may not be. Or could have an index.php page before /public###
SSLEngine on
SSLCertificateFile "conf/ssl.crt/abscert.pem"
SSLCertificateKeyFile "conf/ssl.key/abskey.pem"
CustomLog "G:/xampp/apache/logs/ssl_request.log" \
"%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
</VirtualHost>
Note1. I used www.noip.com to register the domain name. Note2. Rather then try to get them to give me a ssl certificate, as I could not get it to work, the above worked instead. Note3 I use the noip DUC software to keep my personally hosted web site in sync with noip. Note4. Very important to stop and start xampp server after each change you make in xampp. If xampp fails for some reason instead of starting the xampp consol try the start xampp as this will give you problems you can bug fix. Copy these quickly and paste into note.txt.
<>
is used to indicate generics in Java.
T
is a type parameter in this example. And no: instantiating is one of the few things that you can't do with T
.
Apart from the tutorial linked above Angelika Langers Generics FAQ is a great resource on the topic.
Just remove the comma like this:
<article class="column wrapper">
You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:
/**
* Used to stitch together functional operators into a chain.
* @method pipe
* @return {Observable} the Observable result of all of the operators having
* been called in the order they were passed in.
*
* @example
*
* import { map, filter, scan } from 'rxjs/operators';
*
* Rx.Observable.interval(1000)
* .pipe(
* filter(x => x % 2 === 0),
* map(x => x + x),
* scan((acc, x) => acc + x)
* )
* .subscribe(x => console.log(x))
*/
Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan()
, but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe()
to make a chain of those operators (see example above).
Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do()
. You can think of it as if observable was an array over time, then tap()
would be an equivalent to Array.forEach()
.
You need to put the file(s) into a new directory (ex:selected) and then apply
php artisan migrate --path=/database/migrations/selected
if you need rollback:
php artisan migrate:rollback --path=/database/migrations/selected
Note:
php artisan migrate:refresh
this will rollback and then migrate all the migrations files in the default directory (/database/migrations)
I realize you've found another answer - but the fact is that your original code was nearly correct but for a syntax error.
Your code contained the line
set /A COUNTER=%COUNTER%+1
and the syntax that would work is simply...
set /A COUNTER=COUNTER+1
See http://ss64.com/nt/set.html for all the details on the SET command. I just thought I'd add this clarification for anyone else who doesn't have the option of using FreeDOS.
I think using the native URL API is better than a complex regex patterns as @pavlo suggested. It has some drawbacks though which we can fix by some extra code. This approach fails for the following valid url.
//cdn.google.com/script.js
We can add the missing protocol beforehand to avoid that. It also fails to detect following invalid url.
http://w
http://..
So why check the whole url? we can just check the domain. I borrowed the regex to verify domain from here.
function isValidUrl(string) {
if (string && string.length > 1 && string.slice(0, 2) == '//') {
string = 'http:' + string; //dummy protocol so that URL works
}
try {
var url = new URL(string);
return url.hostname && url.hostname.match(/^([a-z0-9])(([a-z0-9-]{1,61})?[a-z0-9]{1})?(\.[a-z0-9](([a-z0-9-]{1,61})?[a-z0-9]{1})?)?(\.[a-zA-Z]{2,4})+$/) ? true : false;
} catch (_) {
return false;
}
}
The hostname
attribute is empty string for javascript:void(0)
, so it works for that too, and you can also add IP address verifier too. I'd like to stick to native API's most, and hope it starts to support everything in near future.
request.FILES['filename'].name
From the request
documentation.
If you don't know the key, you can iterate over the files:
for filename, file in request.FILES.iteritems():
name = request.FILES[filename].name
A small update - hopefully useful for somebody - it works for me in my project:
I use the nice Public Domain class Base64.java from Robert Harder (Thanks Robert - Code availble here: Base64 - download and put it in your package).
and make a download of a file (image, doc, etc.) with authentication and write to local disk
Example:
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpBasicAuth {
public static void downloadFileWithAuth(String urlStr, String user, String pass, String outFilePath) {
try {
// URL url = new URL ("http://ip:port/download_url");
URL url = new URL(urlStr);
String authStr = user + ":" + pass;
String authEncoded = Base64.encodeBytes(authStr.getBytes());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setRequestProperty("Authorization", "Basic " + authEncoded);
File file = new File(outFilePath);
InputStream in = (InputStream) connection.getInputStream();
OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
for (int b; (b = in.read()) != -1;) {
out.write(b);
}
out.close();
in.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
You really want to do this
flog.write("\nCompany Name: "+ pCompanyName.encode('utf-8'))
This is the "encode late" strategy described in this unicode presentation (slides 32 through 35).
Create a block using
#define MACRO(...) do { ... } while(false)
Do not add a ; after the while(false)
I will talk about some specific cases,
if you are using 'PageNotFound method' in HomeController like below
[Route("~/404")]
public ActionResult PageNotFound()
{
return MyView();
}
it wouldn't work this. But you must clear Route tags like below,
//[Route("~/404")]
public ActionResult PageNotFound()
{
return MyView();
}
And if you change it as method Name in web.config it works. However don't forget to do code like below in web.config
<customErrors mode="On">
<error statusCode="404" redirect="~/PageNotFound" />
*// it is not "~/404" because it is not accepted url in Route Tag like [Route("404")]*
</customErrors>
The Updated code is :
private class SMSReceiver extends BroadcastReceiver {
private Bundle bundle;
private SmsMessage currentSMS;
private String message;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
bundle = intent.getExtras();
if (bundle != null) {
Object[] pdu_Objects = (Object[]) bundle.get("pdus");
if (pdu_Objects != null) {
for (Object aObject : pdu_Objects) {
currentSMS = getIncomingMessage(aObject, bundle);
String senderNo = currentSMS.getDisplayOriginatingAddress();
message = currentSMS.getDisplayMessageBody();
Toast.makeText(OtpActivity.this, "senderNum: " + senderNo + " :\n message: " + message, Toast.LENGTH_LONG).show();
}
this.abortBroadcast();
// End of loop
}
}
} // bundle null
}
}
private SmsMessage getIncomingMessage(Object aObject, Bundle bundle) {
SmsMessage currentSMS;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
String format = bundle.getString("format");
currentSMS = SmsMessage.createFromPdu((byte[]) aObject, format);
} else {
currentSMS = SmsMessage.createFromPdu((byte[]) aObject);
}
return currentSMS;
}
older code was :
Object [] pdus = (Object[]) myBundle.get("pdus");
messages = new SmsMessage[pdus.length];
for (int i = 0; i < messages.length; i++)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
String format = myBundle.getString("format");
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i], format);
}
else {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
strMessage += "SMS From: " + messages[i].getOriginatingAddress();
strMessage += " : ";
strMessage += messages[i].getMessageBody();
strMessage += "\n";
}
The simple SYntax of code is :
private class SMSReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)) {
SmsMessage[] smsMessages = Telephony.Sms.Intents.getMessagesFromIntent(intent);
for (SmsMessage message : smsMessages) {
// Do whatever you want to do with SMS.
}
}
}
}
Here's an interesting website that explains how to read complex types in C: http://www.unixwiz.net/techtips/reading-cdecl.html
I know this question is old, but the way I found the executable file for a similar application was to first open the application, then open Windows Task Manager, and in the "Processes" list right-click on it and choose "Open File Location".
I couldn't seem to find the location in the application reference file in my case...
Its because the AddDays()
method returns a new DateTime
, that you are not assigning or using anywhere.
Example of use:
DateTime newDate = endDate.AddDays(2);
EncodedParams variable is redefined as params variable will not work. You need to have same predefined call to variable, otherwise it looks possible with a little more work. Cheers! json is not used to its full capabilities in php there are better ways to call json which I don't recall at the moment.
Splitting by comma doesn't work all the time for instance if you have csv file like
"Name" , "Job" , "Address"
"Pratiyush, Singh" , "Teacher" , "Berlin, Germany"
So, I would recommend using the Apache Commons CSV API:
Reader in = new FileReader("input1.csv");
Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
for (CSVRecord record : records) {
System.out.println(record.get(0));
}
It's a builtin function that returns an object that can be iterated over. See the documentation.
In short, it loops over the elements of an iterable (like a list), as well as an index number, combined in a tuple:
for item in enumerate(["a", "b", "c"]):
print item
prints
(0, "a")
(1, "b")
(2, "c")
It's helpful if you want to loop over a sequence (or other iterable thing), and also want to have an index counter available. If you want the counter to start from some other value (usually 1), you can give that as second argument to enumerate
.
use Handler
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
// Code here will run in UI thread
}
});
To produce a list of methods put the name of the method in a list without the usual parenthesis. Remove the name and attach the parenthesis and that calls the method.
def methodA():
print("@ MethodA")
def methodB():
print("@ methodB")
a = []
a.append(methodA)
a.append(methodB)
for item in a:
item()
SQLite is created in your python directory where you installed the python.
grep -rl $oldstring . | xargs sed -i "s/$oldstring/$newstring/g"
This works without needing jQuery:
var textArea = document.getElementById("my-text-area");
var arrayOfLines = textArea.value.split("\n"); // arrayOfLines is array where every element is string of one line
map
seems like the right tool for the job to me.
my_list = ['foo', 'fob', 'faz', 'funk']
string = 'bar'
list2 = list(map(lambda orig_string: orig_string + string, my_list))
See this section on functional programming tools for more examples of map
.
IF
is a PL/SQL construct. If you are executing a query, you are using SQL not PL/SQL.
In SQL, you can use a CASE
statement in the query itself
SELECT DISTINCT a.item,
(CASE WHEN b.salesman = 'VIKKIE'
THEN 'ICKY'
ELSE b.salesman
END),
NVL(a.manufacturer,'Not Set') Manufacturer
FROM inv_items a,
arv_sales b
WHERE a.co = '100'
AND a.co = b.co
AND A.ITEM_KEY = b.item_key
AND a.item LIKE 'BX%'
AND b.salesman in ('01','15')
AND trans_date BETWEEN to_date('010113','mmddrr')
and to_date('011713','mmddrr')
ORDER BY a.item
Since you aren't doing any aggregation, you don't want a GROUP BY
in your query. Are you really sure that you need the DISTINCT
? People often throw that in haphazardly or add it when they are missing a join condition rather than considering whether it is really necessary to do the extra work to identify and remove duplicates.
look for param type
Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.
<html>
<head >
<title>Welcome</title>
<style type="text/css">
#maincontainer
{
top:0px;
padding-top:0;
margin:auto; position:relative;
width:950px;
height:100%;
}
</style>
</head>
<body>
<div id="maincontainer ">
</div>
</body>
</html>
You can use jspdf to capture a canvas into an image or pdf like this:
var imgData = canvas.toDataURL('image/png');
var doc = new jsPDF('p', 'mm');
doc.addImage(imgData, 'PNG', 10, 10);
doc.save('sample-file.pdf');
More info: https://github.com/MrRio/jsPDF
The -u flag is specifying that you want to link your local branch to the upstream branch. This will also create an upstream branch if one does not exist. None of these answers cover how i do it (in complete form) so here it is:
git push -u origin <your-local-branch-name>
So if your local branch name is coffee
git push -u origin coffee
Approach: 1
Given original string
format: 2019/03/04 00:08:48
you can use
updated_df = df['timestamp'].astype('datetime64[ns]')
The result will be in this datetime
format: 2019-03-04 00:08:48
Approach: 2
updated_df = df.astype({'timestamp':'datetime64[ns]'})
Even there's a better way to get current device language. Let's try it by below code -
NSLog(@"Current Language - %@", [[NSLocale preferredLanguages] firstObject]);
Using C++11
there is a nice version for a manually defined byte type:
enum class byte : std::uint8_t {};
That's at least what the GSL does.
Starting with C++17
(almost) this very version is defined in the standard as std::byte
(thanks Neil Macintosh for both).
This simple hack will indent the text. Works well.
select {
text-indent: 5px;
}
First, create staticfiles folder. Inside that folder create css, js, and img folder.
settings.py
import os
PROJECT_DIR = os.path.dirname(__file__)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(PROJECT_DIR, 'myweblabdev.sqlite'),
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(PROJECT_DIR, 'staticfiles'),
)
main urls.py
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from myweblab import settings
admin.autodiscover()
urlpatterns = patterns('',
.......
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
template
{% load static %}
<link rel="stylesheet" href="{% static 'css/style.css' %}">
You can leverage selectNodeContents which is supported by modern browsers.
var el = document.getElementById('idOfYoursContentEditable');
var selection = window.getSelection();
var range = document.createRange();
selection.removeAllRanges();
range.selectNodeContents(el);
range.collapse(false);
selection.addRange(range);
el.focus();
As skaffman suggested, JSP 2.0 Tag Files are the bee's knees.
Let's take your simple example.
Put the following in WEB-INF/tags/wrapper.tag
<%@tag description="Simple Wrapper Tag" pageEncoding="UTF-8"%>
<html><body>
<jsp:doBody/>
</body></html>
Now in your example.jsp
page:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>
<t:wrapper>
<h1>Welcome</h1>
</t:wrapper>
That does exactly what you think it does.
So, lets expand upon that to something a bit more general.
WEB-INF/tags/genericpage.tag
<%@tag description="Overall Page template" pageEncoding="UTF-8"%>
<%@attribute name="header" fragment="true" %>
<%@attribute name="footer" fragment="true" %>
<html>
<body>
<div id="pageheader">
<jsp:invoke fragment="header"/>
</div>
<div id="body">
<jsp:doBody/>
</div>
<div id="pagefooter">
<jsp:invoke fragment="footer"/>
</div>
</body>
</html>
To use this:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>
<t:genericpage>
<jsp:attribute name="header">
<h1>Welcome</h1>
</jsp:attribute>
<jsp:attribute name="footer">
<p id="copyright">Copyright 1927, Future Bits When There Be Bits Inc.</p>
</jsp:attribute>
<jsp:body>
<p>Hi I'm the heart of the message</p>
</jsp:body>
</t:genericpage>
What does that buy you? A lot really, but it gets even better...
WEB-INF/tags/userpage.tag
<%@tag description="User Page template" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>
<%@attribute name="userName" required="true"%>
<t:genericpage>
<jsp:attribute name="header">
<h1>Welcome ${userName}</h1>
</jsp:attribute>
<jsp:attribute name="footer">
<p id="copyright">Copyright 1927, Future Bits When There Be Bits Inc.</p>
</jsp:attribute>
<jsp:body>
<jsp:doBody/>
</jsp:body>
</t:genericpage>
To use this: (assume we have a user variable in the request)
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>
<t:userpage userName="${user.fullName}">
<p>
First Name: ${user.firstName} <br/>
Last Name: ${user.lastName} <br/>
Phone: ${user.phone}<br/>
</p>
</t:userpage>
But it turns you like to use that user detail block in other places. So, we'll refactor it.
WEB-INF/tags/userdetail.tag
<%@tag description="User Page template" pageEncoding="UTF-8"%>
<%@tag import="com.example.User" %>
<%@attribute name="user" required="true" type="com.example.User"%>
First Name: ${user.firstName} <br/>
Last Name: ${user.lastName} <br/>
Phone: ${user.phone}<br/>
Now the previous example becomes:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>
<t:userpage userName="${user.fullName}">
<p>
<t:userdetail user="${user}"/>
</p>
</t:userpage>
The beauty of JSP Tag files is that it lets you basically tag generic markup and then refactor it to your heart's content.
JSP Tag Files
have pretty much usurped things like Tiles
etc., at least for me. I find them much easier to use as the only structure is what you give it, nothing preconceived. Plus you can use JSP tag files for other things (like the user detail fragment above).
Here's an example that is similar to DisplayTag that I've done, but this is all done with Tag Files (and the Stripes
framework, that's the s: tags..). This results in a table of rows, alternating colors, page navigation, etc:
<t:table items="${actionBean.customerList}" var="obj" css_class="display">
<t:col css_class="checkboxcol">
<s:checkbox name="customerIds" value="${obj.customerId}"
onclick="handleCheckboxRangeSelection(this, event);"/>
</t:col>
<t:col name="customerId" title="ID"/>
<t:col name="firstName" title="First Name"/>
<t:col name="lastName" title="Last Name"/>
<t:col>
<s:link href="/Customer.action" event="preEdit">
Edit
<s:param name="customer.customerId" value="${obj.customerId}"/>
<s:param name="page" value="${actionBean.page}"/>
</s:link>
</t:col>
</t:table>
Of course the tags work with the JSTL tags
(like c:if
, etc.). The only thing you can't do within the body of a tag file tag is add Java scriptlet code, but this isn't as much of a limitation as you might think. If I need scriptlet stuff, I just put the logic in to a tag and drop the tag in. Easy.
So, tag files can be pretty much whatever you want them to be. At the most basic level, it's simple cut and paste refactoring. Grab a chunk of layout, cut it out, do some simple parameterization, and replace it with a tag invocation.
At a higher level, you can do sophisticated things like this table tag I have here.
your can query woocommerce programatically you can even add a product to your shopping cart. I'm sure you can figure out how to interact with woocommerce cart once you read the code. how to interact with woocommerce cart programatically
====================================
<?php
add_action('wp_loaded', 'add_product_to_cart');
function add_product_to_cart()
{
global $wpdb;
if (!is_admin()) {
$product_id = wc_get_product_id_by_sku('L3-670115');
$found = false;
if (is_user_logged_in()) {
if (sizeof(WC()->cart->get_cart()) > 0) {
foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
$_product = $values['data'];
if ($_product->get_id() == $product_id)
WC()->cart->remove_cart_item($cart_item_key);
}
}
} else {
if (sizeof(WC()->cart->get_cart()) > 0) {
foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
$_product = $values['data'];
if ($_product->id == $product_id)
$found = true;
}
// if product not found, add it
if (!$found)
WC()->cart->add_to_cart($product_id);
} else {
// if no products in cart, add it
WC()->cart->add_to_cart($product_id);
}
}
}
}
You could create a git repo and setup a link to the node git repo as a dependency. Then any user who clones the repo could also install node.
#git submodule [--quiet] add [-b branch] [-f|--force]
git submodule add /var/Node-repo.git common
You could easily package a script up to automatically clone the git repo you have hosted somewhere and "install" from one that one script file.
#!/bin/sh
#clone git repo
git clone your-repo.git
The proper way to do it is using the ng-options
directive. The HTML would look like this.
<select ng-model="selectedTestAccount"
ng-options="item.Id as item.Name for item in testAccounts">
<option value="">Select Account</option>
</select>
JavaScript:
angular.module('test', []).controller('DemoCtrl', function ($scope, $http) {
$scope.selectedTestAccount = null;
$scope.testAccounts = [];
$http({
method: 'GET',
url: '/Admin/GetTestAccounts',
data: { applicationId: 3 }
}).success(function (result) {
$scope.testAccounts = result;
});
});
You'll also need to ensure angular is run on your html and that your module is loaded.
<html ng-app="test">
<body ng-controller="DemoCtrl">
....
</body>
</html>
You need to put the last()
indexing on the nodelist result, rather than as part of the selection criteria. Try:
(//element[@name='D'])[last()]
Here is a script for that: Demo, Source
Or another one which works slightly differently: link removed (site no longer exists)
stdout
stands for standard output stream and it is a stream which is available to your program by the operating system itself. It is already available to your program from the beginning together with stdin
and stderr
.
What they point to (or from) can be anything, actually the stream just provides your program an object that can be used as an interface to send or retrieve data. By default it is usually the terminal but it can be redirected wherever you want: a file, to a pipe goint to another process and so on.
You can use Dispatcher.Invoke to update your GUI from a secondary thread.
Here is an example:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
new Thread(DoSomething).Start();
}
public void DoSomething()
{
for (int i = 0; i < 100000000; i++)
{
this.Dispatcher.Invoke(()=>{
textbox.Text=i.ToString();
});
}
}
There are 2 versions of cookies specifications
1. Version 0 cookies aka Netscape cookies,
2. Version 1 aka RFC 2965 cookies
In version 0 The name and value part of cookies are sequences of characters, excluding the semicolon, comma, equals sign, and whitespace, if not used with double quotes
version 1 is a lot more complicated you can check it here
In this version specs for name value part is almost same except name can not start with $ sign
You can try this method that is developed by Chucai Yi and Yingli Tian.
They also share a software (which is based on Opencv-1.0 and it should run under Windows platform.) that you can use (though no source code available). It will generate all the text bounding boxes (shown in color shadows) in the image. By applying to your sample images, you will get the following results:
Note: to make the result more robust, you can further merge adjacent boxes together.
Update: If your ultimate goal is to recognize the texts in the image, you can further check out gttext, which is an OCR free software and Ground Truthing tool for Color Images with Text. Source code is also available.
With this, you can get recognized texts like:
Just wanted to add another simple way someone can sort the the WPF ListView
void SortListView(ListView listView)
{
IEnumerable listView_items = listView.Items.SourceCollection;
List<MY_ITEM_CLASS> listView_items_to_list = listView_items.Cast<MY_ITEM_CLASS>().ToList();
Comparer<MY_ITEM_CLASS> scoreComparer = Comparer<MY_ITEM_CLASS>.Create((first, second) => first.COLUMN_NAME.CompareTo(second.COLUMN_NAME));
listView_items_to_list.Sort(scoreComparer);
listView.ItemsSource = null;
listView.Items.Clear();
listView.ItemsSource = listView_items_to_list;
}
Best way to swap images with javascript with left vertical clickable thumbnails
SCRIPT FILE: function swapImages() {
window.onload = function () {
var img = document.getElementById("img_wrap");
var imgall = img.getElementsByTagName("img");
var firstimg = imgall[0]; //first image
for (var a = 0; a <= imgall.length; a++) {
setInterval(function () {
var rand = Math.floor(Math.random() * imgall.length);
firstimg.src = imgall[rand].src;
}, 3000);
imgall[1].onmouseover = function () {
//alert("what");
clearInterval();
firstimg.src = imgall[1].src;
}
imgall[2].onmouseover = function () {
clearInterval();
firstimg.src = imgall[2].src;
}
imgall[3].onmouseover = function () {
clearInterval();
firstimg.src = imgall[3].src;
}
imgall[4].onmouseover = function () {
clearInterval();
firstimg.src = imgall[4].src;
}
imgall[5].onmouseover = function () {
clearInterval();
firstimg.src = imgall[5].src;
}
}
}
}
sys.maxint is not the largest integer supported by python. It's the largest integer supported by python's regular integer type.
You can get access to the environment variables in either the command line or in the registry.
Command Line
If you want a specific environment variable, then just type the name of it (e.g. PATH
), followed by a >
, and the filename to write to. The following will dump the PATH environment variable to a file named path.txt.
C:\> PATH > path.txt
Registry Method
The Windows Registry holds all the environment variables, in different places depending on which set you are after. You can use the registry Import/Export commands to shift them into the other PC.
For System Variables:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
For User Variables:
HKEY_CURRENT_USER\Environment
Have you tried it?
If you do:
var HI = 'Hello World';
In global.js
. And then do:
alert(HI);
In js1.js
it will alert it fine. You just have to include global.js
prior to the rest in the HTML document.
The only catch is that you have to declare it in the window's scope (not inside any functions).
You could just nix the var
part and create them that way, but it's not good practice.
Try this,
In Unity Editor Go to Menu, Click on Edit -> Preferences -> External Tools -> External Script Editor. Set it to Visual Studio (your installed version of VS).
Now in Menubar go to Edit -> Project Settings -> Player Settings -> Other Settings -> Under Configuration -> Check API Compatibility Level -> Change it to your installed .Net version. In my case I set it to .Net 4.x
Now if Visual Studio is running already go to Visual Studio, it will ask to reload project. Reload the project. Check if it works, if not close Visual Studio. Now Open cs file from Unity Editor, and now it should work.
How about something like:
struct foo bar;
update(init_id(42, init_dont_care(&bar)));
with:
struct foo* init_dont_care(struct foo* bar) {
bar->id = dont_care;
bar->route = dont_care;
bar->backup_route = dont_care;
bar->current_route = dont_care;
return bar;
}
and:
struct foo* init_id(int id, struct foo* bar) {
bar->id = id;
return bar;
}
and correspondingly:
struct foo* init_route(int route, struct foo* bar);
struct foo* init_backup_route(int backup_route, struct foo* bar);
struct foo* init_current_route(int current_route, struct foo* bar);
In C++, a similar pattern has a name which I don't remember just now.
EDIT: It's called the Named Parameter Idiom.
I faced the same issue and got it working.
I think it is because when you import a project, build target is not set in the project properties which then default to the value used in manifest file. Most likely, you already have installed a later android API with your SDK.
The solution is to enable build target toward your installed API level (but keep the minimum api support as specified in the manifest file). TO do this, in project properties, go to android, and from "Project Build Target", pick a target name.
I've found that one of our programmers added the following line to one of the imports:
os.chdir(<path_to_a_local_folder>)
This caused the Celery worker to change its working directory from the projects' default working directory (where it could find the tasks) to a different directory (where it couldn't find the tasks).
After removing this line of code, all tasks were found and registered.
I've just got this working, so specifically, using the Groovy Postbuild plugin, you can do the following:
def paramText
def actionList = manager.build.getActions(hudson.model.ParametersAction)
if (actionList.size() != 0)
{
def pA = actionList.get(0)
paramText = pA.createVariableResolver(manager.build).resolve("MY_PARAM_NAME")
}
I think you'll struggle with keyup event - as it first triggers keypress - and you won't be able to stop the propagation of the second one if you want to exclude the Enter Key.
If you Nuget 2.8 install, check the checkbox
Tools >> Nuget Manager >> Package Manager Settings >> Automatically check for missing packages during build
in Visual Studio. If it is checked, then simply rebuild the project will restore all your reference libraries.
The IPv4 address for the default route:
ip address show $(ip route | grep "^default " | head -n1 | grep -Po "(?<=dev )[^ ]+") | grep -Po "(?<=inet )[^ /]+"
The IPv6 address for the default route:
ip address show $(ip route | grep "^default " | head -n1 | grep -Po "(?<=dev )[^ ]+") | grep -Po "(?<=inet6 )[^ /]+"
These only require commands ip
and grep
with support for -P
and -o
. The head -1
is required because ip route
may show multiple default routes when system has complex enough network setup.
If you don't mind which IP is which, you can just do
ip route | grep -Po '(?<=src )[^ ]+'
or
hostname --all-ip-addresses
.bashrc
is not meant to be executed but sourced. Try this instead:
. ~/.bashrc
Cheers!
I was getting the same error message but had a different issue. Posting for others that are stuck on same.
I ported the get
, post
, put
, delete
functions to new router file while refactoring, and forgot to edit the paths. Example:
Incorrect:
//server.js
app.use('/blog-posts', blogPostsRouter);
//routers/blogPostsRouter.js
router.get('/blog-posts', (req, res) => {
res.json(BlogPosts.get());
});
Correct:
//server.js
app.use('/blog-posts', blogPostsRouter);
//routers/blogPostsRouter.js
router.get('/', (req, res) => {
res.json(BlogPosts.get());
});
Took a while to spot, as the error had me checking syntax where I might have been wrapping an argument in an object or where I missed the module.exports = router;
Try using the following code snippet. This should solve your issue.
body, html {
overflow-x: hidden;
overflow-y: auto;
}
jQuery is a JavaScript library.
Read
wiki-jQuery, github, jQuery vs. javascript?
What is JQuery?
Before JQuery, developers would create their own small frameworks (the group of code) this would allow all the developers to work around all the bugs and give them more time to work on features, so the JavaScript frameworks were born. Then came the collaboration stage, groups of developers instead of writing their own code would give it away for free and creating JavaScript code sets that everyone could use. That is what JQuery is, a library of JavaScript code. The best way to explain JQuery and its mission is well stated on the front page of the JQuery website which says:
JQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.
As you can see all JQuery is JavaScript. There is more than one type of JavaScript set of code sets like MooTools it is just that JQuery is the most popular.
Which is the best JavaScript or JQuery is a contentious discussion, really the answer is neither is best. They both have their roles I have worked on online applications where JQuery was not the right tool and what the application needed was straight JavaScript development. But for most websites JQuery is all that is needed. What a web developer needs to do is make an informed decision on what tools are best for their client. Someone first coming into web development does need some exposure to both technologies just using JQuery all the time does not teach the nuances of JavaScript and how it affects the DOM. Using JavaScript all the time slows projects down and because of the JQuery library has ironed most of the issues that JavaScript will have between each web browser it makes the deployment safe as it is sure to work across all platforms.
JavaScript is a language. jQuery is a library built with JavaScript to help JavaScript programmers who are doing common web tasks.
See here.
Not all controls that can be included in a page must be run at the server. For example:
<INPUT type="submit" runat=server />
This is essentially the same as:
<asp:Button runat=server />
Remove the runat=server tag from the first one and you have a standard HTML button that runs in the browser. There are reasons for and against running a particular control at the server, and there is no way for ASP.NET to "assume" what you want based on the HTML markup you include. It might be possible to "infer" the runat=server for the <asp:XXX />
family of controls, but my guess is that Microsoft would consider that a hack to the markup syntax and ASP.NET engine.
To put it simply, you don't use generate
inside an always process, you use generate to create a parametrized process or instantiate particular modules, where you can combine if-else
or case
. So you can move this generate and crea a particular process or an instantiation e.g.,
module #(
parameter XLEN = 64,
parameter USEIP = 0
)
(
input clk,
input rstn,
input [XLEN-1:0] opA,
input [XLEN-1:0] opB,
input [XLEN-1:0] opR,
input en
);
generate
case(USEIP)
0:begin
always @(posedge clk or negedge rstn)
begin
if(!rstn)
begin
opR <= '{default:0};
end
else
begin
if(en)
opR <= opA+opB;
else
opR <= '{default:0};
end
end
end
1:begin
superAdder #(.XLEN(XLEN)) _adder(.clk(clk),.rstm(rstn), .opA(opA), .opB(opB), .opR(opR), .en(en));
end
endcase
endmodule
If you have a built-in command of GridView like insert, update or delete, on row command you can use the following code to get the index:
int index = Convert.ToInt32(e.CommandArgument);
In a custom command, you can set the command argument to yourRow.RowIndex.ToString()
and then get it back in the RowCommand event handler. Unless, of course, you need the command argument for another purpose.
The input date value format needs the date specified as per http://tools.ietf.org/html/rfc3339#section-5.6 full-date.
So I've ended up doing:
<input type="date" id="last-start-date" value="@string.Format("{0:yyyy-MM-dd}", Model.LastStartDate)" />
I did try doing it "properly" using:
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime LastStartDate
{
get { return lastStartDate; }
set { lastStartDate = value; }
}
with
@Html.TextBoxFor(model => model.LastStartDate,
new { type = "date" })
Unfortunately that always seemed to set the value attribute of the input to a standard date time so I've ended up applying the formatting directly as above.
Edit:
According to Jorn if you use
@Html.EditorFor(model => model.LastStartDate)
instead of TextBoxFor it all works fine.
I solved this problem by restarting PHPStorm (insert your programm instead) as administrator
Looks like you are using pandas dataframe (from the name df2).
You could also do the following:
regr = LinearRegression()
regr.fit(df2.iloc[1:1000, 5].to_frame(), df2.iloc[1:1000, 2].to_frame())
NOTE: I have removed "values" as that converts the pandas Series to numpy.ndarray and numpy.ndarray does not have attribute to_frame().
You should set a fixed value to your span's line-height
property:
.float, .twoline {
line-height: 100px;
}
For Bootstrap (at least for version 3.1.1) and LESS, you can use this:
.btn-my-custom {
.button-variant(@color; @background; @border)
}
This is defined in bootstrap/less/buttons.less
.
og_date = "2012-10-01";
console.log(og_date); // => "2012-10-01"
console.log(og_date.split('-')); // => [ '2012', '10', '01' ]
og_date.value
would only work if the date were stored as a property on the og_date object.
Such as: var og_date = {}; og_date.value="2012-10-01";
In that case, your original console.log would work.
Unfortunately, it seems that proxy information must be set on each call to http.request
. Node does not include a mechanism for global proxy settings.
The global-tunnel-ng
module on NPM appears to handle this, however:
var globalTunnel = require('global-tunnel-ng');
globalTunnel.initialize({
host: '10.0.0.10',
port: 8080,
proxyAuth: 'userId:password', // optional authentication
sockets: 50 // optional pool size for each http and https
});
After the global settings are establish with a call to initialize
, both http.request
and the request
library will use the proxy information.
The module can also use the http_proxy
environment variable:
process.env.http_proxy = 'http://proxy.example.com:3129';
globalTunnel.initialize();
Most of these answers were written in Python version 2.x or earlier. In Python 3.x the syntax for the print function has changed to require parentheses, i.e. print().
So, this earlier high score answer from user13993 in Python 2.x:
import inspect, os
print inspect.getfile(inspect.currentframe()) # script filename (usually with path)
print os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # script directory
Becomes in Python 3.x:
import inspect, os
print(inspect.getfile(inspect.currentframe())) # script filename (usually with path)
print(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) ) # script directory
1)check the package name is the same in google-services.json file
2)make sure that no other project exist with same package name
3)make sure that there is internet access
4)try syncing project and running it again
You can use e.preventDefault();
instead of e.stopPropagation();
In your AVD advanced settings, you should be able to set front and back cameras to Webcam()
or Emulated
.
There are many ways, as listed above, but I find that I just want to import he contents of a file, and don't want to have to write lines and lines and have to import other modules. So, I came up with a way to get the contents of a file, even with the dot syntax (file.property
) as opposed to merging the imported file with yours.
First of all, here is my file which I'll import, data.py
testString= "A string literal to import and test with"
Note: You could use the .txt
extension instead.
In mainfile.py
, start by opening and getting the contents.
#!usr/bin/env python3
Data=open('data.txt','r+').read()
Now you have the contents as a string, but trying to access data.testString
will cause an error, as data
is an instance of the str
class, and even if it does have a property testString
it will not do what you expected.
Next, create a class. For instance (pun intended), ImportedFile
class ImportedFile:
And put this into it (with the appropriate indentation):
exec(data)
And finally, re-assign data
like so:
data=ImportedFile()
And that's it! Just access like you would for any-other module, typing print(data.testString)
will print to the console A string literal to import and test with
.
If, however, you want the equivalent of from mod import *
just drop the class, instance assignment, and de-dent the exec
.
Hope this helps:)
-Benji
Lookarounds can be nested.
So this regex matches "drupal-6.14/" that is not followed by "sites" that is not followed by "/all" or "/default".
Confusing? Using different words, we can say it matches "drupal-6.14/" that is not followed by "sites" unless that is further followed by "/all" or "/default"
The above answers are very reasonable but my solution was simply to run the installer as administrator.
This is clearly stated here on the wampserver forum (2nd tip).
There are 20 other suggestions as well.
I usually use:
$("#my-Select option[text='" + myText +"']").attr("selected","selected") ;
Assuming you want product with MIN()
imial value in sort
column, it would look something like this.
SELECT
c.id, c.title, p.id AS product_id, p.title
FROM
categories AS c
INNER JOIN (
SELECT
p.id, p.category_id, p.title
FROM
products AS p
CROSS JOIN (
SELECT p.category_id, MIN(sort) AS sort
FROM products
GROUP BY category_id
) AS sq USING (category_id)
) AS p ON c.id = p.category_id
position: absolute
will remove it from the layout flow and should solve your problem - the element will remain in the DOM but won't affect others.
Taking for granted that the JSON you posted is actually what you are seeing in the browser, then the problem is the JSON itself.
The JSON snippet you have posted is malformed.
You have posted:
[{
"name" : "shopqwe",
"mobiles" : [],
"address" : {
"town" : "city",
"street" : "streetqwe",
"streetNumber" : "59",
"cordX" : 2.229997,
"cordY" : 1.002539
},
"shoe"[{
"shoeName" : "addidas",
"number" : "631744030",
"producent" : "nike",
"price" : 999.0,
"sizes" : [30.0, 35.0, 38.0]
}]
while the correct JSON would be:
[{
"name" : "shopqwe",
"mobiles" : [],
"address" : {
"town" : "city",
"street" : "streetqwe",
"streetNumber" : "59",
"cordX" : 2.229997,
"cordY" : 1.002539
},
"shoe" : [{
"shoeName" : "addidas",
"number" : "631744030",
"producent" : "nike",
"price" : 999.0,
"sizes" : [30.0, 35.0, 38.0]
}
]
}
]
PHP has already a fair treatment base64 -> file transform
I use to get it done using this way:
$blob=$_POST['blob']; // base64 coming from an url, for example
$blob=file_get_contents($blob);
$fh=fopen("myfile.png",'w'); // be aware, it'll overwrite!
fwrite($fh,$blob);
fclose($fh);
echo '<img src=myfile.png>'; // just for the check
I needed a non-interactive method for cloning a private repo.
Inspired by this issue: https://github.com/github/hub/issues/1644
Step 1.
Create a personal access token in the github developer settings: https://github.com/settings/tokens
Step 2.
git clone https://$token:[email protected]/$username/$repo.git
I would imagine you could do it by setting up a transparent proxy, using something like charles and re-direct traffic that way
Here, I'll over-architect the answer using LINQ. Just shows that there's more than 'n' ways to cook an egg:
public int countTrue(string data)
{
string[] splitdata = data.Split(',');
var results = from p in splitdata
where p.Contains("true")
select p;
return results.Count();
}
Check ur code signing section.make sure that the code signing is iPhoneDeveloper code signe
For Intellij 14.0.0 the Application server option is available under View > Tools window > Application Server (But if it is enable, i mean if you have any plugin installed)
May this code helps you.
$(document).ready(function(){_x000D_
$('.slectOne').on('change', function() {_x000D_
$('.slectOne').not(this).prop('checked', false);_x000D_
$('#result').html($(this).data( "id" ));_x000D_
if($(this).is(":checked"))_x000D_
$('#result').html($(this).data( "id" ));_x000D_
else_x000D_
$('#result').html('Empty...!');_x000D_
});_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<input type="checkbox" class="slectOne" data-id="1 selected"/>_x000D_
<input type="checkbox" class="slectOne" data-id="2 selected"/>_x000D_
<input type="checkbox" class="slectOne" data-id="3 selected"/>_x000D_
<input type="checkbox" class="slectOne" data-id="4 selected"/>_x000D_
<input type="checkbox" class="slectOne" data-id="5 selected"/>_x000D_
<input type="checkbox" class="slectOne" data-id="6 selected"/>_x000D_
<input type="checkbox" class="slectOne" data-id="7 selected"/>_x000D_
<input type="checkbox" class="slectOne" data-id="8 selected"/>_x000D_
<input type="checkbox" class="slectOne" data-id="9 selected"/>_x000D_
<input type="checkbox" class="slectOne" data-id="10 selected"/>_x000D_
<span id="result"></span>_x000D_
</body>_x000D_
</html>
_x000D_
Working link Click here
Just wanted to contribute my version of objects comparison utilizing some es6 features. It doesn't take an order into account. After converting all if/else's to ternary I've came with following:
function areEqual(obj1, obj2) {
return Object.keys(obj1).every(key => {
return obj2.hasOwnProperty(key) ?
typeof obj1[key] === 'object' ?
areEqual(obj1[key], obj2[key]) :
obj1[key] === obj2[key] :
false;
}
)
}
Use this code to read an Internet resource into a String
:
public static String readToString(String targetURL) throws IOException
{
URL url = new URL(targetURL);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(url.openStream()));
StringBuilder stringBuilder = new StringBuilder();
String inputLine;
while ((inputLine = bufferedReader.readLine()) != null)
{
stringBuilder.append(inputLine);
stringBuilder.append(System.lineSeparator());
}
bufferedReader.close();
return stringBuilder.toString().trim();
}
This is based on here.
This is in response to @LordZardeck's comment to @naomik's excellent answer above. Sorry, I would've commented directly but I've never posted before so I don't have the privilege to do so, so I am posting here instead.
Anyhow, I just happened to translate the ES5 version to a more readable form this past weekend so I'm sharing it here. This should be faithful to the original (including the recent edit) and I hope the naming is clear and accurate.
function int_to_words(int) {
if (int === 0) return 'zero';
var ONES = ['','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'];
var TENS = ['','','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety'];
var SCALE = ['','thousand','million','billion','trillion','quadrillion','quintillion','sextillion','septillion','octillion','nonillion'];
// Return string of first three digits, padded with zeros if needed
function get_first(str) {
return ('000' + str).substr(-3);
}
// Return string of digits with first three digits chopped off
function get_rest(str) {
return str.substr(0, str.length - 3);
}
// Return string of triplet convereted to words
function triplet_to_words(_3rd, _2nd, _1st) {
return (_3rd == '0' ? '' : ONES[_3rd] + ' hundred ') + (_1st == '0' ? TENS[_2nd] : TENS[_2nd] && TENS[_2nd] + '-' || '') + (ONES[_2nd + _1st] || ONES[_1st]);
}
// Add to words, triplet words with scale word
function add_to_words(words, triplet_words, scale_word) {
return triplet_words ? triplet_words + (scale_word && ' ' + scale_word || '') + ' ' + words : words;
}
function iter(words, i, first, rest) {
if (first == '000' && rest.length === 0) return words;
return iter(add_to_words(words, triplet_to_words(first[0], first[1], first[2]), SCALE[i]), ++i, get_first(rest), get_rest(rest));
}
return iter('', 0, get_first(String(int)), get_rest(String(int)));
}
This did the trick for me:Just remove all the libraries and then compile and run. It would prompt their are errors in your project confirm. Rerun the project after applying the libraries.
sudo apt-get install phpx.x-gd
sudo service apache2 restart
x.x is the versión php.
The zip()
function in Python 3 returns an iterator. That is the reason why when you print test1
you get - <zip object at 0x1007a06c8>
. From documentation -
Make an iterator that aggregates elements from each of the iterables.
But once you do - list(test1)
- you have exhausted the iterator. So after that anytime you do list(test1)
would only result in empty list.
In case of test2
, you have already created the list once, test2
is a list, and hence it will always be that list.
I had the same issue but the problem was that zoom was not defined within the options object given to Google Maps.
My Problem was that I was not in the correct git directory that I just cloned.
If it's just a single character 0-9 in ASCII, then subtracting the the value of the ASCII zero character from ASCII value should work fine.
If you want to convert larger numbers then the following will do:
char *string = "24";
int value;
int assigned = sscanf(string, "%d", &value);
** don't forget to check the status (which should be 1 if it worked in the above case).
Paul.
I am lost in all these samples but today I needed to load an external .js from my main .js and I did this:
document.write("<script src='https://www.google.com/recaptcha/api.js'></script>");
Each directive's compile
function is only called once, when Angular bootstraps.
Officially, this is the place to perform (source) template manipulations that do not involve scope or data binding.
Primarily, this is done for optimisation purposes; consider the following markup:
<tr ng-repeat="raw in raws">
<my-raw></my-raw>
</tr>
The <my-raw>
directive will render a particular set of DOM markup. So we can either:
ng-repeat
to duplicate the source template (<my-raw>
), and then modify the markup of each instance template (outside the compile
function).compile
function), and then allow ng-repeat
to duplicate it.If there are 1000 items in the raws
collection, the latter option may be faster than the former one.
A pure javascript solution without JQuery. Tested on Chrome & I.e, not tested on IOS
function ScrollTo(name) {
ScrollToResolver(document.getElementById(name));
}
function ScrollToResolver(elem) {
var jump = parseInt(elem.getBoundingClientRect().top * .2);
document.body.scrollTop += jump;
document.documentElement.scrollTop += jump;
if (!elem.lastjump || elem.lastjump > Math.abs(jump)) {
elem.lastjump = Math.abs(jump);
setTimeout(function() { ScrollToResolver(elem);}, "100");
} else {
elem.lastjump = null;
}
}
I would do it in the Initialize event of the controller like this...
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
const string culture = "en-US";
CultureInfo ci = CultureInfo.GetCultureInfo(culture);
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
}
For me, parameter (JSONObject inputJsonObj) was not working. I am using jersey 2.* Hence I feel this is the
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public Map<String, String> methodName(String data) throws Exception {
JSONObject recoData = new JSONObject(data);
//Do whatever with json object
}
Client side I used AngularJS
factory.update = function () {
data = {user:'Shreedhar Bhat',address:[{houseNo:105},{city:'Bengaluru'}]};
data= JSON.stringify(data);//Convert object to string
var d = $q.defer();
$http({
method: 'POST',
url: 'REST/webApp/update',
headers: {'Content-Type': 'text/plain'},
data:data
})
.success(function (response) {
d.resolve(response);
})
.error(function (response) {
d.reject(response);
});
return d.promise;
};
Try doing this, there's no special character to concatenate in bash :
mystring="${arg1}12${arg2}endoffile"
If you don't put brackets, you will ask bash to concatenate $arg112 + $argendoffile
(I guess that's not what you asked) like in the following example :
mystring="$arg112$arg2endoffile"
The brackets are delimiters for the variables when needed. When not needed, you can use it or not.
bash
> 3.1)
$ arg1=foo
$ arg2=bar
$ mystring="$arg1"
$ mystring+="12"
$ mystring+="$arg2"
$ mystring+="endoffile"
$ echo "$mystring"
foo12barendoffile
If I am not mistaken, it will be onunload event.
"Occurs when the application is about to be unloaded." - MSDN
From Apple's docs:
Symbolicating Crash Reports With Xcode Xcode will automatically attempt to symbolicate all crash reports that it encounters. All you need to do for symbolication is to add the crash report to the Xcode Organizer.
Xcode will automatically symbolicate the crash report and display the results To symbolicate a crash report, Xcode needs to be able to locate the following:
The crashing application's binary and dSYM file.
The binaries and dSYM files for all custom frameworks that the application links against. For frameworks that were built from source with the application, their dSYM files are copied into the archive alongside the application's dSYM file. For frameworks that were built by a third-party, you will need to ask the author for the dSYM file.
Symbols for the OS that the that application was running on when it crashed. These symbols contain debug information for the frameworks included in a specific OS release (e.g, iOS 9.3.3). OS symbols are architecture specific - a release of iOS for 64-bit devices won't include armv7 symbols. Xcode will automatically copy OS symbols from each device that you connect to your Mac.
If any of these are missing Xcode may not be able to symbolicate the crash report, or may only partially symbolicate the crash report.
AngularUI Router is a routing framework for AngularJS, which allows you to organize the parts of your interface into a state machine. Unlike the $route service in the Angular ngRoute module, which is organized around URL routes, UI-Router is organized around states, which may optionally have routes, as well as other behavior, attached.
I've tried the solutions above (and also) many other solutions from other posts.
In my case, I did it with the following setup:
public partial class WaitingDialog : Form
{
public WaitingDialog()
{
InitializeComponent();
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
this.BackColor = Color.Transparent;
// Other stuff
}
protected override void OnPaintBackground(PaintEventArgs e) { /* Ignore */ }
}
As you can see, this is a mix of previously given answers.
You can utilize the http.proxy* JVM variables if you're within a standalone JVM but you SHOULD NOT modify their startup scripts and/or do this within your application server (except maybe jboss or tomcat). Instead you should utilize the JAVA Proxy API (not System.setProperty) or utilize the vendor's own configuration options. Both WebSphere and WebLogic have very defined ways of setting up the proxies that are far more powerful than the J2SE one. Additionally, for WebSphere and WebLogic you will likely break your application server in little ways by overriding the startup scripts (particularly the server's interop processes as you might be telling them to use your proxy as well...).
Windows imposes a memory limit per process, you can see what it is for each version here
See:
User-mode virtual address space for each 64-bit process;
With IMAGE_FILE_LARGE_ADDRESS_AWARE set (default):
x64: 8 TB
Intel IPF: 7 TB
2 GB with IMAGE_FILE_LARGE_ADDRESS_AWARE cleared
You can filter using index
of array.
var months = ['Jan', 'March', 'April', 'June'];_x000D_
months = months.filter((month,idx) => idx < 2)_x000D_
console.log(months);
_x000D_
There seems to be no way to place buttons (drawings, images) within cells in a way that would allow them to be linked to Apps Script functions.
This being said, there are some things that you can indeed do:
You can place images within cells using IMAGE(URL)
, but they cannot be linked to Apps Script functions.
You can place images within cells and link them to URLs using:
=HYPERLINK("http://example.com"; IMAGE("http://example.com/myimage.png"; 1))
You can create drawings as described in the answer of @Eduardo and they can be linked to Apps Script functions, but they will be stand-alone items that float freely "above" the spreadsheet and cannot be positioned in cells. They cannot be copied from cell to cell and they do not have a row or col position that the script function could read.
it can be done with CURL or AJAX. The response is equally cryptic as the answer.
Hi This is the way to solve CORS problem in node Just add these lines on server "api" side in Node.js(or what ever your server File), befor that make sure to install "cors"
const express = require('express');
const app = express();
app.use(express.json());
var cors = require('cors');
app.use(cors());
There is also another straight and more clear way
git commit -m "Title" -m "Description ..........";
On local server your following query will work
DELIMITER |
CREATE PROCEDURE sample_sp_with_params (IN empId INT UNSIGNED, OUT oldName VARCHAR(20), INOUT newName VARCHAR(20))
BEGIN
SELECT `first name` into oldName FROM emp where id = empId;
UPDATE emp SET `first name`= newName where id = empId;
END
|
DELIMITER ;
but on production server it might not work. depend on mysql version you are using. I had a same problem on powweb server, i removed delimiter and begin keywords, it works fine. have a look at following query
CREATE PROCEDURE adminsections( IN adminId INT UNSIGNED ) SELECT tbl_adminusersection.ads_name, tbl_adminusersection.ads_controller FROM tbl_adminusersectionright LEFT JOIN tbl_adminusersection ON ( tbl_adminusersectionright.adsr_ads_id = tbl_adminusersection.ads_id ) LEFT JOIN tbl_adminusers ON ( tbl_adminusersectionright.adsr_adusr_id = tbl_adminusers.admusr_id ) WHERE tbl_adminusers.admusr_id = adminId;
Here's the solution for you. It's very easy to just add code like this:
$('#datetimepicker4').datetimepicker({
pickTime: false
minview:2;(Please see here.)
});
You can use a concept that is frequently referred to as 'calendar tables'. Here is a good guide on how to create calendar tables in MySql:
-- create some infrastructure
CREATE TABLE ints (i INTEGER);
INSERT INTO ints VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);
-- only works for 100 days, add more ints joins for more
SELECT cal.date, tbl.data
FROM (
SELECT '2009-06-25' + INTERVAL a.i * 10 + b.i DAY as date
FROM ints a JOIN ints b
ORDER BY a.i * 10 + b.i
) cal LEFT JOIN tbl ON cal.date = tbl.date
WHERE cal.date BETWEEN '2009-06-25' AND '2009-07-01';
You might want to create table cal
instead of the subselect.
git tag -l --format='%(contents)'
or
git for-each-ref refs/tags/ --format='%(contents)'
will output full annotation message for every tag (including signature if its signed).
%(contents:subject)
will output only first line%(contents:body)
will output annotation without first line and signature (useful text only)%(contents:signature)
will output only PGP-signatureSee more in man git-for-each-ref
“Field names” section.
Something like:
find /path/ -type f -exec stat \{} --printf="%y\n" \; |
sort -n -r |
head -n 1
Explanation:
On SQL 2012 getting this information on a table level has become deliciously simple:
SQL Management Studio -> Right click on Db -> Reports -> Standard Reports -> Disk usage by table !
Enjoy
You can try this tool I made:
It converts to JSON, XML and others.
It's all client side, too, so your data never leaves your computer.
If you want to remove F0
from the whole string then the replaceAll()
method works for you.
const str = 'F0123F0456F0'.replaceAll('F0', '');
console.log(str);
_x000D_
For all the pythonian zealots out there I'm sure Johan Cleeze would approve of your dogmatism ;). I'm leaving this answer keep demeriting it It actually makes me more confidant. Leave a comment you chickens!
For python 3.6
class SomeClass:
def attr_list1(self, should_print=False):
for k in self.__dict__.keys():
v = self.__dict__.__getitem__(k)
if should_print:
print(f"attr: {k} value: {v}")
def attr_list(self, should_print=False):
b = [(k, v) for k, v in self.__dict__.items()]
if should_print:
[print(f"attr: {a[0]} value: {a[1]}") for a in b]
return b
public static void main(String[] args) {
int smallest = 0;
int large = 0;
int num;
System.out.println("enter the number");//how many number you want to enter
Scanner input = new Scanner(System.in);
int n = input.nextInt();
num = input.nextInt();
smallest = num; //assume first entered number as small one
// i starts from 2 because we already took one num value
for (int i = 2; i < n; i++) {
num = input.nextInt();
//comparing each time entered number with large one
if (num > large) {
large = num;
}
//comparing each time entered number with smallest one
if (num < smallest) {
smallest = num;
}
}
System.out.println("the largest is:" + large);
System.out.println("Smallest no is : " + smallest);
}
I was just searching for something similar:
I want to sum every odd row column.
SUMIF
has TWO possible ranges, the range to sum from, and a range to consider criteria in.
SUMIF(B1:B1000,1,A1:A1000)
This function will consider if a cell in the B range is "=1", it will sum the corresponding A cell only if it is.
To get "=1" to return in the B range I put this in B:
=MOD(ROWNUM(B1),2)
Then auto fill down to get the modulus to fill, you could put and calculatable criteria here to get the SUMIF or SUMIFS conditions you need to loop through each cell.
Easier than ARRAY stuff and hides the back-end of loops!
You should declare metab as integer and then use arithmetic evaluation
declare -i metab num
...
num+=metab
...
For more information see https://www.gnu.org/software/bash/manual/html_node/Shell-Arithmetic.html#Shell-Arithmetic
When you say
foo = 'bar'
baz(foo)
you are not passing foo
to the baz
function. foo
is just a name used to represent a value, in this case 'bar'
, and that value is passed to the baz
function.
The curly braces inside backgroundImage property are wrong.
Probably you are using webpack along with image files loader, so Background should be already a String:
backgroundImage: "url(" + Background + ")"
You can also use ES6 string templates as below to achieve the same effect:
backgroundImage: `url(${Background})`
The suggested solutions could be optimized using commons.io, handling the error stream, and using Exceptions. I would suggest to wrap like this for use in Java 8 or later:
public static List<String> execute(final String command) throws ExecutionFailedException, InterruptedException, IOException {
try {
return execute(command, 0, null, false);
} catch (ExecutionTimeoutException e) { return null; } /* Impossible case! */
}
public static List<String> execute(final String command, final long timeout, final TimeUnit timeUnit) throws ExecutionFailedException, ExecutionTimeoutException, InterruptedException, IOException {
return execute(command, 0, null, true);
}
public static List<String> execute(final String command, final long timeout, final TimeUnit timeUnit, boolean destroyOnTimeout) throws ExecutionFailedException, ExecutionTimeoutException, InterruptedException, IOException {
Process process = new ProcessBuilder().command("bash", "-c", command).start();
if(timeUnit != null) {
if(process.waitFor(timeout, timeUnit)) {
if(process.exitValue() == 0) {
return IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8);
} else {
throw new ExecutionFailedException("Execution failed: " + command, process.exitValue(), IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8));
}
} else {
if(destroyOnTimeout) process.destroy();
throw new ExecutionTimeoutException("Execution timed out: " + command);
}
} else {
if(process.waitFor() == 0) {
return IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8);
} else {
throw new ExecutionFailedException("Execution failed: " + command, process.exitValue(), IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8));
}
}
}
public static class ExecutionFailedException extends Exception {
private static final long serialVersionUID = 1951044996696304510L;
private final int exitCode;
private final List<String> errorOutput;
public ExecutionFailedException(final String message, final int exitCode, final List<String> errorOutput) {
super(message);
this.exitCode = exitCode;
this.errorOutput = errorOutput;
}
public int getExitCode() {
return this.exitCode;
}
public List<String> getErrorOutput() {
return this.errorOutput;
}
}
public static class ExecutionTimeoutException extends Exception {
private static final long serialVersionUID = 4428595769718054862L;
public ExecutionTimeoutException(final String message) {
super(message);
}
}
What I learn about promises is to use it only as return values avoid referencing them if possible. async/await syntax is particularly practical for that. Today all latest browsers and node support it: https://caniuse.com/#feat=async-functions , is a simple behavior and the code is like reading synchronous code, forget about callbacks...
In cases I do need to reference a promises is when creation and resolution happen at independent/not-related places. So instead an artificial association and probably an event listener just to resolve the "distant" promise, I prefer to expose the promise as a Deferred, which the following code implements it in valid es5
/**
* Promise like object that allows to resolve it promise from outside code. Example:
*
```
class Api {
fooReady = new Deferred<Data>()
private knower() {
inOtherMoment(data=>{
this.fooReady.resolve(data)
})
}
}
```
*/
var Deferred = /** @class */ (function () {
function Deferred(callback) {
var instance = this;
this.resolve = null;
this.reject = null;
this.status = 'pending';
this.promise = new Promise(function (resolve, reject) {
instance.resolve = function () { this.status = 'resolved'; resolve.apply(this, arguments); };
instance.reject = function () { this.status = 'rejected'; reject.apply(this, arguments); };
});
if (typeof callback === 'function') {
callback.call(this, this.resolve, this.reject);
}
}
Deferred.prototype.then = function (resolve) {
return this.promise.then(resolve);
};
Deferred.prototype.catch = function (r) {
return this.promise.catch(r);
};
return Deferred;
}());
transpiled form a typescript project of mine:
For more complex cases I often use these guy small promise utilities without dependencies tested and typed. p-map has been useful several times. I think he covered most use cases:
https://github.com/sindresorhus?utf8=%E2%9C%93&tab=repositories&q=promise&type=source&language=
I have faced this error a lot of time, also research why this error occurs and finally, I caught this error, this error a silly error which occurs when we misspelled .xib
file name.
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"TableViewCell" owner:self options:nil];
At this point, I misspelled TableViewCell
as TabelViewCell
, because the perception of some time we read it as correct, this is the most common problem.
Just copy your .xib
file name, and paste it.
Facebook uses what's called the Open Graph Protocol to decide what things to display when you share a link. The OGP looks at your page and tries to decide what content to show. We can lend a hand and actually tell Facebook what to take from our page.
The way we do that is with og:meta
tags.
The tags look something like this -
<meta property="og:title" content="Stuffed Cookies" />
<meta property="og:image" content="http://fbwerks.com:8000/zhen/cookie.jpg" />
<meta property="og:description" content="The Turducken of Cookies" />
<meta property="og:url" content="http://fbwerks.com:8000/zhen/cookie.html">
You'll need to place these or similar meta tags in the <head>
of your HTML file. Don't forget to substitute the values for your own!
For more information you can read all about how Facebook uses these meta tags in their documentation. Here is one of the tutorials from there - https://developers.facebook.com/docs/opengraph/tutorial/
Facebook gives us a great little tool to help us when dealing with these meta tags - you can use the Debugger to see how Facebook sees your URL, and it'll even tell you if there are problems with it.
One thing to note here is that every time you make a change to the meta tags, you'll need to feed the URL through the Debugger again so that Facebook will clear all the data that is cached on their servers about your URL.
In my case, the table's id column was not set as an Identity column.
Is this what you are looking for? Here is a fiddle demo.
The layout is based on percentage, colors are for clarity. If the content column overflows, a scrollbar should appear.
body, html, .container-fluid {
height: 100%;
}
.navbar {
width:100%;
background:yellow;
}
.article-tree {
height:100%;
width: 25%;
float:left;
background: pink;
}
.content-area {
overflow: auto;
height: 100%;
background:orange;
}
.footer {
background: red;
width:100%;
height: 20px;
}
To show the "My Location" button you have to call
map.getUiSettings().setMyLocationButtonEnabled(true);
on your GoogleMap object.
IIS URL Rewrite Rule to prevent 404 error after page refresh in html5mode
For angular running under IIS on Windows
<rewrite>
<rules>
<rule name="AngularJS" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
NodeJS / ExpressJS Routes to prevent 404 error after page refresh in html5mode
For angular running under Node/Express
var express = require('express');
var path = require('path');
var router = express.Router();
// serve angular front end files from root path
router.use('/', express.static('app', { redirect: false }));
// rewrite virtual urls to angular app to enable refreshing of internal pages
router.get('*', function (req, res, next) {
res.sendFile(path.resolve('app/index.html'));
});
module.exports = router;
More info at: AngularJS - Enable HTML5 Mode Page Refresh Without 404 Errors in NodeJS and IIS
add one folder any name e.g public and add .htaccess file and write allow from all it means, in this folder your all files and all folder will not give error Access forbidden! use it like this
<link href="<?php echo base_url(); ?>application/public/css/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="<?php echo base_url(); ?>application/public/js/javascript.js"></script>
MERGE INTO OPT
USING
(SELECT 1 "one" FROM dual)
ON
(OPT.email= '[email protected]' and OPT.campaign_id= 100)
WHEN NOT matched THEN
INSERT (email, campaign_id)
VALUES ('[email protected]',100)
;
I would suggest the following:
String[] parsedInput = str.split("\n"); String firstName = parsedInput[0].split(": ")[1]; String lastName = parsedInput[1].split(": ")[1]; myMap.put(firstName,lastName);
sudo apt-get install libcurl4-openssl-dev
When you run cmake add the additional parameter -D OPENCV_GENERATE_PKGCONFIG=YES (this will generate opencv.pc file)
Then make and sudo make install as before.
Use the name opencv4 instead of just opencv Eg:-
pkg-config --modversion opencv4
This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.
Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.
In this case I'd ask why you're including both cstdlib
and stdlib.h
; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib
puts them in the namespace std
in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!
Anyway, your use of using namespace std
(which I would recommend against, in future) means that std::system
from cstdlib
now conflicts with system
from stdlib.h
. I can't explain what's going on with std::cout
and std::cin
.
Try removing #include <stdlib.h>
and see what happens.
If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.
Pure js. Can apply it to multiple tables at once. Aborts if only one page is required. I used anushree as my starting point.
Sorry to the asker, obviously this is not a simplePagignation.js solution. However, it's the top google result when you type "javascript table paging", and it's a reasonable solution to many who may be considering a library but unsure whether to go that route or not.
Use like this:
addPagerToTables('#someTable', 8);
Requires no css, though it may be wise to initially hide table tBody rows in css anyway to prevent the effect of rows showing then quicky being hidden (not happening with me right now, but it's something I've seen before).
The code:
function addPagerToTables(tables, rowsPerPage = 10) {
tables =
typeof tables == "string"
? document.querySelectorAll(tables)
: tables;
for (let table of tables)
addPagerToTable(table, rowsPerPage);
}
function addPagerToTable(table, rowsPerPage = 10) {
let tBodyRows = table.querySelectorAll('tBody tr');
let numPages = Math.ceil(tBodyRows.length/rowsPerPage);
let colCount =
[].slice.call(
table.querySelector('tr').cells
)
.reduce((a,b) => a + parseInt(b.colSpan), 0);
table
.createTFoot()
.insertRow()
.innerHTML = `<td colspan=${colCount}><div class="nav"></div></td>`;
if(numPages == 1)
return;
for(i = 0;i < numPages;i++) {
let pageNum = i + 1;
table.querySelector('.nav')
.insertAdjacentHTML(
'beforeend',
`<a href="#" rel="${i}">${pageNum}</a> `
);
}
changeToPage(table, 1, rowsPerPage);
for (let navA of table.querySelectorAll('.nav a'))
navA.addEventListener(
'click',
e => changeToPage(
table,
parseInt(e.target.innerHTML),
rowsPerPage
)
);
}
function changeToPage(table, page, rowsPerPage) {
let startItem = (page - 1) * rowsPerPage;
let endItem = startItem + rowsPerPage;
let navAs = table.querySelectorAll('.nav a');
let tBodyRows = table.querySelectorAll('tBody tr');
for (let nix = 0; nix < navAs.length; nix++) {
if (nix == page - 1)
navAs[nix].classList.add('active');
else
navAs[nix].classList.remove('active');
for (let trix = 0; trix < tBodyRows.length; trix++)
tBodyRows[trix].style.display =
(trix >= startItem && trix < endItem)
? 'table-row'
: 'none';
}
}
Your modifications are in a different branch than the original branch, which simplifies stuff because you get updates in one branch, and your work is in another branch.
Assuming the original branch is named master
, which the case in 99% of git repos, you have to fetch the state of origin, and merge origin/master
updates into your local master
:
git fetch origin
git checkout master
git merge origin/master
To switch to your branch, just do
git checkout branch1
When using kill -3 one should see the thread dump in the standard output. Most of the application servers write the standard output to a separate file. You should find it there when using kill -3. There are multiple ways of getting thread dumps:
kill -3 <PID>
: Gives output to standard output.For hotspot VM's we can also use jstack
command to generate a thread dump. It’s a part of the JDK. Syntax is as follows:
Usage:
jstack [-l] <pid> (to connect to running process)
jstack -F [-m] [-l] <pid>(to connect to a hung process)
- For JRockit JVM we can use JRCMD command which comes with JDK Syntax:
jrcmd <jrockit pid> [<command> [<arguments>]] [-l] [-f file] [-p] -h]
Another type of solution would be to autogenerate the nginx conf files via Jinja2 templates from ansible. The advantage of this is easy deployment to a cloud environment, and easy to replicate on multiple dev machines
I think this is also a solution of this problem.
Change your document type from 'Encode in UTF-8' To 'Encode in UTF-8 without BOM'
I got resolved my problem by doing same changes.
You want to use the null-coalescing operator, which is designed for exactly this purpose.
Using it you end up with this code.
DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate ?? DateTime.Now;
You can add them like this
Route::get('company/{name}', 'PublicareaController@companydetails');
>>> a = numpy.full((2,4), True, dtype=bool)
>>> a[1][3]
True
>>> a
array([[ True, True, True, True],
[ True, True, True, True]], dtype=bool)
numpy.full(Size, Scalar Value, Type). There is other arguments as well that can be passed, for documentation on that, check https://docs.scipy.org/doc/numpy/reference/generated/numpy.full.html
The easiest way for me without having to reinvent the wheel.
void Clear()
{
#if defined _WIN32
system("cls");
//clrscr(); // including header file : conio.h
#elif defined (__LINUX__) || defined(__gnu_linux__) || defined(__linux__)
system("clear");
//std::cout<< u8"\033[2J\033[1;1H"; //Using ANSI Escape Sequences
#elif defined (__APPLE__)
system("clear");
#endif
}
#include <conio.h>
clrscr();
std::cout<< u8"\033[2J\033[1;1H";
Try the following commands to search the string inside all previous tracked files:
git log --patch | less +/searching_string
or
git rev-list --all | GIT_PAGER=cat xargs git grep 'search_string'
which needs to be run from the parent directory where you'd like to do the searching.
Try the below code:
Sub opendfiles()
Dim myfile As Variant
Dim counter As Integer
Dim path As String
myfolder = "D:\temp\"
ChDir myfolder
myfile = Application.GetOpenFilename(, , , , True)
counter = 1
If IsNumeric(myfile) = True Then
MsgBox "No files selected"
End If
While counter <= UBound(myfile)
path = myfile(counter)
Workbooks.Open path
counter = counter + 1
Wend
End Sub
I know this is an old thread, however, here is a really effective approach.
var tn = document.createTextNode("I am just to help")
t.insertData(10, "trying");
What's great about this is that it coerces the node content. So if this node were already on the DOM, you wouldn't need to use any query selectors or update the innerText. The changes would reflect due to its binding.
Were you to need a string, simply access the node's text content property.
tn.textContent
#=> "I am just trying to help"
Ctrl+P and Type "ext install cpptools" it will install everything you need to debug c and c++.
Debugging in VS code is very complete, but if you just need to compile and run: https://code.visualstudio.com/docs/languages/cpp
Look in the debugging section and it will explain everything
Setting colspan="0"
is support only in firefox.
In other browsers we can get around it with:
// Auto calculate table colspan if set to 0
var colCount = 0;
$("td[colspan='0']").each(function(){
colCount = 0;
$(this).parents("table").find('tr').eq(0).children().each(function(){
if ($(this).attr('colspan')){
colCount += +$(this).attr('colspan');
} else {
colCount++;
}
});
$(this).attr("colspan", colCount);
});