问:
App Crashes throwing an exception of permission denial:reading com.android.providers.media.MediaProvider
I am developing an app which needs permission to read and write External Storage.i have write all the permissions in Manifest file as well as also in my java activity file but my app still got crashed as soon as it starts
 with throwing an Exception of

permission denial:reading com.android.providers.media.MediaProvider

Manifest File

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.abhi.scrolling_tab">

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL"></uses-permission>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:exported="true"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".Fragment_one"
        android:label="Fragment_one"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name=".Fragment_two"
        android:label="@string/title_activity_fragment_two"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name=".Fragment_three"
        android:label="@string/title_activity_fragment_three"
        android:theme="@style/AppTheme.NoActionBar"></activity>
</application>
</code>```

Java File

```<code>public class Fragment_two extends Fragment {
private RecyclerView recyclerView2;
private List<Model1> modelList;
private myAdapter2 adapter;
private MenuItem menu;

public Fragment_two() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.activity_fragment_two, container, false);
    ;
    recyclerView2 = (RecyclerView) view.findViewById(R.id.recycle2);
    int No_of_coloumns = 3;
    recyclerView2.setLayoutManager(new GridLayoutManager(getContext(), No_of_coloumns));
    modelList = getAllaudiofromdevice();
    adapter = new myAdapter2(modelList, (ViewGroup) view);
    recyclerView2.setAdapter(adapter);
    return view;
}

public List<Model1> getAllaudiofromdevice() {
    List<Model1> files = new ArrayList<>();
    try {
        ContentResolver contentResolver = getContext().getContentResolver();
        String selection = MediaStore.Audio.Media.IS_MUSIC;
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        String[] projection = {MediaStore.Audio.AudioColumns.DATA, MediaStore.Audio.AudioColumns.ALBUM, MediaStore.Audio.AudioColumns.ARTIST};
        Cursor c = contentResolver.query(uri, null, selection, null, null);
        if (c != null) {
            while (c.moveToNext()) {
                Model1 model1 = new Model1();
                String path = c.getString(0);
                String album = c.getString(1);
                String artist = c.getString(2);
                String name = path.substring(path.lastIndexOf('/') + 1);
                model1.setName(name);
                model1.setArtist(artist);
                model1.setAlbum(album);
                model1.setPath(path);
                files.add(model1);
            }
            c.close();
        }
    } catch (Exception e) {
        throw e;
    }
    check();
    return files;
}

public void check() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 123);
            return;
        }
    } else {
        getAllaudiofromdevice();
    }
}

@Override
public void onRequestPermissionsResult(int requestcode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestcode) {
        case 123:
            if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                getAllaudiofromdevice();
            } else {
                Toast.makeText(getContext(), "you have to set permissions", Toast.LENGTH_SHORT).show();
                check();
            }
        default:
            super.onRequestPermissionsResult(requestcode, permissions, grantResults);
    }

}
</code>```

}

Please help me to get out of this.
Thanks in the anticipation.

答:
Only do work when the permission is granted. Your code contains a logical error:

```<code>if (grantResults[0] != PackageManager.PERMISSION_GRANTED) { // Mistake here.
    getAllaudiofromdevice();
} //...
</code>```

Also on API 23 your code will request permissions when they're not granted, but will do nothing(*) when they already are granted. It should be like this:

```<code>public void check() {
    if (Build.VERSION.SDK_INT >= 23 && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        // Request permissions if they're not granted on API 23.
        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 123);
    } else {
        // Do work on API <23 and when permissions were granted on API 23+.
        getAllaudiofromdevice();
    }
}
</code>```

(*) Depending on how you call your code, it's really confusing.

Body:
I am developing an app which needs permission to read and write External Storage.i have write all the permissions in Manifest file as well as also in my java activity file but my app still got crashed as soon as it starts
 with throwing an Exception of

permission denial:reading com.android.providers.media.MediaProvider

Manifest File

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.abhi.scrolling_tab">

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL"></uses-permission>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:exported="true"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".Fragment_one"
        android:label="Fragment_one"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name=".Fragment_two"
        android:label="@string/title_activity_fragment_two"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name=".Fragment_three"
        android:label="@string/title_activity_fragment_three"
        android:theme="@style/AppTheme.NoActionBar"></activity>
</application>

Java File

public class Fragment_two extends Fragment {
private RecyclerView recyclerView2;
private List<Model1> modelList;
private myAdapter2 adapter;
private MenuItem menu;

public Fragment_two() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.activity_fragment_two, container, false);
    ;
    recyclerView2 = (RecyclerView) view.findViewById(R.id.recycle2);
    int No_of_coloumns = 3;
    recyclerView2.setLayoutManager(new GridLayoutManager(getContext(), No_of_coloumns));
    modelList = getAllaudiofromdevice();
    adapter = new myAdapter2(modelList, (ViewGroup) view);
    recyclerView2.setAdapter(adapter);
    return view;
}

public List<Model1> getAllaudiofromdevice() {
    List<Model1> files = new ArrayList<>();
    try {
        ContentResolver contentResolver = getContext().getContentResolver();
        String selection = MediaStore.Audio.Media.IS_MUSIC;
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        String[] projection = {MediaStore.Audio.AudioColumns.DATA, MediaStore.Audio.AudioColumns.ALBUM, MediaStore.Audio.AudioColumns.ARTIST};
        Cursor c = contentResolver.query(uri, null, selection, null, null);
        if (c != null) {
            while (c.moveToNext()) {
                Model1 model1 = new Model1();
                String path = c.getString(0);
                String album = c.getString(1);
                String artist = c.getString(2);
                String name = path.substring(path.lastIndexOf('/') + 1);
                model1.setName(name);
                model1.setArtist(artist);
                model1.setAlbum(album);
                model1.setPath(path);
                files.add(model1);
            }
            c.close();
        }
    } catch (Exception e) {
        throw e;
    }
    check();
    return files;
}

public void check() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 123);
            return;
        }
    } else {
        getAllaudiofromdevice();
    }
}

@Override
public void onRequestPermissionsResult(int requestcode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestcode) {
        case 123:
            if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                getAllaudiofromdevice();
            } else {
                Toast.makeText(getContext(), "you have to set permissions", Toast.LENGTH_SHORT).show();
                check();
            }
        default:
            super.onRequestPermissionsResult(requestcode, permissions, grantResults);
    }

}

}

Please help me to get out of this.
Thanks in the anticipation.

Body:
Only do work when the permission is granted. Your code contains a logical error:

if (grantResults[0] != PackageManager.PERMISSION_GRANTED) { // Mistake here.
    getAllaudiofromdevice();
} //...

Also on API 23 your code will request permissions when they're not granted, but will do nothing(*) when they already are granted. It should be like this:

public void check() {
    if (Build.VERSION.SDK_INT >= 23 && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        // Request permissions if they're not granted on API 23.
        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 123);
    } else {
        // Do work on API <23 and when permissions were granted on API 23+.
        getAllaudiofromdevice();
    }
}

(*) Depending on how you call your code, it's really confusing.


来源: stackexchange

问:
Simple encryption of an email address that will be in my querystring
The goal of this is not for security, but for obscurity so the casual user will not be able to determine what the email address is.

I don't want to display an email address in the URL like:

```<code>www.example.com/?id=johnsmith@example.com
</code>```

I would like to encrypt the email address, with the goal of:

the encrypted text should be encodable to be in a querystring

the length should be as short as possible

should not be easily decryptable e.g. using md5

I can decrypt the value back

Can someone suggest an ecryption algorith that would meet the above criteria?

答:
If your aim is not to deal with Security aspect of it then you can achieve it through Base64 encoding and decoding of String</p>

```<code> final String encodedValue =  new BASE64Encoder().encode("johnsmith@example.com".getBytes());
System.out.println("encodedValue = "+encodedValue );
final String decodedValue =  new String(new BASE64Decoder().decodeBuffer(encodedValue));
System.out.println("decodedValue = "+decodedValue);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The goal of this is not for security, but for obscurity so the casual user will not be able to determine what the email address is.

I don't want to display an email address in the URL like:

www.example.com/?id=johnsmith@example.com

I would like to encrypt the email address, with the goal of:

the encrypted text should be encodable to be in a querystring

the length should be as short as possible

should not be easily decryptable e.g. using md5

I can decrypt the value back

Can someone suggest an ecryption algorith that would meet the above criteria?

Body:
If your aim is not to deal with Security aspect of it then you can achieve it through Base64 encoding and decoding of String

 final String encodedValue =  new BASE64Encoder().encode("johnsmith@example.com".getBytes());
System.out.println("encodedValue = "+encodedValue );
final String decodedValue =  new String(new BASE64Decoder().decodeBuffer(encodedValue));
System.out.println("decodedValue = "+decodedValue);

ContentLicense: CC BY-SA 3.0


问:
Batch: How to prompt for input and continue if timed out?
I know the timeout /t 60 way to get a delay with automatic continue and the set /p var="prompt" for getting user input but is there any change to do both; ask and have a timeout to continue if nothing is entered? I would use it for a sort of get set screen for my looping script to change script settings.

答:
Take a look at choice /? to request a key and abort with a timeout.

For example:

```<code>CHOICE /T 10 /C YN /D Y
</code>```

will wait 10 seconds for Y (Yes) or N (No), otherwise the default (/D) will be taken, which is Y (Yes) in this example.

To check the result (either keypressed or default value), you have to check %ERRORLEVEL%.

```<code>@echo off
cls
CHOICE /T 5 /C YN /D Y
set _e=%ERRORLEVEL%
if %_e%==1 echo Y&goto :done
if %_e%==2 echo N&goto :done

echo Error
echo %_e%

:done
</code>```

Body:
Take a look at choice /? to request a key and abort with a timeout.

For example:

CHOICE /T 10 /C YN /D Y

will wait 10 seconds for Y (Yes) or N (No), otherwise the default (/D) will be taken, which is Y (Yes) in this example.

To check the result (either keypressed or default value), you have to check %ERRORLEVEL%.

@echo off
cls
CHOICE /T 5 /C YN /D Y
set _e=%ERRORLEVEL%
if %_e%==1 echo Y&goto :done
if %_e%==2 echo N&goto :done

echo Error
echo %_e%

:done


答:
When you talk about encryption you would have bytes, and not characters.
Bu you can encode those bytes as characters using Base64.
For example:</p>

```<code>import javax.xml.bind.DatatypeConverter;

// Encrypt if you really need to encrypt it
// I am assuming you have a method that receive a String, encrypt it and return the byte[] encrypted.
// If you don't know how to encrypt, just ask a new question about how to do it in Java.
byte[] b = encrypt( "email@example.com" );
String encoded = DatatypeConverter.printBase64Binary( b );

// Otherwise, just encode it
b = "email.example.com".getBytes(java.nio.charset.StandardCharsets.UTF_8);
encoded = DatatypeConverter.printBase64Binary( b );
</code>```

Title: Simple encryption of an email address that will be in my querystring

Body:
When you talk about encryption you would have bytes, and not characters.
Bu you can encode those bytes as characters using Base64.
For example:

import javax.xml.bind.DatatypeConverter;

// Encrypt if you really need to encrypt it
// I am assuming you have a method that receive a String, encrypt it and return the byte[] encrypted.
// If you don't know how to encrypt, just ask a new question about how to do it in Java.
byte[] b = encrypt( "email@example.com" );
String encoded = DatatypeConverter.printBase64Binary( b );

// Otherwise, just encode it
b = "email.example.com".getBytes(java.nio.charset.StandardCharsets.UTF_8);
encoded = DatatypeConverter.printBase64Binary( b );


问:
npm config not being updated inside the same npm script
Let's say I have this npm script:

```<code>"test": "npm config set email test@test.com && npm config get email"
</code>```

After running npm run test I don't see email updated.

Similarly if create bash script like so:

```<code>npm config set email test@test.com
npm config get email
</code>```

and add it to npm script, it still works the same way.

This might be a bash issue, I'm a very new to bash.
Is there a way to make it work - meaning to set the config values and use them in the script?

答:
I think the issue is a bit more complicated. Consider this:

```<code>c:\cygwin64\home\qbolec\baro>npm config set email old@email.com

c:\cygwin64\home\qbolec\baro>npm run test

> baro@1.0.0 test c:\cygwin64\home\qbolec\baro
> echo 'before'&& grep '^email' /cygdrive/c/Users/qbolec/.npmrc&& npm config set email test@test.com&& echo 'after'&& grep '^email' /cygdrive/c/Users/qbolec/.npmrc&& echo 'get'&& npm config get email

'before'
init.author.email=qbolec@gmail.com
email=old@email.com
'after'
init.author.email=qbolec@gmail.com
email=test@test.com
'get'
old@email.com

c:\cygwin64\home\qbolec\baro>npm config get email
test@test.com

c:\cygwin64\home\qbolec\baro>cat package.json
{
  "name": "baro",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo 'before'&& grep '^email' /cygdrive/c/Users/qbolec/.npmrc&& npm config set email test@test.com&& echo 'after'&& grep '^email' /cygdrive/c/Users/qbolec/.npmrc&& echo 'get'&& npm config get email"

  },
  "author": "Jakub Łopuszański <qbolec@gmail.com>",
  "license": "ISC"
}
</code>```

It looks like the .npmrc file is actually changed by the npm config set immediately, and the change is permanent, but not available for reading through npm config get. However, I don't know how to overcome this.

Body:
Let's say I have this npm script:

"test": "npm config set email test@test.com && npm config get email"

After running npm run test I don't see email updated.

Similarly if create bash script like so:

npm config set email test@test.com
npm config get email

and add it to npm script, it still works the same way.

This might be a bash issue, I'm a very new to bash.
Is there a way to make it work - meaning to set the config values and use them in the script?

Body:
I think the issue is a bit more complicated. Consider this:

c:\cygwin64\home\qbolec\baro>npm config set email old@email.com

c:\cygwin64\home\qbolec\baro>npm run test

> baro@1.0.0 test c:\cygwin64\home\qbolec\baro
> echo 'before'&& grep '^email' /cygdrive/c/Users/qbolec/.npmrc&& npm config set email test@test.com&& echo 'after'&& grep '^email' /cygdrive/c/Users/qbolec/.npmrc&& echo 'get'&& npm config get email

'before'
init.author.email=qbolec@gmail.com
email=old@email.com
'after'
init.author.email=qbolec@gmail.com
email=test@test.com
'get'
old@email.com

c:\cygwin64\home\qbolec\baro>npm config get email
test@test.com

c:\cygwin64\home\qbolec\baro>cat package.json
{
  "name": "baro",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo 'before'&& grep '^email' /cygdrive/c/Users/qbolec/.npmrc&& npm config set email test@test.com&& echo 'after'&& grep '^email' /cygdrive/c/Users/qbolec/.npmrc&& echo 'get'&& npm config get email"

  },
  "author": "Jakub Łopuszański <qbolec@gmail.com>",
  "license": "ISC"
}

It looks like the .npmrc file is actually changed by the npm config set immediately, and the change is permanent, but not available for reading through npm config get. However, I don't know how to overcome this.


问:
Simple Repeating Push Notification Android
I want to create a simple push notification for my Android app (repeating every day on 6pm)

I did some search and found: How To give notifications on android on specific time?

I followed that tutorial and here is what I got so far:

```<code>public class MyReceiver extends BroadcastReceiver
{
public MyReceiver()
{

}
@Override
public void onReceive(Context context, Intent intent)
{
    Intent intent1 = new Intent(context, HistoryToday.class);
    context.startService(intent1);
}
}

public class MyNewIntentService extends IntentService
</code>```

{
    private static final int NOTIFICATION_ID = 3;

```<code>public MyNewIntentService() {
    super("MyNewIntentService");
}

@Override
protected void onHandleIntent(Intent intent) {
    Notification.Builder builder = new Notification.Builder(this);
    builder.setContentTitle("My Titel");
    builder.setContentText("This is the Body");
    builder.setSmallIcon(R.mipmap.logo_app_icon);
    Intent notifyIntent = new Intent(this, HistoryToday.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 2, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    //to be able to launch your activity from the notification
    builder.setContentIntent(pendingIntent);
    Notification notificationCompat = builder.build();
    NotificationManagerCompat managerCompat =  NotificationManagerCompat.from(this);
    managerCompat.notify(NOTIFICATION_ID, notificationCompat);
}
</code>```

}

Manifest

```<code><receiver
android:name=".MyReceiver"
android:enabled="true"
    android:exported="false" >
</receiver>
<service
    android:name=".MyNewIntentService"
    android:exported="false" >
</service>
</code>```

Java class

```<code>    private void Intend()
{
    Context context = this.getApplicationContext();
    Intent notifyIntent = new Intent(this,MyReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast
            (context, 1, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,  System.currentTimeMillis(),
            10000, pendingIntent);
}
</code>```

Sorry for the bad formatting, I hope it is readable

No notification is shown :-(
Maybe someone can help me out. Thanks to all!

答:
Try AlarmManager, it is the best option that I can suggest to you according to your requirements. Check this code:

```<code>Calendar cur_cal = new GregorianCalendar();
cur_cal.setTimeInMillis(System.currentTimeMillis());//set the current time and date for this calendar

 Calendar cal = new GregorianCalendar();
 cal.add(Calendar.DAY_OF_YEAR, cur_cal.get(Calendar.DAY_OF_YEAR));
 cal.set(Calendar.HOUR_OF_DAY, 18);
 cal.set(Calendar.MINUTE, 00);
 cal.set(Calendar.SECOND, cur_cal.get(Calendar.SECOND));
 cal.set(Calendar.MILLISECOND, cur_cal.get(Calendar.MILLISECOND));
 cal.set(Calendar.DATE, cur_cal.get(Calendar.DATE));
 cal.set(Calendar.MONTH, cur_cal.get(Calendar.MONTH));
 Intent intent = new Intent(ProfileList.this,
 IntentBroadcastedReceiver.class);
 PendingIntent pintent = PendingIntent.getService(ProfileList.this, 0, intent, 0);
 AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
 alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);
</code>```

This code will register the event everyday for 6PM. Now you have to catch the event by adding a broadcast receiver. Here is the code:

```<code>public class MyBroadcastReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent) {

// Generate a push notification here.

}
}
</code>```

Don't forget to define the Broadcast Receiver in Manifest:

```<code><receiver android:name=".MyBroadcastReceiver" >
</code>```

Body:
I want to create a simple push notification for my Android app (repeating every day on 6pm)

I did some search and found: How To give notifications on android on specific time?

I followed that tutorial and here is what I got so far:

public class MyReceiver extends BroadcastReceiver
{
public MyReceiver()
{

}
@Override
public void onReceive(Context context, Intent intent)
{
    Intent intent1 = new Intent(context, HistoryToday.class);
    context.startService(intent1);
}
}

public class MyNewIntentService extends IntentService

{
    private static final int NOTIFICATION_ID = 3;

public MyNewIntentService() {
    super("MyNewIntentService");
}

@Override
protected void onHandleIntent(Intent intent) {
    Notification.Builder builder = new Notification.Builder(this);
    builder.setContentTitle("My Titel");
    builder.setContentText("This is the Body");
    builder.setSmallIcon(R.mipmap.logo_app_icon);
    Intent notifyIntent = new Intent(this, HistoryToday.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 2, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    //to be able to launch your activity from the notification
    builder.setContentIntent(pendingIntent);
    Notification notificationCompat = builder.build();
    NotificationManagerCompat managerCompat =  NotificationManagerCompat.from(this);
    managerCompat.notify(NOTIFICATION_ID, notificationCompat);
}

}

Manifest

<receiver
android:name=".MyReceiver"
android:enabled="true"
    android:exported="false" >
</receiver>
<service
    android:name=".MyNewIntentService"
    android:exported="false" >
</service>

Java class

    private void Intend()
{
    Context context = this.getApplicationContext();
    Intent notifyIntent = new Intent(this,MyReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast
            (context, 1, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,  System.currentTimeMillis(),
            10000, pendingIntent);
}

Sorry for the bad formatting, I hope it is readable

No notification is shown :-(
Maybe someone can help me out. Thanks to all!

Body:
Try AlarmManager, it is the best option that I can suggest to you according to your requirements. Check this code:

Calendar cur_cal = new GregorianCalendar();
cur_cal.setTimeInMillis(System.currentTimeMillis());//set the current time and date for this calendar

 Calendar cal = new GregorianCalendar();
 cal.add(Calendar.DAY_OF_YEAR, cur_cal.get(Calendar.DAY_OF_YEAR));
 cal.set(Calendar.HOUR_OF_DAY, 18);
 cal.set(Calendar.MINUTE, 00);
 cal.set(Calendar.SECOND, cur_cal.get(Calendar.SECOND));
 cal.set(Calendar.MILLISECOND, cur_cal.get(Calendar.MILLISECOND));
 cal.set(Calendar.DATE, cur_cal.get(Calendar.DATE));
 cal.set(Calendar.MONTH, cur_cal.get(Calendar.MONTH));
 Intent intent = new Intent(ProfileList.this,
 IntentBroadcastedReceiver.class);
 PendingIntent pintent = PendingIntent.getService(ProfileList.this, 0, intent, 0);
 AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
 alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);

This code will register the event everyday for 6PM. Now you have to catch the event by adding a broadcast receiver. Here is the code:

public class MyBroadcastReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent) {

// Generate a push notification here.

}
}

Don't forget to define the Broadcast Receiver in Manifest:

<receiver android:name=".MyBroadcastReceiver" >


问:
Creating/Reloading dynamic express folders in node.js
I'm trying to create files and place them into a folder, then send a link to the Microsoft Emotion API.

```<code>app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json({limit: '4mb'}));

app.use('/pics', express.static(path.join(__dirname, 'pics')))
app.post('/face', function(req, res){
    var base64Data = req.body.img.replace(/^data:image\/png;base64,/, "");
    var id;
    fs.readdir("./pics", (err, files) => {
        id = files.length;
        fs.writeFile(`./pics/${id}.png`, base64Data, 'base64', function(err) {
            console.log(err);
            reload(http, app);
            setTimeout(function(){
                fetch(`https://westus.api.cognitive.microsoft.com/emotion/v1.0/recognize`, {
                    method: "POST",
                    data: `{"url": "${"https://{ngrok-id}.ngrok.io/pics/"+id+".png"}"}`,
                    headers: {
                        'Content-Type': 'application/json',
                        'Ocp-Apim-Subscription-Key': '{api-key}'
                    }
                }).then(function(data) {
                    return data.json();
                }).then(function(data){
                    console.log(`{"url": "${"https://{ngrok-id}.ngrok.io/pics/"+id+".png"}"}`);
                    res.json(data);
                });
            }, 2000);
        });
    });
});
</code>```

Is there a way to make express folders dynamic or reload static folders?

答:
I think you're misunderstanding the term static. In short it means:

Static [assets] are things that don't change.

Key words: don't change. As of now, your logic says you will be mutating files in a folder which is supposed to be static. Don't do that.

Create or use a different path to mutate files. There is no way to "reload folders", static or not. You have to explicitly read from the folder which you are doing now via fs.readdir.

Body:
I'm trying to create files and place them into a folder, then send a link to the Microsoft Emotion API.

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json({limit: '4mb'}));

app.use('/pics', express.static(path.join(__dirname, 'pics')))
app.post('/face', function(req, res){
    var base64Data = req.body.img.replace(/^data:image\/png;base64,/, "");
    var id;
    fs.readdir("./pics", (err, files) => {
        id = files.length;
        fs.writeFile(`./pics/${id}.png`, base64Data, 'base64', function(err) {
            console.log(err);
            reload(http, app);
            setTimeout(function(){
                fetch(`https://westus.api.cognitive.microsoft.com/emotion/v1.0/recognize`, {
                    method: "POST",
                    data: `{"url": "${"https://{ngrok-id}.ngrok.io/pics/"+id+".png"}"}`,
                    headers: {
                        'Content-Type': 'application/json',
                        'Ocp-Apim-Subscription-Key': '{api-key}'
                    }
                }).then(function(data) {
                    return data.json();
                }).then(function(data){
                    console.log(`{"url": "${"https://{ngrok-id}.ngrok.io/pics/"+id+".png"}"}`);
                    res.json(data);
                });
            }, 2000);
        });
    });
});

Is there a way to make express folders dynamic or reload static folders?


问:
dotnet restore warning NU1701
I am using .NET Core with C#, and when I did dotnet restore, it gave the following error:

PS C:\workspace\Arbitrator> dotnet restore

C:\workspace\Arbitrator\Arbitrator.csproj : warning NU1701: Package 'PusherClient 0.5.0' was restored using '.NETFramework,Version=v4.6.1' instead the project target framework '.NETCoreApp,Version=v2.0'. This may cause compatibility problems.
C:\workspace\Arbitrator\Arbitrator.csproj : warning NU1701: Package 'WebSocket4Net 0.14.1' was restored using '.NETFramework,Version=v4.6.1' instead the project target framework '.NETCoreApp,Version=v2.0'. This may cause compatibility problems.

This package in problem is PusherClient. I just followed the NuGet documents to import it. How can I fix this warning?

答:
You don't necessarily have to wait until PusherClient is upgraded for .NET Core.

Referencing .NET Framework 4.6.1 (and below) from .NET Core is a new feature available since .NET Core/Standard 2.0 preview 2 / VS 2017 preview 15.3, and according to MS, it can be thought of as a feature that helps you migrate .NET Framework code to .NET Standard or .NET Core over time.

You can just suppress this warning

for a specific package

 <PackageReference Include="Contoso.Base.API" Version="1.0.3">
     <NoWarn>NU1701</NoWarn>
 </PackageReference>
```
<ul>
<li>for all packages</li>
</ul>
 <pre class="lang-xml prettyprint-override"><code> <NoWarn>NU1701</NoWarn>
</code>```

See scenarios 2 and 3 in NuGet wiki for ways to do it from GUI.

It is possible, though, that your application may fail in run-time
when you call an API (like something from WPF) that is not supported
by .NET Core. Another reason of a failure could be native APIs
possibly used by PusherClient. So you should test it extensively.
But in most cases, it will just work on all platforms where .NET Core
is supported (for example, I have tested an application with
MathNet.Numerics dependency and it worked on Linux even though
MathNet.Numerics is also .NET Framework 4.6.1).

If you don't need your app to be cross-platform, just change its target framework to .NET 4.6.1 by adding the following to your csproj file:

 <TargetFramework>net461</TargetFramework>
```

Title: dotnet restore warning NU1701

Body:
You don't necessarily have to wait until PusherClient is upgraded for .NET Core.

Referencing .NET Framework 4.6.1 (and below) from .NET Core is a new feature available since .NET Core/Standard 2.0 preview 2 / VS 2017 preview 15.3, and according to MS, it can be thought of as a feature that helps you migrate .NET Framework code to .NET Standard or .NET Core over time.

You can just suppress this warning

for a specific package

 <PackageReference Include="Contoso.Base.API" Version="1.0.3">
     <NoWarn>NU1701</NoWarn>
 </PackageReference>

for all packages

 <NoWarn>NU1701</NoWarn>

See scenarios 2 and 3 in NuGet wiki for ways to do it from GUI.

It is possible, though, that your application may fail in run-time
when you call an API (like something from WPF) that is not supported
by .NET Core. Another reason of a failure could be native APIs
possibly used by PusherClient. So you should test it extensively.
But in most cases, it will just work on all platforms where .NET Core
is supported (for example, I have tested an application with
MathNet.Numerics dependency and it worked on Linux even though
MathNet.Numerics is also .NET Framework 4.6.1).

If you don't need your app to be cross-platform, just change its target framework to .NET 4.6.1 by adding the following to your csproj file:

 <TargetFramework>net461</TargetFramework>


问:
template does not exist, when invalid data is feed in form
In part_detail_view I am passing part_stock_form() to the template so that I will show the form to add stock in the DetailView.

```<code>class part_detail_view(DetailView):
    model = part_list
    context_object_name = 'part_detail'
    template_name = 'part_detail.html'

    def get_context_data(self, **kwargs):
        context = super(part_detail_view, self).get_context_data(**kwargs)
        context['my_list'] = populate_nav_bar()
        context['form'] = part_stock_form()
        return context
</code>```

The CreateView of stock is given below

```<code>class stock_add_view(CreateView):
    model = part_stock
    fields = ['part_id','entry_date','supplier','amount','remaining']
    success_url = reverse_lazy('parts:part_list')
</code>```

and the template of 'part_detail.html' is

```<code><div>
{{ part_detail.part_id}}<br>
{{ part_detail.part_name }}<br>
{{ part_detail.cost }}<br>
{{ part_detail.available_quantity }}
</div>
<div >
<form method="post" action="{% url 'parts:stock_add_view'%}">
    {% csrf_token %}
          {{ form.errors }}
          {{ form }}
    <input type="submit">
</form>
</div>
</code>```

when adding the stock through stock_add_view() the stock is added successfully but when invalid input is entered the error is shown like this

答:
CreateView assumes that you have a template in the form of model_name_form. In your case, it is part_stock_form.html. From the docs:

The CreateView page displayed to a GET request uses a template_name_suffix of '_form'. For example, changing this attribute to '_create_form' for a view creating objects for the example Author model would cause the default template_name to be 'myapp/author_create_form.html'

So, you need to create such a template with the name part_stock_form.html. If you want to use part_detail.html, try changing template_name variable in your view (untested):

```<code>class stock_add_view(CreateView):
    model = part_stock
    fields = ['part_id','entry_date','supplier','amount','remaining']
    success_url = reverse_lazy('parts:part_list')

    template_name = 'part_detail.html'
</code>```

Hope it helps

Body:
In part_detail_view I am passing part_stock_form() to the template so that I will show the form to add stock in the DetailView.

class part_detail_view(DetailView):
    model = part_list
    context_object_name = 'part_detail'
    template_name = 'part_detail.html'

    def get_context_data(self, **kwargs):
        context = super(part_detail_view, self).get_context_data(**kwargs)
        context['my_list'] = populate_nav_bar()
        context['form'] = part_stock_form()
        return context

The CreateView of stock is given below

class stock_add_view(CreateView):
    model = part_stock
    fields = ['part_id','entry_date','supplier','amount','remaining']
    success_url = reverse_lazy('parts:part_list')

and the template of 'part_detail.html' is

{{ part_detail.part_id}}

{{ part_detail.part_name }}

{{ part_detail.cost }}

{{ part_detail.available_quantity }}

<form method="post" action="{% url 'parts:stock_add_view'%}">
    {% csrf_token %}
          {{ form.errors }}
          {{ form }}
    <input type="submit">
</form>

when adding the stock through stock_add_view() the stock is added successfully but when invalid input is entered the error is shown like this

Body:
CreateView assumes that you have a template in the form of model_name_form. In your case, it is part_stock_form.html. From the docs:

The CreateView page displayed to a GET request uses a template_name_suffix of '_form'. For example, changing this attribute to '_create_form' for a view creating objects for the example Author model would cause the default template_name to be 'myapp/author_create_form.html'

So, you need to create such a template with the name part_stock_form.html. If you want to use part_detail.html, try changing template_name variable in your view (untested):

class stock_add_view(CreateView):
    model = part_stock
    fields = ['part_id','entry_date','supplier','amount','remaining']
    success_url = reverse_lazy('parts:part_list')

    template_name = 'part_detail.html'

Hope it helps


问:
How to get related model's field's value in django
I am trying to get user's gender who is in room between start_date and end_date range here is models.py

```<code> class Profile(models.Model):
    MALE = 'M'
    FEMALE = 'F'
    GENDER_CHOICES = (
        (MALE, u'ere'),
        (FEMALE, u'eme')
    )

    FOOD_TYPE = (
        ('Veg', 'Vegeterian'),
        ('Green', 'Green')
    )
    user = models.OneToOneField(User, related_name="profile", null=True)
    firstname = models.CharField(max_length=50, null=True)
    lastname = models.CharField(max_length=50, null=True)
    phone1 = models.CharField(max_length=50, null=True)
    phone2 = models.CharField(max_length=50, null=True, blank=True)
    birthdate = models.DateField(blank=True, null=True)
    gender = models.CharField(max_length=10, choices=GENDER_CHOICES, null=True)
    emd_number = models.CharField(max_length=10, null=True)
    special_situation = models.IntegerField(choices=SITUATION_CHOICES, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    email = models.EmailField(blank=True, null=True)
    city = models.CharField(max_length=20, blank=True)
    food_type = models.CharField(max_length=50, choices=FOOD_TYPE, blank=True)

    def __unicode__(self):
        return self.user.username

class Room(models.Model):
    number = models.CharField(max_length=8, null=True)
    category = models.ForeignKey(RoomCategory, related_name="rooms")
    beds = models.PositiveIntegerField(null=True)
    description = models.TextField(blank=True)
    size = models.CharField(max_length=2, blank=True)

    def __unicode__(self):
        return self.number

class Reservation(models.Model):
    created_at = models.DateTimeField(auto_now_add=True, editable=False)
    transport_type = models.CharField(max_length=8, blank=True)
    start_date = models.DateField(null=True)
    end_date = models.DateField(null=True)
    total_days = models.PositiveIntegerField(null=True, blank=True)
    arrival_date = models.DateField(null=True, blank=True)
    user = models.ForeignKey(User, related_name="customers")
    room = models.ForeignKey(Room, related_name="reservations")
    total_payment = models.PositiveIntegerField(null=True, blank=True)
    total_paid = models.PositiveIntegerField(null=True, blank=True)
</code>```

currently i get the rooms by this query below:

```<code>queryset = Room.objects.all()
if start_date && end_date:
    queryset = queryset.exclude(reservations__start_date__range=[start_date, end_date], reservations__end_date__range=[start_date, end_date])
</code>```

how to get user's gender who is in room between dates

答:
You can check like, </p>

```<code>for reservetion in Reservation.objects.filter(room__in=queryset):
     print reservation.user.gender
</code>```

Body:
I am trying to get user's gender who is in room between start_date and end_date range here is models.py

 class Profile(models.Model):
    MALE = 'M'
    FEMALE = 'F'
    GENDER_CHOICES = (
        (MALE, u'ere'),
        (FEMALE, u'eme')
    )

    FOOD_TYPE = (
        ('Veg', 'Vegeterian'),
        ('Green', 'Green')
    )
    user = models.OneToOneField(User, related_name="profile", null=True)
    firstname = models.CharField(max_length=50, null=True)
    lastname = models.CharField(max_length=50, null=True)
    phone1 = models.CharField(max_length=50, null=True)
    phone2 = models.CharField(max_length=50, null=True, blank=True)
    birthdate = models.DateField(blank=True, null=True)
    gender = models.CharField(max_length=10, choices=GENDER_CHOICES, null=True)
    emd_number = models.CharField(max_length=10, null=True)
    special_situation = models.IntegerField(choices=SITUATION_CHOICES, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    email = models.EmailField(blank=True, null=True)
    city = models.CharField(max_length=20, blank=True)
    food_type = models.CharField(max_length=50, choices=FOOD_TYPE, blank=True)

    def __unicode__(self):
        return self.user.username

class Room(models.Model):
    number = models.CharField(max_length=8, null=True)
    category = models.ForeignKey(RoomCategory, related_name="rooms")
    beds = models.PositiveIntegerField(null=True)
    description = models.TextField(blank=True)
    size = models.CharField(max_length=2, blank=True)

    def __unicode__(self):
        return self.number

class Reservation(models.Model):
    created_at = models.DateTimeField(auto_now_add=True, editable=False)
    transport_type = models.CharField(max_length=8, blank=True)
    start_date = models.DateField(null=True)
    end_date = models.DateField(null=True)
    total_days = models.PositiveIntegerField(null=True, blank=True)
    arrival_date = models.DateField(null=True, blank=True)
    user = models.ForeignKey(User, related_name="customers")
    room = models.ForeignKey(Room, related_name="reservations")
    total_payment = models.PositiveIntegerField(null=True, blank=True)
    total_paid = models.PositiveIntegerField(null=True, blank=True)

currently i get the rooms by this query below:

queryset = Room.objects.all()
if start_date && end_date:
    queryset = queryset.exclude(reservations__start_date__range=[start_date, end_date], reservations__end_date__range=[start_date, end_date])

how to get user's gender who is in room between dates

Body:
You can check like,

for reservetion in Reservation.objects.filter(room__in=queryset):
     print reservation.user.gender


问:
Find documents by author first or last name and title
If I have this schema for art projects.

```<code>var projectSchema = new mongoose.Schema({
    authors: [String],
    title: String
});

module.exports = mongoose.model("Project", projectSchema);
</code>```

Where the authors is an array of Strings and title is a single String.

Example of one document:

```<code>{
    authors: ["Will Jackson", "Mary Price"],
    title: "Blue sky and green land"
}
</code>```

How can I find all projects that have author with first or last name "Jakson" and have word "Sky" in their title (Both queries must not be case sensitive!)

I was hoping for something along the lines of:

```<code>Projects.find( {authors : {$in : "Jackson"}}, {title : "Sky"});
</code>```

I assume that some $regex query is missing here. Please help.

答:
i think solution should be:-</p>

```<code>Projects.find(
  // Find documents matching any of these values
  {$and:[
    {"authors" : {"$in":[/jackson/]}},
    {"title" : {"$in":"/Sky/"}}
  ]}
)
</code>```

Body:
If I have this schema for art projects.

var projectSchema = new mongoose.Schema({
    authors: [String],
    title: String
});

module.exports = mongoose.model("Project", projectSchema);

Where the authors is an array of Strings and title is a single String.

Example of one document:

{
    authors: ["Will Jackson", "Mary Price"],
    title: "Blue sky and green land"
}

How can I find all projects that have author with first or last name "Jakson" and have word "Sky" in their title (Both queries must not be case sensitive!)

I was hoping for something along the lines of:

Projects.find( {authors : {$in : "Jackson"}}, {title : "Sky"});

I assume that some $regex query is missing here. Please help.

Body:
i think solution should be:-

Projects.find(
  // Find documents matching any of these values
  {$and:[
    {"authors" : {"$in":[/jackson/]}},
    {"title" : {"$in":"/Sky/"}}
  ]}
)


问:
Scrapy How to check if certain class exists in a given element
```<code><li class="a">category1</li>
<li>subcatergory1</li>
<li>subcatergory2</li>
<li class="a">category2</li>
<li>subcatergory1</li>
<li>subcatergory2</li>
</code>```

I'm looping through an ul which contains 2 kinds of li, one has a class and one doesn't. I'm wondering is there an existing method to check if the a class exists in a given li, rather than extracting class value and compare it manually.

```<code>for li in ul
    if (li has class:a)
        ....
</code>```

Any thoughts would be appreciated.

答:
You could check for an element with only one class like this in XPath:

```<code>//li[@class='a']
</code>```

But that looks for exact matches only. So you could try:

```<code>//li[contains(@class, 'a')]
</code>```

Though this will also match "noa" or "abig". So your final answer will probably be:

```<code>//li[contains(concat(' ', @class, ' '), ' a ')]
</code>```

In Scrapy, a Selector will evaluate as true if it matches some nonzero content. So you should be able to write something like:

```<code>li_tag = response.xpath("//li[contains(concat(' ', @class, ' '), ' a ')]")
if li_tag:
    print "Yes, I found an 'a' li tag on the page."
</code>```

Main answer: here

Body:
category1

subcatergory1

subcatergory2

category2

subcatergory1

subcatergory2

I'm looping through an ul which contains 2 kinds of li, one has a class and one doesn't. I'm wondering is there an existing method to check if the a class exists in a given li, rather than extracting class value and compare it manually.

for li in ul
    if (li has class:a)
        ....

Any thoughts would be appreciated.

Body:
You could check for an element with only one class like this in XPath:

//li[@class='a']

But that looks for exact matches only. So you could try:

//li[contains(@class, 'a')]

Though this will also match "noa" or "abig". So your final answer will probably be:

//li[contains(concat(' ', @class, ' '), ' a ')]

In Scrapy, a Selector will evaluate as true if it matches some nonzero content. So you should be able to write something like:

li_tag = response.xpath("//li[contains(concat(' ', @class, ' '), ' a ')]")
if li_tag:
    print "Yes, I found an 'a' li tag on the page."

Main answer: here


答:
You can try to experiment with:
https://nodemon.io

This will reload your entire application, when content in it changes.

This tool is built for development purpose, I have never tried it in production. But maybe it fits your needs.

Title: Creating/Reloading dynamic express folders in node.js


问:
"if" statement performs same action on every occurence
In trying to switch the turn variable for every run of the if statement, I keep getting the same result. Every time, turn evaluates as 2.

Here is the code:

```<code>$(function() {
  var turn = 2;

  if (turn == 1) {
    $(".box").on("click", function() {
      var $thisBox = $(this).children();
      $thisBox.addClass("x").animate({
        opacity: 1
      }, 1000);
    });
    turn = 2;
  } else if (turn == 2) {
    $(".box").on("click", function() {
      var $thisBox = $(this).children();
      $thisBox.addClass("o").animate({
        opacity: 1
      }, 1000);
    });
    turn = 1;
  } else {
    document.write("Uh Oh");
  }
});
</code>```

Why is this happening?

答:
You need to set the onClick listener only once and check the value of the turn value inside the function called by the onClick event.

$(function() {
  var turn = 2;

  $(".box").on("click", function() {
    if (turn === 1) {
      console.log('foo');
      turn = 2;
    } else if (turn === 2) {
      console.log('bar');
      turn = 1;
    } else {
     console.log("Uh Oh");
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='box'>Click me</div></code>```

Body:
In trying to switch the turn variable for every run of the if statement, I keep getting the same result. Every time, turn evaluates as 2.

Here is the code:

$(function() {
  var turn = 2;

  if (turn == 1) {
    $(".box").on("click", function() {
      var $thisBox = $(this).children();
      $thisBox.addClass("x").animate({
        opacity: 1
      }, 1000);
    });
    turn = 2;
  } else if (turn == 2) {
    $(".box").on("click", function() {
      var $thisBox = $(this).children();
      $thisBox.addClass("o").animate({
        opacity: 1
      }, 1000);
    });
    turn = 1;
  } else {
    document.write("Uh Oh");
  }
});

Why is this happening?

Body:
You need to set the onClick listener only once and check the value of the turn value inside the function called by the onClick event.

$(function() {
  var turn = 2;

  $(".box").on("click", function() {
    if (turn === 1) {
      console.log('foo');
      turn = 2;
    } else if (turn === 2) {
      console.log('bar');
      turn = 1;
    } else {
     console.log("Uh Oh");
    }
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='box'>Click me</div>


问:
Django "NameError: name 'Album' not defined"
I am trying to run see and manipulate a simple django database but the error from the Django Shell is saying one of my models isn't defined.

Most of the questions with errors similar to mine are due to people referencing a model before declaring it.  However, I'm not referencing any other model in Album.

models.py

```<code>from __future__ import unicode_literals

from django.db import models

class Album(models.Model):
    artist = models.CharField(max_length=250)
    title = models.CharField(max_length=500)
    genre = models.CharField(max_length=100)
    logo = models.CharField(max_length=1000)

class Song(models.Model):
    album = models.ForeignKey(Album, on_delete=models.CASCADE)
    file_type = models.CharField(max_length=10)
    title = models.CharField(max_length=250)
</code>```

The error I am getting:
NameError: name 'Album' is not defined

Any idea what could the the cause of this error?

For reference, I'm following thenewboston's django tutorial here.

答:
When you open your shell, it is just a python shell without anything from your app imported.

You should import your models first:

```<code>from your_app_name.models import Album
</code>```

If you don't want to import your models every time, use django-extensions which will load them for you. Use shell_plus command:

```<code>python manage.py shell_plus
</code>```

Hope it helps

Body:
I am trying to run see and manipulate a simple django database but the error from the Django Shell is saying one of my models isn't defined.

Most of the questions with errors similar to mine are due to people referencing a model before declaring it.  However, I'm not referencing any other model in Album.

models.py

from __future__ import unicode_literals

from django.db import models

class Album(models.Model):
    artist = models.CharField(max_length=250)
    title = models.CharField(max_length=500)
    genre = models.CharField(max_length=100)
    logo = models.CharField(max_length=1000)

class Song(models.Model):
    album = models.ForeignKey(Album, on_delete=models.CASCADE)
    file_type = models.CharField(max_length=10)
    title = models.CharField(max_length=250)

The error I am getting:
NameError: name 'Album' is not defined

Any idea what could the the cause of this error?

For reference, I'm following thenewboston's django tutorial here.

Body:
When you open your shell, it is just a python shell without anything from your app imported.

You should import your models first:

from your_app_name.models import Album

If you don't want to import your models every time, use django-extensions which will load them for you. Use shell_plus command:

python manage.py shell_plus

Hope it helps


问:
Three.js ray casting for particular Points
I'm working on a network visualization using Three.js and am having trouble determining why my ray casting implementation is not identifying the correct points (Full example and source).

More specifically, I'm trying to use ray casting with a Points cloud, and am attempting to change the color of a point to white once users hover on the point. Right now, hovering points does change the color of points, but the event seems to be triggered on points near the cursor rather than immediately below the cursor.

Here is the code I'm using to initialize the ray caster:

```<code>// configure the raycaster
raycaster = new THREE.Raycaster();
raycaster.params.Points.threshold = 20;
</code>```

Here is the render function:

```<code>function render() {
  renderer.render(scene, camera);
  controls.update();
  raycast();
}

// Color hovered points
function raycast() {
  raycaster.setFromCamera(mouse, camera);
  var intersects = raycaster.intersectObject(particles);
  if (intersects.length) {

    var newColor = new THREE.Color();
    newColor.setRGB( 1, 1, 1 );

    var index = intersects[0].index;
    particles.geometry.colors[index] = newColor;
    particles.geometry.colorsNeedUpdate=true;
  }
}
</code>```

And finally, the callback to the mousemove event triggered on the body:

```<code>/**
* Mouse coordinates go from 0 to container width {0:1}
* and 0 to container height {0:1}. Multiply by 2
* and subtract 1 to center the mouse coords {-1:1}.
* Furthermore, negate the y axis coords, as in the DOM
* the origin is in the top left corner, while in WebGL
* the origin is in the bottom left corner.
**/

function onDocumentMousemove(e) {
  mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
  mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
}
</code>```

Does anyone know why this code doesn't highlight the right points when users mouse around? Any insights would be very helpful!

答:
In the process of typing out the question above, I realized that the raycaster.params.Points.threshold = 20; line was setting a threshold for my Points that was much larger than the Points themselves were:

```<code>pointMaterial = new THREE.PointsMaterial({
  size: 6,
  vertexColors: THREE.VertexColors
});
</code>```

I decreased the raycaster.params.Points.threshold value to 5 and now the hovering seems to be picking up the right points.

Body:
I'm working on a network visualization using Three.js and am having trouble determining why my ray casting implementation is not identifying the correct points (Full example and source).

More specifically, I'm trying to use ray casting with a Points cloud, and am attempting to change the color of a point to white once users hover on the point. Right now, hovering points does change the color of points, but the event seems to be triggered on points near the cursor rather than immediately below the cursor.

Here is the code I'm using to initialize the ray caster:

// configure the raycaster
raycaster = new THREE.Raycaster();
raycaster.params.Points.threshold = 20;

Here is the render function:

function render() {
  renderer.render(scene, camera);
  controls.update();
  raycast();
}

// Color hovered points
function raycast() {
  raycaster.setFromCamera(mouse, camera);
  var intersects = raycaster.intersectObject(particles);
  if (intersects.length) {

    var newColor = new THREE.Color();
    newColor.setRGB( 1, 1, 1 );

    var index = intersects[0].index;
    particles.geometry.colors[index] = newColor;
    particles.geometry.colorsNeedUpdate=true;
  }
}

And finally, the callback to the mousemove event triggered on the body:

/**
* Mouse coordinates go from 0 to container width {0:1}
* and 0 to container height {0:1}. Multiply by 2
* and subtract 1 to center the mouse coords {-1:1}.
* Furthermore, negate the y axis coords, as in the DOM
* the origin is in the top left corner, while in WebGL
* the origin is in the bottom left corner.
**/

function onDocumentMousemove(e) {
  mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
  mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
}

Does anyone know why this code doesn't highlight the right points when users mouse around? Any insights would be very helpful!

Body:
In the process of typing out the question above, I realized that the raycaster.params.Points.threshold = 20; line was setting a threshold for my Points that was much larger than the Points themselves were:

pointMaterial = new THREE.PointsMaterial({
  size: 6,
  vertexColors: THREE.VertexColors
});

I decreased the raycaster.params.Points.threshold value to 5 and now the hovering seems to be picking up the right points.


问:
Parse text to match db records and and transform them into links (Rails 3)
I'm looking for a way to parse a text to turn into links the entities of my web app contained within the text. To make it clear, let's take this text as example:

Stoner rock and stoner metal are two related sub-genres of hard rock and heavy metal respectively, both combining elements of psychedelic rock, blues-rock, traditional heavy metal and doom metal. The genre emerged during the early 1990s and was pioneered foremost by the Californian bands Kyuss and Sleep.

I'd like to link all the genres, bands and albums that appear on the text (and exist as entities on my web app), like this:

Stoner rock and stoner metal are two related sub-genres of hard rock and heavy metal respectively, both combining elements of psychedelic rock, blues-rock, traditional heavy metal and doom metal. The genre emerged during the early 1990s and was pioneered foremost by the Californian bands Kyuss and Sleep.

I've thought different alternatives, such as:

Storing rails code in the database which would output the links (Ugly and insecure),

Do a full search on the database before inserting the text and

a. Find and transform all my entities into links before saving or

b. Store the entities ids on a separated column, place anchor tags and then on the view, combine each entity id with its anchor tag

I'm not really happy with any of the alternatives, I think should be a smarter way to handle this. Can you suggest a better approach? I'm using Ruby On Rails 3.

答:
Pseudo-Codes:

```<code>Keywords.find_each do |keyword|
  text.gsub!(keyword, link_to keyword, some_path_for(keyword))
end
</code>```

Depending on how many keywords you have, this task may be quite CPU intensive. Consider storing the text to DB first and have a background worker (like Resque or Delayed::Job) process each test.

Show the original (unlinked) text until it has been processed. I would suggest using two different table fields for the unlinked and linked texts.

ContentLicense: CC BY-SA 2.5

Body:
Pseudo-Codes:

Keywords.find_each do |keyword|
  text.gsub!(keyword, link_to keyword, some_path_for(keyword))
end

Depending on how many keywords you have, this task may be quite CPU intensive. Consider storing the text to DB first and have a background worker (like Resque or Delayed::Job) process each test.

Show the original (unlinked) text until it has been processed. I would suggest using two different table fields for the unlinked and linked texts.


问:
How to connect to MongoDB server using URI and server
I want to make synchronous queries to my mongoDB, and npm instructs me to use mongo-sync as follows:

```<code>var Server = require("mongo-sync").Server;
var server = new Server('127.0.0.1');
var result = server.db("test").getCollection("posts").find().toArray();
console.log(result);
server.close();
</code>```

However, my db is on a remote location, so I have a connection string (uri). Usually, I'd use such a uri with MongoClient as shown below:

```<code>var MongoClient = require('mongodb').MongoClient;
uri = mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]

MongoClient.connect(uri, function(err, db) {
    // I'd read/update my DB right here
    // But this is asynchronous...
});
</code>```

But mongo-sync doesn't have a MongoClient; it only has a server. So how do I make a connection in this case?

Debugging Update
I'm now getting this error:

```<code>Error: Error: connect ENOENT //heroku_7cr19362
    at Object.exports._errnoException (util.js:1026:11)
at exports._exceptionWithHostPort (util.js:1049:20)
at PipeConnectWrap.afterConnect [as oncomplete] (net.js:1136:14)
Followed by:
    at DB.open (/Users/Chege/NodeJS_Projects/node_modules/mongo-sync/lib/mongo-sync.js:27:13)
at Server.db (/Users/Chege/NodeJS_Projects/node_modules/mongo-sync/lib/mongo-sync.js:50:10)
at /Users/Chege/NodeJS_Projects/Constructing_the_Database/UpdateDB.js:28:22
</code>```

The code causing the error is:

```<code>var mongoURI = "mongodb://heroku_7cr19362:{PASSWORD}@ds153352.mlab.com:53352/heroku_7cr19362"

Fiber(function() {
    var server = new Server("mongodb://heroku_7cr19362:{PASSWORD}@ds153352.mlab.com:53352/");
    var result = server.db('heroku_7cr19362').getCollection("songs").find().toArray();
    console.log(result);
    console.log("Last statement");
}).run();
</code>```

So my current question is: which part of the URI goes into instantiating the server instance? Right now, I'm trying different substrings of the URI, but an explanation of what goes where and why would be awesome!

答:
Just put connection URI in place of '127.0.0.1'.</p>

```<code>var Server = require("mongo-sync").Server;
var server = new Server('mongodb://someaksdmkaasdk');
var result = server.db("test").getCollection("posts").find().toArray();
console.log(result);
server.close();
</code>```

Body:
I want to make synchronous queries to my mongoDB, and npm instructs me to use mongo-sync as follows:

var Server = require("mongo-sync").Server;
var server = new Server('127.0.0.1');
var result = server.db("test").getCollection("posts").find().toArray();
console.log(result);
server.close();

However, my db is on a remote location, so I have a connection string (uri). Usually, I'd use such a uri with MongoClient as shown below:

var MongoClient = require('mongodb').MongoClient;
uri = mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]

MongoClient.connect(uri, function(err, db) {
    // I'd read/update my DB right here
    // But this is asynchronous...
});

But mongo-sync doesn't have a MongoClient; it only has a server. So how do I make a connection in this case?

Debugging Update
I'm now getting this error:

Error: Error: connect ENOENT //heroku_7cr19362
    at Object.exports._errnoException (util.js:1026:11)
at exports._exceptionWithHostPort (util.js:1049:20)
at PipeConnectWrap.afterConnect [as oncomplete] (net.js:1136:14)
Followed by:
    at DB.open (/Users/Chege/NodeJS_Projects/node_modules/mongo-sync/lib/mongo-sync.js:27:13)
at Server.db (/Users/Chege/NodeJS_Projects/node_modules/mongo-sync/lib/mongo-sync.js:50:10)
at /Users/Chege/NodeJS_Projects/Constructing_the_Database/UpdateDB.js:28:22

The code causing the error is:

var mongoURI = "mongodb://heroku_7cr19362:{PASSWORD}@ds153352.mlab.com:53352/heroku_7cr19362"

Fiber(function() {
    var server = new Server("mongodb://heroku_7cr19362:{PASSWORD}@ds153352.mlab.com:53352/");
    var result = server.db('heroku_7cr19362').getCollection("songs").find().toArray();
    console.log(result);
    console.log("Last statement");
}).run();

So my current question is: which part of the URI goes into instantiating the server instance? Right now, I'm trying different substrings of the URI, but an explanation of what goes where and why would be awesome!

Body:
Just put connection URI in place of '127.0.0.1'.

var Server = require("mongo-sync").Server;
var server = new Server('mongodb://someaksdmkaasdk');
var result = server.db("test").getCollection("posts").find().toArray();
console.log(result);
server.close();


问:
CALayer animation beginTime
I'm developing a keyframe animation editor for iOS that allows the user to create simple animations and view them, plotted against a timeline. The user is able to drag the timeline in order to change the current time.

This means that I need to be able to start an animation at a user specified time.

Whilst I can achieve this behaviour, i also am experiencing an annoying glitch every time I re-add the animation to the layer. This glitch causes the first frame of the animation to flash very quickly before CoreAnimation respects the begin time. I can mitigate the effects of this ever so slightly by setting the layer.alpha to 0 before the flush, and 1 after the flush however this still results in a nasty single frame(ish) flash!

I have recreated a sample view controller that demonstrates the code required to "change the time" of the running animation but as this project is so simple, you don't really see the negative effects of the flush:
https://gist.github.com/chrisbirch/5cafca50804cf9d778ccd0fdc9e68d56

Basic idea behind the code is as follows:

Each time the user changes the current time, I restart the animation and fiddle with the CALayer timing properties like so (addStoppedAnimation:line 215):

```<code>ani = createGroup()

animatableLayer.speed = 0

animatableLayer.add(ani, forKey: "an animation key")
let time = CFTimeInterval(slider.value)
animatableLayer.timeOffset = 0
animatableLayer.beginTime = animatableLayer.superlayer!.convertTime(CACurrentMediaTime(), from: nil) - time

CATransaction.flush()
animatableLayer.timeOffset = time// offset
print("Time changed \(time)")
</code>```

The glitch is caused by me having to call CATransaction.flush right before I set timeOffset. Failure to call this flush results in the begin time being ignored it would seem.

I feel like I have scoured the entire internet looking for a solution to this problem but alas Im think I'm stuck.

My question is this:

Can anyone shed any light onto why it is I need to call CATransaction.flush in order for the beginTime value that I set to take effect? Looking at apple code I didn't ever see them using flush for this purpose so perhaps I have got something obvious wrong!

Many thanks in advance

Chris

答:
Using your test code from the gist I have updated it to check for an animation so that there is no need to readd it.  You could us a unique ID to track all animations and store it in a dictionary with view attributes.  I did not implement this part but that is how I would do it. Hopefully I understood your issue enough.  Also I used Xcode 9 and I am not sure of the code differences.  I changed a few logic pieces so let me know if this fixes the issue. </p>

```<code>UUID().uuidString //for unique string in implementation

//from your code just slightly altered.
//
//  ViewController.swift
//  CATest

//
//  CATestViewController.swift
//  SimpleCALayerTest

import UIKit

class CATestViewController: UIViewController, CAAnimationDelegate{

    var slider : UISlider!
    var animatableLayer : CALayer!

    var animationContainerView : UIView!

    var centerY : CGFloat!
    var startTranslationX : CGFloat!
    var endTranslationX : CGFloat!

    let duration = 10.0

    ///boring nibless view setup code
    override func loadView() {
        let marginX = CGFloat(10)
        let marginY = CGFloat(10)
        let view = UIView(frame: CGRect(x: 0, y: 0, width: 400, height: 400))

        view.backgroundColor = .lightGray

        slider = UISlider(frame: CGRect(x: marginX, y: 0, width: 200, height: 50))
        slider.maximumValue = Float(duration)
        slider.addTarget(self, action: #selector(sliderChanged(_:)), for: .valueChanged)

        slider.addTarget(self, action: #selector(sliderDragStart(_:)), for: .touchDown)
        slider.addTarget(self, action: #selector(sliderDragEnd(_:)), for: .touchUpInside)

        //A view to house an animated sublayer
        animationContainerView = UIView(frame: CGRect(x: marginX, y: 50, width: 200, height: 70))

        //add a play button that will allow the animation to be played without hindrance from the slider
        let playButton = UIButton(frame: CGRect(x: marginX, y: animationContainerView.frame.maxY + marginY, width: 200, height: 50))
        playButton.setTitle("Change Frame", for: .normal)
        playButton.addTarget(self, action: #selector(playAnimation), for: .touchUpInside)
        view.addSubview(playButton)

        //add a stopped ani button that will allow the animation to be played using slider
        let addStoppedAniButton = UIButton(frame: CGRect(x: playButton.frame.origin.x, y: playButton.frame.maxY + marginY, width: playButton.frame.width, height: playButton.frame.size.height))
        addStoppedAniButton.setTitle("Pause", for: .normal)
        addStoppedAniButton.addTarget(self, action: #selector(cmPauseTapped(_:)), for: .touchUpInside)
        view.addSubview(addStoppedAniButton)

        let animatableLayerWidth = animationContainerView.bounds.width / CGFloat(4)
        centerY = animationContainerView.bounds.midY
        startTranslationX = animatableLayerWidth / CGFloat(2)
        endTranslationX = animationContainerView.bounds.width - animatableLayerWidth / CGFloat(2)

        animationContainerView.backgroundColor = .white
        animationContainerView.layer.borderColor = UIColor.black.withAlphaComponent(0.5).cgColor
        animationContainerView.layer.borderWidth = 1

        view.addSubview(slider)
        view.addSubview(animationContainerView)

        //Now add a layer to animate to the container
        animatableLayer = CALayer()
        animatableLayer.backgroundColor = UIColor.yellow.cgColor
        animatableLayer.borderWidth = 1
        animatableLayer.borderColor = UIColor.black.withAlphaComponent(0.5).cgColor
        var r = animationContainerView.bounds.insetBy(dx: 0, dy: 4)
        r.size.width = animatableLayerWidth
        animatableLayer.frame = r
        animationContainerView.layer.addSublayer(animatableLayer)

        self.view = view
    }

    @objc func cmPauseTapped(_ sender : UIButton){
        if animatableLayer.speed == 0{
            resume()
        }else{
            pause()
        }
    }

    @objc func sliderChanged(_ sender: UISlider){
        if animatableLayer.speed == 0{
            let time = CFTimeInterval(sender.value)
            animatableLayer.speed = 0
            animatableLayer.timeOffset = time// offset
            print("Time changed \(time)")
        }
    }

    var animations = [CAAnimation]()

    func addAnimations(){
        let ani = CAAnimation()
        animations.append(ani)
    }

    @objc func sliderDragStart(_ sender: UISlider)
    {
        if animatableLayer.speed > 0{
            animatableLayer.speed = 0
        }
        addStoppedAnimation()
    }

    func pause(){
        //just updating slider
        if slider.value != Float(animatableLayer.timeOffset){
            UIView.animate(withDuration: 0.3, animations: {
                self.slider.setValue(Float(self.animatableLayer.timeOffset), animated: true)
            })
        }

        animatableLayer.timeOffset = animatableLayer.convertTime(CACurrentMediaTime(), from: nil)
        animatableLayer.speed = 0

    }

    func resume(){
        if let _ = animatableLayer.animationKeys()?.contains("an animation key"){
            animatableLayer.speed = 1.0;
            let pausedTime = animatableLayer.timeOffset
            animatableLayer.beginTime = 0.0;
            let timeSincePause = animatableLayer.convertTime(CACurrentMediaTime(), from: nil) - pausedTime
            animatableLayer.beginTime = timeSincePause;
            return
        }

        print("Drag End with need to readd animation")
        ani = createGroup()
        animatableLayer.speed = 1
        animatableLayer.add(ani, forKey: "an animation key")
        let time = CFTimeInterval(slider.value)
        animatableLayer.timeOffset = time
        animatableLayer.beginTime = CACurrentMediaTime()

    }
    @objc func sliderDragEnd(_ sender: UISlider){
        resume()
    }

    //Animations

    var ani : CAAnimationGroup!

    func createGroup() -> CAAnimationGroup
    {
        let ani = CAAnimationGroup()

        ani.isRemovedOnCompletion = false
        ani.duration = 10
        ani.delegate = self

        ani.animations = [createTranslationAnimation(),createColourAnimation()]
        return ani
    }
    func createTranslationAnimation() -> CAKeyframeAnimation
    {
        let ani = CAKeyframeAnimation(keyPath: "position")
        ani.delegate = self
        ani.isRemovedOnCompletion = false
        ani.duration = 10
        ani.values = [CGPoint(x:0,y:centerY),CGPoint(x:endTranslationX,y:centerY)]
        ani.keyTimes = [0,1]
        return ani
    }

    func createColourAnimation() -> CAKeyframeAnimation
    {
        let ani = CAKeyframeAnimation(keyPath: "backgroundColor")
        ani.delegate = self
        ani.isRemovedOnCompletion = false

        ani.duration = 10
        ani.values = [UIColor.red.cgColor,UIColor.blue.cgColor]
        ani.keyTimes = [0,1]

        return ani
    }

    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        print("Animation Stopped")
    }

    func animationDidStart(_ anim: CAAnimation) {
        print("Animation started")
    }

    func addStoppedAnimation()
    {
        if let _ = animatableLayer.animationKeys()?.contains("an animation key"){
            slider.value += 0.5
            sliderChanged(slider)
            return
            //we do not want to readd it
        }
        ani = createGroup()
        animatableLayer.speed = 0
        animatableLayer.add(ani, forKey: "an animation key")
        let time = CFTimeInterval(slider.value)
        animatableLayer.timeOffset = time
        animatableLayer.beginTime = CACurrentMediaTime()
    }

    @objc func playAnimation(){
      addStoppedAnimation()
    }

}
</code>```

Title: CALayer animation beginTime

Body:
I'm developing a keyframe animation editor for iOS that allows the user to create simple animations and view them, plotted against a timeline. The user is able to drag the timeline in order to change the current time.

This means that I need to be able to start an animation at a user specified time.

Whilst I can achieve this behaviour, i also am experiencing an annoying glitch every time I re-add the animation to the layer. This glitch causes the first frame of the animation to flash very quickly before CoreAnimation respects the begin time. I can mitigate the effects of this ever so slightly by setting the layer.alpha to 0 before the flush, and 1 after the flush however this still results in a nasty single frame(ish) flash!

I have recreated a sample view controller that demonstrates the code required to "change the time" of the running animation but as this project is so simple, you don't really see the negative effects of the flush:
https://gist.github.com/chrisbirch/5cafca50804cf9d778ccd0fdc9e68d56

Basic idea behind the code is as follows:

Each time the user changes the current time, I restart the animation and fiddle with the CALayer timing properties like so (addStoppedAnimation:line 215):

ani = createGroup()

animatableLayer.speed = 0

animatableLayer.add(ani, forKey: "an animation key")
let time = CFTimeInterval(slider.value)
animatableLayer.timeOffset = 0
animatableLayer.beginTime = animatableLayer.superlayer!.convertTime(CACurrentMediaTime(), from: nil) - time

CATransaction.flush()
animatableLayer.timeOffset = time// offset
print("Time changed \(time)")

The glitch is caused by me having to call CATransaction.flush right before I set timeOffset. Failure to call this flush results in the begin time being ignored it would seem.

I feel like I have scoured the entire internet looking for a solution to this problem but alas Im think I'm stuck.

My question is this:

Can anyone shed any light onto why it is I need to call CATransaction.flush in order for the beginTime value that I set to take effect? Looking at apple code I didn't ever see them using flush for this purpose so perhaps I have got something obvious wrong!

Many thanks in advance

Chris

Body:
Using your test code from the gist I have updated it to check for an animation so that there is no need to readd it.  You could us a unique ID to track all animations and store it in a dictionary with view attributes.  I did not implement this part but that is how I would do it. Hopefully I understood your issue enough.  Also I used Xcode 9 and I am not sure of the code differences.  I changed a few logic pieces so let me know if this fixes the issue.

UUID().uuidString //for unique string in implementation

//from your code just slightly altered.
//
//  ViewController.swift
//  CATest

//
//  CATestViewController.swift
//  SimpleCALayerTest

import UIKit

class CATestViewController: UIViewController, CAAnimationDelegate{

    var slider : UISlider!
    var animatableLayer : CALayer!

    var animationContainerView : UIView!

    var centerY : CGFloat!
    var startTranslationX : CGFloat!
    var endTranslationX : CGFloat!

    let duration = 10.0

    ///boring nibless view setup code
    override func loadView() {
        let marginX = CGFloat(10)
        let marginY = CGFloat(10)
        let view = UIView(frame: CGRect(x: 0, y: 0, width: 400, height: 400))

        view.backgroundColor = .lightGray

        slider = UISlider(frame: CGRect(x: marginX, y: 0, width: 200, height: 50))
        slider.maximumValue = Float(duration)
        slider.addTarget(self, action: #selector(sliderChanged(_:)), for: .valueChanged)

        slider.addTarget(self, action: #selector(sliderDragStart(_:)), for: .touchDown)
        slider.addTarget(self, action: #selector(sliderDragEnd(_:)), for: .touchUpInside)

        //A view to house an animated sublayer
        animationContainerView = UIView(frame: CGRect(x: marginX, y: 50, width: 200, height: 70))

        //add a play button that will allow the animation to be played without hindrance from the slider
        let playButton = UIButton(frame: CGRect(x: marginX, y: animationContainerView.frame.maxY + marginY, width: 200, height: 50))
        playButton.setTitle("Change Frame", for: .normal)
        playButton.addTarget(self, action: #selector(playAnimation), for: .touchUpInside)
        view.addSubview(playButton)

        //add a stopped ani button that will allow the animation to be played using slider
        let addStoppedAniButton = UIButton(frame: CGRect(x: playButton.frame.origin.x, y: playButton.frame.maxY + marginY, width: playButton.frame.width, height: playButton.frame.size.height))
        addStoppedAniButton.setTitle("Pause", for: .normal)
        addStoppedAniButton.addTarget(self, action: #selector(cmPauseTapped(_:)), for: .touchUpInside)
        view.addSubview(addStoppedAniButton)

        let animatableLayerWidth = animationContainerView.bounds.width / CGFloat(4)
        centerY = animationContainerView.bounds.midY
        startTranslationX = animatableLayerWidth / CGFloat(2)
        endTranslationX = animationContainerView.bounds.width - animatableLayerWidth / CGFloat(2)

        animationContainerView.backgroundColor = .white
        animationContainerView.layer.borderColor = UIColor.black.withAlphaComponent(0.5).cgColor
        animationContainerView.layer.borderWidth = 1

        view.addSubview(slider)
        view.addSubview(animationContainerView)

        //Now add a layer to animate to the container
        animatableLayer = CALayer()
        animatableLayer.backgroundColor = UIColor.yellow.cgColor
        animatableLayer.borderWidth = 1
        animatableLayer.borderColor = UIColor.black.withAlphaComponent(0.5).cgColor
        var r = animationContainerView.bounds.insetBy(dx: 0, dy: 4)
        r.size.width = animatableLayerWidth
        animatableLayer.frame = r
        animationContainerView.layer.addSublayer(animatableLayer)

        self.view = view
    }

    @objc func cmPauseTapped(_ sender : UIButton){
        if animatableLayer.speed == 0{
            resume()
        }else{
            pause()
        }
    }

    @objc func sliderChanged(_ sender: UISlider){
        if animatableLayer.speed == 0{
            let time = CFTimeInterval(sender.value)
            animatableLayer.speed = 0
            animatableLayer.timeOffset = time// offset
            print("Time changed \(time)")
        }
    }

    var animations = [CAAnimation]()

    func addAnimations(){
        let ani = CAAnimation()
        animations.append(ani)
    }

    @objc func sliderDragStart(_ sender: UISlider)
    {
        if animatableLayer.speed > 0{
            animatableLayer.speed = 0
        }
        addStoppedAnimation()
    }

    func pause(){
        //just updating slider
        if slider.value != Float(animatableLayer.timeOffset){
            UIView.animate(withDuration: 0.3, animations: {
                self.slider.setValue(Float(self.animatableLayer.timeOffset), animated: true)
            })
        }

        animatableLayer.timeOffset = animatableLayer.convertTime(CACurrentMediaTime(), from: nil)
        animatableLayer.speed = 0

    }

    func resume(){
        if let _ = animatableLayer.animationKeys()?.contains("an animation key"){
            animatableLayer.speed = 1.0;
            let pausedTime = animatableLayer.timeOffset
            animatableLayer.beginTime = 0.0;
            let timeSincePause = animatableLayer.convertTime(CACurrentMediaTime(), from: nil) - pausedTime
            animatableLayer.beginTime = timeSincePause;
            return
        }

        print("Drag End with need to readd animation")
        ani = createGroup()
        animatableLayer.speed = 1
        animatableLayer.add(ani, forKey: "an animation key")
        let time = CFTimeInterval(slider.value)
        animatableLayer.timeOffset = time
        animatableLayer.beginTime = CACurrentMediaTime()

    }
    @objc func sliderDragEnd(_ sender: UISlider){
        resume()
    }

    //Animations

    var ani : CAAnimationGroup!

    func createGroup() -> CAAnimationGroup
    {
        let ani = CAAnimationGroup()

        ani.isRemovedOnCompletion = false
        ani.duration = 10
        ani.delegate = self

        ani.animations = [createTranslationAnimation(),createColourAnimation()]
        return ani
    }
    func createTranslationAnimation() -> CAKeyframeAnimation
    {
        let ani = CAKeyframeAnimation(keyPath: "position")
        ani.delegate = self
        ani.isRemovedOnCompletion = false
        ani.duration = 10
        ani.values = [CGPoint(x:0,y:centerY),CGPoint(x:endTranslationX,y:centerY)]
        ani.keyTimes = [0,1]
        return ani
    }

    func createColourAnimation() -> CAKeyframeAnimation
    {
        let ani = CAKeyframeAnimation(keyPath: "backgroundColor")
        ani.delegate = self
        ani.isRemovedOnCompletion = false

        ani.duration = 10
        ani.values = [UIColor.red.cgColor,UIColor.blue.cgColor]
        ani.keyTimes = [0,1]

        return ani
    }

    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        print("Animation Stopped")
    }

    func animationDidStart(_ anim: CAAnimation) {
        print("Animation started")
    }

    func addStoppedAnimation()
    {
        if let _ = animatableLayer.animationKeys()?.contains("an animation key"){
            slider.value += 0.5
            sliderChanged(slider)
            return
            //we do not want to readd it
        }
        ani = createGroup()
        animatableLayer.speed = 0
        animatableLayer.add(ani, forKey: "an animation key")
        let time = CFTimeInterval(slider.value)
        animatableLayer.timeOffset = time
        animatableLayer.beginTime = CACurrentMediaTime()
    }

    @objc func playAnimation(){
      addStoppedAnimation()
    }

}


问:
Binding not updating as expected
I have a pre-loader screen that essentially says "please wait" as I have server-side computation being processed for several seconds.

I have a value converter that should update and get rid of the loader screen once the server-side computation has been processed and stored.

WPF Portion

```<code><Window.Resources>
    <Client:BoolToVisibilityConverter x:Key="loadConverter"/>
</Window.Resources>
.
.
.
    <Border Panel.ZIndex="1000" BorderBrush="Yellow" BorderThickness="1" Visibility="{Binding OverlayVisibility, Converter={StaticResource loadConverter}, Mode=TwoWay}" Background="#80000000" Margin="0,0,0,-25.6">
        <Grid>
            <TextBlock Panel.ZIndex="100" Margin="0" TextWrapping="Wrap" Text="Loading Passive Seismic Nodes..." HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="21" FontWeight="Bold" Foreground="#FFF"/>
            <TextBlock Panel.ZIndex="100" Margin="11,136,12,75.2" TextWrapping="Wrap" Text="Please Wait..." HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="14" FontWeight="Bold" Foreground="#FFF"/>
        </Grid>
    </Border
</code>```

I have an OverlayVisibility property in this class that is a boolean value to help toggle the preloader screen.

Portion of the Client Class

```<code>    public void LoadRoles()
    {
        foreach (var roleName in ChefServer.GetCookbookNames())
        {
            Cookbooks.Add(new Cookbook() { CookbookName = roleName });
        }
        //This isn't making the preloader disappear
        uiContext.Send((_ => { overlayVisibility = false; }), null);
        Console.WriteLine("Done!"); //This gets called successfully
    }

    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }

    //This function gets called when WPF form loads
    public void Loader()
    {

        uiContext = SynchronizationContext.Current; //Declared at top in namespace
        OverlayVisibility = true; //Make preloader screen show at boot
    }

    #region Props
    private bool overlayVisibility;
    public bool OverlayVisibility
    {
        get { return overlayVisibility; }
        set
        {
            overlayVisibility = value;
            OnPropertyChanged("OverlayVisibility");
        }
    }
#endregion
</code>```

答:
You're setting overlayVisibility (the field), not OverlayVisibility (the property).

Therefore, you never actually raise PropertyChanged, and WPF never finds out.

Title: Binding not updating as expected

Body:
I have a pre-loader screen that essentially says "please wait" as I have server-side computation being processed for several seconds.

I have a value converter that should update and get rid of the loader screen once the server-side computation has been processed and stored.

WPF Portion

<Window.Resources>
    <Client:BoolToVisibilityConverter x:Key="loadConverter"/>
</Window.Resources>
.
.
.
    <Border Panel.ZIndex="1000" BorderBrush="Yellow" BorderThickness="1" Visibility="{Binding OverlayVisibility, Converter={StaticResource loadConverter}, Mode=TwoWay}" Background="#80000000" Margin="0,0,0,-25.6">
        <Grid>
            <TextBlock Panel.ZIndex="100" Margin="0" TextWrapping="Wrap" Text="Loading Passive Seismic Nodes..." HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="21" FontWeight="Bold" Foreground="#FFF"/>
            <TextBlock Panel.ZIndex="100" Margin="11,136,12,75.2" TextWrapping="Wrap" Text="Please Wait..." HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="14" FontWeight="Bold" Foreground="#FFF"/>
        </Grid>
    </Border

I have an OverlayVisibility property in this class that is a boolean value to help toggle the preloader screen.

Portion of the Client Class

    public void LoadRoles()
    {
        foreach (var roleName in ChefServer.GetCookbookNames())
        {
            Cookbooks.Add(new Cookbook() { CookbookName = roleName });
        }
        //This isn't making the preloader disappear
        uiContext.Send((_ => { overlayVisibility = false; }), null);
        Console.WriteLine("Done!"); //This gets called successfully
    }

    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }

    //This function gets called when WPF form loads
    public void Loader()
    {

        uiContext = SynchronizationContext.Current; //Declared at top in namespace
        OverlayVisibility = true; //Make preloader screen show at boot
    }

    #region Props
    private bool overlayVisibility;
    public bool OverlayVisibility
    {
        get { return overlayVisibility; }
        set
        {
            overlayVisibility = value;
            OnPropertyChanged("OverlayVisibility");
        }
    }
#endregion


问:
How do I use a replace method to remove or replace commas in this scala template
I'm new to Scala templates and the Play framework. In this Scala html fragment how can I use a replace method similar to Javascript to replace  commas to other character(s) when the options html data-type attribute  values output?

```<code><select class="chosen-filter reporting-filter columnSelect">
    <option value="-1"></option>
    <% for(var i = 0; i < columns.length; i++) { %>
    <option value="<%= columns[i].id %>" data-type="<%=columns[i].type %>" <%if(columns[i].type == 'picklist') { %> data-list="<%= columns[i].options %>"<% } %>>
    <%= columns[i].displayName %>
    </option>
    <% } %>
</select>
</code>```

So instead of the values looking like

```<code><option data-type="example" data-list="Yes,No">example 1</option>
<option data-type="example" data-list="Yes,No">example 2</option>
</code>```

It would be

```<code><option data-type="example" data-list="Yes,No">example 1</option>
<option data-type="example" data-list="Yes,No">example 2</option>
</code>```

答:
It turns out I needed to add the toString() method in order to use the replace() method. </p>

```<code><%if(columns[i].type == 'picklist') { %> data-list="<%= columns[i].options.toString().replace(',',',') %>"<% } %>>
</code>```

Body:
I'm new to Scala templates and the Play framework. In this Scala html fragment how can I use a replace method similar to Javascript to replace  commas to other character(s) when the options html data-type attribute  values output?

<select class="chosen-filter reporting-filter columnSelect">
    <option value="-1"></option>
    <% for(var i = 0; i < columns.length; i++) { %>
    <option value="<%= columns[i].id %>" data-type="<%=columns[i].type %>" <%if(columns[i].type == 'picklist') { %> data-list="<%= columns[i].options %>"<% } %>>
    <%= columns[i].displayName %>
    </option>
    <% } %>
</select>

So instead of the values looking like

<option data-type="example" data-list="Yes,No">example 1</option>
<option data-type="example" data-list="Yes,No">example 2</option>

It would be

<option data-type="example" data-list="Yes,No">example 1</option>
<option data-type="example" data-list="Yes,No">example 2</option>

Body:
It turns out I needed to add the toString() method in order to use the replace() method.

<%if(columns[i].type == 'picklist') { %> data-list="<%= columns[i].options.toString().replace(',','&#44;') %>"<% } %>>


问:
Do Until Loop Skipping Row 1
I wrote a basic loop that works well, but I need it to ignore row 1 in case there are numerical headers (I previously used On Error Resume Next for String Headers, but I do not think it was the best way to handle the situation). Basically, I would like the loop to start at the second row.</p>

```<code>Sub DoTest()

Dim i As Long
i = 1

Do

Cells(i, 3).Value = Cells(i, 1) / Cells(i, 2)

i = i + 1

Loop Until IsEmpty(Cells(i, 2)) And IsEmpty(Cells(i, 1))

Range("C1").Select
End Sub
</code>```

答:
You need to change the line i=1 to i=2

You should probably use a while loop, as you are currently trying to carry out the division before checking that the first row is non-empty.   You probably also need Cells.Value

```<code>Sub DoTest()

    Dim i As Long
    i = 2

    while not IsEmpty(Cells(i, 2)) And not IsEmpty(Cells(i, 1))

        Cells(i, 3).Value = Cells(i, 1).Value / Cells(i, 2).Value

        i = i + 1

    wend

    Range("C1").Select

End Sub
</code>```

Title: Do Until Loop Skipping Row 1

Body:
I wrote a basic loop that works well, but I need it to ignore row 1 in case there are numerical headers (I previously used On Error Resume Next for String Headers, but I do not think it was the best way to handle the situation). Basically, I would like the loop to start at the second row.

Sub DoTest()

Dim i As Long
i = 1

Do

Cells(i, 3).Value = Cells(i, 1) / Cells(i, 2)

i = i + 1

Loop Until IsEmpty(Cells(i, 2)) And IsEmpty(Cells(i, 1))

Range("C1").Select
End Sub

Body:
You need to change the line i=1 to i=2

You should probably use a while loop, as you are currently trying to carry out the division before checking that the first row is non-empty.   You probably also need Cells.Value

Sub DoTest()

    Dim i As Long
    i = 2

    while not IsEmpty(Cells(i, 2)) And not IsEmpty(Cells(i, 1))

        Cells(i, 3).Value = Cells(i, 1).Value / Cells(i, 2).Value

        i = i + 1

    wend

    Range("C1").Select

End Sub


问:
Python import error: 'Cannot import name'
Im having trouble importing a class on a python module.

Here are my directory structure:

```<code>_wikiSpider
  +scrapy.cfg
  _wikiSpider
    +__init__.py
    +items.py
    +items.pyc
    +settings.py
    +settings.pyc
    +pipelines.py
    _spiders
     +__init__.py
     +__init__.pyc
     +articleSpider.py
     +articleSpider.pyc
     +items.py
</code>```

Code breaks at this line:

```<code>from wikiSpider.items import Article
</code>```

Im not sure why, since class Article is defined at items.py (deepest folder)

Can someone give me an explanation?

答:
Like others, I didn't have a circular reference problem.  I'd like to generalize the solution here just a bit more though.

Any file name conflict can cause this.  You could have multiple sub files with the same name (as above).

Or it could be the file you're working in.

Eg: trello.py as a pet project.
from trello import TrelloApi

Import reference will import itself before importing the pip installed package.  Attempts to import trello and reference objects directly will fail with "NameError: name '' is not defined"

Body:
Im having trouble importing a class on a python module.

Here are my directory structure:

_wikiSpider
  +scrapy.cfg
  _wikiSpider
    +__init__.py
    +items.py
    +items.pyc
    +settings.py
    +settings.pyc
    +pipelines.py
    _spiders
     +__init__.py
     +__init__.pyc
     +articleSpider.py
     +articleSpider.pyc
     +items.py

Code breaks at this line:

from wikiSpider.items import Article

Im not sure why, since class Article is defined at items.py (deepest folder)

Can someone give me an explanation?


问:
Include generic sass file in every file without @import with webpack 2
At the moment, I am having to add the following declaration in every sass file:

```<code>@import '../src/styles/index';
</code>```

My sass files are generally in the same folder as my components so the relative path will be different a lot of the time.

Is there anyway using webpack that I can have the import added without having to declare it on every single file?

答:
You may want to change the order of imports in .scss files.

Let me give you example. Variables are something that also need to be available in every other .scss file. The way I set my styles is to import all .scss partials in main index.scss. The first imported partial in index.scss is just a file with all variables. These variables are then accessible in all partials listed below variables import in index.scss.

Body:
At the moment, I am having to add the following declaration in every sass file:

@import '../src/styles/index';

My sass files are generally in the same folder as my components so the relative path will be different a lot of the time.

Is there anyway using webpack that I can have the import added without having to declare it on every single file?


问:
How to combine columns form two different pipe delimited filea using unix. I need to pick columns from both file and merge into one output file
I am trying to write a logic in unix scripting where I am merging columns form 2 pipe delimited file. For example, I have file a.txt with columns A|B|C and file b.txt which has columns D|E|F. I want the output file c.txt with columns A|D|B|C|E|F.

Thanks!!
Sourabh

答:
try in a single awk command too now.

```<code>awk -F"|" 'FNR==NR{A[FNR]=$1;$1="";B[FNR]=$0;next} {v=$1;$1="";print A[FNR],v B[FNR] $0}' OFS="|"  a.txt b.txt
</code>```

Will add explanation shortly too.

Body:
try in a single awk command too now.

awk -F"|" 'FNR==NR{A[FNR]=$1;$1="";B[FNR]=$0;next} {v=$1;$1="";print A[FNR],v B[FNR] $0}' OFS="|"  a.txt b.txt

Will add explanation shortly too.