If you have that same problem in MySql 5.7.+ :
Access denied for user 'root'@'localhost'
it's because MySql 5.7 by default allow to connect with socket, which means you just connect with sudo mysql
. If you run sql :
SELECT user,authentication_string,plugin,host FROM mysql.user;
then you will see it :
+------------------+-------------------------------------------+-----------------------+-----------+
| user | authentication_string | plugin | host |
+------------------+-------------------------------------------+-----------------------+-----------+
| root | | auth_socket | localhost |
| mysql.session | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | mysql_native_password | localhost |
| mysql.sys | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | mysql_native_password | localhost |
| debian-sys-maint | *497C3D7B50479A812B89CD12EC3EDA6C0CB686F0 | mysql_native_password | localhost |
+------------------+-------------------------------------------+-----------------------+-----------+
4 rows in set (0.00 sec)
To allow connection with root and password, then update the values in the table with command :
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'Current-Root-Password';
FLUSH PRIVILEGES;
Then run the select command again and you'll see it has changed :
+------------------+-------------------------------------------+-----------------------+-----------+
| user | authentication_string | plugin | host |
+------------------+-------------------------------------------+-----------------------+-----------+
| root | *2F2377C1BC54BE827DC8A4EE051CBD57490FB8C6 | mysql_native_password | localhost |
| mysql.session | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | mysql_native_password | localhost |
| mysql.sys | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | mysql_native_password | localhost |
| debian-sys-maint | *497C3D7B50479A812B89CD12EC3EDA6C0CB686F0 | mysql_native_password | localhost |
+------------------+-------------------------------------------+-----------------------+-----------+
4 rows in set (0.00 sec)
And that's it. You can run this process after running and completing the sudo mysql_secure_installation
command.
For mariadb, use
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('manager');
to set password. More at https://mariadb.com/kb/en/set-password/
The top answer misses the fact that you can have a perfectly stable connection to your default gateway but that does not automatically mean you can actually reach something on the internet. The OP asks how he/she can test a connection with the world. So I suggest to alter the top answer by changing the gateway IP to a known IP (x.y.z.w) that is outside your LAN.
So the answer would become:
ping -q -w 1 -c 1 x.y.z.w > /dev/null && echo ok || echo error
Also removing the unfavored backticks for command substitution[1].
If you just want to make sure you are connected to the world before executing some code you can also use:
if ping -q -w 1 -c 1 x.y.z.w > /dev/null; then
# more code
fi
Try using white-space: nowrap;
in the container style (instead of overflow: hidden;
)
The maximum row size for a given table is determined by several factors:
The internal representation of a MySQL table has a maximum row size limit of 65,535 bytes, even if the storage engine is capable of supporting larger rows. BLOB and TEXT columns only contribute 9 to 12 bytes toward the row size limit because their contents are stored separately from the rest of the row.
The maximum row size for an InnoDB table, which applies to data stored locally within a database page, is slightly less than half a page. For example, the maximum row size is slightly less than 8KB for the default 16KB InnoDB page size, which is defined by the innodb_page_size configuration option. “Limits on InnoDB Tables”.
Provide the source image (img) size as the first rectangle:
ctx.drawImage(img, 0, 0, img.width, img.height, // source rectangle
0, 0, canvas.width, canvas.height); // destination rectangle
The second rectangle will be the destination size (what source rectangle will be scaled to).
Update 2016/6: For aspect ratio and positioning (ala CSS' "cover" method), check out:
Simulation background-size: cover in canvas
Try this:
DATE_FORMAT(NOW(),'01/01/%Y')
DATE_FORMAT(NOW(),'31/12/%Y')
for my case i used the following codes :
if (!(/\.(gif|jpg|jpeg|tiff|png)$/i).test(fileName)) {
alert('You must select an image file only');
}
I would suggest querying the sys
views. something similar to
SELECT *
FROM
sys.dm_exec_sessions s
LEFT JOIN sys.dm_exec_connections c
ON s.session_id = c.session_id
LEFT JOIN sys.dm_db_task_space_usage tsu
ON tsu.session_id = s.session_id
LEFT JOIN sys.dm_os_tasks t
ON t.session_id = tsu.session_id
AND t.request_id = tsu.request_id
LEFT JOIN sys.dm_exec_requests r
ON r.session_id = tsu.session_id
AND r.request_id = tsu.request_id
OUTER APPLY sys.dm_exec_sql_text(r.sql_handle) TSQL
This way you can get a TotalPagesAllocated
which can help you figure out the spid
that is taking all the server resources. There has lots of times when I can't even bring up activity monitor and use these sys
views to see what's going on.
I would recommend you reading the following article. I got this reference from here.
This worked for me (using jQuery 2.1)
$(document).ajaxSend(function(elm, xhr, s){
if (s.type == "POST") {
s.data += s.data?"&":"";
s.data += "_token=" + $('#csrf-token').val();
}
});
or this:
$(document).ajaxSend(function(elm, xhr, s){
if (s.type == "POST") {
xhr.setRequestHeader('x-csrf-token', $('#csrf-token').val());
}
});
(where #csrf-token is the element containing the token)
Try sorting index after concatenating them
result=pd.concat([df1,df2]).sort_index()
I would prefer storing keys and values on separate arrays. This i often more practical. Structures of arrays are perfect replacement to array of structures. As most of the time you have to process only a subset of your data (in this cases keys or values, operation only with only one of the two arrays would be more efficient than operating with half of the two arrays together.
But in case this way is not possible, I would suggest to use arrays sorted by column instead of by row. In this way you would have the same benefit as having two arrays, but packed only in one.
import numpy as np
result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442}
names = 0
values = 1
array = np.empty(shape=(2, len(result)), dtype=float)
array[names] = result.keys()
array[values] = result.values()
But my favorite is this (simpler):
import numpy as np
result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442}
arrays = {'names': np.array(result.keys(), dtype=float),
'values': np.array(result.values(), dtype=float)}
It's funny such a question can get so many answers, and yet none fit my requirements :) There are so many languages around, a full language agnostic solution is AFAIK not really possible, as others has mentionned that the FormC or FormD are giving issues.
Since the original question was related to French, the simplest working answer is indeed
public static string ConvertWesternEuropeanToASCII(this string str)
{
return Encoding.ASCII.GetString(Encoding.GetEncoding(1251).GetBytes(str));
}
1251 should be replaced by the encoding code of the input language.
This however replace only one character by one character. Since I am also working with German as input, I did a manual convert
public static string LatinizeGermanCharacters(this string str)
{
StringBuilder sb = new StringBuilder(str.Length);
foreach (char c in str)
{
switch (c)
{
case 'ä':
sb.Append("ae");
break;
case 'ö':
sb.Append("oe");
break;
case 'ü':
sb.Append("ue");
break;
case 'Ä':
sb.Append("Ae");
break;
case 'Ö':
sb.Append("Oe");
break;
case 'Ü':
sb.Append("Ue");
break;
case 'ß':
sb.Append("ss");
break;
default:
sb.Append(c);
break;
}
}
return sb.ToString();
}
It might not deliver the best performance, but at least it is very easy to read and extend. Regex is a NO GO, much slower than any char/string stuff.
I also have a very simple method to remove space:
public static string RemoveSpace(this string str)
{
return str.Replace(" ", string.Empty);
}
Eventually, I am using a combination of all 3 above extensions:
public static string LatinizeAndConvertToASCII(this string str, bool keepSpace = false)
{
str = str.LatinizeGermanCharacters().ConvertWesternEuropeanToASCII();
return keepSpace ? str : str.RemoveSpace();
}
And a small unit test to that (not exhaustive) which pass successfully.
[TestMethod()]
public void LatinizeAndConvertToASCIITest()
{
string europeanStr = "Bonjour ça va? C'est l'été! Ich möchte ä Ä á à â ê é è ë Ë É ï Ï î í ì ó ò ô ö Ö Ü ü ù ú û Û ý Ý ç Ç ñ Ñ";
string expected = "Bonjourcava?C'estl'ete!IchmoechteaeAeaaaeeeeEEiIiiiooooeOeUeueuuuUyYcCnN";
string actual = europeanStr.LatinizeAndConvertToASCII();
Assert.AreEqual(expected, actual);
}
You can write:
python
import keras
keras.__version__
You could add \singlespacing near the beginning of your table. See the setspace instructions for more options.
Your script is blocked from executing due to the execution policy.
You need to run PowerShell as administrator and set it on the client PC to Unrestricted. You can do that by calling Invoke with:
Set-ExecutionPolicy Unrestricted
Whether to use a HashSet<> or List<> comes down to how you need to access your collection. If you need to guarantee the order of items, use a List. If you don't, use a HashSet. Let Microsoft worry about the implementation of their hashing algorithms and objects.
A HashSet will access items without having to enumerate the collection (complexity of O(1) or near it), and because a List guarantees order, unlike a HashSet, some items will have to be enumerated (complexity of O(n)).
Within the WordPress admin interface do the following:
Go to admin setting
Click on permalink and select post name in radio button.
Scroll down and you will see .htaccess
code here like.
<IfModule mod_rewrite.c>
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /wordpress/index.php [L]
</IfModule>
.htaccess
file.If you came here to find out about how to check WordPress version programmatically, then you can do it with the following code.
// Get the WP Version global.
global $wp_version;
// Now use $wp_version which will return a string value.
echo '<pre>' . var_dump( $wp_version ) . '</pre>';
// Output: string '4.6.1' (length=5)
Cheers!
+= is an assignment. When you use it you're really saying ‘some_list2= some_list2+['something']’. Assignments involve rebinding, so:
l= []
def a1(x):
l.append(x) # works
def a2(x):
l= l+[x] # assign to l, makes l local
# so attempt to read l for addition gives UnboundLocalError
def a3(x):
l+= [x] # fails for the same reason
The += operator should also normally create a new list object like list+list normally does:
>>> l1= []
>>> l2= l1
>>> l1.append('x')
>>> l1 is l2
True
>>> l1= l1+['x']
>>> l1 is l2
False
However in reality:
>>> l2= l1
>>> l1+= ['x']
>>> l1 is l2
True
This is because Python lists implement __iadd__() to make a += augmented assignment short-circuit and call list.extend() instead. (It's a bit of a strange wart this: it usually does what you meant, but for confusing reasons.)
In general, if you're appending/extended an existing list, and you want to keep the reference to the same list (instead of making a new one), it's best to be explicit and stick with the append()/extend() methods.
You could use .each()
with .children()
and a selector within the parenthesis:
//Grab Each Instance of Box.
$(".box").each(function(i){
//For Each Instance, grab a child called .something1. Fade It Out.
$(this).children(".something1").fadeOut();
});
The following code will work ISA.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,
IServiceProvider serviceProvider)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseIdentity();
// Add external authentication middleware below. To configure them please see https://go.microsoft.com/fwlink/?LinkID=532715
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
CreateRolesAndAdminUser(serviceProvider);
}
private static void CreateRolesAndAdminUser(IServiceProvider serviceProvider)
{
const string adminRoleName = "Administrator";
string[] roleNames = { adminRoleName, "Manager", "Member" };
foreach (string roleName in roleNames)
{
CreateRole(serviceProvider, roleName);
}
// Get these value from "appsettings.json" file.
string adminUserEmail = "[email protected]";
string adminPwd = "_AStrongP1@ssword!";
AddUserToRole(serviceProvider, adminUserEmail, adminPwd, adminRoleName);
}
/// <summary>
/// Create a role if not exists.
/// </summary>
/// <param name="serviceProvider">Service Provider</param>
/// <param name="roleName">Role Name</param>
private static void CreateRole(IServiceProvider serviceProvider, string roleName)
{
var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
Task<bool> roleExists = roleManager.RoleExistsAsync(roleName);
roleExists.Wait();
if (!roleExists.Result)
{
Task<IdentityResult> roleResult = roleManager.CreateAsync(new IdentityRole(roleName));
roleResult.Wait();
}
}
/// <summary>
/// Add user to a role if the user exists, otherwise, create the user and adds him to the role.
/// </summary>
/// <param name="serviceProvider">Service Provider</param>
/// <param name="userEmail">User Email</param>
/// <param name="userPwd">User Password. Used to create the user if not exists.</param>
/// <param name="roleName">Role Name</param>
private static void AddUserToRole(IServiceProvider serviceProvider, string userEmail,
string userPwd, string roleName)
{
var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
Task<ApplicationUser> checkAppUser = userManager.FindByEmailAsync(userEmail);
checkAppUser.Wait();
ApplicationUser appUser = checkAppUser.Result;
if (checkAppUser.Result == null)
{
ApplicationUser newAppUser = new ApplicationUser
{
Email = userEmail,
UserName = userEmail
};
Task<IdentityResult> taskCreateAppUser = userManager.CreateAsync(newAppUser, userPwd);
taskCreateAppUser.Wait();
if (taskCreateAppUser.Result.Succeeded)
{
appUser = newAppUser;
}
}
Task<IdentityResult> newUserRole = userManager.AddToRoleAsync(appUser, roleName);
newUserRole.Wait();
}
You can have it on github using the command
git clone https://github.com/coreutils/coreutils.git
You can find all the source codes in the src folder.
You need to have git installed.
Things have changed since 2012, ls
source code has now 5309 lines
Hope this works i am writing on prima vista
SELECT COUNT(*)
FROM DocumentOutputItems
GROUP BY DocumentId, DocumentSessionId
I'm told that it's bad practice to overuse it, but you can always add !important
after your code to prioritize the css properties value.
.p{height:400px!important;}
First export the schema metadata:
expdp dumpfile=filename logfile=logname directory=dir_name schemas=schema_name
and then import by using the sqlfile
option (it will not import data it will just write the schema DDL to that file)
impdp dumpfile=filename logfile=logname directory=dir_name sqlfile=ddl.sql
You could create a custom pipe to return the list of key for each element. Something like that:
import { PipeTransform, Pipe } from '@angular/core';
@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
transform(value, args:string[]) : any {
let keys = [];
for (let key in value) {
keys.push(key);
}
return keys;
}
}
and use it like that:
<tr *ngFor="let c of content">
<td *ngFor="let key of c | keys">{{key}}: {{c[key]}}</td>
</tr>
Edit
You could also return an entry containing both key and value:
@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
transform(value, args:string[]) : any {
let keys = [];
for (let key in value) {
keys.push({key: key, value: value[key]});
}
return keys;
}
}
and use it like that:
<span *ngFor="let entry of content | keys">
Key: {{entry.key}}, value: {{entry.value}}
</span>
When FIND
returns #VALUE!
, it is an error, not a string, so you can't compare FIND(...)
with "#VALUE!"
, you need to check if FIND
returns an error with ISERROR
. Also FIND
can work on multiple characters.
So a simplified and working version of your formula would be:
=IF(ISERROR(FIND("abc",A1))=FALSE, "Green", IF(ISERROR(FIND("xyz",A1))=FALSE, "Yellow", "Red"))
Or, to remove the double negations:
=IF(ISERROR(FIND("abc",A1)), IF(ISERROR(FIND("xyz",A1)), "Red", "Yellow"),"Green")
check out this solution... works for me >> https://jsfiddle.net/y49jpdns/
<html lang="en" class="no-js">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<style>
html body {width: 100%;height: 100%;padding: 0px;margin: 0px;overflow: hidden;font-family: arial;font-size: 10px;color: #6e6e6e;background-color: #000;} #preview-frame {width: 100%;background-color: #fff;}</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
var calcHeight = function() {
$('#preview-frame').height($(window).height());
}
$(document).ready(function() {
calcHeight();
});
$(window).resize(function() {
calcHeight();
}).load(function() {
calcHeight();
});
</script>
</head>
<body>
<iframe id="preview-frame" src="http://leowebguy.com/" name="preview-frame" frameborder="0" noresize="noresize">
</iframe>
</body>
</html>
[PrincipalPermission(SecurityAction.Demand, Role = @"BUILTIN\Administrators")]
This will do it without UAC - no need to start a new process. If the running user is member of Admin group as for my case.
The first solution is to use the java.util.Random
class:
import java.util.Random;
Random rand = new Random();
// Obtain a number between [0 - 49].
int n = rand.nextInt(50);
// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
n += 1;
Another solution is using Math.random()
:
double random = Math.random() * 49 + 1;
or
int random = (int)(Math.random() * 50 + 1);
var count = $('.' + myclassname).length;
Neither is better than the other, they do exactly the same thing. However, using .encode()
and .decode()
is the more common way to do it. It is also compatible with Python 2.
Not an answer to the original question. But this might help someone.
To see the changes you have done (know which files are marked as --assume-unchanged)
git ls-files -v
The resulted list of files will have a prefix with one character (ex : H or h) If it is a lowercase (i.e. h) then the file was marked --assume-unchanged
There is no need to add if{}else{} control flow. Initialise the button texts for different states at the View or ViewController constructor:
[btnCheckButton setTitle:@"Normal" forState:UIControlStateNormal]; [btnCheckButton setTitle:@"Selected" forState:UIControlStateSelected];
Then switch the button state to Selected:
[btnCheckButton setSelected:YES];
Then switch the button state to Normal:
[btnCheckButton setSelected:NO];
Thanks to jveirasv for the answer above.
If you need to remove duplicates of a specific sets of column, you can use this (if you have a timestamp in the table that vary for example)
CREATE TABLE TableA_Verify AS SELECT * FROM TableA WHERE 1 GROUP BY [COLUMN TO remove duplicates BY];
DELETE FROM TableA;
INSERT INTO TableA SELECT * FROM TAbleA_Verify;
DROP TABLE TableA_Verify;
Form1 OpenNewForm = new Form1();
OpenNewForm.Show();
"OpenNewForm" is the name of the Form. In the second the form opens.
If you want to close the previous form:
this.Close();
Interesting observation: Tried to copy the same file via various java classes and printed time in nano seconds.
Duration using FileOutputStream byte stream: 4 965 078
Duration using BufferedOutputStream: 1 237 206
Duration using (character text Reader: 2 858 875
Duration using BufferedReader(Buffered character text stream: 1 998 005
Duration using (Files NIO copy): 18 351 115
when using Files Nio copy option it took almost 18 times longer!!! Nio is the slowest option to copy files and BufferedOutputStream looks like the fastest. I used the same simple text file for each class.
Using Backtick
Backticks are commonly used for multi-line strings or when you want to interpolate an expression within your string
let title = 'John';_x000D_
let address = 'address';_x000D_
let address2 = 'address2222';_x000D_
let address3 = 'address33333';_x000D_
let address4 = 'address44444';_x000D_
document.getElementById("address_box").innerText = `${title} _x000D_
${address}_x000D_
${address2}_x000D_
${address3} _x000D_
${address4}`;
_x000D_
<div id="address_box">_x000D_
</div>
_x000D_
instead put this in your functions.php works fine, no redirect problems.
function fix_slash( $string, $type )
{
global $wp_rewrite;
if ( $wp_rewrite->use_trailing_slashes == false )
{
if ( $type != 'single' && $type != 'category' )
return trailingslashit( $string );
if ( $type == 'single' && ( strpos( $string, '.html/' ) !== false ) )
return trailingslashit( $string );
if ( $type == 'category' && ( strpos( $string, 'category' ) !== false ) )
{
$aa_g = str_replace( "/category/", "/", $string );
return trailingslashit( $aa_g );
}
if ( $type == 'category' )
return trailingslashit( $string );
}
return $string;
}
add_filter( 'user_trailingslashit', 'fix_slash', 55, 2 );
Here's a short code that might help.
<yourJFrameName> main = new <yourJFrameName>();
main.setVisible(true);
this.dispose();
where...
main.setVisible(true);
will run the JFrame again.
this.dispose();
will terminate the running window.
What could be easier than something like this:
import tempfile
for i in range(400):
with tempfile.TemporaryFile() as tf:
for j in range(1000):
tf.write('Line {} of file {}'.format(j,i))
That creates 400 temp files and writes 1000 lines to each temp file. It executes in less than 1/2 second on my unremarkable machine. Each temp file of the total is created and deleted as the context manager opens and closes in this case. It is fast, secure, and cross platform.
Using tempfile is a lot better than trying to reinvent it.
As this has already been properly answered, I'd just add the following site as a reference:
You can search for "check", for example.
I have just upgraded the Ubuntu Server version from 12.04 LTS to 14.04 LTS.
Indeed, as said above, the .conf extension to Apache 2.4.x is needed to the websites vhost files that resides on sites-available directory.
Before read this question I did not have a clue what was going on with the server.
Pretty nice solution.
Just summarizing I did the following steps on Terminal:
1) Access sites-enabled folder
$ cd /etc/apache2/sites-enabled
2) Because the command a2dissite will not work with deprecated files (without .conf) remove the old website files that was published
$ sudo rm <my-old-website-without-.conf>
3) Rename the website vhost files changing its extension adding .conf to the end
$ sudo mv /etc/apache2/sites-available/mywebsite /etc/apache2/sites-available/mywebsite.conf
4) Republish the new and correct vhost file
$ sudo a2ensite mywebsite.conf
5) Check the website on browser and have fun! :)
Update: Current Spring cache implementation uses all method parameters as the cache key if not specified otherwise. If you want to use selected keys, refer to Arjan's answer which uses SpEL list {#isbn, #includeUsed}
which is the simplest way to create unique keys.
From Spring Documentation
The default key generation strategy changed with the release of Spring 4.0. Earlier versions of Spring used a key generation strategy that, for multiple key parameters, only considered the hashCode() of parameters and not equals(); this could cause unexpected key collisions (see SPR-10237 for background). The new 'SimpleKeyGenerator' uses a compound key for such scenarios.
Before Spring 4.0
I suggest you to concat the values of the parameters in Spel expression with something like key="#checkWarehouse.toString() + #isbn.toString()")
, I believe this should work as org.springframework.cache.interceptor.ExpressionEvaluator returns Object, which is later used as the key so you don't have to provide an int
in your SPEL expression.
As for the hash code with a high collision probability - you can't use it as the key.
Someone in this thread has suggested to use T(java.util.Objects).hash(#p0,#p1, #p2)
but it WILL NOT WORK and this approach is easy to break, for example I've used the data from SPR-9377 :
System.out.println( Objects.hash("someisbn", new Integer(109), new Integer(434)));
System.out.println( Objects.hash("someisbn", new Integer(110), new Integer(403)));
Both lines print -636517714 on my environment.
P.S. Actually in the reference documentation we have
@Cacheable(value="books", key="T(someType).hash(#isbn)")
public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)
I think that this example is WRONG and misleading and should be removed from the documentation, as the keys should be unique.
P.P.S. also see https://jira.springsource.org/browse/SPR-9036 for some interesting ideas regarding the default key generation.
I'd like to add for the sake of correctness and as an entertaining mathematical/computer science fact that unlike built-in hash, using a secure cryptographic hash function like MD5 or SHA256, due to the properties of such function IS absolutely possible for this task, but to compute it every time may be too expensive, checkout for example Dan Boneh cryptography course to learn more.
This means that you must declare strict mode by writing "use strict"
at the beginning of the file or the function to use block-scope declarations.
EX:
function test(){
"use strict";
let a = 1;
}
Parse
throws an exception if it cannot parse the value, whereas TryParse
returns a bool
indicating whether it succeeded.
TryParse
does not just try
/catch
internally - the whole point of it is that it is implemented without exceptions so that it is fast. In fact the way it is most likely implemented is that internally the Parse
method will call TryParse
and then throw an exception if it returns false
.
In a nutshell, use Parse
if you are sure the value will be valid; otherwise use TryParse
.
Here is a YouTube video that explains exactly what you're wanting to do: Save and load a Keras model
There are three different saving methods that Keras makes available. These are described in the video link above (with examples), as well as below.
First, the reason you're receiving the error is because you're calling load_model
incorrectly.
To save and load the weights of the model, you would first use
model.save_weights('my_model_weights.h5')
to save the weights, as you've displayed. To load the weights, you would first need to build your model, and then call load_weights
on the model, as in
model.load_weights('my_model_weights.h5')
Another saving technique is model.save(filepath)
. This save
function saves:
To load this saved model, you would use the following:
from keras.models import load_model
new_model = load_model(filepath)'
Lastly, model.to_json()
, saves only the architecture of the model. To load the architecture, you would use
from keras.models import model_from_json
model = model_from_json(json_string)
In the case you need to force the reinstallation of pip itself you can do:
python -m pip install --upgrade --force-reinstall pip
Recently, I have tried to develop a simple web app that uses drag and drop components and has lines connecting them. I came across these two simple and amazing javascript libraries:
Working example link (usage: click on add scene to create a draggable, click on add choice to draw a leader line between two different draggables)
try: android:editable="false"
or android:inputType="none"
The construction like this: $('[data-XXX=111]')
isn't working in Safari 8.0.
If you set data attribute this way: $('div').data('XXX', 111)
, it only works if you set data attribute directly in DOM like this: $('div').attr('data-XXX', 111)
.
I think it's because jQuery team optimized garbage collector to prevent memory leaks and heavy operations on DOM rebuilding on each change data attribute.
If you have LaTeX installed you can download as PDF directly from Jupyter notebook with File -> Download as -> PDF via LaTeX (.pdf). Otherwise follow these two steps.
For HTML output, you should now use Jupyter in place of IPython and select File -> Download as -> HTML (.html) or run the following command:
jupyter nbconvert --to html notebook.ipynb
This will convert the Jupyter document file notebook.ipynb into the html output format.
Google Colaboratory is Google's free Jupyter notebook environment that requires no setup and runs entirely in the cloud. If you are using Google Colab the commands are the same, but Google Colab only lets you download .ipynb or .py formats.
Convert the html file notebook.html into a pdf file called notebook.pdf. In Windows, Mac or Linux, install wkhtmltopdf. wkhtmltopdf is a command line utility to convert html to pdf using WebKit. You can download wkhtmltopdf from the linked webpage, or in many Linux distros it can be found in their repositories.
wkhtmltopdf notebook.html notebook.pdf
Original (now almost obsolete) revision: Convert the IPython notebook file to html.
ipython nbconvert --to html notebook.ipynb
This works for me:
$(function () {
$('#datetimepicker5').datetimepicker({
use24hours: true,
format: 'HH:mm'
});
});
Important: It only worked at the point I used uppercase "H" as time format.
Just Javascript (as requested)
Add this function somewhere on your page (preferably in the <head>
)
function clearBox(elementID)
{
document.getElementById(elementID).innerHTML = "";
}
Then add the button on click event:
<button onclick="clearBox('cart_item')" />
In JQuery (for reference)
If you prefer JQuery you could do:
$("#cart_item").html("");
You can use the DataGridViewColumn.Width property to do it:
DataGridViewColumn column = dataGridView.Columns[0];
column.Width = 60;
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcolumn.width.aspx
To generate an area where you can specify a description for the function and each parameter for the function, type the following on the line before your function and hit Enter:
C#: ///
VB: '''
See Recommended Tags for Documentation Comments (C# Programming Guide) for more info on the structured content you can include in these comments.
CREATE DATABASE hindi_test
CHARACTER SET utf8
COLLATE utf8_unicode_ci;
USE hindi_test;
CREATE TABLE `hindi` (`data` varchar(200) COLLATE utf8_unicode_ci NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `hindi` (`data`) VALUES('????????');
I found following program works for me
test1.sh
a=xxx
test2.sh $a
in test2.sh you use $1
to refer variable a
in test1.sh
echo $1
The output would be xxx
I prefer way of "Rosdi Kasim" as that's doesn't require detail configuration on the IP.
I will definitely forget it again when I try to up another server again.
Keep It Simple Stupid (KISS) by simply enable the Sql Server Browser service, then add the \SQLEXPRESS behind the IP when you connect the server.
Direct using IP without "\SQLEXPRESS" was my point of failure as it doesn't use the default port.
Thanks.
If you use the request body in a GET request, you're breaking the REST principle, because your GET request won't be able to be cached, because cache system uses only the URL.
What's worse, your URL can't be bookmarked, because the URL doesn't contain all the information needed to redirect the user to this page.
Use URL or Query parameters instead of request body parameters, e.g.:
/myapp?var1=xxxx&var2=xxxx
/myapp;var1=xxxx/resource;var2=xxxx
In fact, the HTTP RFC 7231 says that:
A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request.
For more information take a look here.
After the file name in the HTML code I add ?forcedownload=1
This has been the simplest way for me to trigger a dialog box to save or download.
I have used this to remove unwanted words from text files:
bad_words = ['abc', 'def', 'ghi', 'jkl']
with open('List of words.txt') as badfile, open('Clean list of words.txt', 'w') as cleanfile:
for line in badfile:
clean = True
for word in bad_words:
if word in line:
clean = False
if clean == True:
cleanfile.write(line)
Or to do the same for all files in a directory:
import os
bad_words = ['abc', 'def', 'ghi', 'jkl']
for root, dirs, files in os.walk(".", topdown = True):
for file in files:
if '.txt' in file:
with open(file) as filename, open('clean '+file, 'w') as cleanfile:
for line in filename:
clean = True
for word in bad_words:
if word in line:
clean = False
if clean == True:
cleanfile.write(line)
I'm sure there must be a more elegant way to do it, but this did what I wanted it to.
Simple code for dynamic array. In below code then array will become full of size we copy all element to new double size array(variable size array).sample code is below
public class DynamicArray {
static int []increaseSizeOfArray(int []arr){
int []brr=new int[(arr.length*2)];
for (int i = 0; i < arr.length; i++) {
brr[i]=arr[i];
}
return brr;
}
public static void main(String[] args) {
int []arr=new int[5];
for (int i = 0; i < 11; i++) {
if (i<arr.length) {
arr[i]=i+100;
}
else {
arr=increaseSizeOfArray(arr);
arr[i]=i+100;
}
}
for (int i = 0; i < arr.length; i++) {
System.out.println("arr="+arr[i]);
}
}
}
Source : How to make dynamic array
You just needed to read a little further and you would have been introduced to the *ngIf structural directive.
selectedHero.name doesn't exist yet because the user has yet to select a hero so it returns undefined.
<div *ngIf="selectedHero">
<h2>{{selectedHero.name}} details!</h2>
<div><label>id: </label>{{selectedHero.id}}</div>
<div>
<label>name: </label>
<input [(ngModel)]="selectedHero.name" placeholder="name"/>
</div>
</div>
The *ngIf directive keeps selectedHero off the DOM until it is selected and therefore becomes truthy.
This document helped me understand structural directives.
If there is no bulk insert into mongodb, we loop all objects in the small_collection
and insert them one by one into the big_collection
:
db.small_collection.find().forEach(function(obj){
db.big_collection.insert(obj)
});
use array_map()
:
$yourArray = array_map('strtolower', $yourArray);
In case you need to lowercase nested array (by Yahya Uddin):
$yourArray = array_map('nestedLowercase', $yourArray);
function nestedLowercase($value) {
if (is_array($value)) {
return array_map('nestedLowercase', $value);
}
return strtolower($value);
}
I have created a tool that combines dex2jar, jd-core and apktool: https://github.com/dirkvranckaert/AndroidDecompiler Just checkout the project locally and run the script as documented and you'll get all the resources and sources decompiled.
$('input[name="testing"]').val(theValue);
Method 1
Client : Send as JSON
$.ajax({
url: 'example.com/ajax/',
type: 'POST',
contentType: 'application/json; charset=utf-8',
processData: false,
data: JSON.stringify({'name':'John', 'age': 42}),
...
});
//Sent as a JSON object {'name':'John', 'age': 42}
Server :
data = json.loads(request.body) # {'name':'John', 'age': 42}
Method 2
Client : Send as x-www-form-urlencoded
(Note: contentType
& processData
have changed, JSON.stringify
is not needed)
$.ajax({
url: 'example.com/ajax/',
type: 'POST',
data: {'name':'John', 'age': 42},
contentType: 'application/x-www-form-urlencoded; charset=utf-8', //Default
processData: true,
});
//Sent as a query string name=John&age=42
Server :
data = request.POST # will be <QueryDict: {u'name':u'John', u'age': 42}>
Changed in 1.5+ : https://docs.djangoproject.com/en/dev/releases/1.5/#non-form-data-in-http-requests
Non-form data in HTTP requests :
request.POST will no longer include data posted via HTTP requests with non form-specific content-types in the header. In prior versions, data posted with content-types other than multipart/form-data or application/x-www-form-urlencoded would still end up represented in the request.POST attribute. Developers wishing to access the raw POST data for these cases, should use the request.body attribute instead.
Probably related
I've tried many times.
And at last I just put autoindex on;
in http
but outside of server
, and it's OK.
Instead of trying to disable the browser back button it's better to support it. .NET 3.5 can very well handle the browser back (and forward) buttons. Search with Google: "Scriptmanager EnableHistory". You can control which user actions will add an entry to the browser's history (ScriptManager -> AddHistoryPoint) and your ASP.NET application receives an event whenever the user clicks the browser Back/Forward buttons. This will work for all known browsers
There's also SSH Key - Still asking for password and passphrase
Using ssh-add ~/.ssh/id_rsa
without a local keychain.
This avoids having to mess with tokens.
It is important to note that 'undefined' is a perfectly valid value for a variable to hold. If you want to check if the variable exists at all,
if (window.variableName)
is a more complete check, since it is verifying that the variable has actually been defined. However, this is only useful if the variable is guaranteed to be an object! In addition, as others have pointed out, this could also return false if the value of variableName is false, 0, '', or null.
That said, that is usually not enough for our everyday purposes, since we often don't want to have an undefined value. As such, you should first check to see that the variable is defined, and then assert that it is not undefined using the typeof operator which, as Adam has pointed out, will not return undefined unless the variable truly is undefined.
if ( variableName && typeof variableName !== 'undefined' )
The difference is in the arguments. It's very common to generate a random number from a uniform distribution in the range [0.0, 1.0), so random.random()
just does this. Use random.uniform(a, b)
to specify a different range.
Simple solution : ES6 Features "includes" method
let arr = [1, 2, 3, 2, 3, 2, 3, 4];
arr.includes(2) // true
arr.includes(93) // false
JavaScript:
var d = new Date();_x000D_
var n = d.getTimezoneOffset();_x000D_
var timezone = n / -60;_x000D_
console.log(timezone);
_x000D_
There's a jquery plugin http://www.asual.com/jquery/address/
I think this is what you need.
I was encountering the following error: The requested package my-foo/bar could not be found in any version, there may be a typo in the package name.
If you're forking another repo to make your own changes you will end up with a new repository.
E.g:
https://github.com/foo/bar.git
=>
https://github.com/my-foo/bar.git
The new url will need to go into your repositories section of your composer.json.
Remember if you want refer to your fork as my-foo/bar
in your require section, you will have to rename the package in the composer.json
file inside of your new repo.
{
"name": "foo/bar",
=>
{
"name": "my-foo/bar",
If you've just forked the easiest way to do this is edit it right inside github.
After looking on the accepted answer I realized that if know size of required vector then we have to use a loop to initialize every element
But I found new to do this using default_structure_element like following...
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
typedef struct subject {
string name;
int marks;
int credits;
}subject;
int main(){
subject default_subject;
default_subject.name="NONE";
default_subject.marks = 0;
default_subject.credits = 0;
vector <subject> sub(10,default_subject); // default_subject to initialize
//to check is it initialised
for(ll i=0;i<sub.size();i++) {
cout << sub[i].name << " " << sub[i].marks << " " << sub[i].credits << endl;
}
}
Then I think its good to way to initialize a vector of the struct, isn't it?
You can delete by 1 or more properties:
//Delets an json object from array by given object properties.
//Exp. someJasonCollection.deleteWhereMatches({ l: 1039, v: '3' }); ->
//removes all items with property l=1039 and property v='3'.
Array.prototype.deleteWhereMatches = function (matchObj) {
var indexes = this.findIndexes(matchObj).sort(function (a, b) { return b > a; });
var deleted = 0;
for (var i = 0, count = indexes.length; i < count; i++) {
this.splice(indexes[i], 1);
deleted++;
}
return deleted;
}
use the itoa()
function included in stdlib.h
char buffer[7]; //the ASCII of the integer will be stored in this char array
itoa(-31596,buffer,10); //(integer, yourBuffer, base)
In your code, jQuery just looks for the first instance of an input with name q12_3
, which in this case has a value of 1
. You want an input with name q12_3
that is :checked
.
$("#submit").click(() => {_x000D_
const val = $('input[name=q12_3]:checked').val();_x000D_
alert(val);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<table>_x000D_
<tr>_x000D_
<td>Sales Promotion</td>_x000D_
<td><input type="radio" name="q12_3" value="1">1</td>_x000D_
<td><input type="radio" name="q12_3" value="2">2</td>_x000D_
<td><input type="radio" name="q12_3" value="3">3</td>_x000D_
<td><input type="radio" name="q12_3" value="4">4</td>_x000D_
<td><input type="radio" name="q12_3" value="5">5</td>_x000D_
</tr>_x000D_
</table>_x000D_
<button id="submit">submit</button>
_x000D_
Note that the above code is not the same as using .is(":checked")
. jQuery's is()
function returns a boolean (true or false) and not (an) element(s).
Because this answer keeps getting a lot of attention, I'll also include a vanilla JavaScript snippet.
document.querySelector("#submit").addEventListener("click", () => {_x000D_
const val = document.querySelector("input[name=q12_3]:checked").value;_x000D_
alert(val);_x000D_
});
_x000D_
<table>_x000D_
<tr>_x000D_
<td>Sales Promotion</td>_x000D_
<td><input type="radio" name="q12_3" value="1">1</td>_x000D_
<td><input type="radio" name="q12_3" value="2">2</td>_x000D_
<td><input type="radio" name="q12_3" value="3">3</td>_x000D_
<td><input type="radio" name="q12_3" value="4">4</td>_x000D_
<td><input type="radio" name="q12_3" value="5">5</td>_x000D_
</tr>_x000D_
</table>_x000D_
<button id="submit">submit</button>
_x000D_
You should use Ctrl+shift+enter when using the =SUM(VLOOKUP(A9,A1:D5,{2,3,4,},FALSE)) that results in {=SUM(VLOOKUP(A9,A1:D5,{2,3,4,},FALSE))} en also works.
If you want to keep only numbers then use /[^0-9]+/
instead of /[^a-zA-Z]+/
I'm agree with most of things said here, but I just want to point out an argument in favor of Underscore.js: the size of the library.
Specially in case you are developing an app or website which intend to be use mostly on mobile devices, the size of the resulting bundle and the effect on the boot or download time may have an important role.
For comparison, these sizes are those I noticed with source-map-explorer after running Ionic serve:
Lodash: 523 kB
Underscore.js: 51.6 kB
One can use BundlePhobia to check the current size of Lodash and Underscore.js.
I've added to /etc/sysconfig/jenkins (CentOS):
# Options to pass to java when running Jenkins.
#
JENKINS_JAVA_OPTIONS="-Djava.awt.headless=true -Xmx1024m -XX:MaxPermSize=512m"
For ubuntu the same config should be located in /etc/default
Do not even try to use flex; stay with css grid!! :)
https://jsfiddle.net/ctt3bqr0/
place-self: center;
is doing the centering work here.
If you want to center something that is inside div
that is inside grid cell you need to define nested grid in order to make it work. (Please look at the fiddle both examples shown there.)
https://css-tricks.com/snippets/css/complete-guide-grid/
Cheers!
Before the return statement in you main, insert this code:
system("pause");
This will hold the console until you hit a key.
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s;
cout << "Please enter your first name followed by a newline\n";
cin >> s;
cout << "Hello, " << s << '\n';
system("pause");
return 0; // this return statement isn't necessary
}
byte[] a = new byte[50];
char [] cArray= System.Text.Encoding.ASCII.GetString(a).ToCharArray();
From the URL thedixon posted
http://bytes.com/topic/c-sharp/answers/250261-byte-char
You cannot ToCharArray the byte without converting it to a string first.
To quote Jon Skeet there
There's no need for the copying here - just use Encoding.GetChars. However, there's no guarantee that ASCII is going to be the appropriate encoding to use.
In windows, put your php.exe file in windows/system32 or any other system executable folders and then go to command line and type php and hit enter following it, if it doesnt generate any error then you are ready to use PHP on command line. If you have set your php.exe somewhere else than default system folders then you need to set the path of it in the environment variables! You can get there in following path....
control panel -> System -> Edith the environment variables of your account -> Environment Vaiables -> path -> edit then set the absolute path of your php.exe there and follow the same procedure as in first paragraph, if nothing in the error department, then you are ready to use php from command line!
This should work:
@interface MyClass
{
int _doubleDigits[10];
}
@property(readonly) int *doubleDigits;
@end
@implementation MyClass
- (int *)doubleDigits
{
return _doubleDigits;
}
@end
If you don't have an existing local branch, it is truly as simple as:
git fetch
git checkout <remote-branch-name>
For instance if you fetch and there is a new remote tracking branch called origin/feature/Main_Page
, just do this:
git checkout feature/Main_Page
This creates a local branch with the same name as the remote branch, tracking that remote branch. If you have multiple remotes with the same branch name, you can use the less ambiguous:
git checkout -t <remote>/<remote-branch-name>
If you already made the local branch and don't want to delete it, see How do you make an existing Git branch track a remote branch?.
If both the list are too big and when we use lamda expression then it will take a long time to fetch . Better to use linq in this case to fetch parameters list:
var items = (from x in parameters
join y in myStrings on x.Source equals y
select x)
.ToList();
I would suggest TARGET_FILE_DIR
if you want the file to be copied to the same folder as your .exe file.
$ Directory of main file (.exe, .so.1.2, .a).
add_custom_command(
TARGET ${PROJECT_NAME} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy
${CMAKE_CURRENT_SOURCE_DIR}/input.txt
$<TARGET_FILE_DIR:${PROJECT_NAME}>)
In VS, this cmake script will copy input.txt to the same file as your final exe, no matter it's debug or release.
for me, this worked
exec utl_mail.send@myotherdb(
sender => '[email protected]',recipients => '[email protected],
cc => null, subject => 'my subject', message => 'my message'
);
The other solutions here either don't account for external links (that you probably want to open externally in Safari) or don't account for relative links (without the domain in them).
The html5 mobile-boilerplate project links to this gist which has a good discussion on the topic: https://gist.github.com/1042026
Here's the final code they came up with:
<script>(function(a,b,c){if(c in b&&b[c]){var d,e=a.location,f=/^(a|html)$/i;a.addEventListener("click",function(a){d=a.target;while(!f.test(d.nodeName))d=d.parentNode;"href"in d&&(d.href.indexOf("http")||~d.href.indexOf(e.host))&&(a.preventDefault(),e.href=d.href)},!1)}})(document,window.navigator,"standalone")</script>
We should have the projects which include (at least) all the filtered tags, or said in a different way, exclude the ones which doesn't include all those filtered tags.
So we can use Linq Except
to get those tags which are not included. Then we can use Count() == 0
to have only those which excluded no tags:
var res = projects.Where(p => filteredTags.Except(p.Tags).Count() == 0);
Or we can make it slightly faster with by replacing Count() == 0
with !Any()
:
var res = projects.Where(p => !filteredTags.Except(p.Tags).Any());
You can use a background image
.application-title img {_x000D_
width:200px;_x000D_
height:200px;_x000D_
box-sizing:border-box;_x000D_
padding-left: 200px;_x000D_
/*width of the image*/_x000D_
background: url(http://lorempixel.com/200/200/city/2) left top no-repeat;_x000D_
}
_x000D_
<div class="application-title">_x000D_
<img src="http://lorempixel.com/200/200/city/1/">_x000D_
</div><br />_x000D_
Original Image: <br />_x000D_
_x000D_
<img src="http://lorempixel.com/200/200/city/1/">
_x000D_
When you use the keyword new
for example JFrame j = new JFrame();
you are creating an instance of the class JFrame
.
The
new
operator instantiates a class by allocating memory for a new object and returning a reference to that memory.
Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class.
Take a look here
Creating Objects
The types of the Java programming language are divided into two categories:
primitive types
andreference
types.
Thereference
types areclass
types,interface
types, andarray
types.
There is also a specialnull
type.
An object is a dynamically created instance of aclass
type or a dynamically createdarray
.
The values of areference
type are references to objects.
Refer Types, Values, and Variables for more information
It looks like placing the click event directly on the button is causing the problem. For some reason it can't find the function. Not sure why...
If you attach the event handler in the javascript, it does work however.
See it here: http://jsfiddle.net/WfBRr/7/
<button id="display-text" type="button">Display text of all options</button>
document.getElementById('display-text').onclick = function () {
var x = document.getElementById("mySelect");
var txt = "All options: ";
var i;
for (i = 0; i < x.length; i++) {
txt = txt + "\n" + x.options[i].value;
}
alert(txt);
}
bootstrap provides various classes for table
<table class="table"></table>
<table class="table table-bordered"></table>
<table class="table table-hover"></table>
<table class="table table-condensed"></table>
<table class="table table-responsive"></table>
How about putting the long text in another <option>
right below and disabling it? Might be a workaround for someone so posting here.
<select>_x000D_
<option>My real option text</option>_x000D_
<option disabled style="font-style:italic"> (...and my really really long option text that is basically a continuation of previous option)</option> _x000D_
<option disabled style="font-style:italic"> (...and still continuing my previous option)</option> _x000D_
<option>Another real option text</option>_x000D_
</select>
_x000D_
The only way is to go an underlying level to the JVM.
df.col._jc.toString().encode('utf8')
This is also how it is converted to a str
in the pyspark code itself.
From pyspark/sql/column.py:
def __repr__(self):
return 'Column<%s>' % self._jc.toString().encode('utf8')
I had a similar issue with mongoose :
fields:
[ '[object Object]',
'[object Object]',
'[object Object]',
'[object Object]' ] }
In fact, I was using "type" as a property name in my schema :
fields: [
{
name: String,
type: {
type: String
},
registrationEnabled: Boolean,
checkinEnabled: Boolean
}
]
To avoid that behavior, you have to change the parameter to :
fields: [
{
name: String,
type: {
type: { type: String }
},
registrationEnabled: Boolean,
checkinEnabled: Boolean
}
]
IPA file are generally executable file for iOS app. Approach used to install IPA in iTunes 12 is different as compared to lower versions.
Simply, add IPA file into iTunes library
and search for IPA
in apps section of connected device.
Click on install and Apply
.
Neither restclient nor REST console support this but curl does.
The HTTP specification says in section 4.3
A message-body MUST NOT be included in a request if the specification of the request method (section 5.1.1) does not allow sending an entity-body in requests.
Section 5.1.1 redirects us to section 9.x for the various methods. None of them explicitly prohibit the inclusion of a message body. However...
Section 5.2 says
The exact resource identified by an Internet request is determined by examining both the Request-URI and the Host header field.
and Section 9.3 says
The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI.
Which together suggest that when processing a GET request, a server is not required to examine anything other that the Request-URI and Host header field.
In summary, the HTTP spec doesn't prevent you from sending a message-body with GET but there is sufficient ambiguity that it wouldn't surprise me if it was not supported by all servers.
Use a Temp Table or a Table variable, e.g.
select 'A' as [value]
into #tmp
union
select 'B'
union
select 'C'
and then
SELECT
blah
FROM foo
WHERE myField IN (select [value] from #tmp)
or
SELECT
f.blah
FROM foo f INNER JOIN #tmp t ON f.myField = t.[value]
Check you have:
1- Access to Internet connectivity.
2- The permission for internet is present in the manifest.
3- The url host is valid and registered in a trusted domain name server.
It turns out after doing a Reference Cleaning, it removed Microsoft.Web.Infrastructure
, but not from the packages.config file. After trying to add it again using the Package Manager Console
, Visual Studio says that it is already installed which is false because it was removed.
I then removed the line of code in the packages.config
file
<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net45" />
and ran the command again
PM> Install-Package Microsoft.Web.Infrastructure
After this, now it works fine.
curl -XGET '{{IP/localhost}}:9200/{{Index name}}/{{type}}/_search?scroll=10m&pretty' -d '{
"query": {
"filtered": {
"query": {
"match_all": {}
}}'
Instead, try:
var now = new Date();
current = new Date(now.getFullYear(), now.getMonth()+1, 1);
ng-if on ng-include and on ng-controller will have a big impact matter on ng-include it will not load the required partial and does not process unless flag is true on ng-controller it will not load the controller unless flag is true but the problem is when a flag gets false in ng-if it will remove from DOM when flag gets true back it will reload the DOM in this case ng-show is better, for one time show ng-if is better
With the new App Launcher YOUR APPS (not chrome extensions) stored in Users/[yourusername]/Applications/Chrome Apps/
With Bootstrap 4 .hidden-*
classes were completely removed (yes, they were replaced by hidden-*-*
but those classes are also gone from v4 alphas).
Starting with v4-beta, you can combine .d-*-none
and .d-*-block
classes to achieve the same result.
visible-* was removed as well; instead of using explicit .visible-*
classes, make the element visible by not hiding it (again, use combinations of .d-none .d-md-block). Here is the working example:
<div class="col d-none d-sm-block">
<span class="vcard">
…
</span>
</div>
<div class="col d-none d-xl-block">
<div class="d-none d-md-block">
…
</div>
<div class="d-none d-sm-block">
…
</div>
</div>
class="hidden-xs"
becomes class="d-none d-sm-block"
(or d-none d-sm-inline-block) ...
<span class="d-none d-sm-inline">hidden-xs</span>
<span class="d-none d-sm-inline-block">hidden-xs</span>
An example of Bootstrap 4 responsive utilities:
<div class="d-none d-sm-block"> hidden-xs
<div class="d-none d-md-block"> visible-md and up (hidden-sm and down)
<div class="d-none d-lg-block"> visible-lg and up (hidden-md and down)
<div class="d-none d-xl-block"> visible-xl </div>
</div>
</div>
</div>
<div class="d-sm-none"> eXtra Small <576px </div>
<div class="d-none d-sm-block d-md-none d-lg-none d-xl-none"> SMall =576px </div>
<div class="d-none d-md-block d-lg-none d-xl-none"> MeDium =768px </div>
<div class="d-none d-lg-block d-xl-none"> LarGe =992px </div>
<div class="d-none d-xl-block"> eXtra Large =1200px </div>
<div class="d-xl-none"> hidden-xl (visible-lg and down)
<div class="d-lg-none d-xl-none"> visible-md and down (hidden-lg and up)
<div class="d-md-none d-lg-none d-xl-none"> visible-sm and down (or hidden-md and up)
<div class="d-sm-none"> visible-xs </div>
</div>
</div>
</div>
This happened to me, and the results on this page were a good resource that led me in many directions, but I would like to add another possibility:
As stated in other replies, creating a constructor with parameters removes the implicit parameterless constructor, so you have to explicitly type it.
What was my problem was that a constructor with default parameters also triggered this exception.
Gives errors:
public CustomerWrapper(CustomerDto customer = null){...}
Works:
public CustomerWrapper(CustomerDto customer){...}
public CustomerWrapper():this(null){}
One way to accomplish that is to order you records and limit to 1. For example if you have the following table ('data').
id | user | price
-------------------
1 | me | 40.23
2 | me | 10.23
Try the following sql query
select * from data where user='me' order by id desc limit 1
You can read the lines and replace all special characters safely this way.
Keep in mind that if you use \\W
you will not replace underscores.
Scanner scan = new Scanner(System.in);
while(scan.hasNextLine()){
System.out.println(scan.nextLine().replaceAll("[^a-zA-Z0-9]", ""));
}
You can use show innodb status
(or show engine innodb status
for newer versions of mysql) to get a list of all the actions currently pending inside the InnoDB engine. Buried in the wall of output will be the transactions, and what internal process ID they're running under.
You won't be able to force a commit or rollback of those transactions, but you CAN kill the MySQL process running them, which does essentially boil down to a rollback. It kills the processes' connection and causes MySQL to clean up the mess its left.
Here's what you'd want to look for:
------------
TRANSACTIONS
------------
Trx id counter 0 140151
Purge done for trx's n:o < 0 134992 undo n:o < 0 0
History list length 10
LIST OF TRANSACTIONS FOR EACH SESSION:
---TRANSACTION 0 0, not started, process no 17004, OS thread id 140621902116624
MySQL thread id 10594, query id 10269885 localhost marc
show innodb status
In this case, there's just one connection to the InnoDB engine right now (my login, running the show
query). If that line were an actual connection/stuck transaction you'd want to terminate, you'd then do a kill 10594
.
@Alwin Doss You should provide the -L option before -l. You would have done the other way round probably. Try this :)
Depending on the system configuration, size of CHAR mesured in BYTES can vary. In your examples:
cd
without any parameters is equivalent to pwd
on Unix/Linux.
From the console output of typing cd /?
:
Displays the name of or changes the current directory.
[...]
Type CD without parameters to display the current drive and directory.
If you are using a non default MySQL port number then do the following:
33747
then paste the following
$cfg['Servers'][$i]['port'] = 33747;
under the
/* Authentication type and info */
section.You can use this:
SET FEEDBACK OFF;
SET SERVEROUTPUT ON;
DECLARE
V_START_DATE CHAR(17) := '28/03/16 17:20:00';
V_END_DATE CHAR(17) := '30/03/16 17:50:10';
V_DATE_DIFF VARCHAR2(17);
BEGIN
SELECT
(TO_NUMBER( SUBSTR(NUMTODSINTERVAL(TO_DATE(V_END_DATE , 'DD/MM/YY HH24:MI:SS') - TO_DATE(V_START_DATE, 'DD/MM/YY HH24:MI:SS'), 'DAY'), 02, 9)) * 24) +
(TO_NUMBER( SUBSTR(NUMTODSINTERVAL(TO_DATE(V_END_DATE , 'DD/MM/YY HH24:MI:SS') - TO_DATE(V_START_DATE, 'DD/MM/YY HH24:MI:SS'), 'DAY'), 12, 2))) ||
SUBSTR(NUMTODSINTERVAL(TO_DATE(V_END_DATE , 'DD/MM/YY HH24:MI:SS') - TO_DATE(V_START_DATE, 'DD/MM/YY HH24:MI:SS'), 'DAY'), 14, 6) AS "HH24:MI:SS"
INTO V_DATE_DIFF
FROM
DUAL;
DBMS_OUTPUT.PUT_LINE(V_DATE_DIFF);
END;
With POST you can also do multipart mime encoding which means you can attach files as well. Also if you are using post variables across navigation of pages, the user will get a warning asking if they want to resubmit the post parameter. Typically they look the same in an HTTP request, but you should just stick to POST if you need to "POST" something TO a server and "GET" if you need to GET something FROM a server as that's the way they were intended.
By implementing the SpinnerAdapter for your adapter object i use interested.getItem(i).toString()
I think what you are looking for is
.style1 {
background: url('http://localhost/msite/images/12.PNG');
background-repeat: no-repeat;
background-position: center;
-webkit-background-size: contain;
-moz-background-size: contain;
-o-background-size: contain;
background-size: contain;
}
My problem was that the nuget package manager did not do a real update but the files contained references to older versions, so i first removed all the installed mvc related packages (including razor and web api) then installed them over again and updating the version of the razor in views/web.config to version 3.0.0.
You can use the function difftime
. It returns the difference between two given time_t
values, the output value is double
(see difftime documentation).
time_t actual_time;
double actual_time_sec;
actual_time = time(0);
actual_time_sec = difftime(actual_time,0);
printf("%g",actual_time_sec);
even better:
lsct ()
{
debugfs -R 'stat <'`ls -i "$1" | (read a b;echo -n $a)`'>' `df "$1" | (read a; read a b; echo "$a")` 2> /dev/null | grep --color=auto crtime | ( read a b c d;
echo $d )
}
Wed Jul 20 19:25:48 2016
There is delete
, delete_all
, destroy
, and destroy_all
.
The docs are: older docs and Rails 3.0.0 docs
delete
doesn't instantiate the objects, while destroy
does. In general, delete
is faster than destroy
.
In addition to the efficient and pre-built functions given in answers I'll add my own which are simply part of my repertory of Haskell functions I was writing to learn the language on my own time:
-- Correct but inefficient implementation
wordsBy :: String -> Char -> [String]
wordsBy s c = reverse (go s []) where
go s' ws = case (dropWhile (\c' -> c' == c) s') of
"" -> ws
rem -> go ((dropWhile (\c' -> c' /= c) rem)) ((takeWhile (\c' -> c' /= c) rem) : ws)
-- Breaks up by predicate function to allow for more complex conditions (\c -> c == ',' || c == ';')
wordsByF :: String -> (Char -> Bool) -> [String]
wordsByF s f = reverse (go s []) where
go s' ws = case ((dropWhile (\c' -> f c')) s') of
"" -> ws
rem -> go ((dropWhile (\c' -> (f c') == False)) rem) (((takeWhile (\c' -> (f c') == False)) rem) : ws)
The solutions are at least tail-recursive so they won't incur a stack overflow.
Major Difference between Object and MAP with Example :
it's Order of iteration in loop, In Map it follows the order as it was set while creation whereas in OBJECT does not.
SEE: OBJECT
const obj = {};
obj.prop1 = "Foo";
obj.prop2 = "Bar";
obj['1'] = "day";
console.log(obj)
**OUTPUT: {1: "day", prop1: "Foo", prop2: "Bar"}**
MAP
const myMap = new Map()
// setting the values
myMap.set("foo", "value associated with 'a string'")
myMap.set("Bar", 'value associated with keyObj')
myMap.set("1", 'value associated with keyFunc')
OUTPUT:
**1. ?0: Array[2]
1. 0: "foo"
2. 1: "value associated with 'a string'"
2. ?1: Array[2]
1. 0: "Bar"
2. 1: "value associated with keyObj"
3. ?2: Array[2]
1. 0: "1"
2. 1: "value associated with keyFunc"**
$("form input[type=submit]").click(function() {
$("<input />")
.attr('type', 'hidden')
.attr('name', $(this).attr('name'))
.attr('value', $(this).attr('value'))
.appendTo(this)
});
add hidden field
Another handy difference (in English where accents are uncommon) is that an InvariantCulture comparison compares the entire strings by case-insensitive first, and then if necessary (and requested) distinguishes by case after first comparing only on the distinct letters. (You can also do a case-insensitive comparison, of course, which won't distinguish by case.) Corrected: Accented letters are considered to be another flavor of the same letters and the string is compared first ignoring accents and then accounting for them if the general letters all match (much as with differing case except not ultimately ignored in a case-insensitive compare). This groups accented versions of the otherwise same word near each other instead of completely separate at the first accent difference. This is the sort order you would typically find in a dictionary, with capitalized words appearing right next to their lowercase equivalents, and accented letters being near the corresponding unaccented letter.
An ordinal comparison compares strictly on the numeric character values, stopping at the first difference. This sorts capitalized letters completely separate from the lowercase letters (and accented letters presumably separate from those), so capitalized words would sort nowhere near their lowercase equivalents.
InvariantCulture also considers capitals to be greater than lower case, whereas Ordinal considers capitals to be less than lowercase (a holdover of ASCII from the old days before computers had lowercase letters, the uppercase letters were allocated first and thus had lower values than the lowercase letters added later).
For example, by Ordinal: "0" < "9" < "A" < "Ab" < "Z" < "a" < "aB" < "ab" < "z" < "Á" < "Áb" < "á" < "áb"
And by InvariantCulture: "0" < "9" < "a" < "A" < "á" < "Á" < "ab" < "aB" < "Ab" < "áb" < "Áb" < "z" < "Z"
Login to mysql as root and type following query
select User from mysql.user;
+------+
| User |
+------+
| amon |
| root |
| root |
+------+
The pack
method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize
or setBounds
(which also sets the frame location). In general, using pack is preferable to calling setSize
, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size.
From Java tutorial
You should also refer to Javadocs any time you need additional information on any Java API
Configuring $mail->SMTPAuth = true;
was the solution for me. The reason why is because without authentication the mail server answers with 'Relay access denied'. Since putting this in my code, all mails work fine.
I ran into this issue when I manually copied the contents of my Laravel project (say sites/oldname) into a new directory on my Mac (say, sites/newname). Since I was manually dragging and droppping, it didn't grab the hidden files, namely, '.env'. When I looked more closely at sites/oldname I saw .editorconfig, .env, .env.example, .gitatrributes, .styleci.yml, etc.
The error went away once I copied the hidden files to the new directory.
So, "No Application Encryption Key Has Been Specified" is Laravel speak for "your .env file is missing."
Set the insetForSectionAt
property of the UICollectionViewFlowLayout
object attached to your UICollectionView
Make sure to add this protocol
UICollectionViewDelegateFlowLayout
Swift
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets (top: top, left: left, bottom: bottom, right: right)
}
Objective - C
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
return UIEdgeInsetsMake(top, left, bottom, right);
}
For CSS that are reused among the entire site I define them in the <head>
section of the _Layout
:
<head>
<link href="@Url.Content("~/Styles/main.css")" rel="stylesheet" type="text/css" />
@RenderSection("Styles", false)
</head>
and if I need some view specific styles I define the Styles
section in each view:
@section Styles {
<link href="@Url.Content("~/Styles/view_specific_style.css")" rel="stylesheet" type="text/css" />
}
Edit: It's useful to know that the second parameter in @RenderSection, false, means that the section is not required on a view that uses this master page, and the view engine will blissfully ignore the fact that there is no "Styles" section defined in your view. If true, the view won't render and an error will be thrown unless the "Styles" section has been defined.
For loading the layout in layout-land folder means you have two separate layouts then you have to make setContentView
in onConfigurationChanged
method.
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
setContentView(R.layout.yourxmlinlayout-land);
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
setContentView(R.layout.yourxmlinlayoutfolder);
}
}
If you have only one layout then no necessary to make setContentView in This method. simply
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
MyClass.class.getDeclaredConstructor(String.class).newInstance("HERESMYARG");
or
obj.getClass().getDeclaredConstructor(String.class).newInstance("HERESMYARG");
In my case, the problem was the optional parameter indicator('?') missing in my template configuration.
For example:
.when('/abc/:id?', {
templateUrl: 'views/abc.html',
controller: 'abcControl'
})
$location.path('/abc');
Without the interrogation character the route obviously would not change suppressing the route parameter.
If you're trying to open a scala/sbt project, the sbt version set in /project/build.properties
must match the sbt version installed on your system or intellij won't detect your project's modules properly.
Once that's done, you can just delete the idea
folder and restart as the other answers suggest.
Create a Date
object using the diffence between your times as a constructor,
then use Calendar methods to get values ..
Date diff = new Date(d2.getTime() - d1.getTime());
Calendar calendar = Calendar.getInstance();
calendar.setTime(diff);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);
Some reading to get you started on character encodings: Joel on Software: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
By the way - ASP.NET has nothing to do with it. Encodings are universal.
You can control the behavior in a headerfile or C-file:
#pragma warning(error:4003) //not enough actual parameters for macro
yet tested with Visual studio 2015. I have a common headerfile 'compl_adaption.h' for such things, included in all files, to set this behavior for all my projects compiled on visual studio.
In mvc 4 Could be rendered with Underscore(" _ ")
Razor:
@Html.ActionLink("Vote", "#", new { id = item.FileId, }, new { @class = "votes", data_fid = item.FileId, data_jid = item.JudgeID, })
Rendered Html
<a class="votes" data-fid="18587" data-jid="9" href="/Home/%23/18587">Vote</a>
Perhaps use plt.annotate:
import numpy as np
import matplotlib.pyplot as plt
N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]
plt.subplots_adjust(bottom = 0.1)
plt.scatter(
data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,
cmap=plt.get_cmap('Spectral'))
for label, x, y in zip(labels, data[:, 0], data[:, 1]):
plt.annotate(
label,
xy=(x, y), xytext=(-20, 20),
textcoords='offset points', ha='right', va='bottom',
bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))
plt.show()
You can do multicolor outputs without any external programs.
@echo off
SETLOCAL EnableDelayedExpansion
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
set "DEL=%%a"
)
echo say the name of the colors, don't read
call :ColorText 0a "blue"
call :ColorText 0C "green"
call :ColorText 0b "red"
echo(
call :ColorText 19 "yellow"
call :ColorText 2F "black"
call :ColorText 4e "white"
goto :eof
:ColorText
echo off
<nul set /p ".=%DEL%" > "%~2"
findstr /v /a:%1 /R "^$" "%~2" nul
del "%~2" > nul 2>&1
goto :eof
It uses the color feature of the findstr command.
Findstr can be configured to output line numbers or filenames in a defined color.
So I first create a file with the text as filename, and the content is a single <backspace>
character (ASCII 8).
Then I search all non empty lines in the file and in nul, so the filename will be output in the correct color appended with a colon, but the colon is immediatly removed by the <backspace>
.
EDIT: One year later ... all characters are valid
@echo off
setlocal EnableDelayedExpansion
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
set "DEL=%%a"
)
rem Prepare a file "X" with only one dot
<nul > X set /p ".=."
call :color 1a "a"
call :color 1b "b"
call :color 1c "^!<>&| %%%%"*?"
exit /b
:color
set "param=^%~2" !
set "param=!param:"=\"!"
findstr /p /A:%1 "." "!param!\..\X" nul
<nul set /p ".=%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%"
exit /b
This uses the rule for valid path/filenames.
If a \..\
is in the path the prefixed elemet will be removed completly and it's not necessary that this element contains only valid filename characters.
You cannot use ++
on something which is not a variable, this would be the closest you can get:
$('#counter').html(function(i, val) { return +val+1 });
jQuery's html()
method can get and set the HTML value of an element. If passed a function it can update the HTML based upon the existing value. So in the context of your code:
$("#update").click(function() {
$('#counter').html(function(i, val) { return +val+1 });
}
DEMO: http://jsfiddle.net/marcuswhybrow/zRX2D/2/
When it comes to synchronising your counter on the page, with the counter value in your database, never trust the client! You send either an increment or decrement signal to you server side script, rather than a continuous value such as 10, or 23.
However you could send an AJAX request to the server when you change the HTML of your counter:
$("#update").click(function() {
$('#counter').html(function(i, val) {
$.ajax({
url: '/path/to/script/',
type: 'POST',
data: {increment: true},
success: function() { alert('Request has returned') }
});
return +val+1;
});
}
You code breaks Demeter's law. That's why it's better to refactor the design itself. As a workaround, you can use Optional
obj = Optional.ofNullable(object1)
.map(o -> o.getIdObject11())
.map(o -> o.getIdObject111())
.map(o -> o.getDescription())
.orElse("")
above is to check to hierarchy of a object so simply use
Optional.ofNullable(object1)
if you have only one object to check
Hope this helps !!!!
If you can not see the "Prevent saving changes that required table re-creation" in list like that The image
You need to enable change tracking.
Using this method it is also possible to perform mass configuration changes, such as changing the all sessions font.
Extracted from here: http://www.sysadmit.com/2015/11/putty-exportar-configuracion.html
C++20 will include std::format
which resembles sprintf
in terms of API but is fully type-safe, works with user-defined types, and uses Python-like format string syntax. Here's how you will be able to format std::string
and write it to a stream:
std::string s = "foo";
std::cout << std::format("Look, a string: {}", s);
Alternatively, you could use the {fmt} library to format a string and write it to stdout
or a file stream in one go:
fmt::print("Look, a string: {}", s);
As for sprintf
or most of the other answers here, unfortunately they use varargs and are inherently unsafe unless you use something like GCC's format
attribute which only works with literal format strings. You can see why these functions are unsafe on the following example:
std::string format_str = "%s";
string_format(format_str, format_str[0]);
where string_format
is an implementation from the Erik Aronesty's answer. This code compiles, but it will most likely crash when you try to run it:
$ g++ -Wall -Wextra -pedantic test.cc
$ ./a.out
Segmentation fault: 11
Disclaimer: I'm the author of {fmt} and C++20 std::format
.
The equivalent would be class SortedDictionary<TKey, TValue>
in the System.Collections.Generic
namespace.
If you don't care about the order the class Dictionary<TKey, TValue>
in the System.Collections.Generic
namespace would probably be sufficient.
Are you using Eclipse? If so I would stick with the default member sort order, because that is likely to be most familiar to whoever reads your code (although it is not my favourite sort order.)
This is a working solution of AES encryption
- implemented using openssl
. It uses the Cipher Block Chaining Mode (CBC-Mode). Thus, alongside data
and key
, you can specify iv
and block size
<?php
class AESEncryption {
protected $key;
protected $data;
protected $method;
protected $iv;
/**
* Available OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING
*
* @var type $options
*/
protected $options = 0;
/**
*
* @param type $data
* @param type $key
* @param type $iv
* @param type $blockSize
* @param type $mode
*/
public function __construct($data = null, $key = null, $iv = null, $blockSize = null, $mode = 'CBC') {
$this->setData($data);
$this->setKey($key);
$this->setInitializationVector($iv);
$this->setMethod($blockSize, $mode);
}
/**
*
* @param type $data
*/
public function setData($data) {
$this->data = $data;
}
/**
*
* @param type $key
*/
public function setKey($key) {
$this->key = $key;
}
/**
* CBC 128 192 256
CBC-HMAC-SHA1 128 256
CBC-HMAC-SHA256 128 256
CFB 128 192 256
CFB1 128 192 256
CFB8 128 192 256
CTR 128 192 256
ECB 128 192 256
OFB 128 192 256
XTS 128 256
* @param type $blockSize
* @param type $mode
*/
public function setMethod($blockSize, $mode = 'CBC') {
if($blockSize==192 && in_array('', array('CBC-HMAC-SHA1','CBC-HMAC-SHA256','XTS'))){
$this->method=null;
throw new Exception('Invalid block size and mode combination!');
}
$this->method = 'AES-' . $blockSize . '-' . $mode;
}
/**
*
* @param type $data
*/
public function setInitializationVector($iv) {
$this->iv = $iv;
}
/**
*
* @return boolean
*/
public function validateParams() {
if ($this->data != null &&
$this->method != null ) {
return true;
} else {
return FALSE;
}
}
//it must be the same when you encrypt and decrypt
protected function getIV() {
return $this->iv;
}
/**
* @return type
* @throws Exception
*/
public function encrypt() {
if ($this->validateParams()) {
return trim(openssl_encrypt($this->data, $this->method, $this->key, $this->options,$this->getIV()));
} else {
throw new Exception('Invalid params!');
}
}
/**
*
* @return type
* @throws Exception
*/
public function decrypt() {
if ($this->validateParams()) {
$ret=openssl_decrypt($this->data, $this->method, $this->key, $this->options,$this->getIV());
return trim($ret);
} else {
throw new Exception('Invalid params!');
}
}
}
Sample usage:
<?php
$data = json_encode(['first_name'=>'Dunsin','last_name'=>'Olubobokun','country'=>'Nigeria']);
$inputKey = "W92ZB837943A711B98D35E799DFE3Z18";
$iv = "tuqZQhKP48e8Piuc";
$blockSize = 256;
$aes = new AESEncryption($data, $inputKey, $iv, $blockSize);
$enc = $aes->encrypt();
$aes->setData($enc);
$dec=$aes->decrypt();
echo "After encryption: ".$enc."<br/>";
echo "After decryption: ".$dec."<br/>";
sqlall
just prints the SQL, it doesn't execute it. syncdb
will create tables that aren't already created, but it won't modify existing tables.
this
is a reference to the current object. It is used in the constructor to distinguish between the local and the current class variable which have the same name. e.g.:
public class circle {
int x;
circle(int x){
this.x =x;
//class variable =local variable
}
}
this
can also be use to call one constructor from another constructor. e.g.:
public class circle {
int x;
circle() {
this(1);
}
circle(int x) {
this.x = x;
}
}
At first you have to understand what does join do? We connect multiple table and get specific result from the joined tables. The simplest way to do this is cross join.
Lets say tableA has two column A and B. And tableB has three column C and D. If we apply cross join it will produce lot of meaningless row. Then we have to match using primary key to get actual data.
Left: it will return all records from left table and matched record from right table.
Right: it will return opposite to Left join. It will return all records from right table and matched records from left table.
Inner: This is like intersection. It will return only matched records from both table.
Outer: And this is like union. It will return all available record from both table.
Some times we don't need all of the data, and also we should need only common data or records. we can easily get it using these join methods. Remember left and right join also are outer join.
You can get all records just using cross join. But it could be expensive when it comes to millions of records. So make it simple by using left, right, inner or outer join.
thanks
#biglinebreakid {_x000D_
line-height: 450%;_x000D_
// 9x the normal height of a line break!_x000D_
}_x000D_
.biglinebreakclass {_x000D_
line-height: 1em;_x000D_
// you could even use calc!_x000D_
}
_x000D_
This is a small line_x000D_
<br />_x000D_
break. Whereas, this is a BIG line_x000D_
<br />_x000D_
<br id="biglinebreakid" />_x000D_
break! You can use any CSS selectors you want for things like this line_x000D_
<br />_x000D_
<br class="biglinebreakclass" />_x000D_
break!
_x000D_
Otro example, custom Data Pagination for JOIN
CODE in Controller CakePHP 2.6 is OK:
$this->SenasaPedidosFacturadosSds->recursive = -1;
// Filtro
$where = array(
'joins' => array(
array(
'table' => 'usuarios',
'alias' => 'Usuarios',
'type' => 'INNER',
'conditions' => array(
'Usuarios.usuario_id = SenasaPedidosFacturadosSds.usuarios_id'
)
),
array(
'table' => 'senasa_pedidos',
'alias' => 'SenasaPedidos',
'type' => 'INNER',
'conditions' => array(
'SenasaPedidos.id = SenasaPedidosFacturadosSds.senasa_pedidos_id'
)
),
array(
'table' => 'clientes',
'alias' => 'Clientes',
'type' => 'INNER',
'conditions' => array(
'Clientes.id_cliente = SenasaPedidos.clientes_id'
)
),
),
'fields'=>array(
'SenasaPedidosFacturadosSds.*',
'Usuarios.usuario_id',
'Usuarios.apellido_nombre',
'Usuarios.senasa_establecimientos_id',
'Clientes.id_cliente',
'Clientes.consolida_doc_sanitaria',
'Clientes.requiere_senasa',
'Clientes.razon_social',
'SenasaPedidos.id',
'SenasaPedidos.domicilio_entrega',
'SenasaPedidos.sds',
'SenasaPedidos.pt_ptr'
),
'conditions'=>array(
'Clientes.requiere_senasa'=>1
),
'order' => 'SenasaPedidosFacturadosSds.created DESC',
'limit'=>100
);
$this->paginate = $where;
// Get datos
$data = $this->Paginator->paginate();
exit(debug($data));
OR Example 2, NOT active conditions:
$this->SenasaPedidosFacturadosSds->recursive = -1;
// Filtro
$where = array(
'joins' => array(
array(
'table' => 'usuarios',
'alias' => 'Usuarios',
'type' => 'INNER',
'conditions' => array(
'Usuarios.usuario_id = SenasaPedidosFacturadosSds.usuarios_id'
)
),
array(
'table' => 'senasa_pedidos',
'alias' => 'SenasaPedidos',
'type' => 'INNER',
'conditions' => array(
'SenasaPedidos.id = SenasaPedidosFacturadosSds.senasa_pedidos_id'
)
),
array(
'table' => 'clientes',
'alias' => 'Clientes',
'type' => 'INNER',
'conditions' => array(
'Clientes.id_cliente = SenasaPedidos.clientes_id',
'Clientes.requiere_senasa = 1'
)
),
),
'fields'=>array(
'SenasaPedidosFacturadosSds.*',
'Usuarios.usuario_id',
'Usuarios.apellido_nombre',
'Usuarios.senasa_establecimientos_id',
'Clientes.id_cliente',
'Clientes.consolida_doc_sanitaria',
'Clientes.requiere_senasa',
'Clientes.razon_social',
'SenasaPedidos.id',
'SenasaPedidos.domicilio_entrega',
'SenasaPedidos.sds',
'SenasaPedidos.pt_ptr'
),
//'conditions'=>array(
// 'Clientes.requiere_senasa'=>1
//),
'order' => 'SenasaPedidosFacturadosSds.created DESC',
'limit'=>100
);
$this->paginate = $where;
// Get datos
$data = $this->Paginator->paginate();
exit(debug($data));
This is super-duper kludgy, but in a kind of cool way, so I'll just toss it into the ring:
GIT_EDITOR='f() { if [ "$(basename $1)" = "git-rebase-todo" ]; then sed -i "2,\$s/pick/squash/" $1; else vim $1; fi }; f' git rebase -i foo~5 foo
Translation: provide a new "editor" for git which, if the filename to be edited is git-rebase-todo
(the interactive rebase prompt) changes all but the first "pick" to "squash", and otherwise spawns vim - so that when you're prompted to edit the squashed commit message, you get vim. (And obviously I was squashing the last five commits on branch foo, but you could change that however you like.)
I'd probably do what Mark Longair suggested, though.
You don't need to use JsonConverterAttribute
, keep your model clean, also use CustomCreationConverter
, the code is simpler:
public class SampleConverter : CustomCreationConverter<ISample>
{
public override ISample Create(Type objectType)
{
return new Sample();
}
}
Then:
var sz = JsonConvert.SerializeObject( sampleGroupInstance );
JsonConvert.DeserializeObject<SampleGroup>( sz, new SampleConverter());
Documentation: Deserialize with CustomCreationConverter
"start" is a name of a script, in npm you run scripts like this npm run scriptName
, npm start
is also a short for npm run start
As for "react-scripts" this is a script related specifically to create-react-app
you can use a string formatter to pad any integer with zeros. It acts just like C's printf
.
>>> d = datetime.date.today()
>>> '%02d' % d.month
'03'
Updated for py36: Use f-strings! For general int
s you can use the d
formatter and explicitly tell it to pad with zeros:
>>> d = datetime.date.today()
>>> f"{d.month:02d}"
'07'
But datetime
s are special and come with special formatters that are already zero padded:
>>> f"{d:%d}" # the day
'01'
>>> f"{d:%m}" # the month
'07'
You can list all existing tags git tag
or you could filter the list with git tag -l 'v1.1.*'
, where *
acts as a wildcard. It will return a list of tags marked with v1.1
.
You will notice that when you call git tag
you do not get to see the contents of your annotations. To preview them you must add -n
to your command: git tag -n2
.
$ git tag -l -n2
v1.0 Release version 1.0
v1.1 Release version 1.1
The command lists all existing tags with maximum 3 lines of their tag message. By default -n
only shows the first line. For more info be sure to check this tag related article as well.
Infinity, NaN and subnormals
These are important caveats that no other answer has mentioned so far.
First read this introduction to IEEE 754 and subnormal numbers: What is a subnormal floating point number?
Then, for single precision floats (32-bit):
IEEE 754 says that if the exponent is all ones (0xFF == 255
), then it represents either NaN or Infinity.
This is why the largest non-infinite number has exponent 0xFE == 254
and not 0xFF
.
Then with the bias, it becomes:
254 - 127 == 127
FLT_MIN
is the smallest normal number. But there are smaller subnormal ones! Those take up the -127
exponent slot.
All asserts of the following program pass on Ubuntu 18.04 amd64:
#include <assert.h>
#include <float.h>
#include <inttypes.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
float float_from_bytes(
uint32_t sign,
uint32_t exponent,
uint32_t fraction
) {
uint32_t bytes;
bytes = 0;
bytes |= sign;
bytes <<= 8;
bytes |= exponent;
bytes <<= 23;
bytes |= fraction;
return *(float*)&bytes;
}
int main(void) {
/* All 1 exponent and non-0 fraction means NaN.
* There are of course many possible representations,
* and some have special semantics such as signalling vs not.
*/
assert(isnan(float_from_bytes(0, 0xFF, 1)));
assert(isnan(NAN));
printf("nan = %e\n", NAN);
/* All 1 exponent and 0 fraction means infinity. */
assert(INFINITY == float_from_bytes(0, 0xFF, 0));
assert(isinf(INFINITY));
printf("infinity = %e\n", INFINITY);
/* ANSI C defines FLT_MAX as the largest non-infinite number. */
assert(FLT_MAX == 0x1.FFFFFEp127f);
/* Not 0xFF because that is infinite. */
assert(FLT_MAX == float_from_bytes(0, 0xFE, 0x7FFFFF));
assert(!isinf(FLT_MAX));
assert(FLT_MAX < INFINITY);
printf("largest non infinite = %e\n", FLT_MAX);
/* ANSI C defines FLT_MIN as the smallest non-subnormal number. */
assert(FLT_MIN == 0x1.0p-126f);
assert(FLT_MIN == float_from_bytes(0, 1, 0));
assert(isnormal(FLT_MIN));
printf("smallest normal = %e\n", FLT_MIN);
/* The smallest non-zero subnormal number. */
float smallest_subnormal = float_from_bytes(0, 0, 1);
assert(smallest_subnormal == 0x0.000002p-126f);
assert(0.0f < smallest_subnormal);
assert(!isnormal(smallest_subnormal));
printf("smallest subnormal = %e\n", smallest_subnormal);
return EXIT_SUCCESS;
}
Compile and run with:
gcc -ggdb3 -O0 -std=c11 -Wall -Wextra -Wpedantic -Werror -o subnormal.out subnormal.c
./subnormal.out
Output:
nan = nan
infinity = inf
largest non infinite = 3.402823e+38
smallest normal = 1.175494e-38
smallest subnormal = 1.401298e-45
use array_keys()
to get an array of all the unique keys.
Note that an array with named keys like your $arr
can also be accessed with numeric indexes, like $arr[0]
.
As a general point when using a search engine to search for SQL codes make sure you put the sqlcode e.g. -302 in quote marks - like "-302" otherwise the search engine will exclude all search results including the text 302, since the - sign is used to exclude results.
For the record, the spring.jpa.hibernate.ddl-auto
property is Spring Data JPA specific and is their way to specify a value that will eventually be passed to Hibernate under the property it knows, hibernate.hbm2ddl.auto
.
The values create
, create-drop
, validate
, and update
basically influence how the schema tool management will manipulate the database schema at startup.
For example, the update
operation will query the JDBC driver's API to get the database metadata and then Hibernate compares the object model it creates based on reading your annotated classes or HBM XML mappings and will attempt to adjust the schema on-the-fly.
The update
operation for example will attempt to add new columns, constraints, etc but will never remove a column or constraint that may have existed previously but no longer does as part of the object model from a prior run.
Typically in test case scenarios, you'll likely use create-drop
so that you create your schema, your test case adds some mock data, you run your tests, and then during the test case cleanup, the schema objects are dropped, leaving an empty database.
In development, it's often common to see developers use update
to automatically modify the schema to add new additions upon restart. But again understand, this does not remove a column or constraint that may exist from previous executions that is no longer necessary.
In production, it's often highly recommended you use none
or simply don't specify this property. That is because it's common practice for DBAs to review migration scripts for database changes, particularly if your database is shared across multiple services and applications.
Try using the net use
command in your script to map the share first, because you can provide it credentials. Then, your copy command should use those credentials.
net use \\<network-location>\<some-share> password /USER:username
Don't leave a trailing \ at the end of the
I wrote a super simple delay function for an application I developed in Qt.
I would advise you to use this code rather than the sleep function as it won't let your GUI freeze.
Here is the code:
void delay()
{
QTime dieTime= QTime::currentTime().addSecs(1);
while (QTime::currentTime() < dieTime)
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}
To delay an event by n seconds - use addSecs(n)
.
Firstly, the level name to use is FINE
, not DEBUG
. Let's assume for a minute that DEBUG
is actually valid, as it makes the following explanation make a bit more sense...
In the Handler specific properties
section, you're setting the logging level for those handlers to DEBUG
. This means the handlers will handle any log messages with the DEBUG
level or higher. It doesn't necessarily mean any DEBUG
messages are actually getting passed to the handlers.
In the Facility specific properties
section, you're setting the logging level for a few explicitly-named loggers to DEBUG
. For those loggers, anything at level DEBUG
or above will get passed to the handlers.
The default logging level is INFO
, and apart from the loggers mentioned in the Facility specific properties
section, all loggers will have that level.
If you want to see all FINE
messages, add this:
.level = FINE
However, this will generate a vast quantity of log messages. It's probably more useful to set the logging level for your code:
your.package.level = FINE
See the Tomcat 6/Tomcat 7 logging documentation for more information. The example logging.properties file shown there uses FINE
instead of DEBUG
:
...
1catalina.org.apache.juli.FileHandler.level = FINE
...
and also gives you examples of setting additional logging levels:
# For example, set the com.xyz.foo logger to only log SEVERE
# messages:
#org.apache.catalina.startup.ContextConfig.level = FINE
#org.apache.catalina.startup.HostConfig.level = FINE
#org.apache.catalina.session.ManagerBase.level = FINE
If the types of the parameters are all the same (varchar2
for example), you can have a package like this which will do the following:
CREATE OR REPLACE PACKAGE testuser.test_pkg IS
TYPE assoc_array_varchar2_t IS TABLE OF VARCHAR2(4000) INDEX BY BINARY_INTEGER;
PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t);
END test_pkg;
CREATE OR REPLACE PACKAGE BODY testuser.test_pkg IS
PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t) AS
BEGIN
FOR i IN p_parm.first .. p_parm.last
LOOP
dbms_output.put_line(p_parm(i));
END LOOP;
END;
END test_pkg;
Then, to call it you'd need to set up the array and pass it:
DECLARE
l_array testuser.test_pkg.assoc_array_varchar2_t;
BEGIN
l_array(0) := 'hello';
l_array(1) := 'there';
testuser.test_pkg.your_proc(l_array);
END;
/
No, and your compiler already gave you a comprehensive explanation.
But you could do this:
constexpr char constString[] = "constString";
At runtime, this can be used to construct a std::string
when needed.
Use npm/bower to install bootstrap if you want to recompile it/change less files/test. With grunt it would be easier to do this, as shown on http://getbootstrap.com/getting-started/#grunt. If you only want to add precompiled libraries feel free to manually include files to project.
No, you have to do this by yourself or use separate grunt tool. For example 'grunt-contrib-concat' How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x)
To get the script, that currently loaded the script you can use
var thisScript = document.currentScript;
You need to keep a reference at the beginning of your script, so you can call later
var url = thisScript.src
Here's a step by step explanation how to install MySQL and JDBC and how to use it:
Download and install the MySQL server. Just do it the usual way. Remember the port number whenever you've changed it. It's by default 3306
.
Download the JDBC driver and put in classpath, extract the ZIP file and put the containing JAR file in the classpath. The vendor-specific JDBC driver is a concrete implementation of the JDBC API (tutorial here).
If you're using an IDE like Eclipse or Netbeans, then you can add it to the classpath by adding the JAR file as Library to the Build Path in project's properties.
If you're doing it "plain vanilla" in the command console, then you need to specify the path to the JAR file in the -cp
or -classpath
argument when executing your Java application.
java -cp .;/path/to/mysql-connector.jar com.example.YourClass
The .
is just there to add the current directory to the classpath as well so that it can locate com.example.YourClass
and the ;
is the classpath separator as it is in Windows. In Unix and clones :
should be used.
Create a database in MySQL. Let's create a database javabase
. You of course want World Domination, so let's use UTF-8 as well.
CREATE DATABASE javabase DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
Create an user for Java and grant it access. Simply because using root
is a bad practice.
CREATE USER 'java'@'localhost' IDENTIFIED BY 'password';
GRANT ALL ON javabase.* TO 'java'@'localhost' IDENTIFIED BY 'password';
Yes, java
is the username and password
is the password here.
Determine the JDBC URL. To connect the MySQL database using Java you need an JDBC URL in the following syntax:
jdbc:mysql://hostname:port/databasename
hostname
: The hostname where MySQL server is installed. If it's installed at the same machine where you run the Java code, then you can just use localhost
. It can also be an IP address like 127.0.0.1
. If you encounter connectivity problems and using 127.0.0.1
instead of localhost
solved it, then you've a problem in your network/DNS/hosts config.
port
: The TCP/IP port where MySQL server listens on. This is by default 3306
.
databasename
: The name of the database you'd like to connect to. That's javabase
.
So the final URL should look like:
jdbc:mysql://localhost:3306/javabase
Test the connection to MySQL using Java. Create a simple Java class with a main()
method to test the connection.
String url = "jdbc:mysql://localhost:3306/javabase";
String username = "java";
String password = "password";
System.out.println("Connecting database...");
try (Connection connection = DriverManager.getConnection(url, username, password)) {
System.out.println("Database connected!");
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
If you get a SQLException: No suitable driver
, then it means that either the JDBC driver wasn't autoloaded at all or that the JDBC URL is wrong (i.e. it wasn't recognized by any of the loaded drivers). Normally, a JDBC 4.0 driver should be autoloaded when you just drop it in runtime classpath. To exclude one and other, you can always manually load it as below:
System.out.println("Loading driver...");
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
}
Note that the newInstance()
call is not needed here. It's just to fix the old and buggy org.gjt.mm.mysql.Driver
. Explanation here. If this line throws ClassNotFoundException
, then the JAR file containing the JDBC driver class is simply not been placed in the classpath.
Note that you don't need to load the driver everytime before connecting. Just only once during application startup is enough.
If you get a SQLException: Connection refused
or Connection timed out
or a MySQL specific CommunicationsException:
Communications link failure
, then it means that the DB isn't reachable at all. This can have one or more of the following causes:
To solve the one or the other, follow the following advices:
ping
.my.cnf
of MySQL DB.--skip-networking option
.finally
.Note that closing the Connection
is extremely important. If you don't close connections and keep getting a lot of them in a short time, then the database may run out of connections and your application may break. Always acquire the Connection
in a try-with-resources
statement. Or if you're not on Java 7 yet, explicitly close it in finally
of a try-finally
block. Closing in finally
is just to ensure that it get closed as well in case of an exception. This also applies to Statement
, PreparedStatement
and ResultSet
.
That was it as far the connectivity concerns. You can find here a more advanced tutorial how to load and store fullworthy Java model objects in a database with help of a basic DAO class.
Using a Singleton Pattern for the DB connection is a bad approach. See among other questions: http://stackoverflow.com/q/9428573/. This is a #1 starters mistake.
The answer of the user load step worked for me.
Sometimes is need edit the file in /etc/mysql/my.cnf
add line to client
[client]
password = your_mysql_root_password
port = 3306
host = 127.0.0.1
socket = /var/lib/mysql/mysql.sock
ASP.NET MVC doesn't work on events like ASP classic; there's no "button click event". Your controller methods correspond to requests sent to the server.
Instead, you need to wrap that form in code something like this:
@using (Html.BeginForm("SignUp", "Account", FormMethod.Post))
{
<!-- form goes here -->
<input type="submit" value="Sign Up" />
}
This will set up a form, and then your submit input will trigger a POST, which will hit your SignUp()
method, assuming your routes are properly set up (the defaults should work).
As others have pointed out, thread safety means that a piece of code will work without errors if it's used by more than one thread at once.
It's worth being aware that this sometimes comes at a cost, of computer time and more complex coding, so it isn't always desirable. If a class can be safely used on only one thread, it may be better to do so.
For example, Java has two classes that are almost equivalent, StringBuffer
and StringBuilder
. The difference is that StringBuffer
is thread-safe, so a single instance of a StringBuffer
may be used by multiple threads at once. StringBuilder
is not thread-safe, and is designed as a higher-performance replacement for those cases (the vast majority) when the String is built by only one thread.
Example valid nginx.conf for reverse proxy; In case someone is stuck like me.
where 10.x.x.x
is the server where you are running the nginx proxy server and to which you are connecting to with the browser, and 10.y.y.y
is where your real web server is running
events {
worker_connections 4096; ## Default: 1024
}
http {
server {
listen 80;
listen [::]:80;
server_name 10.x.x.x;
location / {
proxy_pass http://10.y.y.y:80/;
proxy_set_header Host $host;
}
}
}
Here is the snippet if you want to do SSL pass through. That is if 10.y.y.y
is running a HTTPS webserver. Here 10.x.x.x
, or where the nignx runs is listening to port 443, and all traffic to 443 is directed to your target web server
events {
worker_connections 4096; ## Default: 1024
}
stream {
server {
listen 443;
proxy_pass 10.y.y.y:443;
}
}
and you can serve it up in docker too
docker run --name nginx-container --rm --net=host -v /home/core/nginx/nginx.conf:/etc/nginx/nginx.conf nginx
Just for fun, here some test:
#Added this for @Graimer's request ;) (not same computer, but one with HD little more #performant...)
measure-command { Get-Content ita\ita.txt -TotalCount 260000 | Select-Object -Last 1 }
Days : 0
Hours : 0
Minutes : 0
Seconds : 28
Milliseconds : 893
Ticks : 288932649
TotalDays : 0,000334412788194444
TotalHours : 0,00802590691666667
TotalMinutes : 0,481554415
TotalSeconds : 28,8932649
TotalMilliseconds : 28893,2649
> measure-command { (gc "c:\ps\ita\ita.txt")[260000] }
Days : 0
Hours : 0
Minutes : 0
Seconds : 9
Milliseconds : 257
Ticks : 92572893
TotalDays : 0,000107144552083333
TotalHours : 0,00257146925
TotalMinutes : 0,154288155
TotalSeconds : 9,2572893
TotalMilliseconds : 9257,2893
> measure-command { ([System.IO.File]::ReadAllLines("c:\ps\ita\ita.txt"))[260000] }
Days : 0
Hours : 0
Minutes : 0
Seconds : 0
Milliseconds : 234
Ticks : 2348059
TotalDays : 2,71766087962963E-06
TotalHours : 6,52238611111111E-05
TotalMinutes : 0,00391343166666667
TotalSeconds : 0,2348059
TotalMilliseconds : 234,8059
> measure-command {get-content .\ita\ita.txt | select -index 260000}
Days : 0
Hours : 0
Minutes : 0
Seconds : 36
Milliseconds : 591
Ticks : 365912596
TotalDays : 0,000423509949074074
TotalHours : 0,0101642387777778
TotalMinutes : 0,609854326666667
TotalSeconds : 36,5912596
TotalMilliseconds : 36591,2596
the winner is : ([System.IO.File]::ReadAllLines( path ))[index]
For Swift 3 the following has worked for me and the Swift 2 syntax has not worked:
// menu is a dictionary in this example
var menu = ["main course": 10.99, "dessert": 2.99, "salad": 5.99]
let sortedDict = menu.sorted(by: <)
// without "by:" it does not work in Swift 3
General Syntax:
7z a archive_name target parameters
Check your 7-Zip dir. Depending on the release you have, 7z may be replaced with 7za in the syntax.
Parameters:
Eg. This will prompt for a PW and hide file structures:
7z a archive_name target -p -mhe=on
Eg. No prompt, visible file structure:
7z a archive_name target -pPUT_PASSWORD_HERE
And so on. If you leave target blank, 7z will assume * in current directory and it will recurs directories by default.
typeof(MyType).GetField("fieldName", BindingFlags.NonPublic | BindingFlags.Instance)
CURL OPERATION BETWEEN SERVER TO SERVER WITHOUT HTML FORM IN PHP USING MULTIPART/FORM-DATA
// files to upload
$filename = "https://example.s3.amazonaws.com/0.jpg";
// URL to upload to (Destination server)
$url = "https://otherserver/image";
AND
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
//CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => file_get_contents($filename),
CURLOPT_HTTPHEADER => array(
//"Authorization: Bearer $TOKEN",
"Content-Type: multipart/form-data",
"Content-Length: " . strlen(file_get_contents($filename)),
"API-Key: abcdefghi" //Optional if required
),
));
$response = curl_exec($curl);
$info = curl_getinfo($curl);
//echo "code: ${info['http_code']}";
//print_r($info['request_header']);
var_dump($response);
$err = curl_error($curl);
echo "error";
var_dump($err);
curl_close($curl);
I don't think you can make VS wrap at 80 columns (I'd find that terribly annoying) but you can insert a visual guideline at 80 columns so you know when is a good time to insert a newline.
Details on inserting a guideline at 80 characters for 3 different versions of visual studio.
It's critical to emphasize the comma (,
) in a when
clause. It acts as an ||
of an if
statement, that is, it does an OR comparison and not an AND comparison between the delimited expressions of the when
clause. See the following case statement:
x = 3
case x
when 3, x < 2 then 'apple'
when 3, x > 2 then 'orange'
end
=> "apple"
x
is not less than 2, yet the return value is "apple"
. Why? Because x
was 3 and since ',`` acts as an
||, it did not bother to evaluate the expression
x < 2'.
You might think that to perform an AND, you can do something like this below, but it doesn't work:
case x
when (3 && x < 2) then 'apple'
when (3 && x > 2) then 'orange'
end
=> nil
It doesn't work because (3 && x > 2)
evaluates to true, and Ruby takes the True value and compares it to x
with ===
, which is not true, since x
is 3.
To do an &&
comparison, you will have to treat case
like an if
/else
block:
case
when x == 3 && x < 2 then 'apple'
when x == 3 && x > 2 then 'orange'
end
In the Ruby Programming Language book, Matz says this latter form is the simple (and infrequently used) form, which is nothing more than an alternative syntax for if
/elsif
/else
. However, whether it is infrequently used or not, I do not see any other way to attach multiple &&
expressions for a given when
clause.
Sounds like you need to change the path to your java
executable to match the newest version.
Basically, installing the latest Java does not necessarily mean your machine is configured to use the latest version. You didn't mention any platform details, so that's all I can say.
A slightly less verbose way is to use the performSelector: withObject: afterDelay: which sets up the NSTimer object for you and can be easily cancelled
So continuing with the previous example this would be
[self performSelector:@selector(goToSecondButton) withObject:nil afterDelay:.06];
More info in the doc
You can simply add a right float to .block2 element and place it in the first position (this is very important).
Here is the code:
<html>
<head>
<style type="text/css">
.block1 {
color: red;
width: 100px;
border: 1px solid green;
}
.block2 {
color: blue;
width: 70px;
border: 2px solid black;
position: relative;
float: right;
}
</style>
</head>
<body>
<div class='block1'>
<div class='block2'>block2</div>
<p>text</p>
<p>text2</p>
</div>
</body>
Regards...
$array = array(
22 => true,
25 => true,
34 => true,
35 => true,
);
print_r(
array_replace($array, [
22 => true,
42 => true,
])
);
print_r(
array_merge($array, [
22 => true,
42 => true,
])
);
If it is numeric but not sequential associative array, you need to use array_replace
For those who prefer using the Task Scheduler, it's possible to schedule a task to run after a restart / shutdown has been initiated by setting the task to run after event 1074 in the System log in the Event Viewer has been logged. However, it's only good for very short task, which will run as long as the system is restarting / shutting down, which is usually only a few seconds.
Begin the task: On an event
Log: System
Source: USER32
EventID: 1074
schtasks /create /tn "taskname" /tr "task file" /sc onevent /ec system /mo *[system/eventid=1074]
Comment: the /ec option is available from Windows Vista and above. (thank you @t2d)
Please note that the task status can be:
The operation being requested was not performed because the user has not logged on to the network. The specified service does not exist. (0x800704DD)
However, it doesn't mean that it didn't run.
$this
is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).
It sounds like IIS is listening to port 80 for HTTP requests.
Try stopping IIS by going into Control Panel/Administrative Tools/Internet Information Services, right-clicking on Default Web Site, and click on the Stop option in the popup menu, and see if the listener on port 80 has cleared.