So my goal was to be able to select the same value multiple times which essentially overwrites the the onchange() function and turn it into a useful onclick() method.
Based on the suggestions above I came up with this which works for me.
<select name="ab" id="hi" onchange="if (typeof(this.selectedIndex) != undefined) {alert($('#hi').val()); this.blur();}" onfocus="this.selectedIndex = -1;">
<option value="-1">--</option>
<option value="1">option 1</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
</select>
I had similar problem while installing SQL Server 2005 on Windows 7 Professional and got error SQL server failed to start
. I logged in as a Administrator (my user id is administrator) in windows.
SOLUTION
Go to services, from control panel -> Administrative Tools
Click on properties of "SQL Server (MSSQLSERVER)"
Go to Log On Tab, Select "This Account"
Enter your windows login detail (administrator and password)
Start the service manually, it should work fine..
Hope this too helps..
Yes, just format your strings in the standard String.format()
way.
See the method Context.getString(int, Object...)
and the Android or Java Formatter
documentation.
In your case, the string definition would be:
<string name="timeFormat">%1$d minutes ago</string>
If it's a string, you could assume / hope it's always of the form
return SomeFunction(arguments);
parse for the function name, and then see if that function is defined using
if (window[functionName]) {
// do stuff
}
The JS answer to this question is:
or something similar
If you need to specify the exact charactor length, we have to avoid values with 0 in-front.
Final String representation must have that exact character length.
String GenerateRandomNumber(int charLength) {
return String.valueOf(charLength < 1 ? 0 : new Random()
.nextInt((9 * (int) Math.pow(10, charLength - 1)) - 1)
+ (int) Math.pow(10, charLength - 1));
}
I think this might help...
In order to break down user inputted dates (mm/dd/yyyy) in my scripts, I store the day, month, and year into an array, and then put the values into separate variables as follows:
DATE_ARRAY=(`echo $2 | sed -e 's/\// /g'`)
MONTH=(`echo ${DATE_ARRAY[0]}`)
DAY=(`echo ${DATE_ARRAY[1]}`)
YEAR=(`echo ${DATE_ARRAY[2]}`)
Simplest Way with Jquery -
var finalObj = $.extend(obj1, obj2);
Without Jquery -
var finalobj={};
for(var _obj in obj1) finalobj[_obj ]=obj1[_obj];
for(var _obj in obj2) finalobj[_obj ]=obj2[_obj];
a=[]
for j in range(3):
a.append([int(i) for i in input().split()])
In this above code the given input i.e Mike 18 Kevin 35 Angel 56, will be stored in an array 'a' and gives the output as [['Mike', '18'], ['Kevin', '35'], ['Angel', '56']].
Agree with Gray, as you may need your pattern to have both litrals (\[, \]) and meta-characters ([, ]). so with some utility you should be able to escape all character first and then you can add meta-characters you want to add on same pattern.
Use ggrep.
ggrep -H -R -I "mysearchstring" *
to search for a file in unix containing text located in the current directory or a subdirectory
You might want to check out the angular-ui directive ui-if
if you just want to remove the ul
from the DOM when the list is empty:
<ul ui-if="!!events.length">
<li ng-repeat="event in events">{{event.title}}</li>
</ul>
If your <td>
is not empty, one popular trick is to insert a non breaking space
in it, such that:
<td id="td1"> </td>
Then you will be able to use:
document.getElementById('td1').firstChild.data = 'New Value';
Otherwise, if you do not fancy adding the meaningless  
you can use the solution that Jonathan Fingland described in the other answer.
I believe you want to set the Content
property. This has more information on what is available to a label.
Using an empty string is perfectly fine and actually much safer than simply using $_SERVER['PHP_SELF']
.
When using $_SERVER['PHP_SELF']
it is very easy to inject malicious data by simply appending /<script>...
after the whatever.php
part of the URL so you should not use this method and stop using any PHP tutorial that suggests it.
Maybe try this? It seems the problem is solved after remove all the handlers in my case.
for handler in logging.root.handlers[:]:
logging.root.removeHandler(handler)
logging.basicConfig(filename='output.log', level=logging.INFO)
Or
$dataProvider->setSort([
'defaultOrder' => ['topic_order'=>SORT_DESC],
'attributes' => [...
Semantically what you are trying is invalid html, table
element cannot have a div
element as a direct child. What you can do is, get your div
element inside a td
element and than try to hide it
Use the View's post method like this
post(new Runnable() {
@Override
public void run() {
Log.d(TAG, "width " + MyView.this.getMeasuredWidth());
}
});
At least with Miniconda (I assume it's the same for Anaconda), within the environment folder, the packages are installed in a folder called \conda-meta.
i.e.
C:\Users\username\Miniconda3\envs\environmentname\conda-meta
If you install on the base environment, the location is:
C:\Users\username\Miniconda3\pkgs
logging.basicConfig()
can take a keyword argument handlers
since Python 3.3, which simplifies logging setup a lot, especially when setting up multiple handlers with the same formatter:
handlers
– If specified, this should be an iterable of already created handlers to add to the root logger. Any handlers which don’t already have a formatter set will be assigned the default formatter created in this function.
The whole setup can therefore be done with a single call like this:
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.FileHandler("debug.log"),
logging.StreamHandler()
]
)
(Or with import sys
+ StreamHandler(sys.stdout)
per original question's requirements – the default for StreamHandler is to write to stderr. Look at LogRecord attributes if you want to customize the log format and add things like filename/line, thread info etc.)
The setup above needs to be done only once near the beginning of the script. You can use the logging from all other places in the codebase later like this:
logging.info('Useful message')
logging.error('Something bad happened')
...
Note: If it doesn't work, someone else has probably already initialized the logging system differently. Comments suggest doing logging.root.handlers = []
before the call to basicConfig()
.
You want to convert mdb to mysql (direct transfer to mysql or mysql dump)?
Try a software called Access to MySQL.
Access to MySQL is a small program that will convert Microsoft Access Databases to MySQL.
- Wizard interface.
- Transfer data directly from one server to another.
- Create a dump file.
- Select tables to transfer.
- Select fields to transfer.
- Transfer password protected databases.
- Supports both shared security and user-level security.
- Optional transfer of indexes.
- Optional transfer of records.
- Optional transfer of default values in field definitions.
- Identifies and transfers auto number field types.
- Command line interface.
- Easy install, uninstall and upgrade.
See the aforementioned link for a step-by-step tutorial with screenshots.
Use android:background property for that edittext. Pass your drawable folder image to it. For example,
android:background="@drawable/abc.png"
In Web Application Projects, Visual Studio needs additional .designer files for pages and user controls. Web Site Projects do not require this overhead. The markup itself is interpreted as the design.
Step 1 :
Create ts : app/_helpers/must-match.validator.ts
import { FormGroup } from '@angular/forms';
export function MustMatch(controlName: string, matchingControlName: string) {
return (formGroup: FormGroup) => {
const control = formGroup.controls[controlName];
const matchingControl = formGroup.controls[matchingControlName];
if (matchingControl.errors && !matchingControl.errors.mustMatch) {
return;
}
if (control.value !== matchingControl.value) {
matchingControl.setErrors({ mustMatch: true });
} else {
matchingControl.setErrors(null);
}
}
}
Step 2 :
Use in your component.ts
import { MustMatch } from '../_helpers/must-match.validator';
ngOnInit() {
this.loginForm = this.formbuilder.group({
Password: ['', [Validators.required, Validators.minLength(6)]],
ConfirmPassword: ['', [Validators.required]],
}, {
validator: MustMatch('Password', 'ConfirmPassword')
});
}
Step 3 :
Use In View/Html
<input type="password" formControlName="Password" class="form-control" autofocus>
<div *ngIf="loginForm.controls['Password'].invalid && (loginForm.controls['Password'].dirty || loginForm.controls['Password'].touched)" class="alert alert-danger">
<div *ngIf="loginForm.controls['Password'].errors.required">Password Required. </div>
<div *ngIf="loginForm.controls['Password'].errors.minlength">Password must be at least 6 characters</div>
</div>
<input type="password" formControlName="ConfirmPassword" class="form-control" >
<div *ngIf="loginForm.controls['ConfirmPassword'].invalid && (loginForm.controls['ConfirmPassword'].dirty || loginForm.controls['ConfirmPassword'].touched)" class="alert alert-danger">
<div *ngIf="loginForm.controls['ConfirmPassword'].errors.required">ConfirmPassword Required. </div>
<div *ngIf="loginForm.controls['ConfirmPassword'].errors.mustMatch">Your password and confirmation password do not match.</div>
</div>
Bootstrap 3.1.1 has a .center-block
class for centering divs. See: http://getbootstrap.com/css/#helper-classes-center.
Center content blocks Set an element to
display: block
and center viamargin
. Available as a mixin and class.
<div class="center-block">...</div>
Or, as others have already said, use the .text-center
class to centre text.
If you want to pick cell entries from a list then you have a couple of non-code based options
I would recommend The Data Validation approach where
sample from Debra's site below, click on the first link above to access it.
I could get away with the following solution (works with Ubuntu 14 guest VM on Windows 7 host or Ubuntu 9.10 Casper guest VM on host Windows XP x86):
var consolidatedChildren =
from c in children
group c by new
{
c.School,
c.Friend,
c.FavoriteColor,
} into gcs
select new ConsolidatedChild()
{
School = gcs.Key.School,
Friend = gcs.Key.Friend,
FavoriteColor = gcs.Key.FavoriteColor,
Children = gcs.ToList(),
};
var consolidatedChildren =
children
.GroupBy(c => new
{
c.School,
c.Friend,
c.FavoriteColor,
})
.Select(gcs => new ConsolidatedChild()
{
School = gcs.Key.School,
Friend = gcs.Key.Friend,
FavoriteColor = gcs.Key.FavoriteColor,
Children = gcs.ToList(),
});
Returning null could be more efficient, as no new object is created. However, it would also often require a null
check (or exception handling.)
Semantically, null
and an empty list do not mean the same thing. The differences are subtle and one choice may be better than the other in specific instances.
Regardless of your choice, document it to avoid confusion.
Two points:
List
is an array. If your memory is heavily fragmented, there may not be enough contiguous space to allocate your List
, even though in total you have plenty of free memory.So I discovered pcregrep which stands for Perl Compatible Regular Expressions GREP.
For example, you need to find files where the '_name' variable is immediatelly followed by the '_description' variable:
find . -iname '*.py' | xargs pcregrep -M '_name.*\n.*_description'
Tip: you need to include the line break character in your pattern. Depending on your platform, it could be '\n', \r', '\r\n', ...
The approach you should take is to install pip
for Python 3.2.
You do this in the following way:
$ curl -O https://bootstrap.pypa.io/get-pip.py
$ sudo python3.2 get-pip.py
Then, you can install things for Python 3.2 with pip-3.2
, and install things for Python 2-7 with pip-2.7
. The pip
command will end up pointing to one of these, but I'm not sure which, so you will have to check.
Sometimes you still need to use FirstOrDefault if you have to do different tests. If the Key component of your dictionnary is nullable, you can do this:
thisTag = _tags.FirstOrDefault(t => t.Key.SubString(1,1) == 'a');
if(thisTag.Key != null) { ... }
Using FirstOrDefault, the returned KeyValuePair's key and value will both be null if no match is found.
There is no way that you can do it in PHP when HTML is already generated. What you can do is to use JavaScript or jQuery:
document.getElementById('//ID//').innerHTML="HTML CODE";
If you have to do it when your URI changes you can get the URI and then split it and then insert the HTML in script dynamically:
var url = document.URL;
// to get url and then use split() to check the parameter
I write this function
def larger(x, than=0):
if not x or min(x) > than:
return True
return False
Then
print larger([5, 6, 7], than=5) # False
print larger([6, 7, 8], than=5) # True
print larger([], than=5) # True
print larger([6, 7, 8, None], than=5) # False
Empty list on min() will raise ValueError. So I added if not x
in condition.
If you're on windows you probably want the pywin32
library, which includes pythoncom
and a whole lot of other stuff that is pretty standard.
split with the + sign like this way
String a = tv.getText().toString();
String aa[];
if(a.contains("+"))
aa = a.split("+");
now convert the array
Integer.parseInt(aa[0]); // and so on
I created this, just add the function as an argument and whenever the link has any changes it will run the function returning the old and new url
I created this, just add the function as an argument and whenever the link has any changes it will run the function returning the old and new url
// on-url-change.js v1 (manual verification)
let onUrlChangeCallbacks = [];
let onUrlChangeTimestamp = new Date() * 1;
function onUrlChange(callback){
onUrlChangeCallbacks.push(callback);
};
onUrlChangeAutorun();
function onUrlChangeAutorun(){
let oldURL = window.location.href;
setInterval(function(){
let newURL = window.location.href;
if(oldURL !== newURL){
let event = {
oldURL: oldURL,
newURL: newURL,
type: 'urlchange',
timestamp: new Date() * 1 - onUrlChangeTimestamp
};
oldURL = newURL;
for(let i = 0; i < onUrlChangeCallbacks.length; i++){
onUrlChangeCallbacks[i](event);
};
};
}, 25);
};
I understand you have a scenario with ErrorDocument already defined within your apache conf or .htaccess and want to make those pages appear when manually sending a 4xx status code via php.
Unfortunately this is not possible with common methods because php sends header directly to user's browser (not to Apache web server) whereas ErrorDocument is a display handler for http status generated from Apache.
You could set the image as a background image. Since it resides in a div
, and the div
is undraggable, the image will be undraggable:
<div style="background-image: url("image.jpg");">
</div>
Use theme "Theme.NoTitleBar.Fullscreen"
and try setting "android:windowSoftInputMode=adjustResize"
for the activity in AndroidManifest.xml.
You can find details here.
You must fill the "Button" attribute of the "CompoundButton" class with a XML drawable path (my_checkbox). In the XML drawable, you must have :
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_checked="false" android:drawable="@drawable/checkbox_not_checked" />
<item android:state_checked="true" android:drawable="@drawable/checkbox_checked" />
<item android:drawable="@drawable/checkbox_not_checked" /> <!-- default -->
</selector>
Don't forget to replace my_checkbox by your filename of the checkbox drawable , checkbox_not_checked by your PNG drawable which is your checkbox when it's not checked and checkbox_checked with your image when it's checked.
For the size, directly update the layout parameters.
At my work we have our restful services on a different port number and the data resides in db2 on a pair of AS400s. We typically use the $.getJSON
AJAX method because it easily returns JSONP using the ?callback=?
without having any issues with CORS.
data ='USER=<?echo trim($USER)?>' +
'&QRYTYPE=' + $("input[name=QRYTYPE]:checked").val();
//Call the REST program/method returns: JSONP
$.getJSON( "http://www.stackoverflow.com/rest/resttest?callback=?",data)
.done(function( json ) {
// loading...
if ($.trim(json.ERROR) != '') {
$("#error-msg").text(message).show();
}
else{
$(".error").hide();
$("#jsonp").text(json.whatever);
}
})
.fail(function( jqXHR, textStatus, error ) {
var err = textStatus + ", " + error;
alert('Unable to Connect to Server.\n Try again Later.\n Request Failed: ' + err);
});
By using map function you can do that. Please refer below code.
var userDetails = [{
"_id":"5078c3a803ff4197dc81fbfb",
"email":"[email protected]",
"image":"some_image_url",
"name":"Name 1"
},{
"_id":"5078c3a803ff4197dc81fbfc",
"email":"[email protected]",
"image":"some_image_url",
"name":"Name 2"
}];
var formattedUserDetails = userDetails.map(({ _id:id, email, image, name }) => ({
id,
email,
image,
name
}));
console.log(formattedUserDetails);
I got one good solution. Here I have attached it as the image below. So try it. It may be helpful to you...!
Just remove the throw
from the catch block — change it to an echo
or otherwise handle the error.
It's not telling you that objects can only be thrown in the catch block, it's telling you that only objects can be thrown, and the location of the error is in the catch block — there is a difference.
In the catch block you are trying to throw something you just caught — which in this context makes little sense anyway — and the thing you are trying to throw is a string.
A real-world analogy of what you are doing is catching a ball, then trying to throw just the manufacturer's logo somewhere else. You can only throw a whole object, not a property of the object.
I have thesame issue before but i solved it easily by just following this steps:
*connect your android phone in a debugging mode (to enable debugging mode goto settings scroll down About Phone scroll down tap seven times Build Number and it will automatically enable developer option turn on developer options and check USB debugging)
download Universal ADB Driver Installer
*choose Adb Driver Installer (Universal)
*install it *it will automatically detect your android device(any kind of brand) *chose the device and install
I am pretty new to all of this, but I found that if the script is started via CScript.exe (console scripting host) there is no window popping up on exec(): so when running:
cscript myscript.vbs //nologo
any .Exec() calls in the myscript.vbs do not open an extra window, meaning that you can use the first variant of your original solution (using exec).
(Note that the two forward slashes in the above code are intentional, see cscript /?)
In Powershell 5 escaping double quotes can be done by backtick (`). But sometimes you need to provide your double quotes escaped which can be done by backslash + backtick (\`). Eg in this curl call:
C:\Windows\System32\curl.exe -s -k -H "Content-Type: application/json" -XPOST localhost:9200/index_name/inded_type -d"{\`"velocity\`":3.14}"
Some JavaScript engines can parse that format directly, which makes the task pretty easy:
function convertDate(inputFormat) {_x000D_
function pad(s) { return (s < 10) ? '0' + s : s; }_x000D_
var d = new Date(inputFormat)_x000D_
return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/')_x000D_
}_x000D_
_x000D_
console.log(convertDate('Mon Nov 19 13:29:40 2012')) // => "19/11/2012"
_x000D_
The port that the Admin button references is configurable. In the XAMPP install folder there is a xampp-control.ini
file. Changing the Apache entry under [ServicePorts]
will affect the url the Admin button opens.
[ServicePorts]
Apache=8080
They tell what size can be stored in a integer variable. To remember the size you can think in terms of :-) 2 beer( 2 bytes) , 4 beer(4 bytes) or 8 beer( 8 bytes).
Int16 :-2 beers/bytes = 16 bit = 2^16 = 65536 = 65536/2 = -32768 to 32767
Int32 :- 4 beers/bytes = 32 bit = 2^32 = 4294967296 = 4294967296/2 = -2147483648 to 2147483647
Int64 :- 8 beer/ bytes = 64 bit = 2^64 = 18446744073709551616 = 18446744073709551616 /2 = -9223372036854775808 to 9223372036854775807
In short you can store more than 32767 value in int16 , more than 2147483647 value in int32 and more than 9223372036854775807 value in int64.
To understand above calculation you can check out this video int16 vs int32 vs int64
The correct answer, from all above, is to run the commands below:
sudo cp /etc/kubernetes/admin.conf $HOME/
sudo chown $(id -u):$(id -g) $HOME/admin.conf
export KUBECONFIG=$HOME/admin.conf
//Runs function after x seconds
public static func runThisAfterDelay(seconds: Double, after: @escaping () -> Void) {
runThisAfterDelay(seconds: seconds, queue: DispatchQueue.main, after: after)
}
public static func runThisAfterDelay(seconds: Double, queue: DispatchQueue, after: @escaping () -> Void) {
let time = DispatchTime.now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
queue.asyncAfter(deadline: time, execute: after)
}
//Use:-
runThisAfterDelay(seconds: x){
//write your code here
}
cgi.escape
extendedThis version improves cgi.escape
. It also preserves whitespace and newlines. Returns a unicode
string.
def escape_html(text):
"""escape strings for display in HTML"""
return cgi.escape(text, quote=True).\
replace(u'\n', u'<br />').\
replace(u'\t', u' ').\
replace(u' ', u' ')
>>> escape_html('<foo>\nfoo\t"bar"')
u'<foo><br />foo "bar"'
public static class DateTimeExtensions
{
public static DateTime LastDayOfMonth(this DateTime date)
{
return date.AddDays(1-(date.Day)).AddMonths(1).AddDays(-1);
}
}
read.table
wants to return a data.frame
, which must have an element in each column. Therefore R expects each row to have the same number of elements and it doesn't fill in empty spaces by default. Try read.table("/PathTo/file.csv" , fill = TRUE )
to fill in the blanks.
e.g.
read.table( text= "Element1 Element2
Element5 Element6 Element7" , fill = TRUE , header = FALSE )
# V1 V2 V3
#1 Element1 Element2
#2 Element5 Element6 Element7
A note on whether or not to set header = FALSE
... read.table
tries to automatically determine if you have a header row thus:
header
is set toTRUE
if and only if the first row contains one fewer field than the number of columns
merge into MY_TABLE tgt
using (select [expressions]
from dual ) src
on (src.key_condition = tgt.key_condition)
when matched then
update tgt
set tgt.column1 = src.column1 [,...]
when not matched then
insert into tgt
([list of columns])
values
(src.column1 [,...]);
I was struggling this for some time, it never worked.
In the end, the solution was to put a style element in the head.
The page-break-after can't be in a linked CSS file, it must be in the HTML itself.
This code will add an event listener to the default local Inbox, then take some action on incoming emails. You need to add that action in the code below.
Private WithEvents Items As Outlook.Items
Private Sub Application_Startup()
Dim olApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Set olApp = Outlook.Application
Set objNS = olApp.GetNamespace("MAPI")
' default local Inbox
Set Items = objNS.GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub Items_ItemAdd(ByVal item As Object)
On Error Goto ErrorHandler
Dim Msg As Outlook.MailItem
If TypeName(item) = "MailItem" Then
Set Msg = item
' ******************
' do something here
' ******************
End If
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
End Sub
After pasting the code in ThisOutlookSession
module, you must restart Outlook.
You should amend creation of the gesture recogniser to accept parameter (add colon ':')
UITapGestureRecognizer *letterTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(highlightLetter:)];
And in your method highlightLetter: you can access the view attached to recogniser:
-(IBAction) highlightLetter:(UITapGestureRecognizer*)recognizer
{
UIView *view = [recognizer view];
}
If you are using Python3 with pathlib
you can access os.stat()
information using the Path.stat()
method, which has the attribute st_size
(file size in bytes):
>>> from pathlib import Path
>>> mypath = Path("path/to/my/file")
>>> mypath.stat().st_size == 0 # True if empty
Your understanding is incorrect, in cases like these always consult the JavaDoc.
assertFalse
public static void assertFalse(java.lang.String message, boolean condition)
Asserts that a condition is false. If it isn't it throws an AssertionError with the given message.
Parameters:
message
- the identifying message for the AssertionError (null okay)condition
- condition to be checked
I've found a better way how to manage JS packages in my project with NPM Gulp/Grunt task runners. I don't like the idea to have a NPM with another layer of javascript library to handle the "automation", and my number one requirement is to simple run the npm update without any other worries about to if I need to run gulp stuff, if it successfully copied everything and vice versa.
The NPM way:
- The JS minifier is already bundled in the ASP.net core, look for bundleconfig.json so this is not an issue for me (not compiling something custom)
- The good thing about NPM is that is have a good file structure so I can always find the pre-compiled/minified versions of the dependencies under the node_modules/module/dist
- I'm using an NPM node_modules/.hooks/{eventname} script which is handling the copy/update/delete of the Project/wwwroot/lib/module/dist/.js files, you can find the documentation here https://docs.npmjs.com/misc/scripts (I'll update the script that I'm using to git once it'll be more polished) I don't need additional task runners (.js tools which I don't like) what keeps my project clean and simple.
The python way:
https://pypi.python.org/pyp... but in this case you need to maintain the sources manually
Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity
).
Make sure you refer to the property as fileName
in the Criteria query, not filename
.
Specifically, Hibernate will call the getter method of the filename
property when executing that Criteria query, so it will look for a method called getFilename()
. But the property is called FileName
and the getter getFileName()
.
So, change the projection like so:
criteria.setProjection(Projections.property("fileName"));
exampleData=
const json1 = [
{id: 1, test: 1},
{id: 2, test: 2},
{id: 3, test: 3},
{id: 4, test: 4},
{id: 5, test: 5}
];
const json2 = [
{id: 3, test: 6},
{id: 4, test: 7},
{id: 5, test: 8},
{id: 6, test: 9},
{id: 7, test: 10}
];
example1=
const finalData1 = json1.concat(json2).reduce(function (index, obj) {
index[obj.id] = Object.assign({}, obj, index[obj.id]);
return index;
}, []).filter(function (res, obj) {
return obj;
});
example2=
let hashData = new Map();
json1.concat(json2).forEach(function (obj) {
hashData.set(obj.id, Object.assign(hashData.get(obj.id) || {}, obj))
});
const finalData2 = Array.from(hashData.values());
I recommend second example , it is faster.
Assuming your Data frame is like 'Data' you have to consider if your data is a string or an integer. Both are treated differently. So in this case you need be specific about that.
import pandas as pd
data = [('001','xxx'), ('002','xxx'), ('003','xxx'), ('004','xxx'), ('005','xxx')]
df = pd.DataFrame(data,columns=['issueid', 'industry'])
print("Old DataFrame")
print(df)
df.loc[:,'industry'] = str('yyy')
print("New DataFrame")
print(df)
Now if want to put numbers instead of letters you must create and array
list_of_ones = [1,1,1,1,1]
df.loc[:,'industry'] = list_of_ones
print(df)
Or if you are using Numpy
import numpy as np
n = len(df)
df.loc[:,'industry'] = np.ones(n)
print(df)
The obvious answer, of course, is not to do the unchecked cast.
If it's absolutely necessary, then at least try to limit the scope of the @SuppressWarnings
annotation. According to its Javadocs, it can go on local variables; this way, it doesn't even affect the entire method.
Example:
@SuppressWarnings("unchecked")
Map<String, String> myMap = (Map<String, String>) deserializeMap();
There is no way to determine whether the Map
really should have the generic parameters <String, String>
. You must know beforehand what the parameters should be (or you'll find out when you get a ClassCastException
). This is why the code generates a warning, because the compiler can't possibly know whether is safe.
In ES6, import
s are live read-only views on exported-values. As a result, when you do import a from "somemodule";
, you cannot assign to a
no matter how you declare a
in the module.
However, since imported variables are live views, they do change according to the "raw" exported variable in exports. Consider the following code (borrowed from the reference article below):
//------ lib.js ------
export let counter = 3;
export function incCounter() {
counter++;
}
//------ main1.js ------
import { counter, incCounter } from './lib';
// The imported value `counter` is live
console.log(counter); // 3
incCounter();
console.log(counter); // 4
// The imported value can’t be changed
counter++; // TypeError
As you can see, the difference really lies in lib.js
, not main1.js
.
To summarize:
import
-ed variables, no matter how you declare the corresponding variables in the module.let
-vs-const
semantics applies to the declared variable in the module.
const
, it cannot be reassigned or rebound in anywhere.let
, it can only be reassigned in the module (but not the user). If it is changed, the import
-ed variable changes accordingly.This is a good use case for Objective C categories.
For Base64 encoding:
#import <Foundation/NSString.h>
@interface NSString (NSStringAdditions)
+ (NSString *) base64StringFromData:(NSData *)data length:(int)length;
@end
-------------------------------------------
#import "NSStringAdditions.h"
static char base64EncodingTable[64] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
};
@implementation NSString (NSStringAdditions)
+ (NSString *) base64StringFromData: (NSData *)data length: (int)length {
unsigned long ixtext, lentext;
long ctremaining;
unsigned char input[3], output[4];
short i, charsonline = 0, ctcopy;
const unsigned char *raw;
NSMutableString *result;
lentext = [data length];
if (lentext < 1)
return @"";
result = [NSMutableString stringWithCapacity: lentext];
raw = [data bytes];
ixtext = 0;
while (true) {
ctremaining = lentext - ixtext;
if (ctremaining <= 0)
break;
for (i = 0; i < 3; i++) {
unsigned long ix = ixtext + i;
if (ix < lentext)
input[i] = raw[ix];
else
input[i] = 0;
}
output[0] = (input[0] & 0xFC) >> 2;
output[1] = ((input[0] & 0x03) << 4) | ((input[1] & 0xF0) >> 4);
output[2] = ((input[1] & 0x0F) << 2) | ((input[2] & 0xC0) >> 6);
output[3] = input[2] & 0x3F;
ctcopy = 4;
switch (ctremaining) {
case 1:
ctcopy = 2;
break;
case 2:
ctcopy = 3;
break;
}
for (i = 0; i < ctcopy; i++)
[result appendString: [NSString stringWithFormat: @"%c", base64EncodingTable[output[i]]]];
for (i = ctcopy; i < 4; i++)
[result appendString: @"="];
ixtext += 3;
charsonline += 4;
if ((length > 0) && (charsonline >= length))
charsonline = 0;
}
return result;
}
@end
For Base64 decoding:
#import <Foundation/Foundation.h>
@class NSString;
@interface NSData (NSDataAdditions)
+ (NSData *) base64DataFromString:(NSString *)string;
@end
-------------------------------------------
#import "NSDataAdditions.h"
@implementation NSData (NSDataAdditions)
+ (NSData *)base64DataFromString: (NSString *)string
{
unsigned long ixtext, lentext;
unsigned char ch, inbuf[4], outbuf[3];
short i, ixinbuf;
Boolean flignore, flendtext = false;
const unsigned char *tempcstring;
NSMutableData *theData;
if (string == nil)
{
return [NSData data];
}
ixtext = 0;
tempcstring = (const unsigned char *)[string UTF8String];
lentext = [string length];
theData = [NSMutableData dataWithCapacity: lentext];
ixinbuf = 0;
while (true)
{
if (ixtext >= lentext)
{
break;
}
ch = tempcstring [ixtext++];
flignore = false;
if ((ch >= 'A') && (ch <= 'Z'))
{
ch = ch - 'A';
}
else if ((ch >= 'a') && (ch <= 'z'))
{
ch = ch - 'a' + 26;
}
else if ((ch >= '0') && (ch <= '9'))
{
ch = ch - '0' + 52;
}
else if (ch == '+')
{
ch = 62;
}
else if (ch == '=')
{
flendtext = true;
}
else if (ch == '/')
{
ch = 63;
}
else
{
flignore = true;
}
if (!flignore)
{
short ctcharsinbuf = 3;
Boolean flbreak = false;
if (flendtext)
{
if (ixinbuf == 0)
{
break;
}
if ((ixinbuf == 1) || (ixinbuf == 2))
{
ctcharsinbuf = 1;
}
else
{
ctcharsinbuf = 2;
}
ixinbuf = 3;
flbreak = true;
}
inbuf [ixinbuf++] = ch;
if (ixinbuf == 4)
{
ixinbuf = 0;
outbuf[0] = (inbuf[0] << 2) | ((inbuf[1] & 0x30) >> 4);
outbuf[1] = ((inbuf[1] & 0x0F) << 4) | ((inbuf[2] & 0x3C) >> 2);
outbuf[2] = ((inbuf[2] & 0x03) << 6) | (inbuf[3] & 0x3F);
for (i = 0; i < ctcharsinbuf; i++)
{
[theData appendBytes: &outbuf[i] length: 1];
}
}
if (flbreak)
{
break;
}
}
}
return theData;
}
@end
As an aside, when trying to diagnose a similar bug I realised that jquery's ajax error callback returns a status of "timeout" if it failed due to a timeout.
Here's an example:
$.ajax({
url: "/ajax_json_echo/",
timeout: 500,
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus); // this will be "timeout"
}
});
Generally when I want to create a JSON or YAML string, I start out by building the Perl data structure, and then running a simple conversion on it. You could put a UI in front of the Perl data structure generation, e.g. a web form.
Converting a structure to JSON is very straightforward:
use strict;
use warnings;
use JSON::Any;
my $data = { arbitrary structure in here };
my $json_handler = JSON::Any->new(utf8=>1);
my $json_string = $json_handler->objToJson($data);
Note that the onload event doesn't seem to fire if the iframe is loaded when offscreen. This frequently occurs when using "Open in New Window" /w tabs.
how to completely clear localstorage
localStorage.clear();
how to completely clear sessionstorage
sessionStorage.clear();
[...] Cookies ?
var cookies = document.cookie;
for (var i = 0; i < cookies.split(";").length; ++i)
{
var myCookie = cookies[i];
var pos = myCookie.indexOf("=");
var name = pos > -1 ? myCookie.substr(0, pos) : myCookie;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
is there any way to get the value back after clear these ?
No, there isn't. But you shouldn't rely on this if this is related to a security question.
Use this in onCreate() of the Activity
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
This code needs to be put inside Run SQL query/queries on database
ALTER TABLE `table_name` CHANGE `column_name` `column_name` VARCHAR(128) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL;
Please replace table_name and column_name with appropriate name.
element instanceof RenderedWebElement
should work.
Yes, provided you have access to the object definition and can modify it to declare the custom event
public event EventHandler<EventArgs> ModelChanged;
And normally you'd back this up with a private method used internally to invoke the event:
private void OnModelChanged(EventArgs e)
{
if (ModelChanged != null)
ModelChanged(this, e);
}
Your code simply declares a handler for the declared myMethod
event (you can also remove the constructor), which would get invoked every time the object triggers the event.
myObject.myMethod += myNameEvent;
Similarly, you can detach a handler using
myObject.myMethod -= myNameEvent;
Also, you can write your own subclass of EventArgs
to provide specific data when your event fires.
try to use absolute url. if it not works, check if service's response has headers:
Access-Control-Allow-Origin and Access-Control-Allow-Headers
for example:
"Access-Control-Allow-Origin": "*"
"Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept"
By default findOneAndUpdate returns the original document. If you want it to return the modified document pass an options object { new: true }
to the function:
Cat.findOneAndUpdate({ age: 17 }, { $set: { name: "Naomi" } }, { new: true }, function(err, doc) {
});
I've created a small mapper function:
private getAddressParts(object): Object {
let address = {};
const address_components = object.address_components;
address_components.forEach(element => {
address[element.types[0]] = element.short_name;
});
return address;
}
It's a solution for Angular 4 but I think you'll get the idea.
Usage:
geocoder.geocode({ 'location' : latlng }, (results, status) => {
if (status === google.maps.GeocoderStatus.OK) {
const address = {
formatted_address: results[0].formatted_address,
address_parts: this.getAddressParts(results[0])
};
(....)
}
This way the address
object will be something like this:
address: {
address_parts: {
administrative_area_level_1: "NY",
administrative_area_level_2: "New York County",
country: "US",
locality: "New York",
neighborhood: "Lower Manhattan",
political: "Manhattan",
postal_code: "10038",
route: "Beekman St",
street_number: "90",
},
formatted_address: "90 Beekman St, New York, NY 10038, USA"
}
Hope it helps!
In my case, this error was due to incorrect paths used to specify intents in my preferences xml file after I renamed the project. For instance, where I had:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<Preference
android:key="pref_edit_recipe_key"
android:title="Add/Edit Recipe">
<intent
android:action="android.intent.action.VIEW"
android:targetPackage="com.ssimon.olddirectory"
android:targetClass="com.ssimon.olddirectory.RecipeEditActivity"/>
</Preference>
</PreferenceScreen>
I needed the following instead:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<Preference
android:key="pref_edit_recipe_key"
android:title="Add/Edit Recipe">
<intent
android:action="android.intent.action.VIEW"
android:targetPackage="com.ssimon.newdirectory"
android:targetClass="com.ssimon.newdirectory.RecipeEditActivity"/>
</Preference>
Correcting the path names fixed the problem.
Maybe you want to track the remote branch with a local branch:
git branch new-local-branch
git branch --set-upstream-to=origin/remote-branch new-local-branch
git checkout new-local-branch
git pull
You could make use of the Javascript DOM API. In particular, look at the createElement() method.
You could create a re-usable function that will create an image like so...
function show_image(src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
// This next line will just add it to the <body> tag
document.body.appendChild(img);
}
Then you could use it like this...
<button onclick=
"show_image('http://google.com/images/logo.gif',
276,
110,
'Google Logo');">Add Google Logo</button>
good = [x for x in mylist if x in goodvals] bad = [x for x in mylist if x not in goodvals]
is there a more elegant way to do this?
That code is perfectly readable, and extremely clear!
# files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]
IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
images = [f for f in files if f[2].lower() in IMAGE_TYPES]
anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]
Again, this is fine!
There might be slight performance improvements using sets, but it's a trivial difference, and I find the list comprehension far easier to read, and you don't have to worry about the order being messed up, duplicates being removed as so on.
In fact, I may go another step "backward", and just use a simple for loop:
images, anims = [], []
for f in files:
if f.lower() in IMAGE_TYPES:
images.append(f)
else:
anims.append(f)
The a list-comprehension or using set()
is fine until you need to add some other check or another bit of logic - say you want to remove all 0-byte jpeg's, you just add something like..
if f[1] == 0:
continue
I was facing the problem in passing string value to string parameters in Ajax. After so much googling, i have come up with a custom solution as below.
var bar = 'xyz';
var calibri = 'no$libri';
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "http://nakolesah.ru/",
data: '{ foo: \'' + bar + '\', zoo: \'' + calibri + '\'}',
success: function(msg){
alert('wow'+msg);
},
});
Here, bar and calibri are two string variables and you can pass whatever string value to respective string parameters in web method.
You can set a control variable in vars files located in group_vars/
or directly in hosts file like this:
[vagrant:vars]
test_var=true
[location-1]
192.168.33.10 hostname=apollo
[location-2]
192.168.33.20 hostname=zeus
[vagrant:children]
location-1
location-2
And run tasks like this:
- name: "test"
command: "echo {{test_var}}"
when: test_var is defined and test_var
I do get the same information while debugging. Though not while I am checking the stacktrace. Most probably you would have used the optimization flag I think. Check this link - something related.
Try compiling with -g3
remove any optimization flag.
Then it might work.
HTH!
itemdescription
is shorter than 38 chars. Which is why the StringOutOfBoundsException
is being thrown.
Checking .length() > 0
simply makes sure the String
has some not-null value, what you need to do is check that the length is long enough. You could try:
if(itemdescription.length() > 38)
...
I initialised the slider with one of the properties as
variableWidth: true
then i could set the width of the slides to anything i wanted in CSS with:
.slick-slide {
width: 200px;
}
DateTimeFormatter
in Java 8 is immutable and thread-safe alternative to SimpleDateFormat
.
You may not find this in any book or site but I found out that it works pretty well:
ifstream ifs ("filename.txt");
string s;
getline (ifs, s, (char) ifs.eof());
To me, it is better to put the transition codes with the original/minimum selectors than with the :hover or any other additional selectors:
#content #nav a {_x000D_
background-color: #FF0;_x000D_
_x000D_
-webkit-transition: background-color 1000ms linear;_x000D_
-moz-transition: background-color 1000ms linear;_x000D_
-o-transition: background-color 1000ms linear;_x000D_
-ms-transition: background-color 1000ms linear;_x000D_
transition: background-color 1000ms linear;_x000D_
}_x000D_
_x000D_
#content #nav a:hover {_x000D_
background-color: #AD310B;_x000D_
}
_x000D_
<div id="content">_x000D_
<div id="nav">_x000D_
<a href="#link1">Link 1</a>_x000D_
</div>_x000D_
</div>
_x000D_
This wrapper method will help :
private static JSONObject merge(JSONObject... jsonObjects) throws JSONException {
JSONObject jsonObject = new JSONObject();
for(JSONObject temp : jsonObjects){
Iterator<String> keys = temp.keys();
while(keys.hasNext()){
String key = keys.next();
jsonObject.put(key, temp.get(key));
}
}
return jsonObject;
}
Use this. Beware of i's larger than 9, as these will require a char array with more than 2 elements to avoid a buffer overrun.
char c[2];
int i=1;
sprintf(c, "%d", i);
In Rails 3 and newer:
Rails.root
which returns a Pathname
object. If you want a string you have to add .to_s
. If you want another path in your Rails app, you can use join
like this:
Rails.root.join('app', 'assets', 'images', 'logo.png')
In Rails 2 you can use the RAILS_ROOT
constant, which is a string.
If you used read.table()
(or one of it's ilk, e.g. read.csv()
) then the easy fix is to change the call to:
read.table(file = "foo.txt", row.names = 1, ....)
where ....
are the other arguments you needed/used. The row.names
argument takes the column number of the data file from which to take the row names. It need not be the first column. See ?read.table
for details/info.
If you already have the data in R and can't be bothered to re-read it, or it came from another route, just set the rownames
attribute and remove the first variable from the object (assuming obj
is your object)
rownames(obj) <- obj[, 1] ## set rownames
obj <- obj[, -1] ## remove the first variable
To Add a Function To a new Button on your Form: (and avoid using macro to call function)
After you created your Function (Function MyFunctionName()) and you are in form design view:
Add a new button (I don't think you can reassign an old button - not sure though).
When the button Wizard window opens up click Cancel.
Go to the Button properties Event Tab - On Click - field.
At that fields drop down menu select: Event Procedure.
Now click on button beside drop down menu that has ... in it and you will be taken to a new Private Sub in the forms Visual Basic window.
In that Private Sub type: Call MyFunctionName
It should look something like this:
Private Sub Command23_Click()
Call MyFunctionName
End Sub
Then just save it.
When working on a supercomputer, I received this error when I ran:
module load python/3.4.0
screen
python
To resolve the error, I simply needed to reload the module in the screen terminal:
module load python/3.4.0
python
A small static custom method in a Util
class would help:
public static int getIndex(Set<? extends Object> set, Object value) {
int result = 0;
for (Object entry:set) {
if (entry.equals(value)) return result;
result++;
}
return -1;
}
If you need/want one class that is a Set
and offers a getIndex()
method, I strongly suggest to implement a new Set
and use the decorator pattern:
public class IndexAwareSet<T> implements Set {
private Set<T> set;
public IndexAwareSet(Set<T> set) {
this.set = set;
}
// ... implement all methods from Set and delegate to the internal Set
public int getIndex(T entry) {
int result = 0;
for (T entry:set) {
if (entry.equals(value)) return result;
result++;
}
return -1;
}
}
Easiest method: Alt
+Enter
on
private static final long serialVersionUID = ;
IntelliJ will underline the space after the =
. put your cursor on it and hit alt
+Enter
(Option
+Enter
on Mac). You'll get a popover that says "Randomly Change serialVersionUID Initializer". Just hit enter, and it'll populate that space with a random long.
To get a local timestamp using datetime library, Python 3.x
#wanted format: year-month-day hour:minute:seconds
from datetime import datetime
# get time now
dt = datetime.now()
# format it to a string
timeStamp = dt.strftime('%Y-%m-%d %H:%M:%S')
# print it to screen
print(timeStamp)
You separate the values you want to return by commas:
def get_name():
# you code
return first_name, last_name
The commas indicate it's a tuple, so you could wrap your values by parentheses:
return (first_name, last_name)
Then when you call the function you a) save all values to one variable as a tuple, or b) separate your variable names by commas
name = get_name() # this is a tuple
first_name, last_name = get_name()
(first_name, last_name) = get_name() # You can put parentheses, but I find it ugly
result = []
# Make a set of your "types":
input_set = set([tpl[1] for tpl in input])
>>> set(['ETH', 'KAT', 'NOT'])
# Iterate over the input_set
for type_ in input_set:
# a dict to gather things:
D = {}
# filter all tuples from your input with the same type as type_
tuples = filter(lambda tpl: tpl[1] == type_, input)
# write them in the D:
D["type"] = type_
D["itmes"] = [tpl[0] for tpl in tuples]
# append D to results:
result.append(D)
result
>>> [{'itmes': ['9085267', '11788544'], 'type': 'NOT'}, {'itmes': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}, {'itmes': ['11013331', '9843236'], 'type': 'KAT'}]
A little late, but I use a _is_running
variable to tell the thread when I want to close. It's easy to use, just implement a stop() inside your thread class.
def stop(self):
self._is_running = False
And in run()
just loop on while(self._is_running)
from datetime import timedelta
try:
next = (x.replace(day=1) + timedelta(days=31)).replace(day=x.day)
except ValueError: # January 31 will return last day of February.
next = (x + timedelta(days=31)).replace(day=1) - timedelta(days=1)
If you simply want the first day of the next month:
next = (x.replace(day=1) + timedelta(days=31)).replace(day=1)
This can happen when you run python script.py
vs just python
to enter the interactive shell, among other reasons for readline being disabled.
Try:
import readline
The definition for DTO can be found on Martin Fowler's site. DTOs are used to transfer parameters to methods and as return types. A lot of people use those in the UI, but others inflate domain objects from them.
Avoid Eclipse for C/C++ development for now on Mac OS X v10.6 (Snow Leopard). There are serious problems which make debugging problematic or nearly impossible on it currently due to GDB incompatibility problems and the like. See: Trouble debugging C++ using Eclipse Galileo on Mac.
If you dont want to merge the changes and still want to update your local then run:
git reset --hard HEAD
This will reset your local with HEAD and then pull your remote using git pull.
If you've already committed your merge locally (but haven't pushed to remote yet), and want to revert it as well:
git reset --hard HEAD~1
please see below answer.
Custom_CameraActivity.java
public class Custom_CameraActivity extends Activity {
private Camera mCamera;
private CameraPreview mCameraPreview;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mCamera = getCameraInstance();
mCameraPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mCameraPreview);
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
}
});
}
/**
* Helper method to access the camera returns null if it cannot get the
* camera or does not exist
*
* @return
*/
private Camera getCameraInstance() {
Camera camera = null;
try {
camera = Camera.open();
} catch (Exception e) {
// cannot get camera or does not exist
}
return camera;
}
PictureCallback mPicture = new PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
};
private static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
return mediaFile;
}
}
CameraPreview.java
public class CameraPreview extends SurfaceView implements
SurfaceHolder.Callback {
private SurfaceHolder mSurfaceHolder;
private Camera mCamera;
// Constructor that obtains context and camera
@SuppressWarnings("deprecation")
public CameraPreview(Context context, Camera camera) {
super(context);
this.mCamera = camera;
this.mSurfaceHolder = this.getHolder();
this.mSurfaceHolder.addCallback(this);
this.mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (IOException e) {
// left blank for now
}
}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
mCamera.stopPreview();
mCamera.release();
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
int width, int height) {
// start preview with new settings
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (Exception e) {
// intentionally left blank for a test
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<FrameLayout
android:id="@+id/camera_preview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" />
<Button
android:id="@+id/button_capture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Capture" />
</LinearLayout>
Add Below Lines to your androidmanifest.xml file
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You could avoid hardcoding the full path by setting a JS variable in the header of your template, before wp_head()
is called, holding the template URL. Like:
<script type="text/javascript">
var templateUrl = '<?= get_bloginfo("template_url"); ?>';
</script>
And use that variable to set the background (I realize you know how to do this, I only include these details in case they helps others):
Reset.style.background = " url('"+templateUrl+"/images/searchfield_clear.png') ";
If you are using plain LINQ-to-objects and don't want to take a dependency on an external library it is not hard to achieve what you want.
The OrderBy()
clause accepts a Func<TSource, TKey>
that gets a sort key from a source element. You can define the function outside the OrderBy()
clause:
Func<Item, Object> orderByFunc = null;
You can then assign it to different values depending on the sort criteria:
if (sortOrder == SortOrder.SortByName)
orderByFunc = item => item.Name;
else if (sortOrder == SortOrder.SortByRank)
orderByFunc = item => item.Rank;
Then you can sort:
var sortedItems = items.OrderBy(orderByFunc);
This example assumes that the source type is Item
that have properties Name
and Rank
.
Note that in this example TKey
is Object
to not constrain the property types that can be sorted on. If the func returns a value type (like Int32
) it will get boxed when sorting and that is somewhat inefficient. If you can constrain TKey
to a specific value type you can work around this problem.
But this is obviously performing a 'string' comparison
No. The string will be automatically cast into a DATETIME value.
See 11.2. Type Conversion in Expression Evaluation.
When an operator is used with operands of different types, type conversion occurs to make the operands compatible. Some conversions occur implicitly. For example, MySQL automatically converts numbers to strings as necessary, and vice versa.
As for a tool I started using, I suggest firecamp Its like Postman, but it also supports websockets and socket.io.
There is a concept of a working directory
.
This directory is represented by a .
(dot).
In relative paths, everything else is relative to it.
Simply put the .
(the working directory) is where you run your program.
In some cases the working directory can be changed but in general this is
what the dot represents. I think this is C:\JavaForTesters\
in your case.
So test\..\test.txt
means: the sub-directory test
in my working directory, then one level up, then the
file test.txt
. This is basically the same as just test.txt
.
For more details check here.
http://docs.oracle.com/javase/7/docs/api/java/io/File.html
http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html
This is in the case if first answer does not work The latest version of git does not require to set proxy it directly uses system proxy settings .so just do these
unset HTTP_PROXY
unset HTTPS_PROXY
in some systems you may also have to do
unset http_proxy
unset https_proxy
if you want to permanantly remove proxy then
sudo gsettings set org.gnome.system.proxy mode 'none'
Like Robert Nishihara mentioned, Apache Arrow makes this easy, specifically with the Plasma in-memory object store, which is what Ray is built on.
I made brain-plasma specifically for this reason - fast loading and reloading of big objects in a Flask app. It's a shared-memory object namespace for Apache Arrow-serializable objects, including pickle
'd bytestrings generated by pickle.dumps(...)
.
The key difference with Apache Ray and Plasma is that it keeps track of object IDs for you. Any processes or threads or programs that are running on locally can share the variables' values by calling the name from any Brain
object.
$ pip install brain-plasma
$ plasma_store -m 10000000 -s /tmp/plasma
from brain_plasma import Brain
brain = Brain(path='/tmp/plasma/)
brain['a'] = [1]*10000
brain['a']
# >>> [1,1,1,1,...]
I realize this question was asked a long time ago, but I came here looking for answers and wasn't satisfied with anything I could find. I finally found the answer here:
https://www.tutorialsteacher.com/mvc/htmlhelper-dropdownlist-dropdownlistfor
To get the results from the form, use the FormCollection and then pull each individual value out by it's model name thus:
yourRecord.FieldName = Request.Form["FieldNameInModel"];
As far as I could tell it makes absolutely no difference what argument name you give to the FormCollection - use Request.Form["NameFromModel"] to retrieve it.
No, I did not dig down to see how th4e magic works under the covers. I just know it works...
I hope this helps somebody avoid the hours I spent trying different approaches before I got it working.
This is not jQuery, but it works for me. Taken from this site.
function addCommas(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
You can find the list
of duplicate
names using the following aggregate
pipeline:
Group
all the records having similar name
.Match
those groups
having records greater than 1
.group
again to project
all the duplicate names as an array
.The Code:
db.collection.aggregate([
{$group:{"_id":"$name","name":{$first:"$name"},"count":{$sum:1}}},
{$match:{"count":{$gt:1}}},
{$project:{"name":1,"_id":0}},
{$group:{"_id":null,"duplicateNames":{$push:"$name"}}},
{$project:{"_id":0,"duplicateNames":1}}
])
o/p:
{ "duplicateNames" : [ "ksqn291", "ksqn29123213Test" ] }
In case you want to sort dates with descending order the minus sign doesn't work with Dates.
out <- DF[rev(order(as.Date(DF$end))),]
However you can have the same effect with a general purpose function: rev(). Therefore, you mix rev and order like:
#init data
DF <- data.frame(ID=c('ID3', 'ID2','ID1'), end=c('4/1/09 12:00', '6/1/10 14:20', '1/1/11 11:10')
#change order
out <- DF[rev(order(as.Date(DF$end))),]
Hope it helped.
If you just want the date portion (e.g. 2017-06-27), and you want it to work regardless of time zone and also in Arabic, here is code I wrote:
function isoDate(date) {
if (!date) {
return null
}
date = moment(date).toDate()
// don't call toISOString because it takes the time zone into
// account which we don't want. Also don't call .format() because it
// returns Arabic instead of English
var month = 1 + date.getMonth()
if (month < 10) {
month = '0' + month
}
var day = date.getDate()
if (day < 10) {
day = '0' + day
}
return date.getFullYear() + '-' + month + '-' + day
}
Another solution that it is similar to those already exposed here is this one. Just before the closing body tag place this html:
<div id="resultLoading" style="display: none; width: 100%; height: 100%; position: fixed; z-index: 10000; top: 0px; left: 0px; right: 0px; bottom: 0px; margin: auto;">
<div style="width: 340px; height: 200px; text-align: center; position: fixed; top: 0px; left: 0px; right: 0px; bottom: 0px; margin: auto; z-index: 10; color: rgb(255, 255, 255);">
<div class="uil-default-css">
<img src="/images/loading-animation1.gif" style="max-width: 150px; max-height: 150px; display: block; margin-left: auto; margin-right: auto;" />
</div>
<div class="loader-text" style="display: block; font-size: 18px; font-weight: 300;"> </div>
</div>
<div style="background: rgb(0, 0, 0); opacity: 0.6; width: 100%; height: 100%; position: absolute; top: 0px;"></div>
</div>
Finally, replace .loader-text element's
content on the fly on every navigation event and turn on the #resultloading
div, note that it is initially hidden.
var showLoader = function (text) {
$('#resultLoading').show();
$('#resultLoading').find('.loader-text').html(text);
};
jQuery(document).ready(function () {
jQuery(window).on("beforeunload ", function () {
showLoader('Loading, please wait...');
});
});
This can be applied to any html based project with jQuery where you don't know which pages of your administration area will take too long to finish loading.
The gif image is 176x176px but you can use any transparent gif animation, please take into account that the image size is not important as it will be maxed to 150x150px.
Also, the function showLoader can be called on an element's click to perform an action that will further redirect the page, that is why it is provided ad an individual function. i hope this can also help anyone.
Try this
if (location.protocol !== 'https:') {
location.replace(`https:${location.href.substring(location.protocol.length)}`);
}
location.href = blah
adds this redirect to the browser history. If the user hits the back button, they will be redirected back to the the same page. It is better to use location.replace
as it doesn't add this redirect to the browser history.
Please disable js bundling and increase memory. That should fix it. I fixed mine by disabling js bundling.
Thanks
from os import system, remove
from uuid import uuid4
def bash_(shell_command: str) -> tuple:
"""
:param shell_command: your shell command
:return: ( 1 | 0, stdout)
"""
logfile: str = '/tmp/%s' % uuid4().hex
err: int = system('%s &> %s' % (shell_command, logfile))
out: str = open(logfile, 'r').read()
remove(logfile)
return err, out
# Example:
print(bash_('cat /usr/bin/vi | wc -l'))
>>> (0, '3296\n')```
What about the following?
print testlist.index(element)
If you are not sure whether the element to look for is actually in the list, you can add a preliminary check, like
if element in testlist:
print testlist.index(element)
or
print(testlist.index(element) if element in testlist else None)
or the "pythonic way", which I don't like so much because code is less clear, but sometimes is more efficient,
try:
print testlist.index(element)
except ValueError:
pass
No. Actually it's the "same" as
char array[] = {'O', 'n', 'e', ..... 'i','c','\0');
Every character is a separate element, with an additional \0
character as a string terminator.
I quoted "same", because there are some differences between char * array
and char array[]
.
If you want to read more, take a look at C: differences between char pointer and array
Adding the actual code here for future reference
So, there are 3 steps, and therefore 3 SQL statements:
Step 1: Move the non duplicates (unique tuples) into a temporary table
CREATE TABLE new_table as
SELECT * FROM old_table WHERE 1 GROUP BY [column to remove duplicates by];
Step 2: delete the old table (or rename it) We no longer need the table with all the duplicate entries, so drop it!
DROP TABLE old_table;
Step 3: rename the new_table to the name of the old_table
RENAME TABLE new_table TO old_table;
And of course, don't forget to fix your buggy code to stop inserting duplicates!
new TextBox
{
Text = text,
TextAlignment = TextAlignment.Center,
TextWrapping = TextWrapping.Wrap,
IsReadOnly = true,
Background = Brushes.Transparent,
BorderThickness = new Thickness()
{
Top = 0,
Bottom = 0,
Left = 0,
Right = 0
}
};
Copy and paste this format yyyy-mm-dd hh:MM:ss in format cells by clicking customs category under Type
Some tips:
About your questions:
An inputMethod is basically an Android Service
, so yes, you can do HTTP and all the stuff you can do in a Service
.
You can open Activities
and dialogs from the InputMethod
. Once again, it's just a Service
.
I've been developing an IME, so ask again if you run into an issue.
Here is a code-example of how you can do it:
Intent intent = getIntent(getApplicationContext(), A.class)
This will make sure that you only have one instance of an activity on the stack.
private static Intent getIntent(Context context, Class<?> cls) {
Intent intent = new Intent(context, cls);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
return intent;
}
you can use window.setInterval and time must to be define in miliseconds, in below case the function will call after every single second (1000 miliseconds)
<script>
var time = 3670;
window.setInterval(function(){
// Time calculations for days, hours, minutes and seconds
var h = Math.floor(time / 3600);
var m = Math.floor(time % 3600 / 60);
var s = Math.floor(time % 3600 % 60);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = h + "h "
+ m + "m " + s + "s ";
// If the count down is finished, write some text
if (time < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
time--;
}, 1000);
</script>
Load the multicol package, like this \usepackage{multicol}
. Then use:
\begin{multicols}{2}
Column 1
\columnbreak
Column 2
\end{multicols}
If you omit the \columnbreak
, the columns will balance automatically.
CSS can do that with background-size: cover;
But to be more detailed and support more browsers...
Use aspect ratio like this:
aspectRatio = $bg.width() / $bg.height();
I ? visualizations, and here I've created a one to show the basic differences between structs and classes.
For more information look below:
SomeVal=ActiveWorkbook.worksheets("Sheet2").cells(aRow,aCol).Value
did not work. However the following code only worked for me.
SomeVal = ThisWorkbook.Sheets(2).cells(aRow,aCol).Value
vagrant init laravel/homestead
and then
vagrant up
Was what worked for me.
Why are you changing android os inbuilt theme.
As per your activity Require You have to implements this way
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
as per @arianoo
says you have to used this feature.
I think this is better way to hide titlebar theme.
Simple Upload Form
<script>_x000D_
//form Submit_x000D_
$("form").submit(function(evt){ _x000D_
evt.preventDefault();_x000D_
var formData = new FormData($(this)[0]);_x000D_
$.ajax({_x000D_
url: 'fileUpload',_x000D_
type: 'POST',_x000D_
data: formData,_x000D_
async: false,_x000D_
cache: false,_x000D_
contentType: false,_x000D_
enctype: 'multipart/form-data',_x000D_
processData: false,_x000D_
success: function (response) {_x000D_
alert(response);_x000D_
}_x000D_
});_x000D_
return false;_x000D_
});_x000D_
</script>
_x000D_
<!--Upload Form-->_x000D_
<form>_x000D_
<table>_x000D_
<tr>_x000D_
<td colspan="2">File Upload</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<th>Select File </th>_x000D_
<td><input id="csv" name="csv" type="file" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td colspan="2">_x000D_
<input type="submit" value="submit"/> _x000D_
</td>_x000D_
</tr>_x000D_
</table>_x000D_
</form>
_x000D_
Just for the sake of academic interest, I did it this way...
(dt.replace(month = dt.month % 12 +1, day = 1)-timedelta(days=1)).day
If you want to keep it simple, this should suffice:
function parseIsoDatetime(dtstr) {
var dt = dtstr.split(/[: T-]/).map(parseFloat);
return new Date(dt[0], dt[1] - 1, dt[2], dt[3] || 0, dt[4] || 0, dt[5] || 0, 0);
}
note parseFloat is must, parseInt doesn't always work. Map requires IE9 or later.
Works for formats:
Not valid for timezones, see other answers about those.
<p:ajax listener="#{my.handleChange}" update="id of component that need to be rerender after change" process="@this" />
import javax.faces.component.UIOutput;
import javax.faces.event.AjaxBehaviorEvent;
public void handleChange(AjaxBehaviorEvent vce){
String name= (String) ((UIOutput) vce.getSource()).getValue();
}
Several answers have pointed at uintptr_t
and #include <stdint.h>
as 'the' solution. That is, I suggest, part of the answer, but not the whole answer. You also need to look at where the function is called with the message ID of FOO.
Consider this code and compilation:
$ cat kk.c
#include <stdio.h>
static void function(int n, void *p)
{
unsigned long z = *(unsigned long *)p;
printf("%d - %lu\n", n, z);
}
int main(void)
{
function(1, 2);
return(0);
}
$ rmk kk
gcc -m64 -g -O -std=c99 -pedantic -Wall -Wshadow -Wpointer-arith \
-Wcast-qual -Wstrict-prototypes -Wmissing-prototypes \
-D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE kk.c -o kk
kk.c: In function 'main':
kk.c:10: warning: passing argument 2 of 'func' makes pointer from integer without a cast
$
You will observe that there is a problem at the calling location (in main()
) — converting an integer to a pointer without a cast. You are going to need to analyze your function()
in all its usages to see how values are passed to it. The code inside my function()
would work if the calls were written:
unsigned long i = 0x2341;
function(1, &i);
Since yours are probably written differently, you need to review the points where the function is called to ensure that it makes sense to use the value as shown. Don't forget, you may be finding a latent bug.
Also, if you are going to format the value of the void *
parameter (as converted), look carefully at the <inttypes.h>
header (instead of stdint.h
— inttypes.h
provides the services of stdint.h
, which is unusual, but the C99 standard says [t]he header <inttypes.h>
includes the header <stdint.h>
and extends it with
additional facilities provided by hosted implementations) and use the PRIxxx macros in your format strings.
Also, my comments are strictly applicable to C rather than C++, but your code is in the subset of C++ that is portable between C and C++. The chances are fair to good that my comments apply.
An alternative way to do it is:
var div = document.getElementById('myDiv');
while(div.firstChild)
div.removeChild(div.firstChild);
However, using document.getElementById('myDiv').innerHTML = "";
is faster.
See: Benchmark test
N.B.
Both methods preserve the div.
You need to have the System.Linq
namespace included in your view since Select is an extension method. You have a couple of options on how to do this:
Add @using System.Linq
to the top of your cshtml file.
If you find that you will be using this namespace often in many of your views, you can do this for all views by modifying the web.config inside of your Views folder (not the one at the root). You should see a pages/namespace XML element, create a new add
child that adds System.Linq. Here is an example:
<configuration>
<system.web.webPages.razor>
<pages>
<namespaces>
<add namespace="System.Linq" />
</namespaces>
</pages>
</system.web.webPages.razor>
</configuration>
I found out that it also happens if you uninstalled some packages from your react-native project and there is still packages in your build gradle dependencies in the bottom of page like:
{
project(':react-native-sound-player')
}
You can add an alias
or a function
in your startup script file. Usually this is .bashrc
, .bash_login
or .profile
file in your home directory.
Since these files are hidden you will have to do an ls -a
to list them. If you don't have one you can create one.
If I remember correctly, when I had bought my Mac, the .bash_login
file wasn't there. I had to create it for myself so that I could put prompt info
, alias
, functions
, etc. in it.
Here are the steps if you would like to create one:
cd ~/
to go to your home foldertouch .bash_profile
to create your new file..bash_profile
with your favorite editor (or you can just type open -e .bash_profile
to open it in TextEdit.. .bash_profile
to reload .bash_profile
and update any alias you add.The following meta tag, placed between inside the head, will tell the browser to redirect:
<meta http-equiv="Refresh" content="seconds; url=URL">
Replace seconds with the number of seconds to wait before it redirects, and replace URL with the URL you want it to redirect to.
Alternatively, you can redirect with JavaScript. Place this inside of a script tag anywhere on the page:
window.location = "URL"
This was previously asked on R-Help, so that's worth reviewing.
One suggestion there was to use readChar()
and then do string manipulation on the result with strsplit()
and substr()
. You can see the logic involved in readChar is much less than read.table.
I don't know if memory is an issue here, but you might also want to take a look at the HadoopStreaming package. This uses Hadoop, which is a MapReduce framework designed for dealing with large data sets. For this, you would use the hsTableReader function. This is an example (but it has a learning curve to learn Hadoop):
str <- "key1\t3.9\nkey1\t8.9\nkey1\t1.2\nkey1\t3.9\nkey1\t8.9\nkey1\t1.2\nkey2\t9.9\nkey2\"
cat(str)
cols = list(key='',val=0)
con <- textConnection(str, open = "r")
hsTableReader(con,cols,chunkSize=6,FUN=print,ignoreKey=TRUE)
close(con)
The basic idea here is to break the data import into chunks. You could even go so far as to use one of the parallel frameworks (e.g. snow) and run the data import in parallel by segmenting the file, but most likely for large data sets that won't help since you will run into memory constraints, which is why map-reduce is a better approach.
You should just scope your * selector to the specific areas that need the reset. .legacy * { }
, etc.
Thought I would give Sugar.js a mention. It has a truncate method that is pretty smart.
From the documentation:
Truncates a string. Unless split is true, truncate will not split words up, and instead discard the word where the truncation occurred.
Example:
'just sittin on the dock of the bay'.truncate(20)
Output:
just sitting on...
As of 2011 you can use Apache Commons StringUtils.stripAccents(input) (since 3.0):
String input = StringUtils.stripAccents("Thïs iš â funky Štring");
System.out.println(input);
// Prints "This is a funky String"
Note:
The accepted answer (Erick Robertson's) doesn't work for Ø or L. Apache Commons 3.5 doesn't work for Ø either, but it does work for L. After reading the Wikipedia article for Ø, I'm not sure it should be replaced with "O": it's a separate letter in Norwegian and Danish, alphabetized after "z". It's a good example of the limitations of the "strip accents" approach.
"Just set the MaxSelectionCount
to 1 so that users cannot select more than one day. Then in the SelectionRange.Start.ToString()
. There is nothing available to show the selection of only one day." - Justin Etheredge
From here.
Try this it works for me
public class TestClass extends Fragment {
private ImageView imageView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.testclassfragment, container, false);
findViews(view);
return view;
}
private void findViews(View view) {
imageView = (ImageView) view.findViewById(R.id.my_image);
}
}
Bruno's answer was the correct one in the end. This is most easily controlled by the https.protocols
system property. This is how you are able to control what the factory method returns. Set to "TLSv1" for example.
You'll have problems creating lists without commas. It shouldn't be too hard to transform your data so that it uses commas as separating character.
Once you have commas in there, it's a relatively simple list creation operations:
array1 = [1,2,3]
array2 = [4,5,6]
array3 = [array1, array2]
array4 = [7,8,9]
array5 = [10,11,12]
array3 = [array3, [array4, array5]]
When testing we get:
print(array3)
[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]
And if we test with indexing it works correctly reading the matrix as made up of 2 rows and 2 columns:
array3[0][1]
[4, 5, 6]
array3[1][1]
[10, 11, 12]
Hope that helps.
As most people have said, both ways work indeed, but I think only the first one should. Being semantically strict, the label does not "contain" the input. In my opinion, containment (parent/child) relationship in the markup structure should reflect containment in the visual output. i.e., an element surrounding another one in the markup should be drawn around that one in the browser. According to this, the label should be the input's sibling, not it's parent. So option number two is arbitrary and confusing. Everyone that has read the Zen of Python will probably agree (Flat is better than nested, Sparse is better than dense, There should be one-- and preferably only one --obvious way to do it...).
Because of decisions like that from W3C and major browser vendors (allowing "whichever way you prefer to do it", instead of "do it the right way") is that the web is so messed up today and we developers have to deal with tangled and so diverse legacy code.
e.g.:
CREATE
, ALTER
, DROP
, TRUNCATE
, COMMIT
, etc.DML statement are affect on table. So that is the basic operations we perform in a table.
SELECT
, INSERT
, UPDATE
, etc.Below Commands are used in DML:
INSERT
, UPDATE
, SELECT
, DELETE
, etc.var top = ($('#bottom').position().top) + ($('#bottom').height());
You are not copying the map, but the reference to the map. Your delete
thus modifies the values in both your original map and the super map. To copy a map, you have to use a for
loop like this:
for k,v := range originalMap {
newMap[k] = v
}
Here's an example from the now-retired SO documentation:
// Create the original map
originalMap := make(map[string]int)
originalMap["one"] = 1
originalMap["two"] = 2
// Create the target map
targetMap := make(map[string]int)
// Copy from the original map to the target map
for key, value := range originalMap {
targetMap[key] = value
}
Excerpted from Maps - Copy a Map. The original author was JepZ. Attribution details can be found on the contributor page. The source is licenced under CC BY-SA 3.0 and may be found in the Documentation archive. Reference topic ID: 732 and example ID: 9834.
Other answers deal with the technical aspect of the border-opacity issue, while I'd like to present a hack(pure CSS and HTML only). Basically create a container div, having a border div and then the content div.
<div class="container">
<div class="border-box"></div>
<div class="content-box"></div>
</div>
And then the CSS:(set content border to none, take care of positioning such that border thickness is accounted for)
.container {
width: 20vw;
height: 20vw;
position: relative;
}
.border-box {
width: 100%;
height: 100%;
border: 5px solid black;
position: absolute;
opacity: 0.5;
}
.content-box {
width: 100%;
height: 100%;
border: none;
background: green;
top: 5px;
left: 5px;
position: absolute;
}
There is a public domain TimeZone library for .NET. Really useful. It will answer your needs.
Solving the general-case timezone problem is harder than you think.
unable to verify the first certificate
The certificate chain is incomplete.
It means that the webserver you are connecting to is misconfigured and did not include the intermediate certificate in the certificate chain it sent to you.
It most likely looks as follows:
Intermediate certificate should be installed on the server, along with the server certificate.
Root certificates are embedded into the software applications, browsers and operating systems.
The application serving the certificate has to send the complete chain, this means the server certificate itself and all the intermediates. The root certificate is supposed to be known by the client.
Go to https://incomplete-chain.badssl.com using your browser.
It doesn't show any error (padlock in the address bar is green).
It's because browsers tend to complete the chain if it’s not sent from the server.
Now, connect to https://incomplete-chain.badssl.com using Node:
// index.js
const axios = require('axios');
axios.get('https://incomplete-chain.badssl.com')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Logs: "Error: unable to verify the first certificate".
You need to complete the certificate chain yourself.
To do that:
1: You need to get the missing intermediate certificate in .pem
format, then
2a: extend Node’s built-in certificate store using NODE_EXTRA_CA_CERTS
,
2b: or pass your own certificate bundle (intermediates and root) using ca
option.
Using openssl
(comes with Git for Windows).
Save the remote server's certificate details:
openssl s_client -connect incomplete-chain.badssl.com:443 -servername incomplete-chain.badssl.com | tee logcertfile
We're looking for the issuer (the intermediate certificate is the issuer / signer of the server certificate):
openssl x509 -in logcertfile -noout -text | grep -i "issuer"
It should give you URI of the signing certificate. Download it:
curl --output intermediate.crt http://cacerts.digicert.com/DigiCertSHA2SecureServerCA.crt
Finally, convert it to .pem
:
openssl x509 -inform DER -in intermediate.crt -out intermediate.pem -text
I'm using cross-env to set environment variables in package.json
file:
"start": "cross-env NODE_EXTRA_CA_CERTS=\"C:\\Users\\USERNAME\\Desktop\\ssl-connect\\intermediate.pem\" node index.js"
ca
optionThis option is going to overwrite the Node's built-in root CAs.
That's why we need to create our own root CA. Use ssl-root-cas.
Then, create a custom https
agent configured with our certificate bundle (root and intermediate). Pass this agent to axios
when making request.
// index.js
const axios = require('axios');
const path = require('path');
const https = require('https');
const rootCas = require('ssl-root-cas').create();
rootCas.addFile(path.resolve(__dirname, 'intermediate.pem'));
const httpsAgent = new https.Agent({ca: rootCas});
axios.get('https://incomplete-chain.badssl.com', { httpsAgent })
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Instead of creating a custom https
agent and passing it to axios
, you can place the certifcates on the https
global agent:
// Applies to ALL requests (whether using https directly or the request module)
https.globalAgent.options.ca = rootCas;
You could achieve that simply by wrapping the image by a <div>
and adding overflow: hidden
to that element:
<div class="img-wrapper">
<img src="..." />
</div>
.img-wrapper {
display: inline-block; /* change the default display type to inline-block */
overflow: hidden; /* hide the overflow */
}
Also it's worth noting that <img>
element (like the other inline elements) sits on its baseline by default. And there would be a 4~5px
gap at the bottom of the image.
That vertical gap belongs to the reserved space of descenders like: g j p q y. You could fix the alignment issue by adding vertical-align
property to the image with a value other than baseline
.
Additionally for a better user experience, you could add transition
to the images.
Thus we'll end up with the following:
.img-wrapper img {
transition: all .2s ease;
vertical-align: middle;
}
As Christian's answer with assign()
shows, there is a way to assign in the global environment. A simpler, shorter (but not better ... stick with assign) way is to use the <<-
operator, ie
a <<- "new"
inside the function.
The usual method when not using float
s is to use display: inline-block
: http://www.jsfiddle.net/zygnz/1/
.container div {
display: inline-block;
}
Do note its limitations though: There is a additional space after the first bloc - this is because the two blocks are now essentially inline
elements, like a
and em
, so whitespace between the two counts. This could break your layout and/or not look nice, and I'd prefer not to strip out all whitespaces between characters for the sake of this working.
Floats are also more flexible, in most cases.
Another alternative altogether is to use the printf function.
printf -v str 'hello'
Moreover, this construct, combined with the use of single quotes where appropriate, helps to avoid the multi-escape problems of subshells and other forms of interpolative quoting.
If you need to programmatically and asynchronously load a CSS link:
// https://www.filamentgroup.com/lab/load-css-simpler/
function loadCSS(href, position) {
const link = document.createElement('link');
link.media = 'print';
link.rel = 'stylesheet';
link.href = href;
link.onload = () => { link.media = 'all'; };
position.parentNode.insertBefore(link, position);
}
After lots of investigation in the same issue I found this one to be extremely convenient: https://github.com/flagbug/FlagFtp
For example (try doing this with the standard .net "library" - it will be a real pain) -> Recursively retreving all files on the FTP server:
public IEnumerable<FtpFileInfo> GetFiles(string server, string user, string password)
{
var credentials = new NetworkCredential(user, password);
var baseUri = new Uri("ftp://" + server + "/");
var files = new List<FtpFileInfo>();
AddFilesFromSubdirectory(files, baseUri, credentials);
return files;
}
private void AddFilesFromSubdirectory(List<FtpFileInfo> files, Uri uri, NetworkCredential credentials)
{
var client = new FtpClient(credentials);
var lookedUpFiles = client.GetFiles(uri);
files.AddRange(lookedUpFiles);
foreach (var subDirectory in client.GetDirectories(uri))
{
AddFilesFromSubdirectory(files, subDirectory.Uri, credentials);
}
}
You should use:
URLEncoder.encode("NAME", "UTF-8");
Yes, to some degree as detailed here.
The approach I've used (pre-2008) is to do the conversion in the .NET business logic before inserting into the DB.
I had same issue for which I came here. With some trials, I figured out for copying multiple pages of chrome data as in the question I zoomed out till I got all the data in one page, that is, without scroll, with very small font size. Now copy and paste that in excel which copies all the records and in normal font. This is good for few pages of data I think.
Suppose I have numbers 1 to 10 in cells A2:A11
with my autofilter in A1
. I now filter to only show numbers greater then 5 (i.e. 6, 7, 8, 9, 10).
This code will only print visible cells:
Sub SpecialLoop()
Dim cl As Range, rng As Range
Set rng = Range("A2:A11")
For Each cl In rng
If cl.EntireRow.Hidden = False Then //Use Hidden property to check if filtered or not
Debug.Print cl
End If
Next
End Sub
Perhaps there is a better way with SpecialCells
but the above worked for me in Excel 2003.
EDIT
Just found a better way with SpecialCells
:
Sub SpecialLoop()
Dim cl As Range, rng As Range
Set rng = Range("A2:A11")
For Each cl In rng.SpecialCells(xlCellTypeVisible)
Debug.Print cl
Next cl
End Sub
I had the same message with a totally different cause: the wsock32.dll
was not found. The ::socket(PF_INET, SOCK_STREAM, 0);
call kept returning an INVALID_SOCKET
but the reason was that the winsock dll was not loaded.
In the end I launched Sysinternals' process monitor and noticed that it searched for the dll 'everywhere' but didn't find it.
Silent failures are great!
In Visual Studio the default stack size is 1 MB i think, so with a recursion depth of 10,000 each stack frame can be at most ~100 bytes which should be sufficient for a DFS algorithm.
Most compilers including Visual Studio let you specify the stack size. On some (all?) linux flavours the stack size isn't part of the executable but an environment variable in the OS. You can then check the stack size with ulimit -s
and set it to a new value with for example ulimit -s 16384
.
Here's a link with default stack sizes for gcc.
DFS without recursion:
std::stack<Node> dfs;
dfs.push(start);
do {
Node top = dfs.top();
if (top is what we are looking for) {
break;
}
dfs.pop();
for (outgoing nodes from top) {
dfs.push(outgoing node);
}
} while (!dfs.empty())
Try this:
Python Cryptography Toolkit (pycrypto) is required
$ pip install pycrypto
Code:
from Crypto.Cipher import AES
from base64 import b64encode, b64decode
class Crypt:
def __init__(self, salt='SlTKeYOpHygTYkP3'):
self.salt = salt.encode('utf8')
self.enc_dec_method = 'utf-8'
def encrypt(self, str_to_enc, str_key):
try:
aes_obj = AES.new(str_key, AES.MODE_CFB, self.salt)
hx_enc = aes_obj.encrypt(str_to_enc.encode('utf8'))
mret = b64encode(hx_enc).decode(self.enc_dec_method)
return mret
except ValueError as value_error:
if value_error.args[0] == 'IV must be 16 bytes long':
raise ValueError('Encryption Error: SALT must be 16 characters long')
elif value_error.args[0] == 'AES key must be either 16, 24, or 32 bytes long':
raise ValueError('Encryption Error: Encryption key must be either 16, 24, or 32 characters long')
else:
raise ValueError(value_error)
def decrypt(self, enc_str, str_key):
try:
aes_obj = AES.new(str_key.encode('utf8'), AES.MODE_CFB, self.salt)
str_tmp = b64decode(enc_str.encode(self.enc_dec_method))
str_dec = aes_obj.decrypt(str_tmp)
mret = str_dec.decode(self.enc_dec_method)
return mret
except ValueError as value_error:
if value_error.args[0] == 'IV must be 16 bytes long':
raise ValueError('Decryption Error: SALT must be 16 characters long')
elif value_error.args[0] == 'AES key must be either 16, 24, or 32 bytes long':
raise ValueError('Decryption Error: Encryption key must be either 16, 24, or 32 characters long')
else:
raise ValueError(value_error)
Usage:
test_crpt = Crypt()
test_text = """Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum."""
test_key = 'MyKey4TestingYnP'
test_enc_text = test_crpt.encrypt(test_text, test_key)
test_dec_text = test_crpt.decrypt(test_enc_text, test_key)
print(f'Encrypted:{test_enc_text} Decrypted:{test_dec_text}')
Whatever code you are writing in viewDidLoad
, Add that in viewWillappear()
. This will solve your problem.
For a custom class to work properly in collections you'll have to implement/override the equals()
methods of the class. For sorting also override compareTo()
.
See this article or google about how to implement those methods properly.
If you give a Scanner object a String, it will read it in as data. That is, "a.txt" does not open up a file called "a.txt". It literally reads in the characters 'a', '.', 't' and so forth.
This is according to Core Java Volume I, section 3.7.3.
If I find a solution to reading the actual paths, I will return and update this answer. The solution this text offers is to use
Scanner in = new Scanner(Paths.get("myfile.txt"));
But I can't get this to work because Path isn't recognized as a variable by the compiler. Perhaps I'm missing an import statement.
With Swift 5, according to your needs, you may choose one of the following Playground sample codes in order to solve your problem.
Character
s into a String
with no separator:let characterArray: [Character] = ["J", "o", "h", "n"]
let string = String(characterArray)
print(string)
// prints "John"
String
s into a String
with no separator:let stringArray = ["Bob", "Dan", "Bryan"]
let string = stringArray.joined(separator: "")
print(string) // prints: "BobDanBryan"
String
s into a String
with a separator between words:let stringArray = ["Bob", "Dan", "Bryan"]
let string = stringArray.joined(separator: " ")
print(string) // prints: "Bob Dan Bryan"
String
s into a String
with a separator between characters:let stringArray = ["car", "bike", "boat"]
let characterArray = stringArray.flatMap { $0 }
let stringArray2 = characterArray.map { String($0) }
let string = stringArray2.joined(separator: ", ")
print(string) // prints: "c, a, r, b, i, k, e, b, o, a, t"
Float
s into a String
with a separator between numbers:let floatArray = [12, 14.6, 35]
let stringArray = floatArray.map { String($0) }
let string = stringArray.joined(separator: "-")
print(string)
// prints "12.0-14.6-35.0"
This can actually be done in CSS and very minimal JS just by adding a CSS class (don't set styles directly in JS!) with e.g. a ng-click
event. The principle is that one can't animate height: 0;
to height: auto;
but this can be tricked by animating the max-height
property. The container will expand to it's "auto-height" value when .foo-open
is set - no need for fixed height or positioning.
.foo {
max-height: 0;
}
.foo--open {
max-height: 1000px; /* some arbitrary big value */
transition: ...
}
see this fiddle by the excellent Lea Verou
As a concern raised in the comments, note that while this animation works perfectly with linear easing, any exponential easing will produce a behaviour different from what could be expected - due to the fact that the animated property is max-height
and not height
itself; specifically, only the height
fraction of the easing curve of max-height
will be displayed.
You could try this if you want to insert all column using SELECT * INTO
table.
SELECT *
INTO Table2
FROM Table1;
In my case I finally made it with
import java.lang.Thread;
import java.io.BufferedReader;
import java.io.InputStreamReader;
final BufferedReader in = new BufferedReader(new InputStreamReader(
Thread.currentThread().getContextClassLoader().getResourceAsStream("file.txt"))
); // no initial slash in file.txt
This was the only way I could get this to work
add_action('init','add_query_args');
function add_query_args()
{
add_query_arg( 'var1', 'val1' );
}
You could try:
$j('div.contextualError.ckgcellphone').css('display')
If you want to do that why not go with a while, for ease of mind? :P No, but seriously I didn't know that and seems kinda nice so thanks, nice to know!
The fundamental difference in most programming languages is that unless the unexpected happens a for
loop will always repeat n
times or until a break statement, (which may be conditional), is met then finish with a while
loop it may repeat 0 times, 1, more or even forever
, depending on a given condition which must be true at the start of each loop for it to execute and always false on exiting the loop, (for completeness a do ... while
loop, (or repeat until
), for languages that have it, always executes at least once and does not guarantee the condition on the first execution).
It is worth noting that in Python a for
or while
statement can have break
, continue
and else
statements where:
break
- terminates the loopcontinue
- moves on to the next time around the loop without executing following code this time aroundelse
- is executed if the loop completed without any break
statements being executed.N.B. In the now unsupported Python 2 range
produced a list of integers but you could use xrange
to use an iterator. In Python 3 range
returns an iterator.
So the answer to your question is 'it all depends on what you are trying to do'!
My understanding is that this question is better answered over in this post.
But briefly, the answer to the OP with this method is simply:
s1 = pd.merge(df1, df2, how='inner', on=['user_id'])
Which gives s1 with 5 columns: user_id and the other two columns from each of df1 and df2.
Use this to implement mask:
https://rawgit.com/RobinHerbots/jquery.inputmask/3.x/dist/jquery.inputmask.bundle.js
<input id="phn-number" class="ant-input" type="text" placeholder="(XXX) XXX-XXXX" data-inputmask-mask="(999) 999-9999">
jQuery( '#phn-number[data-inputmask-mask]' ).inputmask();
To do it properly, you need to handle the exceptions.
Here is how I do a wait for an iFrame. This requires that your JUnit test class pass the instance of RemoteWebDriver into the page object :
public class IFrame1 extends LoadableComponent<IFrame1> {
private RemoteWebDriver driver;
@FindBy(id = "iFrame1TextFieldTestInputControlID" )
public WebElement iFrame1TextFieldInput;
@FindBy(id = "iFrame1TextFieldTestProcessButtonID" )
public WebElement copyButton;
public IFrame1( RemoteWebDriver drv ) {
super();
this.driver = drv;
this.driver.switchTo().defaultContent();
waitTimer(1, 1000);
this.driver.switchTo().frame("BodyFrame1");
LOGGER.info("IFrame1 constructor...");
}
@Override
protected void isLoaded() throws Error {
LOGGER.info("IFrame1.isLoaded()...");
PageFactory.initElements( driver, this );
try {
assertTrue( "Page visible title is not yet available.", driver
.findElementByCssSelector("body form#webDriverUnitiFrame1TestFormID h1")
.getText().equals("iFrame1 Test") );
} catch ( NoSuchElementException e) {
LOGGER.info("No such element." );
assertTrue("No such element.", false);
}
}
@Override
protected void load() {
LOGGER.info("IFrame1.load()...");
Wait<WebDriver> wait = new FluentWait<WebDriver>( driver )
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring( NoSuchElementException.class )
.ignoring( StaleElementReferenceException.class ) ;
wait.until( ExpectedConditions.presenceOfElementLocated(
By.cssSelector("body form#webDriverUnitiFrame1TestFormID h1") ) );
}
....
NOTE: You can see my entire working example here.
Try this:
$('element').attr('id', 'value');
So it becomes;
$(function() {
$('span .breadcrumb').each(function(){
$('#nav').attr('id', $(this).text());
$('#container').attr('id', $(this).text());
$('.stretch_footer').attr('id', $(this).text())
$('#footer').attr('id', $(this).text());
});
});
So you are changing/overwriting the id of three elements and adding an id to one element. You can modify as per you needs...
Quick and Simple Code
public static bool IsValidEmail(this string email)
{
const string pattern = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|" + @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)" + @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$";
var regex = new Regex(pattern, RegexOptions.IgnoreCase);
return regex.IsMatch(email);
}