You can do it like:
change_column :table_name, :column_name, 'integer USING CAST(column_name AS integer)'
or try this:
change_column :table_name, :column_name, :integer, using: 'column_name::integer'
If you are interested to find more about this topic read this article: https://kolosek.com/rails-change-database-column
Below is working example of file upload:
http://jsfiddle.net/vishalvasani/4hqVu/
In this one function called
setFiles
From View which will update the file array in controller
or
You can check jQuery File Upload using AngularJS
Please note this doesn't solve the cookie sharing process, as in general this is bad practice.
You need to be using JSONP as your type:
From $.ajax documentation: Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.
$.ajax(
{
type: "POST",
url: "http://example.com/api/getlist.json",
dataType: 'jsonp',
xhrFields: {
withCredentials: true
},
crossDomain: true,
beforeSend: function(xhr) {
xhr.setRequestHeader("Cookie", "session=xxxyyyzzz");
},
success: function(){
alert('success');
},
error: function (xhr) {
alert(xhr.responseText);
}
}
);
Hey please add code in your project,it is easy and i think will solve your problem.
int count = 10;
private void timer1_Tick(object sender, EventArgs e)
{
count--;
if (count != 0 && count > 0)
{
label1.Text = count / 60 + ":" + ((count % 60) >= 10 ? (count % 60).ToString() : "0" + (count % 60));
}
else
{
label1.Text = "game over";
}
}
private void Form1_Load(object sender, EventArgs e)
{
timer1 = new System.Windows.Forms.Timer();
timer1.Interval = 1;
timer1.Tick += new EventHandler(timer1_Tick);
}
I often use the simplest way:
var variable;
if (variable === undefined){
console.log('Variable is undefined');
} else {
console.log('Variable is defined');
}
EDIT:
Without initializing the variable, exception will be thrown "Uncaught ReferenceError: variable is not defined..."
Simply put, casting is more efficient than creating a Double object.
As I wanted a full fledged BiDirectional Dictionary (and not only a Map), I added the missing functions to make it an IDictionary compatible class. This is based on the version with unique Key-Value Pairs. Here's the file if desired (Most work was the XMLDoc through):
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Common
{
/// <summary>Represents a bidirectional collection of keys and values.</summary>
/// <typeparam name="TFirst">The type of the keys in the dictionary</typeparam>
/// <typeparam name="TSecond">The type of the values in the dictionary</typeparam>
[System.Runtime.InteropServices.ComVisible(false)]
[System.Diagnostics.DebuggerDisplay("Count = {Count}")]
//[System.Diagnostics.DebuggerTypeProxy(typeof(System.Collections.Generic.Mscorlib_DictionaryDebugView<,>))]
//[System.Reflection.DefaultMember("Item")]
public class BiDictionary<TFirst, TSecond> : Dictionary<TFirst, TSecond>
{
IDictionary<TSecond, TFirst> _ValueKey = new Dictionary<TSecond, TFirst>();
/// <summary> PropertyAccessor for Iterator over KeyValue-Relation </summary>
public IDictionary<TFirst, TSecond> KeyValue => this;
/// <summary> PropertyAccessor for Iterator over ValueKey-Relation </summary>
public IDictionary<TSecond, TFirst> ValueKey => _ValueKey;
#region Implemented members
/// <Summary>Gets or sets the value associated with the specified key.</Summary>
/// <param name="key">The key of the value to get or set.</param>
/// <Returns>The value associated with the specified key. If the specified key is not found,
/// a get operation throws a <see cref="KeyNotFoundException"/>, and
/// a set operation creates a new element with the specified key.</Returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception>
/// <exception cref="T:System.Collections.Generic.KeyNotFoundException">
/// The property is retrieved and <paramref name="key"/> does not exist in the collection.</exception>
/// <exception cref="T:System.ArgumentException"> An element with the same key already
/// exists in the <see cref="ValueKey"/> <see cref="Dictionary<TFirst,TSecond>"/>.</exception>
public new TSecond this[TFirst key]
{
get { return base[key]; }
set { _ValueKey.Remove(base[key]); base[key] = value; _ValueKey.Add(value, key); }
}
/// <Summary>Gets or sets the key associated with the specified value.</Summary>
/// <param name="val">The value of the key to get or set.</param>
/// <Returns>The key associated with the specified value. If the specified value is not found,
/// a get operation throws a <see cref="KeyNotFoundException"/>, and
/// a set operation creates a new element with the specified value.</Returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="val"/> is null.</exception>
/// <exception cref="T:System.Collections.Generic.KeyNotFoundException">
/// The property is retrieved and <paramref name="val"/> does not exist in the collection.</exception>
/// <exception cref="T:System.ArgumentException"> An element with the same value already
/// exists in the <see cref="KeyValue"/> <see cref="Dictionary<TFirst,TSecond>"/>.</exception>
public TFirst this[TSecond val]
{
get { return _ValueKey[val]; }
set { base.Remove(_ValueKey[val]); _ValueKey[val] = value; base.Add(value, val); }
}
/// <Summary>Adds the specified key and value to the dictionary.</Summary>
/// <param name="key">The key of the element to add.</param>
/// <param name="value">The value of the element to add.</param>
/// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> or <paramref name="value"/> is null.</exception>
/// <exception cref="T:System.ArgumentException">An element with the same key or value already exists in the <see cref="Dictionary<TFirst,TSecond>"/>.</exception>
public new void Add(TFirst key, TSecond value) {
base.Add(key, value);
_ValueKey.Add(value, key);
}
/// <Summary>Removes all keys and values from the <see cref="Dictionary<TFirst,TSecond>"/>.</Summary>
public new void Clear() { base.Clear(); _ValueKey.Clear(); }
/// <Summary>Determines whether the <see cref="Dictionary<TFirst,TSecond>"/> contains the specified
/// KeyValuePair.</Summary>
/// <param name="item">The KeyValuePair to locate in the <see cref="Dictionary<TFirst,TSecond>"/>.</param>
/// <Returns>true if the <see cref="Dictionary<TFirst,TSecond>"/> contains an element with
/// the specified key which links to the specified value; otherwise, false.</Returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="item"/> is null.</exception>
public bool Contains(KeyValuePair<TFirst, TSecond> item) => base.ContainsKey(item.Key) & _ValueKey.ContainsKey(item.Value);
/// <Summary>Removes the specified KeyValuePair from the <see cref="Dictionary<TFirst,TSecond>"/>.</Summary>
/// <param name="item">The KeyValuePair to remove.</param>
/// <Returns>true if the KeyValuePair is successfully found and removed; otherwise, false. This
/// method returns false if <paramref name="item"/> is not found in the <see cref="Dictionary<TFirst,TSecond>"/>.</Returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="item"/> is null.</exception>
public bool Remove(KeyValuePair<TFirst, TSecond> item) => base.Remove(item.Key) & _ValueKey.Remove(item.Value);
/// <Summary>Removes the value with the specified key from the <see cref="Dictionary<TFirst,TSecond>"/>.</Summary>
/// <param name="key">The key of the element to remove.</param>
/// <Returns>true if the element is successfully found and removed; otherwise, false. This
/// method returns false if <paramref name="key"/> is not found in the <see cref="Dictionary<TFirst,TSecond>"/>.</Returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception>
public new bool Remove(TFirst key) => _ValueKey.Remove(base[key]) & base.Remove(key);
/// <Summary>Gets the key associated with the specified value.</Summary>
/// <param name="value">The value of the key to get.</param>
/// <param name="key">When this method returns, contains the key associated with the specified value,
/// if the value is found; otherwise, the default value for the type of the key parameter.
/// This parameter is passed uninitialized.</param>
/// <Returns>true if <see cref="ValueKey"/> contains an element with the specified value;
/// otherwise, false.</Returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="value"/> is null.</exception>
public bool TryGetValue(TSecond value, out TFirst key) => _ValueKey.TryGetValue(value, out key);
#endregion
}
}
public static byte[] hexToBin(String str)
{
int len = str.length();
byte[] out = new byte[len / 2];
int endIndx;
for (int i = 0; i < len; i = i + 2)
{
endIndx = i + 2;
if (endIndx > len)
endIndx = len - 1;
out[i / 2] = (byte) Integer.parseInt(str.substring(i, endIndx), 16);
}
return out;
}
It can also happen if your password policy or something else have changed your password in case your appPools are using the the user with changed password.
So, you should update the user password from the advanced settings of your appPool throught "Identity" property.
The reference is here
As said by Sparky in comments on many answers to this question, there is NOT any textarea
value for the type
attribute of the input
tag.
On other terms, the following markup is not valid :
<input type="textarea" />
And the browser replaces it by the default :
<input type="text" />
To define a multi-lines text input, use :
<textarea></textarea>
See the textarea element documentation for more details.
To solve this problem, github recommends Connecting over HTTPS.
Git's documentation discuss how to how to do exactly that using gitcredentials.
Solution 1
Static configuration of usernames for a given authentication context.
https://username:<personal-access-tokens>@repository-url.com
You will find the details in the documentation.
Solution 2
Use credential helpers to cache password (in memory for a short period of time).
git config --global credential.helper cache
Solution 3
Use credential helpers to store password (indefinitely on disk).
git config --global credential.helper 'store --file ~/.my-credentials'
You can find where the credential will be saved (If not set explicitly with --file) in the documentation.
If not set explicitly with --file, there are two files where git-credential-store will search for credentials in order of precedence:
~/.git-credentials
User-specific credentials file. $XDG_CONFIG_HOME/git/credentials Second user-specific credentials file. If $XDG_CONFIG_HOME is not set or empty, $HOME/.config/git/credentials will be used. Any
credentials stored in this file will not be used if ~/.git-credentials has a matching credential as well. It is a good idea not to create this file if you sometimes use older versions of Git that do not support it.
P.S.
To address the concern:
your password is going to be stored completely unencrypted ("as is") at ~/.git-credentials.
You can always encrypt the file and decrypt it before using.
Child can ask kernel to deliver SIGHUP
(or other signal) when parent dies by specifying option PR_SET_PDEATHSIG
in prctl()
syscall like this:
prctl(PR_SET_PDEATHSIG, SIGHUP);
See man 2 prctl
for details.
Edit: This is Linux-only
Pig-latin is data flow style, is more suitable for software engineer. While sql is more suitable for analytics person who are get used to sql. For complex task, for hive you have to manually to create temporary table to store intermediate data, but it is not necessary for pig.
Pig-latin is suitable for complicated data structure( like small graph). There's a data structure in pig called DataBag which is a collection of Tuple. Sometimes you need to calculate metrics which involve multiple tuples ( there's a hidden link between tuples, in this case I would call it graph). In this case, it is very easy to write a UDF to calculate the metrics which involve multiple tuples. Of course it could be done in hive, but it is not so convenient as it is in pig.
Writing UDF in pig much is easier than in Hive in my opinion.
Pig has no metadata support, (or it is optional, in future it may integrate hcatalog). Hive has tables' metadata stored in database.
You can debug pig script in local environment, but it would be hard for hive to do that. The reason is point 3. You need to set up hive metadata in your local environment, very time consuming.
I would suggest to use CSS over jquery ( if possible) otherwise you can use something like this
$("div.myclass").hover(function() {
$(this).css("background-color","red")
});
You can change your selector as per your need.
As commented by @A.Wolff, If you want to use this hover effect to multiple classes, you can use it like this
$(".myclass, .myclass2").hover(function(e) {
$(this).css("background-color",e.type === "mouseenter"?"red":"transparent")
})
In my case I want to make sure that absolutely everything in the web view opens Safari except the initial load and so I use...
- (BOOL)webView:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType {
if(inType != UIWebViewNavigationTypeOther) {
[[UIApplication sharedApplication] openURL:[inRequest URL]];
return NO;
}
return YES;
}
One option is to use Python's slicing and indexing features to logically evaluate the places where your condition holds and overwrite the data there.
Assuming you can load your data directly into pandas
with pandas.read_csv
then the following code might be helpful for you.
import pandas
df = pandas.read_csv("test.csv")
df.loc[df.ID == 103, 'FirstName'] = "Matt"
df.loc[df.ID == 103, 'LastName'] = "Jones"
As mentioned in the comments, you can also do the assignment to both columns in one shot:
df.loc[df.ID == 103, ['FirstName', 'LastName']] = 'Matt', 'Jones'
Note that you'll need pandas
version 0.11 or newer to make use of loc
for overwrite assignment operations.
Another way to do it is to use what is called chained assignment. The behavior of this is less stable and so it is not considered the best solution (it is explicitly discouraged in the docs), but it is useful to know about:
import pandas
df = pandas.read_csv("test.csv")
df['FirstName'][df.ID == 103] = "Matt"
df['LastName'][df.ID == 103] = "Jones"
$ cd Desktop
$ openssl x509 -in aps_development.cer -inform der -out PushChatCert.pem
I was successful using tidy
command line utility. On linux I installed it quickly with apt-get install tidy
. Then the command:
tidy -q -asxml --numeric-entities yes source.html >file.xml
gave an xml file, which I was able to process with xslt processor. However I needed to set up xhtml1 dtds correctly.
This is their homepage: html-tidy.org (and the legacy one: HTML Tidy)
Increasing the timeout will not likely solve your issue since, as you say, the actual target web server is responding just fine.
I had this same issue and I found it had to do with not using a keep-alive on the connection. I can't actually answer why this is but, in clearing the connection header I solved this issue and the request was proxied just fine:
server {
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $http_host;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_pass http://localhost:5000;
}
}
Have a look at this posts which explains it in more detail: nginx close upstream connection after request Keep-alive header clarification http://nginx.org/en/docs/http/ngx_http_upstream_module.html#keepalive
Use the change event of the select:
$('#my_select').change(function()
{
$(this).parents('td').css('background', '#000000');
});
// groovy
String hostname ={url -> url[(url.indexOf('://')+ 3)..-1]?.split('/')[0]? }
hostname('http://hello.world.com/something') // return 'hello.world.com'
hostname('docker://quay.io/skopeo/stable') // return 'quay.io'
Like this:
> df[df==""]<-NA
> df
A B
1 <NA> 12
2 xyz <NA>
3 jkl 100
Locate the file at /etc/mysql/my.cnf
Edit the file by adding the following lines:
[mysqld]
lower_case_table_names=1
sudo /etc/init.d/mysql restart
Run mysqladmin -u root -p variables | grep table
to check that lower_case_table_names
is 1
now
You might need to recreate these tables to make it work.
If you do android native code development using NDK, give Visual Studio a try. (Not a typo!!!) Check out: http://ian-ni-lewis.blogspot.com/2011/01/its-like-coming-home-again.html
The first question you need to ask is whether you really need the ID to be random. Sometime, sequential IDs are good enough.
Now, if you do need it to be random, we first note a generated sequence of numbers that contain no duplicates can not be called random. :p Now that we get that out of the way, the fastest way to do this is to have a Hashtable
or HashMap
containing all the IDs already generated. Whenever a new ID is generated, check it against the hashtable, re-generate if the ID already occurs. This will generally work well if the number of students is much less than the range of the IDs. If not, you're in deeper trouble as the probability of needing to regenerate an ID increases, P(generate new ID) = number_of_id_already_generated / number_of_all_possible_ids. In this case, check back the first paragraph (do you need the ID to be random?).
Hope this helps.
If you're just interested in the properties and data types from the database, you can use Model.inspect
.
irb(main):001:0> User.inspect
=> "User(id: integer, email: string, encrypted_password: string,
reset_password_token: string, reset_password_sent_at: datetime,
remember_created_at: datetime, sign_in_count: integer,
current_sign_in_at: datetime, last_sign_in_at: datetime,
current_sign_in_ip: string, last_sign_in_ip: string, created_at: datetime,
updated_at: datetime)"
Alternatively, having run rake db:create
and rake db:migrate
for your development environment, the file db/schema.rb
will contain the authoritative source for your database structure:
ActiveRecord::Schema.define(version: 20130712162401) do
create_table "users", force: true do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
end
end
Assuming you put your custom variables into a yaml file:
# config/acme.yml
development:
:api_user: 'joe'
:api_pass: 's4cret'
:timeout: 20
Create an initializer to load them:
# config/initializers/acme.rb
acme_config = Rails.application.config_for :acme
Rails.application.configure do
config.acme = ActiveSupport::OrderedOptions.new
config.acme.api_user = acme_config[:api_user]
config.acme.api_pass = acme_config[:api_pass]
config.acme.timeout = acme_config[:timeout]
end
Now anywhere in your app you can access these values like so:
Rails.configuration.acme.api_user
It is convenient that Rails.application.config_for :acme
will load your acme.yml
and use the correct environment.
If the required properties need to set in system then there is no option than -D But if you need those properties while bootstrapping an application then loading properties through the properties files is a best option. It will not require to change build for a single property.
Improving the @Derek Springer
post with fill length function:
public static String getFileWithDate(String fileName, String fileSaperator, String dateFormat) {
String FileNamePrefix = fileName.substring(0, fileName.lastIndexOf(fileSaperator));
String FileNameSuffix = fileName.substring(fileName.lastIndexOf(fileSaperator)+1, fileName.length());
//System.out.println("File= Prefix~Suffix:"+FileNamePrefix +"~"+FileNameSuffix);
String newFileName = new SimpleDateFormat("'"+FileNamePrefix+"_'"+dateFormat+"'"+fileSaperator+FileNameSuffix+"'").format(new Date());
System.out.println("New File:"+newFileName);
return newFileName;
}
Using the funciton and its Output:
String fileSaperator = ".", format = "yyyyMMMdd_HHmm";
getFileWithDate("Text1.txt", fileSaperator, format);
getFileWithDate("Text1.doc", fileSaperator, format);
getFileWithDate("Text1.txt.json", fileSaperator, format);
Output:
Old File:Text1.txt New File:Text1_2020Nov11_1807.txt
Old File:Text1.doc New File:Text1_2020Nov11_1807.doc
Old File:Text1.txt.json New File:Text1.txt_2020Nov11_1807.json
The guide by Ani Menon (thx!) almost worked for me on windows 10, i just had to get a newer winutils.exe off that git (currently hadoop-2.8.1): https://github.com/steveloughran/winutils
You have a JSON object that contains an Array. You need to access the array results
. Change your code to:
this.data = res.json().results
This difference is due to the behavior of Promises more than fetch()
specifically.
When a .then()
callback returns an additional Promise
, the next .then()
callback in the chain is essentially bound to that Promise, receiving its resolve or reject fulfillment and value.
The 2nd snippet could also have been written as:
iterator.then(response =>
response.json().then(post => document.write(post.title))
);
In both this form and yours, the value of post
is provided by the Promise returned from response.json()
.
When you return a plain Object
, though, .then()
considers that a successful result and resolves itself immediately, similar to:
iterator.then(response =>
Promise.resolve({
data: response.json(),
status: response.status
})
.then(post => document.write(post.data))
);
post
in this case is simply the Object
you created, which holds a Promise
in its data
property. The wait for that promise to be fulfilled is still incomplete.
<table style="border:2px solid #ddedde">
<tr>
<td style="border:2px solid #ddedde;width:50%">a</td>
<td style="border:2px solid #ddedde;width:20%">b</td>
<td style="border:2px solid #ddedde;width:30%">c</td>
</tr>
<tr>
<td style="border:2px solid #ddedde;width:50%">a</td>
<td style="border:2px solid #ddedde;width:20%">b</td>
<td style="border:2px solid #ddedde;width:30%">c</td>
</tr>
</table>
char members[255] = {0};
There's a very simple answer to this: Profile the performance of your web server to see what the performance penalty is for your particular situation. There are several tools out there to compare the performance of an HTTP vs HTTPS server (JMeter and Visual Studio come to mind) and they are quite easy to use.
No one can give you a meaningful answer without some information about the nature of your web site, hardware, software, and network configuration.
As others have said, there will be some level of overhead due to encryption, but it is highly dependent on:
In my experience, servers that are heavy on dynamic content tend to be impacted less by HTTPS because the time spent encrypting (SSL-overhead) is insignificant compared to content generation time.
Servers that are heavy on serving a fairly small set of static pages that can easily be cached in memory suffer from a much higher overhead (in one case, throughput was havled on an "intranet").
Edit: One point that has been brought up by several others is that SSL handshaking is the major cost of HTTPS. That is correct, which is why "typical session length" and "caching behavior of clients" are important.
Many, very short sessions means that handshaking time will overwhelm any other performance factors. Longer sessions will mean the handshaking cost will be incurred at the start of the session, but subsequent requests will have relatively low overhead.
Client caching can be done at several steps, anywhere from a large-scale proxy server down to the individual browser cache. Generally HTTPS content will not be cached in a shared cache (though a few proxy servers can exploit a man-in-the-middle type behavior to achieve this). Many browsers cache HTTPS content for the current session and often times across sessions. The impact the not-caching or less caching means clients will retrieve the same content more frequently. This results in more requests and bandwidth to service the same number of users.
Dim strFirstAddress As String
Dim searchlast As Range
Dim search As Range
Set search = ActiveSheet.Range("A1:A100")
Set searchlast = search.Cells(search.Cells.Count)
Set rngFindValue = ActiveSheet.Range("A1:A100").Find(Text, searchlast, xlValues)
If Not rngFindValue Is Nothing Then
strFirstAddress = rngFindValue.Address
Do
Set rngFindValue = search.FindNext(rngFindValue)
Loop Until rngFindValue.Address = strFirstAddress
context.getPackageManager().getInstalledApplications(PackageManager.GET_META_DATA);
Should return the list of all the installed apps but in android 11 it'll only return the list of system apps. To get the list of all the applications(system+user) we need to provide an additional permission to the application i.e
<uses-permission android:name"android.permission.QUERY_ALL_PACKAGES">
def binary(decimal) :
otherBase = ""
while decimal != 0 :
otherBase = str(decimal % 2) + otherBase
decimal //= 2
return otherBase
print binary(10)
output:
1010
Starting from Java 9, there is a new utility method allowing to create an immutable entry which is Map#entry(Object, Object)
.
Here is a simple example:
Entry<String, String> entry = Map.entry("foo", "bar");
As it is immutable, calling setValue
will throw an UnsupportedOperationException
. The other limitations are the fact that it is not serializable and null
as key or value is forbidden, if it is not acceptable for you, you will need to use AbstractMap.SimpleImmutableEntry
or AbstractMap.SimpleEntry
instead.
NB: If your need is to create directly a Map
with 0 to up to 10 (key, value) pairs, you can instead use the methods of type Map.of(K key1, V value1, ...)
.
Because your update
uses PUT method, {entryId: $scope.entryId}
is considered as data, to tell angular generate from the PUT data, you need to add params: {entryId: '@entryId'}
when you define your update
, which means
return $resource('http://localhost\\:3000/realmen/:entryId', {}, {
query: {method:'GET', params:{entryId:''}, isArray:true},
post: {method:'POST'},
update: {method:'PUT', params: {entryId: '@entryId'}},
remove: {method:'DELETE'}
});
Fix: Was missing a closing curly brace on the update line.
This will open a second cmd.exe window. If you want it to go away, replace the /K with /C.
Obviously, replace new_file_loc with whatever your new file location will be.
@echo off
for /F %%i in ('dir /B /O:-D *.txt') do (
call :open "%%i"
exit /B 0
)
:open
start "window title" "cmd /K copy %~1 new_file_loc"
exit /B 0
I found several posts telling me to run several gpg commands, but they didn't solve the problem because of two things. First, I was missing the debian-keyring package on my system and second I was using an invalid keyserver. Try different keyservers if you're getting timeouts!
Thus, the way I fixed it was:
apt-get install debian-keyring
gpg --keyserver pgp.mit.edu --recv-keys 1F41B907
gpg --armor --export 1F41B907 | apt-key add -
Then running a new "apt-get update" worked flawlessly!
If you could reload this, you might be able to use dtypes argument.
pd.read_csv(..., dtype={'COL_NAME':'str'})
I used a slightly modified version:
with open(file_name, 'w', encoding = 'utf-8') as f:
for rec_index, rec in df.iterrows():
f.write(rec['<field>'] + '\n')
I had to write the contents of a dataframe field (that was delimited) as a text file.
InnoDB works slightly different that MyISAM and they both are viable options. You should use what you think it fits the project.
Some keypoints will be:
Notes:
Notes2: - I am reading this book "High performance MySQL", the author says "InnoDB loads data and creates indexes slower than MyISAM", this could also be a very important factor when deciding what to use.
I think it needs to be checked if any row is selected or not? The below code would check it:
var entityGrid = $("#EntitesGrid").data("kendoGrid");
var selectedItem = entityGrid.dataItem(entityGrid.select());
if (selectedItem != undefined)
alert("The Row Is SELECTED");
else
alert("NO Row Is SELECTED")
This depends entirely on the JavaScript environment. Please elaborate.
For example, in Windows Scripting, you do things like:
var shell = WScript.CreateObject("WScript.Shell");
shell.Run("command here");
Update:
Separate the event and property bindings:
<select [ngModel]="selectedItem" (ngModelChange)="onChange($event)">
onChange(newValue) {
console.log(newValue);
this.selectedItem = newValue; // don't forget to update the model here
// ... do other stuff here ...
}
You could also use
<select [(ngModel)]="selectedItem" (ngModelChange)="onChange($event)">
and then you wouldn't have to update the model in the event handler, but I believe this causes two events to fire, so it is probably less efficient.
Old answer, before they fixed a bug in beta.1:
Create a local template variable and attach a (change)
event:
<select [(ngModel)]="selectedItem" #item (change)="onChange(item.value)">
See also How can I get new selection in "select" in Angular 2?
You're pretty close:
var myTag = $(':selected', element).attr("myTag");
Please try
sudo a2enmod rewrite
or use correct apache restart command
sudo /etc/init.d/apache2 restart
$this->db->select('id, name, price, author, category, language, ISBN, publish_date');
$this->db->from('tbl_books');
Following Query works for me. Database Tabel t_sonde_results has domain d_date (datatype DATE) and d_time (datatype TIME) The intention is to query for last entry in t_sonde_results sorted by Date and Time
select * from
(select * from
(SELECT * FROM t_sonde_results
WHERE d_user_name = 'kenis' and d_smartbox_id = 6 order by d_time asc) AS tmp
order by d_date and d_time limit 1) as tmp1
Take a look at Blaze-Persistence Entity Views which works on top of JPA and provides first class DTO support. You can project anything to attributes within Entity Views and it will even reuse existing join nodes for associations if possible.
Here is an example mapping
@EntityView(Order.class)
interface OrderSummary {
Integer getId();
@Mapping("SUM(orderPositions.price * orderPositions.amount * orderPositions.tax)")
BigDecimal getOrderAmount();
@Mapping("COUNT(orderPositions)")
Long getItemCount();
}
Fetching this will generate a JPQL/HQL query similar to this
SELECT
o.id,
SUM(p.price * p.amount * p.tax),
COUNT(p.id)
FROM
Order o
LEFT JOIN
o.orderPositions p
GROUP BY
o.id
Here is a blog post about custom subquery providers which might be interesting to you as well: https://blazebit.com/blog/2017/entity-view-mapping-subqueries.html
I'm in a module environnement where all are core-dependents using gulp.
So, the core
module needs to be appended before the others.
What I did:
src
foldergulp-rename
your core
directory to _core
gulp is keeping the order of your gulp.src
, my concat src
looks like this:
concat: ['./client/src/js/*.js', './client/src/js/**/*.js', './client/src/js/**/**/*.js']
It'll obviously take the _
as the first directory from the list (natural sort?).
Note (angularjs):
I then use gulp-angular-extender to dynamically add the modules to the core
module.
Compiled it looks like this:
angular.module('Core', ["ui.router","mm.foundation",(...),"Admin","Products"])
Where Admin and Products are two modules.
you use the scrollTop attribute
var position = document.getElementById('id').scrollTop;
int32
and time.Duration
are different types. You need to convert the int32
to a time.Duration
, such as time.Sleep(time.Duration(rand.Int31n(1000)) * time.Millisecond)
.
I was facing the same issue earlier but I have somehow found the solution,
You can try reg.predict([[3300]])
.
The API used to allow scalar value but now you need to give a 2D array.
Try the command FLUSH PRIVILEGES
when you log into the MySQL terminal. If that doesn't work, try the following set of commands while in the MySQL terminal
$ mysql -u root
mysql> USE mysql;
mysql> UPDATE user SET password=PASSWORD("NEWPASSWORD") WHERE User='root';
mysql> FLUSH PRIVILEGES;
mysql> quit
Change out NEWPASSWORD with whatever password you want. Should be all set!
Update: As of MySQL 5.7, the password
field has been renamed authentication_string
. When changing the password, use the following query to change the password. All other commands remain the same:
mysql> UPDATE user SET authentication_string=PASSWORD("NEWPASSWORD") WHERE User='root';
Update: On 8.0.15 (maybe already before that version) the PASSWORD() function does not work, as mentioned in the comments below. You have to use:
UPDATE mysql.user SET authentication_string='password' WHERE User='root';
Using background-size cover worked for me.
#footer {
background-color: #eee;
background-image: url(images/bodybgbottomleft.png);
background-repeat: no-repeat;
background-size: cover;
clear: both;
width: 100%;
margin: 0;
padding: 30px 0 0;
}
Obviously be aware of support issues, check Can I Use: http://caniuse.com/#search=background-size
In order to import your .sql try the following steps
I had given permissions I shouldn't have to write in some folders (especially /usr/bin/), and that caused the problem. I fixed it by opening Disk Utility and running 'Repair Disk Permissions' on the Macintosh HD disk.
I use Notepad++ and got this error.
In Notepad++ you will see that both the tab and the four spaces are the same, but when you copy your code to Python IDLE you would see the difference and the line with a tab would have more space before it than the others.
To solve the problem, I just deleted the tab before the line then added four spaces.
A more general approach:
if ( ($("body").hasClass("homepage") || $("body").hasClass("contact")) && (theLanguage == 'en-gb') ) {
// Do something
}
Look for exceptions being thrown and caught in the ...
sections of your code. Runtime and rollbacking application exceptions cause rollback when thrown out of a business method even if caught on some other place.
You can use context to find out whether the transaction is marked for rollback.
@Resource
private SessionContext context;
context.getRollbackOnly();
Also you can use
<select ng-change="updateValue(user, oldValue)"
ng-init="oldValue=0"
ng-focus="oldValue=user.id"
ng-model="user.id" ng-options="user.id as user.name for user in users">
</select>
You can directly call the
method and pass your list as parameter.
l = ['Thanks You','Its fine no problem','Are you sure']
pd.DataFrame(l)
Output:
0
0 Thanks You
1 Its fine no problem
2 Are you sure
And if you have multiple lists and you want to make a dataframe out of it.You can do it as following:
import pandas as pd
names =["A","B","C","D"]
salary =[50000,90000,41000,62000]
age = [24,24,23,25]
data = pd.DataFrame([names,salary,age]) #Each list would be added as a row
data = data.transpose() #To Transpose and make each rows as columns
data.columns=['Names','Salary','Age'] #Rename the columns
data.head()
Output:
Names Salary Age
0 A 50000 24
1 B 90000 24
2 C 41000 23
3 D 62000 25
you can integrate to LDAP or AD as well. It works well.
As suggested by @Joel and @Mark Chorley in earlier comments:
${empty companies}
This checks for null and empty lists/collections/arrays. It doesn't get you the length but it satisfies the example in the OP. If you can get away with it this is just cleaner than importing a tag library and its crusty syntax like gt
.
I had to do this for a modern windows app. I used the following:
public static class UriExtensions
{
private static readonly Regex _regex = new Regex(@"[?&](\w[\w.]*)=([^?&]+)");
public static IReadOnlyDictionary<string, string> ParseQueryString(this Uri uri)
{
var match = _regex.Match(uri.PathAndQuery);
var paramaters = new Dictionary<string, string>();
while (match.Success)
{
paramaters.Add(match.Groups[1].Value, match.Groups[2].Value);
match = match.NextMatch();
}
return paramaters;
}
}
If you run the above as they are, they will appear to run simultaenously.
Here's some test code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
$(function () {
$('#first').animate({ width: 200 }, 200);
$('#second').animate({ width: 600 }, 200);
});
</script>
<div id="first" style="border:1px solid black; height:50px; width:50px"></div>
<div id="second" style="border:1px solid black; height:50px; width:50px"></div>
You cannot return two values, but you can return a tuple
or a list
and unpack it after the call:
def select_choice():
...
return i, card # or [i, card]
my_i, my_card = select_choice()
On line return i, card
i, card
means creating a tuple. You can also use parenthesis like return (i, card)
, but tuples are created by comma, so parens are not mandatory. But you can use parens to make your code more readable or to split the tuple over multiple lines. The same applies to line my_i, my_card = select_choice()
.
If you want to return more than two values, consider using a named tuple. It will allow the caller of the function to access fields of the returned value by name, which is more readable. You can still access items of the tuple by index. For example in Schema.loads
method Marshmallow framework returns a UnmarshalResult
which is a namedtuple
. So you can do:
data, errors = MySchema.loads(request.json())
if errors:
...
or
result = MySchema.loads(request.json())
if result.errors:
...
else:
# use `result.data`
In other cases you may return a dict
from your function:
def select_choice():
...
return {'i': i, 'card': card, 'other_field': other_field, ...}
But you might want consider to return an instance of a utility class, which wraps your data:
class ChoiceData():
def __init__(self, i, card, other_field, ...):
# you can put here some validation logic
self.i = i
self.card = card
self.other_field = other_field
...
def select_choice():
...
return ChoiceData(i, card, other_field, ...)
choice_data = select_choice()
print(choice_data.i, choice_data.card)
<?php
$args = array(
'post_type' => 'product',
'posts_per_page' => 10,
'product_cat' => 'hoodies'
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
echo '<br /><a href="'.get_permalink().'">' . woocommerce_get_product_thumbnail().' '.get_the_title().'</a>';
endwhile;
wp_reset_query();
?>
This will list all product thumbnails and names along with their links to product page. change the category name and posts_per_page as per your requirement.
Hello I have only a MINOR classname edit, and so far this is how iv divulged it. i think i need to pass in multpile parameters to the helper,
server.js
app.engine('handlebars', ViewEngine({
"helpers":{
isActive: (val, options)=>{
if (val === 3 || val === 0){
return options.fn(this)
}
}
}
}));
header.handlebars
<ul class="navlist">
<li class="navitem navlink {{#isActive 0}}active{{/isActive}}"
><a href="#">Home</a></li>
<li class="navitem navlink {{#isActive 1}}active{{/isActive}}"
><a href="#">Trending</a></li>
<li class="navitem navlink {{#isActive 2}}active{{/isActive}}"
><a href="#">People</a></li>
<li class="navitem navlink {{#isActive 3}}active{{/isActive}}"
><a href="#">Mystery</a></li>
<li class="navitem navbar-search">
<input type="text" id="navbar-search-input" placeholder="Search...">
<button type="button" id="navbar-search-button"><i class="fas fa-search"></i></button>
</li>
</ul>
I assume you're trying to tunnel into some unix box.
Make sure X11 forwarding is enabled in your PuTTY settings.
I think NSDecimalNumber will do it:
Example:
NSNumber *theNumber = [NSDecimalNumber decimalNumberWithString:[stringVariable text]]];
NSDecimalNumber is a subclass of NSNumber, so implicit casting allowed.
Try this
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
// do some work
}
"Upstream" would refer to the main repo that other people will be pulling from, e.g. your GitHub repo. The -u option automatically sets that upstream for you, linking your repo to a central one. That way, in the future, Git "knows" where you want to push to and where you want to pull from, so you can use git pull
or git push
without arguments. A little bit down, this article explains and demonstrates this concept.
Why has no one mentioned glob
? glob
lets you use Unix-style pathname expansion, and is my go to function for almost everything that needs to find more than one path name. It makes it very easy:
from glob import glob
paths = glob('*/')
Note that glob
will return the directory with the final slash (as unix would) while most path
based solutions will omit the final slash.
Just use resize: none
textarea {
resize: none;
}
You can also decide to resize your textareas only horizontal or vertical, this way:
textarea { resize: vertical; }
textarea { resize: horizontal; }
Finally,
resize: both
enables the resize grabber.
You can also used below code
<html>
<head>
<style>
.labelClass{
float: left;
width: 113px;
}
</style>
</head>
<body>
<form action="yourclassName.jsp">
<span class="labelClass">First name: </span><input type="text" name="fname"><br>
<span class="labelClass">Last name: </span><input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Since the method NetworkInfo.isConnected() is now deprecated in API-23, here is a method which detects if the Wi-Fi adapter is on and also connected to an access point using WifiManager instead:
private boolean checkWifiOnAndConnected() {
WifiManager wifiMgr = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (wifiMgr.isWifiEnabled()) { // Wi-Fi adapter is ON
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
if( wifiInfo.getNetworkId() == -1 ){
return false; // Not connected to an access point
}
return true; // Connected to an access point
}
else {
return false; // Wi-Fi adapter is OFF
}
}
.dex file
Compiled Android application code file.
Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped into a single .apk file on the device. .dex files can be created automatically by Android, by translating the compiled applications written in the Java programming language.
Behavior from some of the properties of UINavigationBar
has changed from iOS 7. You can see in the image shown below :
Two beautiful links I'd like to share with you. For more details you can go through these links :
Apple Documentation for barTintColor says :
This color is made translucent by default unless you set the translucent property to NO.
Sample Code :
self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
[self.navigationController.navigationBar
setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
self.navigationController.navigationBar.translucent = NO;
On iOS there is the switch UI component instead of a checkbox, look into the UISwitch
class.
The property on
(boolean) can be used to determine the state of the slider and about the saving of its state: That depends on how you save your other stuff already, its just saving a boolean value.
Install autoenv either by
$ pip install autoenv
(or)
$ brew install autoenv
And then create .env
file in your virtualenv project folder
$ echo "source bin/activate" > .env
Now everything works fine.
I would suggest you take a look at Modernizr. Its a small light weight library that you can asynchronously load your javascript with features that allow you to check if the file is loaded and execute the script in the other you specify.
Here is an example of loading jquery:
Modernizr.load([
{
load: '//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js',
complete: function () {
if ( !window.jQuery ) {
Modernizr.load('js/libs/jquery-1.6.1.min.js');
}
}
},
{
// This will wait for the fallback to load and
// execute if it needs to.
load: 'needs-jQuery.js'
}
]);
You can encapsulate this quite nicely in a func similar to what is below.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
fmt.Println(prompt())
}
func prompt(params ...string) string {
prompt := ": "
if len(params) > 0 {
prompt = params[0]
}
reader := bufio.NewReader(os.Stdin)
fmt.Print(prompt)
text, _ := reader.ReadString('\n')
return text
}
In this example, the prompt by default has a colon and a space in front of it . . .
:
. . . however you can override that by supplying a parameter to the prompt function.
prompt("Input here -> ")
This will result in a prompt like below.
Input here ->
Unity supports:
1. UnityScript(Is known as Javascript but includes more functionality for the Unity game engine. I think this could be very easy to learn)
2. Boo (No experience)
3. C# (I prefer this as it is useful to learn and you will be able to use this outside of unity as well. I also think it is easy to get used to)
If you need a Win 10 UWP compatible variant:
using DomXmlDocument = Windows.Data.Xml.Dom.XmlDocument;
public static class DocumentExtensions
{
public static XmlDocument ToXmlDocument(this XDocument xDocument)
{
var xmlDocument = new XmlDocument();
using (var xmlReader = xDocument.CreateReader())
{
xmlDocument.Load(xmlReader);
}
return xmlDocument;
}
public static DomXmlDocument ToDomXmlDocument(this XDocument xDocument)
{
var xmlDocument = new DomXmlDocument();
using (var xmlReader = xDocument.CreateReader())
{
xmlDocument.LoadXml(xmlReader.ReadOuterXml());
}
return xmlDocument;
}
public static XDocument ToXDocument(this XmlDocument xmlDocument)
{
using (var memStream = new MemoryStream())
{
using (var w = XmlWriter.Create(memStream))
{
xmlDocument.WriteContentTo(w);
}
memStream.Seek(0, SeekOrigin.Begin);
using (var r = XmlReader.Create(memStream))
{
return XDocument.Load(r);
}
}
}
public static XDocument ToXDocument(this DomXmlDocument xmlDocument)
{
using (var memStream = new MemoryStream())
{
using (var w = XmlWriter.Create(memStream))
{
w.WriteRaw(xmlDocument.GetXml());
}
memStream.Seek(0, SeekOrigin.Begin);
using (var r = XmlReader.Create(memStream))
{
return XDocument.Load(r);
}
}
}
}
I like to use:
(strlen(string) + 1 ) * sizeof(char)
This will give you the buffer size in bytes. You can use this with snprintf() may help:
const char* message = "%s, World!";
char* string = (char*)malloc((strlen(message)+1))*sizeof(char));
snprintf(string, (strlen(message)+1))*sizeof(char), message, "Hello");
Cheers! Function: size_t strlen (const char *s)
I know it's for a long time ago but you (or any other new comers) can resolve this issue by
Here's a trick I found to compare two branches and show how many commits each branch is ahead of the other (a more general answer on your question 1):
For local branches:
git rev-list --left-right --count master...test-branch
For remote branches:
git rev-list --left-right --count origin/master...origin/test-branch
This gives output like the following:
1 7
This output means: "Compared to master
, test-branch
is 7 commits ahead and 1 commit behind."
You can also compare local branches with remote branches, e.g. origin/master...master
to find out how many commits the local master
branch is ahead/behind its remote counterpart.
I found that along with setting the -p port values, Docker for Windows uses vpnkit and inbound traffic for it was disabled by default on my host machine's firewall. After enabling the inbound TCP rules for vpnkit I was able to access my containers from other machines on the local network.
In Oracle PL/SQL, if you are running a query that may return multiple rows, you need a cursor to iterate over the results. The simplest way is with a for loop, e.g.:
declare
myname varchar2(20) := 'tom';
begin
for result_cursor in (select * from mytable where first_name = myname) loop
dbms_output.put_line(result_cursor.first_name);
dbms_output.put_line(result_cursor.other_field);
end loop;
end;
If you have a query that returns exactly one row, then you can use the select...into...
syntax, e.g.:
declare
myname varchar2(20);
begin
select first_name into myname
from mytable
where person_id = 123;
end;
Here is some C code that produces the above mentioned error:
int main(int argc, char **argv) {
exit(1);
}
Compiled like this on Fedora 17 Linux 64 bit with gcc:
el@defiant ~/foo2 $ gcc -o n n2.c
n2.c: In function ‘main’:
n2.c:2:3: warning: incompatible implicit declaration of built-in
function ‘exit’ [enabled by default]
el@defiant ~/foo2 $ ./n
el@defiant ~/foo2 $
To make the warning go away, add this declaration to the top of the file:
#include <stdlib.h>
set -x
is fine, but if you do something like:
set -x;
command;
set +x;
it would result in printing
+ command
+ set +x;
You can use a subshell to prevent that such as:
(set -x; command)
which would just print the command.
Powershell solution for windows git, find the largest files:
git ls-tree -r -t -l --full-name HEAD | Where-Object {
$_ -match '(.+)\s+(.+)\s+(.+)\s+(\d+)\s+(.*)'
} | ForEach-Object {
New-Object -Type PSObject -Property @{
'col1' = $matches[1]
'col2' = $matches[2]
'col3' = $matches[3]
'Size' = [int]$matches[4]
'path' = $matches[5]
}
} | sort -Property Size -Top 10 -Descending
I can't leave this question in this state with that final code in the question hanging over me...
dan: here's a much neater and shorter version of your code. It would be a good idea to look at how this is done and code more this way in future. I realise you probably have no further need of this code, but learning how you should do it is a good idea. Some things to note:
There are only two comments - and even the second is not really necessary for someone familiar with Python, they'll realise NL is being stripped. Only write comments where it adds value.
The with
statement (recommended in another answer) removes the bother of closing the file through the context handler.
Use a dictionary instead of two lists.
A generator comprehension ((x for y in z)
) is used to do the translation in one line.
Wrap as little code as you can in a try
/except
block to reduce the probability of catching an exception you didn't mean to.
Use the input()
argument rather than print()
ing first - Use '\n'
to get the new line you want.
Don't write code across multiple lines or with intermediate variables like this just for the sake of it:
a = a.b()
a = a.c()
b = a.x()
c = b.y()
Instead, write these constructs like this, chaining the calls as is perfectly valid:
a = a.b().c()
c = a.x().y()
code = {}
with open('morseCode.txt', 'r') as morse_code_file:
# line format is <letter>:<morse code translation>
for line in morse_code_file:
line = line.rstrip() # Remove NL
code[line[0]] = line[2:]
user_input = input("Enter a string to convert to morse code or press <enter> to quit\n")
while user_input:
try:
print(''.join(code[x] for x in user_input.replace(' ', '').upper()))
except KeyError:
print("Error in input. Only alphanumeric characters, a comma, and period allowed")
user_input = input("Try again or press <enter> to quit\n")
It seams you need to versionate, so when some change happens browser will catch something new and user won't need to clear browser's cache.
You can do it by subfolders (example /css/v1/style.css)
or by filename (example: css/style_v1.css)
or even by setting different folders for your website, example:
www.mywebsite.com/site1
www.mywebsite.com/site2
www.mywebsite.com/site3
And use a .htaccess or even change httpd.conf to redirect to your current application.
If's about one image or page:
<?$time = date("H:i:s");?>
<img src="myfile.jpg?time=<?$time;?>">
You can use $time on parts when you don't wanna cache. So it will always pull a new image. Versionate it seams a better approach, otherwise it can overload your server. Remember, browser's cache it's not only good to user experience, but also for your server.
If are you working with numbers a lot, you might want to take a look at NumPy. It lets you perform all kinds of operation directly on numerical arrays. For example:
>>> import numpy
>>> array = numpy.array([49, 51, 53, 56])
>>> array - 13
array([36, 38, 40, 43])
Try to add Space widget after adding view like this:
layout.addView(view)
val space = Space(context)
space.minimumHeight = spaceInterval
layout.addView(space)
See this page for the solution! https://msdn.microsoft.com/en-us/library/7aw8zc76(v=vs.110).aspx
I was able to implement the Child
form inside the parent.
In the Example below Form2
should change to the name of your child form.
NewMDIChild.MdiParent=me
is the main form since the control that opens (shows) the child form is the parent or Me
.
NewMDIChild.Show()
is your child form since you associated your child form with Dim NewMDIChild As New Form2()
Protected Sub MDIChildNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem2.Click
Dim NewMDIChild As New Form2()
'Set the Parent Form of the Child window.
NewMDIChild.MdiParent = Me
'Display the new form.
NewMDIChild.Show()
End Sub
Simple and it works.
In addition to Eric Leschinski's answer, and because this is stackoverflow, a programmatical solution:
Windows uses hidden file forks to mark content as "downloaded". Truncating these unblocks the file. The name of the stream used for CHM's is "Zone.Identifier". One can access streams by appending :streamname when opening the file. (keep backups the first time, in case your RTL messes that up!)
In Delphi it would look like this:
var f : file;
begin
writeln('unblocking ',s);
assignfile(f,'some.chm:Zone.Identifier');
rewrite(f,1);
truncate(f);
closefile(f);
end;
I'm told that on non forked filesystems (like FAT32) there are hidden files, but I haven't gotten to the bottom of that yet.
P.s. Delphi's DeleteFile() should also recognize forks.
I like the idea of redefining existing tags if they're unused due to the fact that the text is cleaner, at the expense of existing tags. The inline styling works but creates a lot of noise when reading the raw text.
Using VSCode I've found that custom single-letter tags, supported by a small <style>
section at the top, works well with a minimum of noise, especially for spot colour, e.g.
<style>
r { color: Red }
o { color: Orange }
g { color: Green }
</style>
# TODOs:
- <r>TODO:</r> Important thing to do
- <o>TODO:</o> Less important thing to do
- <g>DONE:</g> Breath deeply and improve karma
My use-case is orgmode-ish in-app note taking during development but I guess it might work elsewhere?
I extended @Ben Lesh's answer with an ability to specify whether the validation is case sensitive or not (default)
use:
<input type="text" name="fruitName" ng-model="data.fruitName" blacklist="Coconuts,Bananas,Pears" caseSensitive="true" required/>
code:
angular.module('crm.directives', []).
directive('blacklist', [
function () {
return {
restrict: 'A',
require: 'ngModel',
scope: {
'blacklist': '=',
},
link: function ($scope, $elem, $attrs, modelCtrl) {
var check = function (value) {
if (!$attrs.casesensitive) {
value = (value && value.toUpperCase) ? value.toUpperCase() : value;
$scope.blacklist = _.map($scope.blacklist, function (item) {
return (item.toUpperCase) ? item.toUpperCase() : item
})
}
return !_.isArray($scope.blacklist) || $scope.blacklist.indexOf(value) === -1;
}
//For DOM -> model validation
modelCtrl.$parsers.unshift(function (value) {
var valid = check(value);
modelCtrl.$setValidity('blacklist', valid);
return value;
});
//For model -> DOM validation
modelCtrl.$formatters.unshift(function (value) {
modelCtrl.$setValidity('blacklist', check(value));
return value;
});
}
};
}
]);
From the MDN documentation:
[The margin property] applies to all elements except elements with table display types other than table-caption, table and inline-table
In other words, the margin
property is not applicable to display:table-cell
elements.
Consider using the border-spacing
property instead.
Note it should be applied to a parent element with a display:table
layout and border-collapse:separate
.
For example:
HTML
<div class="table">
<div class="row">
<div class="cell">123</div>
<div class="cell">456</div>
<div class="cell">879</div>
</div>
</div>
CSS
.table {display:table;border-collapse:separate;border-spacing:5px;}
.row {display:table-row;}
.cell {display:table-cell;padding:5px;border:1px solid black;}
Different margin horizontally and vertically
As mentioned by Diego Quirós, the border-spacing
property also accepts two values to set a different margin for the horizontal and vertical axes.
For example
.table {/*...*/border-spacing:3px 5px;} /* 3px horizontally, 5px vertically */
You can also use the code below, if you do not want to get IndexError when the list is empty.
next(reversed(some_list), None)
I have one generic log4j.xml file for you:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration debug="false">
<appender name="default.console" class="org.apache.log4j.ConsoleAppender">
<param name="target" value="System.out" />
<param name="threshold" value="debug" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
</layout>
</appender>
<appender name="default.file" class="org.apache.log4j.FileAppender">
<param name="file" value="/log/mylogfile.log" />
<param name="append" value="false" />
<param name="threshold" value="debug" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
</layout>
</appender>
<appender name="another.file" class="org.apache.log4j.FileAppender">
<param name="file" value="/log/anotherlogfile.log" />
<param name="append" value="false" />
<param name="threshold" value="debug" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
</layout>
</appender>
<logger name="com.yourcompany.SomeClass" additivity="false">
<level value="debug" />
<appender-ref ref="another.file" />
</logger>
<root>
<priority value="info" />
<appender-ref ref="default.console" />
<appender-ref ref="default.file" />
</root>
</log4j:configuration>
with one console, two file appender and one logger poiting to the second file appender instead of the first.
EDIT
In one of the older projects I have found a simple log4j.properties file:
# For the general syntax of property based configuration files see
# the documentation of org.apache.log4j.PropertyConfigurator.
# The root category uses two appenders: default.out and default.file.
# The first one gathers all log output, the latter only starting with
# the priority INFO.
# The root priority is DEBUG, so that all classes can be logged unless
# defined otherwise in more specific properties.
log4j.rootLogger=DEBUG, default.out, default.file
# System.out.println appender for all classes
log4j.appender.default.out=org.apache.log4j.ConsoleAppender
log4j.appender.default.out.threshold=DEBUG
log4j.appender.default.out.layout=org.apache.log4j.PatternLayout
log4j.appender.default.out.layout.ConversionPattern=%-5p %c: %m%n
log4j.appender.default.file=org.apache.log4j.FileAppender
log4j.appender.default.file.append=true
log4j.appender.default.file.file=/log/mylogfile.log
log4j.appender.default.file.threshold=INFO
log4j.appender.default.file.layout=org.apache.log4j.PatternLayout
log4j.appender.default.file.layout.ConversionPattern=%-5p %c: %m%n
For the description of all the layout arguments look here: log4j PatternLayout arguments
This works (I feel so idiotic):
C:\Windows\System32\cmd.exe /C runas /savecred /user:OtherUser DebugTarget.Exe
The above command will ask for your password everytime, so for less frustration, you can use /savecred. You get asked only once. (but works only for Home Edition and Starter, I think)
The official mongo
image has merged a PR to include the functionality to databases and admin users at startup.
The database initialisation will run scripts in /docker-entrypoint-initdb.d/
when there is nothing populated in the /data/db
directory.
The mongo
container image provides the /docker-entrypoint-initdb.d/
path to deploy custom .js
or .sh
setup scripts that will be run once on database initialisation. .js
scripts will be run against test
by default or MONGO_INITDB_DATABASE
if defined in the environment.
COPY mysetup.sh /docker-entrypoint-initdb.d/
or
COPY mysetup.js /docker-entrypoint-initdb.d/
A simple initialisation mongo shell javascript file that demonstrates setting up the container
collection with data, logging and how to exit with an error (for result checking).
let error = true
let res = [
db.container.drop(),
db.container.createIndex({ myfield: 1 }, { unique: true }),
db.container.createIndex({ thatfield: 1 }),
db.container.createIndex({ thatfield: 1 }),
db.container.insert({ myfield: 'hello', thatfield: 'testing' }),
db.container.insert({ myfield: 'hello2', thatfield: 'testing' }),
db.container.insert({ myfield: 'hello3', thatfield: 'testing' }),
db.container.insert({ myfield: 'hello3', thatfield: 'testing' })
]
printjson(res)
if (error) {
print('Error, exiting')
quit(1)
}
The environment variables to control "root" user setup are
MONGO_INITDB_ROOT_USERNAME
MONGO_INITDB_ROOT_PASSWORD
Example
docker run -d \
-e MONGO_INITDB_ROOT_USERNAME=admin \
-e MONGO_INITDB_ROOT_PASSWORD=password \
mongod
or Dockerfile
FROM docker.io/mongo
ENV MONGO_INITDB_ROOT_USERNAME admin
ENV MONGO_INITDB_ROOT_PASSWORD password
You don't need to use --auth
on the command line as the docker entrypoint.sh
script adds this in when it detects the environment variables exist.
If you're talking about finding the latest and greatest commit after you've performed a git checkout of some earlier commit (and forgot to write down HEAD's hash prior to executing the checkout) most of the above won't get you back to where you started. git log -[some #] only shows the log from the CURRENT position of HEAD, which is not necessarily the very last commit (state of the project). Checkout will disconnect the HEAD and point it to whatever you checked out.
You could view the entire git reflog, until reaching the entry referencing the original clone. BTW, this too won't work if any commits were made between the time you cloned the project and when you performed a checkout. Otherwise you can hope all your commits on your local machine are on the server, and then re-clone the entire project.
Hope this helps.
I replaced the original code with import { Observable, of } from 'rxjs'
, and the problem is solved.
//assuming you have a map called 'map'
var infowindow = new google.maps.InfoWindow();
var latlng1 = new google.maps.LatLng(0,0);
var marker1 = new google.maps.Marker({position:latlng1, map:map});
google.maps.event.addListener(marker1, 'click',
function(){
infowindow.close();//hide the infowindow
infowindow.setContent('Marker #1');//update the content for this marker
infowindow.open(map, marker1);//"move" the info window to the clicked marker and open it
}
);
var latlng2 = new google.maps.LatLng(10,10);
var marker2 = new google.maps.Marker({position:latlng2, map:map});
google.maps.event.addListener(marker2, 'click',
function(){
infowindow.close();//hide the infowindow
infowindow.setContent('Marker #2');//update the content for this marker
infowindow.open(map, marker2);//"move" the info window to the clicked marker and open it
}
);
This will "move" the info window around to each clicked marker, in effect closing itself, then reopening (and panning to fit the viewport) in its new location. It changes its contents before opening to give the desired effect. Works for n markers.
Use System.Windows.Forms.Timer.
private Timer timer1;
public void InitTimer()
{
timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 2000; // in miliseconds
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
isonline();
}
You can call InitTimer()
in Form1_Load()
.
i know this question is old, but hopefully it will help someone.
i found a great plugin for those who are using PyCharm IDE:
string-manipulation
that can easily escape double quotes (and many more...), this plugin is great for cases where you know what the string going to be.
for other cases, using json.dumps(string)
will be the recommended solution
str_to_escape = 'my string with "double quotes" blablabla'
after_escape = 'my string with \"double quotes\" blablabla'
Using a predicate like 1=1
is a normal hint sometimes used to force the access plan to use or not use an index scan. The reason why this is used is when you are using a multi-nested joined query with many predicates in the where clause where sometimes even using all of the indexes causes the access plan to read each table - a full table scan. This is just 1 of many hints used by DBAs to trick a dbms into using a more efficient path. Just don't throw one in; you need a dba to analyze the query since it doesn't always work.
As mentioned above, you can change the property of the textbox "Read Only" to "True" from the properties window.
I always use join
on indices:
import pandas as pd
left = pd.DataFrame({'key': ['foo', 'bar'], 'val': [1, 2]}).set_index('key')
right = pd.DataFrame({'key': ['foo', 'bar'], 'val': [4, 5]}).set_index('key')
left.join(right, lsuffix='_l', rsuffix='_r')
val_l val_r
key
foo 1 4
bar 2 5
The same functionality can be had by using merge
on the columns follows:
left = pd.DataFrame({'key': ['foo', 'bar'], 'val': [1, 2]})
right = pd.DataFrame({'key': ['foo', 'bar'], 'val': [4, 5]})
left.merge(right, on=('key'), suffixes=('_l', '_r'))
key val_l val_r
0 foo 1 4
1 bar 2 5
go to canvas page.. view it in browser.. copy the address bar text. now go to your facebook app go to edit settings
in website, in site url paste that address
in facebook integration , again paste the that address in canvas url
and also the same code wherever you require canvas url or redirect url..
hope it will help..
Try $.param
$.post("page.php",( $('#myForm').serialize()+'&'+$.param({ 'wordlist': wordlist })));
Here's the 3 best ways of doing this.
Method One:
$x = '+3';
echo "1+2$x";
Double Quotes (") allows you to just pass the variable directly inside it.
Method Two:
$x = '+3';
echo '1+2'.$x;
When you don't want to use double quotes for whatever reason go with this. The (.) simply means "Add" basically. So if you were to want to add something like, 1+2+3+4+5 and have your variable in the middle all you need to do is:
$x = '+3';
echo '1+2'.$x.'+4+5';
Method 3: (Adding a variable directly inside the called variable)
$x = '+3';
$y = '+4';
$z = '+5';
echo "1+2${"x".$y.$z}";
Output: 1+2+3+4+5
Here we are adding $y
and $z
to $x
using the "."
; The {}
prioritize's the work inside it before rendering the undefined
variable.
This personally is a very useful function for calling functions like:
//Add the Get request to a variable.
$x = $_GET['tool'];
//Edit: If you want this if to contain multiple $xresult's change the if's
//Conditon in the "()" to isset($get). Simple. Now just add $xresultprogram
//or whatever.
if($x == 'app') {
$xresultapp = 'User requested tool: App';
}
//Somewhere down far in HTML maybe...
echo ${"xresult".$x}; // so this outputs: $xresultapp's value
//Note: doing ${"xresult".$_GET['tool']} directly wont work.
//I believe this is because since some direct non-echo html was loaded
//before we got to this php section it cant load cause it has already
//Started loading client side HTML and JS.
This would output $xresultapp
's 'User requested tool: App' if the url query is: example.com?tool=app
. You can modify with an else statement to define what happens when some value other than 'app' is requested. Remember, everything is case-sensitive so if they request 'App' in capitals it won't output $xresultapp
.
a:not([href]) { cursor: pointer; }
Swift 5
Add these protocols
- `UICollectionViewDelegate`
- `UICollectionViewDataSource`
- `UICollectionViewDelegateFlowLayout`
Your code will then look like this
extension YourViewController: UICollectionViewDelegate {
//Write Delegate Code Here
}
extension YourViewController: UICollectionViewDataSource {
//Write DataSource Code Here
}
extension YourViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: screenWidth, height: screenWidth)
}
}
Now the final and crucial step to see this take effect is to go to your viedDidLoad function inside your Viewcontroller.
override func viewDidLoad() {
super.viewDidLoad()
collection.dataSource = self // Add this
collection.delegate = self // Add this
// Do any additional setup after loading the view.
}
Without telling your view which class the delegate is it won't work.
Something like this?
if so, type the HTML ✔
And ✓
gives a lighter one:
✓
I know that we are (n-1) * (n times), but why the division by 2?
It's only (n - 1) * n
if you use a naive bubblesort. You can get a significant savings if you notice the following:
After each compare-and-swap, the largest element you've encountered will be in the last spot you were at.
After the first pass, the largest element will be in the last position; after the kth pass, the kth largest element will be in the kth last position.
Thus you don't have to sort the whole thing every time: you only need to sort n - 2 elements the second time through, n - 3 elements the third time, and so on. That means that the total number of compare/swaps you have to do is (n - 1) + (n - 2) + ...
. This is an arithmetic series, and the equation for the total number of times is (n - 1)*n / 2.
Example: if the size of the list is N = 5, then you do 4 + 3 + 2 + 1 = 10 swaps -- and notice that 10 is the same as 4 * 5 / 2.
In C, if time efficiency is crucial and integer overflows will wrap, one could do if ((unsigned)(value-min) <= (max-min)) ...
. If 'max' and 'min' are independent variables, the extra subtraction for (max-min) will waste time, but if that expression can be precomputed at compile time, or if it can be computed once at run-time to test many numbers against the same range, the above expression may be computed efficiently even in the case where the value is within range (if a large fraction of values will be below the valid range, it may be faster to use if ((value >= min) && (value <= max)) ...
because it will exit early if value is less than min).
Before using an implementation like that, though, benchmark one one's target machine. On some processors, the two-part expression may be faster in all cases since the two comparisons may be done independently whereas in the subtract-and-compare method the subtraction has to complete before the compare can execute.
Found method to see your own html file (from here (scroll down to answer from prac): https://productforums.google.com/forum/#!topic/drive/YY_fou2vo0A)
-- use Get Link to get URL with id=... substring -- put uc instead of open in URL
you can just do $scope.todo = Todo.get({ id: 123 })
. .get()
and .query()
on a Resource return an object immediately and fill it with the result of the promise later (to update your template). It's not a typical promise which is why you need to either use a callback or the $promise property if you have some special code you want executed after the call. But there is no need to assign it to your scope in a callback if you are only using it in the template.
In MacOS Catalina 10.15.5 the .npmrc
file path can be found at
/Users/<user-name>/.npmrc
Open in it in (for first time users, create a new file) any editor and copy-paste your token. Save it.
You are ready to go.
Note:
As mentioned by @oligofren, the command npm config ls -l
will npm configurations. You will get the .npmrc file from config parameter userconfig
Hijacking a bit to add what ended up working for me:
Go into the Maven Projects
sidebar on the right edge of the IDE, and verify that your dependencies are listed correctly under your module there. Assuming they are, just ask IDEA to reimport then (the first button at the top, looks like two blue arrows forming a counter-clockwise circle).
Once I did that, and let IDEA reload the project for me, all my dependencies were magically understood.
For reference: this was with IDEA 13.1.2
If you are building DEBUG APK, just add:
debug {
multiDexEnabled true
}
inside buildTypes
and if you are building RELEASE APK, add
multiDexEnabled true
in release block as-
release {
...
multiDexEnabled true
...
}
look, i had the same problem but i insert the function as a global variable
as
var RNumber = Int(arc4random_uniform(9)+1)
func GetCase(){
your code
}
obviously this is not efficent, so then i just copy and paste the code into the function so it could be reusable, then xcode suggest me to set the var as constant so my code were
func GetCase() {
let RNumber = Int(arc4random_uniform(9)+1)
if categoria == 1 {
}
}
well thats a part of my code so xcode tell me something of inmutable and initialization but, it build the app anyway and that advice simply dissapear
hope it helps
Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.
$("legend").each(function() {
var SoftwareItem = $(this).text();
itemCost = GetItemCost(SoftwareItem);
$("input:checked").each(function() {
var Component = $(this).next("label").text();
itemCost += GetItemCost(Component);
});
$(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost);
});
If you want MySQL to automatically produce primary keys then you have to tell it when creating the table. You don't have to do this in Oracle.
On the Primary Key you have to include AUTO_INCREMENT
. See the example below.
CREATE TABLE `supplier`
(
`ID` int(11) NOT NULL **AUTO_INCREMENT**,
`FIRSTNAME` varchar(60) NOT NULL,
`SECONDNAME` varchar(100) NOT NULL,
`PROPERTYNUM` varchar(50) DEFAULT NULL,
`STREETNAME` varchar(50) DEFAULT NULL,
`CITY` varchar(50) DEFAULT NULL,
`COUNTY` varchar(50) DEFAULT NULL,
`COUNTRY` varchar(50) DEFAULT NULL,
`POSTCODE` varchar(50) DEFAULT NULL,
`HomePHONENUM` bigint(20) DEFAULT NULL,
`WorkPHONENUM` bigint(20) DEFAULT NULL,
`MobilePHONENUM` bigint(20) DEFAULT NULL,
`EMAIL` varchar(100) DEFAULT NULL,
PRIMARY KEY (`ID`)
)
ENGINE=InnoDB DEFAULT CHARSET=latin1;
Here's the Entity
package com.keyes.jpa;
import java.io.Serializable;
import javax.persistence.*;
import java.math.BigInteger;
/**
* The persistent class for the parkingsupplier database table.
*
*/
@Entity
@Table(name = "supplier")
public class supplier implements Serializable
{
private static final long serialVersionUID = 1L;
@Id
**@GeneratedValue(strategy = GenerationType.IDENTITY)**
@Column(name = "ID")
private long id;
@Column(name = "CITY")
private String city;
@Column(name = "COUNTRY")
private String country;
@Column(name = "COUNTY")
private String county;
@Column(name = "EMAIL")
private String email;
@Column(name = "FIRSTNAME")
private String firstname;
@Column(name = "HomePHONENUM")
private BigInteger homePHONENUM;
@Column(name = "MobilePHONENUM")
private BigInteger mobilePHONENUM;
@Column(name = "POSTCODE")
private String postcode;
@Column(name = "PROPERTYNUM")
private String propertynum;
@Column(name = "SECONDNAME")
private String secondname;
@Column(name = "STREETNAME")
private String streetname;
@Column(name = "WorkPHONENUM")
private BigInteger workPHONENUM;
public supplier()
{
}
public long getId()
{
return this.id;
}
public void setId(long id)
{
this.id = id;
}
public String getCity()
{
return this.city;
}
public void setCity(String city)
{
this.city = city;
}
public String getCountry()
{
return this.country;
}
public void setCountry(String country)
{
this.country = country;
}
public String getCounty()
{
return this.county;
}
public void setCounty(String county)
{
this.county = county;
}
public String getEmail()
{
return this.email;
}
public void setEmail(String email)
{
this.email = email;
}
public String getFirstname()
{
return this.firstname;
}
public void setFirstname(String firstname)
{
this.firstname = firstname;
}
public BigInteger getHomePHONENUM()
{
return this.homePHONENUM;
}
public void setHomePHONENUM(BigInteger homePHONENUM)
{
this.homePHONENUM = homePHONENUM;
}
public BigInteger getMobilePHONENUM()
{
return this.mobilePHONENUM;
}
public void setMobilePHONENUM(BigInteger mobilePHONENUM)
{
this.mobilePHONENUM = mobilePHONENUM;
}
public String getPostcode()
{
return this.postcode;
}
public void setPostcode(String postcode)
{
this.postcode = postcode;
}
public String getPropertynum()
{
return this.propertynum;
}
public void setPropertynum(String propertynum)
{
this.propertynum = propertynum;
}
public String getSecondname()
{
return this.secondname;
}
public void setSecondname(String secondname)
{
this.secondname = secondname;
}
public String getStreetname()
{
return this.streetname;
}
public void setStreetname(String streetname)
{
this.streetname = streetname;
}
public BigInteger getWorkPHONENUM()
{
return this.workPHONENUM;
}
public void setWorkPHONENUM(BigInteger workPHONENUM)
{
this.workPHONENUM = workPHONENUM;
}
}
Way to unlock the user :
$ sqlplus /nolog
SQL > conn sys as sysdba
SQL > ALTER USER USER_NAME ACCOUNT UNLOCK;
and open new terminal
SQL > sqlplus / as sysdba
connected
SQL > conn username/password //which username u gave before unlock
password:password
password:password
Answering the 2012 refreshed (by the second bounty) question, and reviewing the today's results (other answers).
About SOAP 1.2, advantages and drawbacks when comparing with "REST"... Well, since 2007 you can describe REST Web services with WSDL, and using SOAP protocol... That is, if you work a little harder, all W3C standards of the web services protocol stack can be REST!
It is a good starting point, because we can imagine a scenario in which all the philosophical and methodological discussions are temporarily avoided. We can compare technically "SOAP-REST" with "NON-SOAP-REST" in similar services,
SOAP-REST (="REST-SOAP"): as showed by L.Mandel, WSDL2 can describe a REST webservice, and, if we suppose that exemplified XML can be enveloped in SOAP, all the implementation will be "SOAP-REST".
NON-SOAP-REST: any REST web service that can not be SOAP... That is, "90%" of the well-knowed REST examples. Some not use XML (ex. typical AJAX RESTs use JSON instead), some use another XML strucutures, without the SOAP headers or rules. PS: to avoid informality, we can suppose REST level 2 in the comparisons.
Of course, to compare more conceptually, compare "NON-REST-SOAP" with "NON-SOAP-REST", as different modeling approaches. So, completing this taxonomy of web services:
NON-REST-SOAP: any SOAP web service that can not be REST... That is, "90%" of the well-knowed SOAP examples.
NON-REST-NEITHER-SOAP: yes, the universe of "web services modeling" comprises other things (ex. XML-RPC).
Comparing comparable things: SOAP-REST with NON-SOAP-REST.
Explaining some terms,
Contractual stability: for all kinds of contracts (as "written agreements"),
By the use of standars: all levels of the W3C stack are mutually compliant. REST, by other hand, is not a W3C or ISO standard, and have no normatized details about service's peripherals. So, as I, @DaveWoldrich(20 votes), @cynicalman(5), @Exitos(0) said before, in a context where are NEED FOR STANDARDS, you need SOAP.
By the use of best practices: the "verbose aspect" of the W3C stack implementations, translates relevant human/legal/juridic agreements.
Robustness: the safety of SOAP structure and headers. With metada communication (with the full expressiveness of XML) and verification you have an "insurance policy" against any changes or noise.
SOAP have "transactional reliability (...) deal with communication failures. SOAP has more controls around retry logic and thus can provide more end-to-end reliability and service guarantees", E. Terman.
Sorting pros by popularity,
Better tools (~70 votes): SOAP currently has the advantage of better tools, since 2007 and still 2012, because it is a well-defined and widely accepted standard. See @MarkCidade(27 votes), @DaveWoldrich(20), @JoshM(13), @TravisHeseman(9).
Standars compliance (25 votes): as I, @DaveWoldrich(20 votes), @cynicalman(5), @Exitos(0) said before, in a context where are NEED FOR STANDARDS, you need SOAP.
Robustness: insurance of SOAP headers, @JohnSaunders (8 votes).
SOAP strucuture is more complex (more than 300 votes): all answers here, and sources about "SOAP vs REST", manifest some degree of dislike with SOAP's redundancy and complexity. This is a natural consequence of the requirements for formal verification (see below), and for robustness (see above). "REST NON-SOAP" (and XML-RPC, the SOAP originator) can be more simple and informal.
The "only XML" restriction is a performance obstacle when using tiny services (~50 votes): see json.org/xml and this question, or this other one. This point is showed by @toluju(41), and others.
PS: as JSON is not a IETF standard, but we can consider a de facto standard for web software community.
Now, we can add SOAP-NON-REST with NON-SOAP-REST comparisons, and explain when is better to use SOAP:
Need for standards and stable contracts (see "PROS" section). PS: see a typical "B2B need for standards" described by @saille.
Need for tools (see "PROS" section). PS: standards, and the existence of formal verifications (see bellow), are important issues for the tools automation.
Parallel heavy processing (see "Context/Foundations" section below): with bigger and/or slower processes, no matter with a bit more complexity of SOAP, reliability and stability are the best investments.
Need more security: when more than HTTPS is required, and you really need additional features for protection, SOAP is a better choice (see @Bell, 32 votes). "Sending the message along a path more complicated than request/response or over a transport that does not involve HTTP", S. Seely. XML is a core issue, offering standards for XML Encryption, XML Signature, and XML Canonicalization, and, only with SOAP you can to embed these mechanisms into a message by a well-accepted standard as WS-Security.
Need more flexibility (less restrictions): SOAP not need exact correspondence with an URI; not nedd restrict to HTTP; not need to restrict to 4 verbs. As @TravisHeseman (9 votes) says, if you wanted something "flexible for an arbitrary number of client technologies and uses", use SOAP.
PS: remember that XML is more universal/expressive than JSON (et al).
Need for formal verifications: important to understand that W3C stack uses formal methods, and REST is more informal. Your WSDL (a formal language) service description is a formal specification of your web services interfaces, and SOAP is a robust protocol that accept all possible WSDL prescriptions.
To assess trends is necessary historical perspective. For this subject, a 10 or 15 years perspective...
Before the W3C standardization, there are some anarchy. Was difficult to implement interoperable services with different frameworks, and more difficult, costly, and time consuming to implement something interoperable between companys. The W3C stack standards has been a light, a north for interoperation of sets of complex web services.
For day-by-day tasks, like to implement AJAX, SOAP is heavy... So, the need for simple approaches need to elect a new theory-framework... And big "Web software players", as Google, Amazon, Yahoo, et al, elected the best alternative, that is the REST approach. Was in this context that REST concept arrived as a "competing framework", and, today (2012's), this alternative is a de facto standard for programmers.
In a context of Parallel Computing the web services provides parallel subtasks; and protocols, like SOAP, ensures good synchronization and communication. Not "any task": web services can be classified as
coarse-grained and embarrassing parallelism.
As the task gets bigger, it becomes less significant "complexity debate", and becomes more relevant the robustness of the communication and the solidity of the contracts.
If you do not need a table border, apply this:
table{
table-layout:fixed;
border-collapse:collapse;
}
td{
word-wrap: break-word;
}
If performance matters to you make sure you time:
import sys
import timeit
import pandas as pd
print('Python %s on %s' % (sys.version, sys.platform))
print('Pandas version %s' % pd.__version__)
repeat = 3
numbers = 100
def time(statement, _setup=None):
print (min(
timeit.Timer(statement, setup=_setup or setup).repeat(
repeat, numbers)))
print("Format %m/%d/%y")
setup = """import pandas as pd
import io
data = io.StringIO('''\
ProductCode,Date
''' + '''\
x1,07/29/15
x2,07/29/15
x3,07/29/15
x4,07/30/15
x5,07/29/15
x6,07/29/15
x7,07/29/15
y7,08/05/15
x8,08/05/15
z3,08/05/15
''' * 100)"""
time('pd.read_csv(data); data.seek(0)')
time('pd.read_csv(data, parse_dates=["Date"]); data.seek(0)')
time('pd.read_csv(data, parse_dates=["Date"],'
'infer_datetime_format=True); data.seek(0)')
time('pd.read_csv(data, parse_dates=["Date"],'
'date_parser=lambda x: pd.datetime.strptime(x, "%m/%d/%y")); data.seek(0)')
print("Format %Y-%m-%d %H:%M:%S")
setup = """import pandas as pd
import io
data = io.StringIO('''\
ProductCode,Date
''' + '''\
x1,2016-10-15 00:00:43
x2,2016-10-15 00:00:56
x3,2016-10-15 00:00:56
x4,2016-10-15 00:00:12
x5,2016-10-15 00:00:34
x6,2016-10-15 00:00:55
x7,2016-10-15 00:00:06
y7,2016-10-15 00:00:01
x8,2016-10-15 00:00:00
z3,2016-10-15 00:00:02
''' * 1000)"""
time('pd.read_csv(data); data.seek(0)')
time('pd.read_csv(data, parse_dates=["Date"]); data.seek(0)')
time('pd.read_csv(data, parse_dates=["Date"],'
'infer_datetime_format=True); data.seek(0)')
time('pd.read_csv(data, parse_dates=["Date"],'
'date_parser=lambda x: pd.datetime.strptime(x, "%Y-%m-%d %H:%M:%S")); data.seek(0)')
prints:
Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 03:13:28)
[Clang 6.0 (clang-600.0.57)] on darwin
Pandas version 0.23.4
Format %m/%d/%y
0.19123052499999993
8.20691274
8.143124389
1.2384357139999977
Format %Y-%m-%d %H:%M:%S
0.5238807110000039
0.9202787830000005
0.9832778819999959
12.002349824999996
So with iso8601-formatted date (%Y-%m-%d %H:%M:%S
is apparently an iso8601-formatted date, I guess the T can be dropped and replaced by a space) you should not specify infer_datetime_format
(which does not make a difference with more common ones either apparently) and passing your own parser in just cripples performance. On the other hand, date_parser
does make a difference with not so standard day formats. Be sure to time before you optimize, as usual.
numpy.random.randint
accepts a third argument (size
) , in which you can specify the size of the output array. You can use this to create your DataFrame
-
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
Here - np.random.randint(0,100,size=(100, 4))
- creates an output array of size (100,4)
with random integer elements between [0,100)
.
Demo -
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
which produces:
A B C D
0 45 88 44 92
1 62 34 2 86
2 85 65 11 31
3 74 43 42 56
4 90 38 34 93
5 0 94 45 10
6 58 23 23 60
.. .. .. .. ..
In Python 3 you can use concurrent.futures.ThreadPoolExecutor
, i.e.:
executor = ThreadPoolExecutor(max_workers=10)
a = executor.submit(my_function)
See the docs for more info and examples.
This answer was originally written in response to a question which has since been marked as duplicate: Removing coordinates from list on python
There are two problems in your code:
1) When using remove(), you attempt to remove integers whereas you need to remove a tuple.
2) The for loop will skip items in your list.
Let's run through what happens when we execute your code:
>>> L1 = [(1,2), (5,6), (-1,-2), (1,-2)]
>>> for (a,b) in L1:
... if a < 0 or b < 0:
... L1.remove(a,b)
...
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
TypeError: remove() takes exactly one argument (2 given)
The first problem is that you are passing both 'a' and 'b' to remove(), but remove() only accepts a single argument. So how can we get remove() to work properly with your list? We need to figure out what each element of your list is. In this case, each one is a tuple. To see this, let's access one element of the list (indexing starts at 0):
>>> L1[1]
(5, 6)
>>> type(L1[1])
<type 'tuple'>
Aha! Each element of L1 is actually a tuple. So that's what we need to be passing to remove(). Tuples in python are very easy, they're simply made by enclosing values in parentheses. "a, b" is not a tuple, but "(a, b)" is a tuple. So we modify your code and run it again:
# The remove line now includes an extra "()" to make a tuple out of "a,b"
L1.remove((a,b))
This code runs without any error, but let's look at the list it outputs:
L1 is now: [(1, 2), (5, 6), (1, -2)]
Why is (1,-2) still in your list? It turns out modifying the list while using a loop to iterate over it is a very bad idea without special care. The reason that (1, -2) remains in the list is that the locations of each item within the list changed between iterations of the for loop. Let's look at what happens if we feed the above code a longer list:
L1 = [(1,2),(5,6),(-1,-2),(1,-2),(3,4),(5,7),(-4,4),(2,1),(-3,-3),(5,-1),(0,6)]
### Outputs:
L1 is now: [(1, 2), (5, 6), (1, -2), (3, 4), (5, 7), (2, 1), (5, -1), (0, 6)]
As you can infer from that result, every time that the conditional statement evaluates to true and a list item is removed, the next iteration of the loop will skip evaluation of the next item in the list because its values are now located at different indices.
The most intuitive solution is to copy the list, then iterate over the original list and only modify the copy. You can try doing so like this:
L2 = L1
for (a,b) in L1:
if a < 0 or b < 0 :
L2.remove((a,b))
# Now, remove the original copy of L1 and replace with L2
print L2 is L1
del L1
L1 = L2; del L2
print ("L1 is now: ", L1)
However, the output will be identical to before:
'L1 is now: ', [(1, 2), (5, 6), (1, -2), (3, 4), (5, 7), (2, 1), (5, -1), (0, 6)]
This is because when we created L2, python did not actually create a new object. Instead, it merely referenced L2 to the same object as L1. We can verify this with 'is' which is different from merely "equals" (==).
>>> L2=L1
>>> L1 is L2
True
We can make a true copy using copy.copy(). Then everything works as expected:
import copy
L1 = [(1,2), (5,6),(-1,-2), (1,-2),(3,4),(5,7),(-4,4),(2,1),(-3,-3),(5,-1),(0,6)]
L2 = copy.copy(L1)
for (a,b) in L1:
if a < 0 or b < 0 :
L2.remove((a,b))
# Now, remove the original copy of L1 and replace with L2
del L1
L1 = L2; del L2
>>> L1 is now: [(1, 2), (5, 6), (3, 4), (5, 7), (2, 1), (0, 6)]
Finally, there is one cleaner solution than having to make an entirely new copy of L1. The reversed() function:
L1 = [(1,2), (5,6),(-1,-2), (1,-2),(3,4),(5,7),(-4,4),(2,1),(-3,-3),(5,-1),(0,6)]
for (a,b) in reversed(L1):
if a < 0 or b < 0 :
L1.remove((a,b))
print ("L1 is now: ", L1)
>>> L1 is now: [(1, 2), (5, 6), (3, 4), (5, 7), (2, 1), (0, 6)]
Unfortunately, I cannot adequately describe how reversed() works. It returns a 'listreverseiterator' object when a list is passed to it. For practical purposes, you can think of it as creating a reversed copy of its argument. This is the solution I recommend.
Pygmentize is a killer tool. See this.
I combine python json.tool with pygmentize
echo '{"foo": "bar"}' | python -m json.tool | pygmentize -l json
See the link above for pygmentize installation instruction.
A demo of this is in the image below:
If you can make an approximation of the number of items that will be there at the end, use the overload of the List constuctor that takes count as a parameter. You will save some expensive List duplications. Otherwise you have to pay for it.
You can also use list comprehension on splitted string
[ int(x) for x in example_string.split(',') ]
You can simply use,
import json
json.loads(my_bytes_value)
A StreamReader is for text, not plain bytes. Don't use a StreamReader, and instead read directly from the underlying stream.
Specifically, document.all
was introduced for IE4 BEFORE document.getElementById
had been introduced.
So, the presence of document.all
means that the code is intended to support IE4, or is trying to identify the browser as IE4 (though it could have been Opera), or the person who wrote (or copied and pasted) the code wasn't up on the latest.
In the highly unlikely event that you need to support IE4, then, you do need document.all
(or a library that handles these ancient IE specs).
You should set async = false in head. Use post/get instead of ajax.
jQuery.ajaxSetup({ async: false });
$.post({
url: 'api.php',
data: 'id1=' + q + '',
dataType: 'json',
success: function (data) {
id = data[0];
vname = data[1];
}
});
Since it's a long time and people keep suggesting to use Scanner#nextLine()
, there's another chance that Scanner
can take spaces included in input.
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
You can use Scanner#useDelimiter()
to change the delimiter of Scanner
to another pattern such as a line feed
or something else.
Scanner in = new Scanner(System.in);
in.useDelimiter("\n"); // use LF as the delimiter
String question;
System.out.println("Please input question:");
question = in.next();
// TODO do something with your input such as removing spaces...
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
I know this is an older question, but I ran into a similar situation, and I wanted to share what I had found for future searchers, possibly including myself :).
DateTime.Parse()
can be tricky -- see here for example.
If the DateTime
is coming from a Web service or some other source with a known format, you might want to consider something like
DateTime.ParseExact(dateString,
"MM/dd/yyyy HH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal)
or, even better,
DateTime.TryParseExact(...)
The AssumeUniversal
flag tells the parser that the date/time is already UTC; the combination of AssumeUniversal
and AdjustToUniversal
tells it not to convert the result to "local" time, which it will try to do by default. (I personally try to deal exclusively with UTC in the business / application / service layer(s) anyway. But bypassing the conversion to local time also speeds things up -- by 50% or more in my tests, see below.)
Here's what we were doing before:
DateTime.Parse(dateString, new CultureInfo("en-US"))
We had profiled the app and found that the DateTime.Parse represented a significant percentage of CPU usage. (Incidentally, the CultureInfo
constructor was not a significant contributor to CPU usage.)
So I set up a console app to parse a date/time string 10000 times in a variety of ways. Bottom line:
Parse()
10 sec
ParseExact()
(converting to local) 20-45 ms
ParseExact()
(not converting to local) 10-15 ms
... and yes, the results for Parse()
are in seconds, whereas the others are in milliseconds.
Example: to view the Windows User Name on Cell C5, you can use this script :
Range("C5").Value = ": " & Environ("USERNAME").
You are calling the addToCart method and passing the product id. Now you may use jQuery ajax to pass that data to your server side action method.d
jQuery post is the short version of jQuery ajax.
function addToCart(id)
{
$.post('@Url.Action("Add","Cart")',{id:id } function(data) {
//do whatever with the result.
});
}
If you want more options like success callbacks and error handling, use jQuery ajax,
function addToCart(id)
{
$.ajax({
url: '@Url.Action("Add","Cart")',
data: { id: id },
success: function(data){
//call is successfully completed and we got result in data
},
error:function (xhr, ajaxOptions, thrownError){
//some errror, some show err msg to user and log the error
alert(xhr.responseText);
}
});
}
When making ajax calls, I strongly recommend using the Html helper method such as Url.Action
to generate the path to your action methods.
This will work if your code is in a razor view because Url.Action will be executed by razor at server side and that c# expression will be replaced with the correct relative path. But if you are using your jQuery code in your external js file, You may consider the approach mentioned in this answer.
Guys, I found that JQuery has only one effect: the page is reloaded when the back button is pressed. This has nothing to do with "ready".
How does this work? Well, JQuery adds an onunload event listener.
// http://code.jquery.com/jquery-latest.js
jQuery(window).bind("unload", function() { // ...
By default, it does nothing. But somehow this seems to trigger a reload in Safari, Opera and Mozilla -- no matter what the event handler contains.
[edit(Nickolay): here's why it works that way: webkit.org, developer.mozilla.org. Please read those articles (or my summary in a separate answer below) and consider whether you really need to do this and make your page load slower for your users.]
Can't believe it? Try this:
<body onunload=""><!-- This does the trick -->
<script type="text/javascript">
alert('first load / reload');
window.onload = function(){alert('onload')};
</script>
<a href="http://stackoverflow.com">click me, then press the back button</a>
</body>
You will see similar results when using JQuery.
You may want to compare to this one without onunload
<body><!-- Will not reload on back button -->
<script type="text/javascript">
alert('first load / reload');
window.onload = function(){alert('onload')};
</script>
<a href="http://stackoverflow.com">click me, then press the back button</a>
</body>
This has nothing to do with structs - arrays in C are not assignable:
char a[20];
a = "foo"; // error
you need to use strcpy:
strcpy( a, "foo" );
or in your code:
strcpy( sara.first, "Sara" );
I have build a small demo project on this you could have a look to it Link to project
$ youtube-dl -o '%(playlist)s/%(playlist_index)s - %(title)s.%(ext)s' https://www.youtube.com/playlist?list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re
$ youtube-dl -o '%(uploader)s/%(playlist)s/%(playlist_index)s - %(title)s.%(ext)s' https://www.youtube.com/user/TheLinuxFoundation/playlists
youtube-dl is a command-line program to download videos from YouTube.com and a few more sites. It requires the Python interpreter, version 2.6, 2.7, or 3.2+, and it is not platform specific. It should work on your Unix box, on Windows or on macOS. It is released to the public domain, which means you can modify it, redistribute it or use it however you like.
$ youtube-dl [OPTIONS] URL [URL...]
--playlist-start NUMBER Playlist video to start at (default is 1) --playlist-end NUMBER Playlist video to end at (default is last) --playlist-items ITEM_SPEC Playlist video items to download. Specify indices of the videos in the playlist separated by commas like: "--playlist-items 1,2,5,8" if you want to download videos indexed 1, 2, 5, 8 in the playlist. You can specify range: "--playlist-items 1-3,7,10-13", it will download the videos at index 1, 2, 3, 7, 10, 11, 12 and 13.
Based on dule's answer for appending a collection of items, a one-liner for...in
will also work wonders:
let cities = {'ny':'New York','ld':'London','db':'Dubai','pk':'Beijing','tk':'Tokyo','nd':'New Delhi'};_x000D_
_x000D_
for(let c in cities){$('#selectCity').append($('<option>',{value: c,text: cities[c]}))}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>_x000D_
<select id="selectCity"></select>
_x000D_
Both object values and indexes are assigned to the options. This solution works even in the old jQuery (v1.4)!
--Update on 9th July---
Removed "It is correct and accurate" as commented by @mgiuca
======
NO. It is NOT talking about your files currently with CRLF
. It is instead talking about files with LF
.
It should read:
warning: (If you check it out/or clone to another folder with your current core.autocrlf configuration,)LF will be replaced by CRLF
The file will have its original line endings in your (current) working directory.
I have seen instances where the remote became out of sync and needed to be updated. If a reset --hard
or a branch -D
fail to work, try
git pull origin
git reset --hard
We're having a lot of race conditions with elementToBeClickable
. See https://github.com/angular/protractor/issues/2313. Something along these lines worked reasonably well even if a little brute force
Awaitility.await()
.atMost(timeout)
.ignoreException(NoSuchElementException.class)
.ignoreExceptionsMatching(
Matchers.allOf(
Matchers.instanceOf(WebDriverException.class),
Matchers.hasProperty(
"message",
Matchers.containsString("is not clickable at point")
)
)
).until(
() -> {
this.driver.findElement(locator).click();
return true;
},
Matchers.is(true)
);
You need a reference to an Axes
object to keep drawing on the same subplot.
import matplotlib.pyplot as plt
x = range(100)
y = range(100,200)
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.scatter(x[:4], y[:4], s=10, c='b', marker="s", label='first')
ax1.scatter(x[40:],y[40:], s=10, c='r', marker="o", label='second')
plt.legend(loc='upper left');
plt.show()
Ok, found it.
package.json must contain a dependency to angular-cli.
When I uninstalled my local angular-cli, npm also removed the dependency entry.
simply use a 'script' tag with a dot after.
script.
var users = !{JSON.stringify(users).replace(/<\//g, "<\\/")}
https://github.com/pugjs/pug/blob/master/examples/dynamicscript.pug
try this one last:
so I tried all the suggestions on this page.. none worked.. The way my problem started was by following the steps in this tutorial that teaches how to link static libraries. With my sample project the instructions worked fine.. but then on my actual project I started getting the error above.
So what I did was go through each step of the said tutorial and built after each step.. the offending line turned out to be this one: adding -all_load to build settings-> other linker flags
it turns out that this flag was recommended once upon a time to link categories to static libraries.. but then it turned out that this flag was no longer necessary Xcode 4.2+.. (same goes for the -force_load flag.. which was also recommended in other posts)..
If the main intent is to check whether the supplied value is not found in a list, maybe you can use the extended regular expression matching built in BASH via the "equal tilde" operator (see also this answer):
if ! [[ "$cms" =~ ^(wordpress|meganto|typo3)$ ]]; then get_cms ; fi
Have a nice day
I found out that if we do not specify which python version we want the environment which is created is completely empty. Thus, to resolve this issue what I did is that I gave the python version as well. i.e
conda create --name env_name python=3.6
so what it does now is that it installs python 3.6 and now we can select the interpreter. For that follow the below-mentioned steps:
Firstly, open the command palette using Ctrl + Shift + P
Secondly, Select Python: select Interpreter
Now, Select Enter interpreter path
We have to add the path where the env is, the default location will be
C:\Users\YourUserName\Anaconda3\envs\env_name
Finally, you have successfully activated your environment. It might now be the best way but it worked for me. Let me know if there is any issue.
Public Sub SelectFirstBlankCell()
Dim sourceCol As Integer, rowCount As Integer, currentRow As Integer
Dim currentRowValue As String
sourceCol = 6 'column F has a value of 6
rowCount = Cells(Rows.Count, sourceCol).End(xlUp).Row
'for every row, find the first blank cell and select it
For currentRow = 1 To rowCount
currentRowValue = Cells(currentRow, sourceCol).Value
If IsEmpty(currentRowValue) Or currentRowValue = "" Then
Cells(currentRow, sourceCol).Select
End If
Next
End Sub
If any column contains more than one empty cell continuously then this code will not work properly
Depending on what exactly is preventing you from doing this, there's another option that requires no changes to your current implementation. You should be able to augment React in your project with a .ts
or .d.ts
file (not sure which) at project root. It would look something like this:
declare module 'react' {
interface HTMLAttributes<T> extends React.DOMAttributes<T> {
'custom-attribute'?: string; // or 'some-value' | 'another-value'
}
}
Another possibility is the following:
declare namespace JSX {
interface IntrinsicElements {
[elemName: string]: any;
}
}
You might even have to wrap that in a declare global {
. I haven't landed on a final solution yet.
See also: How do I add attributes to existing HTML elements in TypeScript/JSX?
The primary key is used to work with different tables. This is the foundation of relational databases. If you have a book database it's better to create 2 tables - 1) books and 2) authors with INT primary key "id". Then you use id in books instead of authors name.
The unique key is used if you don't want to have repeated entries. For example you may have title in your book table and want to be sure there is only one entry for each title.
The java.sql.Timestamp class has no format. Its toString method generates a String with a format.
Do not conflate a date-time object with a String that may represent its value. A date-time object can parse strings and generate strings but is not itself a string.
First convert from the troubled old legacy date-time classes to java.time classes. Use the new methods added to the old classes.
Instant instant = mySqlDate.toInstant() ;
Lose the fraction of a second you don't want.
instant = instant.truncatedTo( ChronoUnit.Seconds );
Assign the time zone to adjust from UTC used by Instant.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z );
Generate a String close to your desired output. Replace its T
in the middle with a SPACE.
DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_DATE_TIME ;
String output = zdt.format( f ).replace( "T" , " " );
A better solution:
if type(value) == str:
# Ignore errors even if the string is not proper UTF-8 or has
# broken marker bytes.
# Python built-in function unicode() can do this.
value = unicode(value, "utf-8", errors="ignore")
else:
# Assume the value object has proper __unicode__() method
value = unicode(value)
If you would like to read more about why:
http://docs.plone.org/manage/troubleshooting/unicode.html#id1
another language meta tag is og:locale and you can define og:locale meta tag for social media
<meta property="og:locale" content="en" />
For anyone experiencing this on windows after an update
What happened was that Windows Defender made some changes. Possibly cause running data extraction scripts, but python.exe got reduced to 0kb for that project. Copying the python.exe from another project and replacing it solved for now.
Use the SCL repos.
sudo sh -c 'wget -qO- http://people.redhat.com/bkabrda/scl_python33.repo >> /etc/yum.repos.d/scl.repo'
sudo yum install python33
scl enable python27
(This last command will have to be run each time you want to use python27 rather than the system default.)
Mac OSX High Sierra 10.13 fixes this somewhat. Just make a virtual APFS partition for your git projects, by default it has no size limit and takes no space.
Sensitive
git
and ln -s /Volumes/Sensitive/git /Users/johndoe/git
Your drive will be in /Volumes/Sensitive/
How do I commit case-sensitive only filename changes in Git?
Just a very quick addition as I have been testing a few options and missed this along the way. Make sure your page has:
<meta name="viewport" content="initial-scale=1.0">
You can also set the tableview's bounces property to NO. This will keep the section headers non-floating/static, but then you also lose the bounce property of the tableview.
try this (a2 is BLOB col)
PreparedStatement ps1 = conn.prepareStatement("update t1 set a2=? where id=1");
Blob blob = conn.createBlob();
blob.setBytes(1, str.getBytes());
ps1.setBlob(1, blob);
ps1.executeUpdate();
it may work even without BLOB, driver will transform types automatically:
ps1.setBytes(1, str.getBytes);
ps1.setString(1, str);
Besides if you work with text CLOB seems to be a more natural col type
For people who want one-liners without loops:
I can't believe that noone has though of this, but perhaps it's because of the more C-like approach. Anyways, it is perfectly safe to do this without a loop, in a one-liner, ASSUMING that the std::vector<char>
is null-terminated:
std::vector<char> test { 'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!', '\0' };
std::cout << test.data() << std::endl;
But I would wrap this in the ostream
operator, as @Zorawar suggested, just to be safe:
template <typename T>std::ostream& operator<< (std::ostream& out, std::vector<T>& v)
{
v.push_back('\0'); // safety-check!
out << v.data();
return out;
}
std::cout << test << std::endl; // will print 'Hello, world!'
We can achieve similar behaviour by using printf
instead:
fprintf(stdout, "%s\n", &test[0]); // will also print 'Hello, world!'
NOTE:
The overloaded ostream
operator needs to accept the vector as non-const. This might make the program insecure or introduce misusable code. Also, since null-character is appended, a reallocation of the std::vector
might occur. So using for-loops with iterators will likely be faster.
For python 3,
for d in list:
d.update((k, float(v)) for k, v in d.items())
"Not Possible". You can do this using this query. Initialize here
declare @sql nvarchar(4000)=''
Set Value & exec command of your sp with parameters
SET @sql += ' Exec spName @param'
EXECUTE sp_executesql @sql, N'@param type', @param = @param
Isn't it already created ? Mkdir returns false if the folder already exists too mkdir
An alternative to the answer by @Marco Ponti, and avoiding the checkout:
git diff --name-only <notMainDev> $(git merge-base <notMainDev> <mainDev>)
If your particular shell doesn't understand the $() construct, use back-ticks instead.
You can use the Chrome DevTools Utilities API copy()
command for copying the string representation of the specified object to the clipboard.
If you have lots of objects then you can actually JSON.stringify() all your objects and keep on appending them to a string. Now use copy()
method to copy the complete string to clipboard.
One shouldn't use set_yticklabels
to change the fontsize, since this will also set the labels (i.e. it will replace any automatic formatter by a FixedFormatter
), which is usually undesired. The easiest is to set the respective tick_params
:
ax.tick_params(axis="x", labelsize=8)
ax.tick_params(axis="y", labelsize=20)
or
ax.tick_params(labelsize=8)
in case both axes shall have the same size.
Of course using the rcParams as in @tmdavison's answer is possible as well.
select count(*) from
(
SELECT distinct column1,column2,column3,column4 FROM abcd
) T
This will give count of distinct group of columns.
Writing your own parser is fun, but likely you should have a look at Open CSV. It provides numerous ways of accessing the CSV and also allows to generate CSV. And it does handle escapes properly. As mentioned in another post, there is also a CSV-parsing lib in the Apache Commons, but that one isn't released yet.
here's what six is:
pip search six
six - Python 2 and 3 compatibility utilities
to install:
pip install six
though if you did install python-dateutil
from pip six should have been set as a dependency.
N.B.: to install pip run easy_install pip
from command line.
Simply replace
print $image;
with
echo '<img src=".$image." >';
As your output results a double you should cast either completed variable or total variable or both to double while dividing.
So, the correct implmentation will be:
System.out.println((double)completed/total);
Sometimes ! be careful with property depth of the image ! and name for image
exemple : ic_xxxxx_xxxx - Copie
First of all, %d is for a int
So %1.16lld
makes no sense, because %d is an integer
That typedef you do, is also unnecessary, use the type straight ahead, makes a much more readable code.
What you want to use is the type double
, for calculating pi
and then using %f
or %1.16f
.
The first is a constant pointer to a char and the second is a pointer to a constant char. You didn't touch all the cases in your code:
char * const pc1 = &a; /* You can't make pc1 point to anything else */
const char * pc2 = &a; /* You can't dereference pc2 to write. */
*pc1 = 'c' /* Legal. */
*pc2 = 'c' /* Illegal. */
pc1 = &b; /* Illegal, pc1 is a constant pointer. */
pc2 = &b; /* Legal, pc2 itself is not constant. */
I had a similar issue, my error was:
Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: java.lang.ClassNotFoundException:org.glassfish.jersey.servlet.ServletContainer from [Module "deployment.RESTful_Services_CRUD.war:main" from Service Module Loader]
I use jboss
and glassfish
so I changed the web.xml
to the following:
<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
Instead of:
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
Hope this work for you.
Hello year 2010 question.
The OP.'s requirement is preserve keys (keep keys) and not overlap (I think overwrite). In some case such as numeric keys it is possible but if string keys it seems to be not possible.
If you use array_merge()
the numeric keys will always re-index or renumbered.
If you use array_replace()
, array_replace_recursive()
it will be overlap or overwrite from the right to the left. The value with the same key on first array will be replaced with second array.
If you use $array1 + $array2
as the comment was mentioned, if the keys are same then it will keep the value from first array but drop the second array.
Here is my function that I just wrote to work on the same requirements. You are free to use for any purpose.
/**
* Array custom merge. Preserve indexed array key (numbers) but overwrite string key (same as PHP's `array_merge()` function).
*
* If the another array key is string, it will be overwrite the first array.<br>
* If the another array key is integer, it will be add to first array depend on duplicated key or not.
* If it is not duplicate key with the first, the key will be preserve and add to the first array.
* If it is duplicated then it will be re-index the number append to the first array.
*
* @param array $array1 The first array is main array.
* @param array ...$arrays The another arrays to merge with the first.
* @return array Return merged array.
*/
function arrayCustomMerge(array $array1, array ...$arrays): array
{
foreach ($arrays as $additionalArray) {
foreach ($additionalArray as $key => $item) {
if (is_string($key)) {
// if associative array.
// item on the right will always overwrite on the left.
$array1[$key] = $item;
} elseif (is_int($key) && !array_key_exists($key, $array1)) {
// if key is number. this should be indexed array.
// and if array 1 is not already has this key.
// add this array with the key preserved to array 1.
$array1[$key] = $item;
} else {
// if anything else...
// get all keys from array 1 (numbers only).
$array1Keys = array_filter(array_keys($array1), 'is_int');
// next key index = get max array key number + 1.
$nextKeyIndex = (intval(max($array1Keys)) + 1);
unset($array1Keys);
// set array with the next key index.
$array1[$nextKeyIndex] = $item;
unset($nextKeyIndex);
}
}// endforeach; $additionalArray
unset($item, $key);
}// endforeach;
unset($additionalArray);
return $array1;
}// arrayCustomMerge
<?php
$array1 = [
'cat',
'bear',
'fruitred' => 'apple',
3.1 => 'dog',
null => 'null',
];
$array2 = [
1 => 'polar bear',
20 => 'monkey',
'fruitred' => 'strawberry',
'fruityellow' => 'banana',
null => 'another null',
];
// require `arrayCustomMerge()` function here.
function printDebug($message)
{
echo '<pre>';
print_r($message);
echo '</pre>' . PHP_EOL;
}
echo 'array1: <br>';
printDebug($array1);
echo 'array2: <br>';
printDebug($array2);
echo PHP_EOL . '<hr>' . PHP_EOL . PHP_EOL;
echo 'arrayCustomMerge:<br>';
$merged = arrayCustomMerge($array1, $array2);
printDebug($merged);
assert($merged[0] == 'cat', 'array key 0 should be \'cat\'');
assert($merged[1] == 'bear', 'array key 1 should be \'bear\'');
assert($merged['fruitred'] == 'strawberry', 'array key \'fruitred\' should be \'strawberry\'');
assert($merged[3] == 'dog', 'array key 3 should be \'dog\'');
assert(array_search('another null', $merged) !== false, '\'another null\' should be merged.');
assert(array_search('polar bear', $merged) !== false, '\'polar bear\' should be merged.');
assert($merged[20] == 'monkey', 'array key 20 should be \'monkey\'');
assert($merged['fruityellow'] == 'banana', 'array key \'fruityellow\' should be \'banana\'');
The results.
array1:
Array
(
[0] => cat
[1] => bear
[fruitred] => apple
[3] => dog
[] => null
)
array2:
Array
(
[1] => polar bear
[20] => monkey
[fruitred] => strawberry
[fruityellow] => banana
[] => another null
)
---
arrayCustomMerge:
Array
(
[0] => cat
[1] => bear
[fruitred] => strawberry
[3] => dog
[] => another null
[4] => polar bear
[20] => monkey
[fruityellow] => banana
)
I know it's 2 years late, but these answers helped me to formulate a filter function to output objects and trim the resulting strings. Since I have to format everything into a string in my final solution I went about things a little differently. Long-hand, my problem is very similar, and looks a bit like this
$verbosepreference="Continue"
write-verbose (ls | ft | out-string) # this generated too many blank lines
Here is my example:
ls | Out-Verbose # out-verbose formats the (pipelined) object(s) and then trims blanks
My Out-Verbose function looks like this:
filter Out-Verbose{
Param([parameter(valuefrompipeline=$true)][PSObject[]]$InputObject,
[scriptblock]$script={write-verbose "$_"})
Begin {
$val=@()
}
Process {
$val += $inputobject
}
End {
$val | ft -autosize -wrap|out-string |%{$_.split("`r`n")} |?{$_.length} |%{$script.Invoke()}
}
}
Note1: This solution will not scale to like millions of objects(it does not handle the pipeline serially)
Note2: You can still add a -noheaddings option. If you are wondering why I used a scriptblock here, that's to allow overloading like to send to disk-file or other output streams.
case the column isn't string, use astype to convert:
df['col'] = df['col'].astype(str).str[:9]
os.path.split(os.path.realpath(__file__))[0]
os.path.realpath(__file__)
return the abspath of the current script; os.path.split(abspath)[0] return the current dir
Using Linq to xml
Add a reference to System.Xml.Linq
and use
XDocument.Parse(string xmlString)
Edit: Sample follows, xml data (TestConfig.xml)..
<?xml version="1.0"?>
<Tests>
<Test TestId="0001" TestType="CMD">
<Name>Convert number to string</Name>
<CommandLine>Examp1.EXE</CommandLine>
<Input>1</Input>
<Output>One</Output>
</Test>
<Test TestId="0002" TestType="CMD">
<Name>Find succeeding characters</Name>
<CommandLine>Examp2.EXE</CommandLine>
<Input>abc</Input>
<Output>def</Output>
</Test>
<Test TestId="0003" TestType="GUI">
<Name>Convert multiple numbers to strings</Name>
<CommandLine>Examp2.EXE /Verbose</CommandLine>
<Input>123</Input>
<Output>One Two Three</Output>
</Test>
<Test TestId="0004" TestType="GUI">
<Name>Find correlated key</Name>
<CommandLine>Examp3.EXE</CommandLine>
<Input>a1</Input>
<Output>b1</Output>
</Test>
<Test TestId="0005" TestType="GUI">
<Name>Count characters</Name>
<CommandLine>FinalExamp.EXE</CommandLine>
<Input>This is a test</Input>
<Output>14</Output>
</Test>
<Test TestId="0006" TestType="GUI">
<Name>Another Test</Name>
<CommandLine>Examp2.EXE</CommandLine>
<Input>Test Input</Input>
<Output>10</Output>
</Test>
</Tests>
C# usage...
XElement root = XElement.Load("TestConfig.xml");
IEnumerable<XElement> tests =
from el in root.Elements("Test")
where (string)el.Element("CommandLine") == "Examp2.EXE"
select el;
foreach (XElement el in tests)
Console.WriteLine((string)el.Attribute("TestId"));
This code produces the following output: 0002 0006
Using jQuery you can do exactly the same thing, for example:
$("a").click();
Which will "click" all anchors on the page.