qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
2,608,763 |
While debugging slow startup of an Eclipse RCP app on a Citrix server, I came to find out that java.io.createTempFile(String,String,File) is taking 5 seconds. It does this only on the first execution and only for certain user accounts. Specifically, I am noticing it Citrix anonymous user accounts. I have not tried many other types of accounts, but this behavior is not exhibited with an administrator account.
Also, it does not matter if the user has access to write to the given directory or not. If the user does not have access, the call will take 5 seconds to fail. If they do have access, the call with take 5 seconds to succeed.
This is on a Windows 2003 Server. I've tried Sun's 1.6.0\_16 and 1.6.0\_19 JREs and see the same behavior.
I googled a bit expecting this to be some sort of known issue, but didn't find anything. It seems like someone else would have had to have run into this before.
The Eclipse Platform uses File.createTempFile() to test various directories to see if they are writeable during initialization and this issue adds 5 seconds to the startup time of our application.
I imagine somebody has run into this before and might have some insight. Here is sample code I executed to see that it is indeed this call that is consuming the time. I also tried it with a second call to createTempFile and notice that subsequent calls return nearly instantaneously.
```
public static void main(final String[] args) throws IOException {
final File directory = new File(args[0]);
final long startTime = System.currentTimeMillis();
File file = null;
try {
file = File.createTempFile("prefix", "suffix", directory);
System.out.println(file.getAbsolutePath());
} finally {
System.out.println(System.currentTimeMillis() - startTime);
if (file != null) {
file.delete();
}
}
}
```
Sample output of this program is the following:
```
C:\>java.exe -jar filetest.jar C:/Temp
C:\Temp\prefix8098550723198856667suffix
5093
```
|
2010/04/09
|
[
"https://Stackoverflow.com/questions/2608763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/312944/"
] |
It might be the intialisation of the secure random number generator which is causing the problem. In particular if a secure random seed is not obtainable from the operating system, then the fall-back mechanism attempts to gain entropy. IIRC, one of the things it does is to list temporary files, so if you have a large number of those that will not help start-up performance.
|
It looks like the slowness is due to the seeding of SecureRandom and only when the user is a member of the Guests group.
The SecureRandom seed initialization uses a Windows Crypto API which fails when the user is a guest as described here [1]. By setting the system property "java.security.debug" equal to "all", I can see the following when the program as run as a guest:
```
ProviderConfig: Loaded provider SUN version 1.6
provider: Failed to use operating system seed generator: java.io.IOException: Required native CryptoAPI features not available on this machine
provider: Using default threaded seed generator
```
When run as non-guest user, the output is this:
```
ProviderConfig: Loaded provider SUN version 1.6
provider: Using operating system seed generator
```
It appears the default threaded seed generator is quite slow. Here [2] is a very old bug logged to Sun about this.
[1] <http://www.derkeiler.com/Newsgroups/microsoft.public.platformsdk.security/2003-12/0349.html>
[2] <http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4210047>
|
2,608,763 |
While debugging slow startup of an Eclipse RCP app on a Citrix server, I came to find out that java.io.createTempFile(String,String,File) is taking 5 seconds. It does this only on the first execution and only for certain user accounts. Specifically, I am noticing it Citrix anonymous user accounts. I have not tried many other types of accounts, but this behavior is not exhibited with an administrator account.
Also, it does not matter if the user has access to write to the given directory or not. If the user does not have access, the call will take 5 seconds to fail. If they do have access, the call with take 5 seconds to succeed.
This is on a Windows 2003 Server. I've tried Sun's 1.6.0\_16 and 1.6.0\_19 JREs and see the same behavior.
I googled a bit expecting this to be some sort of known issue, but didn't find anything. It seems like someone else would have had to have run into this before.
The Eclipse Platform uses File.createTempFile() to test various directories to see if they are writeable during initialization and this issue adds 5 seconds to the startup time of our application.
I imagine somebody has run into this before and might have some insight. Here is sample code I executed to see that it is indeed this call that is consuming the time. I also tried it with a second call to createTempFile and notice that subsequent calls return nearly instantaneously.
```
public static void main(final String[] args) throws IOException {
final File directory = new File(args[0]);
final long startTime = System.currentTimeMillis();
File file = null;
try {
file = File.createTempFile("prefix", "suffix", directory);
System.out.println(file.getAbsolutePath());
} finally {
System.out.println(System.currentTimeMillis() - startTime);
if (file != null) {
file.delete();
}
}
}
```
Sample output of this program is the following:
```
C:\>java.exe -jar filetest.jar C:/Temp
C:\Temp\prefix8098550723198856667suffix
5093
```
|
2010/04/09
|
[
"https://Stackoverflow.com/questions/2608763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/312944/"
] |
It looks like the slowness is due to the seeding of SecureRandom and only when the user is a member of the Guests group.
The SecureRandom seed initialization uses a Windows Crypto API which fails when the user is a guest as described here [1]. By setting the system property "java.security.debug" equal to "all", I can see the following when the program as run as a guest:
```
ProviderConfig: Loaded provider SUN version 1.6
provider: Failed to use operating system seed generator: java.io.IOException: Required native CryptoAPI features not available on this machine
provider: Using default threaded seed generator
```
When run as non-guest user, the output is this:
```
ProviderConfig: Loaded provider SUN version 1.6
provider: Using operating system seed generator
```
It appears the default threaded seed generator is quite slow. Here [2] is a very old bug logged to Sun about this.
[1] <http://www.derkeiler.com/Newsgroups/microsoft.public.platformsdk.security/2003-12/0349.html>
[2] <http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4210047>
|
I'm not a Citrix expert, but I know someone who is, and who conjectures:
The accounts may be set up so that application reads/writes are redirected to non-local resources. The latency you're experiencing may be related to the initialization or performance of that resolution.
Another possibility is that the application isolation may be in effect, which means file reads/writes happen on virtualized versions of resources.
|
153,510 |
I am having problems getting lengths from multilinestrings after transforming data from EPSG:27700 - OSGB 1936 / British National Grid to EPSG:4326/ WGS 84.
I'm doing this conversion to import a roads shapefile into a PostGIS database that uses WGS84 as default. However, when I try to calulate lengths, I'm having weird readings.
Firstly I thought about some incorrect transformation, but after doing some additional tests in an empty database importing the layer without transforming it (OSGB 1936 reference), I´m still puzzled:
The following query returns contradictory results
```
SELECT
ST_Length(geom) AS length_OSGB
,ST_Length_Spheroid(ST_Transform(geom,4326),'SPHEROID["WGS 84",6378137,298.257223563]') As length_WGS84
FROM osgb36_data
WHERE id = 108
```
this yields 338 meters for the OSGB36 length and 482 meters for the WGS84 length. The right one is 338 meters.
I've done the importation to the database using QGIS and DBmanager.
Also, I had to guess the initial projectios, as the .prj was missing, but projecting the result over google maps results in a perfect match.
Any hint is welcome
**EDIT:**
This is the WKT for the element in the example, as suggested:
```
SRID=27700;MULTILINESTRING((
423216.279 574665.249 0,
423206.315 574708.077 44.649,
423158.458 574896.911 242.525,
423132.406 574993.061 344))
```
Well, that's weird, seems like they were using the z coordinate to register the accumulated distance for each point in the linestring... That could explain the issue with the wrong distances
|
2015/07/07
|
[
"https://gis.stackexchange.com/questions/153510",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/37933/"
] |
The length functions work differently with 3D linestring geometries:
* [`ST_Length`](http://postgis.net/docs/ST_Length.html) - returns 2D distances for `geometry` types, and oddly 3D distances for `geography` types (but not in this question)
* [`ST_Length_Spheroid`](http://postgis.net/docs/ST_Length_Spheroid.html) - returns 3D distances for `geometry` types
Your example is in 3D, so it will calculate the 3D length with `ST_Length_Spheroid` and the 2D length with `ST_Length` on a `geometry`.
However, if you always want 2D lengths, you can force the geometry to a 2D linestring using either [`ST_Force2D` or `ST_Force_2D`](http://postgis.net/docs/ST_Force_2D.html) function (the name change in PostGIS 2.1).
```
SELECT ST_Length(geom) AS length_27700,
ST_Length_Spheroid(ST_Transform(ST_Force2d(geom), 4326), spheroid) AS length_spheroid_2d,
ST_Length_Spheroid(ST_Transform(geom, 4326), spheroid) AS length_spheroid_3d
FROM (
SELECT 'SRID=27700;MULTILINESTRING((
423216.279 574665.249 0,
423206.315 574708.077 44.649,
423158.458 574896.911 242.525,
423132.406 574993.061 344))'::geometry AS geom,
'SPHEROID["WGS 84",6378137,298.257223563]'::spheroid
) AS f;
length_27700 | length_spheroid_2d | length_spheroid_3d
-----------------+--------------------+--------------------
338.39264086563 | 338.515774984236 | 482.622196178051
```
|
Postgis is correct.
Your line is in 3d space, and in fact has a length of ~482m even in the British National Grid.
338 meters is also correct but it corespondents in the projection of the 3d line in the 2d space.
```
with a as ( select st_Geomfromewkt('SRID=27700;MULTILINESTRING((
423216.279 574665.249 0,
423206.315 574708.077 44.649,
423158.458 574896.911 242.525,
423132.406 574993.061 344))') geom)
select ST_Length(geom) "2D Length", ST_3DLength(geom) "3D_Length" from a;
2d_length | 3d_length
-----------------+-----------------
338.39264086563 | 482.54086040695 (1 row)
```
Manual Links:
[ST\_Length](http://postgis.net/docs/ST_Length.html)
[ST\_3DLength](http://postgis.net/docs/ST_3DLength.html)
**Edit:**
Related:
<http://revenant.ca/www/postgis/workshop/measurement.html>
|
23,764,324 |
from showing every time I run my Test Application in my AVD. I'm trying to show a maps and Eclipse shows no mistakes. So how can I fix this and how can I find out what the problem is if Eclipse shows no problems?
(Here's a copy of my MainActivity)
```
package com.example.test;
import android.app.Activity;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle arg0) {
// TODO Auto-generated method stub
super.onCreate(arg0);
setContentView(R.layout.activity_main);
}
}
```
(Here's a copy of my Activity\_main.xml)
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<fragment
android:id="@+id/fragment1"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
```
(Here's a copy of my TestManifest)
```
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="14" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.djandroid.mapsv2.permission.MAPS_RECEIVE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.test.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.example.test..API_KEY"
android:value="AIzaSyBQ1sjxD09jxrSff68ZP77JpLQxm9LB8Hs" />
<uses-library
android:name="com.google.android.maps"
android:required="true" />
</application>
</manifest>
```
please help me
|
2014/05/20
|
[
"https://Stackoverflow.com/questions/23764324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3657268/"
] |
in manifest file
================
```
<!-- Google API Key -->
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="YOURAPIKEY" />
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
```
|
You are missing `<meta-data>` tag in your `Android_Manifest.xml`
So please add this along with
```
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
```
Also replace
```
<meta-data
android:name="com.example.test..API_KEY"
android:value="AIzaSyBQ1sjxD09jxrSff68ZP77JpLQxm9LB8Hs" />
```
as
```
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyBQ1sjxD09jxrSff68ZP77JpLQxm9LB8Hs" />
```
You dont need
```
<uses-library
android:name="com.google.android.maps"
android:required="true" />
```
as you are using Google Maps v2
|
23,764,324 |
from showing every time I run my Test Application in my AVD. I'm trying to show a maps and Eclipse shows no mistakes. So how can I fix this and how can I find out what the problem is if Eclipse shows no problems?
(Here's a copy of my MainActivity)
```
package com.example.test;
import android.app.Activity;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle arg0) {
// TODO Auto-generated method stub
super.onCreate(arg0);
setContentView(R.layout.activity_main);
}
}
```
(Here's a copy of my Activity\_main.xml)
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<fragment
android:id="@+id/fragment1"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
```
(Here's a copy of my TestManifest)
```
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="14" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.djandroid.mapsv2.permission.MAPS_RECEIVE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.test.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.example.test..API_KEY"
android:value="AIzaSyBQ1sjxD09jxrSff68ZP77JpLQxm9LB8Hs" />
<uses-library
android:name="com.google.android.maps"
android:required="true" />
</application>
</manifest>
```
please help me
|
2014/05/20
|
[
"https://Stackoverflow.com/questions/23764324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3657268/"
] |
Looking at the code you are missing
```
...// rest of the code
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
</application>
```
You are missing
```
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
```
Also change this
```
<meta-data
android:name="com.example.test..API_KEY"
android:value="AIzaSyBQ1sjxD09jxrSff68ZP77JpLQxm9LB8Hs" />
```
to
```
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value=" AIzaSyBQ1sjxD09jxrSff68ZP77JpLQxm9LB8Hs"/>
```
You don't need
```
<uses-library
android:name="com.google.android.maps"
android:required="true" />
```
and
```
<uses-permission android:name="com.djandroid.mapsv2.permission.MAPS_RECEIVE" />
```
Also
>
> I run my Test Application in my AVD.
>
>
>
Note : Google maps require google play services installed. You need Google api platform 4.4.2 and above to test.
Its better to test it on a real device.
|
You are missing `<meta-data>` tag in your `Android_Manifest.xml`
So please add this along with
```
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
```
Also replace
```
<meta-data
android:name="com.example.test..API_KEY"
android:value="AIzaSyBQ1sjxD09jxrSff68ZP77JpLQxm9LB8Hs" />
```
as
```
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyBQ1sjxD09jxrSff68ZP77JpLQxm9LB8Hs" />
```
You dont need
```
<uses-library
android:name="com.google.android.maps"
android:required="true" />
```
as you are using Google Maps v2
|
23,764,324 |
from showing every time I run my Test Application in my AVD. I'm trying to show a maps and Eclipse shows no mistakes. So how can I fix this and how can I find out what the problem is if Eclipse shows no problems?
(Here's a copy of my MainActivity)
```
package com.example.test;
import android.app.Activity;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle arg0) {
// TODO Auto-generated method stub
super.onCreate(arg0);
setContentView(R.layout.activity_main);
}
}
```
(Here's a copy of my Activity\_main.xml)
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<fragment
android:id="@+id/fragment1"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
```
(Here's a copy of my TestManifest)
```
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="14" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.djandroid.mapsv2.permission.MAPS_RECEIVE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.test.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.example.test..API_KEY"
android:value="AIzaSyBQ1sjxD09jxrSff68ZP77JpLQxm9LB8Hs" />
<uses-library
android:name="com.google.android.maps"
android:required="true" />
</application>
</manifest>
```
please help me
|
2014/05/20
|
[
"https://Stackoverflow.com/questions/23764324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3657268/"
] |
in manifest file
================
```
<!-- Google API Key -->
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="YOURAPIKEY" />
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
```
|
PERMISSIONS
```
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<permission android:name="com.example.test.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-feature android:glEsVersion="0x00020000" android:required="true" />
<uses-permission android:name="com.example.test.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
```
Inside your Application tag, next to API KEY put
```
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
```
|
23,764,324 |
from showing every time I run my Test Application in my AVD. I'm trying to show a maps and Eclipse shows no mistakes. So how can I fix this and how can I find out what the problem is if Eclipse shows no problems?
(Here's a copy of my MainActivity)
```
package com.example.test;
import android.app.Activity;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle arg0) {
// TODO Auto-generated method stub
super.onCreate(arg0);
setContentView(R.layout.activity_main);
}
}
```
(Here's a copy of my Activity\_main.xml)
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<fragment
android:id="@+id/fragment1"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
```
(Here's a copy of my TestManifest)
```
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="14" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.djandroid.mapsv2.permission.MAPS_RECEIVE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.test.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.example.test..API_KEY"
android:value="AIzaSyBQ1sjxD09jxrSff68ZP77JpLQxm9LB8Hs" />
<uses-library
android:name="com.google.android.maps"
android:required="true" />
</application>
</manifest>
```
please help me
|
2014/05/20
|
[
"https://Stackoverflow.com/questions/23764324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3657268/"
] |
Looking at the code you are missing
```
...// rest of the code
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
</application>
```
You are missing
```
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
```
Also change this
```
<meta-data
android:name="com.example.test..API_KEY"
android:value="AIzaSyBQ1sjxD09jxrSff68ZP77JpLQxm9LB8Hs" />
```
to
```
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value=" AIzaSyBQ1sjxD09jxrSff68ZP77JpLQxm9LB8Hs"/>
```
You don't need
```
<uses-library
android:name="com.google.android.maps"
android:required="true" />
```
and
```
<uses-permission android:name="com.djandroid.mapsv2.permission.MAPS_RECEIVE" />
```
Also
>
> I run my Test Application in my AVD.
>
>
>
Note : Google maps require google play services installed. You need Google api platform 4.4.2 and above to test.
Its better to test it on a real device.
|
PERMISSIONS
```
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<permission android:name="com.example.test.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-feature android:glEsVersion="0x00020000" android:required="true" />
<uses-permission android:name="com.example.test.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
```
Inside your Application tag, next to API KEY put
```
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
```
|
7,055 |
I am working with ArcGIS 10.0. As a simple example let's say I have a map of the United States. I want to each row of the data which states have adjacent boundaries with that state - so that in the row for South Carolina there would be new variables adjacent\_1 and adjacent\_2 that list North Carolina and Georgia (or anything similar to this)
Any thoughts? I know I can select on "features that touch the boundary of the selected feature" but then I'm not sure how to add the information to the data.
|
2011/03/10
|
[
"https://gis.stackexchange.com/questions/7055",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/2270/"
] |
You should be able to write a script that loops through every feature present in the feature class, execute a spatial query to select any adjoining features, loop through the results of the spatial query, and write a specific attribute from the resulting features into the original feature. Depending on how exactly you want to use this information, you'll want to add a new column to the feature class called AdjoiningFeatures, and add a comma separated (or similar format) list of adjoining feature names/ids/etc in that column.
One major issue to think about is that the list of adjoining features is static, and will not update along with your data without having to re-execute your script.
As for where to start, look at Python scripting in ArcGIS 10.0.
|
This is what GIS is for. However if you want the duplication I think you will have to get creative and do some spatial joins. possibly make a copy of your polygon data and sp join that back to the original.
??
|
7,055 |
I am working with ArcGIS 10.0. As a simple example let's say I have a map of the United States. I want to each row of the data which states have adjacent boundaries with that state - so that in the row for South Carolina there would be new variables adjacent\_1 and adjacent\_2 that list North Carolina and Georgia (or anything similar to this)
Any thoughts? I know I can select on "features that touch the boundary of the selected feature" but then I'm not sure how to add the information to the data.
|
2011/03/10
|
[
"https://gis.stackexchange.com/questions/7055",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/2270/"
] |
Buffer the features infinitesimally (such as one meter). Union the buffer layer with itself, thereby creating *k* records for each distinct overlap of *k* features. The records in this union include the identifiers of the parent features. Summarize the union on the concatenation of these two identifiers: this effectively strips out all the duplication. You have created a table implementing the desired relation. A many-to-one join of this table to the original layer finishes the job.
(If you don't want to count two polygons meeting at a point as "adjacent," filter out all elements of the union based on their areas or extents: an area less than Pi \* r^2 /2, where r is the buffer radius, is almost surely not an indication of adjacency.)
|
This is what GIS is for. However if you want the duplication I think you will have to get creative and do some spatial joins. possibly make a copy of your polygon data and sp join that back to the original.
??
|
7,055 |
I am working with ArcGIS 10.0. As a simple example let's say I have a map of the United States. I want to each row of the data which states have adjacent boundaries with that state - so that in the row for South Carolina there would be new variables adjacent\_1 and adjacent\_2 that list North Carolina and Georgia (or anything similar to this)
Any thoughts? I know I can select on "features that touch the boundary of the selected feature" but then I'm not sure how to add the information to the data.
|
2011/03/10
|
[
"https://gis.stackexchange.com/questions/7055",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/2270/"
] |
Buffer the features infinitesimally (such as one meter). Union the buffer layer with itself, thereby creating *k* records for each distinct overlap of *k* features. The records in this union include the identifiers of the parent features. Summarize the union on the concatenation of these two identifiers: this effectively strips out all the duplication. You have created a table implementing the desired relation. A many-to-one join of this table to the original layer finishes the job.
(If you don't want to count two polygons meeting at a point as "adjacent," filter out all elements of the union based on their areas or extents: an area less than Pi \* r^2 /2, where r is the buffer radius, is almost surely not an indication of adjacency.)
|
You should be able to write a script that loops through every feature present in the feature class, execute a spatial query to select any adjoining features, loop through the results of the spatial query, and write a specific attribute from the resulting features into the original feature. Depending on how exactly you want to use this information, you'll want to add a new column to the feature class called AdjoiningFeatures, and add a comma separated (or similar format) list of adjoining feature names/ids/etc in that column.
One major issue to think about is that the list of adjoining features is static, and will not update along with your data without having to re-execute your script.
As for where to start, look at Python scripting in ArcGIS 10.0.
|
7,055 |
I am working with ArcGIS 10.0. As a simple example let's say I have a map of the United States. I want to each row of the data which states have adjacent boundaries with that state - so that in the row for South Carolina there would be new variables adjacent\_1 and adjacent\_2 that list North Carolina and Georgia (or anything similar to this)
Any thoughts? I know I can select on "features that touch the boundary of the selected feature" but then I'm not sure how to add the information to the data.
|
2011/03/10
|
[
"https://gis.stackexchange.com/questions/7055",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/2270/"
] |
You should be able to write a script that loops through every feature present in the feature class, execute a spatial query to select any adjoining features, loop through the results of the spatial query, and write a specific attribute from the resulting features into the original feature. Depending on how exactly you want to use this information, you'll want to add a new column to the feature class called AdjoiningFeatures, and add a comma separated (or similar format) list of adjoining feature names/ids/etc in that column.
One major issue to think about is that the list of adjoining features is static, and will not update along with your data without having to re-execute your script.
As for where to start, look at Python scripting in ArcGIS 10.0.
|
I note that you are using ArcGIS Desktop 10.0, but if you were using ArcGIS 10.1 for Desktop or later then you would have access to the Polygon Neighbors tool.
For more details see [Adding/updating field to polygon feature class that lists bordering (neighbor) polygons?](https://gis.stackexchange.com/questions/80363/adding-updating-field-to-polygon-feature-class-that-lists-bordering-neighbor-p)
|
7,055 |
I am working with ArcGIS 10.0. As a simple example let's say I have a map of the United States. I want to each row of the data which states have adjacent boundaries with that state - so that in the row for South Carolina there would be new variables adjacent\_1 and adjacent\_2 that list North Carolina and Georgia (or anything similar to this)
Any thoughts? I know I can select on "features that touch the boundary of the selected feature" but then I'm not sure how to add the information to the data.
|
2011/03/10
|
[
"https://gis.stackexchange.com/questions/7055",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/2270/"
] |
Buffer the features infinitesimally (such as one meter). Union the buffer layer with itself, thereby creating *k* records for each distinct overlap of *k* features. The records in this union include the identifiers of the parent features. Summarize the union on the concatenation of these two identifiers: this effectively strips out all the duplication. You have created a table implementing the desired relation. A many-to-one join of this table to the original layer finishes the job.
(If you don't want to count two polygons meeting at a point as "adjacent," filter out all elements of the union based on their areas or extents: an area less than Pi \* r^2 /2, where r is the buffer radius, is almost surely not an indication of adjacency.)
|
I note that you are using ArcGIS Desktop 10.0, but if you were using ArcGIS 10.1 for Desktop or later then you would have access to the Polygon Neighbors tool.
For more details see [Adding/updating field to polygon feature class that lists bordering (neighbor) polygons?](https://gis.stackexchange.com/questions/80363/adding-updating-field-to-polygon-feature-class-that-lists-bordering-neighbor-p)
|
19,013 |
I am currently analyzing a project and am encountering the following situation, where I'd like to know your point of view.
For a specific content type we would like to allow users to place comments, but they should only see the comments made by users with the same role. Only administrators should be allowed to view them all.
Anyone encountered a similar situation?
|
2012/01/06
|
[
"https://drupal.stackexchange.com/questions/19013",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/3902/"
] |
My gut tell me that this plan will make your servers catch on fire...
Seriously, if you are churning that much data, then I think you need to keep the data in an external datasource and then integrate it with Drupal.
My initial thought would to use two databases for the external data, so that you can do the weekly import w/o disturbing things too much. In other words, get database A up and running, and then import into B. When the import is done, make B the live source. Then wipe and import into A.
I have done a lot of integration of external datasources into Drupal, and it really isn't that hard. I gave an overview in [Transition plan for PHP5 abomination to Drupal](https://drupal.stackexchange.com/questions/4918/transition-plan-for-php5-abomination-to-drupal/4931#4931). That was for Drupal 6, but the same thing basically applies to Drupal 7. Essentially, you simulate what CCK / Fields API does with your own interface.
Not having a UUID for the weekly database really throws a wrench in the works, though. That part requires a lot of though, more that can be provided in a Q/A forum like this.
If you really do want to go down the import route, I would bail on Feeds and Migrate and write your own import script. Basically, you do the initial bookstrap process from index.php, query your datasource, make your nodes, and then save them. Programmatically making nodes is easy.
The best way to start out with this is to make a node with the UI, then print\_r it, and replicate the object with code in your import script. Taxonomy, files, and noderefs, are hard parts, but you just need to get familiar with these portions of the API to build up these object properties. Once you have a valid node object, then you can just do a node\_save(). Make sure you set a very large limit with set\_time\_limit() so your script runs.
EDIT BELOW TO ADDRESS CLARIFICATION/EXPANSION:
Personally, we stopped using the contrib module based approaches for data imports a while ago. They do work mostly well, but we just ended up spending way too much time fighting them and decided the cost/benefit was too low.
If you really need the data in Drupal proper, then my opinion about a custom import script hasn't changed. One of the modules you reference could be used as a starting point for how to build the node objects, then just loop through your data build nodes and save them. If you have a PK, you can easily add in logic to search the database and node\_load(), modify, and save. An import script is really only a few hours work if you know the Drupal API.
If views integration is a key (and it sound like it is based on the edit) and you want to do the external tables approach, then your best option is do do a custom module and implement [hook\_views\_data](http://drupalcontrib.org/api/drupal/contributions--views--docs--views.api.php/function/hook_views_data/7) to get your data into views. More than likely, you will custom module anyway to support your datasource, so adding this hook shouldn't be that much more work. The TW and Data modules should have some example to get you going.
Personally, though, I have never found the views integration with external data to be really worthwhile. In the cases where I have considered it, the data was just too "different" to work well with a views based approach. I just end up using the method I described in the "abomination" link above.
|
I think a node based (or even entity based) approach will burn out your server with millions of node. Besides, looking at your hourly import, that means your'll make a node\_save() at least once a second. That's too much for Drupal and cause a performance problem.
The reason behind that is for those content, you won't need any hook mechanism, you won't need pathauto (but you can manually create alias, it's much cheaper than pathauto), you won't need fields... Write a simple "INSERT" query is 100x faster than node\_save() or entity\_save().
1/ IMHO the best option is a custom table and a custom module for your data import, then write Views handlers for Drupal integration.
2/ The database cache is invalidated during the hourly import. If it takes too much time, you can think about a replication. In the easiest form, create two identical tables, use the first one, import to the second, switch your Drupal configuration to use the second table, sync the 2nd table to the 1st (then optionally switch back to the first). Another solution is in your custom import script, prepare and group the INSERT/UPDATE queries, then only send it at the end in one transaction to reduce the database write time.
|
27,170,348 |
I'm logging the testresults to DB while testNG runs the testcases. I'm using excel sheet to provide input data .
For eg:
```
tablename
row1 col1
row2 col2
tablename
```
I want to know, which row is getting executed ? There might be any function in dataprovider class which will be storing the counter.
Please help me get the counter value.
Thanks in advance.
|
2014/11/27
|
[
"https://Stackoverflow.com/questions/27170348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/479117/"
] |
Well, your `query` dictionary is rather funky, for one, `'fowl'` and `'Year of the Monkey'` values are not structured the same, so you cannot aply the same data access patterns, or categories being misspelled as `'cateogry'`. If you can, you may be better off fixing that before trying to process it further.
As for extracting the `'fowl'` data:
```
>>> query = {'fowl': [{'cateogry': 'Space'}, {'cateogry': 'Movie'}, {'cateogry': 'six'}], u'Year of the Monkey': {'score': 40, 'match': [{'category': u'Movie'}, {'category': 'heaven'}, {'category': 'released'}]}}
>>> query['fowl'] # 'fowl'
[{'cateogry': 'Space'}, {'cateogry': 'Movie'}, {'cateogry': 'six'}]
>>> [d['cateogry'] for d in query['fowl']] # 'fowl' categories
['Space', 'Movie', 'six']
>>> [d['cateogry'] for d in query['fowl']][0] # 'fowl' 'Space' category
'Space'
```
|
`query` is a dictionary not a list, so do `query['fowl']` instead
|
27,170,348 |
I'm logging the testresults to DB while testNG runs the testcases. I'm using excel sheet to provide input data .
For eg:
```
tablename
row1 col1
row2 col2
tablename
```
I want to know, which row is getting executed ? There might be any function in dataprovider class which will be storing the counter.
Please help me get the counter value.
Thanks in advance.
|
2014/11/27
|
[
"https://Stackoverflow.com/questions/27170348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/479117/"
] |
Well, your `query` dictionary is rather funky, for one, `'fowl'` and `'Year of the Monkey'` values are not structured the same, so you cannot aply the same data access patterns, or categories being misspelled as `'cateogry'`. If you can, you may be better off fixing that before trying to process it further.
As for extracting the `'fowl'` data:
```
>>> query = {'fowl': [{'cateogry': 'Space'}, {'cateogry': 'Movie'}, {'cateogry': 'six'}], u'Year of the Monkey': {'score': 40, 'match': [{'category': u'Movie'}, {'category': 'heaven'}, {'category': 'released'}]}}
>>> query['fowl'] # 'fowl'
[{'cateogry': 'Space'}, {'cateogry': 'Movie'}, {'cateogry': 'six'}]
>>> [d['cateogry'] for d in query['fowl']] # 'fowl' categories
['Space', 'Movie', 'six']
>>> [d['cateogry'] for d in query['fowl']][0] # 'fowl' 'Space' category
'Space'
```
|
`query['Year of the Monkey']['match'][0]['category']` you need to iterate
|
582,309 |
I just set up a freenas zfs raid-z2 with 4 drives sata enterprise drives and doing some performance tests. Right now I'm pushing and pulling linux images into the storage. My notebook has a samsung 840pro ssd with 400MB/s local read write speed. Samba4 is used.
I can write with avg 105 MB/s in an continuous stream. I'm impressed, this is is really fine thinking of a 1Gb/s lan.
However reading is pretty slow and network io is jumping from a few kB to 30MB/s probably in avg. about 10MB/s. Adding a l2arc doesn't help.
Any ideas, why the reading performance is so poor? is this normal?
|
2014/03/15
|
[
"https://serverfault.com/questions/582309",
"https://serverfault.com",
"https://serverfault.com/users/122722/"
] |
You may want to read [this](https://blogs.oracle.com/roch/entry/when_to_and_not_to).
Essentially, in a single RAID Z group, read performance is equal to the performance of a single disk. RAID Z is great for write performance and poor for read performance. Given the slow low-end disks you're using, the numbers you've posted seem reasonable.
If you want to use RAID Z and still have reasonable read performance, you'll have to create multiple RAID Z groups (which you don't have disks for) and stripe across them.
With four disks, you may be best off creating two mirrors and striping data across them.
|
Even thought this post is rather old, I came accross it while I was looking for the solution to the exact same problem. So maybe others can benefit from my experience;
I have a FreeNas setup where I can push up to a 110MB/s to it (write), but reading from it was twice as slow (50MB/s). Couldn't figure out why. Read a few articles where an expert user says that in general FreeNas shouldn't need tuneups or special ZIL's and L2ARC's and stuff and still should be able to hit the limits of one's gigabit network in both directions. That same dude was telling about Realtec NICs not always performing fine. I did have a Realtec NIC in my machine, and thought if it can pull data in with over 100MB/s it should also be able to push data out with 100MB/s.
Just because I had a spare Intel server based NIC (PRO/1000) lying around I swapped it with the Realtec NIC and did the exact same test. My FreeNas now has syncronious read and write speeds. The both hit 110MB/s. Simple as that!
|
63,379,598 |
I had created a slider using react slick now there is a requirement to change transition and animation of slides on prev and next button click. Got some help that add class to currently active slide while changing slide and add animation and transition effect to it. And remove after it slides completely changed. I tried but it is not working as expecting.
First it is not adding classe on next or prev button button click
Second it is adding class on swiping slide but it disturbs other carousel items
Here is my code
```
const settings = {
slidesToShow: 1,
slidesToScroll: 1,
arrows: false,
autoplay: false,
autoplaySpeed: 2000,
infinite: false,
beforeChange,
afterChange,
useCSS: false,
useTransform : false
}
const beforeChange = (prev: number, next: number) => {
let element = document.querySelector('.slick-active');
element?.classList.add('next-slide-anim');
setIndex(next);
};
const afterChange = (index : number) => {
let element = document.querySelector('.slick-active');
element.classList.remove('next-slide-anim')
};
const settings = {
slidesToShow: 1,
slidesToScroll: 1,
arrows: false,
autoplay: false,
autoplaySpeed: 2000,
infinite: false,
beforeChange,
afterChange,
useCSS: false,
useTransform : false
}
const next = () => {
sliderRef.current.slickNext()
};
const previous = () => {
sliderRef.current.slickPrev();
};
<div className="home-slider">
<div className="carousel">
<Slider {...settings} className="carousel-inner" ref={ref => sliderRef.current = ref}>
{
slides.map((slide: any, index) => (
<div className="carousel-item" key={index} ref={ref => carouselRef.current = ref}>
<div className="slide-content">
{index !== slides.length - 1 &&
<>
<h3>{slide.username}</h3>
<span id="user-icon-link">
<Link to="/" target="_blank">
<img src="/images/homeScreen/instagram.png" alt="link-icon" width="20" height="20" />{slide.userlink}</Link>
</span>
</>
}
</div>
<img src={slide.path} alt="Chicago" width="1100" height="500" />
</div>
))
}
</Slider>
{((slides.length !== 0) && (index !== slides.length - 1)) &&
<>
{(index !== 0) && <a href="#/" className="carousel-control-prev" onClick={previous}>
<img src="/images/homeScreen/skipnewbtn.png" alt="Los Angeles" />
</a>}
{index !== slides.length - 1 && <a href="#/" className="carousel-control-next" id="next-btn" onClick={next} >
<img src="/images/homeScreen/fast-forward-button.gif" alt="Los Angeles" />
</a>}
</>
}
</div>
</div>
```
|
2020/08/12
|
[
"https://Stackoverflow.com/questions/63379598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12660992/"
] |
You can try Mathjax. The following works at my end (Python 3.9.1, dash==1.19.0, dash-html-components==1.1.2)
First create a javascript file (anyname.js) in the assets folder of your current project. In that file have just the following line:
```
setInterval("MathJax.Hub.Queue(['Typeset',MathJax.Hub])",1000);
```
Then back to your python file:
```
from dash import Dash
import dash_html_components as html
MATHJAX_CDN = '''
https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/
MathJax.js?config=TeX-MML-AM_CHTML'''
external_scripts = [
{'type': 'text/javascript',
'id': 'MathJax-script',
'src': MATHJAX_CDN,
},
]
app = Dash(__name__, external_scripts=external_scripts)
app.layout = html.Div(
children=[
html.P('''\(Area\)(\(m^2\)) '''),
]
)
app.run_server()
```
Some caveats:
* I have never been able to get Mathjax to work in the Markdown
component.
* This solution doesn't work with the latest Mathjax version (nor with
2.7.7). I am unsure which is the latest version it will work with.
If you are able to address any of the two caveats do let me know.
|
With plotly you have to use unicode. For example if you want to print a greek letter mu is "\u03bc". You can obtain some symbols from [here](https://en.wikipedia.org/wiki/Mathematical_operators_and_symbols_in_Unicode) and superscripts from [here](https://en.wikipedia.org/wiki/Superscripts_and_Subscripts_(Unicode_block)). m square will be "m\U+2072".
|
63,379,598 |
I had created a slider using react slick now there is a requirement to change transition and animation of slides on prev and next button click. Got some help that add class to currently active slide while changing slide and add animation and transition effect to it. And remove after it slides completely changed. I tried but it is not working as expecting.
First it is not adding classe on next or prev button button click
Second it is adding class on swiping slide but it disturbs other carousel items
Here is my code
```
const settings = {
slidesToShow: 1,
slidesToScroll: 1,
arrows: false,
autoplay: false,
autoplaySpeed: 2000,
infinite: false,
beforeChange,
afterChange,
useCSS: false,
useTransform : false
}
const beforeChange = (prev: number, next: number) => {
let element = document.querySelector('.slick-active');
element?.classList.add('next-slide-anim');
setIndex(next);
};
const afterChange = (index : number) => {
let element = document.querySelector('.slick-active');
element.classList.remove('next-slide-anim')
};
const settings = {
slidesToShow: 1,
slidesToScroll: 1,
arrows: false,
autoplay: false,
autoplaySpeed: 2000,
infinite: false,
beforeChange,
afterChange,
useCSS: false,
useTransform : false
}
const next = () => {
sliderRef.current.slickNext()
};
const previous = () => {
sliderRef.current.slickPrev();
};
<div className="home-slider">
<div className="carousel">
<Slider {...settings} className="carousel-inner" ref={ref => sliderRef.current = ref}>
{
slides.map((slide: any, index) => (
<div className="carousel-item" key={index} ref={ref => carouselRef.current = ref}>
<div className="slide-content">
{index !== slides.length - 1 &&
<>
<h3>{slide.username}</h3>
<span id="user-icon-link">
<Link to="/" target="_blank">
<img src="/images/homeScreen/instagram.png" alt="link-icon" width="20" height="20" />{slide.userlink}</Link>
</span>
</>
}
</div>
<img src={slide.path} alt="Chicago" width="1100" height="500" />
</div>
))
}
</Slider>
{((slides.length !== 0) && (index !== slides.length - 1)) &&
<>
{(index !== 0) && <a href="#/" className="carousel-control-prev" onClick={previous}>
<img src="/images/homeScreen/skipnewbtn.png" alt="Los Angeles" />
</a>}
{index !== slides.length - 1 && <a href="#/" className="carousel-control-next" id="next-btn" onClick={next} >
<img src="/images/homeScreen/fast-forward-button.gif" alt="Los Angeles" />
</a>}
</>
}
</div>
</div>
```
|
2020/08/12
|
[
"https://Stackoverflow.com/questions/63379598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12660992/"
] |
You can try Mathjax. The following works at my end (Python 3.9.1, dash==1.19.0, dash-html-components==1.1.2)
First create a javascript file (anyname.js) in the assets folder of your current project. In that file have just the following line:
```
setInterval("MathJax.Hub.Queue(['Typeset',MathJax.Hub])",1000);
```
Then back to your python file:
```
from dash import Dash
import dash_html_components as html
MATHJAX_CDN = '''
https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/
MathJax.js?config=TeX-MML-AM_CHTML'''
external_scripts = [
{'type': 'text/javascript',
'id': 'MathJax-script',
'src': MATHJAX_CDN,
},
]
app = Dash(__name__, external_scripts=external_scripts)
app.layout = html.Div(
children=[
html.P('''\(Area\)(\(m^2\)) '''),
]
)
app.run_server()
```
Some caveats:
* I have never been able to get Mathjax to work in the Markdown
component.
* This solution doesn't work with the latest Mathjax version (nor with
2.7.7). I am unsure which is the latest version it will work with.
If you are able to address any of the two caveats do let me know.
|
Install
```sh
pip install dash -U
```
Code
```py
import dash
from dash import dcc, html
app = dash.Dash()
app.layout = html.Div([
dcc.Markdown('$Area (m^{2})$', mathjax=True),
])
app.run_server()
```
[](https://i.stack.imgur.com/bkgEC.png)
|
63,379,598 |
I had created a slider using react slick now there is a requirement to change transition and animation of slides on prev and next button click. Got some help that add class to currently active slide while changing slide and add animation and transition effect to it. And remove after it slides completely changed. I tried but it is not working as expecting.
First it is not adding classe on next or prev button button click
Second it is adding class on swiping slide but it disturbs other carousel items
Here is my code
```
const settings = {
slidesToShow: 1,
slidesToScroll: 1,
arrows: false,
autoplay: false,
autoplaySpeed: 2000,
infinite: false,
beforeChange,
afterChange,
useCSS: false,
useTransform : false
}
const beforeChange = (prev: number, next: number) => {
let element = document.querySelector('.slick-active');
element?.classList.add('next-slide-anim');
setIndex(next);
};
const afterChange = (index : number) => {
let element = document.querySelector('.slick-active');
element.classList.remove('next-slide-anim')
};
const settings = {
slidesToShow: 1,
slidesToScroll: 1,
arrows: false,
autoplay: false,
autoplaySpeed: 2000,
infinite: false,
beforeChange,
afterChange,
useCSS: false,
useTransform : false
}
const next = () => {
sliderRef.current.slickNext()
};
const previous = () => {
sliderRef.current.slickPrev();
};
<div className="home-slider">
<div className="carousel">
<Slider {...settings} className="carousel-inner" ref={ref => sliderRef.current = ref}>
{
slides.map((slide: any, index) => (
<div className="carousel-item" key={index} ref={ref => carouselRef.current = ref}>
<div className="slide-content">
{index !== slides.length - 1 &&
<>
<h3>{slide.username}</h3>
<span id="user-icon-link">
<Link to="/" target="_blank">
<img src="/images/homeScreen/instagram.png" alt="link-icon" width="20" height="20" />{slide.userlink}</Link>
</span>
</>
}
</div>
<img src={slide.path} alt="Chicago" width="1100" height="500" />
</div>
))
}
</Slider>
{((slides.length !== 0) && (index !== slides.length - 1)) &&
<>
{(index !== 0) && <a href="#/" className="carousel-control-prev" onClick={previous}>
<img src="/images/homeScreen/skipnewbtn.png" alt="Los Angeles" />
</a>}
{index !== slides.length - 1 && <a href="#/" className="carousel-control-next" id="next-btn" onClick={next} >
<img src="/images/homeScreen/fast-forward-button.gif" alt="Los Angeles" />
</a>}
</>
}
</div>
</div>
```
|
2020/08/12
|
[
"https://Stackoverflow.com/questions/63379598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12660992/"
] |
MathJax 3 works in Dash v2.3.0 which includes Plotly.js v2.10.0 with Markdown. Example: dcc.Markdown('$$y=x+1$$', mathjax=True)
|
With plotly you have to use unicode. For example if you want to print a greek letter mu is "\u03bc". You can obtain some symbols from [here](https://en.wikipedia.org/wiki/Mathematical_operators_and_symbols_in_Unicode) and superscripts from [here](https://en.wikipedia.org/wiki/Superscripts_and_Subscripts_(Unicode_block)). m square will be "m\U+2072".
|
63,379,598 |
I had created a slider using react slick now there is a requirement to change transition and animation of slides on prev and next button click. Got some help that add class to currently active slide while changing slide and add animation and transition effect to it. And remove after it slides completely changed. I tried but it is not working as expecting.
First it is not adding classe on next or prev button button click
Second it is adding class on swiping slide but it disturbs other carousel items
Here is my code
```
const settings = {
slidesToShow: 1,
slidesToScroll: 1,
arrows: false,
autoplay: false,
autoplaySpeed: 2000,
infinite: false,
beforeChange,
afterChange,
useCSS: false,
useTransform : false
}
const beforeChange = (prev: number, next: number) => {
let element = document.querySelector('.slick-active');
element?.classList.add('next-slide-anim');
setIndex(next);
};
const afterChange = (index : number) => {
let element = document.querySelector('.slick-active');
element.classList.remove('next-slide-anim')
};
const settings = {
slidesToShow: 1,
slidesToScroll: 1,
arrows: false,
autoplay: false,
autoplaySpeed: 2000,
infinite: false,
beforeChange,
afterChange,
useCSS: false,
useTransform : false
}
const next = () => {
sliderRef.current.slickNext()
};
const previous = () => {
sliderRef.current.slickPrev();
};
<div className="home-slider">
<div className="carousel">
<Slider {...settings} className="carousel-inner" ref={ref => sliderRef.current = ref}>
{
slides.map((slide: any, index) => (
<div className="carousel-item" key={index} ref={ref => carouselRef.current = ref}>
<div className="slide-content">
{index !== slides.length - 1 &&
<>
<h3>{slide.username}</h3>
<span id="user-icon-link">
<Link to="/" target="_blank">
<img src="/images/homeScreen/instagram.png" alt="link-icon" width="20" height="20" />{slide.userlink}</Link>
</span>
</>
}
</div>
<img src={slide.path} alt="Chicago" width="1100" height="500" />
</div>
))
}
</Slider>
{((slides.length !== 0) && (index !== slides.length - 1)) &&
<>
{(index !== 0) && <a href="#/" className="carousel-control-prev" onClick={previous}>
<img src="/images/homeScreen/skipnewbtn.png" alt="Los Angeles" />
</a>}
{index !== slides.length - 1 && <a href="#/" className="carousel-control-next" id="next-btn" onClick={next} >
<img src="/images/homeScreen/fast-forward-button.gif" alt="Los Angeles" />
</a>}
</>
}
</div>
</div>
```
|
2020/08/12
|
[
"https://Stackoverflow.com/questions/63379598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12660992/"
] |
MathJax 3 works in Dash v2.3.0 which includes Plotly.js v2.10.0 with Markdown. Example: dcc.Markdown('$$y=x+1$$', mathjax=True)
|
Install
```sh
pip install dash -U
```
Code
```py
import dash
from dash import dcc, html
app = dash.Dash()
app.layout = html.Div([
dcc.Markdown('$Area (m^{2})$', mathjax=True),
])
app.run_server()
```
[](https://i.stack.imgur.com/bkgEC.png)
|
18,087 |
we have a custom PHP script which is running under JUMI to perform and display some data.
The custom script is accessible to a SEF url such as
```
http://www.mysite.com/jumi-script
```
which is a rewritten version of
```
http://www.mysite.com/index.php?option=com_jumi&view=application&fileid=11&Itemid=271
```
Now we would like to filter data applying parameters such as
```
category=mycat&place=myplace
```
like this
```
/index.php?option=com_jumi&view=application&fileid=11&Itemid=271&category=mycat&place=myplace
```
and we would like to obtain a SEF url like this
```
/jumi-script/mycat/myplace
```
and process these variables in my script with
```
$mycat = JFactory::getApplication()->input->post->get('category');
$myplace = JFactory::getApplication()->input->post->get('place');
```
How do we obtain this? we are testing the
```
$currentUrl =& JURI::getInstance();
$currentUrl->setVar( 'mycat', $catvalue );
```
but we are loosing the rest of the query string. Can the above be achieved?
Any suggestion?
Thank you
|
2016/10/08
|
[
"https://joomla.stackexchange.com/questions/18087",
"https://joomla.stackexchange.com",
"https://joomla.stackexchange.com/users/9125/"
] |
Looking at the router implementation of com\_jumi here <https://github.com/BonavalMultimedia/com_jumi/blob/master/com_jumi_bnvl/router.php> for me it seems it doesn't handle extra parameters when sef is on (see JumiParseRoute function).
You need to modify this function to check for your extra parameters and add them to the `$vars` array, so they will be available using `JInput` or `JRequest` if you are on Joomla versions before 3.0
To check the parameters, simply look if they are defined in the `$segments` parameter.
To see if you have a `category` , a `place` or both you need to determine your own criteria or store the possible values anywhere you can check for sure which value 'type' is in every segment.
**Example**: my criteria is that URLs will always be jumi/category/place . Then:
```
$vars['category'] = $segments[1];
$vars['place'] = $segments[2];
```
Of course, you must check that `$segment` indexes are defined and do whatever checking you need.
Maybe you will want to produce SEF urls when creating the routes. Then you should modify the `JumiBuildRoute` function to follow your criteria.
### Alternative to edit code
If you don't want to edit the routing code of the component then use an URL like this:
```
http://www.mysite.com/jumi-script?category=mycat&place=myplace
```
to get your script. Now, both values should be accessible through `JInput` or `JRequest` on older Joomla versions.
Regards,
|
For your url `/index.php?option=com_jumi&view=application&fileid=11&Itemid=271&category=mycat&place=myplace` :
```
$JInput = JFactory::getApplication()->input;
$myRequest = $JInput->getArray(array(
'option' =>'',
'view' =>'',
'fileid' =>'',
'Itemid' =>'',
'category'=>'',
'place' =>''
));
```
Or if you want to **filter** the input:
```
$myRequest = $JInput->getArray(array(
'option' =>'word',
'view' =>'alnum',
'fileid' =>'int',
'Itemid' =>'int',
'category'=>'string',
'place' =>'string'
));
```
each input will return value as filtered type, or `NULL` if there is no value.
|
63,472,578 |
I tried to create recursive function for generating Pascal's triangle as below.
```
numRows = 5
ans=[[1],[1,1]]
def pascal(arr,pre,idx):
if idx==numRows:
return ans
if len(arr)!=idx:
for i in range (0,len(pre)-1,1):
arr+=[pre[i]+pre[i+1]]
if len(arr)==idx:
arr+=[1]
ans.append(arr)
pascal([1],arr,idx+1)
a = pascal([1],ans[1],2)
return a
```
The output I got was an empty list `[ ]`. But if I add `return` when calling `pascal` as
```
return pascal([1],arr,idx+1)
```
the output was correct `[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]`.
As I understand, `a` should have been assigned by `return ans`. Then why `a` failed to get an answer when calling `pascal` without `return` and why `return` is necessary in this case?
|
2020/08/18
|
[
"https://Stackoverflow.com/questions/63472578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9804823/"
] |
I had the same issue, was fixed by specifying the import for act like this
`import { renderHook, act } from '@testing-library/react-hooks/dom' // will use react-dom`
based on documentation <https://react-hooks-testing-library.com/installation#renderer>
for your case other import options might work, depending on what's used in project
|
The warning was triggered because something down your chain of dependencies was calling `ReactDOM.render` directly.
In `hooks.js` you have:
```js
import { useManageNotifications } from "./notifications";
```
In `notifications.js`:
```js
import { notification, Alert } from "antd";
```
The notification package from antd does:
```js
import Notification from 'rc-notification';
```
That's the component that [calls ReactDOM.render directly](https://github.com/react-component/notification/blob/2c5e1fa5a8a5b040e1722c48188ad54b263f5811/src/Notification.tsx#L274).
If you scan up a few lines you'll see that you could tell that component to use a specific test render by passing a `TEST_RENDER` property. Unfortunately, there doesn't seem any way to get a `TEST_RENDER` property through `notification` from `antd` and into `Notification` from `rc-notification`.
One option to avoid triggering the warning is to skip that component if you detect you're running tests. i.e. guard its usage which a check to `process.env.NODE_ENV` in your `src/notifications.js` file:
```js
if (process.env.NODE_ENV !== 'test') {
notification[type]({
message: messageIntlId && <b>{messageIntlId}</b>,
description: descriptionIntlId && { descriptionIntlId },
duration: null,
...restProps
});
}
```
|
36,286,017 |
Given the following data
```
A B
Steven 01/05/1958
Mike 05/12/1923
Bob 05/11/2001
Richard 10/22/1985
Maverick 12/25/1991
Ed 01/07/1954
```
I'd like to get a list in, let's just say the column D, containing the next couple birthdays that will occur.
So if today was 05/05/2016, I'd like to see
```
D E
Bob 05/11/2001
Mike 05/12/1923
```
My current approach (yet not working properly) is to create another column and have the days until the birthday calculated there, using this formula:
```
=DATE(YEAR(B2)+DATEDIF(B2+1;TODAY();"y")+1;MONTH(B2);DAY(B2))-TODAY()
```
Then I list the birthdays that come up in the next 5 days using:
```
=IF(ISERROR(INDEX($A$2:$C$5,SMALL(IF($A$2:$C$5<5,ROW($A$2:$A$5)),ROW(1:1)),2)),"",INDEX($A$2:$C$5,SMALL(IF($A$2:$A$5<5,ROW($A$2:$A$5)),ROW(1:1)),2))
```
I'd rather have **the next 5 upcoming birthdays**, no matter how far away from today they are.
Any Ideas how to achieve this without using makros?
Help is much appreciated!
|
2016/03/29
|
[
"https://Stackoverflow.com/questions/36286017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3653975/"
] |
To get the birthday difference from today in days :
```
=(DATEDIF($D$1,DATE(IF((DATE(YEAR($D$1),MONTH(B2),DAY(B2))>$D$1),YEAR($D$1),YEAR($D$1)+1),MONTH(B2),DAY(B2)),"D"))+0
```
The first BD from current date :
```
=VLOOKUP(SMALL(A2:A8,1)+0,A2:B8,2,FALSE)
```
Please see the img for more details :[](https://i.stack.imgur.com/712jG.jpg)
|
OK slightly different approach
Instead of counting days in a helper column, change the date in a helper column. Then sort that helper column for only the first 5 entries. This will show upcoming birthDAYS instead of birthDATES.
So assuming Names in column A, Dates in Column B, Column C is created with:
```
=DATE(YEAR(TODAY())+IF(TODAY()>DATE(YEAR(TODAY()),MONTH(B2),DAY(B2)),1,0),MONTH(B2),DAY(B2))
```
Now I was assuming no header rows and A1 was the first entry so to display the next 5 entries in column D I used:
```
=IF(ROW()<=5,SMALL($C$1:$C$6,ROW()),"")
```
Now this will not pull names but just the upcoming birthDAYS not birthDATES. The year being the difference between the two.
If you want to pull the names as well you can use the following:
```
=IF(D2<>"",INDEX($A$1:$A$6,MATCH(D2,$C$1:$C$6,0)),"")
```
Right now it will not return names of multiple people with the same date but there are ways around that. If you need that too let us know.
```
(A) (B) (C) (D) (E)
Steven 58/01/05 17/01/05 16/05/11 Bob
Mike 23/05/12 16/05/12 16/05/12 Mike
Bob 01/05/11 16/05/11 16/10/22 Richard
Richard 85/10/22 16/10/22 16/12/25 Maverick
Maverick 91/12/25 16/12/25 17/01/05 Steven
Ed 54/01/07 17/01/07
```
UPDATE
------
In order to deal with duplicate birthdays... try the following:
```
=IF(E5<>"",INDEX($A$1:$A$6,MATCH(E5,$C$1:$C$6,0)+COUNTIF($E$1:E5,E5)-1),"")
```
That was the entry for row 5. I tested it with the same birthdate, but I forgot to check for same birthday (different years).
UPDATE 2
--------
NEW TABLE
The table below matches to formula from the last update
```
(A) (B) (C) (D) (E) (F) (G)
Steven 58/01/05 17/01/05 59 16/05/11 Bob 15
Mike 23/05/12 16/05/12 93 16/05/12 Mike 93
Bob 01/05/11 16/05/11 15 16/10/22 Richard 31
Richard 85/10/22 16/10/22 31 16/12/25 Maverick 25
Maverick 91/12/25 16/12/25 25 16/12/25 Ed 21
Ed 95/12/25 16/12/25 21
```
I inserted a column in D which shifted things right. The following was placed in D1.
```
=year(C1)-Year(B1)
```
In column G I had it lookup the age
```
=IF(E1<>"",INDEX($D$1:$D$6,MATCH(E1,$C$1:$C$6,0)+COUNTIF($E$1:E1,E1)-1),"")
```
|
36,286,017 |
Given the following data
```
A B
Steven 01/05/1958
Mike 05/12/1923
Bob 05/11/2001
Richard 10/22/1985
Maverick 12/25/1991
Ed 01/07/1954
```
I'd like to get a list in, let's just say the column D, containing the next couple birthdays that will occur.
So if today was 05/05/2016, I'd like to see
```
D E
Bob 05/11/2001
Mike 05/12/1923
```
My current approach (yet not working properly) is to create another column and have the days until the birthday calculated there, using this formula:
```
=DATE(YEAR(B2)+DATEDIF(B2+1;TODAY();"y")+1;MONTH(B2);DAY(B2))-TODAY()
```
Then I list the birthdays that come up in the next 5 days using:
```
=IF(ISERROR(INDEX($A$2:$C$5,SMALL(IF($A$2:$C$5<5,ROW($A$2:$A$5)),ROW(1:1)),2)),"",INDEX($A$2:$C$5,SMALL(IF($A$2:$A$5<5,ROW($A$2:$A$5)),ROW(1:1)),2))
```
I'd rather have **the next 5 upcoming birthdays**, no matter how far away from today they are.
Any Ideas how to achieve this without using makros?
Help is much appreciated!
|
2016/03/29
|
[
"https://Stackoverflow.com/questions/36286017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3653975/"
] |
To get the birthday difference from today in days :
```
=(DATEDIF($D$1,DATE(IF((DATE(YEAR($D$1),MONTH(B2),DAY(B2))>$D$1),YEAR($D$1),YEAR($D$1)+1),MONTH(B2),DAY(B2)),"D"))+0
```
The first BD from current date :
```
=VLOOKUP(SMALL(A2:A8,1)+0,A2:B8,2,FALSE)
```
Please see the img for more details :[](https://i.stack.imgur.com/712jG.jpg)
|
Another approach would be to use the `Advanced Filter`. And you could automate it using VBA.
For the Criteria:
```
A2: =DATE(YEAR(TODAY()),MONTH(B6),DAY(B6))>=TODAY()
B2: =(TODAY()+$C$2)>=DATE(YEAR(TODAY()),MONTH(B6),DAY(B6))
```
Range is the number of days after today to show birthdays.
[](https://i.stack.imgur.com/J2Sd5.png)
|
315,201 |
Here is my context,
>
> BECU is a non profit organisation, set up to protect the interests of their customers. But news media is using it as their **weapon** to score political point.
>
>
>
Weapon is a violent word, and I would like to use an alternative word here.
Could somebody recommend me an alternative word?
|
2022/05/16
|
[
"https://ell.stackexchange.com/questions/315201",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/893/"
] |
You can just cut the sentence a little:
>
> But news media is using it to score political points.
>
>
>
If you want to keep the original structure you can call it a **tool**:
>
> But news media is using it as a tool to score political points.
>
>
>
*Tool* itself is neutral here. The force of the sentences above comes from "to score political points". Using *a* instead of *their* just sounds more natural to me. And it's not idiomatic to use the singular "score point" so the plural is required.
|
You could say "But news media is using it as their **puppet** to score political point".
|
29,618,765 |
This is my issue:
I have 3 forms:
* Form fParent
* Form fChild
* Form OpenForm
I want that When I click a button on Form fChild, it shows Form OpenFormand and hides Form fParentand Form fChild.
How can I do that?
Please help me.
|
2015/04/14
|
[
"https://Stackoverflow.com/questions/29618765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4162835/"
] |
**Swift 3** - Useful `UIView` extension when you need to round specific corners of some views:
```
extension UIView {
func round(corners: UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
}
}
```
then just use it like this:
```
someView.round(corners: [.topLeft, .topRight], radius: 5)
```
|
>
> iOS 11+ Only | You can check iOS usage stats [here](https://developer.apple.com/support/app-store/)
>
>
>
Explanation
===========
Since the `CACornerMask` rawValue is an `UInt` you know that a `CACornerMask` *rawValue* is the sum of each `CACornerMask.Element` *rawValue*
More specifically:
* TopLeft (`layerMinXMinYCorner`) = 1
* TopRight (`layerMaxXMinYCorner`) = 2
* BottomLeft (`layerMinXMaxYCorner`) = 4
* BottomRight (`layerMaxXMaxYCorner`) = 8
So for example if you want **top left** and **top right** corners you can just type `CACornerMask(rawValue: 3)`.
---
Example
========
Below is a simple extension of `UIView`
```
extension UIView {
enum Corner:Int {
case bottomRight = 0,
topRight,
bottomLeft,
topLeft
}
private func parseCorner(corner: Corner) -> CACornerMask.Element {
let corners: [CACornerMask.Element] = [.layerMaxXMaxYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMinXMinYCorner]
return corners[corner.rawValue]
}
private func createMask(corners: [Corner]) -> UInt {
return corners.reduce(0, { (a, b) -> UInt in
return a + parseCorner(corner: b).rawValue
})
}
func roundCorners(corners: [Corner], amount: CGFloat = 5) {
layer.cornerRadius = amount
let maskedCorners: CACornerMask = CACornerMask(rawValue: createMask(corners: corners))
layer.maskedCorners = maskedCorners
}
}
```
You can use it this like:
```
let myRect = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
myRect.roundCorners(corners: [.topRight, .topLeft])
```
|
29,618,765 |
This is my issue:
I have 3 forms:
* Form fParent
* Form fChild
* Form OpenForm
I want that When I click a button on Form fChild, it shows Form OpenFormand and hides Form fParentand Form fChild.
How can I do that?
Please help me.
|
2015/04/14
|
[
"https://Stackoverflow.com/questions/29618765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4162835/"
] |
In summary, you can create pretty extension like this:
```
extension UIView {
func roundCorners(_ corners: UIRectCorner, radius: Double) {
let maskPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let shape = CAShapeLayer()
shape.path = maskPath.cgPath
layer.mask = shape
}
}
```
Use it like this:
```
view.roundCorners([.topRight, .bottomRight], radius: 10)
```
Here is all corners values:
* .topLeft
* .topRight
* .bottomLeft
* .bottomRight
|
One simple hack could be as following. Take views like below example in image. **Red View** will have rounded corners and **Yellow View** (inside Red View) will prevent the corners to be rounded
[](https://i.stack.imgur.com/PdCxM.png)
Now write below code for **Red View**.
```
self.myView.layer.cornerRadius = 15
```
Make sure you don't write any code as **clipsToBounds = true** or **masksToBounds = true**.
Below image is the result
[](https://i.stack.imgur.com/fMoDU.png)
Placement of **Yellow View** will decide, which 2 corners will not be rounded. Hope this is easy to implement.
|
29,618,765 |
This is my issue:
I have 3 forms:
* Form fParent
* Form fChild
* Form OpenForm
I want that When I click a button on Form fChild, it shows Form OpenFormand and hides Form fParentand Form fChild.
How can I do that?
Please help me.
|
2015/04/14
|
[
"https://Stackoverflow.com/questions/29618765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4162835/"
] |
In **Swift 2.3** you could do so by
```
let maskPath = UIBezierPath(roundedRect: anyView.bounds,
byRoundingCorners: [.BottomLeft, .BottomRight],
cornerRadii: CGSize(width: 10.0, height: 10.0))
let shape = CAShapeLayer()
shape.path = maskPath.CGPath
view.layer.mask = shape
```
---
In **Objective-C** you could use the `UIBezierPath` class method
```
bezierPathWithRoundedRect:byRoundingCorners:cornerRadii:
```
example implementation-
```
// set the corner radius to the specified corners of the passed container
- (void)setMaskTo:(UIView*)view byRoundingCorners:(UIRectCorner)corners
{
UIBezierPath *rounded = [UIBezierPath bezierPathWithRoundedRect:view.bounds
byRoundingCorners:corners
cornerRadii:CGSizeMake(10.0, 10.0)];
CAShapeLayer *shape = [[CAShapeLayer alloc] init];
[shape setPath:rounded.CGPath];
view.layer.mask = shape;
}
```
and call the above method as-
```
[self setMaskTo:anyView byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight];
```
|
Here is what you do in **Swift 2.0**
```
var maskPath = UIBezierPath(roundedRect: anyView.bounds,
byRoundingCorners: [.BottomLeft, .BottomRight],
cornerRadii: CGSize(width: 10.0, height: 10.0))
```
|
29,618,765 |
This is my issue:
I have 3 forms:
* Form fParent
* Form fChild
* Form OpenForm
I want that When I click a button on Form fChild, it shows Form OpenFormand and hides Form fParentand Form fChild.
How can I do that?
Please help me.
|
2015/04/14
|
[
"https://Stackoverflow.com/questions/29618765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4162835/"
] |
**Swift 4+, iOS 11+**
If you already have a `UIView` named `myView` referenced as an `IBOutlet`, try adding the following two lines in `ViewDidLoad()` or wherever it's being loaded:
```
myView.layer.cornerRadius = 10
myView.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]
```
You can change the array `[]` to any combination of `MinX`, `MinY`, `MaxX`, and `MaxY` to select the desired corners. The above example rounds the bottom two corners.
This is just another approach, can be a bit simpler depending on your design.
|
In summary, you can create pretty extension like this:
```
extension UIView {
func roundCorners(_ corners: UIRectCorner, radius: Double) {
let maskPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let shape = CAShapeLayer()
shape.path = maskPath.cgPath
layer.mask = shape
}
}
```
Use it like this:
```
view.roundCorners([.topRight, .bottomRight], radius: 10)
```
Here is all corners values:
* .topLeft
* .topRight
* .bottomLeft
* .bottomRight
|
29,618,765 |
This is my issue:
I have 3 forms:
* Form fParent
* Form fChild
* Form OpenForm
I want that When I click a button on Form fChild, it shows Form OpenFormand and hides Form fParentand Form fChild.
How can I do that?
Please help me.
|
2015/04/14
|
[
"https://Stackoverflow.com/questions/29618765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4162835/"
] |
In **Swift 2.3** you could do so by
```
let maskPath = UIBezierPath(roundedRect: anyView.bounds,
byRoundingCorners: [.BottomLeft, .BottomRight],
cornerRadii: CGSize(width: 10.0, height: 10.0))
let shape = CAShapeLayer()
shape.path = maskPath.CGPath
view.layer.mask = shape
```
---
In **Objective-C** you could use the `UIBezierPath` class method
```
bezierPathWithRoundedRect:byRoundingCorners:cornerRadii:
```
example implementation-
```
// set the corner radius to the specified corners of the passed container
- (void)setMaskTo:(UIView*)view byRoundingCorners:(UIRectCorner)corners
{
UIBezierPath *rounded = [UIBezierPath bezierPathWithRoundedRect:view.bounds
byRoundingCorners:corners
cornerRadii:CGSizeMake(10.0, 10.0)];
CAShapeLayer *shape = [[CAShapeLayer alloc] init];
[shape setPath:rounded.CGPath];
view.layer.mask = shape;
}
```
and call the above method as-
```
[self setMaskTo:anyView byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight];
```
|
```swift
extension CACornerMask {
public static var leftBottom : CACornerMask { get { return .layerMinXMaxYCorner}}
public static var rightBottom : CACornerMask { get { return .layerMaxXMaxYCorner}}
public static var leftTop : CACornerMask { get { return .layerMaxXMinYCorner}}
public static var rightTop : CACornerMask { get { return .layerMinXMinYCorner}}
}
extension CALayer {
func roundCorners(_ mask:CACornerMask,corner:CGFloat) {
self.maskedCorners = mask
self.cornerRadius = corner
}
}
self.viewBack.layer.roundCorners([.leftBottom,.rightBottom], corner: 23)
```
|
29,618,765 |
This is my issue:
I have 3 forms:
* Form fParent
* Form fChild
* Form OpenForm
I want that When I click a button on Form fChild, it shows Form OpenFormand and hides Form fParentand Form fChild.
How can I do that?
Please help me.
|
2015/04/14
|
[
"https://Stackoverflow.com/questions/29618765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4162835/"
] |
>
> iOS 11+ Only | You can check iOS usage stats [here](https://developer.apple.com/support/app-store/)
>
>
>
Explanation
===========
Since the `CACornerMask` rawValue is an `UInt` you know that a `CACornerMask` *rawValue* is the sum of each `CACornerMask.Element` *rawValue*
More specifically:
* TopLeft (`layerMinXMinYCorner`) = 1
* TopRight (`layerMaxXMinYCorner`) = 2
* BottomLeft (`layerMinXMaxYCorner`) = 4
* BottomRight (`layerMaxXMaxYCorner`) = 8
So for example if you want **top left** and **top right** corners you can just type `CACornerMask(rawValue: 3)`.
---
Example
========
Below is a simple extension of `UIView`
```
extension UIView {
enum Corner:Int {
case bottomRight = 0,
topRight,
bottomLeft,
topLeft
}
private func parseCorner(corner: Corner) -> CACornerMask.Element {
let corners: [CACornerMask.Element] = [.layerMaxXMaxYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMinXMinYCorner]
return corners[corner.rawValue]
}
private func createMask(corners: [Corner]) -> UInt {
return corners.reduce(0, { (a, b) -> UInt in
return a + parseCorner(corner: b).rawValue
})
}
func roundCorners(corners: [Corner], amount: CGFloat = 5) {
layer.cornerRadius = amount
let maskedCorners: CACornerMask = CACornerMask(rawValue: createMask(corners: corners))
layer.maskedCorners = maskedCorners
}
}
```
You can use it this like:
```
let myRect = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
myRect.roundCorners(corners: [.topRight, .topLeft])
```
|
**Swift 4:**
```
let maskPath = UIBezierPath(
roundedRect: view.bounds,
byRoundingCorners: [.allCorners],
cornerRadii: CGSize(width: 10.0, height: 10.0)
)
let shape = CAShapeLayer()
shape.path = maskPath.cgPath
view.layer.mask = shape
```
|
29,618,765 |
This is my issue:
I have 3 forms:
* Form fParent
* Form fChild
* Form OpenForm
I want that When I click a button on Form fChild, it shows Form OpenFormand and hides Form fParentand Form fChild.
How can I do that?
Please help me.
|
2015/04/14
|
[
"https://Stackoverflow.com/questions/29618765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4162835/"
] |
Update: See [this answer](https://stackoverflow.com/a/50396485/308315) below for Swift 4 / iOS 11 which is much, much easier
---
Here's a quick Swift 3 extension you can use to do rounding and optional borders.
Note: if you're using autolayout, you may need to call this in one of the view lifecycle callbacks like `viewDidLayoutSubviews` or `layoutSubviews` after the view has been constrained.
```
import UIKit
extension UIView {
/**
Rounds the given set of corners to the specified radius
- parameter corners: Corners to round
- parameter radius: Radius to round to
*/
func round(corners: UIRectCorner, radius: CGFloat) {
_ = _round(corners: corners, radius: radius)
}
/**
Rounds the given set of corners to the specified radius with a border
- parameter corners: Corners to round
- parameter radius: Radius to round to
- parameter borderColor: The border color
- parameter borderWidth: The border width
*/
func round(corners: UIRectCorner, radius: CGFloat, borderColor: UIColor, borderWidth: CGFloat) {
let mask = _round(corners: corners, radius: radius)
addBorder(mask: mask, borderColor: borderColor, borderWidth: borderWidth)
}
/**
Fully rounds an autolayout view (e.g. one with no known frame) with the given diameter and border
- parameter diameter: The view's diameter
- parameter borderColor: The border color
- parameter borderWidth: The border width
*/
func fullyRound(diameter: CGFloat, borderColor: UIColor, borderWidth: CGFloat) {
layer.masksToBounds = true
layer.cornerRadius = diameter / 2
layer.borderWidth = borderWidth
layer.borderColor = borderColor.cgColor;
}
}
private extension UIView {
@discardableResult func _round(corners: UIRectCorner, radius: CGFloat) -> CAShapeLayer {
let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
return mask
}
func addBorder(mask: CAShapeLayer, borderColor: UIColor, borderWidth: CGFloat) {
let borderLayer = CAShapeLayer()
borderLayer.path = mask.path
borderLayer.fillColor = UIColor.clear.cgColor
borderLayer.strokeColor = borderColor.cgColor
borderLayer.lineWidth = borderWidth
borderLayer.frame = bounds
layer.addSublayer(borderLayer)
}
}
```
|
In summary, you can create pretty extension like this:
```
extension UIView {
func roundCorners(_ corners: UIRectCorner, radius: Double) {
let maskPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let shape = CAShapeLayer()
shape.path = maskPath.cgPath
layer.mask = shape
}
}
```
Use it like this:
```
view.roundCorners([.topRight, .bottomRight], radius: 10)
```
Here is all corners values:
* .topLeft
* .topRight
* .bottomLeft
* .bottomRight
|
29,618,765 |
This is my issue:
I have 3 forms:
* Form fParent
* Form fChild
* Form OpenForm
I want that When I click a button on Form fChild, it shows Form OpenFormand and hides Form fParentand Form fChild.
How can I do that?
Please help me.
|
2015/04/14
|
[
"https://Stackoverflow.com/questions/29618765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4162835/"
] |
**Swift 5:** For top-left and top-right round corners.
```
yourView.layer.cornerRadius = 12
yourView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
```
|
Objective-C version of iWasRobbed's answer:
UIView+RoundCorners.h
```
#import <UIKit/UIKit.h>
@interface UIView (RoundCorners)
/**
Rounds the given set of corners to the specified radius
- parameter corners: Corners to round
- parameter radius: Radius to round to
*/
- (void)roundCorners:(UIRectCorner)corners radius:(CGFloat)radius;
/**
Rounds the given set of corners to the specified radius with a border
- parameter corners: Corners to round
- parameter radius: Radius to round to
- parameter borderColor: The border color
- parameter borderWidth: The border width
*/
- (void)roundCorners:(UIRectCorner)corners radius:(CGFloat)radius borderColor:(UIColor *)borderColor borderWidth:(CGFloat)borderWidth;
/**
Fully rounds an autolayout view (e.g. one with no known frame) with the given diameter and border
- parameter diameter: The view's diameter
- parameter borderColor: The border color
- parameter borderWidth: The border width
*/
- (void)fullyRoundWithDiameter:(CGFloat)diameter borderColor:(UIColor *)borderColor borderWidth:(CGFloat)borderWidth;
@end
```
UIView+RoundCorners.m
```
#import "UIView+RoundCorners.h"
@implementation UIView (RoundCorners)
- (void)roundCorners:(UIRectCorner)corners radius:(CGFloat)radius {
[self _roundCorners:corners radius:radius];
}
- (void)roundCorners:(UIRectCorner)corners radius:(CGFloat)radius borderColor:(UIColor *)borderColor borderWidth:(CGFloat)borderWidth {
CAShapeLayer *mask = [self _roundCorners:corners radius:radius];
[self addBorderWithMask:mask borderColor:borderColor borderWidth:borderWidth];
}
- (void)fullyRoundWithDiameter:(CGFloat)diameter borderColor:(UIColor *)borderColor borderWidth:(CGFloat)borderWidth {
self.layer.masksToBounds = YES;
self.layer.cornerRadius = diameter / 2;
self.layer.borderWidth = borderWidth;
self.layer.borderColor = borderColor.CGColor;
}
- (CAShapeLayer *)_roundCorners:(UIRectCorner)corners radius:(CGFloat)radius {
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:corners cornerRadii:CGSizeMake(radius, radius)];
CAShapeLayer *mask = [CAShapeLayer layer];
mask.path = path.CGPath;
self.layer.mask = mask;
return mask;
}
- (void)addBorderWithMask:(CAShapeLayer *)mask borderColor:(UIColor *)borderColor borderWidth:(CGFloat)borderWidth {
CAShapeLayer *borderLayer = [CAShapeLayer layer];
borderLayer.path = mask.path;
borderLayer.fillColor = UIColor.clearColor.CGColor;
borderLayer.strokeColor = borderColor.CGColor;
borderLayer.lineWidth = borderWidth;
borderLayer.frame = self.bounds;
[self.layer addSublayer:borderLayer];
}
@end
```
|
29,618,765 |
This is my issue:
I have 3 forms:
* Form fParent
* Form fChild
* Form OpenForm
I want that When I click a button on Form fChild, it shows Form OpenFormand and hides Form fParentand Form fChild.
How can I do that?
Please help me.
|
2015/04/14
|
[
"https://Stackoverflow.com/questions/29618765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4162835/"
] |
Up-to-date for 2021 ...
=======================
Please note that syntax/systems have changed a lot since this question was asked a long time ago!
[](https://i.stack.imgur.com/DFlsB.png)
```
import UIKit
@IBDesignable
class RoundedEnds: UIView {
override func layoutSubviews() {
super.layoutSubviews()
setup()
}
func setup() {
let r = self.bounds.size.height / 2
let path = UIBezierPath(roundedRect: self.bounds, cornerRadius:r)
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
}
}
```
For only some corners, just change the `path` line of code to:
[](https://i.stack.imgur.com/mRvi4.png)
```
let path = UIBezierPath(
roundedRect: self.bounds,
byRoundingCorners: [.topLeft,.topRight],
cornerRadii: CGSize(width: r, height: r))
```
|
Updated iWasRobbed's answer to work with the Swift 3.0 GM version:
```
import UIKit
extension UIView {
/**
Rounds the given set of corners to the specified radius
- parameter corners: Corners to round
- parameter radius: Radius to round to
*/
func round(corners: UIRectCorner, radius: CGFloat) {
_round(corners: corners, radius: radius)
}
/**
Rounds the given set of corners to the specified radius with a border
- parameter corners: Corners to round
- parameter radius: Radius to round to
- parameter borderColor: The border color
- parameter borderWidth: The border width
*/
func round(corners: UIRectCorner, radius: CGFloat, borderColor: UIColor, borderWidth: CGFloat) {
let mask = _round(corners: corners, radius: radius)
addBorder(mask: mask, borderColor: borderColor, borderWidth: borderWidth)
}
/**
Fully rounds an autolayout view (e.g. one with no known frame) with the given diameter and border
- parameter diameter: The view's diameter
- parameter borderColor: The border color
- parameter borderWidth: The border width
*/
func fullyRound(diameter: CGFloat, borderColor: UIColor, borderWidth: CGFloat) {
layer.masksToBounds = true
layer.cornerRadius = diameter / 2
layer.borderWidth = borderWidth
layer.borderColor = borderColor.cgColor;
}
}
private extension UIView {
@discardableResult func _round(corners: UIRectCorner, radius: CGFloat) -> CAShapeLayer {
let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
return mask
}
func addBorder(mask: CAShapeLayer, borderColor: UIColor, borderWidth: CGFloat) {
let borderLayer = CAShapeLayer()
borderLayer.path = mask.path
borderLayer.fillColor = UIColor.clear.cgColor
borderLayer.strokeColor = borderColor.cgColor
borderLayer.lineWidth = borderWidth
borderLayer.frame = bounds
layer.addSublayer(borderLayer)
}
}
```
|
29,618,765 |
This is my issue:
I have 3 forms:
* Form fParent
* Form fChild
* Form OpenForm
I want that When I click a button on Form fChild, it shows Form OpenFormand and hides Form fParentand Form fChild.
How can I do that?
Please help me.
|
2015/04/14
|
[
"https://Stackoverflow.com/questions/29618765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4162835/"
] |
>
> iOS 11+ Only | You can check iOS usage stats [here](https://developer.apple.com/support/app-store/)
>
>
>
Explanation
===========
Since the `CACornerMask` rawValue is an `UInt` you know that a `CACornerMask` *rawValue* is the sum of each `CACornerMask.Element` *rawValue*
More specifically:
* TopLeft (`layerMinXMinYCorner`) = 1
* TopRight (`layerMaxXMinYCorner`) = 2
* BottomLeft (`layerMinXMaxYCorner`) = 4
* BottomRight (`layerMaxXMaxYCorner`) = 8
So for example if you want **top left** and **top right** corners you can just type `CACornerMask(rawValue: 3)`.
---
Example
========
Below is a simple extension of `UIView`
```
extension UIView {
enum Corner:Int {
case bottomRight = 0,
topRight,
bottomLeft,
topLeft
}
private func parseCorner(corner: Corner) -> CACornerMask.Element {
let corners: [CACornerMask.Element] = [.layerMaxXMaxYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMinXMinYCorner]
return corners[corner.rawValue]
}
private func createMask(corners: [Corner]) -> UInt {
return corners.reduce(0, { (a, b) -> UInt in
return a + parseCorner(corner: b).rawValue
})
}
func roundCorners(corners: [Corner], amount: CGFloat = 5) {
layer.cornerRadius = amount
let maskedCorners: CACornerMask = CACornerMask(rawValue: createMask(corners: corners))
layer.maskedCorners = maskedCorners
}
}
```
You can use it this like:
```
let myRect = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
myRect.roundCorners(corners: [.topRight, .topLeft])
```
|
One simple hack could be as following. Take views like below example in image. **Red View** will have rounded corners and **Yellow View** (inside Red View) will prevent the corners to be rounded
[](https://i.stack.imgur.com/PdCxM.png)
Now write below code for **Red View**.
```
self.myView.layer.cornerRadius = 15
```
Make sure you don't write any code as **clipsToBounds = true** or **masksToBounds = true**.
Below image is the result
[](https://i.stack.imgur.com/fMoDU.png)
Placement of **Yellow View** will decide, which 2 corners will not be rounded. Hope this is easy to implement.
|
926,721 |
I would be very grateful if someone can help me with the following assignment:
I'm given an $n\times n$ matrix $A$.
If $A \neq I,0$ and $A = A^2$, I need to prove that $\lambda=0$ and $\lambda=1$ are $A$'s eigenvalues and that they are $A$'s only eigenvalues.
|
2014/09/10
|
[
"https://math.stackexchange.com/questions/926721",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/175107/"
] |
Suppose $\;0\neq v\in V\; $ is an eigenvector of $\;A\;$with eigenvalue $\;\lambda\;$ , then
$$\lambda v= Av=A^2v=A(\lambda v)=\lambda Av=\lambda^2v$$
So
$$(\lambda^2-\lambda)v=0\implies \lambda^2=\lambda\iff \lambda=0,1$$
$\;A\;$ is a zero of $\;x^2-x\;$ , which means this is the matrix's minimal polynomial (why?), and thus the above two are indeed eigenvalues of $\;A\;$
|
Suppose $A$ were invertible. Then, $$A^2 = A \implies A^2 \cdot A^{-1} = A\cdot A^{-1} \implies A = I,$$
contrary to our hypothesis. Therefore, $A$ is not invertible and so $\det A = 0$. Since the determinant is the product of eigenvalues, $A$ must have $0$ as an eigenvalue.
Suppose $\lambda = 0$ were the only eigenvalue. Then $(A-I)v \neq 0$ for all non-zero $v$ and hence $A-I$ is full rank. But since $A^2=A$, we have $(A-I)A = A^2-A = 0$, so every column of $A$ is in the null space of $A-I$, implying that $A = 0$, which contradicts our hypothesis.
|
25,661,580 |
I've got a list of daily values ordered into a list of dicts like so:
```
vals = [
{'date': '1-1-2014', 'a': 10, 'b': 33.5, 'c': 82, 'notes': 'high repeat rate'},
{'date': '2-1-2014', 'a': 5, 'b': 11.43, 'c': 182, 'notes': 'normal operations'},
{'date': '3-1-2014', 'a': 0, 'b': 0.5, 'c': 2, 'notes': 'high failure rate'},
...]
```
What I'd like to do is get an average of a, b & c for the month.
Is there a better way than doing something like:
```
val_points = {}
val_len = len(vals)
for day in vals:
for p in ['a', 'b', 'c']:
if val_points.has_key(p):
val_points += day[p]
else:
val_points = day[p]
val_avg = dict([(i, val_points[i] / val_len] for p in val_points])
```
I haven't run the code above, may have glitches but I hope I'm getting the idea across. I know there's probably a better way using some combination of operator, itertools and collections.
|
2014/09/04
|
[
"https://Stackoverflow.com/questions/25661580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/80460/"
] |
```
{p:sum(map(lambda x:x[p],vals))/len(vals) for p in ['a','b','c']}
```
**output:**
```
{'a': 5, 'c': 88, 'b': 15.143333333333333}
```
|
This might be slightly longer than Elisha's answer, but there are less intermediate data structures, hence it *might* be faster:
```
KEYS = ['a', 'b', 'c']
def sum_and_count(sums_and_counts, item, key):
prev_sum, prev_count = sums_and_counts.get(key, (0,0)) # using get to have a fall-back if there is nothing in our sums_and_counts
return (prev_sum+item.get(key, 0), prev_count+1) # using get to have a 0 default for a non-existing key in item
sums_and_counts = reduce(lambda sc, item: {key: sum_and_count(sc, item, key) for key in KEYS}, vals, {})
averages = {k:float(total)/no for (k,(total,no)) in sums_and_counts.iteritems()}
print averages
```
**output**:
```
{'a': 5.0, 'c': 88.66666666666667, 'b': 15.143333333333333}
```
|
25,661,580 |
I've got a list of daily values ordered into a list of dicts like so:
```
vals = [
{'date': '1-1-2014', 'a': 10, 'b': 33.5, 'c': 82, 'notes': 'high repeat rate'},
{'date': '2-1-2014', 'a': 5, 'b': 11.43, 'c': 182, 'notes': 'normal operations'},
{'date': '3-1-2014', 'a': 0, 'b': 0.5, 'c': 2, 'notes': 'high failure rate'},
...]
```
What I'd like to do is get an average of a, b & c for the month.
Is there a better way than doing something like:
```
val_points = {}
val_len = len(vals)
for day in vals:
for p in ['a', 'b', 'c']:
if val_points.has_key(p):
val_points += day[p]
else:
val_points = day[p]
val_avg = dict([(i, val_points[i] / val_len] for p in val_points])
```
I haven't run the code above, may have glitches but I hope I'm getting the idea across. I know there's probably a better way using some combination of operator, itertools and collections.
|
2014/09/04
|
[
"https://Stackoverflow.com/questions/25661580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/80460/"
] |
```
{p:sum(map(lambda x:x[p],vals))/len(vals) for p in ['a','b','c']}
```
**output:**
```
{'a': 5, 'c': 88, 'b': 15.143333333333333}
```
|
If you have multiple month's data, Pandas will make your life a lot easier:
```
df = pandas.DataFrame(vals)
df.date = [pandas.datetools.parse(d, dayfirst=True) for d in df.date]
df.set_index('date', inplace=True)
means = df.resample('m', how='mean')
```
Results in:
```
a b c
date
2014-01-31 5 15.143333 88.666667
```
|
25,661,580 |
I've got a list of daily values ordered into a list of dicts like so:
```
vals = [
{'date': '1-1-2014', 'a': 10, 'b': 33.5, 'c': 82, 'notes': 'high repeat rate'},
{'date': '2-1-2014', 'a': 5, 'b': 11.43, 'c': 182, 'notes': 'normal operations'},
{'date': '3-1-2014', 'a': 0, 'b': 0.5, 'c': 2, 'notes': 'high failure rate'},
...]
```
What I'd like to do is get an average of a, b & c for the month.
Is there a better way than doing something like:
```
val_points = {}
val_len = len(vals)
for day in vals:
for p in ['a', 'b', 'c']:
if val_points.has_key(p):
val_points += day[p]
else:
val_points = day[p]
val_avg = dict([(i, val_points[i] / val_len] for p in val_points])
```
I haven't run the code above, may have glitches but I hope I'm getting the idea across. I know there's probably a better way using some combination of operator, itertools and collections.
|
2014/09/04
|
[
"https://Stackoverflow.com/questions/25661580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/80460/"
] |
```
{p:sum(map(lambda x:x[p],vals))/len(vals) for p in ['a','b','c']}
```
**output:**
```
{'a': 5, 'c': 88, 'b': 15.143333333333333}
```
|
As you want to calculate average by month(Here considering the date format in 'dd-mm-yyyy'):
```
vals = [
{'date': '1-1-2014', 'a': 10, 'b': 33.5, 'c': 82, 'notes': 'high repeat rate'},
{'date': '2-1-2014', 'a': 5, 'b': 11.43, 'c': 182, 'notes': 'normal operations'},
{'date': '3-1-2014', 'a': 20, 'b': 0.5, 'c': 2, 'notes': 'high failure rate'},
{'date': '3-2-2014', 'a': 0, 'b': 0.5, 'c': 2, 'notes': 'high failure rate'},
{'date': '4-2-2014', 'a': 20, 'b': 0.5, 'c': 2, 'notes': 'high failure rate'}
]
month = {}
for x in vals:
newKey = x['date'].split('-')[1]
if newKey not in month:
month[newKey] = {}
for k in 'abc':
if k in month[newKey]:
month[newKey][k].append(x[k])
else:
month[newKey][k] = [x[k]]
output = {}
for y in month:
if y not in output:
output[y] = {}
for z in month[y]:
output[y][z] = sum(month[y][z])/float(len(month[y][z]))
print output
```
**OUTPUT:**
```
{'1': {'a': 11.666666666666666, 'c': 88.66666666666667, 'b': 15.143333333333333},
'2': {'a': 10.0, 'c': 2.0, 'b': 0.5}}
```
|
25,661,580 |
I've got a list of daily values ordered into a list of dicts like so:
```
vals = [
{'date': '1-1-2014', 'a': 10, 'b': 33.5, 'c': 82, 'notes': 'high repeat rate'},
{'date': '2-1-2014', 'a': 5, 'b': 11.43, 'c': 182, 'notes': 'normal operations'},
{'date': '3-1-2014', 'a': 0, 'b': 0.5, 'c': 2, 'notes': 'high failure rate'},
...]
```
What I'd like to do is get an average of a, b & c for the month.
Is there a better way than doing something like:
```
val_points = {}
val_len = len(vals)
for day in vals:
for p in ['a', 'b', 'c']:
if val_points.has_key(p):
val_points += day[p]
else:
val_points = day[p]
val_avg = dict([(i, val_points[i] / val_len] for p in val_points])
```
I haven't run the code above, may have glitches but I hope I'm getting the idea across. I know there's probably a better way using some combination of operator, itertools and collections.
|
2014/09/04
|
[
"https://Stackoverflow.com/questions/25661580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/80460/"
] |
This might be slightly longer than Elisha's answer, but there are less intermediate data structures, hence it *might* be faster:
```
KEYS = ['a', 'b', 'c']
def sum_and_count(sums_and_counts, item, key):
prev_sum, prev_count = sums_and_counts.get(key, (0,0)) # using get to have a fall-back if there is nothing in our sums_and_counts
return (prev_sum+item.get(key, 0), prev_count+1) # using get to have a 0 default for a non-existing key in item
sums_and_counts = reduce(lambda sc, item: {key: sum_and_count(sc, item, key) for key in KEYS}, vals, {})
averages = {k:float(total)/no for (k,(total,no)) in sums_and_counts.iteritems()}
print averages
```
**output**:
```
{'a': 5.0, 'c': 88.66666666666667, 'b': 15.143333333333333}
```
|
If you have multiple month's data, Pandas will make your life a lot easier:
```
df = pandas.DataFrame(vals)
df.date = [pandas.datetools.parse(d, dayfirst=True) for d in df.date]
df.set_index('date', inplace=True)
means = df.resample('m', how='mean')
```
Results in:
```
a b c
date
2014-01-31 5 15.143333 88.666667
```
|
25,661,580 |
I've got a list of daily values ordered into a list of dicts like so:
```
vals = [
{'date': '1-1-2014', 'a': 10, 'b': 33.5, 'c': 82, 'notes': 'high repeat rate'},
{'date': '2-1-2014', 'a': 5, 'b': 11.43, 'c': 182, 'notes': 'normal operations'},
{'date': '3-1-2014', 'a': 0, 'b': 0.5, 'c': 2, 'notes': 'high failure rate'},
...]
```
What I'd like to do is get an average of a, b & c for the month.
Is there a better way than doing something like:
```
val_points = {}
val_len = len(vals)
for day in vals:
for p in ['a', 'b', 'c']:
if val_points.has_key(p):
val_points += day[p]
else:
val_points = day[p]
val_avg = dict([(i, val_points[i] / val_len] for p in val_points])
```
I haven't run the code above, may have glitches but I hope I'm getting the idea across. I know there's probably a better way using some combination of operator, itertools and collections.
|
2014/09/04
|
[
"https://Stackoverflow.com/questions/25661580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/80460/"
] |
As you want to calculate average by month(Here considering the date format in 'dd-mm-yyyy'):
```
vals = [
{'date': '1-1-2014', 'a': 10, 'b': 33.5, 'c': 82, 'notes': 'high repeat rate'},
{'date': '2-1-2014', 'a': 5, 'b': 11.43, 'c': 182, 'notes': 'normal operations'},
{'date': '3-1-2014', 'a': 20, 'b': 0.5, 'c': 2, 'notes': 'high failure rate'},
{'date': '3-2-2014', 'a': 0, 'b': 0.5, 'c': 2, 'notes': 'high failure rate'},
{'date': '4-2-2014', 'a': 20, 'b': 0.5, 'c': 2, 'notes': 'high failure rate'}
]
month = {}
for x in vals:
newKey = x['date'].split('-')[1]
if newKey not in month:
month[newKey] = {}
for k in 'abc':
if k in month[newKey]:
month[newKey][k].append(x[k])
else:
month[newKey][k] = [x[k]]
output = {}
for y in month:
if y not in output:
output[y] = {}
for z in month[y]:
output[y][z] = sum(month[y][z])/float(len(month[y][z]))
print output
```
**OUTPUT:**
```
{'1': {'a': 11.666666666666666, 'c': 88.66666666666667, 'b': 15.143333333333333},
'2': {'a': 10.0, 'c': 2.0, 'b': 0.5}}
```
|
If you have multiple month's data, Pandas will make your life a lot easier:
```
df = pandas.DataFrame(vals)
df.date = [pandas.datetools.parse(d, dayfirst=True) for d in df.date]
df.set_index('date', inplace=True)
means = df.resample('m', how='mean')
```
Results in:
```
a b c
date
2014-01-31 5 15.143333 88.666667
```
|
43,146,388 |
```js
import React, { Component } from 'react';
let _ = require('lodash');
import {bindActionCreators} from "redux";
import {connect} from 'react-redux';
import {fetchedBeaconsEdit} from '../../actions/';
import {editBeacon} from '../../actions/index';
// TODO - come up with a decent name
class InfoRow extends Component {
render() {
return (
<tr>
<td>
{ this.props.beacon === "name"
|| this.props.beacon === "major"
|| this.props.beacon === "minor"
|| this.props.beacon === "beaconType" ?
<span>{this.props.beacon}<span className="font-css top">*</span></span>:
<span>{this.props.beacon}</span>
}
</td>
<td>
{ this.props.beacon !== "beaconType" &&
this.props.beacon !== "uuid" &&
this.props.beacon !== "status" &&
this.props.beacon !== "store"&&
this.props.beacon !== "group" ?
<div>
<input type="text"
className="form-control"
defaultValue={this.props.beaconValue}
name={this.props.beaconValue}
onChange={(e) =>this.props.handleInputChangeProp(e.target.value)}
/></div>:
this.props.beacon === "uuid" && this.props.beacon === "status" && this.props.beacon=== "store"?
<span></span>:
this.props.beacon === "beaconType"?
<select defaultValue={this.props.beaconValue} name={this.props.beaconValue} className="form-control" onChange={(e) =>this.props.handleInputChangeProp(e.target.value)}>
<option name="ibeacon">IBEACON</option>
<option name="eddystone">EDDYSTONE</option>
</select>:this.props.beaconValue
}
</td>
</tr>
)
}
}
class BeaconEdit extends Component {
constructor(props){
super(props);
this.state = {
};
this.handleInputChange = this.handleInputChange.bind(this);
this.handleClick = this.handleClick.bind(this);
}
handleInputChange(beacon, value) {
this.setState({
[beacon]: value
});
}
handleClick = () =>{
Object.keys(this.props.ebcn).map((key)=> {
if (this.state[key] !== undefined) {
this.props.editBeaconGroup[key]=this.state[key];
}
})
this.props.handleSubmitProp(this.props.editBeaconGroup);
}
render() {
const rows = [];
let a = this.props.ebcn;
Object.keys(this.props.ebcn).map((keyName, keyIndex) =>{
if (keyName === "store" || keyName === "group") {
return rows.push(<InfoRow beacon={keyName} beaconValue={a[keyName].name.toString()} name={this.state[keyName]} key={keyIndex} handleInputChangeProp={(inp) =>this.handleInputChange(keyName, inp)}/>);
}else{
return rows.push(<InfoRow beacon={keyName} beaconValue={a[keyName].toString()} name={this.state[keyName]} key={keyIndex} handleInputChangeProp={(inp) =>this.handleInputChange(keyName, inp)}/>);
}
});
return (
<div className="col-md-6">
<div className="">
<table className="table table-clear">
<tbody>
{rows}
</tbody>
</table>
</div>
<div className="px-1" >
<button className="btn btn-sm btn-info btn-size btn-block" onClick={this.handleClick}>Save</button>
</div>
</div>
)
}
}
class BeaconDetailEditComponent extends Component {
constructor(props){
super(props);
this.state = {
editbeacons: {}
};
this.handleSubmit = this.handleSubmit.bind(this);
this.validateName = this.validateName.bind(this);
this.validateMajor = this.validateMajor.bind(this);
this.validateMinor = this.validateMinor.bind(this);
}
validateMinor = (minor) => {
var re = /^[0-9]+$/;
return re.test(minor);
}
validateMajor = (major) => {
var re = /^[0-9]+$/;
return re.test(major);
}
validateName = (name) => {
var re = /^[A-Za-z ]+$/;
return re.test(name);
};
handleSubmit (beaconedited) {
console.log(beaconedited.name);
if (!this.validateName(beaconedited.name)) {
alert('Name can not be an integer')
}
else if (!this.validateMajor(beaconedited.major)) {
alert('Major number can only be an integer')
}
else if (beaconedited.major.length > 5) {
alert('Major number can not exceed 5 digits')
}
else if (!this.validateMinor(beaconedited.minor)) {
alert('Minor number can only be an integer')
}
else if (beaconedited.major > 65535) {
alert('Major number can not exceed the limit of 65535')
}
else if (beaconedited.minor > 65535) {
alert('Minor number can not exceed the limit of 65535')
}
else {
this.props.editBeacon(beaconedited, this.props.location.query.id);
}
}
componentWillMount = () => {
this.props.fetchedBeaconsEdit(this.props.location.query.id);
};
render() {
return (
<div className="container px-3 mr-3">
<div>
<div className="col-md-6 col-md-offset-3"><h1>Edit Beacon Information</h1></div>
</div>
<br/>
<br/>
{ this.props.ebcn != null?
<div>
<BeaconEdit ebcn={this.props.ebcn} handleSubmitProp={this.handleSubmit} editBeaconGroup={this.state.editbeacons}/>
</div> :
<center><img className="gif-size" src={'img/avatars/default.gif'} alt="Loading"/></center>
}
</div>
)
}
}
function mapStateToProps(state) {
return {
eBeacon: state.eBeacon,
ebcn: state.beacons
}
}
function matchDispatchToProps(dispatch){
return bindActionCreators({editBeacon: editBeacon, fetchedBeaconsEdit: fetchedBeaconsEdit}, dispatch);
}
export default connect(mapStateToProps, matchDispatchToProps)(BeaconDetailEditComponent);
```
[](https://i.stack.imgur.com/1IqIT.png)
[](https://i.stack.imgur.com/gHEi3.png)
i had provided the code snippet
what i am doing is
i had fetched the values from the server and were shown in the fields and I'm making this page as editable form
what i want to do is now to take the values changed or changed by the user and to print them in console.
i had applied handleInputChange and its showing changed values while changing but i want to see those values in console on button click as well
how to do it?
|
2017/03/31
|
[
"https://Stackoverflow.com/questions/43146388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7645971/"
] |
This is correct, because, `scanf()` returns number of successfully matched and converted elements. Considering proper input in your case, every time your input passes the conversion, so you get to see the value 1.
Point to note, `scanf()` **does not return** the scanned value itself, it stores the value in the passed argument.
Quoting `C11`, chapter §7.21.6.4
>
> [...] the `scanf` function returns the
> number of input items assigned, which can be fewer than provided for, or even zero, in
> the event of an early matching failure.
>
>
>
|
The return type of scanf is to indicate if it successfully read an integer.
This will do what you're expecting
```
#include <stdio.h>
int main() {
int days = 0;
scanf("%d", &days);
printf("%d", days);
return 0;
}
```
|
34,072,768 |
I am creating a column family in Cassandra and I expect the column order to match the one I am specifying in the create clause.
This
```
CREATE TABLE cf.mycf (
timestamp timestamp,
id text,
score int,
type text,
publisher_id text,
embed_url text,
PRIMARY KEY (timestamp, id, score)
) WITH bloom_filter_fp_chance = 0.01
AND comment = ''
AND dclocal_read_repair_chance = 0.1
AND default_time_to_live = 0
AND gc_grace_seconds = 864000
AND max_index_interval = 2048
AND memtable_flush_period_in_ms = 0
AND min_index_interval = 128
AND read_repair_chance = 0.0
AND speculative_retry = '99.0PERCENTILE'
AND caching = {
'keys' : 'ALL',
'rows_per_partition' : 'NONE'
}
AND compression = {
'chunk_length_kb' : 64,
'crc_check_chance' : 1.0,
'sstable_compression' : 'LZ4Compressor'
}
AND compaction = {
'base_time_seconds' : 60,
'class' : 'DateTieredCompactionStrategy',
'enabled' : true,
'max_sstable_age_days' : 365,
'max_threshold' : 32,
'min_threshold' : 4,
'timestamp_resolution' : 'MICROSECONDS',
'tombstone_compaction_interval' : 86400,
'tombstone_threshold' : 0.2,
'unchecked_tombstone_compaction' : false
};
```
Should create a table like :
`timestamp ,id ,score , type, id ,embed_url`
Instead I am getting this:
```
timestamp timestamp,
id text,
score int,
embed_url text,
publisher_id text,
type text,
```
I've created quite a few tables in the same way and this never happened so any help would be appreciated.
I put the `id` and `score` as keys to show that these keep their respective position. while the actual scheme I am looking for is only the timestamp to be the primary key.
|
2015/12/03
|
[
"https://Stackoverflow.com/questions/34072768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1143013/"
] |
Looks like there is no such thing as fields order in cassandra.
```
The others columns are displayed in alphabetical order by Cassandra.
```
<http://docs.datastax.com/en/cql/3.1/cql/ddl/ddl_compound_keys_c.html>
|
You should make a clear distinction on how *you* want the data to be presented and how it is effectively presented to you. Moreover, you should not rely on the ordinal position of the fields but only on their names.
In order to be efficient, and against your will (you specified an order to the columns when you modeled your schema), Cassandra needs to store the columns in a particular order, and for simplicity this reflects on how it (the CQL interface or the driver) will give back your data.
I suggest you to have a deep insight on how Cassandra stores data (column names included!) in [Understanding How CQL3 Maps to Cassandra’s Internal Data Structure](http://opensourceconnections.com/blog/2013/07/24/understanding-how-cql3-maps-to-cassandras-internal-data-structure/).
By the way, if you absolutely need to keep *your* order at application level (and are too lazy to specify all the fields in the `SELECT` instead of using `SELECT *`), you need to create an abstraction interface on your own, something like creating an ordered "field names" array (your order):
```
String myorder[] = { "timestamp", "id", "score", "type", "publisher_id", "embed_url"};
```
and then use this as a map in loops using ordinal values.
|
34,072,768 |
I am creating a column family in Cassandra and I expect the column order to match the one I am specifying in the create clause.
This
```
CREATE TABLE cf.mycf (
timestamp timestamp,
id text,
score int,
type text,
publisher_id text,
embed_url text,
PRIMARY KEY (timestamp, id, score)
) WITH bloom_filter_fp_chance = 0.01
AND comment = ''
AND dclocal_read_repair_chance = 0.1
AND default_time_to_live = 0
AND gc_grace_seconds = 864000
AND max_index_interval = 2048
AND memtable_flush_period_in_ms = 0
AND min_index_interval = 128
AND read_repair_chance = 0.0
AND speculative_retry = '99.0PERCENTILE'
AND caching = {
'keys' : 'ALL',
'rows_per_partition' : 'NONE'
}
AND compression = {
'chunk_length_kb' : 64,
'crc_check_chance' : 1.0,
'sstable_compression' : 'LZ4Compressor'
}
AND compaction = {
'base_time_seconds' : 60,
'class' : 'DateTieredCompactionStrategy',
'enabled' : true,
'max_sstable_age_days' : 365,
'max_threshold' : 32,
'min_threshold' : 4,
'timestamp_resolution' : 'MICROSECONDS',
'tombstone_compaction_interval' : 86400,
'tombstone_threshold' : 0.2,
'unchecked_tombstone_compaction' : false
};
```
Should create a table like :
`timestamp ,id ,score , type, id ,embed_url`
Instead I am getting this:
```
timestamp timestamp,
id text,
score int,
embed_url text,
publisher_id text,
type text,
```
I've created quite a few tables in the same way and this never happened so any help would be appreciated.
I put the `id` and `score` as keys to show that these keep their respective position. while the actual scheme I am looking for is only the timestamp to be the primary key.
|
2015/12/03
|
[
"https://Stackoverflow.com/questions/34072768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1143013/"
] |
Looks like there is no such thing as fields order in cassandra.
```
The others columns are displayed in alphabetical order by Cassandra.
```
<http://docs.datastax.com/en/cql/3.1/cql/ddl/ddl_compound_keys_c.html>
|
Keep in mind that the rendering of the CQL string in DESCRIBE in cqlsh is just a [function call in the python driver](https://github.com/datastax/python-driver/blob/806e0b0021ca283842ea7ce48f27305725658e3b/cassandra/metadata.py#L1150) iterating over the metadata. It has nothing to do with how C\* stores or sends its results.
If it matters you can set the order. When you Insert you can define the order explicitly
```
INSERT INTO keyspace_name.table_name
( identifier, column_name, whatever, order)
VALUES ( value, value ... )
```
When you do a select you can define the order explicitly.
```
SELECT identifier, whatever, order, column_name FROM keyspace_name.table_name
```
|
34,072,768 |
I am creating a column family in Cassandra and I expect the column order to match the one I am specifying in the create clause.
This
```
CREATE TABLE cf.mycf (
timestamp timestamp,
id text,
score int,
type text,
publisher_id text,
embed_url text,
PRIMARY KEY (timestamp, id, score)
) WITH bloom_filter_fp_chance = 0.01
AND comment = ''
AND dclocal_read_repair_chance = 0.1
AND default_time_to_live = 0
AND gc_grace_seconds = 864000
AND max_index_interval = 2048
AND memtable_flush_period_in_ms = 0
AND min_index_interval = 128
AND read_repair_chance = 0.0
AND speculative_retry = '99.0PERCENTILE'
AND caching = {
'keys' : 'ALL',
'rows_per_partition' : 'NONE'
}
AND compression = {
'chunk_length_kb' : 64,
'crc_check_chance' : 1.0,
'sstable_compression' : 'LZ4Compressor'
}
AND compaction = {
'base_time_seconds' : 60,
'class' : 'DateTieredCompactionStrategy',
'enabled' : true,
'max_sstable_age_days' : 365,
'max_threshold' : 32,
'min_threshold' : 4,
'timestamp_resolution' : 'MICROSECONDS',
'tombstone_compaction_interval' : 86400,
'tombstone_threshold' : 0.2,
'unchecked_tombstone_compaction' : false
};
```
Should create a table like :
`timestamp ,id ,score , type, id ,embed_url`
Instead I am getting this:
```
timestamp timestamp,
id text,
score int,
embed_url text,
publisher_id text,
type text,
```
I've created quite a few tables in the same way and this never happened so any help would be appreciated.
I put the `id` and `score` as keys to show that these keep their respective position. while the actual scheme I am looking for is only the timestamp to be the primary key.
|
2015/12/03
|
[
"https://Stackoverflow.com/questions/34072768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1143013/"
] |
You should make a clear distinction on how *you* want the data to be presented and how it is effectively presented to you. Moreover, you should not rely on the ordinal position of the fields but only on their names.
In order to be efficient, and against your will (you specified an order to the columns when you modeled your schema), Cassandra needs to store the columns in a particular order, and for simplicity this reflects on how it (the CQL interface or the driver) will give back your data.
I suggest you to have a deep insight on how Cassandra stores data (column names included!) in [Understanding How CQL3 Maps to Cassandra’s Internal Data Structure](http://opensourceconnections.com/blog/2013/07/24/understanding-how-cql3-maps-to-cassandras-internal-data-structure/).
By the way, if you absolutely need to keep *your* order at application level (and are too lazy to specify all the fields in the `SELECT` instead of using `SELECT *`), you need to create an abstraction interface on your own, something like creating an ordered "field names" array (your order):
```
String myorder[] = { "timestamp", "id", "score", "type", "publisher_id", "embed_url"};
```
and then use this as a map in loops using ordinal values.
|
Keep in mind that the rendering of the CQL string in DESCRIBE in cqlsh is just a [function call in the python driver](https://github.com/datastax/python-driver/blob/806e0b0021ca283842ea7ce48f27305725658e3b/cassandra/metadata.py#L1150) iterating over the metadata. It has nothing to do with how C\* stores or sends its results.
If it matters you can set the order. When you Insert you can define the order explicitly
```
INSERT INTO keyspace_name.table_name
( identifier, column_name, whatever, order)
VALUES ( value, value ... )
```
When you do a select you can define the order explicitly.
```
SELECT identifier, whatever, order, column_name FROM keyspace_name.table_name
```
|
19,256,996 |
I've looked at a ton of posts on similar things, but none of them quite match or fix this issue. Since iOS 7, whenever I add a `UIButton` to a `UITableViewCell` or even to the footerview it works "fine", meaning it receives the target action, but it doesn't show the little highlight that normally happens as you tap a `UIButton`. It makes the UI look funky not showing the button react to touch.
I'm pretty sure this counts as a bug in iOS7, but has anyone found a solution or could help me find one :)
Edit:
I forgot to mention that it will highlight if I long hold on the button, but not a quick tap like it does if just added to a standard view.
**Code:**
Creating the button:
```
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.titleLabel.font = [UIFont systemFontOfSize:14];
button.titleLabel.textColor = [UIColor blueColor];
[button setTitle:@"Testing" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonPressed:) forControlEvents: UIControlEventTouchDown];
button.frame = CGRectMake(0, 0, self.view.frame.size.width/2, 40);
```
Things I've Tested:
//Removing gesture recognizers on `UITableView` in case they were getting in the way.
```
for (UIGestureRecognizer *recognizer in self.tableView.gestureRecognizers) {
recognizer.enabled = NO;
}
```
//Removing gestures from the Cell
```
for (UIGestureRecognizer *recognizer in self.contentView.gestureRecognizers) {
recognizer.enabled = NO;
}
```
//This shows the little light touch, but this isn't the desired look
```
button.showsTouchWhenHighlighted = YES;
```
|
2013/10/08
|
[
"https://Stackoverflow.com/questions/19256996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/904355/"
] |
Here's Roman B's answer in Swift 2:
```
for view in tableView.subviews {
if view is UIScrollView {
(view as? UIScrollView)!.delaysContentTouches = false
break
}
}
```
|
This is a **Swift** version of Raphaël Pinto's answer above. Don't forget to upvote him too :)
```
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
super.touchesBegan(touches, withEvent: event)
NSOperationQueue.mainQueue().addOperationWithBlock { () -> Void in self.highlighted = true }
}
override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) {
super.touchesCancelled(touches, withEvent: event)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC)))
dispatch_after(time, dispatch_get_main_queue()) {
self.setDefault()
}
}
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
super.touchesEnded(touches, withEvent: event)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC)))
dispatch_after(time, dispatch_get_main_queue()) {
self.setDefault()
}
}
func setDefault() {
NSOperationQueue.mainQueue().addOperationWithBlock { () -> Void in self.highlighted = false }
}
```
|
19,256,996 |
I've looked at a ton of posts on similar things, but none of them quite match or fix this issue. Since iOS 7, whenever I add a `UIButton` to a `UITableViewCell` or even to the footerview it works "fine", meaning it receives the target action, but it doesn't show the little highlight that normally happens as you tap a `UIButton`. It makes the UI look funky not showing the button react to touch.
I'm pretty sure this counts as a bug in iOS7, but has anyone found a solution or could help me find one :)
Edit:
I forgot to mention that it will highlight if I long hold on the button, but not a quick tap like it does if just added to a standard view.
**Code:**
Creating the button:
```
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.titleLabel.font = [UIFont systemFontOfSize:14];
button.titleLabel.textColor = [UIColor blueColor];
[button setTitle:@"Testing" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonPressed:) forControlEvents: UIControlEventTouchDown];
button.frame = CGRectMake(0, 0, self.view.frame.size.width/2, 40);
```
Things I've Tested:
//Removing gesture recognizers on `UITableView` in case they were getting in the way.
```
for (UIGestureRecognizer *recognizer in self.tableView.gestureRecognizers) {
recognizer.enabled = NO;
}
```
//Removing gestures from the Cell
```
for (UIGestureRecognizer *recognizer in self.contentView.gestureRecognizers) {
recognizer.enabled = NO;
}
```
//This shows the little light touch, but this isn't the desired look
```
button.showsTouchWhenHighlighted = YES;
```
|
2013/10/08
|
[
"https://Stackoverflow.com/questions/19256996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/904355/"
] |
I tried to add this to the accepted answer but it never went through. This is a much safer way of turning off the cells delaysContentTouches property as it does not look for a specific class, but rather anything that responds to the selector.
In Cell:
```
for (id obj in self.subviews) {
if ([obj respondsToSelector:@selector(setDelaysContentTouches:)]) {
[obj setDelaysContentTouches:NO];
}
}
```
In TableView:
```
self.tableView.delaysContentTouches = NO;
```
|
What I did to solve the problem was a category of UIButton using the following code :
```
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesBegan:touches withEvent:event];
[NSOperationQueue.mainQueue addOperationWithBlock:^{ self.highlighted = YES; }];
}
- (void) touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesCancelled:touches withEvent:event];
[self performSelector:@selector(setDefault) withObject:nil afterDelay:0.1];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesEnded:touches withEvent:event];
[self performSelector:@selector(setDefault) withObject:nil afterDelay:0.1];
}
- (void)setDefault
{
[NSOperationQueue.mainQueue addOperationWithBlock:^{ self.highlighted = NO; }];
}
```
the button reacts correctly when I press on it in a UITableViewCell, and my UITableView behaves normally as the `delaysContentTouches` isn't forced.
|
19,256,996 |
I've looked at a ton of posts on similar things, but none of them quite match or fix this issue. Since iOS 7, whenever I add a `UIButton` to a `UITableViewCell` or even to the footerview it works "fine", meaning it receives the target action, but it doesn't show the little highlight that normally happens as you tap a `UIButton`. It makes the UI look funky not showing the button react to touch.
I'm pretty sure this counts as a bug in iOS7, but has anyone found a solution or could help me find one :)
Edit:
I forgot to mention that it will highlight if I long hold on the button, but not a quick tap like it does if just added to a standard view.
**Code:**
Creating the button:
```
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.titleLabel.font = [UIFont systemFontOfSize:14];
button.titleLabel.textColor = [UIColor blueColor];
[button setTitle:@"Testing" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonPressed:) forControlEvents: UIControlEventTouchDown];
button.frame = CGRectMake(0, 0, self.view.frame.size.width/2, 40);
```
Things I've Tested:
//Removing gesture recognizers on `UITableView` in case they were getting in the way.
```
for (UIGestureRecognizer *recognizer in self.tableView.gestureRecognizers) {
recognizer.enabled = NO;
}
```
//Removing gestures from the Cell
```
for (UIGestureRecognizer *recognizer in self.contentView.gestureRecognizers) {
recognizer.enabled = NO;
}
```
//This shows the little light touch, but this isn't the desired look
```
button.showsTouchWhenHighlighted = YES;
```
|
2013/10/08
|
[
"https://Stackoverflow.com/questions/19256996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/904355/"
] |
Here's Roman B's answer in Swift 2:
```
for view in tableView.subviews {
if view is UIScrollView {
(view as? UIScrollView)!.delaysContentTouches = false
break
}
}
```
|
Solution in Swift, iOS8 only (needs the extra work on each of the cells for iOS7):
```
//
// NoDelayTableView.swift
// DivineBiblePhone
//
// Created by Chris Hulbert on 30/03/2015.
// Copyright (c) 2015 Chris Hulbert. All rights reserved.
//
// This solves the delayed-tap issue on buttons on cells.
import UIKit
class NoDelayTableView: UITableView {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
delaysContentTouches = false
// This solves the iOS8 delayed-tap issue.
// http://stackoverflow.com/questions/19256996/uibutton-not-showing-highlight-on-tap-in-ios7
for view in subviews {
if let scroll = view as? UIScrollView {
scroll.delaysContentTouches = false
}
}
}
override func touchesShouldCancelInContentView(view: UIView!) -> Bool {
// So that if you tap and drag, it cancels the tap.
return true
}
}
```
To use, all you have to do is change the class to `NoDelayTableView` in your storyboard.
I can confirm that in iOS8, buttons placed inside a contentView in a cell now highlight instantly.
|
19,256,996 |
I've looked at a ton of posts on similar things, but none of them quite match or fix this issue. Since iOS 7, whenever I add a `UIButton` to a `UITableViewCell` or even to the footerview it works "fine", meaning it receives the target action, but it doesn't show the little highlight that normally happens as you tap a `UIButton`. It makes the UI look funky not showing the button react to touch.
I'm pretty sure this counts as a bug in iOS7, but has anyone found a solution or could help me find one :)
Edit:
I forgot to mention that it will highlight if I long hold on the button, but not a quick tap like it does if just added to a standard view.
**Code:**
Creating the button:
```
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.titleLabel.font = [UIFont systemFontOfSize:14];
button.titleLabel.textColor = [UIColor blueColor];
[button setTitle:@"Testing" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonPressed:) forControlEvents: UIControlEventTouchDown];
button.frame = CGRectMake(0, 0, self.view.frame.size.width/2, 40);
```
Things I've Tested:
//Removing gesture recognizers on `UITableView` in case they were getting in the way.
```
for (UIGestureRecognizer *recognizer in self.tableView.gestureRecognizers) {
recognizer.enabled = NO;
}
```
//Removing gestures from the Cell
```
for (UIGestureRecognizer *recognizer in self.contentView.gestureRecognizers) {
recognizer.enabled = NO;
}
```
//This shows the little light touch, but this isn't the desired look
```
button.showsTouchWhenHighlighted = YES;
```
|
2013/10/08
|
[
"https://Stackoverflow.com/questions/19256996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/904355/"
] |
The accepted answer did not work at some "taps" for me .
Finally I add the bellow code in a uibutton category(/subclass),and it works a hundred percent.
```
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
self.backgroundColor = [UIColor greenColor];
[UIView animateWithDuration:0.05 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
self.backgroundColor = [UIColor clearColor];
} completion:^(BOOL finished)
{
}];
[super touchesBegan:touches withEvent:event];
}
```
|
In Swift 3 this UIView extension can be used on the UITableViewCell. Preferably in the `cellForRowAt` method.
```
func removeTouchDelayForSubviews() {
for subview in subviews {
if let scrollView = subview as? UIScrollView {
scrollView.delaysContentTouches = false
} else {
subview.removeTouchDelayForSubviews()
}
}
}
```
|
19,256,996 |
I've looked at a ton of posts on similar things, but none of them quite match or fix this issue. Since iOS 7, whenever I add a `UIButton` to a `UITableViewCell` or even to the footerview it works "fine", meaning it receives the target action, but it doesn't show the little highlight that normally happens as you tap a `UIButton`. It makes the UI look funky not showing the button react to touch.
I'm pretty sure this counts as a bug in iOS7, but has anyone found a solution or could help me find one :)
Edit:
I forgot to mention that it will highlight if I long hold on the button, but not a quick tap like it does if just added to a standard view.
**Code:**
Creating the button:
```
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.titleLabel.font = [UIFont systemFontOfSize:14];
button.titleLabel.textColor = [UIColor blueColor];
[button setTitle:@"Testing" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonPressed:) forControlEvents: UIControlEventTouchDown];
button.frame = CGRectMake(0, 0, self.view.frame.size.width/2, 40);
```
Things I've Tested:
//Removing gesture recognizers on `UITableView` in case they were getting in the way.
```
for (UIGestureRecognizer *recognizer in self.tableView.gestureRecognizers) {
recognizer.enabled = NO;
}
```
//Removing gestures from the Cell
```
for (UIGestureRecognizer *recognizer in self.contentView.gestureRecognizers) {
recognizer.enabled = NO;
}
```
//This shows the little light touch, but this isn't the desired look
```
button.showsTouchWhenHighlighted = YES;
```
|
2013/10/08
|
[
"https://Stackoverflow.com/questions/19256996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/904355/"
] |
For a solution that works in both iOS7 and iOS8, create a custom `UITableView` subclass and custom `UITableViewCell` subclass.
Use this sample `UITableView`'s `initWithFrame:`
```
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
// iterate over all the UITableView's subviews
for (id view in self.subviews)
{
// looking for a UITableViewWrapperView
if ([NSStringFromClass([view class]) isEqualToString:@"UITableViewWrapperView"])
{
// this test is necessary for safety and because a "UITableViewWrapperView" is NOT a UIScrollView in iOS7
if([view isKindOfClass:[UIScrollView class]])
{
// turn OFF delaysContentTouches in the hidden subview
UIScrollView *scroll = (UIScrollView *) view;
scroll.delaysContentTouches = NO;
}
break;
}
}
}
return self;
}
```
Use this sample `UITableViewCell`'s `initWithStyle:reuseIdentifier:`
```
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self)
{
// iterate over all the UITableViewCell's subviews
for (id view in self.subviews)
{
// looking for a UITableViewCellScrollView
if ([NSStringFromClass([view class]) isEqualToString:@"UITableViewCellScrollView"])
{
// this test is here for safety only, also there is no UITableViewCellScrollView in iOS8
if([view isKindOfClass:[UIScrollView class]])
{
// turn OFF delaysContentTouches in the hidden subview
UIScrollView *scroll = (UIScrollView *) view;
scroll.delaysContentTouches = NO;
}
break;
}
}
}
return self;
}
```
|
That solution for me doesn't work, I **fixed** subclassing TableView and implementing these two methods
```
- (instancetype)initWithCoder:(NSCoder *)coder{
self = [super initWithCoder:coder];
if (self) {
for (id obj in self.subviews) {
if ([obj respondsToSelector:@selector(setDelaysContentTouches:)]){
[obj performSelector:@selector(setDelaysContentTouches:) withObject:NO];
}
}
}
return self;
}
- (BOOL)delaysContentTouches{
return NO;
}
```
|
19,256,996 |
I've looked at a ton of posts on similar things, but none of them quite match or fix this issue. Since iOS 7, whenever I add a `UIButton` to a `UITableViewCell` or even to the footerview it works "fine", meaning it receives the target action, but it doesn't show the little highlight that normally happens as you tap a `UIButton`. It makes the UI look funky not showing the button react to touch.
I'm pretty sure this counts as a bug in iOS7, but has anyone found a solution or could help me find one :)
Edit:
I forgot to mention that it will highlight if I long hold on the button, but not a quick tap like it does if just added to a standard view.
**Code:**
Creating the button:
```
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.titleLabel.font = [UIFont systemFontOfSize:14];
button.titleLabel.textColor = [UIColor blueColor];
[button setTitle:@"Testing" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonPressed:) forControlEvents: UIControlEventTouchDown];
button.frame = CGRectMake(0, 0, self.view.frame.size.width/2, 40);
```
Things I've Tested:
//Removing gesture recognizers on `UITableView` in case they were getting in the way.
```
for (UIGestureRecognizer *recognizer in self.tableView.gestureRecognizers) {
recognizer.enabled = NO;
}
```
//Removing gestures from the Cell
```
for (UIGestureRecognizer *recognizer in self.contentView.gestureRecognizers) {
recognizer.enabled = NO;
}
```
//This shows the little light touch, but this isn't the desired look
```
button.showsTouchWhenHighlighted = YES;
```
|
2013/10/08
|
[
"https://Stackoverflow.com/questions/19256996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/904355/"
] |
Solution in Swift, iOS8 only (needs the extra work on each of the cells for iOS7):
```
//
// NoDelayTableView.swift
// DivineBiblePhone
//
// Created by Chris Hulbert on 30/03/2015.
// Copyright (c) 2015 Chris Hulbert. All rights reserved.
//
// This solves the delayed-tap issue on buttons on cells.
import UIKit
class NoDelayTableView: UITableView {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
delaysContentTouches = false
// This solves the iOS8 delayed-tap issue.
// http://stackoverflow.com/questions/19256996/uibutton-not-showing-highlight-on-tap-in-ios7
for view in subviews {
if let scroll = view as? UIScrollView {
scroll.delaysContentTouches = false
}
}
}
override func touchesShouldCancelInContentView(view: UIView!) -> Bool {
// So that if you tap and drag, it cancels the tap.
return true
}
}
```
To use, all you have to do is change the class to `NoDelayTableView` in your storyboard.
I can confirm that in iOS8, buttons placed inside a contentView in a cell now highlight instantly.
|
That solution for me doesn't work, I **fixed** subclassing TableView and implementing these two methods
```
- (instancetype)initWithCoder:(NSCoder *)coder{
self = [super initWithCoder:coder];
if (self) {
for (id obj in self.subviews) {
if ([obj respondsToSelector:@selector(setDelaysContentTouches:)]){
[obj performSelector:@selector(setDelaysContentTouches:) withObject:NO];
}
}
}
return self;
}
- (BOOL)delaysContentTouches{
return NO;
}
```
|
19,256,996 |
I've looked at a ton of posts on similar things, but none of them quite match or fix this issue. Since iOS 7, whenever I add a `UIButton` to a `UITableViewCell` or even to the footerview it works "fine", meaning it receives the target action, but it doesn't show the little highlight that normally happens as you tap a `UIButton`. It makes the UI look funky not showing the button react to touch.
I'm pretty sure this counts as a bug in iOS7, but has anyone found a solution or could help me find one :)
Edit:
I forgot to mention that it will highlight if I long hold on the button, but not a quick tap like it does if just added to a standard view.
**Code:**
Creating the button:
```
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.titleLabel.font = [UIFont systemFontOfSize:14];
button.titleLabel.textColor = [UIColor blueColor];
[button setTitle:@"Testing" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonPressed:) forControlEvents: UIControlEventTouchDown];
button.frame = CGRectMake(0, 0, self.view.frame.size.width/2, 40);
```
Things I've Tested:
//Removing gesture recognizers on `UITableView` in case they were getting in the way.
```
for (UIGestureRecognizer *recognizer in self.tableView.gestureRecognizers) {
recognizer.enabled = NO;
}
```
//Removing gestures from the Cell
```
for (UIGestureRecognizer *recognizer in self.contentView.gestureRecognizers) {
recognizer.enabled = NO;
}
```
//This shows the little light touch, but this isn't the desired look
```
button.showsTouchWhenHighlighted = YES;
```
|
2013/10/08
|
[
"https://Stackoverflow.com/questions/19256996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/904355/"
] |
Since iOS 8 we need to apply the same technique to UITableView subviews (table contains a hidden UITableViewWrapperView scroll view). There is no need iterate UITableViewCell subviews anymore.
```
for (UIView *currentView in tableView.subviews) {
if ([currentView isKindOfClass:[UIScrollView class]]) {
((UIScrollView *)currentView).delaysContentTouches = NO;
break;
}
}
```
[This answer](https://stackoverflow.com/questions/22924817/ios-delayed-touch-down-event-for-uibutton-in-uitableviewcell) should be linked with this question.
|
That solution for me doesn't work, I **fixed** subclassing TableView and implementing these two methods
```
- (instancetype)initWithCoder:(NSCoder *)coder{
self = [super initWithCoder:coder];
if (self) {
for (id obj in self.subviews) {
if ([obj respondsToSelector:@selector(setDelaysContentTouches:)]){
[obj performSelector:@selector(setDelaysContentTouches:) withObject:NO];
}
}
}
return self;
}
- (BOOL)delaysContentTouches{
return NO;
}
```
|
19,256,996 |
I've looked at a ton of posts on similar things, but none of them quite match or fix this issue. Since iOS 7, whenever I add a `UIButton` to a `UITableViewCell` or even to the footerview it works "fine", meaning it receives the target action, but it doesn't show the little highlight that normally happens as you tap a `UIButton`. It makes the UI look funky not showing the button react to touch.
I'm pretty sure this counts as a bug in iOS7, but has anyone found a solution or could help me find one :)
Edit:
I forgot to mention that it will highlight if I long hold on the button, but not a quick tap like it does if just added to a standard view.
**Code:**
Creating the button:
```
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.titleLabel.font = [UIFont systemFontOfSize:14];
button.titleLabel.textColor = [UIColor blueColor];
[button setTitle:@"Testing" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonPressed:) forControlEvents: UIControlEventTouchDown];
button.frame = CGRectMake(0, 0, self.view.frame.size.width/2, 40);
```
Things I've Tested:
//Removing gesture recognizers on `UITableView` in case they were getting in the way.
```
for (UIGestureRecognizer *recognizer in self.tableView.gestureRecognizers) {
recognizer.enabled = NO;
}
```
//Removing gestures from the Cell
```
for (UIGestureRecognizer *recognizer in self.contentView.gestureRecognizers) {
recognizer.enabled = NO;
}
```
//This shows the little light touch, but this isn't the desired look
```
button.showsTouchWhenHighlighted = YES;
```
|
2013/10/08
|
[
"https://Stackoverflow.com/questions/19256996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/904355/"
] |
Slightly modified version of [Chris Harrison's answer](https://stackoverflow.com/a/28066210/649379). Swift 2.3:
```
class HighlightButton: UIButton {
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event)
NSOperationQueue.mainQueue().addOperationWithBlock { _ in self.highlighted = true }
}
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
super.touchesCancelled(touches, withEvent: event)
setDefault()
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesEnded(touches, withEvent: event)
setDefault()
}
private func setDefault() {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
NSOperationQueue.mainQueue().addOperationWithBlock { _ in self.highlighted = false }
}
}
}
```
|
I wrote a category extension on `UITableViewCell` to make this issue simple to address. It does basically the same thing as the accepted answer except I walk up the view hierarchy (as opposed to down) from the `UITableViewCell contentView`.
I considered a fully "automagic" solution that would make all cells added to a `UITableView` set their `delaysContentTouches` state to match the owning `UITableView`'s `delaysContentTouches` state. To make this work I'd have to either swizzle `UITableView`, or require the developer to use a `UITableView` subclass. Not wanting to require either I settled on this solution which I feel is simpler and more flexible.
Category extension and sample harness here:
<https://github.com/TomSwift/UITableViewCell-TS_delaysContentTouches>
It's dead-simple to use:
```
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// using static cells from storyboard...
UITableViewCell* cell = [super tableView: tableView cellForRowAtIndexPath: indexPath];
cell.ts_delaysContentTouches = NO;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
```
Here's the code for the category:
```
@interface UITableViewCell (TS_delaysContentTouches)
@property (nonatomic, assign) BOOL ts_delaysContentTouches;
@end
@implementation UITableViewCell (TS_delaysContentTouches)
- (UIScrollView*) ts_scrollView
{
id sv = self.contentView.superview;
while ( ![sv isKindOfClass: [UIScrollView class]] && sv != self )
{
sv = [sv superview];
}
return sv == self ? nil : sv;
}
- (void) setTs_delaysContentTouches:(BOOL)delaysContentTouches
{
[self willChangeValueForKey: @"ts_delaysContentTouches"];
[[self ts_scrollView] setDelaysContentTouches: delaysContentTouches];
[self didChangeValueForKey: @"ts_delaysContentTouches"];
}
- (BOOL) ts_delaysContentTouches
{
return [[self ts_scrollView] delaysContentTouches];
}
@end
```
|
19,256,996 |
I've looked at a ton of posts on similar things, but none of them quite match or fix this issue. Since iOS 7, whenever I add a `UIButton` to a `UITableViewCell` or even to the footerview it works "fine", meaning it receives the target action, but it doesn't show the little highlight that normally happens as you tap a `UIButton`. It makes the UI look funky not showing the button react to touch.
I'm pretty sure this counts as a bug in iOS7, but has anyone found a solution or could help me find one :)
Edit:
I forgot to mention that it will highlight if I long hold on the button, but not a quick tap like it does if just added to a standard view.
**Code:**
Creating the button:
```
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.titleLabel.font = [UIFont systemFontOfSize:14];
button.titleLabel.textColor = [UIColor blueColor];
[button setTitle:@"Testing" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonPressed:) forControlEvents: UIControlEventTouchDown];
button.frame = CGRectMake(0, 0, self.view.frame.size.width/2, 40);
```
Things I've Tested:
//Removing gesture recognizers on `UITableView` in case they were getting in the way.
```
for (UIGestureRecognizer *recognizer in self.tableView.gestureRecognizers) {
recognizer.enabled = NO;
}
```
//Removing gestures from the Cell
```
for (UIGestureRecognizer *recognizer in self.contentView.gestureRecognizers) {
recognizer.enabled = NO;
}
```
//This shows the little light touch, but this isn't the desired look
```
button.showsTouchWhenHighlighted = YES;
```
|
2013/10/08
|
[
"https://Stackoverflow.com/questions/19256996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/904355/"
] |
What I did to solve the problem was a category of UIButton using the following code :
```
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesBegan:touches withEvent:event];
[NSOperationQueue.mainQueue addOperationWithBlock:^{ self.highlighted = YES; }];
}
- (void) touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesCancelled:touches withEvent:event];
[self performSelector:@selector(setDefault) withObject:nil afterDelay:0.1];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesEnded:touches withEvent:event];
[self performSelector:@selector(setDefault) withObject:nil afterDelay:0.1];
}
- (void)setDefault
{
[NSOperationQueue.mainQueue addOperationWithBlock:^{ self.highlighted = NO; }];
}
```
the button reacts correctly when I press on it in a UITableViewCell, and my UITableView behaves normally as the `delaysContentTouches` isn't forced.
|
In Swift 3 this UIView extension can be used on the UITableViewCell. Preferably in the `cellForRowAt` method.
```
func removeTouchDelayForSubviews() {
for subview in subviews {
if let scrollView = subview as? UIScrollView {
scrollView.delaysContentTouches = false
} else {
subview.removeTouchDelayForSubviews()
}
}
}
```
|
19,256,996 |
I've looked at a ton of posts on similar things, but none of them quite match or fix this issue. Since iOS 7, whenever I add a `UIButton` to a `UITableViewCell` or even to the footerview it works "fine", meaning it receives the target action, but it doesn't show the little highlight that normally happens as you tap a `UIButton`. It makes the UI look funky not showing the button react to touch.
I'm pretty sure this counts as a bug in iOS7, but has anyone found a solution or could help me find one :)
Edit:
I forgot to mention that it will highlight if I long hold on the button, but not a quick tap like it does if just added to a standard view.
**Code:**
Creating the button:
```
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.titleLabel.font = [UIFont systemFontOfSize:14];
button.titleLabel.textColor = [UIColor blueColor];
[button setTitle:@"Testing" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonPressed:) forControlEvents: UIControlEventTouchDown];
button.frame = CGRectMake(0, 0, self.view.frame.size.width/2, 40);
```
Things I've Tested:
//Removing gesture recognizers on `UITableView` in case they were getting in the way.
```
for (UIGestureRecognizer *recognizer in self.tableView.gestureRecognizers) {
recognizer.enabled = NO;
}
```
//Removing gestures from the Cell
```
for (UIGestureRecognizer *recognizer in self.contentView.gestureRecognizers) {
recognizer.enabled = NO;
}
```
//This shows the little light touch, but this isn't the desired look
```
button.showsTouchWhenHighlighted = YES;
```
|
2013/10/08
|
[
"https://Stackoverflow.com/questions/19256996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/904355/"
] |
```
- (void)viewDidLoad
{
[super viewDidLoad];
for (id view in self.tableView.subviews)
{
// looking for a UITableViewWrapperView
if ([NSStringFromClass([view class]) isEqualToString:@"UITableViewWrapperView"])
{
// this test is necessary for safety and because a "UITableViewWrapperView" is NOT a UIScrollView in iOS7
if([view isKindOfClass:[UIScrollView class]])
{
// turn OFF delaysContentTouches in the hidden subview
UIScrollView *scroll = (UIScrollView *) view;
scroll.delaysContentTouches = NO;
}
break;
}
}
}
```

|
Solution in Swift, iOS8 only (needs the extra work on each of the cells for iOS7):
```
//
// NoDelayTableView.swift
// DivineBiblePhone
//
// Created by Chris Hulbert on 30/03/2015.
// Copyright (c) 2015 Chris Hulbert. All rights reserved.
//
// This solves the delayed-tap issue on buttons on cells.
import UIKit
class NoDelayTableView: UITableView {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
delaysContentTouches = false
// This solves the iOS8 delayed-tap issue.
// http://stackoverflow.com/questions/19256996/uibutton-not-showing-highlight-on-tap-in-ios7
for view in subviews {
if let scroll = view as? UIScrollView {
scroll.delaysContentTouches = false
}
}
}
override func touchesShouldCancelInContentView(view: UIView!) -> Bool {
// So that if you tap and drag, it cancels the tap.
return true
}
}
```
To use, all you have to do is change the class to `NoDelayTableView` in your storyboard.
I can confirm that in iOS8, buttons placed inside a contentView in a cell now highlight instantly.
|
48,021,400 |
so if I put the keywords..
return type:int, parameter:String (something like this)
it show results such as
void int Integer.parseInt(String)
Hope I could explain what I'm looking for.
|
2017/12/29
|
[
"https://Stackoverflow.com/questions/48021400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6215388/"
] |
Assuming
* *Array* items are sorted (if not, you need to sort them)
* `arr2` doesn't contain any element which is not part of `arr1`
Use `map` to iterate and check if `index` of each `item` is not `-1`
```
var output = arr1.map( s => arr2.indexOf( s ) != -1 ? s : "--" );
```
**Demo**
```js
var arr1 = ["CRS02","CRS04","CRS03","CRS01","CRS05"];
var arr2 = ["CRS02","CRS03","CRS05"];
var output = arr1.map( s => arr2.indexOf( s ) != -1 ? s : "--" );
console.log( output );
```
|
First of all, it seems like you have filled the arrays with vars.
Strings in JavaScript start and end with single (`''`) or double (`""`) quotes.
I will assume they are strings in terms of simplicity.
You don't need two loops for that. Just use a `step` counter:
**Note**: The aim of this solution is to be readable, in order for you to catch the concept. Of course, it can be implemented using `indexOf` or `reduce` as suggested in other answers.
```js
var arr1 = ["CRS02","CRS04","CRS03","CRS01","CRS05"];
var arr2 = ["CRS02","CRS03","CRS05"];
var content = "";
// Use length of largest array.
for (var i = 0, step = 0; i < arr1.length; ++i) {
if (arr1[i] == arr2[step]) {
content += arr1[i] + ", ";
++step;
} else {
content += "--, ";
}
}
// Remove last comma and space.
content = content.substring(0, content.length - 2);
console.log(content);
```
|
48,021,400 |
so if I put the keywords..
return type:int, parameter:String (something like this)
it show results such as
void int Integer.parseInt(String)
Hope I could explain what I'm looking for.
|
2017/12/29
|
[
"https://Stackoverflow.com/questions/48021400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6215388/"
] |
Assuming
* *Array* items are sorted (if not, you need to sort them)
* `arr2` doesn't contain any element which is not part of `arr1`
Use `map` to iterate and check if `index` of each `item` is not `-1`
```
var output = arr1.map( s => arr2.indexOf( s ) != -1 ? s : "--" );
```
**Demo**
```js
var arr1 = ["CRS02","CRS04","CRS03","CRS01","CRS05"];
var arr2 = ["CRS02","CRS03","CRS05"];
var output = arr1.map( s => arr2.indexOf( s ) != -1 ? s : "--" );
console.log( output );
```
|
```js
var arr1 = ["CRS02","CRS04","CRS03","CRS01","CRS05"];
var arr2 = ["CRS02","CRS03","CRS05"];
var str = "";
for(var i = 0; i < arr1.length; i++){
if(arr2.indexOf(arr1[i]) >= 0){
str += arr1[i] + ",";
}
else{
str += "--"+",";
}
}
str = str.substring(0,(str.length-1));
console.log(str);
```
|
48,021,400 |
so if I put the keywords..
return type:int, parameter:String (something like this)
it show results such as
void int Integer.parseInt(String)
Hope I could explain what I'm looking for.
|
2017/12/29
|
[
"https://Stackoverflow.com/questions/48021400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6215388/"
] |
Assuming
* *Array* items are sorted (if not, you need to sort them)
* `arr2` doesn't contain any element which is not part of `arr1`
Use `map` to iterate and check if `index` of each `item` is not `-1`
```
var output = arr1.map( s => arr2.indexOf( s ) != -1 ? s : "--" );
```
**Demo**
```js
var arr1 = ["CRS02","CRS04","CRS03","CRS01","CRS05"];
var arr2 = ["CRS02","CRS03","CRS05"];
var output = arr1.map( s => arr2.indexOf( s ) != -1 ? s : "--" );
console.log( output );
```
|
Try the following:
```
var arr1 = ["CRS02","CRS04","CRS03","CRS01","CRS05"];
var arr2 = ["CRS02","CRS03","CRS05"];
function getContainsString(arr1, arr2) {
return arr1.reduce(function(result, el) {
return result + (arr2.indexOf(el) < 0 ? "--" : el) + ",";
}, "").slice(0, -1);
}
console.log(getContainsString(arr1, arr2));
//CRS02,--,CRS03,--,CRS05
```
|
48,021,400 |
so if I put the keywords..
return type:int, parameter:String (something like this)
it show results such as
void int Integer.parseInt(String)
Hope I could explain what I'm looking for.
|
2017/12/29
|
[
"https://Stackoverflow.com/questions/48021400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6215388/"
] |
Assuming
* *Array* items are sorted (if not, you need to sort them)
* `arr2` doesn't contain any element which is not part of `arr1`
Use `map` to iterate and check if `index` of each `item` is not `-1`
```
var output = arr1.map( s => arr2.indexOf( s ) != -1 ? s : "--" );
```
**Demo**
```js
var arr1 = ["CRS02","CRS04","CRS03","CRS01","CRS05"];
var arr2 = ["CRS02","CRS03","CRS05"];
var output = arr1.map( s => arr2.indexOf( s ) != -1 ? s : "--" );
console.log( output );
```
|
If your data sets are large and you don't want to use `indexOf` repeatedly in the loop, you can use a `Set` to quickly check the contents of `arr2`:
```js
const arr1 = ["CRS02","CRS04","CRS03","CRS01","CRS05"];
const set2 = new Set(["CRS02","CRS03","CRS05"]);
console.log(
arr1
.map(x => set2.has(x) ? x : "--")
.join(",")
);
```
|
48,021,400 |
so if I put the keywords..
return type:int, parameter:String (something like this)
it show results such as
void int Integer.parseInt(String)
Hope I could explain what I'm looking for.
|
2017/12/29
|
[
"https://Stackoverflow.com/questions/48021400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6215388/"
] |
Assuming
* *Array* items are sorted (if not, you need to sort them)
* `arr2` doesn't contain any element which is not part of `arr1`
Use `map` to iterate and check if `index` of each `item` is not `-1`
```
var output = arr1.map( s => arr2.indexOf( s ) != -1 ? s : "--" );
```
**Demo**
```js
var arr1 = ["CRS02","CRS04","CRS03","CRS01","CRS05"];
var arr2 = ["CRS02","CRS03","CRS05"];
var output = arr1.map( s => arr2.indexOf( s ) != -1 ? s : "--" );
console.log( output );
```
|
You can use `array#map` to iterate through `arr1` and use `array#includes` to test the existence of value in `arr2`.
```js
var arr1 = ["CRS02","CRS04","CRS03","CRS01","CRS05"],
arr2 = ["CRS02","CRS03","CRS05"],
result = arr1.map(v => arr2.includes(v) ? v :'--')
.join(',');
console.log(result);
```
|
28,920,739 |
people
I have a problem I want to read from a file and use and fetch some parts of the file like below. This is whats inside the file but I want to fetch the names. This file is used by my server and if a player logs in the server then the list of names get bigger. But I have no clue how to do it.. and I really want to know how to do so.
I already tryed stuff myself by exploding the first characters but thats how far my knowledge reaches.
Already Big thanks for the one so kind to help me out.
```
Players online: NAME1, NAME2, NAME3, NAME4, NAME5, NAME6, ETC, ETC. Total: 4
```
|
2015/03/07
|
[
"https://Stackoverflow.com/questions/28920739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3866202/"
] |
```
String myString = "myString";
int maxLength = 3;
if (myString.length() > maxLength)
myString = myString.substring(0, maxLength);
```
Result will be "myS"
|
"I was searching around on the web for a manual code to count the amount of characters within a string, and then to a further extent cut off any excess characters of the string."
Count amount of characters within a string:
```
int length = stringName.length();
```
Cutting off extra characters of the string
```
int maxAmount; //wherever you want to stop
if(length > maxAmount)
{
stringName = stringName.substring(0,stopPoint);
}
```
|
63,251 |
(This doesn't affect me personally but is something that came up which I'm curious about. I'm not sure what to tag it with)
Could an employer ask "me" to change my hours for that week so that I'd do the jury duty in the normal court hours and an "evening shift" instead of my normal work hours? (6-midnight instead of 8-4 or whatever)
Assuming there's a contract that says something like Hours are 8-4 or as otherwise required.
Possible reasons: unexpected issues in live systems, "crunch time", someone on a production line called in sick, minimum number of staff to patients needed in a care home, or such like.
Would regulations on max number of hours "worked" (in a week or per "shift") include time spent on a jury?
Actually, if you normally work evenings/nights how would that work with a "day" of jury duty?
Edit: I know there are laws that the employer has to let you do the jury duty, but that doesn't take into account "unexpected" needs of the employer that weren't known when you receive the summons.
|
2016/03/08
|
[
"https://workplace.stackexchange.com/questions/63251",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/47059/"
] |
In the US this depends on company policy. Some companies only give you time off for the conflicting hours, and tell you to request the minor daily stipend the government offers to partly reimburse you for your time. Some pay the difference between that stipend and your normal salary. Others offer other arrangements.
For a reliable answer you really have to ask your own HR department, not us.
|
Depends what country you are in, but if you are in the UK you can contact the Jury Central Summoning Bureau.
>
> The Jury Central Summoning Bureau can:
>
>
> * give advice about your summons or jury service
> * arrange a visit to the court for you, eg if you’re disabled and want to see the facilities
>
>
> **Jury Central Summoning Bureau**
>
>
> [email protected]
>
>
> Telephone: 0300 456 1024
>
>
> Monday to Thursday 9am to 5pm
>
>
> Friday 9am to 3pm
>
>
>
Source: [Gov.UK](https://www.gov.uk/jury-service/questions-about-jury-service)
|
63,251 |
(This doesn't affect me personally but is something that came up which I'm curious about. I'm not sure what to tag it with)
Could an employer ask "me" to change my hours for that week so that I'd do the jury duty in the normal court hours and an "evening shift" instead of my normal work hours? (6-midnight instead of 8-4 or whatever)
Assuming there's a contract that says something like Hours are 8-4 or as otherwise required.
Possible reasons: unexpected issues in live systems, "crunch time", someone on a production line called in sick, minimum number of staff to patients needed in a care home, or such like.
Would regulations on max number of hours "worked" (in a week or per "shift") include time spent on a jury?
Actually, if you normally work evenings/nights how would that work with a "day" of jury duty?
Edit: I know there are laws that the employer has to let you do the jury duty, but that doesn't take into account "unexpected" needs of the employer that weren't known when you receive the summons.
|
2016/03/08
|
[
"https://workplace.stackexchange.com/questions/63251",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/47059/"
] |
In the US this depends on company policy. Some companies only give you time off for the conflicting hours, and tell you to request the minor daily stipend the government offers to partly reimburse you for your time. Some pay the difference between that stipend and your normal salary. Others offer other arrangements.
For a reliable answer you really have to ask your own HR department, not us.
|
In virtually every country in the world that uses juries, employers are obliged to give you time off for jury duty. Time off means time off - it does not mean working at a different time. While your company could *ask* you to come in after your jury duty hours for an emergency, they couldn't compel you. And any hours you worked on those days would be additional hours of work, just like if you had booked a vacation and then came to work, you would be expected to be paid extra for those hours. Also remember that once you assigned to a case there are restrictions on what you can do and who you can interact with as a juror. Your court will give you details.
Most countries also allow you to be excused jury duty if your absence would seriously affect your employer, for example if there was important work scheduled that only you could do. This would have to be asked for in advance. It would be up to the judge to decide if your specific circumstances warranted excusing. However once you are assigned to a case, it is very unlikely that you would be excused for anything other than a genuine serious emergency, as your absence might mean a retrial, with the huge expense that involves.
In my personal opinion, some of the cases you describe are a bit thin. It would be hard to believe that you were the only person who could fill in for a sick colleague. You might want to ask the company what they would do in these circumstances if you were completely unavailable, such as being out of the country, and why they couldn't take that action in this case?
|
26,167,150 |
I have a JSONArray which I am iterating to populate my Map as shown below. My `ppJsonArray` will have data like this -
```
[693,694,695,696,697,698,699,700,701,702]
```
Below is my code which is having issues with thread safety as my static analysis tool complained -
```
Map<Integer, Integer> m = new HashMap<Integer, Integer>();
ConcurrentMap<String, Map<Integer, Integer>> partitionsToNodeMap = new ConcurrentHashMap<String, Map<Integer, Integer>>();
int hostNum = 2;
JSONArray ppJsonArray = j.getJSONArray("pp");
for (int i = 0; i < ppJsonArray.length(); i++) {
m.put(Integer.parseInt(ppJsonArray.get(i).toString()), hostNum);
}
Map<Integer, Integer> tempMap = partitionsToNodeMap.get("PRIMARY");
if (tempMap != null) {
tempMap.putAll(m);
} else {
tempMap = m;
}
partitionsToNodeMap.put("PRIMARY", tempMap);
```
But when I am running static analysis tool, it is complaining as -
```
Non-atomic use of get/check/put on partitionsToNodeMap.put("PRIMARY", tempMap)
```
Which makes me think my above code is not thread safe? How can I resolve this issue?
|
2014/10/02
|
[
"https://Stackoverflow.com/questions/26167150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2809564/"
] |
The above code is not thread safe.
Does it need to be thread safe? (i.e., Is partitionsToNodeMap used by more than one thread? Could more than one thread run this routine? or could thread A thread update partitionsToNodeMap in some other routine while thread B runs this routine?)
If you answered "yes" to any of those questions, then you probably need to use some kind of synchronization.
---
partitionsToNodeMap is a ConcurrentHashMap. That will prevent the map structure itself from becoming corrupt if it is updated by more than one thread at one time; but the data in the map presumably aren't just random strings and integers. It probably *means* something to your program. The fact that the map structure itself is protected from corruption will not prevent the higher-level meaning of the map contents from becoming corrupt.
---
>
> Can you provide an example how can I protect this?
>
>
>
Not a complete one, because thread-safety is a property of the whole program. You can't do thread-safety function-by-function.
Being thread-safe is all about protecting *invariants*. An invariant is an assertion about your data that must always be true. For example, if you were modeling a game of Monopoly, one invariant would say that the total amount of money in the game must always be $15,140.
If some thread in the Monopoly game processes a payment by taking X dollars away from one player, and returning it to the bank, that's a two step process, and in-between the two steps the invariant is *broken*. If the first thread were preempted in-between the two steps, and some other thread counted all of the money in the game, it would get the wrong total.
The main use-case for the Java `synchronized` keyword (or equivalently, for the java.util.concurrent.locks.ReentrantLock class) is to prevent other threads from seeing broken invariants.
Either way of locking is *voluntary*. To make it work, you must wrap every block of code that can temporarily break an invariant in a protected block
```
synchronized(bank-lock) {
deductNDollarsFrom(N, player);
giveNDollarsTo(N, bank);
}
```
*AND* every block of code that *cares* about the invariant must also be wrapped in a protected block.
```
synchronized(bank-lock) {
int totalDollars = countAllMoneyInGame(...);
if (totalDollars != 15140) {
throw new CheatingDetectedException(...);
}
}
```
Java won't let the balance transfer and the audit happen at the same time because it never allows two threads to synchronize on the same object (bank-lock, in this case) at the same time.
You will have to figure out what your invariants are. The static analyzer is telling you that the get()...put() sequence looks like a block of code that might *care* about an invariant. You have to figure out whether it really does or not. Is there something that some other thread could do in-between the get() and the put() that could cause things to go south? If so then both blocks of code should synchronize on the same object so that they can not both be executed at the same time.
|
Your static analysis tool is confused because what you're doing looks like a classic race condition.
```
Map<Integer, Integer> tempMap = partitionsToNodeMap.get("PRIMARY"); // GET
if (tempMap != null) { // CHECK
tempMap.putAll(m);
} else {
tempMap = m;
}
partitionsToNodeMap.put("PRIMARY", tempMap); // PUT
```
If another thread were to `partitionsToNodeMap.put("PRIMARY");` after you get assign `tempMap`, you would overwrite the other thread's work. Among a myriad of other potential bad things. It seems like you don't have multiple threads accessing it though, so it isn't an issue. However, it would be more clearly expressed as:
```
Map<Integer, Integer> primaryMap = partitionsToNodeMap.get("PRIMARY");
if (primaryMap != null) {
primaryMap.putAll(m);
} else {
partitionsToNodeMap.put("PRIMARY", m);
}
```
If you want to make the static analysis tool happy, swap out your concurrent map for a regular map. The code you've provided doesn't require a threadsafe data structure.
|
39,456,448 |
I have 3 files and want to print lines that are a combination of the same line from each file. The files can have any number of lines. How can I iterate over three files in parallel?
protocol.txt
```
http
ftp
sftp
```
website.txt
```
facebook
yahoo
gmail
```
port.txt
```
23
45
56
```
Expected output:
```
Protocol 'http' for website 'facebook' with port '23'
Protocol 'ftp' for website 'yahoo' with port '45'
Protocol 'sftp' for website 'gmail' with port '56'
```
```
from time import sleep
with open ("C:/Users/Desktop/3 files read/protocol.txt", 'r') as test:
for line in test:
with open ("C:/Users/Desktop/3 files read/website.txt", 'r') as test1:
for line1 in test1:
with open ("C:/Users/Desktop/3 files read/port.txt", 'r') as test2:
for line2 in test2:
print "Protocol (%s) for website (%s) with port (%d)" % line, line1, line2
```
|
2016/09/12
|
[
"https://Stackoverflow.com/questions/39456448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3611969/"
] |
Here is my version:
```
import os.path
directory = "C:/Users/3 files read"
with open(os.path.join(directory, "protocol.txt"), 'r') as f1,\
open(os.path.join(directory, "website.txt"), 'r') as f2,\
open(os.path.join(directory, "port.txt"), 'r') as f3:
for l1, l2, l3 in zip(f1, f2, f3):
print "Protocol %s for website %s with port %d" % (l1.rstrip(), l2.rstrip(), int(l3))
```
I used the directory variable to simplify the code. Notice that I joined the elements using `os.path.join()`, which is safer than just putting a directory separator there.
Using `zip()`, we iterate through the three file objects. Using `zip()` means that the loop will exit on the file with the fewer lines, if they are uneven. If you cannot guarantee that they all have the same number of lines, then you might need to put an extra check in there.
By the way, at least some of this information is in the etc/services file.
|
This will work:
```
with open(...) as file1, open(...) as file2, open(...) as file3:
for l1, l2, l3 in zip(file1, file2, file3):
print("prot %s website %s port %s" % (l1.rstrip(),l2.rstrip(),l3.rstrip()))
```
|
12,394,348 |
Is quoting every part of a SELECT statement deprecated T-SQL syntax?
```
SELECT "A", "B", "C" FROM "database"."table" where "column" = @p2
```
This is syntax being used by MS Access to query against a SQL Server instance. I do not know what version of Access is being used.
|
2012/09/12
|
[
"https://Stackoverflow.com/questions/12394348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2184/"
] |
As far as I know it is not. Microsoft SQL 2012 still supports using double quotes in select statements see [here](http://msdn.microsoft.com/en-us/library/ms174393.aspx)
|
This sentence is working, BUT only if A, B and C are columns:
```
SELECT "A", "B", "C" FROM "database"."table" where "column" = @p2
```
If those are values like varchar, you have to use 'A','B','C'.
And the "database"."table" is not well defined.
It should be `"database"."schemaName"."table"`. (Usually schemaName is dbo)
So the query is working on this way:
```
SELECT "A", "B", "C" FROM "database"."schemaName"."table" where "column" = @p2
```
OR simply use
```
SELECT "A", "B", "C" FROM "table" where "column" = @p2
```
|
67,077,518 |
Hoping someone could help me out with something here, I'm trying to split a long string w/ numbers and card suits so that it displays nicely by number.
```none
AS AC AH AD 2S 2C 2H 2D 3S 3C 3H 3D 4S 4C 4H 4D 5S 5C 5H 5D 6S 6C 6H 6D 7S 7C 7H 7D 8S 8C 8H 8D 9S 9C 9H 9D 10S 10C 10H 10D JS JC JH JD QS QC QH QD KS KC KH KD
```
would like it to split like:
```none
AS AC AH AD
2S 2C 2H 2D
3S 3C 3H 3D
```
etc...
Is there a way to use .split() every certain number of characters,etc or by next number?
below is my code to generate a deck of cards
```
public class Main {
public static void main(String[] args) {
//System.out.printf("hello world");
String cards = "";
char[] suits = {'S', 'C', 'H', 'D'};
for(int i = 1; i <=14; i++){
for(int j = 0; j < suits.length; j++){
if(i == 1){
cards = cards + 'A' + suits[j] + " ";
} else if(i == 11){
break;
} else if(i == 12){
cards = cards + 'J' + suits[j] + " ";
} else if(i == 13){
cards = cards + 'Q' + suits[j] + " ";
} else if(i == 14){
cards = cards + 'K' + suits[j] + " ";
} else {
cards = cards + i + suits[j] + " ";
}
}
}
System.out.println(cards);
}
```
|
2021/04/13
|
[
"https://Stackoverflow.com/questions/67077518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12759155/"
] |
Actually, in your case, you want to split on the space following a **D**, so `split("(?<=D) ")` will do:
```java
String input = "AS AC AH AD 2S 2C 2H 2D 3S 3C 3H 3D 4S 4C 4H 4D 5S 5C 5H 5D 6S 6C 6H 6D 7S 7C 7H 7D 8S 8C 8H 8D 9S 9C 9H 9D 10S 10C 10H 10D JS JC JH JD QS QC QH QD KS KC KH KD";
String[] ranks = input.split("(?<=D) ");
for (String rank : ranks)
System.out.println(rank);
```
*Output*
```none
AS AC AH AD
2S 2C 2H 2D
3S 3C 3H 3D
4S 4C 4H 4D
5S 5C 5H 5D
6S 6C 6H 6D
7S 7C 7H 7D
8S 8C 8H 8D
9S 9C 9H 9D
10S 10C 10H 10D
JS JC JH JD
QS QC QH QD
KS KC KH KD
```
|
The simplest way is to include a newline character `\n` after each value like this:
```
for(int i = 1; i <=14; i++){
for(int j = 0; j < suits.length; j++){
// your stuff
}
cards = cards + '\n';
}
```
Note however, that concatenating to a `String` in a loop is usually discouraged in Java, because it requires constructing an entirely new `String` object for each concatenation, thus leading to lots of copying (which could be bad for performance and GC pressure). [Use of a `StringBuilder`](https://stackoverflow.com/a/1532483/40342) is often considered better.
|
67,077,518 |
Hoping someone could help me out with something here, I'm trying to split a long string w/ numbers and card suits so that it displays nicely by number.
```none
AS AC AH AD 2S 2C 2H 2D 3S 3C 3H 3D 4S 4C 4H 4D 5S 5C 5H 5D 6S 6C 6H 6D 7S 7C 7H 7D 8S 8C 8H 8D 9S 9C 9H 9D 10S 10C 10H 10D JS JC JH JD QS QC QH QD KS KC KH KD
```
would like it to split like:
```none
AS AC AH AD
2S 2C 2H 2D
3S 3C 3H 3D
```
etc...
Is there a way to use .split() every certain number of characters,etc or by next number?
below is my code to generate a deck of cards
```
public class Main {
public static void main(String[] args) {
//System.out.printf("hello world");
String cards = "";
char[] suits = {'S', 'C', 'H', 'D'};
for(int i = 1; i <=14; i++){
for(int j = 0; j < suits.length; j++){
if(i == 1){
cards = cards + 'A' + suits[j] + " ";
} else if(i == 11){
break;
} else if(i == 12){
cards = cards + 'J' + suits[j] + " ";
} else if(i == 13){
cards = cards + 'Q' + suits[j] + " ";
} else if(i == 14){
cards = cards + 'K' + suits[j] + " ";
} else {
cards = cards + i + suits[j] + " ";
}
}
}
System.out.println(cards);
}
```
|
2021/04/13
|
[
"https://Stackoverflow.com/questions/67077518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12759155/"
] |
Actually, in your case, you want to split on the space following a **D**, so `split("(?<=D) ")` will do:
```java
String input = "AS AC AH AD 2S 2C 2H 2D 3S 3C 3H 3D 4S 4C 4H 4D 5S 5C 5H 5D 6S 6C 6H 6D 7S 7C 7H 7D 8S 8C 8H 8D 9S 9C 9H 9D 10S 10C 10H 10D JS JC JH JD QS QC QH QD KS KC KH KD";
String[] ranks = input.split("(?<=D) ");
for (String rank : ranks)
System.out.println(rank);
```
*Output*
```none
AS AC AH AD
2S 2C 2H 2D
3S 3C 3H 3D
4S 4C 4H 4D
5S 5C 5H 5D
6S 6C 6H 6D
7S 7C 7H 7D
8S 8C 8H 8D
9S 9C 9H 9D
10S 10C 10H 10D
JS JC JH JD
QS QC QH QD
KS KC KH KD
```
|
A possible solution is that you will first split your string by space `(" ")`.
Then loop through the resulting array, keeping track of the latest "starting character" (eg. 2).
Print the new item as long as it `startsWith()` that character. If it doesn't, print a new line and change the "starting character" (eg. 3)
|
67,077,518 |
Hoping someone could help me out with something here, I'm trying to split a long string w/ numbers and card suits so that it displays nicely by number.
```none
AS AC AH AD 2S 2C 2H 2D 3S 3C 3H 3D 4S 4C 4H 4D 5S 5C 5H 5D 6S 6C 6H 6D 7S 7C 7H 7D 8S 8C 8H 8D 9S 9C 9H 9D 10S 10C 10H 10D JS JC JH JD QS QC QH QD KS KC KH KD
```
would like it to split like:
```none
AS AC AH AD
2S 2C 2H 2D
3S 3C 3H 3D
```
etc...
Is there a way to use .split() every certain number of characters,etc or by next number?
below is my code to generate a deck of cards
```
public class Main {
public static void main(String[] args) {
//System.out.printf("hello world");
String cards = "";
char[] suits = {'S', 'C', 'H', 'D'};
for(int i = 1; i <=14; i++){
for(int j = 0; j < suits.length; j++){
if(i == 1){
cards = cards + 'A' + suits[j] + " ";
} else if(i == 11){
break;
} else if(i == 12){
cards = cards + 'J' + suits[j] + " ";
} else if(i == 13){
cards = cards + 'Q' + suits[j] + " ";
} else if(i == 14){
cards = cards + 'K' + suits[j] + " ";
} else {
cards = cards + i + suits[j] + " ";
}
}
}
System.out.println(cards);
}
```
|
2021/04/13
|
[
"https://Stackoverflow.com/questions/67077518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12759155/"
] |
Actually, in your case, you want to split on the space following a **D**, so `split("(?<=D) ")` will do:
```java
String input = "AS AC AH AD 2S 2C 2H 2D 3S 3C 3H 3D 4S 4C 4H 4D 5S 5C 5H 5D 6S 6C 6H 6D 7S 7C 7H 7D 8S 8C 8H 8D 9S 9C 9H 9D 10S 10C 10H 10D JS JC JH JD QS QC QH QD KS KC KH KD";
String[] ranks = input.split("(?<=D) ");
for (String rank : ranks)
System.out.println(rank);
```
*Output*
```none
AS AC AH AD
2S 2C 2H 2D
3S 3C 3H 3D
4S 4C 4H 4D
5S 5C 5H 5D
6S 6C 6H 6D
7S 7C 7H 7D
8S 8C 8H 8D
9S 9C 9H 9D
10S 10C 10H 10D
JS JC JH JD
QS QC QH QD
KS KC KH KD
```
|
You may have to bend this if the format changes, but in your current example printing a new line after 4 items is just fine:
```
final String testCase = "AS AC AH AD 2S 2C 2H 2D 3S 3C 3H 3D 4S 4C 4H 4D 5S 5C 5H 5D 6S 6C 6H 6D 7S 7C 7H 7D 8S 8C 8H 8D 9S 9C 9H 9D 10S 10C 10H 10D JS JC JH JD QS QC QH QD KS KC KH KD";
final String[] arr = testCase.split(" ");
for(int i = 0; i < arr.length; i++) {
System.out.print((i % 4 == 0 ? "\n" : " ")+arr[i]);
}
```
Which prints:
```java
AS AC AH AD
2S 2C 2H 2D
3S 3C 3H 3D
4S 4C 4H 4D
5S 5C 5H 5D
6S 6C 6H 6D
7S 7C 7H 7D
8S 8C 8H 8D
9S 9C 9H 9D
10S 10C 10H 10D
JS JC JH JD
QS QC QH QD
KS KC KH KD
```
|
3,703,726 |
So I have $(x^4 + 2x^3 +3x^2 +2x +1) + I$ and I'm wanting to show that this is not an integral domain. I know that I have to use the principal ideal which is $x^3 + 1$ and somehow get it into a form that involves the principal ideal to show that it's not the integral domain but I'm not sure how to. Some guidance would be much appreciated.
Using the the ring is $\mathbb{F}\_2[x]/I$, I think this can then be simplified to $(x^4 +3x^2 +1) + I$ but I'm not sure if that's right and if it is right, I'm stuck on how to proceed.
|
2020/06/03
|
[
"https://math.stackexchange.com/questions/3703726",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] |
The polynomial is reducible over $\Bbb F\_2$, namely we have
$$
f=x^4 + 2x^3 +3x^2 +2x +1=(x^2 + x + 1)^2.
$$
Hence there are zero divisors and the quotient ring $\Bbb F\_2[x]/(f)$ is not an integral domain. For the same reason,
$$
\Bbb F\_2[x]/(x^3+1)
$$
has zero divisors, i.e., because $x^3+1$ is reducible over $\Bbb F\_2$.
|
All you have to check is whether the polynomial you wrote is irreducible or not. The polynomial you wrote modulo $\mathbb{F}\_2$ is $x^4+x^2+1=(x^2+x+1)^2$, obviously i used the “freshman’s dream”.
|
68,105,405 |
I have case statement below as
```
count(CASE WHEN time_lag / 10000 >= 0 AND time_lag / 1000 <= 50 THEN 1 END) AS [0 - 50]
```
but am getting error on syntax error, is there proper way to divide in case statement? thanks
|
2021/06/23
|
[
"https://Stackoverflow.com/questions/68105405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8797830/"
] |
Use the `vh` relative unit. `vh` stands for Viewport Height and can be used like so:
```css
html,
body {
height: 100vh;
}
```
This will tell the browser to use **100%** of the **viewport height**. There is also a `vw`, which controls the width relative to the viewport.
Read more on relative units on the [MDN page.](https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Values_and_units)
I'd recommend using [CSS Grid Layout](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout) to create your layout. Combine it with the `100vh` to first make your layout full height, and then divide the elements within it by creating a grid.
Look at the example below, specifically the CSS part. In there you see `grid-template-rows` where we define three rows of 20%, 70% and 10% height. Thats, 20, 70 and 10 percent of the `100vh` to divide.
With `grid-template-areas` we can name our rows and columns. Later on we need to tell the grid children *where* in the grid they are supposed to go. By naming our cells, we only have to reference the name of the cell at each child (see `grid-area` in the CSS).
```css
body {
margin: 0;
}
.grid {
display: grid;
grid-template-rows: 20% 70% 10%;
grid-template-columns: 1fr;
grid-template-areas:
"header"
"main"
"footer";
height: 100vh;
}
.grid-header {
grid-area: header;
background-color: blue;
}
.grid-main {
grid-area: main;
background-color: aqua;
}
.grid-footer {
grid-area: footer;
background-color: crimson;
}
```
```html
<body class="grid">
<header class="grid-header"></header>
<main class="grid-main"></main>
<footer class="grid-footer"></footer>
</body>
```
Alternatively you could divide your three main sections into `20vh`, `70vh` and `10vh` sections.
|
You should use this code for the `body`:
```css
body {
margin: 0;
height: 100vh;
}
```
You can learn more about units here: <https://www.w3schools.com/cssref/css_units.asp>
|
68,105,405 |
I have case statement below as
```
count(CASE WHEN time_lag / 10000 >= 0 AND time_lag / 1000 <= 50 THEN 1 END) AS [0 - 50]
```
but am getting error on syntax error, is there proper way to divide in case statement? thanks
|
2021/06/23
|
[
"https://Stackoverflow.com/questions/68105405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8797830/"
] |
Use the `vh` relative unit. `vh` stands for Viewport Height and can be used like so:
```css
html,
body {
height: 100vh;
}
```
This will tell the browser to use **100%** of the **viewport height**. There is also a `vw`, which controls the width relative to the viewport.
Read more on relative units on the [MDN page.](https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Values_and_units)
I'd recommend using [CSS Grid Layout](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout) to create your layout. Combine it with the `100vh` to first make your layout full height, and then divide the elements within it by creating a grid.
Look at the example below, specifically the CSS part. In there you see `grid-template-rows` where we define three rows of 20%, 70% and 10% height. Thats, 20, 70 and 10 percent of the `100vh` to divide.
With `grid-template-areas` we can name our rows and columns. Later on we need to tell the grid children *where* in the grid they are supposed to go. By naming our cells, we only have to reference the name of the cell at each child (see `grid-area` in the CSS).
```css
body {
margin: 0;
}
.grid {
display: grid;
grid-template-rows: 20% 70% 10%;
grid-template-columns: 1fr;
grid-template-areas:
"header"
"main"
"footer";
height: 100vh;
}
.grid-header {
grid-area: header;
background-color: blue;
}
.grid-main {
grid-area: main;
background-color: aqua;
}
.grid-footer {
grid-area: footer;
background-color: crimson;
}
```
```html
<body class="grid">
<header class="grid-header"></header>
<main class="grid-main"></main>
<footer class="grid-footer"></footer>
</body>
```
Alternatively you could divide your three main sections into `20vh`, `70vh` and `10vh` sections.
|
Set the heights for the header, section and footer with height: ...vh.
vh is the shortcut for viewport height.
```
...
header {
display: flex;
justify-content: center;
align-items: center;
height: 20vh;
background-color: blue;
padding: 30px 0;
font-size: 30px;
}
section {
height: 70vh;
display: flex;
}
footer {
height: 10vh;
border: solid 1px black;
background-color: crimson;
padding: 10px;
text-align: center;
}
...
```
|
68,105,405 |
I have case statement below as
```
count(CASE WHEN time_lag / 10000 >= 0 AND time_lag / 1000 <= 50 THEN 1 END) AS [0 - 50]
```
but am getting error on syntax error, is there proper way to divide in case statement? thanks
|
2021/06/23
|
[
"https://Stackoverflow.com/questions/68105405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8797830/"
] |
Use the `vh` relative unit. `vh` stands for Viewport Height and can be used like so:
```css
html,
body {
height: 100vh;
}
```
This will tell the browser to use **100%** of the **viewport height**. There is also a `vw`, which controls the width relative to the viewport.
Read more on relative units on the [MDN page.](https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Values_and_units)
I'd recommend using [CSS Grid Layout](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout) to create your layout. Combine it with the `100vh` to first make your layout full height, and then divide the elements within it by creating a grid.
Look at the example below, specifically the CSS part. In there you see `grid-template-rows` where we define three rows of 20%, 70% and 10% height. Thats, 20, 70 and 10 percent of the `100vh` to divide.
With `grid-template-areas` we can name our rows and columns. Later on we need to tell the grid children *where* in the grid they are supposed to go. By naming our cells, we only have to reference the name of the cell at each child (see `grid-area` in the CSS).
```css
body {
margin: 0;
}
.grid {
display: grid;
grid-template-rows: 20% 70% 10%;
grid-template-columns: 1fr;
grid-template-areas:
"header"
"main"
"footer";
height: 100vh;
}
.grid-header {
grid-area: header;
background-color: blue;
}
.grid-main {
grid-area: main;
background-color: aqua;
}
.grid-footer {
grid-area: footer;
background-color: crimson;
}
```
```html
<body class="grid">
<header class="grid-header"></header>
<main class="grid-main"></main>
<footer class="grid-footer"></footer>
</body>
```
Alternatively you could divide your three main sections into `20vh`, `70vh` and `10vh` sections.
|
I think adding a wrapper would solve the problem! The final code is like below:
```html
<style>
* {
box-sizing: border-box;
border: 0;
}
.wrapper {
display: flex;
height:100%;
flex-direction: column;
}
.wrapper > *{
display: flex;
flex:1;
}
header{
background-color: blue;
padding: 30px 0;
text-align: center;
font-size: 30px;
}
nav, article {
border: solid 1px black;
clear: both;
background-color: aqua;
}
nav {
flex: 1;
padding: 20px;
background-color: darkslateblue;
}
article {
text-align: center;
padding: 10px;
flex: 4;
}
footer {
border: solid 1px black;
background-color: crimson;
padding: 10px;
text-align: center;
}
</style>
</head>
<body>
<div class="wrapper">
<header>hello!</header>
<section>
<nav>
<ul>
<li><a href="">1</a></li>
<li><a href="">2</a></li>
<li><a href="">3</a></li>
<li><a href="">4</a></li>
</ul>
</nav>
<article>
<h2>hello</h2>
<p>hello how are you?</p>
</article>
</section>
<footer>this is footer</footer>
</div>
</body>
```
|
44,303 |
I cannot seem to figure out how to remove the Headers/Footers from *printed* Firefox pages. Could someone please show me the way?
(I'm using Firefox 3.5.3.)
|
2009/09/20
|
[
"https://superuser.com/questions/44303",
"https://superuser.com",
"https://superuser.com/users/991/"
] |
On the menu bar go to File → Print.
In the dialog that comes up, on the bottom you should be able to select to not print those, like I did below.

|
Just click File > Page Setup, then the second tab is "Margins & Header/Footer". You can change all the settings there to --blank--.

|
56,532,235 |
Click on `ŞHOW / HIDE` several times.
You'll see that after each click textarea becomes more and more higher.
What is the reason and how to avoid this.
I need the textarea always to fit the content.
```js
$('#btna').on('click', function(){
$('#txa').hide()
});
$('#btnb').on('click', function(){
$('#txa').show()
let a = $('#txa').prop('scrollHeight');
$('#txa').height(a);
});
```
```css
#txa, #txb{
display:block;
width:100%;
resize:none;
overflow:hidde;
}
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<textarea id='txa'>
lorem ipsum
lorem ipsum
</textarea>
<button id='btnb'>SHOW</button>
<button id='btna'>HIDE</button>
```
|
2019/06/10
|
[
"https://Stackoverflow.com/questions/56532235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3044737/"
] |
Please try this.
```js
$('#btna').on('click', function(){
$('#txa').hide()
});
$('#btnb').on('click', function(){
$('#txa').show()
});
autosize();
function autosize(){
var text = $('#txa');
text.each(function(){
$(this).attr('rows',1);
resize($(this));
});
text.on('input', function(){
resize($(this));
});
function resize ($text) {
$text.css('height', 'auto');
$text.css('height', $text[0].scrollHeight+'px');
}
}
```
```css
#txa, #txb{
display:block;
width:100%;
resize:none;
overflow:hidden;
}
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<textarea id='txa' name="md-content">
lorem ipsum
lorem ipsum
sdf
sdf
sdf
sdf
sdf
sdf
s
</textarea>
<button id='btnb'>SHOW</button>
<button id='btna'>HIDE</button>
```
|
Here you go, the height manipulation was unnecessary.
```js
$('#btna').on('click', function(){
$('#txa').hide()
});
$('#btnb').on('click', function(){
$('#txa').show()
});
```
```css
#txa, #txb{
display:block;
width:100%;
resize:none;
overflow:hidde;
}
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<textarea id='txa'>
lorem ipsum
lorem ipsum
</textarea>
<button id='btnb'>SHOW</button>
<button id='btna'>HIDE</button>
```
|
56,532,235 |
Click on `ŞHOW / HIDE` several times.
You'll see that after each click textarea becomes more and more higher.
What is the reason and how to avoid this.
I need the textarea always to fit the content.
```js
$('#btna').on('click', function(){
$('#txa').hide()
});
$('#btnb').on('click', function(){
$('#txa').show()
let a = $('#txa').prop('scrollHeight');
$('#txa').height(a);
});
```
```css
#txa, #txb{
display:block;
width:100%;
resize:none;
overflow:hidde;
}
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<textarea id='txa'>
lorem ipsum
lorem ipsum
</textarea>
<button id='btnb'>SHOW</button>
<button id='btna'>HIDE</button>
```
|
2019/06/10
|
[
"https://Stackoverflow.com/questions/56532235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3044737/"
] |
Please try this.
```js
$('#btna').on('click', function(){
$('#txa').hide()
});
$('#btnb').on('click', function(){
$('#txa').show()
});
autosize();
function autosize(){
var text = $('#txa');
text.each(function(){
$(this).attr('rows',1);
resize($(this));
});
text.on('input', function(){
resize($(this));
});
function resize ($text) {
$text.css('height', 'auto');
$text.css('height', $text[0].scrollHeight+'px');
}
}
```
```css
#txa, #txb{
display:block;
width:100%;
resize:none;
overflow:hidden;
}
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<textarea id='txa' name="md-content">
lorem ipsum
lorem ipsum
sdf
sdf
sdf
sdf
sdf
sdf
s
</textarea>
<button id='btnb'>SHOW</button>
<button id='btna'>HIDE</button>
```
|
Remove the following 2 lines from your script
```
let a = $('#txa').prop('scrollHeight');
$('#txa').height(a);
```
It still works and does not add an extra line in the textarea field.
|
62,001,013 |
I need to replace the salary status to `1` or `0` respectively if the salary is `greater than 50,000` or `less than or equal to 50,000` in a df.

The DataFrame shape:30162\*13
I have tried this:
```
data2['SalStat']=data2['SalStat'].map({"less than or equal to 50,000":0,"greater than 50,000":1})
```
I also tried `data2['SalStat']`
and `loc` without any success.
How can I do the same?
|
2020/05/25
|
[
"https://Stackoverflow.com/questions/62001013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11405742/"
] |
You can try like below:
```
RuleFor(u => u)
.Must(u => u.FirstPassword != u.SecondPassword)
.WithMessage("Second password are not allow to same as first password.");
```
Test Result:
[](https://i.stack.imgur.com/8E3ql.gif)
|
```
RuleFor(x => x.FirstPassword) .NotEmpty().WithMessage(localizer["{PropertyName} must not be empty."]) .MinimumLength(8);
RuleFor(x => x.SecondPassword) .NotEmpty().WithMessage(localizer["{PropertyName} must not be empty."]) .NotEqual(x => x.Password).WithMessage(localizer["{PropertyName} do not match."]);
```
|
18,207,873 |
I have an action on my controller that takes two parameters that should be captured when a form is posted:
```
[HttpPost]
public ActionResult Index(MyModel model, FormAction action)
```
The idea is that the model data should be captured in `MyModel` and the button that the user pressed should be captured in `FormAction`:
```
public class MyModel
{
public string MyValue { get; set; }
}
public class FormAction
{
public string Command { get; set; }
}
```
Here is my view:
```
@model TestApp.Models.MyModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
@using (Html.BeginForm("Index", "Home"))
{
@Html.TextBoxFor(x => x.MyValue)
<input type="submit" value="OK" name="command" />
<input type="submit" value="Cancel" name="command" />
}
</div>
</body>
</html>
```
If I add another string parameter to the action called 'command' then the value of the button comes through but it doesn't get bound to the `Command` property on the `FormAction` parameter - the parameter is always null.
If I add a `Command` property to `MyModel` then the button value does come through.
Is there something in MVC model binding that prevents more than one complex model to be bound in one action method?
|
2013/08/13
|
[
"https://Stackoverflow.com/questions/18207873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2417702/"
] |
Try this
```
$this->db->join('post_likes', "post_likes.user_id=$the_userid AND
post_likes.post_id=post.id", 'left');
```
or
```
$this->db->join('post_likes', 'post_likes.user_id="'.$the_userid.'" AND
post_likes.post_id=post.id', 'left');
```
Update:
Define
```
$db['default']['_protect_identifiers']= FALSE;
```
in "application/config/database.php" at the end.
|
try this one
```
$this->db->join('post_likes', 'post_likes.user_id="{$online_user}" AND post_likes.post_id=post.id', 'left');
```
please let me know if you face any problem.
|
18,207,873 |
I have an action on my controller that takes two parameters that should be captured when a form is posted:
```
[HttpPost]
public ActionResult Index(MyModel model, FormAction action)
```
The idea is that the model data should be captured in `MyModel` and the button that the user pressed should be captured in `FormAction`:
```
public class MyModel
{
public string MyValue { get; set; }
}
public class FormAction
{
public string Command { get; set; }
}
```
Here is my view:
```
@model TestApp.Models.MyModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
@using (Html.BeginForm("Index", "Home"))
{
@Html.TextBoxFor(x => x.MyValue)
<input type="submit" value="OK" name="command" />
<input type="submit" value="Cancel" name="command" />
}
</div>
</body>
</html>
```
If I add another string parameter to the action called 'command' then the value of the button comes through but it doesn't get bound to the `Command` property on the `FormAction` parameter - the parameter is always null.
If I add a `Command` property to `MyModel` then the button value does come through.
Is there something in MVC model binding that prevents more than one complex model to be bound in one action method?
|
2013/08/13
|
[
"https://Stackoverflow.com/questions/18207873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2417702/"
] |
Try this
```
$this->db->join('post_likes', "post_likes.user_id=$the_userid AND
post_likes.post_id=post.id", 'left');
```
or
```
$this->db->join('post_likes', 'post_likes.user_id="'.$the_userid.'" AND
post_likes.post_id=post.id', 'left');
```
Update:
Define
```
$db['default']['_protect_identifiers']= FALSE;
```
in "application/config/database.php" at the end.
|
Dont use `$this->db->escape`
```
$this->db->join('post_likes', 'post_likes.user_id="'.$online_user.'" AND post_likes.post_id=post.id', 'left');
```
|
18,207,873 |
I have an action on my controller that takes two parameters that should be captured when a form is posted:
```
[HttpPost]
public ActionResult Index(MyModel model, FormAction action)
```
The idea is that the model data should be captured in `MyModel` and the button that the user pressed should be captured in `FormAction`:
```
public class MyModel
{
public string MyValue { get; set; }
}
public class FormAction
{
public string Command { get; set; }
}
```
Here is my view:
```
@model TestApp.Models.MyModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
@using (Html.BeginForm("Index", "Home"))
{
@Html.TextBoxFor(x => x.MyValue)
<input type="submit" value="OK" name="command" />
<input type="submit" value="Cancel" name="command" />
}
</div>
</body>
</html>
```
If I add another string parameter to the action called 'command' then the value of the button comes through but it doesn't get bound to the `Command` property on the `FormAction` parameter - the parameter is always null.
If I add a `Command` property to `MyModel` then the button value does come through.
Is there something in MVC model binding that prevents more than one complex model to be bound in one action method?
|
2013/08/13
|
[
"https://Stackoverflow.com/questions/18207873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2417702/"
] |
You SHOULD not use the double quotes in SQL query:
```
$this->db->join('post_likes', "post_likes.user_id = $online_user AND post_likes.post_id=post.id", 'left');
```
### Update:
This is a bug in the current CI stable version (fixed in v3.0-DEV), CI ActiveRecord methods (which doesn't implement really ActiveRecord) are prepared for simple usages.
I fixed this issue before by hacking the core files (by adding a parameter to join method to disable `_protect_identifires`).
There we go:
In `system/database/DB_active_rec.php` line #310, add `$escape` as 4th parameter:
```
public function join($table, $cond, $type = '', $escape = TRUE)
```
And change `$match[3] = ...` to:
```
if ($escape === TRUE)
{
$match[3] = $this->_protect_identifiers($match[3]);
}
```
So, you can use `join($table, $cond, $type = '', $escape = FALSE)` to disable *escaping*.
In addition, setting `_protect_identifires` globally to `FALSE` is not in a correct direction.
the only option remains is using custom [`query()`](http://ellislab.com/codeigniter/user-guide/database/queries.html):
```
$sql = "SELECT * FROM some_table WHERE id = ?"
$this->db->query($sql, array(3));
```
|
Try this
```
$this->db->join('post_likes', "post_likes.user_id=$the_userid AND
post_likes.post_id=post.id", 'left');
```
or
```
$this->db->join('post_likes', 'post_likes.user_id="'.$the_userid.'" AND
post_likes.post_id=post.id', 'left');
```
Update:
Define
```
$db['default']['_protect_identifiers']= FALSE;
```
in "application/config/database.php" at the end.
|
18,207,873 |
I have an action on my controller that takes two parameters that should be captured when a form is posted:
```
[HttpPost]
public ActionResult Index(MyModel model, FormAction action)
```
The idea is that the model data should be captured in `MyModel` and the button that the user pressed should be captured in `FormAction`:
```
public class MyModel
{
public string MyValue { get; set; }
}
public class FormAction
{
public string Command { get; set; }
}
```
Here is my view:
```
@model TestApp.Models.MyModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
@using (Html.BeginForm("Index", "Home"))
{
@Html.TextBoxFor(x => x.MyValue)
<input type="submit" value="OK" name="command" />
<input type="submit" value="Cancel" name="command" />
}
</div>
</body>
</html>
```
If I add another string parameter to the action called 'command' then the value of the button comes through but it doesn't get bound to the `Command` property on the `FormAction` parameter - the parameter is always null.
If I add a `Command` property to `MyModel` then the button value does come through.
Is there something in MVC model binding that prevents more than one complex model to be bound in one action method?
|
2013/08/13
|
[
"https://Stackoverflow.com/questions/18207873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2417702/"
] |
You SHOULD not use the double quotes in SQL query:
```
$this->db->join('post_likes', "post_likes.user_id = $online_user AND post_likes.post_id=post.id", 'left');
```
### Update:
This is a bug in the current CI stable version (fixed in v3.0-DEV), CI ActiveRecord methods (which doesn't implement really ActiveRecord) are prepared for simple usages.
I fixed this issue before by hacking the core files (by adding a parameter to join method to disable `_protect_identifires`).
There we go:
In `system/database/DB_active_rec.php` line #310, add `$escape` as 4th parameter:
```
public function join($table, $cond, $type = '', $escape = TRUE)
```
And change `$match[3] = ...` to:
```
if ($escape === TRUE)
{
$match[3] = $this->_protect_identifiers($match[3]);
}
```
So, you can use `join($table, $cond, $type = '', $escape = FALSE)` to disable *escaping*.
In addition, setting `_protect_identifires` globally to `FALSE` is not in a correct direction.
the only option remains is using custom [`query()`](http://ellislab.com/codeigniter/user-guide/database/queries.html):
```
$sql = "SELECT * FROM some_table WHERE id = ?"
$this->db->query($sql, array(3));
```
|
try this one
```
$this->db->join('post_likes', 'post_likes.user_id="{$online_user}" AND post_likes.post_id=post.id', 'left');
```
please let me know if you face any problem.
|
18,207,873 |
I have an action on my controller that takes two parameters that should be captured when a form is posted:
```
[HttpPost]
public ActionResult Index(MyModel model, FormAction action)
```
The idea is that the model data should be captured in `MyModel` and the button that the user pressed should be captured in `FormAction`:
```
public class MyModel
{
public string MyValue { get; set; }
}
public class FormAction
{
public string Command { get; set; }
}
```
Here is my view:
```
@model TestApp.Models.MyModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
@using (Html.BeginForm("Index", "Home"))
{
@Html.TextBoxFor(x => x.MyValue)
<input type="submit" value="OK" name="command" />
<input type="submit" value="Cancel" name="command" />
}
</div>
</body>
</html>
```
If I add another string parameter to the action called 'command' then the value of the button comes through but it doesn't get bound to the `Command` property on the `FormAction` parameter - the parameter is always null.
If I add a `Command` property to `MyModel` then the button value does come through.
Is there something in MVC model binding that prevents more than one complex model to be bound in one action method?
|
2013/08/13
|
[
"https://Stackoverflow.com/questions/18207873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2417702/"
] |
Simple solution would be to temporarily set the protect\_identifiers off before join query, like so:
```
$this->db->_protect_identifiers = false;
```
After making join query you could set it back to `true`
Works for me in CodeIgniter version 2.1.2
|
try this one
```
$this->db->join('post_likes', 'post_likes.user_id="{$online_user}" AND post_likes.post_id=post.id', 'left');
```
please let me know if you face any problem.
|
18,207,873 |
I have an action on my controller that takes two parameters that should be captured when a form is posted:
```
[HttpPost]
public ActionResult Index(MyModel model, FormAction action)
```
The idea is that the model data should be captured in `MyModel` and the button that the user pressed should be captured in `FormAction`:
```
public class MyModel
{
public string MyValue { get; set; }
}
public class FormAction
{
public string Command { get; set; }
}
```
Here is my view:
```
@model TestApp.Models.MyModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
@using (Html.BeginForm("Index", "Home"))
{
@Html.TextBoxFor(x => x.MyValue)
<input type="submit" value="OK" name="command" />
<input type="submit" value="Cancel" name="command" />
}
</div>
</body>
</html>
```
If I add another string parameter to the action called 'command' then the value of the button comes through but it doesn't get bound to the `Command` property on the `FormAction` parameter - the parameter is always null.
If I add a `Command` property to `MyModel` then the button value does come through.
Is there something in MVC model binding that prevents more than one complex model to be bound in one action method?
|
2013/08/13
|
[
"https://Stackoverflow.com/questions/18207873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2417702/"
] |
You SHOULD not use the double quotes in SQL query:
```
$this->db->join('post_likes', "post_likes.user_id = $online_user AND post_likes.post_id=post.id", 'left');
```
### Update:
This is a bug in the current CI stable version (fixed in v3.0-DEV), CI ActiveRecord methods (which doesn't implement really ActiveRecord) are prepared for simple usages.
I fixed this issue before by hacking the core files (by adding a parameter to join method to disable `_protect_identifires`).
There we go:
In `system/database/DB_active_rec.php` line #310, add `$escape` as 4th parameter:
```
public function join($table, $cond, $type = '', $escape = TRUE)
```
And change `$match[3] = ...` to:
```
if ($escape === TRUE)
{
$match[3] = $this->_protect_identifiers($match[3]);
}
```
So, you can use `join($table, $cond, $type = '', $escape = FALSE)` to disable *escaping*.
In addition, setting `_protect_identifires` globally to `FALSE` is not in a correct direction.
the only option remains is using custom [`query()`](http://ellislab.com/codeigniter/user-guide/database/queries.html):
```
$sql = "SELECT * FROM some_table WHERE id = ?"
$this->db->query($sql, array(3));
```
|
Dont use `$this->db->escape`
```
$this->db->join('post_likes', 'post_likes.user_id="'.$online_user.'" AND post_likes.post_id=post.id', 'left');
```
|
18,207,873 |
I have an action on my controller that takes two parameters that should be captured when a form is posted:
```
[HttpPost]
public ActionResult Index(MyModel model, FormAction action)
```
The idea is that the model data should be captured in `MyModel` and the button that the user pressed should be captured in `FormAction`:
```
public class MyModel
{
public string MyValue { get; set; }
}
public class FormAction
{
public string Command { get; set; }
}
```
Here is my view:
```
@model TestApp.Models.MyModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
@using (Html.BeginForm("Index", "Home"))
{
@Html.TextBoxFor(x => x.MyValue)
<input type="submit" value="OK" name="command" />
<input type="submit" value="Cancel" name="command" />
}
</div>
</body>
</html>
```
If I add another string parameter to the action called 'command' then the value of the button comes through but it doesn't get bound to the `Command` property on the `FormAction` parameter - the parameter is always null.
If I add a `Command` property to `MyModel` then the button value does come through.
Is there something in MVC model binding that prevents more than one complex model to be bound in one action method?
|
2013/08/13
|
[
"https://Stackoverflow.com/questions/18207873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2417702/"
] |
Simple solution would be to temporarily set the protect\_identifiers off before join query, like so:
```
$this->db->_protect_identifiers = false;
```
After making join query you could set it back to `true`
Works for me in CodeIgniter version 2.1.2
|
Dont use `$this->db->escape`
```
$this->db->join('post_likes', 'post_likes.user_id="'.$online_user.'" AND post_likes.post_id=post.id', 'left');
```
|
18,207,873 |
I have an action on my controller that takes two parameters that should be captured when a form is posted:
```
[HttpPost]
public ActionResult Index(MyModel model, FormAction action)
```
The idea is that the model data should be captured in `MyModel` and the button that the user pressed should be captured in `FormAction`:
```
public class MyModel
{
public string MyValue { get; set; }
}
public class FormAction
{
public string Command { get; set; }
}
```
Here is my view:
```
@model TestApp.Models.MyModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
@using (Html.BeginForm("Index", "Home"))
{
@Html.TextBoxFor(x => x.MyValue)
<input type="submit" value="OK" name="command" />
<input type="submit" value="Cancel" name="command" />
}
</div>
</body>
</html>
```
If I add another string parameter to the action called 'command' then the value of the button comes through but it doesn't get bound to the `Command` property on the `FormAction` parameter - the parameter is always null.
If I add a `Command` property to `MyModel` then the button value does come through.
Is there something in MVC model binding that prevents more than one complex model to be bound in one action method?
|
2013/08/13
|
[
"https://Stackoverflow.com/questions/18207873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2417702/"
] |
You SHOULD not use the double quotes in SQL query:
```
$this->db->join('post_likes', "post_likes.user_id = $online_user AND post_likes.post_id=post.id", 'left');
```
### Update:
This is a bug in the current CI stable version (fixed in v3.0-DEV), CI ActiveRecord methods (which doesn't implement really ActiveRecord) are prepared for simple usages.
I fixed this issue before by hacking the core files (by adding a parameter to join method to disable `_protect_identifires`).
There we go:
In `system/database/DB_active_rec.php` line #310, add `$escape` as 4th parameter:
```
public function join($table, $cond, $type = '', $escape = TRUE)
```
And change `$match[3] = ...` to:
```
if ($escape === TRUE)
{
$match[3] = $this->_protect_identifiers($match[3]);
}
```
So, you can use `join($table, $cond, $type = '', $escape = FALSE)` to disable *escaping*.
In addition, setting `_protect_identifires` globally to `FALSE` is not in a correct direction.
the only option remains is using custom [`query()`](http://ellislab.com/codeigniter/user-guide/database/queries.html):
```
$sql = "SELECT * FROM some_table WHERE id = ?"
$this->db->query($sql, array(3));
```
|
Simple solution would be to temporarily set the protect\_identifiers off before join query, like so:
```
$this->db->_protect_identifiers = false;
```
After making join query you could set it back to `true`
Works for me in CodeIgniter version 2.1.2
|
52,637,338 |
I am using Python 3.6.5 64bit and the latest version of Selenium Webdriver and Google chromedriver. My IDE is Visual Studio Code.
I have been able to locate and use every element I have needed of hundreds over multiple web automation projects. I often use the Chrome developer console to identify and test for valid Xpath selectors.
Now I have an element that was identified and tested using Chrome developer console, but it does not work in my python script.
Given an HTML structure of:
```
<html>
<head>...</head>
<body>
<form name='someform'>
<table>
<tbody>
<tr>
<th>
<font>...</font>
<br>
"
This is the text I am searching for."
</th>
</tr>
<tr>
<td>
Content I am using
</td>
</tr>
<tr>
<td>
Content I am using
</td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
```
Chrome developer consoles gives an Xpath of:
"/html/body/form/table[1](https://i.stack.imgur.com/5YkqK.jpg)/tbody/tr[1](https://i.stack.imgur.com/5YkqK.jpg)/th"
and correctly identifies the element and can display all node data.
[](https://i.stack.imgur.com/5YkqK.jpg)
Also tested various versions of
contains(text(),'text I am')
which of course all work as expected, along with two or three other valid Xpath selectors.
The script has already made hundreds of selenium calls when I come to this in my code:
```
try:
tableHeader = driver.find_element_by_xpath("/html/body/form/table[1]/tbody/tr[1]/th")
#grab tableHeader text and do something with it...
except:
print("Selenium Error:", sys.exc()[0])
```
And all of these valid Xpaths fail:
```
Selenium Error: <class 'selenium.common.exceptions.NoSuchElementException'>
```
The page in question is much longer than the example above, but continues in the same simple structure. There are no iframes.
I cannot find any reason for this and am further frustrated by the fact that another part of the same script works with a different page on the same website that has the EXACT same structure and I can reference the exact same element on that page with the exact same Xpath selector with no issue.
The only thing I can think of is that the element contains a carriage return / newline before the text, as you can see above. I don't see how this would affect identifying the element.
Any ideas?
|
2018/10/04
|
[
"https://Stackoverflow.com/questions/52637338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5759901/"
] |
Have you tried finding a list of elements on the active page and seeing if any of those contain the element you are looking for?
```
tableHeaders = driver.find_elements_by_tag_name('th')
```
You should be able to navigate through tableHeaders and find the element where the Text value matches what you desire.
|
Good grief! I have tunnel vision... been staring at this screen for too long today. There were two calls, a hundred lines apart. I was trying the variations on the second call when in fact it was the first call above that was throwing the exception. It was there in front of me as obvious as the screens glaring back at me. I just wasted two hours on this.
My Xpath works perfectly well, as expected. As so often is the case, I was the problem.
|
5,728 |
I've been teaching Java and C# for years and I'll be picking up a web development (HTML, CSS, JS) course in the fall semester because our department is down a faculty member and won't be filling the position.
I can run unit tests on Java and C# to make sure the code students are submitting is correct without an issue, but I don't know how to efficiently assess websites. My school uses Cengage for curriculum delivery and their MindTap product does assessments, but I don't want to rely on that for the primary driver in class for a number of reasons.
How can I efficiently and effectively assess student work other than reading through all their code and observing every web page? There has to be some tool out there that I can work with to do an initial sweep for me... right?
|
2019/05/30
|
[
"https://cseducators.stackexchange.com/questions/5728",
"https://cseducators.stackexchange.com",
"https://cseducators.stackexchange.com/users/8104/"
] |
Much less detail than the excellent [post](https://cseducators.stackexchange.com/a/5730/104) by [Buffy](https://cseducators.stackexchange.com/users/1293), but directly to the question. Replace unit tests with validations and linters.
Have the students create all content in distinct files: HTML, CSS, and JS. Any styles or JavaScript in the `.html` file is *invalid* for the project(s). There are many validators and linters for all three, as well as for any other "code" you choose to use/allow, such as PHP, Ruby, etc.
Since a unit test only gives go/no-go results, a validator is at least as effective. A visual check of the resulting page/site shouldn't take but a few moments as well. If it validates and looks correct, it must be "right."
If you also wish to instill, or enforce, coding standards, comments, indentation, etc., a linter may help.
Running a series of validators and linters, checking the operations of the page/site, and visually scanning the code should take much less time than grading a paper-based exam, so you are still time ahead. If the students are provided access to similar tools, if not the exact ones, or exact settings you use, they can develop the habit of applying the "test" to their own code as part of their development work-flow.
---
As an extra note, if you need to compare versions/iterations of their code, you can use a system such as `git`, which need not be based on GitHub, or even use remote repos at all. Each student can be required to create a GPG key for their project work, and sign their commits. With that system, you can use the built-in diff function to see the changes and be certain who committed what.
|
For me, 60 is a very large class. Let me focus on a course design, extrapolated from other areas, in my case, the compiler course. The intent here is to make assessment feasible, rather than to say how to do it explicitly.
I would have two projects for the course. The first is individual and lasts two weeks. It would be to extend a framework that I provide and when completed would contain in the simplest way, the elements required for the larger project. It would count for a small portion of grading. But, I'd have to actually grade it. To make this feasible, I'd have them high light all changes from my base code.
The second project is done in teams. I'd choose the teams so that the total number is reasonable. Maybe five people per team, giving you about a dozen projects being done at once. I would also specify this project and possibly supply some base code giving a framework. Each team works separately on the project in parallel. It isn't a division of a larger project, but a "competition" of teams working on the same thing. With everyone working on the same project structure, I only have one thing to think about when grading.
I'd give them clear instructions about now NOT to manage their projects. No "dividing up the work" for example. Everyone is responsible for every part. I would try to convince them that dividing the work is actually more work for everyone since they need to integrate at some point. For beginners this is almost always a bad thing to do.
I would teach them how to run an agile team using something like XP. Iterations can be weekly or every other week. In particular, no one is permitted to commit code that only they worked on, avoiding the "prima donna" problem. I've had the teams name themselves, or I've named them, to build esprit d'corps: Fire, Ice, Wind, ....
I would also want to look at their code, but I now have a more reasonable work load. I would, again, have them highlight any changes they make from previous versions and include all past work (along with my comments) whenever they turn in the next iteration. It is now easy for me to see their progress. Each team turns in a folder each iteration.
I would (probably) require public demos of the projects at the end of the course, with each team having a few minutes to show their results. I normally require that everyone participate in the demo, but with five members per team it might be impossible.
I would use peer assessment within each team to get an idea about how people behave when not under my view. Peer assessment is always positive. "What is the main contribution of each team member? What is your own chief contribution?". Actually I usually, for a team of five, would have everyone give positive assessments of each of the top three contributors. If no one labels "jimmy" as a top contributor, I learn something. If everyone mentions "jimmy" I learn something else. But a positive assessment is more likely to be accurate and avoids the problem of people not wanting to say negative things about their friends.
Everyone gets the same grade on the big project unless there are serious reasons to do otherwise.
I have sometimes created (randomly) a "leader" of each team. The leader is not a manager, but is simply my main contact with each team so that I can get and give feedback when necessary. Try to do interventions early, if needed.
I usually use an asynchronous communication mechanism (a mailing list) so that anyone can ask a question at any time. I encourage others to answer questions as well as ask them, so I don't need to answer every question.
The goal is to reduce the load to a manageable level and still give individual feedback periodically. I haven't tried to automate grading in any way, but just made the scope of my problem more feasible.
Most of the course grade would be on the second project not the final exam (if any).
I could either use face time for lectures, or I could flip the classroom, letting the teams work together in lab and providing "content" through videos or readings done after hours. With a flipped design, I get to monitor each team in real time.
|
5,728 |
I've been teaching Java and C# for years and I'll be picking up a web development (HTML, CSS, JS) course in the fall semester because our department is down a faculty member and won't be filling the position.
I can run unit tests on Java and C# to make sure the code students are submitting is correct without an issue, but I don't know how to efficiently assess websites. My school uses Cengage for curriculum delivery and their MindTap product does assessments, but I don't want to rely on that for the primary driver in class for a number of reasons.
How can I efficiently and effectively assess student work other than reading through all their code and observing every web page? There has to be some tool out there that I can work with to do an initial sweep for me... right?
|
2019/05/30
|
[
"https://cseducators.stackexchange.com/questions/5728",
"https://cseducators.stackexchange.com",
"https://cseducators.stackexchange.com/users/8104/"
] |
For me, 60 is a very large class. Let me focus on a course design, extrapolated from other areas, in my case, the compiler course. The intent here is to make assessment feasible, rather than to say how to do it explicitly.
I would have two projects for the course. The first is individual and lasts two weeks. It would be to extend a framework that I provide and when completed would contain in the simplest way, the elements required for the larger project. It would count for a small portion of grading. But, I'd have to actually grade it. To make this feasible, I'd have them high light all changes from my base code.
The second project is done in teams. I'd choose the teams so that the total number is reasonable. Maybe five people per team, giving you about a dozen projects being done at once. I would also specify this project and possibly supply some base code giving a framework. Each team works separately on the project in parallel. It isn't a division of a larger project, but a "competition" of teams working on the same thing. With everyone working on the same project structure, I only have one thing to think about when grading.
I'd give them clear instructions about now NOT to manage their projects. No "dividing up the work" for example. Everyone is responsible for every part. I would try to convince them that dividing the work is actually more work for everyone since they need to integrate at some point. For beginners this is almost always a bad thing to do.
I would teach them how to run an agile team using something like XP. Iterations can be weekly or every other week. In particular, no one is permitted to commit code that only they worked on, avoiding the "prima donna" problem. I've had the teams name themselves, or I've named them, to build esprit d'corps: Fire, Ice, Wind, ....
I would also want to look at their code, but I now have a more reasonable work load. I would, again, have them highlight any changes they make from previous versions and include all past work (along with my comments) whenever they turn in the next iteration. It is now easy for me to see their progress. Each team turns in a folder each iteration.
I would (probably) require public demos of the projects at the end of the course, with each team having a few minutes to show their results. I normally require that everyone participate in the demo, but with five members per team it might be impossible.
I would use peer assessment within each team to get an idea about how people behave when not under my view. Peer assessment is always positive. "What is the main contribution of each team member? What is your own chief contribution?". Actually I usually, for a team of five, would have everyone give positive assessments of each of the top three contributors. If no one labels "jimmy" as a top contributor, I learn something. If everyone mentions "jimmy" I learn something else. But a positive assessment is more likely to be accurate and avoids the problem of people not wanting to say negative things about their friends.
Everyone gets the same grade on the big project unless there are serious reasons to do otherwise.
I have sometimes created (randomly) a "leader" of each team. The leader is not a manager, but is simply my main contact with each team so that I can get and give feedback when necessary. Try to do interventions early, if needed.
I usually use an asynchronous communication mechanism (a mailing list) so that anyone can ask a question at any time. I encourage others to answer questions as well as ask them, so I don't need to answer every question.
The goal is to reduce the load to a manageable level and still give individual feedback periodically. I haven't tried to automate grading in any way, but just made the scope of my problem more feasible.
Most of the course grade would be on the second project not the final exam (if any).
I could either use face time for lectures, or I could flip the classroom, letting the teams work together in lab and providing "content" through videos or readings done after hours. With a flipped design, I get to monitor each team in real time.
|
Assessing web dev courses at scale can be tricky because you have to consider the following:
* ensure that the resulting web app **looks** as expected
* all functionalities should work as expected with the **correct logic**
* the **code quality** to make everything work should meet the industry standard
With 60 students (or any number over 20 really), this can get really tricky.
---
My recommendation would be to find tools that help you do the following:
* Asses the looks: You should be able to preview the submission without downloading and running anything locally ([CodeSandbox](https://codesandbox.io/))
* Correct logic: Either run E2E tests and/or unit tests ([Puppeteer](https://pptr.dev/), [Jest](https://jestjs.io/))
* Code quality: linters ([ESLint](https://eslint.org/))
---
I would also recommend giving a try to [AutoGradr](https://autogradr.com) that does all of the above in a single tool and is built specifically for educators such as yourself. (Disclaimer: I'm the author of this free tool)
|
5,728 |
I've been teaching Java and C# for years and I'll be picking up a web development (HTML, CSS, JS) course in the fall semester because our department is down a faculty member and won't be filling the position.
I can run unit tests on Java and C# to make sure the code students are submitting is correct without an issue, but I don't know how to efficiently assess websites. My school uses Cengage for curriculum delivery and their MindTap product does assessments, but I don't want to rely on that for the primary driver in class for a number of reasons.
How can I efficiently and effectively assess student work other than reading through all their code and observing every web page? There has to be some tool out there that I can work with to do an initial sweep for me... right?
|
2019/05/30
|
[
"https://cseducators.stackexchange.com/questions/5728",
"https://cseducators.stackexchange.com",
"https://cseducators.stackexchange.com/users/8104/"
] |
For me, 60 is a very large class. Let me focus on a course design, extrapolated from other areas, in my case, the compiler course. The intent here is to make assessment feasible, rather than to say how to do it explicitly.
I would have two projects for the course. The first is individual and lasts two weeks. It would be to extend a framework that I provide and when completed would contain in the simplest way, the elements required for the larger project. It would count for a small portion of grading. But, I'd have to actually grade it. To make this feasible, I'd have them high light all changes from my base code.
The second project is done in teams. I'd choose the teams so that the total number is reasonable. Maybe five people per team, giving you about a dozen projects being done at once. I would also specify this project and possibly supply some base code giving a framework. Each team works separately on the project in parallel. It isn't a division of a larger project, but a "competition" of teams working on the same thing. With everyone working on the same project structure, I only have one thing to think about when grading.
I'd give them clear instructions about now NOT to manage their projects. No "dividing up the work" for example. Everyone is responsible for every part. I would try to convince them that dividing the work is actually more work for everyone since they need to integrate at some point. For beginners this is almost always a bad thing to do.
I would teach them how to run an agile team using something like XP. Iterations can be weekly or every other week. In particular, no one is permitted to commit code that only they worked on, avoiding the "prima donna" problem. I've had the teams name themselves, or I've named them, to build esprit d'corps: Fire, Ice, Wind, ....
I would also want to look at their code, but I now have a more reasonable work load. I would, again, have them highlight any changes they make from previous versions and include all past work (along with my comments) whenever they turn in the next iteration. It is now easy for me to see their progress. Each team turns in a folder each iteration.
I would (probably) require public demos of the projects at the end of the course, with each team having a few minutes to show their results. I normally require that everyone participate in the demo, but with five members per team it might be impossible.
I would use peer assessment within each team to get an idea about how people behave when not under my view. Peer assessment is always positive. "What is the main contribution of each team member? What is your own chief contribution?". Actually I usually, for a team of five, would have everyone give positive assessments of each of the top three contributors. If no one labels "jimmy" as a top contributor, I learn something. If everyone mentions "jimmy" I learn something else. But a positive assessment is more likely to be accurate and avoids the problem of people not wanting to say negative things about their friends.
Everyone gets the same grade on the big project unless there are serious reasons to do otherwise.
I have sometimes created (randomly) a "leader" of each team. The leader is not a manager, but is simply my main contact with each team so that I can get and give feedback when necessary. Try to do interventions early, if needed.
I usually use an asynchronous communication mechanism (a mailing list) so that anyone can ask a question at any time. I encourage others to answer questions as well as ask them, so I don't need to answer every question.
The goal is to reduce the load to a manageable level and still give individual feedback periodically. I haven't tried to automate grading in any way, but just made the scope of my problem more feasible.
Most of the course grade would be on the second project not the final exam (if any).
I could either use face time for lectures, or I could flip the classroom, letting the teams work together in lab and providing "content" through videos or readings done after hours. With a flipped design, I get to monitor each team in real time.
|
Another thought that comes to mind is that you can, to some extent, automate checking of web pages with [selenium](https://www.seleniumhq.org/). It would be a very large lift and your students would be forced to follow certain conventions in building their web pages but that may be an approach which could automate part of the work for you.
Just to insure I'm being clear, I'd envision you writing a set of tests which could automatically be run against the student web pages to check for the presence or absence of certain elements.
|
5,728 |
I've been teaching Java and C# for years and I'll be picking up a web development (HTML, CSS, JS) course in the fall semester because our department is down a faculty member and won't be filling the position.
I can run unit tests on Java and C# to make sure the code students are submitting is correct without an issue, but I don't know how to efficiently assess websites. My school uses Cengage for curriculum delivery and their MindTap product does assessments, but I don't want to rely on that for the primary driver in class for a number of reasons.
How can I efficiently and effectively assess student work other than reading through all their code and observing every web page? There has to be some tool out there that I can work with to do an initial sweep for me... right?
|
2019/05/30
|
[
"https://cseducators.stackexchange.com/questions/5728",
"https://cseducators.stackexchange.com",
"https://cseducators.stackexchange.com/users/8104/"
] |
For me, 60 is a very large class. Let me focus on a course design, extrapolated from other areas, in my case, the compiler course. The intent here is to make assessment feasible, rather than to say how to do it explicitly.
I would have two projects for the course. The first is individual and lasts two weeks. It would be to extend a framework that I provide and when completed would contain in the simplest way, the elements required for the larger project. It would count for a small portion of grading. But, I'd have to actually grade it. To make this feasible, I'd have them high light all changes from my base code.
The second project is done in teams. I'd choose the teams so that the total number is reasonable. Maybe five people per team, giving you about a dozen projects being done at once. I would also specify this project and possibly supply some base code giving a framework. Each team works separately on the project in parallel. It isn't a division of a larger project, but a "competition" of teams working on the same thing. With everyone working on the same project structure, I only have one thing to think about when grading.
I'd give them clear instructions about now NOT to manage their projects. No "dividing up the work" for example. Everyone is responsible for every part. I would try to convince them that dividing the work is actually more work for everyone since they need to integrate at some point. For beginners this is almost always a bad thing to do.
I would teach them how to run an agile team using something like XP. Iterations can be weekly or every other week. In particular, no one is permitted to commit code that only they worked on, avoiding the "prima donna" problem. I've had the teams name themselves, or I've named them, to build esprit d'corps: Fire, Ice, Wind, ....
I would also want to look at their code, but I now have a more reasonable work load. I would, again, have them highlight any changes they make from previous versions and include all past work (along with my comments) whenever they turn in the next iteration. It is now easy for me to see their progress. Each team turns in a folder each iteration.
I would (probably) require public demos of the projects at the end of the course, with each team having a few minutes to show their results. I normally require that everyone participate in the demo, but with five members per team it might be impossible.
I would use peer assessment within each team to get an idea about how people behave when not under my view. Peer assessment is always positive. "What is the main contribution of each team member? What is your own chief contribution?". Actually I usually, for a team of five, would have everyone give positive assessments of each of the top three contributors. If no one labels "jimmy" as a top contributor, I learn something. If everyone mentions "jimmy" I learn something else. But a positive assessment is more likely to be accurate and avoids the problem of people not wanting to say negative things about their friends.
Everyone gets the same grade on the big project unless there are serious reasons to do otherwise.
I have sometimes created (randomly) a "leader" of each team. The leader is not a manager, but is simply my main contact with each team so that I can get and give feedback when necessary. Try to do interventions early, if needed.
I usually use an asynchronous communication mechanism (a mailing list) so that anyone can ask a question at any time. I encourage others to answer questions as well as ask them, so I don't need to answer every question.
The goal is to reduce the load to a manageable level and still give individual feedback periodically. I haven't tried to automate grading in any way, but just made the scope of my problem more feasible.
Most of the course grade would be on the second project not the final exam (if any).
I could either use face time for lectures, or I could flip the classroom, letting the teams work together in lab and providing "content" through videos or readings done after hours. With a flipped design, I get to monitor each team in real time.
|
I think Buffy's answer is an excellent philosophy of how to solve this, but I would add a specific thing to it: dependency breaks.
Back when I was learning Compiler Construction, we were supposed to develop a Pascal compiler in several steps, each building on the next bit. If you couldn't solve part A, you couldn't even begin to work on part B. Or of your implementation of B was poor, you'd be hobbled in part C too. That's sliding towards "either you do this class excellently or you fail miserably". Not great for students.
So to avoid that, use dependency breaks. The first project should give you a setup for the next project, and that one for the last project. But after the first project has been handed in, graded, and feedback given, there's also a code skeleton available from which to start working on the second project, if you're not so happy with your first project.
Having explicit dependency breaks also makes it easier to reshuffle teams in between projects, in case students drop out of the class or members of a team have a falling out.
In summary: dependency breaks make the class more robust.
|
5,728 |
I've been teaching Java and C# for years and I'll be picking up a web development (HTML, CSS, JS) course in the fall semester because our department is down a faculty member and won't be filling the position.
I can run unit tests on Java and C# to make sure the code students are submitting is correct without an issue, but I don't know how to efficiently assess websites. My school uses Cengage for curriculum delivery and their MindTap product does assessments, but I don't want to rely on that for the primary driver in class for a number of reasons.
How can I efficiently and effectively assess student work other than reading through all their code and observing every web page? There has to be some tool out there that I can work with to do an initial sweep for me... right?
|
2019/05/30
|
[
"https://cseducators.stackexchange.com/questions/5728",
"https://cseducators.stackexchange.com",
"https://cseducators.stackexchange.com/users/8104/"
] |
Much less detail than the excellent [post](https://cseducators.stackexchange.com/a/5730/104) by [Buffy](https://cseducators.stackexchange.com/users/1293), but directly to the question. Replace unit tests with validations and linters.
Have the students create all content in distinct files: HTML, CSS, and JS. Any styles or JavaScript in the `.html` file is *invalid* for the project(s). There are many validators and linters for all three, as well as for any other "code" you choose to use/allow, such as PHP, Ruby, etc.
Since a unit test only gives go/no-go results, a validator is at least as effective. A visual check of the resulting page/site shouldn't take but a few moments as well. If it validates and looks correct, it must be "right."
If you also wish to instill, or enforce, coding standards, comments, indentation, etc., a linter may help.
Running a series of validators and linters, checking the operations of the page/site, and visually scanning the code should take much less time than grading a paper-based exam, so you are still time ahead. If the students are provided access to similar tools, if not the exact ones, or exact settings you use, they can develop the habit of applying the "test" to their own code as part of their development work-flow.
---
As an extra note, if you need to compare versions/iterations of their code, you can use a system such as `git`, which need not be based on GitHub, or even use remote repos at all. Each student can be required to create a GPG key for their project work, and sign their commits. With that system, you can use the built-in diff function to see the changes and be certain who committed what.
|
Assessing web dev courses at scale can be tricky because you have to consider the following:
* ensure that the resulting web app **looks** as expected
* all functionalities should work as expected with the **correct logic**
* the **code quality** to make everything work should meet the industry standard
With 60 students (or any number over 20 really), this can get really tricky.
---
My recommendation would be to find tools that help you do the following:
* Asses the looks: You should be able to preview the submission without downloading and running anything locally ([CodeSandbox](https://codesandbox.io/))
* Correct logic: Either run E2E tests and/or unit tests ([Puppeteer](https://pptr.dev/), [Jest](https://jestjs.io/))
* Code quality: linters ([ESLint](https://eslint.org/))
---
I would also recommend giving a try to [AutoGradr](https://autogradr.com) that does all of the above in a single tool and is built specifically for educators such as yourself. (Disclaimer: I'm the author of this free tool)
|
5,728 |
I've been teaching Java and C# for years and I'll be picking up a web development (HTML, CSS, JS) course in the fall semester because our department is down a faculty member and won't be filling the position.
I can run unit tests on Java and C# to make sure the code students are submitting is correct without an issue, but I don't know how to efficiently assess websites. My school uses Cengage for curriculum delivery and their MindTap product does assessments, but I don't want to rely on that for the primary driver in class for a number of reasons.
How can I efficiently and effectively assess student work other than reading through all their code and observing every web page? There has to be some tool out there that I can work with to do an initial sweep for me... right?
|
2019/05/30
|
[
"https://cseducators.stackexchange.com/questions/5728",
"https://cseducators.stackexchange.com",
"https://cseducators.stackexchange.com/users/8104/"
] |
Much less detail than the excellent [post](https://cseducators.stackexchange.com/a/5730/104) by [Buffy](https://cseducators.stackexchange.com/users/1293), but directly to the question. Replace unit tests with validations and linters.
Have the students create all content in distinct files: HTML, CSS, and JS. Any styles or JavaScript in the `.html` file is *invalid* for the project(s). There are many validators and linters for all three, as well as for any other "code" you choose to use/allow, such as PHP, Ruby, etc.
Since a unit test only gives go/no-go results, a validator is at least as effective. A visual check of the resulting page/site shouldn't take but a few moments as well. If it validates and looks correct, it must be "right."
If you also wish to instill, or enforce, coding standards, comments, indentation, etc., a linter may help.
Running a series of validators and linters, checking the operations of the page/site, and visually scanning the code should take much less time than grading a paper-based exam, so you are still time ahead. If the students are provided access to similar tools, if not the exact ones, or exact settings you use, they can develop the habit of applying the "test" to their own code as part of their development work-flow.
---
As an extra note, if you need to compare versions/iterations of their code, you can use a system such as `git`, which need not be based on GitHub, or even use remote repos at all. Each student can be required to create a GPG key for their project work, and sign their commits. With that system, you can use the built-in diff function to see the changes and be certain who committed what.
|
Another thought that comes to mind is that you can, to some extent, automate checking of web pages with [selenium](https://www.seleniumhq.org/). It would be a very large lift and your students would be forced to follow certain conventions in building their web pages but that may be an approach which could automate part of the work for you.
Just to insure I'm being clear, I'd envision you writing a set of tests which could automatically be run against the student web pages to check for the presence or absence of certain elements.
|
5,728 |
I've been teaching Java and C# for years and I'll be picking up a web development (HTML, CSS, JS) course in the fall semester because our department is down a faculty member and won't be filling the position.
I can run unit tests on Java and C# to make sure the code students are submitting is correct without an issue, but I don't know how to efficiently assess websites. My school uses Cengage for curriculum delivery and their MindTap product does assessments, but I don't want to rely on that for the primary driver in class for a number of reasons.
How can I efficiently and effectively assess student work other than reading through all their code and observing every web page? There has to be some tool out there that I can work with to do an initial sweep for me... right?
|
2019/05/30
|
[
"https://cseducators.stackexchange.com/questions/5728",
"https://cseducators.stackexchange.com",
"https://cseducators.stackexchange.com/users/8104/"
] |
Much less detail than the excellent [post](https://cseducators.stackexchange.com/a/5730/104) by [Buffy](https://cseducators.stackexchange.com/users/1293), but directly to the question. Replace unit tests with validations and linters.
Have the students create all content in distinct files: HTML, CSS, and JS. Any styles or JavaScript in the `.html` file is *invalid* for the project(s). There are many validators and linters for all three, as well as for any other "code" you choose to use/allow, such as PHP, Ruby, etc.
Since a unit test only gives go/no-go results, a validator is at least as effective. A visual check of the resulting page/site shouldn't take but a few moments as well. If it validates and looks correct, it must be "right."
If you also wish to instill, or enforce, coding standards, comments, indentation, etc., a linter may help.
Running a series of validators and linters, checking the operations of the page/site, and visually scanning the code should take much less time than grading a paper-based exam, so you are still time ahead. If the students are provided access to similar tools, if not the exact ones, or exact settings you use, they can develop the habit of applying the "test" to their own code as part of their development work-flow.
---
As an extra note, if you need to compare versions/iterations of their code, you can use a system such as `git`, which need not be based on GitHub, or even use remote repos at all. Each student can be required to create a GPG key for their project work, and sign their commits. With that system, you can use the built-in diff function to see the changes and be certain who committed what.
|
I think Buffy's answer is an excellent philosophy of how to solve this, but I would add a specific thing to it: dependency breaks.
Back when I was learning Compiler Construction, we were supposed to develop a Pascal compiler in several steps, each building on the next bit. If you couldn't solve part A, you couldn't even begin to work on part B. Or of your implementation of B was poor, you'd be hobbled in part C too. That's sliding towards "either you do this class excellently or you fail miserably". Not great for students.
So to avoid that, use dependency breaks. The first project should give you a setup for the next project, and that one for the last project. But after the first project has been handed in, graded, and feedback given, there's also a code skeleton available from which to start working on the second project, if you're not so happy with your first project.
Having explicit dependency breaks also makes it easier to reshuffle teams in between projects, in case students drop out of the class or members of a team have a falling out.
In summary: dependency breaks make the class more robust.
|
5,728 |
I've been teaching Java and C# for years and I'll be picking up a web development (HTML, CSS, JS) course in the fall semester because our department is down a faculty member and won't be filling the position.
I can run unit tests on Java and C# to make sure the code students are submitting is correct without an issue, but I don't know how to efficiently assess websites. My school uses Cengage for curriculum delivery and their MindTap product does assessments, but I don't want to rely on that for the primary driver in class for a number of reasons.
How can I efficiently and effectively assess student work other than reading through all their code and observing every web page? There has to be some tool out there that I can work with to do an initial sweep for me... right?
|
2019/05/30
|
[
"https://cseducators.stackexchange.com/questions/5728",
"https://cseducators.stackexchange.com",
"https://cseducators.stackexchange.com/users/8104/"
] |
Assessing web dev courses at scale can be tricky because you have to consider the following:
* ensure that the resulting web app **looks** as expected
* all functionalities should work as expected with the **correct logic**
* the **code quality** to make everything work should meet the industry standard
With 60 students (or any number over 20 really), this can get really tricky.
---
My recommendation would be to find tools that help you do the following:
* Asses the looks: You should be able to preview the submission without downloading and running anything locally ([CodeSandbox](https://codesandbox.io/))
* Correct logic: Either run E2E tests and/or unit tests ([Puppeteer](https://pptr.dev/), [Jest](https://jestjs.io/))
* Code quality: linters ([ESLint](https://eslint.org/))
---
I would also recommend giving a try to [AutoGradr](https://autogradr.com) that does all of the above in a single tool and is built specifically for educators such as yourself. (Disclaimer: I'm the author of this free tool)
|
Another thought that comes to mind is that you can, to some extent, automate checking of web pages with [selenium](https://www.seleniumhq.org/). It would be a very large lift and your students would be forced to follow certain conventions in building their web pages but that may be an approach which could automate part of the work for you.
Just to insure I'm being clear, I'd envision you writing a set of tests which could automatically be run against the student web pages to check for the presence or absence of certain elements.
|
5,728 |
I've been teaching Java and C# for years and I'll be picking up a web development (HTML, CSS, JS) course in the fall semester because our department is down a faculty member and won't be filling the position.
I can run unit tests on Java and C# to make sure the code students are submitting is correct without an issue, but I don't know how to efficiently assess websites. My school uses Cengage for curriculum delivery and their MindTap product does assessments, but I don't want to rely on that for the primary driver in class for a number of reasons.
How can I efficiently and effectively assess student work other than reading through all their code and observing every web page? There has to be some tool out there that I can work with to do an initial sweep for me... right?
|
2019/05/30
|
[
"https://cseducators.stackexchange.com/questions/5728",
"https://cseducators.stackexchange.com",
"https://cseducators.stackexchange.com/users/8104/"
] |
Assessing web dev courses at scale can be tricky because you have to consider the following:
* ensure that the resulting web app **looks** as expected
* all functionalities should work as expected with the **correct logic**
* the **code quality** to make everything work should meet the industry standard
With 60 students (or any number over 20 really), this can get really tricky.
---
My recommendation would be to find tools that help you do the following:
* Asses the looks: You should be able to preview the submission without downloading and running anything locally ([CodeSandbox](https://codesandbox.io/))
* Correct logic: Either run E2E tests and/or unit tests ([Puppeteer](https://pptr.dev/), [Jest](https://jestjs.io/))
* Code quality: linters ([ESLint](https://eslint.org/))
---
I would also recommend giving a try to [AutoGradr](https://autogradr.com) that does all of the above in a single tool and is built specifically for educators such as yourself. (Disclaimer: I'm the author of this free tool)
|
I think Buffy's answer is an excellent philosophy of how to solve this, but I would add a specific thing to it: dependency breaks.
Back when I was learning Compiler Construction, we were supposed to develop a Pascal compiler in several steps, each building on the next bit. If you couldn't solve part A, you couldn't even begin to work on part B. Or of your implementation of B was poor, you'd be hobbled in part C too. That's sliding towards "either you do this class excellently or you fail miserably". Not great for students.
So to avoid that, use dependency breaks. The first project should give you a setup for the next project, and that one for the last project. But after the first project has been handed in, graded, and feedback given, there's also a code skeleton available from which to start working on the second project, if you're not so happy with your first project.
Having explicit dependency breaks also makes it easier to reshuffle teams in between projects, in case students drop out of the class or members of a team have a falling out.
In summary: dependency breaks make the class more robust.
|
16,097,453 |
I have [data](http://dpaste.com/1064360/plain/) that contain 54 samples for each condition (x and y).
I have computed the correlation the following way:
```
> dat <- read.table("http://dpaste.com/1064360/plain/",header=TRUE)
> cor(dat$x,dat$y)
[1] 0.2870823
```
Is there a native way to produce SE of correlation in R's cor() functions above
and p-value from T-test?
As explained in this [web](http://www.sjsu.edu/faculty/gerstman/StatPrimer/correlation.pdf) (page 14.6)
|
2013/04/19
|
[
"https://Stackoverflow.com/questions/16097453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/67405/"
] |
I think that what you're looking for is simply the `cor.test()` function, which will return everything you're looking for except for the standard error of correlation. However, as you can see, the formula for that is very straightforward, and if you use `cor.test`, you have all the inputs required to calculate it.
Using the data from the example (so you can compare it yourself with the results on page 14.6):
```
> cor.test(mydf$X, mydf$Y)
Pearson's product-moment correlation
data: mydf$X and mydf$Y
t = -5.0867, df = 10, p-value = 0.0004731
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
-0.9568189 -0.5371871
sample estimates:
cor
-0.8492663
```
If you wanted to, you could also create a function like the following to include the standard error of the correlation coefficient.
For convenience, here's the equation:

*r* = the correlation estimate and *n* - 2 = degrees of freedom, both of which are readily available in the output above. Thus, a simple function could be:
```
cor.test.plus <- function(x) {
list(x,
Standard.Error = unname(sqrt((1 - x$estimate^2)/x$parameter)))
}
```
And use it as follows:
```
cor.test.plus(cor.test(mydf$X, mydf$Y))
```
Here, "mydf" is defined as:
```
mydf <- structure(list(Neighborhood = c("Fair Oaks", "Strandwood", "Walnut Acres",
"Discov. Bay", "Belshaw", "Kennedy", "Cassell", "Miner", "Sedgewick",
"Sakamoto", "Toyon", "Lietz"), X = c(50L, 11L, 2L, 19L, 26L,
73L, 81L, 51L, 11L, 2L, 19L, 25L), Y = c(22.1, 35.9, 57.9, 22.2,
42.4, 5.8, 3.6, 21.4, 55.2, 33.3, 32.4, 38.4)), .Names = c("Neighborhood",
"X", "Y"), class = "data.frame", row.names = c(NA, -12L))
```
|
Can't you simply take the test statistic from the return value? Of course the test statistic is the estimate/se so you can calc se from just dividing the estimate by the tstat:
Using `mydf` in the answer above:
```
r = cor.test(mydf$X, mydf$Y)
tstat = r$statistic
estimate = r$estimate
estimate; tstat
cor
-0.8492663
t
-5.086732
```
|
55,795,775 |
Please let us know how to remove "Microsoft Power BI" footer from the report while publishing to web.
Please find the below snapshot.
[](https://i.stack.imgur.com/XpbvZ.jpg)
|
2019/04/22
|
[
"https://Stackoverflow.com/questions/55795775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10249366/"
] |
You cannot, Power bi gives back an Iframe, and you have no control over it. If you want to have this control use power bi embedded instead.
|
Link Powerbi + &navContentPaneEnabled=false
|
38,854,968 |
I would like to (ab-)use Core Animation or even UIDynamics to generate animated values (floats) that I could use to control other parameters.
E.g. Having an animation with an ease in, I would like to control a color with an 'eased' value.
|
2016/08/09
|
[
"https://Stackoverflow.com/questions/38854968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/624459/"
] |
Core Animation can certainly do this for you. You need to create a `CALayer` subclass that has a new property you'd like to animate:
```
class CustomLayer: CALayer {
@NSManaged var colorPercentage: Float
override required init(layer: AnyObject) {
super.init(layer: layer)
if let layer = layer as? CustomLayer {
colorPercentage = layer.colorPercentage
} else {
colorPercentage = 0.0
}
}
required init?(coder decoder: NSCoder) {
super.init(coder: decoder)
}
override class func needsDisplay(forKey key: String) -> Bool {
var needsDisplay = super.needsDisplay(forKey: key)
if key == "colorPercentage" {
needsDisplay = true
}
return needsDisplay
}
override func action(forKey key: String) -> CAAction? {
var action = super.action(forKey: key)
if key == "colorPercentage" {
action = super.action(forKey: "opacity") // Create reference action from an existing CALayer key
if let action = action as? CABasicAnimation {
action.keyPath = key
action.fromValue = value(forKeyPath: key)
}
}
return action
}
override func display() {
guard let presentationLayer = presentation() else { return }
print("Current 'colorPercentage' value: \(presentationLayer.colorPercentage)")
// Called for every frame of an animation involving "colorPercentage"
}
}
```
(In Swift, `@NSManaged` is a hack currently necessary for Core Animation to treat `colorPercentage` as an Objective-C `@dynamic` property.)
Following this pattern, you can create a custom layer that contains your own animatable properties. `display()` will be called for every frame of the animation on the main thread, so you can respond to value changes over time however you'd like:
```
let animation = CABasicAnimation(keyPath: "colorPercentage")
animation.duration = 1.0
animation.fromValue = customLayer.colorPercentage
customLayer.colorPercentage = 1.0
customLayer.add(animation, forKey: "colorPercentageAnimation")
```
As a bonus, `action(forKey:)` can be used to create an action from a "reference animation" that Core Animation knows about and configures it to work with your custom property. With this, it's possible to invoke `CALayer` animations inside UIKit-style animation closures, which are much more convenient to use:
```
UIView.animate(withDuration: 1.0, animations: {
customLayer.colorPercentage = 1.0
})
```
|
My best guess is to use [CADisplayLink](https://developer.apple.com/library/ios/documentation/QuartzCore/Reference/CADisplayLink_ClassRef/). See this [post](http://mokagio.github.io/tech-journal/2015/02/23/ios-animating-with-cadisplaylink.html). Changes of an animation are not observable by KVO.
|
375,774 |
[UPDATE] This issue seems to be fixed in 10.15.2.
---
**Device, OS version and other background info:**
* MacBook Pro Retina late-2013, Catalina 10.15.1
* FileVault is not enabled.
* iCloud Desktop/Document syncing is not enabled.
* Time Machine backup stored on an external drive; auto-backup is temporarily disabled.
* Daemons, extensions and login items:
+ Alfred 4
+ BetterTouchTool
+ DropBox
+ Calendar 366
+ Logitech Option
**Problem description:**
All files under ~/Desktop path are inaccessible by most applications, including Finder:
* Double click on the file or choose from "File > Open..." within application both fail to open the file. The error message of open dialog claimed "The document XXXX could not be opened."
* Files can be renamed in Finder, can quick view the content, and can be copied to other directory, but can not be moved out of Desktop or delete.
* Files in other directories can not be copied or moved to Desktop and applications can not save files to Desktop either; the error message of save dialog claimed "The file 'Desktop' couldn't be opened".
* Finder can still create new folder on Desktop and it can be opened, but it can't be moved or deleted as well, files from other directory can be moved into these folders, but the moved files will become inaccessible too.
Reboot can temporarily solve this issue, but logout and re-login and this situation will happen again. Create a new account on the same machine and it is not affected by the same problem so far.
**Possible cause of problem:**
This problem seems to only affect applications that use Launch Service, because other applications that use conventional POSIX file I/O are not affected. All CLI utilities in Terminal can read, create, write and delete all these files, including `vi`, `cp`, `mv`, `rm` command; pipelined commands like `echo hello > ~/Desktop/hello.txt` are still functional and new files will be created on desktop, but these newly created files can not be opened by TextEdit.app as well.
Other applications like Visual Studio Code can also open and write to the files without problem. It also worth mentioning that web browsers like Safari, Chrome and Firefox can open and read the content, but I'd guess that's because web browsers are specially coded to tolerate read error and partial contents.
FileVault is not enabled; and this is an old model so it's not T2 and file system encryption related issue. **Permission is irrelevant to this issue because Visual Studio Code can access these affected files normally**. Adding applications like TextEdit to full disk access does not help either.
I guess that the problem is related to Launch Service, like a broken database file or something, but I've no idea how to identify the source of trouble. Tried to search related logs in Console.app but don't know where to start.
**Temporary measures:**
Reboot everyday.
Please help.
[EDIT] **NO PERMISSION IS IRRELEVANT TO THIS ISSUE**. That’s the first thing I’ve checked. All permission is set normally and **NOTHING IS LOCKED**. It just will revert back to normal right after rebooting— without doing anything else. And applications that use conventional POSIX I/O can still work perfectly normal.
|
2019/11/22
|
[
"https://apple.stackexchange.com/questions/375774",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/18405/"
] |
I have the same issue. My USBC hub is Deltaco USBC 1266.
You probably don't need to reboot, just move the keyboard from one slot to another or move the whole dongle from one port to another. This usually resolves it for me.
I had this problem when the computer was new in 2016. Whatever the OS was then. And I got it again after upgrading to Catalina.
|
I am using a 2019 Macbook Pro 13" with Mac OS 10.15.3 (Catalina). I have a Dell D6000 USB-C dock and a Dell P2419HC USB-C monitor that can act as a USB-C hub. With both of these docks/hubs, I have the issue where I will plug in the USB-C cable to the Macbook Pro 13" and sometimes the USB devices or monitors will be recognized and sometimes they won't. Additionally, sometimes the Dell D6000 will provide power to the laptop and other times it won't.
Essentially, each time I plug the USB-C cable in to the laptop, it is completely random as to whether things will work or not, and this behavior occurs with both the monitor hub and the dock. If I unplug and replug the cable in multiple times, it will eventually work... sometimes on the first try, second try, or third try. Sometimes I will reconnect the cable 5-6 times before I get all external devices to be recognized PLUS power to the laptop.
I have reset the SMC and the NVRAM with no luck. I almost returned the D6000 dock until I realized the monitor was behaving the same way. I have a CalDigit Thunderbolt 2 Dock that I can plugin to the same laptop using a Thunderbolt 2 to Thunderbolt 3 adapter, and when using this approach, the USB devices show up every single time I disconnect and reconnect, leading me to believe that this could be a Dell hardware problem, or something about how the Dell devices work with Apple's hardware or OS. However the original post references an Anker device, and another post Deltaco, so it's tricky to know if this has something to do with Thunderbolt 3, or just with 3rd party vendors using USB-C.
So, my long-winded answer would be try disconnecting and reconnecting until everything works fine. Or try some other hardware or device to see what happens, I just don't have the disposable income to throw around testing this out.
|
58,876,225 |
How to integrate screen time/ Parental control API in iOS app. Is screen time api available?
I tried with MDM(Mobile device management) but I am unable to create the MDM CSR. As there is no option for this certificate on developer account.
Please guide me if you have any solution. Basically I want to create an app having restrictions like screen time in iPhone or parental control app.
|
2019/11/15
|
[
"https://Stackoverflow.com/questions/58876225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9858609/"
] |
I did research and setting compiler flags solved the problem.
Earlier they were blank and the way Xcode UI is I got confused how to edit them they looked disabled.
So what you have to do is double tap on the side of the flags or press enter and add the following values as I had attached the screenshot below.
[](https://i.stack.imgur.com/kx98J.png)
|
`DEBUG` is the only default swift flag on a new project. You can create your own in your project build settings, `Other Swift Flags`.
Otherwise:
```
#if DEBUG
// This code will be run while installing from Xcode
#else
// This code will be run from AppStore, Adhoc ...
#endif
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.