Assume that you have 2 branches,
"branchA" : includes commits you want to copy (from "commitA" to "commitB"
"branchB" : the branch you want the commits to be transferred from "branchA"
1)
git checkout <branchA>
2) get the IDs of "commitA" and "commitB"
3)
git checkout <branchB>
4)
git cherry-pick <commitA>^..<commitB>
5) In case you have a conflict, solve it and type
git cherry-pick --continue
to continue the cherry-pick process.
Depends what it does. If your app takes up too much memory, or makes calls to functions/classes it shouldn't, SpringBoard may terminate it. However, it will most likely be rejected by Apple, as it does not follow their 7 background uses.
Using "groupby" and list comprehension:
Storing all the split dataframe in list variable and accessing each of the seprated dataframe by their index.
DF = pd.DataFrame({'chr':["chr3","chr3","chr7","chr6","chr1"],'pos':[10,20,30,40,50],})
ans = [pd.DataFrame(y) for x, y in DF.groupby('chr', as_index=False)]
accessing the separated DF like this:
ans[0]
ans[1]
ans[len(ans)-1] # this is the last separated DF
accessing the column value of the separated DF like this:
ansI_chr=ans[i].chr
I used Dynamic Programming & Memoization to find count of subsets from a set having a particular total. The code below code is in java. Have included the comments to explain the code intentions -
package com.company.dynamicProgramming;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class FindSumInSubSet {
public static void main(String...args){
int[] arr = {3, 2, 4, 6, 10};
int total = 16;
// Challenge is to find the subsets of numbers total 6 in above super set (represented as array)
// In general - Write a code to count subset of elements totalling m(6 above) in given set of n(9 as array size above) elements
Map<Entry, Integer> memoMap = new HashMap<>();
Entry entry = new Entry(total, arr.length-1);
int count = countSubSetForSum(arr, entry, memoMap);
System.out.format("In set of %d elements, the number of subsets having total=%d is %d %n", arr.length,total, count);
}
static int countSubSetForSum(int[] arr, Entry entry, Map<Entry, Integer> memoMap){
int total = entry.getTotal();
int i = entry.getI();
if (total == 0){ // means element was equal in previous recursion
return 1;
}else if(total < 0){ // means element was less in previous recursion i.e. not equal
return 0;
}else if (i < 0){ // means arr was finished previous recursion
return 0;
}else if (arr[i] > total){ // means element is greater than total
// i.e. leave that element and look further sets excluding this element
return getCountForIthAndTotal(arr, new Entry( total, i-1), memoMap);
}else{ // means element is less than total i.e. 2 possibilities :
// 1st - look further sets including this element
// 2nd - look further sets excluding this element
return getCountForIthAndTotal(arr, new Entry( total-arr[i], i-1), memoMap) +
getCountForIthAndTotal(arr, new Entry( total, i-1), memoMap);
}
}
static int getCountForIthAndTotal(int[] arr, Entry entry, Map<Entry, Integer> memoMap){
if (memoMap.containsKey(entry)){ //look up in has table if we already calculated particular total for ith subset..
return memoMap.get(entry); //This is nothing but using memoization that reduce the entire below code i.e. further recursion -
}else {
int count = countSubSetForSum(arr, entry, memoMap); //Recursion
memoMap.put(entry, count); //Build memoization
return count;
}
}
//Just Data Structure for Key in HashMap (memoMaP)... intent to include particular total for ith element's subset.
static class Entry {
int total;
int i;
public Entry(int total, int i) {
this.total = total;
this.i = i;
}
public int getTotal() {
return total;
}
public int getI() {
return i;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Entry entry = (Entry) o;
return total == entry.total &&
i == entry.i;
}
@Override
public int hashCode() {
return Objects.hash(total, i);
}
}
}
When i ran this the out put is :
In set of 5 elements, the number of subsets having total=16 is 2
Process finished with exit code 0
In the Blade Template : define a variable like this
@extends('app',['title' => 'Your Title Goes Here'])
@section('content')
And in the app.blade.php or any other of your choice ( I'm just following default Laravel 5 setup )
<title>{{ $title or 'Default title Information if not set explicitly' }}</title>
This is my first answer here. Hope it works.Good luck!
When the JVM loads classes, or otherwise sees a literal string, or some code intern
s a string, it adds the string to a mostly-hidden lookup table that has one copy of each such string. If another copy is added, the runtime arranges it so that all the literals refer to the same string object. This is called "interning". If you say something like
String s = "test";
return (s == "test");
it'll return true
, because the first and second "test" are actually the same object. Comparing interned strings this way can be much, much faster than String.equals
, as there's a single reference comparison rather than a bunch of char
comparisons.
You can add a string to the pool by calling String.intern()
, which will give you back the pooled version of the string (which could be the same string you're interning, but you'd be crazy to rely on that -- you often can't be sure exactly what code has been loaded and run up til now and interned the same string). The pooled version (the string returned from intern
) will be equal to any identical literal. For example:
String s1 = "test";
String s2 = new String("test"); // "new String" guarantees a different object
System.out.println(s1 == s2); // should print "false"
s2 = s2.intern();
System.out.println(s1 == s2); // should print "true"
In React Router version 5.0.1 and above, you can use:
<Link to="route" target="_blank" onClick={(event) => {event.preventDefault(); window.open(this.makeHref("route"));}} />
Use Thread.sleep(100);
.
The unit of time is milliseconds
For example:
public class SleepMessages {
public static void main(String args[])
throws InterruptedException {
String importantInfo[] = {
"Mares eat oats",
"Does eat oats",
"Little lambs eat ivy",
"A kid will eat ivy too"
};
for (int i = 0;
i < importantInfo.length;
i++) {
//Pause for 4 seconds
Thread.sleep(4000);
//Print a message
System.out.println(importantInfo[i]);
}
}
}
I had the same issue. I used yarn instead of npm to install the dependencies and it worked.
yarn add *****
The issue is in the line -
grade_1, grade_2, grade_3, average = 0.0
and
fName, lName, ID, converted_ID = ""
In python, if the left hand side of the assignment operator has multiple variables, python would try to iterate the right hand side that many times and assign each iterated value to each variable sequentially. The variables grade_1, grade_2, grade_3, average
need three 0.0
values to assign to each variable.
You may need something like -
grade_1, grade_2, grade_3, average = [0.0 for _ in range(4)]
fName, lName, ID, converted_ID = ["" for _ in range(4)]
There is a jQuery plugin that can deal with this very well
http://www.jqui.net/jquery-projects/jquery-mutate-official/
here is a demo of it with different scenarios as to when the height change, if you resize the red bordered div.
Try Html.EditorFor
helper method instead of Html.TextBoxFor
.
Just add your text between the font tags:
for blue color
<string name="hello_world"><font color='blue'>Hello world!</font></string>
or for red color
<string name="hello_world"><font color='red'>Hello world!</font></string>
There is a another best/effective way to solve this error,
for example, let's take a loop which counts till 10 thousand, here you may get the error Out of memory
, do to solve it you can give the computer time to recover.
So, you can sleep for 400-500ms
before you're loop counts the next number :
new Thread(new Runnable() {
public void run() {
try {
sleep(550); // 550 ms (milli seconds)
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
By doing this, will make you're program slower but you don't get any error till the heap space
is full again, so by waiting some ms
, you can prevent that error.
You can apply this method other than loop.
Hope it helped you, :D
Piping to xargs is a dirty way of doing that which can be done inside of find.
find . -type d -exec chmod 0755 {} \;
find . -type f -exec chmod 0644 {} \;
You can be even more controlling with other options, such as:
find . -type d -user harry -exec chown daisy {} \;
You can do some very cool things with find and you can do some very dangerous things too. Have a look at "man find", it's long but is worth a quick read. And, as always remember:
Also, does Jenkins delete the artifacts after each build ? (not the archived artifacts, I know I can tell it to delete those)
No, Hudson/Jenkins does not, by itself, clear the workspace after a build. You might have actions in your build process that erase, overwrite, or move build artifacts from where you left them. There is an option in the job configuration, in Advanced Project Options (which must be expanded), called "Clean workspace before build" that will wipe the workspace at the beginning of a new build.
Just use Date
constructor to compare with string input:
function isDate(str) {_x000D_
return 'string' === typeof str && (dt = new Date(str)) && !isNaN(dt) && str === dt.toISOString().substr(0, 10);_x000D_
}_x000D_
_x000D_
console.log(isDate("2018-08-09"));_x000D_
console.log(isDate("2008-23-03"));_x000D_
console.log(isDate("0000-00-00"));_x000D_
console.log(isDate("2002-02-29"));_x000D_
console.log(isDate("2004-02-29"));
_x000D_
Edited: Responding to one of the comments
Hi, it does not work on IE8 do you have a solution for – Mehdi Jalal
function pad(n) {_x000D_
return (10 > n ? ('0' + n) : (n));_x000D_
}_x000D_
_x000D_
function isDate(str) {_x000D_
if ('string' !== typeof str || !/\d{4}\-\d{2}\-\d{2}/.test(str)) {_x000D_
return false;_x000D_
}_x000D_
var dt = new Date(str.replace(/\-/g, '/'));_x000D_
return dt && !isNaN(dt) && 0 === str.localeCompare([dt.getFullYear(), pad(1 + dt.getMonth()), pad(dt.getDate())].join('-'));_x000D_
}_x000D_
_x000D_
console.log(isDate("2018-08-09"));_x000D_
console.log(isDate("2008-23-03"));_x000D_
console.log(isDate("0000-00-00"));_x000D_
console.log(isDate("2002-02-29"));_x000D_
console.log(isDate("2004-02-29"));
_x000D_
typedef struct{
char name[30];
char surname[30];
int age;
} data;
defines that data
should be a block of memory that fits 60 chars plus 4 for the int (see note)
[----------------------------,------------------------------,----]
^ this is name ^ this is surname ^ this is age
This allocates the memory on the stack.
data s1;
Assignments just copies numbers, sometimes pointers.
This fails
s1.name = "Paulo";
because the compiler knows that s1.name
is the start of a struct 64 bytes long, and "Paulo"
is a char[] 6 bytes long (6 because of the trailing \0 in C strings)
Thus, trying to assign a pointer to a string into a string.
To copy "Paulo" into the struct at the point name
and "Rossi" into the struct at point surname
.
memcpy(s1.name, "Paulo", 6);
memcpy(s1.surname, "Rossi", 6);
s1.age = 1;
You end up with
[Paulo0----------------------,Rossi0-------------------------,0001]
strcpy
does the same thing but it knows about \0
termination so does not need the length hardcoded.
Alternatively you can define a struct which points to char arrays of any length.
typedef struct {
char *name;
char *surname;
int age;
} data;
This will create
[----,----,----]
This will now work because you are filling the struct with pointers.
s1.name = "Paulo";
s1.surname = "Rossi";
s1.age = 1;
Something like this
[---4,--10,---1]
Where 4 and 10 are pointers.
Note: the ints and pointers can be different sizes, the sizes 4 above are 32bit as an example.
Dates are stored in their timestamp format. If you want everything that belongs to a specific month, query for the start and the end of the month.
var start = new Date(2010, 11, 1);
var end = new Date(2010, 11, 30);
db.posts.find({created_on: {$gte: start, $lt: end}});
//taken from http://cookbook.mongodb.org/patterns/date_range/
I had faced the similar error, it is basically caused when use the ad blockers.Turn them off, and you run it easily.
try this
sizes.OrderBy(x => Convert.ToInt32(x)).ToList<string>();
Note: this will helpful when all are string convertable to int.....
This also can happen if the device you are trying to run on has some older version of the provisioning profile you are using that points to an old, expired or revoked certificate or a certificate without associated private key. Delete any invalid Provisioning Profiles under your device section in Xcode organizer.
For running it on any CPU either 62 bit or 32 bit follow these steps: Right click on the name of the project in Solution Explorer> Properties>Build and have these under Configuration: Active(Release), Platform:Active(Any CPU) and Target:x86. and just beside the Run button Select option Release and Any CPU from the options. And then Save it and Run.
I needed this:
$('#myTable tbody > tr').remove();
It deletes all rows except the header.
see tag input example :
<div class="input-group date" data-target-input="nearest">
<input type="text" class="form-control datetimepicker-input form-control-sm" data-target="#dt_expdate" id="dt_expdate" />
<div class="input-group-append" data-target="#dt_expdate" data-toggle="datetimepicker">
<div class="input-group-text form-control-sm"><i class="fa fa-calendar"></i></div>
</div>
</div>
acess to get & assign value from
id="dt_expdate"
get value:
var date= $("#dt_expdate").val();
assign value:
$("#dt_expdate").val('20/08/2020');
From a client perspective, static behavior is known to the client but Singleton behavior can be completed hidden from a client. Client may never know that there only one single instance he's playing around with again and again.
<summary>
and <details>
Using <summary>
and <details>
elements is the simplest but see browser support as current IE is not supporting it. You can polyfill though (most are jQuery-based). Do note that unsupported browser will simply show the expanded version of course, so that may be acceptable in some cases.
/* Optional styling */_x000D_
summary::-webkit-details-marker {_x000D_
color: blue;_x000D_
}_x000D_
summary:focus {_x000D_
outline-style: none;_x000D_
}
_x000D_
<details>_x000D_
<summary>Summary, caption, or legend for the content</summary>_x000D_
Content goes here._x000D_
</details>
_x000D_
See also how to style the <details>
element (HTML5 Doctor) (little bit tricky).
The :target
selector has a pretty good browser support, and it can be used to make a single collapsible element within the frame.
.details,_x000D_
.show,_x000D_
.hide:target {_x000D_
display: none;_x000D_
}_x000D_
.hide:target + .show,_x000D_
.hide:target ~ .details {_x000D_
display: block;_x000D_
}
_x000D_
<div>_x000D_
<a id="hide1" href="#hide1" class="hide">+ Summary goes here</a>_x000D_
<a id="show1" href="#show1" class="show">- Summary goes here</a>_x000D_
<div class="details">_x000D_
Content goes here._x000D_
</div>_x000D_
</div>_x000D_
<div>_x000D_
<a id="hide2" href="#hide2" class="hide">+ Summary goes here</a>_x000D_
<a id="show2" href="#show2" class="show">- Summary goes here</a>_x000D_
<div class="details">_x000D_
Content goes here._x000D_
</div>_x000D_
</div>
_x000D_
You could use CSS to attain this. By specifying the list in the color and style of your choice, you can then also specify the text as a different color.
Follow the example at http://www.echoecho.com/csslists.htm.
This will work (pure JS, appending to a div of id myDiv
):
Demo: http://jsfiddle.net/4pwvg/
var myParent = document.body;_x000D_
_x000D_
//Create array of options to be added_x000D_
var array = ["Volvo","Saab","Mercades","Audi"];_x000D_
_x000D_
//Create and append select list_x000D_
var selectList = document.createElement("select");_x000D_
selectList.id = "mySelect";_x000D_
myParent.appendChild(selectList);_x000D_
_x000D_
//Create and append the options_x000D_
for (var i = 0; i < array.length; i++) {_x000D_
var option = document.createElement("option");_x000D_
option.value = array[i];_x000D_
option.text = array[i];_x000D_
selectList.appendChild(option);_x000D_
}
_x000D_
I like Roger Cruz's answer of:
width: fit-content;
and I just want to add that you can use
padding: 0px 10px;
to add a nice 10px padding on the right and left side of the text in the button. Otherwise the text would be right up along the edge of the button and that wouldn't look good.
Try This...
<html>_x000D_
_x000D_
<head>_x000D_
<script>_x000D_
function myFunction() {_x000D_
var number = "123";_x000D_
document.getElementById("myText").innerHTML = number;_x000D_
}_x000D_
</script>_x000D_
</head>_x000D_
_x000D_
<body onload="myFunction()">_x000D_
_x000D_
<h1>"The value for number is: " <span id="myText"></span></h1>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
You can see the println()
statements in the Run
window of Android Studio.
See detailed answer with screenshot here.
You can use following formulas.
For Excel 2007 or later:
=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")
For Excel 2003:
=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))
Note, that
List!A:C
in VLOOKUP
and returns value from column ? 3
VLOOKUP
equals to FALSE
, in that case VLOOKUP
will only find an exact match, and the values in the first column of List!A:C
do not need to be sorted (opposite to case when you're using TRUE
).Basic ripple setup
Ripples contained within the view.
android:background="?selectableItemBackground"
Ripples that extend beyond the view's bounds:
android:background="?selectableItemBackgroundBorderless"
Have a look here for resolving ?(attr)
xml references in Java code.
Support Library
?attr:
(or the ?
shorthand) instead of ?android:attr
references the support library, so is available back to API 7.Ripples with images/backgrounds
View
in a FrameLayout
with the ripple set with setForeground()
or setBackground()
.Honestly there is no clean way of doing this otherwise.
Oh boy! This looks bad! The only option that I can think of is that the working copy is corrupt.
Try deleting the working copy, performing a fresh checkout and performing the merge again.
If that doesn't work, then log a bug.
I know this is an oldie but here is a quick way to hide the scroll bar with pure CSS.
Just add
::-webkit-scrollbar {display:none;}
To your id or class of the div you're using the scroll bar with.
Here is a helpful link Custom Scroll Bar in Webkit
This actually sums it up pretty nicely.
API Levels generally mean that as a programmer, you can communicate with the devices' built in functions and functionality. As the API level increases, functionality adds up (although some of it can get deprecated).
Choosing an API level for an application development should take at least two thing into account:
Android API levels can be divided to five main groups (not scientific, but what the heck):
To elaborate Steven Spielberg's answer, I did this in such a case:
$('a').click(function() {
$(this).attr('target', '_blank');
});
This way, just before the browser will follow the link I'm setting the target attribute, so it will make the link open in a new tab or window (depends on user's settings).
One line example in jQuery:
$('a').attr('target', '_blank').get(0).click();
// The `.get(0)` must be there to return the actual DOM element.
// Doing `.click()` on the jQuery object for it did not work.
This can also be accomplished just using native browser DOM APIs as well:
document.querySelector('a').setAttribute('target', '_blank');
document.querySelector('a').click();
I know that JSON.stringfy is slow when dealing with large datasets but what if you used template literals?
Example:
const a = [1, 2, 3];
const b = [1, 2, 'test'];
const a_string = Array.isArray(a) && `${a}`;
const b_string = Array.isArray(b) && `${b}`;
const result = (a === b);
console.log(result);
Taking into consideration you're using ES6 of course.
=)
upper answer only near solving the Problem. heres your answer:
Integer.decode(Character.toString(char c));
You can use the SharedPreferences to identify if it is the "First time" the app is launched. Just use a Boolean variable ("my_first_time") and change its value to false when your task for "first time" is over.
This is my code to catch the first time you open the app:
final String PREFS_NAME = "MyPrefsFile";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if (settings.getBoolean("my_first_time", true)) {
//the app is being launched for first time, do something
Log.d("Comments", "First time");
// first time task
// record the fact that the app has been started at least once
settings.edit().putBoolean("my_first_time", false).commit();
}
In my case, I added GoogleService-Info.plist
file twice disappointedly to my Firebase project.
I delete first added GoogleService-Info.plist
and problem solved.
Install PAR::Packer
. Example for *nix:
sudo cpan -i PAR::Packer
For Strawberry Perl for Windows or for ActivePerl and MSVC installed:
cpan -i PAR::Packer
Pack it with pp
. It will create an executable named "example" or "example.exe" on Windows.
pp -o example example.pl
This would work only on the OS where it was built.
P.S. It is really hard to find a Unix clone without Perl. Did you mean Windows?
-D, --dump-header <file>
Write the protocol headers to the specified file.
This option is handy to use when you want to store the headers
that a HTTP site sends to you. Cookies from the headers could
then be read in a second curl invocation by using the -b,
--cookie option! The -c, --cookie-jar option is however a better
way to store cookies.
and
-S, --show-error
When used with -s, --silent, it makes curl show an error message if it fails.
and
-L/--location
(HTTP/HTTPS) If the server reports that the requested page has moved to a different location (indicated with a Location: header and a 3XX response
code), this option will make curl redo the request on the new place. If used together with -i/--include or -I/--head, headers from all requested
pages will be shown. When authentication is used, curl only sends its credentials to the initial host. If a redirect takes curl to a different
host, it won’t be able to intercept the user+password. See also --location-trusted on how to change this. You can limit the amount of redirects to
follow by using the --max-redirs option.
When curl follows a redirect and the request is not a plain GET (for example POST or PUT), it will do the following request with a GET if the HTTP
response was 301, 302, or 303. If the response code was any other 3xx code, curl will re-send the following request using the same unmodified
method.
from the man page. so
curl -sSL -D - www.acooke.org -o /dev/null
follows redirects, dumps the headers to stdout and sends the data to /dev/null (that's a GET, not a POST, but you can do the same thing with a POST - just add whatever option you're already using for POSTing data)
note the -
after the -D
which indicates that the output "file" is stdout.
If you add this to your meta tags:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
IE8 will render the page like IE7.
// SharedPrefHelper is a class contains the get and save sharedPrefernce data
public class SharedPrefHelper {
// save data in sharedPrefences
public static void setSharedOBJECT(Context context, String key,
Object value) {
SharedPreferences sharedPreferences = context.getSharedPreferences(
context.getPackageName(), Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(value);
prefsEditor.putString(key, json);
prefsEditor.apply();
}
// get data from sharedPrefences
public static Object getSharedOBJECT(Context context, String key) {
SharedPreferences sharedPreferences = context.getSharedPreferences(
context.getPackageName(), Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString(key, "");
Object obj = gson.fromJson(json, Object.class);
User objData = new Gson().fromJson(obj.toString(), User.class);
return objData;
}
}
// save data in your activity
User user = new User("Hussein","[email protected]","3107310890983");
SharedPrefHelper.setSharedOBJECT(this,"your_key",user);
User data = (User) SharedPrefHelper.getSharedOBJECT(this,"your_key");
Toast.makeText(this,data.getName()+"\n"+data.getEmail()+"\n"+data.getPhone(),Toast.LENGTH_LONG).show();
// User is the class you want to save its objects
public class User {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
private String name,email,phone;
public User(String name,String email,String phone){
this.name=name;
this.email=email;
this.phone=phone;
}
}
// put this in gradle
compile 'com.google.code.gson:gson:2.7'
hope this helps you :)
Yes, people use these terms interchangeably with regard to MySQL. Though oftentimes you will hear people inappropriately refer to the entire database server as the database.
select <column list> into <dest. table> from <source table>;
You could do this way.
SELECT windows_release, windows_service_pack_level,
windows_sku, os_language_version
into new_table_name
FROM sys.dm_os_windows_info OPTION (RECOMPILE);
CAUSE:
The error is happening because your project folder is owned by the root user.
SOLUTION
Change ownership to the currently signed in user and not the root user. If you only have root as the sole user, create another user with root privileges.
$ sudo chown -R current_user /my/project/directory/
then
$ composer install
Distributed (a)synchronous computing.
A real world example could be an application-wide notification framework, which sends mails to the stakeholders at various points during the course of application usage. So the application would act as a Producer
by create a Message
object, putting it on a particular Queue
, and moving forward.
There would be a set of Consumer
s who would subscribe to the Queue
in question, and would take care handling the Message
sent across. Note that during the course of this transaction, the Producer
s are decoupled from the logic of how a given Message
would be handled.
Messaging frameworks (ActiveMQ and the likes) act as a backbone to facilitate such Message
transactions by providing MessageBroker
s.
This work well on Windows:
npm install --save-dev copyfiles
package.json
I have a copy task : "copy": "copyfiles -u 1 ./app/index.html ./deploy"
This move my index.html from the app folder into the deploy folder.
You can now use CSS Grid to fix this.
<div class="outer">
<div class="top"> </div>
<div class="below"> </div>
</div>
And the css for this:
.outer {
display: grid;
grid-template: 1fr / 1fr;
place-items: center;
}
.outer > * {
grid-column: 1 / 1;
grid-row: 1 / 1;
}
.outer .below {
z-index: 2;
}
.outer .top {
z-index: 1;
}
The most upvoted answer is not implementing a real slide in/out (or down/up), as:
translateY(-100%)
and then suddenly disappears, causing another glitch on the elements below it.You can implement a slide in and slide out like so:
my-component.ts
import { animate, style, transition, trigger } from '@angular/animations';
@Component({
...
animations: [
trigger('slideDownUp', [
transition(':enter', [style({ height: 0 }), animate(500)]),
transition(':leave', [animate(500, style({ height: 0 }))]),
]),
],
})
my-component.html
<div @slideDownUp *ngIf="isShowing" class="box">
I am the content of the div!
</div>
my-component.scss
.box {
overflow: hidden;
}
From the command line, enter the folder where your database file is located and execute the following command:
chmod 777 databasefilename
This will grant all permissions to all users.
use zip
columns = zip(*rows) #transpose rows to columns
print columns[0] #print the first column
#you can also do more with the columns
print columns[1] # or print the second column
columns.append([7,7,7]) #add a new column to the end
backToRows = zip(*columns) # now we are back to rows with a new column
print backToRows
you can also use numpy
a = numpy.array(a)
print a[:,0]
Edit: zip object is not subscriptable. It need to be converted to list to access as list:
column = list(zip(*row))
If you feel like reinventing the wheel, the following may work for you:
public static IEnumerable<string> SplitCSV(string line)
{
var s = new StringBuilder();
bool escaped = false, inQuotes = false;
foreach (char c in line)
{
if (c == ',' && !inQuotes)
{
yield return s.ToString();
s.Clear();
}
else if (c == '\\' && !escaped)
{
escaped = true;
}
else if (c == '"' && !escaped)
{
inQuotes = !inQuotes;
}
else
{
escaped = false;
s.Append(c);
}
}
yield return s.ToString();
}
It would be good to know what your purpose is, why you want to initialize the keys in the first place. I am not sure you need to do that at all.
1) If you want to count the number of occurrences of keys, you can just do:
Definition = {}
# ...
Definition[key] = Definition.get(key, 0) + 1
2) If you want to get None (or some other value) later for keys that you did not encounter, again you can just use the get() method:
Definition.get(key) # returns None if key not stored
Definition.get(key, default_other_than_none)
3) For all other purposes, you can just use a list of the expected keys, and check if the keys found later match those.
For example, if you only want to store values for those keys:
expected_keys = ['apple', 'banana']
# ...
if key_found in expected_keys:
Definition[key_found] = value
Or if you want to make sure all expected keys were found:
assert(all(key in Definition for key in expected_keys))
Go to control panel --> Java You can select the active version here
I believe that if you run git branch --all
from Bash that the list of remote and local branches you see will reflect what your local Git "knows" about at the time you run the command. Because your Git is always up to date with regard to the local branches in your system, the list of local branches will always be accurate.
However, for remote branches this need not be the case. Your local Git only knows about remote branches which it has seen in the last fetch (or pull). So it is possible that you might run git branch --all
and not see a new remote branch which appeared after the last time you fetched or pulled.
To ensure that your local and remote branch list be up to date you can do a git fetch
before running git branch --all
.
For further information, the "remote" branches which appear when you run git branch --all
are not really remote at all; they are actually local. For example, suppose there be a branch on the remote called feature
which you have pulled at least once into your local Git. You will see origin/feature
listed as a branch when you run git branch --all
. But this branch is actually a local Git branch. When you do git fetch origin
, this tracking branch gets updated with any new changes from the remote. This is why your local state can get stale, because there may be new remote branches, or your tracking branches can become stale.
If the users enter an incorrect value, apply a 1px red color border to the input field:
document.getElementById('fName').style.border ="1px solid red";
If the user enters a correct value, remove the border from the input field:
document.getElementById('fName').style.border ="";
The --net=host
option is used to make the programs inside the Docker container look like they are running on the host itself, from the perspective of the network. It allows the container greater network access than it can normally get.
Normally you have to forward ports from the host machine into a container, but when the containers share the host's network, any network activity happens directly on the host machine - just as it would if the program was running locally on the host instead of inside a container.
While this does mean you no longer have to expose ports and map them to container ports, it means you have to edit your Dockerfiles to adjust the ports each container listens on, to avoid conflicts as you can't have two containers operating on the same host port. However, the real reason for this option is for running apps that need network access that is difficult to forward through to a container at the port level.
For example, if you want to run a DHCP server then you need to be able to listen to broadcast traffic on the network, and extract the MAC address from the packet. This information is lost during the port forwarding process, so the only way to run a DHCP server inside Docker is to run the container as --net=host
.
Generally speaking, --net=host
is only needed when you are running programs with very specific, unusual network needs.
Lastly, from a security perspective, Docker containers can listen on many ports, even though they only advertise (expose) a single port. Normally this is fine as you only forward the single expected port, however if you use --net=host
then you'll get all the container's ports listening on the host, even those that aren't listed in the Dockerfile. This means you will need to check the container closely (especially if it's not yours, e.g. an official one provided by a software project) to make sure you don't inadvertently expose extra services on the machine.
Replacement groups provide impler approach resolving replacement of multiple white space characters with same single one:
public static void WhiteSpaceReduce()
{
string t1 = "a b c d";
string t2 = "a b\n\nc\nd";
Regex whiteReduce = new Regex(@"(?<firstWS>\s)(?<repeatedWS>\k<firstWS>+)");
Console.WriteLine("{0}", t1);
//Console.WriteLine("{0}", whiteReduce.Replace(t1, x => x.Value.Substring(0, 1)));
Console.WriteLine("{0}", whiteReduce.Replace(t1, @"${firstWS}"));
Console.WriteLine("\nNext example ---------");
Console.WriteLine("{0}", t2);
Console.WriteLine("{0}", whiteReduce.Replace(t2, @"${firstWS}"));
Console.WriteLine();
}
Please notice the second example keeps single \n
while accepted answer would replace end of line with space.
If you need to replace any combination of white space characters with the first one, just remove the back-reference \k
from the pattern.
The toString()
implementation of java.util.Date
does not depend on the way the class is imported. It always returns a nice formatted date.
The toString()
you see comes from another class.
Specific import have precedence over wildcard imports.
in this case
import other.Date
import java.util.*
new Date();
refers to other.Date
and not java.util.Date
.
The odd thing is that
import other.*
import java.util.*
Should give you a compiler error stating that the reference to Date is ambiguous because both other.Date
and java.util.Date
matches.
SELECT *
FROM A.tableA JOIN B.tableB
or
SELECT *
FROM A.tableA JOIN B.tableB
ON A.tableA.id = B.tableB.a_id;
Simply execute
CKEDITOR.instances[elementId].getData();
with element id = id
of element assigned the editor.
1) You can put your favicon where you want and add this tag to your page head
<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />
although some browsers will try to get the favicon from /favicon.ico by default, so you should use the IgnoreRoute.
2) If a browser makes a request for the favicon in another directory it will get a 404 error wich is fine and if you have the link tag in answer 1 in your master page the browser will get the favicon you want.
Either:
(This strange error message is produced by Oracle's JDBC driver when it can't connect to the database server. 'Network adapter' appears to refer to some component of their code, which isn't very useful. Real network adapters (NICs) don't establish connections at all: TCP protocol stacks do that. It would have been a lot more useful if they had just let the original ConnectException
be thrown, or at least used its error message and let it appear in the stack trace.)
Reload is easy. You should use:
location.reload(true);
And detecting back is :
window.history.pushState('', null, './');
$(window).on('popstate', function() {
location.reload(true);
});
From MSDN:
C#, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection. However, it is usually best to release limited resources such as file handles and network connections as quickly as possible.
The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.
In other words, the using
statement tells .NET to release the object specified in the using
block once it is no longer needed.
To handle the situation in which there is no wiring, beans are available with @Autowired
required
attribute set to false
.
But when using @Inject
, the Provider interface works with the bean which means that the bean is not injected directly but with the Provider.
var idPost=document.getElementById("status").innerHTML;
The 'status' element does not exist in your webpage.
So document.getElementById("status") return null. While you can not use innerHTML property of NULL.
You should add a condition like this:
if(document.getElementById("status") != null){
var idPost=document.getElementById("status").innerHTML;
}
Hope this answer can help you. :)
Some important facts were not given in other answers:
"async await" is more complex at CIL level and thus costs memory and CPU time.
Any task can be canceled if the waiting time is unacceptable.
In the case "async await" we do not have a handler for such a task to cancel it or monitoring it.
Using Task is more flexible then "async await".
Any sync functionality can by wrapped by async.
public async Task<ActionResult> DoAsync(long id)
{
return await Task.Run(() => { return DoSync(id); } );
}
"async await" generate many problems. We do not now is await statement will be reached without runtime and context debugging. If first await not reached everything is blocked. Some times even await seems to be reached still everything is blocked:
https://github.com/dotnet/runtime/issues/36063
I do not see why I'm must live with the code duplication for sync and async method or using hacks.
Conclusion: Create Task manually and control them is much better. Handler to Task give more control. We can monitor Tasks and manage them:
https://github.com/lsmolinski/MonitoredQueueBackgroundWorkItem
Sorry for my english.
There are few steps if we dont use "create-react-app",([email protected]) first we should install file-loader as devDedepencie,next step is to add rule in webpack.config
{
test: /\.(png|jpe?g|gif)$/i,
loader: 'file-loader',
}
_x000D_
, then in our src directory we should make file called declarationFiles.d.ts(for example) and register modules inside
declare module '*.jpg';
declare module '*.png';
_x000D_
,then restart dev-server. After these steps we can import and use images like in code bellow
import React from 'react';
import image from './img1.png';
import './helloWorld.scss';
const HelloWorld = () => (
<>
<h1 className="main">React TypeScript Starter</h1>
<img src={image} alt="some example image" />
</>
);
export default HelloWorld;
_x000D_
Works in typescript and also in javacript,just change extension from .ts to .js
Cheers.
<script type="text/javascript" src="https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element');
}
</script>
I have done this before, I think you need to remove the ActionResult. Make it a void and remove the return View(MyView). this is the solution
Added jQuery.browser.webkit
to the "else if" for Chrome. Could not get this working in Chrome 23.
Made this script below for selecting the content in a <pre>
tag that has the class="code"
.
jQuery( document ).ready(function() {
jQuery('pre.code').attr('title', 'Click to select all');
jQuery( '#divFoo' ).click( function() {
var refNode = jQuery( this )[0];
if ( jQuery.browser.msie ) {
var range = document.body.createTextRange();
range.moveToElementText( refNode );
range.select();
} else if ( jQuery.browser.mozilla || jQuery.browser.opera || jQuery.browser.webkit ) {
var selection = refNode.ownerDocument.defaultView.getSelection();
console.log(selection);
var range = refNode.ownerDocument.createRange();
range.selectNodeContents( refNode );
selection.removeAllRanges();
selection.addRange( range );
} else if ( jQuery.browser.safari ) {
var selection = refNode.ownerDocument.defaultView.getSelection();
selection.setBaseAndExtent( refNode, 0, refNode, 1 );
}
} );
} );
select u from UserGroup ug inner join ug.user u
where ug.group_id = :groupId
order by u.lastname
As a named query:
@NamedQuery(
name = "User.findByGroupId",
query =
"SELECT u FROM UserGroup ug " +
"INNER JOIN ug.user u WHERE ug.group_id = :groupId ORDER BY u.lastname"
)
Use paths in the HQL statement, from one entity to the other. See the Hibernate documentation on HQL and joins for details.
You turn off pack_propagate
by setting pack_propagate(0)
Turning off pack_propagate
here basically says don't let the widgets inside the frame control it's size. So you've set it's width and height to be 500. Turning off propagate stills allows it to be this size without the widgets changing the size of the frame to fill their respective width / heights which is what would happen normally
To turn off resizing the root window, you can set root.resizable(0, 0)
, where resizing is allowed in the x
and y
directions respectively.
To set a maxsize to window, as noted in the other answer you can set the maxsize
attribute or minsize
although you could just set the geometry of the root window and then turn off resizing. A bit more flexible imo.
Whenever you set grid
or pack
on a widget it will return None
. So, if you want to be able to keep a reference to the widget object you shouldn't be setting a variabe to a widget where you're calling grid
or pack
on it. You should instead set the variable to be the widget Widget(master, ....)
and then call pack
or grid
on the widget instead.
import tkinter as tk
def startgame():
pass
mw = tk.Tk()
#If you have a large number of widgets, like it looks like you will for your
#game you can specify the attributes for all widgets simply like this.
mw.option_add("*Button.Background", "black")
mw.option_add("*Button.Foreground", "red")
mw.title('The game')
#You can set the geometry attribute to change the root windows size
mw.geometry("500x500") #You want the size of the app to be 500x500
mw.resizable(0, 0) #Don't allow resizing in the x or y direction
back = tk.Frame(master=mw,bg='black')
back.pack_propagate(0) #Don't allow the widgets inside to determine the frame's width / height
back.pack(fill=tk.BOTH, expand=1) #Expand the frame to fill the root window
#Changed variables so you don't have these set to None from .pack()
go = tk.Button(master=back, text='Start Game', command=startgame)
go.pack()
close = tk.Button(master=back, text='Quit', command=mw.destroy)
close.pack()
info = tk.Label(master=back, text='Made by me!', bg='red', fg='black')
info.pack()
mw.mainloop()
grep is the right tool for extracting.
using your example and your regex:
kent$ echo 'foo bar <foo> bla 1 2 3.4'|grep -o '[0-9][0-9]*[\ \t][0-9.]*[\ \t]*$'
2 3.4
Python started as a scripting language for Linux like Perl but less cryptic. Now it is used for both web and desktop applications and is available on Windows too. Desktop GUI APIs like GTK have their Python implementations and Python based web frameworks like Django are preferred by many over PHP et al. for web applications.
And by the way,
I had to get clean table without columns. I have done folowing:
jMyTable.setModel(new DefaultTableModel());
Here is an example to convert an NSData object to Base 64. It also shows how to go the other way (decode a base 64 encoded NSData object):
NSData *dataTake2 =
[@"iOS Developer Tips" dataUsingEncoding:NSUTF8StringEncoding];
// Convert to Base64 data
NSData *base64Data = [dataTake2 base64EncodedDataWithOptions:0];
// Do something with the data...
// Now convert back from Base64
NSData *nsdataDecoded = [base64Data initWithBase64EncodedData:base64Data options:0];
Each data type is capable of overloading each operator. If both the numerator and the denominator are integers, the integer type will perform the division operation and it will return an integer type. If you want floating point division, you must cast one or more of the number to floating point types before dividing them. For instance:
int x = 13;
int y = 4;
float x = (float)y / (float)z;
or, if you are using literals:
float x = 13f / 4f;
Keep in mind, floating points are not precise. If you care about precision, use something like the decimal type, instead.
scan
can read from a web page automatically; you don't necessarily have to mess with connections.
Add the css for .card
.card {
margin: 0 auto; /* Added */
float: none; /* Added */
margin-bottom: 10px; /* Added */
}
here is the pen
UPDATE:
You can use the class .mx-auto
available in bootstrap 4 to center cards.
There are multiple ways to achieve this. Here, I have explained the two most common approaches.
1. You can use axios interceptors to intercept any requests and add authorization headers.
// Add a request interceptor
axios.interceptors.request.use(function (config) {
const token = store.getState().session.token;
config.headers.Authorization = token;
return config;
});
2. From the documentation of axios
you can see there is a mechanism available which allows you to set default header which will be sent with every request you make.
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
So in your case:
axios.defaults.headers.common['Authorization'] = store.getState().session.token;
If you want, you can create a self-executable function which will set authorization header itself when the token is present in the store.
(function() {
String token = store.getState().session.token;
if (token) {
axios.defaults.headers.common['Authorization'] = token;
} else {
axios.defaults.headers.common['Authorization'] = null;
/*if setting null does not remove `Authorization` header then try
delete axios.defaults.headers.common['Authorization'];
*/
}
})();
Now you no longer need to attach token manually to every request. You can place the above function in the file which is guaranteed to be executed every time (e.g: File which contains the routes).
Hope it helps :)
The Serializable interface can be used the same way as the Parcelable one, resulting in (not much) better performances. Just overwrite those two methods to handle manual marshalling and unmarshalling process:
private void writeObject(java.io.ObjectOutputStream out)
throws IOException
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException
Still, it seems to me that when developing native Android, using the Android api is the way to go.
See :
Sorting by key:
public static void main(String[] args) {
Map<String,String> map = new HashMap<>();
map.put("b", "dd");
map.put("c", "cc");
map.put("a", "aa");
map = new TreeMap<>(map);
for (String key : map.keySet()) {
System.out.println(key+"="+map.get(key));
}
}
HTML standard on link rel=icon
Just for completeness, this is what the standard says: https://html.spec.whatwg.org/multipage/links.html#rel-icon
The icon keyword may be used with link elements. This keyword creates an external resource link.
The specified resource is an icon representing the page or site, and should be used by the user agent when representing the page in the user interface.
[...]
The following snippet shows the top part of an application with several icons.
<!DOCTYPE HTML> <html lang="en"> <head> <title>lsForums — Inbox</title> <link rel=icon href=favicon.png sizes="16x16" type="image/png"> <link rel=icon href=windows.ico sizes="32x32 48x48" type="image/vnd.microsoft.icon"> <link rel=icon href=mac.icns sizes="128x128 512x512 8192x8192 32768x32768"> <link rel=icon href=iphone.png sizes="57x57" type="image/png"> <link rel=icon href=gnome.svg sizes="any" type="image/svg+xml"> <link rel=stylesheet href=lsforums.css> <script src=lsforums.js></script> <meta name=application-name content="lsForums"> </head> <body> ...
For historical reasons, the icon keyword may be preceded by the keyword "shortcut". If the "shortcut" keyword is present, the rel attribute's entire value must be an ASCII case-insensitive match for the string "shortcut icon" (with a single U+0020 SPACE character between the tokens and no other ASCII whitespace).
With jQuery (and without FormData API) you can use something like this:
function readFile(file){
var loader = new FileReader();
var def = $.Deferred(), promise = def.promise();
//--- provide classic deferred interface
loader.onload = function (e) { def.resolve(e.target.result); };
loader.onprogress = loader.onloadstart = function (e) { def.notify(e); };
loader.onerror = loader.onabort = function (e) { def.reject(e); };
promise.abort = function () { return loader.abort.apply(loader, arguments); };
loader.readAsBinaryString(file);
return promise;
}
function upload(url, data){
var def = $.Deferred(), promise = def.promise();
var mul = buildMultipart(data);
var req = $.ajax({
url: url,
data: mul.data,
processData: false,
type: "post",
async: true,
contentType: "multipart/form-data; boundary="+mul.bound,
xhr: function() {
var xhr = jQuery.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position; /*event.position is deprecated*/
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
def.notify(percent);
}
}, false);
}
return xhr;
}
});
req.done(function(){ def.resolve.apply(def, arguments); })
.fail(function(){ def.reject.apply(def, arguments); });
promise.abort = function(){ return req.abort.apply(req, arguments); }
return promise;
}
var buildMultipart = function(data){
var key, crunks = [], bound = false;
while (!bound) {
bound = $.md5 ? $.md5(new Date().valueOf()) : (new Date().valueOf());
for (key in data) if (~data[key].indexOf(bound)) { bound = false; continue; }
}
for (var key = 0, l = data.length; key < l; key++){
if (typeof(data[key].value) !== "string") {
crunks.push("--"+bound+"\r\n"+
"Content-Disposition: form-data; name=\""+data[key].name+"\"; filename=\""+data[key].value[1]+"\"\r\n"+
"Content-Type: application/octet-stream\r\n"+
"Content-Transfer-Encoding: binary\r\n\r\n"+
data[key].value[0]);
}else{
crunks.push("--"+bound+"\r\n"+
"Content-Disposition: form-data; name=\""+data[key].name+"\"\r\n\r\n"+
data[key].value);
}
}
return {
bound: bound,
data: crunks.join("\r\n")+"\r\n--"+bound+"--"
};
};
//----------
//---------- On submit form:
var form = $("form");
var $file = form.find("#file");
readFile($file[0].files[0]).done(function(fileData){
var formData = form.find(":input:not('#file')").serializeArray();
formData.file = [fileData, $file[0].files[0].name];
upload(form.attr("action"), formData).done(function(){ alert("successfully uploaded!"); });
});
With FormData API you just have to add all fields of your form to FormData object and send it via $.ajax({ url: url, data: formData, processData: false, contentType: false, type:"POST"})
I'd solve it with a javascript solution (jQUery) if the sizes can vary.
window.setTimeout(function () {
$(document).ready(function () {
var ResizeTarget = $('#B');
ResizeTarget.resize(function () {
var target = $('#B2');
target.css('height', ResizeTarget.height());
}).trigger('resize');
});
}, 500);
You can try with below one:
<div style="width: 100%; height: 100%; overflow-x: visible; overflow-y: scroll;">Text</div>
The with
function will let you use shorthand column references and sum
will count TRUE
results from the expression(s).
sum(with(aaa, sex==1 & group1==2))
## [1] 3
sum(with(aaa, sex==1 & group2=="A"))
## [1] 2
As @mnel pointed out, you can also do:
nrow(aaa[aaa$sex==1 & aaa$group1==2,])
## [1] 3
nrow(aaa[aaa$sex==1 & aaa$group2=="A",])
## [1] 2
The benefit of that is that you can do:
nrow(aaa)
## [1] 6
And, the behaviour matches Stata's count
almost exactly (syntax notwithstanding).
select *
into #TempTable
from SomeTale
select *
from #TempTable
You can use the rootViewController
also when your controller is not a UINavigationController
:
UIViewController *vc = self.window.rootViewController;
Once you know the root view controller, then it depends on how you have built your UI, but you can possibly find out a way to navigate through the controllers hierarchy.
If you give some more details about the way you defined your app, then I might give some more hint.
EDIT:
If you want the topmost view (not view controller), you could check
[[[[UIApplication sharedApplication] keyWindow] subviews] lastObject];
although this view might be invisible or even covered by some of its subviews...
again, it depends on your UI, but this might help...
The best way to implement it using matplotlib.pyplot.bar(range, height, tick_label)
where the range provides scalar values for the positioning of the corresponding bar in the graph. tick_label
does the same work as xticks()
. One can replace it with an integer also and use multiple plt.bar(integer, height, tick_label)
. For detailed information please refer the documentation.
import matplotlib.pyplot as plt
data = {'apple': 67, 'mango': 60, 'lichi': 58}
names = list(data.keys())
values = list(data.values())
#tick_label does the some work as plt.xticks()
plt.bar(range(len(data)),values,tick_label=names)
plt.savefig('bar.png')
plt.show()
Additionally the same plot can be generated without using range()
. But the problem encountered was that tick_label
just worked for the last plt.bar()
call. Hence xticks()
was used for labelling:
data = {'apple': 67, 'mango': 60, 'lichi': 58}
names = list(data.keys())
values = list(data.values())
plt.bar(0,values[0],tick_label=names[0])
plt.bar(1,values[1],tick_label=names[1])
plt.bar(2,values[2],tick_label=names[2])
plt.xticks(range(0,3),names)
plt.savefig('fruit.png')
plt.show()
DateTime
inherits its equals
method from AbstractInstant
. It is implemented as such
public boolean equals(Object readableInstant) { // must be to fulfil ReadableInstant contract if (this == readableInstant) { return true; } if (readableInstant instanceof ReadableInstant == false) { return false; } ReadableInstant otherInstant = (ReadableInstant) readableInstant; return getMillis() == otherInstant.getMillis() && FieldUtils.equals(getChronology(), otherInstant.getChronology()); }
Notice the last line comparing chronology. It's possible your instances' chronologies are different.
This explains the whole thing:
The HTTP Content-Security-Policy (CSP) upgrade-insecure-requests directive instructs user agents to treat all of a site's insecure URLs (those served over HTTP) as though they have been replaced with secure URLs (those served over HTTPS). This directive is intended for web sites with large numbers of insecure legacy URLs that need to be rewritten.
The upgrade-insecure-requests directive is evaluated before block-all-mixed-content and if it is set, the latter is effectively a no-op. It is recommended to set one directive or the other, but not both.
The upgrade-insecure-requests directive will not ensure that users visiting your site via links on third-party sites will be upgraded to HTTPS for the top-level navigation and thus does not replace the Strict-Transport-Security (HSTS) header, which should still be set with an appropriate max-age to ensure that users are not subject to SSL stripping attacks.
The toolset on the client side would be one. And the familiarity with SOAP services the other. More and more services are going the RESTful route these days, and testing such services can be done with simple cURL examples. Although, it's not all that difficult to implement both methods and allow for the widest utilization from clients.
If you need to pick one, I'd suggest REST, it's easier.
Upgrade MySql driver to Connector/Python 8.0.17 or greater than 8.0.17, Those who are using greater than MySQL 5.5 version
I sometimes do a mysqldump and pipe the output into another mysql command to import it into a different database.
mysqldump --add-drop-table -u wordpress -p wordpress | mysql -u wordpress -p wordpress_backup
It looks like ByRef needs to know the size of the parameter. A declaration of Dim last_name as string doesn't specify the size of the string so it takes it as an error. Before using Worksheets(data_sheet).Range("C2").Value = ProcessString(last_name) The last_name has to be declared as Dim last_name as string *10 ' size of string is up to you but must be a fix length
No need to change the function. Function doesn't take a fix length declaration.
And if you have one hell of a files to download from the remote location and if you don't much care about security, try changing the scp default encryption (Triple-DES) to something like 'blowfish'.
This will reduce file copying time drastically.
scp -c blowfish -r [email protected]:/path/to/foo /home/user/Desktop/
If its anywhere in the string than you can't do better than O(n).
And the only way is to search for '\n' in the string and erase it.
for(int i=0;i<s.length();i++) if(s[i]=='\n') s.erase(s.begin()+i);
For more newlines than:
int n=0;
for(int i=0;i<s.length();i++){
if(s[i]=='\n'){
n++;//we increase the number of newlines we have found so far
}else{
s[i-n]=s[i];
}
}
s.resize(s.length()-n);//to delete only once the last n elements witch are now newlines
It erases all the newlines once.
They may look a bit different from normal HTML, but : and @ are valid chars for attribute names and all Vue.js supported browsers can parse it correctly. In addition, they do not appear in the final rendered markup. The shorthand syntax is totally optional, but you will likely appreciate it when you learn more about its usage later.
Source: official documentation.
One cross-platform solution is to use a bind mount to share the host's .ssh
folder to the container:
docker run -v /home/<host user>/.ssh:/home/<docker user>/.ssh <image>
Similar to agent forwarding this approach will make the public keys accessible to the container. An additional upside is that it works with a non-root user too and will get you connected to GitHub. One caveat to consider, however, is that all contents (including private keys) from the .ssh
folder will be shared so this approach is only desirable for development and only for trusted container images.
First of all, from __future__ import print_function
needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print
as a function now. That's the whole point of from __future__ import print_function
; to bring the print
function from Python 3 into Python 2.6+.
from __future__ import print_function
import sys, os, time
for x in range(0,10):
print(x, sep=' ', end='') # No need for sep here, but okay :)
time.sleep(1)
__future__
statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:
A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.
The documentation also mentions that the only things that can precede a __future__
statement are the module docstring, comments, blank lines, and other future statements.
Need to apply css as belows:
button:disabled,button[disabled]{
background-color: #cccccc;
cursor:not-allowed !important;
}
Execute these commands in the terminal (excluding the lines with hashtags - they're comments):
# Deletes the Android Studio application
# Note that this may be different depending on what you named the application as, or whether you downloaded the preview version
rm -Rf /Applications/Android\ Studio.app
# Delete All Android Studio related preferences
# The asterisk here should target all folders/files beginning with the string before it
rm -Rf ~/Library/Preferences/AndroidStudio*
rm -Rf ~/Library/Preferences/Google/AndroidStudio*
# Deletes the Android Studio's plist file
rm -Rf ~/Library/Preferences/com.google.android.*
# Deletes the Android Emulator's plist file
rm -Rf ~/Library/Preferences/com.android.*
# Deletes mainly plugins (or at least according to what mine (Edric) contains)
rm -Rf ~/Library/Application\ Support/AndroidStudio*
rm -Rf ~/Library/Application\ Support/Google/AndroidStudio*
# Deletes all logs that Android Studio outputs
rm -Rf ~/Library/Logs/AndroidStudio*
rm -Rf ~/Library/Logs/Google/AndroidStudio*
# Deletes Android Studio's caches
rm -Rf ~/Library/Caches/AndroidStudio*
# Deletes older versions of Android Studio
rm -Rf ~/.AndroidStudio*
If you would like to delete all projects:
rm -Rf ~/AndroidStudioProjects
To remove gradle related files (caches & wrapper)
rm -Rf ~/.gradle
Use the below command to delete all Android Virtual Devices(AVDs) and keystores.
Note: This folder is used by other Android IDEs as well, so if you still using other IDE you may not want to delete this folder)
rm -Rf ~/.android
To delete Android SDK tools
rm -Rf ~/Library/Android*
Emulator Console Auth Token
rm -Rf ~/.emulator_console_auth_token
Thanks to those who commented/improved on this answer!
rm
are case-sensitive1 (as with most other commands), which means that the f
flag must be in lower case. However, the r
flag can also be capitalised.rm
can be either combined together or separated. They don't have to be combined.r
flag indicates that the rm
command should-
attempt to remove the file hierarchy rooted in each file argument. - DESCRIPTION section on the manpage for
rm
(Seeman rm
for more info)
f
flag indicates that the rm
command should-
attempt to remove the files without prompting for confirmation, regardless of the file's permissions. - DESCRIPTION section on the manpage for
rm
(Seeman rm
for more info)
For people coming here from Google looking for a fast way to downsample images in numpy
arrays for use in Machine Learning applications, here's a super fast method (adapted from here ). This method only works when the input dimensions are a multiple of the output dimensions.
The following examples downsample from 128x128 to 64x64 (this can be easily changed).
Channels last ordering
# large image is shape (128, 128, 3)
# small image is shape (64, 64, 3)
input_size = 128
output_size = 64
bin_size = input_size // output_size
small_image = large_image.reshape((output_size, bin_size,
output_size, bin_size, 3)).max(3).max(1)
Channels first ordering
# large image is shape (3, 128, 128)
# small image is shape (3, 64, 64)
input_size = 128
output_size = 64
bin_size = input_size // output_size
small_image = large_image.reshape((3, output_size, bin_size,
output_size, bin_size)).max(4).max(2)
For grayscale images just change the 3
to a 1
like this:
Channels first ordering
# large image is shape (1, 128, 128)
# small image is shape (1, 64, 64)
input_size = 128
output_size = 64
bin_size = input_size // output_size
small_image = large_image.reshape((1, output_size, bin_size,
output_size, bin_size)).max(4).max(2)
This method uses the equivalent of max pooling. It's the fastest way to do this that I've found.
As @pimvdb said in his comment,
Note that change will only fire when the input element has lost focus. There is also the input event which fires whenever the textbox updates without it needing to lose focus. Unlike key events it also works for pasting/dragging text.
(See documentation.)
This is so useful, it is worth putting it in an answer. Currently (v1.8*?) there is no .input() convenience fn in jquery, so the way to do it is
$('input.myTextInput').on('input',function(e){
alert('Changed!')
});
This is ages too late, but good for anyone that is searching the topic. If you're not innoDB, and you're not worried about locking while you dump simply use the option:
--lock-tables=false
The source referenced by the OP has some credibility ...but what about Microsoft - what is the stance on struct usage? I sought some extra learning from Microsoft, and here is what I found:
Consider defining a structure instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects.
Do not define a structure unless the type has all of the following characteristics:
- It logically represents a single value, similar to primitive types (integer, double, and so on).
- It has an instance size smaller than 16 bytes.
- It is immutable.
- It will not have to be boxed frequently.
Okay, #2 and #3 anyway. Our beloved dictionary has 2 internal structs:
[StructLayout(LayoutKind.Sequential)] // default for structs
private struct Entry //<Tkey, TValue>
{
// View code at *Reference Source
}
[Serializable, StructLayout(LayoutKind.Sequential)]
public struct Enumerator :
IEnumerator<KeyValuePair<TKey, TValue>>, IDisposable,
IDictionaryEnumerator, IEnumerator
{
// View code at *Reference Source
}
The 'JonnyCantCode.com' source got 3 out of 4 - quite forgivable since #4 probably wouldn't be an issue. If you find yourself boxing a struct, rethink your architecture.
Let's look at why Microsoft would use these structs:
Entry
and Enumerator
, represent single values.Entry
is never passed as a parameter outside of the Dictionary class. Further investigation shows that in order to satisfy implementation of IEnumerable, Dictionary uses the Enumerator
struct which it copies every time an enumerator is requested ...makes sense.Enumerator
is public because Dictionary is enumerable and must have equal accessibility to the IEnumerator interface implementation - e.g. IEnumerator getter. Update - In addition, realize that when a struct implements an interface - as Enumerator does - and is cast to that implemented type, the struct becomes a reference type and is moved to the heap. Internal to the Dictionary class, Enumerator is still a value type. However, as soon as a method calls GetEnumerator()
, a reference-type IEnumerator
is returned.
What we don't see here is any attempt or proof of requirement to keep structs immutable or maintaining an instance size of only 16 bytes or less:
readonly
- not immutableEntry
has an undetermined lifetime (from Add()
, to Remove()
, Clear()
, or garbage collection);And ... 4. Both structs store TKey and TValue, which we all know are quite capable of being reference types (added bonus info)
Hashed keys notwithstanding, dictionaries are fast in part because instancing a struct is quicker than a reference type. Here, I have a Dictionary<int, int>
that stores 300,000 random integers with sequentially incremented keys.
Capacity: 312874
MemSize: 2660827 bytes
Completed Resize: 5ms
Total time to fill: 889ms
Capacity: number of elements available before the internal array must be resized.
MemSize: determined by serializing the dictionary into a MemoryStream and getting a byte length (accurate enough for our purposes).
Completed Resize: the time it takes to resize the internal array from 150862 elements to 312874 elements. When you figure that each element is sequentially copied via Array.CopyTo()
, that ain't too shabby.
Total time to fill: admittedly skewed due to logging and an OnResize
event I added to the source; however, still impressive to fill 300k integers while resizing 15 times during the operation. Just out of curiosity, what would the total time to fill be if I already knew the capacity? 13ms
So, now, what if Entry
were a class? Would these times or metrics really differ that much?
Capacity: 312874
MemSize: 2660827 bytes
Completed Resize: 26ms
Total time to fill: 964ms
Obviously, the big difference is in resizing. Any difference if Dictionary is initialized with the Capacity? Not enough to be concerned with ... 12ms.
What happens is, because Entry
is a struct, it does not require initialization like a reference type. This is both the beauty and the bane of the value type. In order to use Entry
as a reference type, I had to insert the following code:
/*
* Added to satisfy initialization of entry elements --
* this is where the extra time is spent resizing the Entry array
* **/
for (int i = 0 ; i < prime ; i++)
{
destinationArray[i] = new Entry( );
}
/* *********************************************** */
The reason I had to initialize each array element of Entry
as a reference type can be found at MSDN: Structure Design. In short:
Do not provide a default constructor for a structure.
If a structure defines a default constructor, when arrays of the structure are created, the common language runtime automatically executes the default constructor on each array element.
Some compilers, such as the C# compiler, do not allow structures to have default constructors.
It is actually quite simple and we will borrow from Asimov's Three Laws of Robotics:
...what do we take away from this: in short, be responsible with the use of value types. They are quick and efficient, but have the ability to cause many unexpected behaviors if not properly maintained (i.e. unintentional copies).
You can get through every object in the list and get which value you want. Just pass an object as first parameter in the function call and object property which you want as second parameter. Change object with your object.
const treeData = [{_x000D_
"jssType": "fieldset",_x000D_
"jssSelectLabel": "Fieldset (with legend)",_x000D_
"jssSelectGroup": "jssItem",_x000D_
"jsName": "fieldset-715",_x000D_
"jssLabel": "Legend",_x000D_
"jssIcon": "typcn typcn-folder",_x000D_
"expanded": true,_x000D_
"children": [{_x000D_
"jssType": "list-ol",_x000D_
"jssSelectLabel": "List - ol",_x000D_
"jssSelectGroup": "jssItem",_x000D_
"jsName": "list-ol-147",_x000D_
"jssLabel": "",_x000D_
"jssIcon": "dashicons dashicons-editor-ol",_x000D_
"noChildren": false,_x000D_
"expanded": true,_x000D_
"children": [{_x000D_
"jssType": "list-li",_x000D_
"jssSelectLabel": "List Item - li",_x000D_
"jssSelectGroup": "jssItem",_x000D_
"jsName": "list-li-752",_x000D_
"jssLabel": "",_x000D_
"jssIcon": "dashicons dashicons-editor-ul",_x000D_
"noChildren": false,_x000D_
"expanded": true,_x000D_
"children": [{_x000D_
"jssType": "text",_x000D_
"jssSelectLabel": "Text (short text)",_x000D_
"jssSelectGroup": "jsTag",_x000D_
"jsName": "text-422",_x000D_
"jssLabel": "Your Name (required)",_x000D_
"jsRequired": true,_x000D_
"jsTagOptions": [{_x000D_
"jsOption": "",_x000D_
"optionLabel": "Default value",_x000D_
"optionType": "input"_x000D_
},_x000D_
{_x000D_
"jsOption": "placeholder",_x000D_
"isChecked": false,_x000D_
"optionLabel": "Use this text as the placeholder of the field",_x000D_
"optionType": "checkbox"_x000D_
},_x000D_
{_x000D_
"jsOption": "akismet_author_email",_x000D_
"isChecked": false,_x000D_
"optionLabel": "Akismet - this field requires author's email address",_x000D_
"optionType": "checkbox"_x000D_
}_x000D_
],_x000D_
"jsValues": "",_x000D_
"jsPlaceholder": false,_x000D_
"jsAkismetAuthor": false,_x000D_
"jsIdAttribute": "",_x000D_
"jsClassAttribute": "",_x000D_
"jssIcon": "typcn typcn-sort-alphabetically",_x000D_
"noChildren": true_x000D_
}]_x000D_
},_x000D_
{_x000D_
"jssType": "list-li",_x000D_
"jssSelectLabel": "List Item - li",_x000D_
"jssSelectGroup": "jssItem",_x000D_
"jsName": "list-li-538",_x000D_
"jssLabel": "",_x000D_
"jssIcon": "dashicons dashicons-editor-ul",_x000D_
"noChildren": false,_x000D_
"expanded": true,_x000D_
"children": [{_x000D_
"jssType": "email",_x000D_
"jssSelectLabel": "Email",_x000D_
"jssSelectGroup": "jsTag",_x000D_
"jsName": "email-842",_x000D_
"jssLabel": "Email Address (required)",_x000D_
"jsRequired": true,_x000D_
"jsTagOptions": [{_x000D_
"jsOption": "",_x000D_
"optionLabel": "Default value",_x000D_
"optionType": "input"_x000D_
},_x000D_
{_x000D_
"jsOption": "placeholder",_x000D_
"isChecked": false,_x000D_
"optionLabel": "Use this text as the placeholder of the field",_x000D_
"optionType": "checkbox"_x000D_
},_x000D_
{_x000D_
"jsOption": "akismet_author_email",_x000D_
"isChecked": false,_x000D_
"optionLabel": "Akismet - this field requires author's email address",_x000D_
"optionType": "checkbox"_x000D_
}_x000D_
],_x000D_
"jsValues": "",_x000D_
"jsPlaceholder": false,_x000D_
"jsAkismetAuthorEmail": false,_x000D_
"jsIdAttribute": "",_x000D_
"jsClassAttribute": "",_x000D_
"jssIcon": "typcn typcn-mail",_x000D_
"noChildren": true_x000D_
}]_x000D_
},_x000D_
{_x000D_
"jssType": "list-li",_x000D_
"jssSelectLabel": "List Item - li",_x000D_
"jssSelectGroup": "jssItem",_x000D_
"jsName": "list-li-855",_x000D_
"jssLabel": "",_x000D_
"jssIcon": "dashicons dashicons-editor-ul",_x000D_
"noChildren": false,_x000D_
"expanded": true,_x000D_
"children": [{_x000D_
"jssType": "textarea",_x000D_
"jssSelectLabel": "Textarea (long text)",_x000D_
"jssSelectGroup": "jsTag",_x000D_
"jsName": "textarea-217",_x000D_
"jssLabel": "Your Message",_x000D_
"jsRequired": false,_x000D_
"jsTagOptions": [{_x000D_
"jsOption": "",_x000D_
"optionLabel": "Default value",_x000D_
"optionType": "input"_x000D_
},_x000D_
{_x000D_
"jsOption": "placeholder",_x000D_
"isChecked": false,_x000D_
"optionLabel": "Use this text as the placeholder of the field",_x000D_
"optionType": "checkbox"_x000D_
}_x000D_
],_x000D_
"jsValues": "",_x000D_
"jsPlaceholder": false,_x000D_
"jsIdAttribute": "",_x000D_
"jsClassAttribute": "",_x000D_
"jssIcon": "typcn typcn-document-text",_x000D_
"noChildren": true_x000D_
}]_x000D_
}_x000D_
]_x000D_
},_x000D_
{_x000D_
"jssType": "paragraph",_x000D_
"jssSelectLabel": "Paragraph - p",_x000D_
"jssSelectGroup": "jssItem",_x000D_
"jsName": "paragraph-993",_x000D_
"jssContent": "* Required",_x000D_
"jssIcon": "dashicons dashicons-editor-paragraph",_x000D_
"noChildren": true_x000D_
}_x000D_
]_x000D_
_x000D_
},_x000D_
{_x000D_
"jssType": "submit",_x000D_
"jssSelectLabel": "Submit",_x000D_
"jssSelectGroup": "jsTag",_x000D_
"jsName": "submit-704",_x000D_
"jssLabel": "Send",_x000D_
"jsValues": "",_x000D_
"jsRequired": false,_x000D_
"jsIdAttribute": "",_x000D_
"jsClassAttribute": "",_x000D_
"jssIcon": "typcn typcn-mail",_x000D_
"noChildren": true_x000D_
},_x000D_
_x000D_
];_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
function findObjectByLabel(obj, label) {_x000D_
for(var elements in obj){_x000D_
if (elements === label){_x000D_
console.log(obj[elements]);_x000D_
}_x000D_
if(typeof obj[elements] === 'object'){_x000D_
findObjectByLabel(obj[elements], 'jssType');_x000D_
}_x000D_
_x000D_
}_x000D_
};_x000D_
_x000D_
findObjectByLabel(treeData, 'jssType');
_x000D_
I had a similar problem recently, and here's what I did:
SELECT
columnname as 'Original_Value',
LEN(LTRIM(columnname)) as 'Orig_Val_Char_Count',
N'['+columnname+']' as 'UnicodeStr_Value',
LEN(N'['+columnname+']')-2 as 'True_Char_Count'
FROM mytable
The first two columns look at the original value and count the characters (minus leading/trailing spaces).
I needed to compare that with the true count of characters, which is why I used the second LEN function. It sets the column value to a string, forces that string to Unicode, and then counts the characters.
By using the brackets, you ensure that any leading or trailing spaces are also counted as characters; of course, you don't want to count the brackets themselves, so you subtract 2 at the end.
This is normally the case then the ID is not a natural part of the entity, but a database artifact that needs be abstracted away.
It is a design decision - to only allow setting the ID during construction or through method invocation, so it is managed internally by the class.
You can write a setter yourself, assuming you have a backing field:
private int Id = 0;
public void SetId (int id)
{
this.Id = id;
}
Or through a constructor:
private int Id = 0;
public Person (int id)
{
this.Id = id;
}
var leg= $scope.name.length;
$log.info(leg);
If you want to create a .war file you can deploy to a Tomcat instance using the Manager app, create a folder, put all your files in that folder (including an index.html file) move your terminal window into that folder, and execute the following command:
zip -r <AppName>.war *
I've tested it with Tomcat 8 on the Mac, but it should work anywhere
// This is wrong
categoryTitle.textColor = [UIColor colorWithRed:188 green:149 blue:88 alpha:1.0];
// This should be
categoryTitle.textColor = [UIColor colorWithRed:188/255 green:149/255 blue:88/255 alpha:1.0];
// In the documentation, the limit of the parameters are mentioned.
One point no one has touched on is the fact that the h1 attribute should be specific to every page and using the site logo will effectively replicate the H1 on every page of the site.
I like to use a z index hidden h1 for each page as the best SEO h1 is often not the best for sales or aesthetic value.
I'm using a message service that wraps an rxjs Subject
(TypeScript)
Plunker example: Message Service
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Subscription } from 'rxjs/Subscription';
import 'rxjs/add/operator/filter'
import 'rxjs/add/operator/map'
interface Message {
type: string;
payload: any;
}
type MessageCallback = (payload: any) => void;
@Injectable()
export class MessageService {
private handler = new Subject<Message>();
broadcast(type: string, payload: any) {
this.handler.next({ type, payload });
}
subscribe(type: string, callback: MessageCallback): Subscription {
return this.handler
.filter(message => message.type === type)
.map(message => message.payload)
.subscribe(callback);
}
}
Components can subscribe and broadcast events (sender):
import { Component, OnDestroy } from '@angular/core'
import { MessageService } from './message.service'
import { Subscription } from 'rxjs/Subscription'
@Component({
selector: 'sender',
template: ...
})
export class SenderComponent implements OnDestroy {
private subscription: Subscription;
private messages = [];
private messageNum = 0;
private name = 'sender'
constructor(private messageService: MessageService) {
this.subscription = messageService.subscribe(this.name, (payload) => {
this.messages.push(payload);
});
}
send() {
let payload = {
text: `Message ${++this.messageNum}`,
respondEvent: this.name
}
this.messageService.broadcast('receiver', payload);
}
clear() {
this.messages = [];
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
(receiver)
import { Component, OnDestroy } from '@angular/core'
import { MessageService } from './message.service'
import { Subscription } from 'rxjs/Subscription'
@Component({
selector: 'receiver',
template: ...
})
export class ReceiverComponent implements OnDestroy {
private subscription: Subscription;
private messages = [];
constructor(private messageService: MessageService) {
this.subscription = messageService.subscribe('receiver', (payload) => {
this.messages.push(payload);
});
}
send(message: {text: string, respondEvent: string}) {
this.messageService.broadcast(message.respondEvent, message.text);
}
clear() {
this.messages = [];
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
The subscribe
method of MessageService
returns an rxjs Subscription
object, which can be unsubscribed from like so:
import { Subscription } from 'rxjs/Subscription';
...
export class SomeListener {
subscription: Subscription;
constructor(private messageService: MessageService) {
this.subscription = messageService.subscribe('someMessage', (payload) => {
console.log(payload);
this.subscription.unsubscribe();
});
}
}
Also see this answer: https://stackoverflow.com/a/36782616/1861779
You want to use css float for this, you can put it directly in your code.
<body>
<img src="website_art.png" height= "75" width="235" style="float:left;"/>
<h3 style="float:right;">The Art of Gaming</h3>
</body>
But I would really suggest learning the basics of css and splitting all your styling out to a separate style sheet, and use classes. It will help you in the future. A good place to start is w3schools or, perhaps later down the path, Mozzila Dev. Network (MDN).
HTML:
<body>
<img src="website_art.png" class="myImage"/>
<h3 class="heading">The Art of Gaming</h3>
</body>
CSS:
.myImage {
float: left;
height: 75px;
width: 235px;
font-family: Veranda;
}
.heading {
float:right;
}
Your second example does not work if you send the argument by reference. Did you mean
void copyVecFast(vec<int> original) // no reference
{
vector<int> new_;
new_.swap(original);
}
That would work, but an easier way is
vector<int> new_(original);
Here is the small example
public class TryWithResource {
public static void main(String[] args) {
try (TestMe r = new TestMe()) {
r.generalTest();
} catch(Exception e) {
System.out.println("From Exception Block");
} finally {
System.out.println("From Final Block");
}
}
}
public class TestMe implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println(" From Close - AutoCloseable ");
}
public void generalTest() {
System.out.println(" GeneralTest ");
}
}
Here is the output:
GeneralTest
From Close - AutoCloseable
From Final Block
Too late to answer but if your input is in form of ASCII bytes, then you could try this solution:
function convertArrToString(rArr){
//Step 1: Convert each element to character
let tmpArr = new Array();
rArr.forEach(function(element,index){
tmpArr.push(String.fromCharCode(element));
});
//Step 2: Return the string by joining the elements
return(tmpArr.join(""));
}
function convertArrToHexNumber(rArr){
return(parseInt(convertArrToString(rArr),16));
}
You can create a class and override the toString
method to do anything you want.
For example- you can create a class "MyMail" and override the toString
method to send an email or do some other operation instead of writing the current object.
The Convert.toString
converts the specified value to its equivalent string representation.
You can just target the id directly:
var value = $('#b').val();
If you have more than one element with that id in the same page, it won't work properly anyway. You have to make sure that the id is unique.
If you actually are using the code for different pages, and only want to find the element on those pages where the id:s are nested, you can just use the descendant operator, i.e. space:
var value = $('#a #b').val();
Arrays in JS have two types of properties:
Regular elements and associative properties (which are nothing but objects)
When you define a = new Array()
, you are defining an empty array. Note that there are no associative objects yet
When you define b = new Array(2)
, you are defining an array with two undefined locations.
In both your examples of 'a' and 'b', you are adding associative properties i.e. objects to these arrays.
console.log (a)
or console.log(b)
prints the array elements i.e. []
and [undefined, undefined]
respectively. But since a1/a2
and b1/b2
are associative objects inside their arrays, they can be logged only by console.log(a.a1, a.a2)
kind of syntax
It is good practice to make sure the callback is an actual function before attempting to execute it:
if (callback && typeof(callback) === "function") {
callback();
}
This worked for me:
Espresso.onView(ViewMatchers.withId(R.id.radiobutton)).check(ViewAssertions.matches(isChecked()))
It takes two numbers from the user, feeds them to the function called add
(in the very last line of the code), and add
will sum them up and print them.
#!/bin/bash
read -p "Enter the first value: " x
read -p "Enter the second value: " y
add(){
arg1=$1 # arg1 gets to be the first assigned argument (note there are no spaces)
arg2=$2 # arg2 gets to be the second assigned argument (note there are no spaces)
echo $(($arg1 + $arg2))
}
add x y # Feeding the arguments
Regarding Nambari's answer there was a mistake. If you compare values using double equal sign == program will never reach compare method, unless someone will use new keyword to create String object which is not the best practice. This might be a bit better solution:
public int compare(String o1, String o2) {
if (o1 == null && o2 == null){return 0;}
if (o1 == null) { return -1;}
if (o2 == null) { return 1;}
return o1.compareTo(o2);
}
P.S. Thanks for comments ;)
You have to use the iterator's remove() method, which means no enhanced for loop:
for (final Iterator iterator = myArrayList.iterator(); iterator.hasNext(); ) {
iterator.next();
if (someCondition) {
iterator.remove();
}
}
No, you can't. The compiler doesn't know what the pointer is pointing to. There are tricks, like ending the array with a known out-of-band value and then counting the size up until that value, but that's not using sizeof()
.
Another trick is the one mentioned by Zan, which is to stash the size somewhere. For example, if you're dynamically allocating the array, allocate a block one int bigger than the one you need, stash the size in the first int, and return ptr+1
as the pointer to the array. When you need the size, decrement the pointer and peek at the stashed value. Just remember to free the whole block starting from the beginning, and not just the array.
Maybe this is an XY problem, and what you are really trying to do is to highlight occurrences of words as they appear in your shell. If so, you may be able to use your terminal emulator for this. For instance, in Konsole, start Find (ctrl+shift+F) and type your word. The word will then be highlighted whenever it occurs in new or existing output until you cancel the function.
I would try to set a flag on the window.onfocus
and window.onblur
events.
The following snippet has been tested on Firefox, Safari and Chrome, open the console and move between tabs back and forth:
var isTabActive;
window.onfocus = function () {
isTabActive = true;
};
window.onblur = function () {
isTabActive = false;
};
// test
setInterval(function () {
console.log(window.isTabActive ? 'active' : 'inactive');
}, 1000);
Try it out here.
I would look at the Join operator:
from r in list join i in listofIds on r.Id equals i select r
I'm not sure how this would be optimized over the Contains methods, but at least it gives the compiler a better idea of what you're trying to do. It's also sematically closer to what you're trying to achieve.
Edit: Extension method syntax for completeness (now that I've figured it out):
var results = listofIds.Join(list, i => i, r => r.Id, (i, r) => r);
You also have CSS Grid and CSS Flex, both can give you columns that keep their position and size ratios depending on screen size, and flex can also easily rearrange the columns if screen size is too small so they can maintain a minimum width nicely.
See these guides for full details:
Grid:
.container {
display: grid | inline-grid;
}
Flex:
.container {
display: flex | inline-flex;
}
For information on php extensions
etc, on site.
Create a new file and name it info.php
(or some other name.php
)
Write this code in it:
<?php
phpinfo ();
?>
Save the file in the root
(home)of the site
example.com/info.php
All the php
information on your site will be displayed.The easiest solution is to simply tell Xcode to compile everything as Objective C++.
Set your project or target settings for Compile Sources As to Objective C++ and recompile.
Then you can use C++ or Objective C everywhere, for example:
void CPPObject::Function( ObjectiveCObject* context, NSView* view )
{
[context renderbufferStorage:GL_RENDERBUFFER fromDrawable:(CAEAGLLayer*)view.layer]
}
This has the same affect as renaming all your source files from .cpp or .m to .mm.
There are two minor downsides to this: clang cannot analyse C++ source code; some relatively weird C code does not compile under C++.
If you want to read file from sd card. Then following code might be helpful for you.
StringBuilder text = new StringBuilder();
try {
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"testFile.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
Log.i("Test", "text : "+text+" : end");
text.append('\n');
} }
catch (IOException e) {
e.printStackTrace();
}
finally{
br.close();
}
TextView tv = (TextView)findViewById(R.id.amount);
tv.setText(text.toString()); ////Set the text to text view.
}
}
If you wan to read file from asset folder then
AssetManager am = context.getAssets();
InputStream is = am.open("test.txt");
Or If you wan to read this file from res/raw
foldery, where the file will be indexed and is accessible by an id in the R file:
InputStream is = getResources().openRawResource(R.raw.test);
Here is what worked for me:
Context:
Building a project on a server
git status
returns a HEAD detached at <commit-SHA>
What ever operation I did locally, I had this error. More specifically:
Solution
<work-dir>/.git/index
. git status
would indicate that all files in the projet are not tracked (no surprise here).git reset HEAD --hard
HEAD detached at <commit-SHA>
when doing a git status
, but then you should be able togit checkout <some-branch>
and you're back on track!
!! IMPORTANT !!
This works only because I am "merly" building. No precious modification has been performed on the code. If you are actually in "dev-time", then I would recommand to save your work first or go for another method.
Hope it will help :).
var path = require("path");
var filepath = "C:\\Python27\\ArcGIS10.2\\python.exe";
var name = path.parse(filepath).name;
// returns
'python'
Above code returns the name of the file without extension, if you need the name with extention use
var path = require("path");
var filepath = "C:\\Python27\\ArcGIS10.2\\python.exe";
var name = path.basename(filepath);
// returns
'python.exe'
This is old topic but on my last test on one my API, cURL is faster and more stable. Sometimes file_get_contents on larger request need over 5 seconds when cURL need only from 1.4 to 1.9 seconds what is double faster.
I need to add one note on this that I just send GET and recive JSON content. If you setup cURL properly, you will have a great response. Just "tell" to cURL what you need to send and what you need to recive and that's it.
On your exampe I would like to do this setup:
$ch = curl_init('http://api.bitly.com/v3/shorten?login=user&apiKey=key&longUrl=url');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
$result = curl_exec($ch);
This request will return data in 0.10 second max
This article describes maximum transmission unit (MTU) http://en.wikipedia.org/wiki/Maximum_transmission_unit. It states that IP hosts must be able to process 576 bytes for an IP packet. However, it notes the minumum is 68. RFC 791: "Every internet module must be able to forward a datagram of 68 octets without further fragmentation. This is because an internet header may be up to 60 octets, and the minimum fragment is 8 octets."
Thus, safe packet size of 508 = 576 - 60 (IP header) - 8 (udp header) is reasonable.
As mentioned by user607811, fragmentation by other network layers must be reassembled. https://tools.ietf.org/html/rfc1122#page-56 3.3.2 Reassembly The IP layer MUST implement reassembly of IP datagrams. We designate the largest datagram size that can be reassembled by EMTU_R ("Effective MTU to receive"); this is sometimes called the "reassembly buffer size". EMTU_R MUST be greater than or equal to 576
You only initialize the first N positions to the values in braces and all others are initialized to 0. In this case, N is the number of arguments you passed to the initialization list, i.e.,
float arr1[10] = { }; // all elements are 0
float arr2[10] = { 0 }; // all elements are 0
float arr3[10] = { 1 }; // first element is 1, all others are 0
float arr4[10] = { 1, 2 }; // first element is 1, second is 2, all others are 0
I configured the app.config
with the tool for EntLib configuration and set up my LoggingConfiguration
block. Then I copied this into the DotNetConfig.xsd
. Of course, it does not cover all attributes, only the ones I added but it does not display those annoying info messages anymore.
<xs:element name="loggingConfiguration">
<xs:complexType>
<xs:sequence>
<xs:element name="listeners">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="add">
<xs:complexType>
<xs:attribute name="fileName" type="xs:string" use="required" />
<xs:attribute name="footer" type="xs:string" use="required" />
<xs:attribute name="formatter" type="xs:string" use="required" />
<xs:attribute name="header" type="xs:string" use="required" />
<xs:attribute name="rollFileExistsBehavior" type="xs:string" use="required" />
<xs:attribute name="rollInterval" type="xs:string" use="required" />
<xs:attribute name="rollSizeKB" type="xs:unsignedByte" use="required" />
<xs:attribute name="timeStampPattern" type="xs:string" use="required" />
<xs:attribute name="listenerDataType" type="xs:string" use="required" />
<xs:attribute name="traceOutputOptions" type="xs:string" use="required" />
<xs:attribute name="filter" type="xs:string" use="required" />
<xs:attribute name="type" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="formatters">
<xs:complexType>
<xs:sequence>
<xs:element name="add">
<xs:complexType>
<xs:attribute name="template" type="xs:string" use="required" />
<xs:attribute name="type" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="logFilters">
<xs:complexType>
<xs:sequence>
<xs:element name="add">
<xs:complexType>
<xs:attribute name="enabled" type="xs:boolean" use="required" />
<xs:attribute name="type" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="categorySources">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="add">
<xs:complexType>
<xs:sequence>
<xs:element name="listeners">
<xs:complexType>
<xs:sequence>
<xs:element name="add">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="switchValue" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="specialSources">
<xs:complexType>
<xs:sequence>
<xs:element name="allEvents">
<xs:complexType>
<xs:attribute name="switchValue" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
<xs:element name="notProcessed">
<xs:complexType>
<xs:attribute name="switchValue" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
<xs:element name="errors">
<xs:complexType>
<xs:sequence>
<xs:element name="listeners">
<xs:complexType>
<xs:sequence>
<xs:element name="add">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="switchValue" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="tracingEnabled" type="xs:boolean" use="required" />
<xs:attribute name="defaultCategory" type="xs:string" use="required" />
<xs:attribute name="logWarningsWhenNoCategoriesMatch" type="xs:boolean" use="required" />
</xs:complexType>
</xs:element>
Read textarea value and code-char conversion:
function keys(e) {
msg.innerHTML = `last key: ${String.fromCharCode(e.keyCode)}`
if(e.key == 'Enter') {
console.log('send: ', mycon.value);
mycon.value='';
e.preventDefault();
}
}
_x000D_
Push enter to 'send'<br>
<textarea id='mycon' onkeydown="keys(event)"></textarea>
<div id="msg"></div>
_x000D_
And below nice Quake like console on div-s only :)
document.addEventListener('keyup', keys);
let conShow = false
function keys(e) {
if (e.code == 'Backquote') {
conShow = !conShow;
mycon.classList.toggle("showcon");
} else {
if (conShow) {
if (e.code == "Enter") {
conTextOld.innerHTML+= '<br>' + conText.innerHTML;
let command=conText.innerHTML.replace(/ /g,' ');
conText.innerHTML='';
console.log('Send to server:', command);
}
else if (e.code == "Backspace") {
conText.innerHTML = conText.innerText.slice(0, -1);
} else if (e.code == "Space") {
conText.innerHTML = conText.innerText + ' '
} else {
conText.innerHTML = conText.innerText + e.key;
}
}
}
}
_x000D_
body {
margin: 0
}
.con {
display: flex;
flex-direction: column;
justify-content: flex-end;
align-items: flex-start;
width: 100%;
height: 90px;
background: rgba(255, 0, 0, 0.4);
position: fixed;
top: -90px;
transition: top 0.5s ease-out 0.2s;
font-family: monospace;
}
.showcon {
top: 0px;
}
.conTextOld {
color: white;
}
.line {
display: flex;
flex-direction: row;
}
.conText{ color: yellow; }
.carret {
height: 20px;
width: 10px;
background: red;
margin-left: 1px;
}
.start { color: red; margin-right: 2px}
_x000D_
Click here and Press tilde ` (and Enter for "send")
<div id="mycon" class="con">
<div id='conTextOld' class='conTextOld'>Hello!</div>
<div class="line">
<div class='start'> > </div>
<div id='conText' class="conText"></div>
<div class='carret'></div>
</div>
</div>
_x000D_
I have spent some time trying to figure out the difference.
And i think the factory function uses the module pattern and service function uses the standard java script constructor pattern.
From CREATE FUNCTION
:
When a parameter of the function has a default value, the keyword
DEFAULT
must be specified when the function is called to retrieve the default value. This behavior is different from using parameters with default values in stored procedures in which omitting the parameter also implies the default value.
So you need to do:
SELECT dbo.fCalculateEstimateDate(647,DEFAULT)
Branching off Neil's answer, you often don't need a var at all, you can use a function in much the same way as a variable and it's much easier to read than the inline or read
-based solutions.
$ complex_message() {
cat <<'EOF'
abc'asdf"
$(dont-execute-this)
foo"bar"''
EOF
}
$ echo "This is a $(complex_message)"
This is a abc'asdf"
$(dont-execute-this)
foo"bar"''
if you add a jpg,png,pdf picture, you should use pdflatex to compile it.
The code that does what I need could be this:
# test
aux=[[0 for n in range(3)] for i in range(4)]
print('aux:',aux)
# initialization
a,b,c,d=[[0 for n in range(3)] for i in range(4)]
# changing values
a[0]=1
d[2]=5
print('a:',a)
print('b:',b)
print('c:',c)
print('d:',d)
Result:
('aux:', [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]])
('a:', [1, 0, 0])
('b:', [0, 0, 0])
('c:', [0, 0, 0])
('d:', [0, 0, 5])
The naming convention is part of the well-established JavaBeans specification and is supported by the classes in the java.beans package.
There is my working solution for sending image with post, using apache http libraries (very important here is boundary add It won't work without it in my connection):
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] imageBytes = baos.toByteArray();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(StaticData.AMBAJE_SERVER_URL + StaticData.AMBAJE_ADD_AMBAJ_TO_GROUP);
String boundary = "-------------" + System.currentTimeMillis();
httpPost.setHeader("Content-type", "multipart/form-data; boundary="+boundary);
ByteArrayBody bab = new ByteArrayBody(imageBytes, "pic.png");
StringBody sbOwner = new StringBody(StaticData.loggedUserId, ContentType.TEXT_PLAIN);
StringBody sbGroup = new StringBody("group", ContentType.TEXT_PLAIN);
HttpEntity entity = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.setBoundary(boundary)
.addPart("group", sbGroup)
.addPart("owner", sbOwner)
.addPart("image", bab)
.build();
httpPost.setEntity(entity);
try {
HttpResponse response = httpclient.execute(httpPost);
...then reading response
Combining two highly rated answers here into a complete example that is hopefully useful and self-explanatory:
#!/bin/bash
intro="You know what,"
pet1="cat"
pet2="chicken"
pet3="cow"
pet4="dog"
pet5="pig"
# Setting and reading dynamic variables
for i in {1..5}; do
pet="pet$i"
declare "sentence$i=$intro I have a pet ${!pet} at home"
done
# Just reading dynamic variables
for i in {1..5}; do
sentence="sentence$i"
echo "${!sentence}"
done
echo
echo "Again, but reading regular variables:"
echo $sentence1
echo $sentence2
echo $sentence3
echo $sentence4
echo $sentence5
Output:
You know what, I have a pet cat at home
You know what, I have a pet chicken at home
You know what, I have a pet cow at home
You know what, I have a pet dog at home
You know what, I have a pet pig at home
Again, but reading regular variables:
You know what, I have a pet cat at home
You know what, I have a pet chicken at home
You know what, I have a pet cow at home
You know what, I have a pet dog at home
You know what, I have a pet pig at home
I tried this but it didn't work for me and threw errors:
npm --depth 9999 update
npm rebuild node-sass
I have installed the latest Node.js
(which for the moment is 11.11.0 Current), after facing this problem I just did the following:
- downgrade to recommended version (which for the moment is 10.15.3 LTS)
- you can get it from NodeJS,
- deleted node_modules and
- then reinstall yarn:
yarn install
yarn start
After executing these commands everything is working fine for me.
Can't think of a only css solution, but couldn't you just had a div between those 2 and set in the css the properties to look like a line like shown in the image? If you are using divs as they were table cells this is a pretty simple solution to the problem
var_dump()
can do this.
This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.
I finally solved the problem!!! You should first set the jre path to system variables by navigating to::
control panel > System and Security > System > Advanced system settings
Under System variables click on new
Variable name: KEY_PATH
Variable value: C:\Program Files (x86)\Java\jre1.8.0_171\bin
Where Variable value should be the path to your JDK's bin folder.
Then open command prompt and Change directory to the same JDK's bin folder like this
C:\Program Files (x86)\Java\jre1.8.0_171\bin
then paste,
keytool -list -v -keystore "C:\Users\user\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
NOTE: People are confusing jre and jdk. All I did applied strictly to jre
I would suggest you to don't modify web.config from your, because every time when change, it will restart your application.
However you can read web.config using System.Configuration.ConfigurationManager.AppSettings
I have an Xml File books.xml
<ParameterDBConfig>
<ID Definition="1" />
</ParameterDBConfig>
Program:
XmlDocument doc = new XmlDocument();
doc.Load("D:/siva/books.xml");
XmlNodeList elemList = doc.GetElementsByTagName("ID");
for (int i = 0; i < elemList.Count; i++)
{
string attrVal = elemList[i].Attributes["Definition"].Value;
}
Now, attrVal
has the value of ID
.
Combination of lambda and map function can also do the job:
list_ = ['a', 'b', 'b', 'c']
sum(map(lambda x: x=="b", list_))
:2
Depending on the situation you can check with isinstance
what kind of object you have, and then use the corresponding attributes. With the introduction of abstract base classes in Python 2.6/3.0 this approach has also become much more powerful (basically ABCs allow for a more sophisticated way of duck typing).
One situation were this is useful would be if two different objects have an attribute with the same name, but with different meaning. Using only hasattr
might then lead to strange errors.
One nice example is the distinction between iterators and iterables (see this question). The __iter__
methods in an iterator and an iterable have the same name but are semantically quite different! So hasattr
is useless, but isinstance
together with ABC's provides a clean solution.
However, I agree that in most situations the hasattr
approach (described in other answers) is the most appropriate solution.
This works for me without throwing an exception:
package com.sandbox;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Sandbox {
public static void main(String[] args) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
Date parsed = format.parse("20110210");
java.sql.Date sql = new java.sql.Date(parsed.getTime());
}
}
Almost correctly.. Look at the joins, you are referring the wrong fields
SELECT student.firstname,
student.lastname,
exam.name,
exam.date,
grade.grade
FROM grade
INNER JOIN student ON student.studentId = grade.fk_studentId
INNER JOIN exam ON exam.examId = grade.fk_examId
ORDER BY exam.date
If you can wait to eliminate the duplicates until after all the additions, the typical approach is to first sort the array and then eliminate duplicates. The sorting avoids the N * N approach of scanning the array for each element as you walk through them.
The "eliminate duplicates" function is usually called unique or uniq. Some existing implementations may combine the two steps, e.g., prototype's uniq
This post has few ideas to try (and some to avoid :-) ) if your library doesn't already have one! Personally I find this one the most straight forward:
function unique(a){
a.sort();
for(var i = 1; i < a.length; ){
if(a[i-1] == a[i]){
a.splice(i, 1);
} else {
i++;
}
}
return a;
}
// Provide your own comparison
function unique(a, compareFunc){
a.sort( compareFunc );
for(var i = 1; i < a.length; ){
if( compareFunc(a[i-1], a[i]) === 0){
a.splice(i, 1);
} else {
i++;
}
}
return a;
}
I accidentally installed 'serial' (sudo python -m pip install serial
) instead of 'pySerial' (sudo python -m pip install pyserial
), which lead to the same error.
If the previously mentioned solutions did not work for you, double check if you installed the correct library.
If you are not bound to use Hashmap, I would advise to use pair< T,T >. The individual elements can be accessed by first and second calls.
Have a look at this http://www.cplusplus.com/reference/utility/pair/
I used it here : http://codeforces.com/contest/507/submission/9531943
Strangely importing directly from $_SESSION not working but have to do this to make it work :
<?php
$phpVar = $_SESSION['var'];
?>
<script>
var variableValue= '<?php echo $phpVar; ?>';
var imported = document.createElement('script');
imported.src = './your/path/to.js';
document.head.appendChild(imported);
</script>
and in to.js
$(document).ready(function(){
alert(variableValue);
// rest of js file
I have the same problem, in build.gradle (Module:app) add the following line of code inside dependencies:
dependencies
{
...
compile 'com.android.support:support-annotations:27.1.1'
}
It worked for me perfectly
try this:
update `list`
set `test` = `number`
Use the built in date_sub and date_add functions to math with dates. (See http://php.net/manual/en/datetime.sub.php)
Similar to Sazzad's answer, but in procedural style PHP,
$date = date_create('2008-12-02');
date_sub($date, date_interval_create_from_date_string('5 days'));
echo date_format($date, 'Y-m-d'); //outputs 2008-11-27
No one here posted an answer with all of the correct CSS variations, so here it is:
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
This is the procedure that seems simplest to me:
SharedPreferences sp = getSharedPreferences("MySharedPrefs", MODE_PRIVATE);
SharedPreferences.Editor e = sp.edit();
if (sp.getString("sharedString", null).equals("true")
|| sp.getString("sharedString", null) == null) {
e.putString("sharedString", "false").commit();
// Do something
} else {
// Do something else
}
I used them a fair bit when I was in school, but not so much since.
In theory they are useful when you want the loop body to execute once before the exit condition check. The problem is that for the few instances where I don't want the check first, typically I want the exit check in the middle of the loop body rather than at the very end. In that case, I prefer to use the well-known for (;;)
with an if (condition) exit;
somewhere in the body.
In fact, if I'm a bit shaky on the loop exit condition, sometimes I find it useful to start writing the loop as a for (;;) {}
with an exit statement where needed, and then when I'm done I can see if it can be "cleaned up" by moving initilizations, exit conditions, and/or increment code inside the for
's parentheses.
One solution is to run manually a shell function that sets my environment to work or personal, but I am pretty sure that I will often forget to switch to the correct identity resulting in committing under the wrong identity.
That was exactly my problem. I have written a hook script which warns you if you have any github remote and not defined a local username.
Here's how you set it up:
Create a directory to hold the global hook
mkdir -p ~/.git-templates/hooks
Tell git to copy everything in ~/.git-templates
to your per-project .git
directory when you run git init or clone
git config --global init.templatedir '~/.git-templates'
And now copy the following lines to ~/.git-templates/hooks/pre-commit
and make the file executable (don't forget this otherwise git won't execute it!)
#!/bin/bash
RED='\033[0;31m' # red color
NC='\033[0m' # no color
GITHUB_REMOTE=$(git remote -v | grep github.com)
LOCAL_USERNAME=$(git config --local user.name)
if [ -n "$GITHUB_REMOTE" ] && [ -z "$LOCAL_USERNAME" ]; then
printf "\n${RED}ATTENTION: At least one Github remote repository is configured, but no local username. "
printf "Please define a local username that matches your Github account.${NC} [pre-commit hook]\n\n"
exit 1
fi
If you use other hosts for your private repositories you have to replace github.com
according to your needs.
Now every time you do a git init
or git clone
git will copy this script to the repository and executes it before any commit is done. If you have not set a local username it will output a warning and won't let you commit.
Some Google services do not like to be used to much. Quite recently my account was locked because of script, which was sending two e-mails per second to the same user. Google considered it as a spam. So using sleep here is also justified to prevent such situations.
I don't know exactly how C
calculates PI
directly as I'm more familiar with C++
than C
; however, you could either have a predefined C
macro
or const
such as:
#define PI 3.14159265359.....
const float PI = 3.14159265359.....
const double PI = 3.14159265359.....
/* If your machine,os & compiler supports the long double */
const long double PI = 3.14159265359.....
or you could calculate it with either of these two formulas:
#define M_PI acos(-1.0);
#define M_PI (4.0 * atan(1.0)); // tan(pi/4) = 1 or acos(-1)
IMHO I'm not 100% certain but I think atan()
is cheaper than acos()
.
Try the binascii module
from binascii import unhexlify
b = unhexlify(myhexstr)
Adding to the above answers, you can also use
!which python
Type this in a cell and this will show the path of the environment. I'm not sure of the reason, but in my installation, there is no segregation of environments in the notebook, but on activating the environment and launching jupyter notebook, the path used is the python installed in the environment.
In the same case this works for me:
< git checkout Branch_name
> Switched to branch 'Branch_name'
< git fetch
> [Branch_name] Branch_name -> origin/Branch_name
< git branch --set-upstream-to origin/Branch_name Branch_name
> Branch Branch_name set up to track remote branch <New_Branch> from origin.
You can use JavaScript to do what you want:
if (document.addEventListener !== undefined) {
// Not IE
document.addEventListener('click', checkSelection, false);
} else {
// IE
document.attachEvent('onclick', checkSelection);
}
function checkSelection() {
var sel = {};
if (window.getSelection) {
// Mozilla
sel = window.getSelection();
} else if (document.selection) {
// IE
sel = document.selection.createRange();
}
// Mozilla
if (sel.rangeCount) {
sel.removeAllRanges();
return;
}
// IE
if (sel.text > '') {
document.selection.empty();
return;
}
}
Soap box: You really shouldn't be screwing with the client's user agent in this manner. If the client wants to select things on the document, then they should be able to select things on the document. It doesn't matter if you don't like the highlight color, because you aren't the one viewing the document.
If the number of buckets (call it b) is held constant (the usual case), then lookup is actually O(n).
As n gets large, the number of elements in each bucket averages n/b. If collision resolution is done in one of the usual ways (linked list for example), then lookup is O(n/b) = O(n).
The O notation is about what happens when n gets larger and larger. It can be misleading when applied to certain algorithms, and hash tables are a case in point. We choose the number of buckets based on how many elements we're expecting to deal with. When n is about the same size as b, then lookup is roughly constant-time, but we can't call it O(1) because O is defined in terms of a limit as n ? 8.
I tried using ISO-8859-1 as said in the first answer. All went ok on encoding, but when I tried to get the byte[] using result string on decoding, all negative bytes became the character 63 (question mark). The following code does not work:
// Encoding works great
byte[] contents = new byte[]{-1};
QRCodeWriter codeWriter = new QRCodeWriter();
BitMatrix bitMatrix = codeWriter.encode(new String(contents, Charset.forName("ISO-8859-1")), BarcodeFormat.QR_CODE, w, h);
// Decodes like this fails
LuminanceSource ls = new BufferedImageLuminanceSource(encodedBufferedImage);
Result result = new QRCodeReader().decode(new BinaryBitmap( new HybridBinarizer(ls)));
byte[] resultBytes = result.getText().getBytes(Charset.forName("ISO-8859-1")); // a byte[] with byte 63 is given
return resultBytes;
It looks so strange because the API in a very old version (don't know exactly) had a method thar works well:
Vector byteSegments = result.getByteSegments();
So I tried to search why this method was removed and realized that there is a way to get ByteSegments, through metadata. So my decode method looks like:
// Decodes like this works perfectly
LuminanceSource ls = new BufferedImageLuminanceSource(encodedBufferedImage);
Result result = new QRCodeReader().decode(new BinaryBitmap( new HybridBinarizer(ls)));
Vector byteSegments = (Vector) result.getResultMetadata().get(ResultMetadataType.BYTE_SEGMENTS);
int i = 0;
int tam = 0;
for (Object o : byteSegments) {
byte[] bs = (byte[])o;
tam += bs.length;
}
byte[] resultBytes = new byte[tam];
i = 0;
for (Object o : byteSegments) {
byte[] bs = (byte[])o;
for (byte b : bs) {
resultBytes[i++] = b;
}
}
return resultBytes;
scrollHeight
is a regular javascript property so you don't need jQuery.
var test = document.getElementById("foo").scrollHeight;
Try this command for Version <= Marshmallow,
adb devices
List of devices attached 38ccdc87 device
adb tcpip 5555
restarting in TCP mode port: 5555
adb shell ip addr show wlan0
24: wlan0: mtu 1500 qdisc mq state UP qlen 1000 link/ether ac:c1:ee:6b:22:f1 brd ff:ff:ff:ff:ff:ff inet 192.168.0.18/24 brd 192.168.0.255 scope global wlan0 valid_lft forever preferred_lft forever inet6 fd01::1d45:6b7a:a3b:5f4d/64 scope global temporary dynamic valid_lft 287sec preferred_lft 287sec inet6 fd01::aec1:eeff:fe6b:22f1/64 scope global dynamic valid_lft 287sec preferred_lft 287sec inet6 fe80::aec1:eeff:fe6b:22f1/64 scope link valid_lft forever preferred_lft forever
To connect to your device run this
adb connect 192.168.0.18
connected to 192.168.0.18:5555
Make sure you have adb inside this location android-sdk\platform-tools
Here the solution http://www.wacdesigns.com/2008/10/03/merge-pdf-files-using-c It use free open source iTextSharp library http://sourceforge.net/projects/itextsharp
Syntax: error_log file | stderr | syslog:server=address[,parameter=value] | memory:size [debug | info | notice | warn | error | crit | alert | emerg];
Default:
error_log logs/error.log error;
Context: main, http, stream, server, location
http://nginx.org/en/docs/ngx_core_module.html#error_log
Don't use: /dev/stderr
This will break your setup if you're going to use systemd-nspawn.
Set the attribute
android:animateLayoutChanges="true"
inside the parent layout .
Put the view in a layout if its not and set android:animateLayoutChanges="true"
for that layout.
NOTE: This works only from API Level 11+ (Android 3.0)
The other answers will break if output of command contains spaces (which is rather frequent) or glob characters like *
, ?
, [...]
.
To get the output of a command in an array, with one line per element, there are essentially 3 ways:
With Bash=4 use mapfile
—it's the most efficient:
mapfile -t my_array < <( my_command )
Otherwise, a loop reading the output (slower, but safe):
my_array=()
while IFS= read -r line; do
my_array+=( "$line" )
done < <( my_command )
As suggested by Charles Duffy in the comments (thanks!), the following might perform better than the loop method in number 2:
IFS=$'\n' read -r -d '' -a my_array < <( my_command && printf '\0' )
Please make sure you use exactly this form, i.e., make sure you have the following:
IFS=$'\n'
on the same line as the read
statement: this will only set the environment variable IFS
for the read
statement only. So it won't affect the rest of your script at all. The purpose of this variable is to tell read
to break the stream at the EOL character \n
.-r
: this is important. It tells read
to not interpret the backslashes as escape sequences.-d ''
: please note the space between the -d
option and its argument ''
. If you don't leave a space here, the ''
will never be seen, as it will disappear in the quote removal step when Bash parses the statement. This tells read
to stop reading at the nil byte. Some people write it as -d $'\0'
, but it is not really necessary. -d ''
is better.-a my_array
tells read
to populate the array my_array
while reading the stream.printf '\0'
statement after my_command
, so that read
returns 0
; it's actually not a big deal if you don't (you'll just get an return code 1
, which is okay if you don't use set -e
– which you shouldn't anyway), but just bear that in mind. It's cleaner and more semantically correct. Note that this is different from printf ''
, which doesn't output anything. printf '\0'
prints a null byte, needed by read
to happily stop reading there (remember the -d ''
option?).If you can, i.e., if you're sure your code will run on Bash=4, use the first method. And you can see it's shorter too.
If you want to use read
, the loop (method 2) might have an advantage over method 3 if you want to do some processing as the lines are read: you have direct access to it (via the $line
variable in the example I gave), and you also have access to the lines already read (via the array ${my_array[@]}
in the example I gave).
Note that mapfile
provides a way to have a callback eval'd on each line read, and in fact you can even tell it to only call this callback every N lines read; have a look at help mapfile
and the options -C
and -c
therein. (My opinion about this is that it's a little bit clunky, but can be used sometimes if you only have simple things to do — I don't really understand why this was even implemented in the first place!).
Now I'm going to tell you why the following method:
my_array=( $( my_command) )
is broken when there are spaces:
$ # I'm using this command to test:
$ echo "one two"; echo "three four"
one two
three four
$ # Now I'm going to use the broken method:
$ my_array=( $( echo "one two"; echo "three four" ) )
$ declare -p my_array
declare -a my_array='([0]="one" [1]="two" [2]="three" [3]="four")'
$ # As you can see, the fields are not the lines
$
$ # Now look at the correct method:
$ mapfile -t my_array < <(echo "one two"; echo "three four")
$ declare -p my_array
declare -a my_array='([0]="one two" [1]="three four")'
$ # Good!
Then some people will then recommend using IFS=$'\n'
to fix it:
$ IFS=$'\n'
$ my_array=( $(echo "one two"; echo "three four") )
$ declare -p my_array
declare -a my_array='([0]="one two" [1]="three four")'
$ # It works!
But now let's use another command, with globs:
$ echo "* one two"; echo "[three four]"
* one two
[three four]
$ IFS=$'\n'
$ my_array=( $(echo "* one two"; echo "[three four]") )
$ declare -p my_array
declare -a my_array='([0]="* one two" [1]="t")'
$ # What?
That's because I have a file called t
in the current directory… and this filename is matched by the glob [three four]
… at this point some people would recommend using set -f
to disable globbing: but look at it: you have to change IFS
and use set -f
to be able to fix a broken technique (and you're not even fixing it really)! when doing that we're really fighting against the shell, not working with the shell.
$ mapfile -t my_array < <( echo "* one two"; echo "[three four]")
$ declare -p my_array
declare -a my_array='([0]="* one two" [1]="[three four]")'
here we're working with the shell!
Try to use "#" before and after of the date and be sure of your system date format. maybe "YYYYMMDD O YYYY-MM-DD O MM-DD-YYYY O USING '/ O \' "
Ex:
select id,numbers_from,created_date,amount_numbers,SMS_text
from Test_Table
where
created_date <= #2013-04-12#
This is just about the most bizarre query I've ever written, but I'm pretty sure it gets the "last 5" rows from a table without ordering:
select *
from issues
where issueid not in (
select top (
(select count(*) from issues) - 5
) issueid
from issues
)
Note that this makes use of SQL Server 2005's ability to pass a value into the "top" clause - it doesn't work on SQL Server 2000.
public class B3PassingExcelDataBase {
@Test()
//Import the data::row start at 3 and column at 1:
public static void imortingData () throws IOException {
FileInputStream file=new FileInputStream("/Users/Downloads/Book2.xlsx");
XSSFWorkbook book=new XSSFWorkbook(file);
XSSFSheet sheet=book.getSheet("Sheet1");
int rowNum=sheet.getLastRowNum();
System.out.println(rowNum);
//get the row and value and assigned to variable to use in application
for (int r=3;r<rowNum;r++) {
// Rows stays same but column num changes and this is for only one person. It iterate for other.
XSSFRow currentRow=sheet.getRow(r);
String fName=currentRow.getCell(1).toString();
String lName=currentRow.getCell(2).toString();
String phone=currentRow.getCell(3).toString();
String email=currentRow.getCell(4).toString()
//passing the data
yogen.findElement(By.name("firstName")).sendKeys(fName); ;
yogen.findElement(By.name("lastName")).sendKeys(lName); ;
yogen.findElement(By.name("phone")).sendKeys(phone); ;
}
yogen.close();
}
}
Here's how I do it (in Java):
private static long ONE_SECOND = 1000000L * 1000L; //1 second is 1000ms which is 1000000ns
LinkedList<Long> frames = new LinkedList<>(); //List of frames within 1 second
public int calcFPS(){
long time = System.nanoTime(); //Current time in nano seconds
frames.add(time); //Add this frame to the list
while(true){
long f = frames.getFirst(); //Look at the first element in frames
if(time - f > ONE_SECOND){ //If it was more than 1 second ago
frames.remove(); //Remove it from the list of frames
} else break;
/*If it was within 1 second we know that all other frames in the list
* are also within 1 second
*/
}
return frames.size(); //Return the size of the list
}
You can use javascript to block form submission until the appropriate time. A very crude example:
<form onsubmit='return false;' id='frmNoEnterSubmit' action="index.html">
<input type='text' name='txtTest' />
<input type='button' value='Submit'
onclick='document.forms["frmNoEnterSubmit"].onsubmit=""; document.forms["frmNoEnterSubmit"].submit();' />
</form>
Pressing enter will still trigger the form to submit, but the javascript will keep it from actually submitting, until you actually press the button.
If your project is .net Core 3.1 API project.
update your Startup.cs in your .net core project to:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://localhost:53135",
"http://localhost:4200"
)
.AllowAnyHeader()
.AllowAnyMethod();
});
});
services.AddDbContext<CIVDataContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("CIVDatabaseConnection")));
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(MyAllowSpecificOrigins);
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
From the Mozilla Developer Network (MDN) documentation, HTMLElement.click() is what you're looking for. You can find out more events here.